Consume WCF service in Titanium - wcf

I have written a code to consume the WCF service in my Titanium Project.
Alloy.Globals.wcfservice=function callservice()
{
//fetching data from server.
var xhr = Titanium.Network.createHTTPClient();
xhr.setTimeout(1200);
console.log(xhr.status);
console.log(xhr.statusText);
xhr.onerror = function(e) /* on error in getting data from server */
{
//check response status and act aaccordingly.
if (xhr.status != 200) {
alert("The service is currently unavailable. Please Try Again Later.");
return;
}
};
//on getting response from server.
xhr.onload = function()
{
alert(this.responseText);
var response = XML.parse(this.responseText);
};
//set the url for the service to the get student courses
var request_url = getWebserviceURL() + "GetAvailableAppointmentFromWCF";
console.log(request_url);
xhr.open("POST", request_url);
xhr.send();
};
But I always receive status as 0, "the service is currently unavailable. Please Try Again Later" . What wrong am I doing in this code?

Related

Workbox BackgroundSyncPlugin _ Failed Request _ Notifications

i have a pwa who works fine. I make it with workbox.
But i want to try something.
I want to push notification when : the request ( who was hold in IndexeDB -> thanks of BackgroundSyncPlugin ) have an error ( like Error 500 ). The request send, is not the probleme of BackgroundSyncPlugin, but a probleme with my HTTP request. And i want to warn user that the request wasn't work
here a part of my service worker :
const bgSyncPlugin = new BackgroundSyncPlugin('myQueueName', {
maxRetentionTime: 0.1 * 60, // mins,
onSync: async({ queue }) => {
let entry;
while ((entry = await queue.shiftRequest())) {
try {
await fetch(entry.request);
console.error("Replay successful for request", entry.request);
} catch (error) {
console.error("Replay failed for request", entry.request, error);
// Put the entry back in the queue and re-throw the error:
await queue.unshiftRequest(entry);
throw error;
}
}
console.log("Replay complete!");
showNotification();
}
});
registerRoute(
/http:\/\/localhost:8000/,
new NetworkFirst({
plugins: [bgSyncPlugin]
}),
'POST'
);
I just want to know the status code of my request
Any help :)
Edit : i want to get Body in header2
You should be able to change this line:
await fetch(entry.request);
to
const response = await fetch(entry.request);
// Check response.status, and do something, e.g. throw an
// Error when it's above 500:
if (response.status > 500) {
// Throwing an Error will trigger a retry.
throw new Error('Status: ' + response.status);
}
// This assumes that your response from the server is JSON,
// and has an error field which might be set if the request
// failed for some reason, regardless of the HTTP status code.
const responseJSON = await response.json();
if (responseJSON.error) {
throw new Error('Failed request: ' + responseJSON.error);
}

Xhttp request always returns a 0 response code. - While making a post request using form data

I am trying to upload an array of images using form data and xhttp.
Client : React Native - Both platforms
Server : Node running on GCP
Images go into s3.
Problem : Images are uploaded into s3. And when i look at my server logs i see the server is sending 200.
But, client is always receiving response code 0.
And also xhttp goes from state 1 -> 4.
We have added CORS on both ends so that might not be an issue.
I have accept and content headers. But, no idea what's going wrong.
Any help is appreciated.
React-Native Client:
upload()
{
let url = "MYAPIGOESHERE"
let uploadBody = new FormData()
let imagesUpload = []
imagesUpload.push({type:'image/jpg',uri:this.state.coverImage[0].uri,name:"cover"})
uploadBody.append('photos',{uri:this.state.coverImage[0].uri, type:'image/jpg', name:"cover"})
uploadBody.append('duration',this.state.duration)
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
console.log(this.readyState+" "+this.statusText)
if (this.readyState === 4) {
alert(this.status)
if (this.status === 200) {
console.log(this.responseText);
} else {
console.log(this);
}
}
if(this.readyState === 3)
{
console.log("Inside 3")
}
if(this.readyState === 2)
{
console.log("Inside 2")
}
};
xhttp.open("POST", url)
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Access-Control-Allow-Origin', '*');
xhttp.responseType = 'json'
xhttp.send(uploadBody)
}

