PhoneGap with WCF Rest Service - wcf

So I have started with PhoneGap/Cordova (windows phone) and WCF Rest Services, however, I am having problems on getting the Emulator to interact with the WCF Service.
At first I was thinking that maybe the Emulator could not connect to the localhost WCF Service, so I published the WCF Service on an external host however the problem still occured... i.e. still not able to make a call to the WCF Service.
The code I have is shown below:
The javascript file for the PhoneGap application is the following:
function getAjax() {
var jqxhr = $.ajax({
url: 'http://link.to.service.com/service1/',
//headers:
beforeSend: function (xhr) {
//xhr.overrideMimeType('text/plain; charset=x-user-defined');
},
dataType: 'json'
})
.done(function (data) {
var element = document.getElementById('ajaxCall');
element.innerHTML = JSON.stringify(data, null, "\t");
})
.fail(function (xhr, status, error) {
showError(error);
})
.always(function () { showAlert("complete"); });
}
Then the WCF Service contains the following method:
[WebGet(UriTemplate = "")]
public List<SampleItem> GetCollection()
{
return new List<SampleItem>()
{
new SampleItem()
{
Id = 1,
StringValue = "Hello" }
};
}
Therefore, when the a call to the javascript method "getAjax" is done, the WCF Service method should be called however it keeps entering the fail function instead showing an error message 'undefined'.
Is there something that I am missing out here?

After further investigation, this has been resolved using the line:
jQuery.support.cors = true;
Just a small quote from the jQuery library for those having the same issue, this is what the above line does:
cors is equal to true if a browser can create an XMLHttpRequest object and if that XMLHttpRequest object has a withCredentials property. To enable cross-domain requests in environments that do not support cors yet but do allow cross-domain XHR requests (windows gadget, etc), set $.support.cors = true;. CORS WD

Related

How we can authenticate signalR by using cross domain call?

I am working asp.net apis project where i am using signalR and i want to authenticate with authorize attribute.For this i send jwt token and this token add
into signalR pipeline.First i call to Apis to get token.Then i send this token to get signalR connection,But signalR returns unauthorized response.
The below is my code,
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
// SignalR Auth0 custom configuration.
map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Provider = new OAuthBearerAuthenticationProvider()
{
OnRequestToken = context =>
{
if (context.Request.Path.Value.StartsWith("/signalr"))
{
string bearerToken = context.Request.Query.Get("access_token");
if (bearerToken != null)
{
string[] authorization = new string[] { "bearer " + bearerToken };
context.Request.Headers.Add("Authorization", authorization);
}
}
return null;
}
}
});
var hubConfiguration = new HubConfiguration
{
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
// EnableJSONP = true
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
app.UseWebApi(config);
GlobalHost.DependencyResolver.Register(
typeof(SignalRHUB),
() => new SignalRHUB(new UnitOfWork(new DbFactory())));
//GlobalHost.HubPipeline.RequireAuthentication();
//app.MapSignalR();

ionic 2: http get request not working (proxy added)

I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

posting object from angular 2 application to Web Api application (getting Unsupported Media Type)

I could use some guidens, sending an object from my angular 2 application to the Web API.
I know how to GET objects from the Web Api, to my angular 2 application, but can't seem to figure out how the post method works or even if I should use the http.post methodd.
My angular 2 application has the following method:
sendUpdatdReservation(updatedReservation: Reservation) {
var result;
var objectToSend = JSON.stringify(updatedReservation);
this.http.post('http://localhost:52262/api/postbookings', objectToSend)
.map((res: Response) => res.json()).subscribe(res => result = res);
console.log(result);
}
The "updatedReservation" is an object, which I convert to JSON.
The Web api can be reached by the following address:
httl://localhost:52262/api/postbookings
Web Api controller:
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PostBookingsController : ApiController
{
[AcceptVerbs()]
public bool ConfirmBooking(Booking booking)
{
return true;
}
}
What I'm trying to do is to send the object, update my database based on the changes values that the object has. Then send back true or false if this is a confirmation or not so I can redirect to confirmation page.
Do any know the unsupported media type error?, is that related to that the object i send is not what the api method expects?
Hope someone can help.
You need to set the Content-Type header when sending the request:
sendUpdatdReservation(updatedReservation: Reservation) {
var result;
var objectToSend = JSON.stringify(updatedReservation);
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://localhost:52262/api/postbookings', objectToSend, { headers: headers })
.map((res: Response) => res.json()).subscribe(res => {
this.result = res;
console.log(this.result);
});
}
Don't forget to import this class:
import {Http,Headers} from 'angular2/http';

How to invoke rest service using dojo xhr?

try{
var targetURL ="http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer/1/query?where=STATE_NAME%3D%27Florida%27&f=json";
var xhrArgs = {
url: targetURL,
handleAs: "json",
load: function(data) {
alert(data);
},
error: function(error) {
alert("An unexpected error occurred: " + error);
}
};
var deferred = dojo.xhrGet(xhrArgs);
}catch(e){
alert(e);
}
Is this the right way of calling rest service?
I am getting null response from the above code.
dojo/xhr cannot be used for cross domain requests.
Is http://sampleserver1.arcgisonline.com/ the same domain that loads the web page or a different server?
If it is the same server, drop the domain name (ie ArcGIS/rest/services/...);
If not, you can use jsonp
https://dojotoolkit.org/reference-guide/1.9/dojo/request/script.html#dojo-request-script
Another alternative is to call a service located on the web server that acts as a proxy and makes the call to the other server.

Intercept HTTP Request that needs authorization Header with AngularJS ngResource

Hello I'm doing a REST API client with AngularJS using ngResource plugin and my implementation of HMAC authentication.
I wrote an HttpIntercept Service that intercepts the http requests and calculate and attach the Authorization Header with HMAC sign. But with this implementation it calculates and attaches the sign to all requests, that's bad.
.factory('authInterceptor', function($q) {
return {
request: function(request) {
#sign calculation...
request.headers['Authorization'] = sign;
}
return request || $q.when(request);
}
};
})
.controller('HomeCtrl', function ($scope,$resource) {
var Articles = $resource('/api/articles');
$scope.articles = Articles.query();
})
Do you have a suggestion to intercept only requests that needs authentication or all requests that came from ngResource plugin?
I thought to three workrounds:
1. an array list of the private requests
2. different subdomain for public and private APIs
3. attach supply http Header to the requests that need authentication
See $http and overriding transformations and also $resource
Each $resource action takes an $http.config like object which has transformRequest:
var Articles = $resource(
'/api/articles',
{
},
{
'query': {
method: 'GET',
isArray: true,
transformRequest: function (config) {
config.headers['Authentication']: 'sign';
return config;
}
}
});