Using OData with breeze - query not executed - breeze

i am trying to query webapi asp.net odata controller using breeze
in my query
function getIncidentsInternal() {
var query = breeze.EntityQuery
.from("Customers");
//var serverAddress = "http://localhost:53809/odata/";
var serverAddress = "/odata";
var manager = new breeze.EntityManager(serverAddress);
return manager.executeQuery(query)
.then(getSucceededInternal); // caller to handle failure
after the metadata request there is no actual request to get the items
i see one error of
OPTIONS http://localhost:53809/odata/$metadata 405 (Method Not Allowed)
after this request there is a GEt request with the metadata which pass but no query

If you got a 405, I bet you have issues with CORS. Does you OData service support CORS? Also, looks like you need to change breeze to use OData instead of web api. you can do that like so..
breeze.config.initializeAdapterInstances({ dataService: "OData" });

Related

Not able to call Odata Service in UI5

I am calling Odata service for my UI5 application. I am using below mentioned code for creating the model.
var oModel = new sap.ui.model.json.JSONModel("https://<>/sap/opu/odata/SIE/MED_TEST_OSIRIS_SRV/SalesOrderSet?$format=json");
//Getting the Data and putting in list model
sap.ui.getCore().setModel(oModel,"table");
With this code , I can call the Odata and display the results in a table.
But now when I am applying filter like this :
https://<>/sap/opu/odata/SIE/MED_TEST_OSIRIS_SRV/SalesOrderSet?$filter=Country_SP
eq 'DE'
I can get the results in browser's address bar but not in the code like :
var sUrl = "https://<>/sap/opu/odata/SIE/MED_TEST_OSIRIS_SRV/SalesOrderSet?$filter=Country_SP eq 'DE'";
var oModel = new sap.ui.model.json.JSONModel(sUrl);
what I am doing wrong ? I can filter the results in the browser with the same url :(
Regards,
Mayank
Try with synchronous call.
var oModelData = new sap.ui.model.json.JSONModel();
oModelData.loadData(sUrl, null, false);
The UI5 ODataModel only supports the base address of the OData service. The model will construct filtered and sorted queries based on that base address. It will do that for example when you supply Filters or Sorters to an aggregation binding.
You can however use a JSONModel in your case. It's agnostic to the OData query parameters and will simply call the given URL and store the results.
You need to encode URI component the filters, and then append to the base URL
var filter = "Country_SP eq 'DE'";
var baseUrl = "https://<>/sap/opu/odata/SIE/MED_TEST_OSIRIS_SRV/SalesOrderSet";
var sUrl = baseUrl+encodeURIComponent(filter);
var oModel = new sap.ui.model.json.JSONModel(sUrl);

Returning result for .net Web Api from db call

I'm new to the .net Web API and am trying to figure out how I return a Get result from a call to my database. I know everything works in my regular MVC page. But Not sure how to return the result from the Web API controller. I thought it was as simple as returning Json with the result. Here is my code:
// GET api/<controller>
public IEnumerable<string> Get()
{
using (var _db = new JobsDatabaseEntities())
{
var user = Env.CurrentUser;
var posts =
_db.JobPostings.Where(
j =>
j.City.Equals(user.City, StringComparison.OrdinalIgnoreCase) &&
j.Industry.ID == user.Industry.ID);
var result = new List<BusJobPost>();
foreach (var post in posts)
{
var p = new BusJobPost(post);
result.Add(p);
}
return Json(result);
}
}
Please visit this resource: Action Results in Web API 2. Your case is described in fourth section Some other type (which is applicable to first version of Web API as well).
In Web API you don't return JSON result explicitly. It is actually done by process called Content Negotiation. You can read about it here [Content Negotiation in ASP.NET Web API] in detail.
Highlighting briefly just some of this:
You can set Accept header for you request as: Accept: application/json (for example, if you use jquery ajax function: dataType: 'json')
Or even if you don't use Accept header at all, if you send request with JSON data, you should also get response back in JSON format
So you should just return result variable from your controller action and satisfy some of conditions to get response serialized into JSON.

Custom DataService adapter saveChanges method to set entities to Unchanged

I've implemented a custom DataService adapter for BreezeJS - I wanted to use Breeze with a RESTful back end service (not OData or ASP.NET Web API).
So far - decent results after a learning curve.
I'm having an issue that when I call save changes - afterwards my entities on the client do not get marked as 'Unchanged'. They keep the same entityState.
I assume it has something to do with the success handler of the AJAX request to the backend service (looking at the source code to the WebAPI adapter):
success: function(data, textStatus, XHR) {
if (data.Error) {
// anticipatable errors on server - concurrency...
var err = createError(XHR);
err.message = data.Error;
deferred.reject(err);
} else {
// HACK: need to change the 'case' of properties in the saveResult
// but KeyMapping properties internally are still ucase. ugh...
var keyMappings = data.KeyMappings.map(function(km) {
var entityTypeName = MetadataStore.normalizeTypeName(km.EntityTypeName);
return { entityTypeName: entityTypeName, tempValue: km.TempValue, realValue: km.RealValue };
});
var saveResult = { entities: data.Entities, keyMappings: keyMappings, XHR: data.XHR };
deferred.resolve(saveResult);
}
},
It looks like the response includes an array of 'Entities'. What do these 'Entities' look like? It echoes what the client sent with an updated entityAspect.entityState value (server responses with 'Unchanged')?
Is that what should be passed into the deferred.resolve call?
I've got a working solution for this.
In a nutshell here's what is required for the object that is passed to the
deferred.resolve(saveResult);
Call in the success handler of the save change AJAX request.
Server response should include information about how to map from the client generated id to the server generated id (if the server generated one). This can be one keyMapping property returned in the response (like the Breeze API controller does) or what my service does is return a keyMapping property as a child property of a particular resource
The client code should create an array of objects that look like:
{ entityTypeName: "fully qualified entity type name",
tempValue: "client generated id",
realValue: "server generated id"
}
this array is the keyMappings property of the saveResult object
the entities property of the saveResult object is a flat list of all the entities that were modified from the server. Because of the design of my service API, it can return an entity, and child entities embedded in it, which I had to traverse and pull out into a flat list. Additionally these entity objects should be 'raw' and not include the entityAspect property or anything Breeze might interpret as a 'real' entity.
Also - something that can also be helpful is to look at the new sample from the Breeze folks - the MongoDB Breeze sample. They've implemented a custom dataServiceAdapter that hooks up their NodeJS/MongoDB backend. That provided some additional insight as well.
Good luck!

Retrieving entries by key without using filter in Breezejs

When we query for an entity in Breezejs with its key, the framework is creating an url using the $filter property.
/api/orderCollection?$filter=orderId%20eq%20'0001'
Is it possible to force breeze to use the odata format?
/api/orderCollection(0001)
I have a standard odata service and it doesn't support the first url...
this is my query:
var query = new breeze.EntityQuery().from("OrderCollection");
var pred = breeze.Predicate.create('orderId', '==', orderId);
query = query.where(pred);
kr,
Joachim
Breeze always generates OData queries using the $filter operator because that gives us the most flexibility and consistency as you add Predicate expressions. This is part of the OData spec.
However, if you really need the alternative expression you can actually pass the entire URL as a string to Breeze to execute as a query, i.e.
var query = "orderCollection(0001)";
myEntityManager.executeQuery(query).then(function (data) {
...
});
Breeze should still return the same results that this will
var query = new breeze.EntityQuery().from("OrderCollection")
.where('orderId', '==', orderId);
myEntityManager.executeQuery(query).then(function (data) {
...
});

Using JSON data in ASP.NET MVC

I have not done this before, so need some leads. I have a ASP.NET MVC4 (beta) project - Mobile project - setup. And I am given a set of REST APIs to consume. How would I do this? The APIs return data in JSON format. Do you have any examples, best practices...?
You could use the $.ajax method to send an AJAX request to the Web Api controller on the server:
$.ajax({
url: 'api/values/123',
type: 'GET',
success: function(data) {
// if the controller returned JSON data, the data argument
// will represent a javascript object that you could directly
// access its properties
}
});
Use DownloadString method of WebClient class. That will give you a string output of what the RESTURL is returning. You can convert that to Json and iterate the results
string address="http://yourrestdomain/customer/234";
WebClient client = new WebClient ();
string reply = client.DownloadString (address);

Resources