SignalR 404 when connecting using .Net Client

What is the URL do we need to put, when connecting to SignalR core.
When we try to put Url as https://localhost:44308, it says not found. Yes web server is running. Any suffix is required?
HubConnection connection;
connection = new HubConnectionBuilder()
.WithUrl(**Url**)
.Build();
await connection.StartAsync();
bool isClosed = false;
connection.Closed += async (error) =>
{
isClosed = true;
await Task.Delay(new Random().Next(0, 5) * 1000);
await connection.StartAsync();
};
if (isClosed == false)
{
connection.InvokeAsync("NewMessage", "from server", $"{DateTime.Now.ToShortDateString()}").Wait();
}
Changes in Signal Core:
https://localhost:44308 should contain, Hub suffix, so correct URL is:
https://localhost:44308/hub
this is configurable in Startup.cs

adal.js inifnite loop when refreshing token

I am using the latest adal.js to query data from MicroSoft Dynamics CRM. The code gets into an infinite loop when renewing the token.
Additionally after loging into microsoft and being redirected back to my page the adaljs tries to refresh the token.
Note - this is javascript in an ASP.NET MVC web app. It is not using angular js.
This is also similar to the SO question Adal & Adal-Angular - refresh token infinite loop
var endpoints = {
orgUri: "https://<tenant>.crm6.dynamics.com/"
};
var config = {
clientId: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
tenant: '<tenant>.onmicrosoft.com',
redirectUri: 'http://localhost:53290/home/AuthenticatedByCrm/',
endpoints: endpoints,
cacheLocation: 'localStorage'
};
var x = new AuthenticationContext(config);
var isCallback = x.isCallback(window.location.hash);
if (isCallback) {
x.handleWindowCallback();
x.acquireToken(endpoints.orgUri, retrieveAccounts);
} else {
x.login();
}
function retrieveAccounts(error, token) {
// Handle ADAL Errors.
if (error || !token) {
alert('ADAL error occurred: ' + error);
return;
}
var req = new XMLHttpRequest();
req.open("GET", encodeURI(organizationURI + "/api/data/v8.0/accounts?$select=name,address1_city&$top=10"), true);
//Set Bearer token
req.setRequestHeader("Authorization", "Bearer " + token);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if (this.readyState == 4 /* complete */) {
req.onreadystatechange = null;
if (this.status == 200) {
var accounts = JSON.parse(this.response).value;
//renderAccounts(accounts);
}
else {
var error = JSON.parse(this.response).error;
console.log(error.message);
//errorMessage.textContent = error.message;
}
}
};
req.send();
}
The Active Directory Authentication Library (ADAL) for JavaScript helps you to use Azure AD for handling authentication in your single page applications. This library is optimized for working together with AngularJS.
Based on the investigation, this issue is caused by the handleWindowCallback. The response not able to run into the branch for if ((requestInfo.requestType === this.REQUEST_TYPE.RENEW_TOKEN) && window.parent && (window.parent !== window)) since it is not used in the Angular enviroment.
To integrate Azure AD with MVC application, I suggest that you using the Active Directory Authentication Library. And you can refer the code sample here.
Update
if (isCallback) {
// x.handleWindowCallback();
var requestInfo=x.getRequestInfo(window.location.hash);
//get the token provided resource. to get the id_token, we need to pass the client id
var token = x.getCachedToken("{clientId}")
x.saveTokenFromHash(requestInfo);
} else {
x.login();
}

angularjs post file to web api

I've a angular function for to upload file to web api
$scope.uploadFile = function () {
var file = $scope.file;
console.log("file: " + file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", uri);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
$scope.progressVisible = true;
xhr.send(file);
}
function uploadProgress(evt) {
$scope.$apply(function () {
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total);
}
})
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
$scope.$apply(function () {
$scope.progressVisible = false;
})
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
The code is available here http://jsfiddle.net/vishalvasani/4hqVu/
I need a web api controller to manage file post, how can I read it?
Is it possible to use PostValue instead of task async?
Server side I get the file, read content, query a database and return JSON response
Thanks