Getting data with Breeze that is "Ignore"d in the database - javascript

I am building a SPA and are using BreezeJS for data management. Now I want to be able to set processed data on my model class that are not present in the database and send it up the client. The problem is that breeze also ignores these properties.
public class MyModel{
public int Id{get; set;}
public string Name{get; set;}
public string ProcessedData{get; set;}
}
...
Ignore(model=> model.ProcessedData);
I realize that Breeze uses the same metadata as my datacontext, but there should be a way to override it.
The ignored properties is sent by the controller as json, it's just a matter of making breeze parse it as I need it to.

I haven't confirmed this but I think that if your are sure that the data is being returned from the server then you can add "unmapped" properties with the correct names to the Breeze client and it will materialize these as well. See the "unmapped" discussion here: http://www.breezejs.com/documentation/extending-entities .
Or you could try this ( I haven't actually tested this) AFTER the metadata has already been returned.
var dp = new breeze.DataProperty( {
nameOnServer: "ProcessedData",
dataType: "String",
isUnmapped: true
});
myEntityManager.metadataStore.getEntityType("MyModel").addProperty(dp);
and then try your query.
Note: only "unmapped" properties can be added to the EntityType after the EntityType has been itself added to a MetadataStore.

Related

JAX-RS JSON object to JavaScript

I am new to JAX-RS and trying to build a simple website interface.
So I have written a function returning a JSON object
like this:
#GET
#Path("/mypath")
#Produces (Mediatype.APPLICATION_JSON)
public String returnJson() {
String json = //.... fill String
return json;
}
which works well when browsing to this path.
On the other hand I have a UI page like this:
#GET
Produces(MediaType.TEXT_HTML)
public InputStream viewUI() throws FileNotFoundException {
File page = new File("page.html");
return new FileInputStream(page);
}
which works also.
Next thing I want to do is filling a dropdown list in my page.html with JavaScript, which also should not be a problem.
But I dont know how to get the JSON object to the JavaScript array (in page.html).
First of all, when using jaxrs, you don't need to convert objects to json. This is done automatically by jaxrs. Your method should return an object. As you asking to convert json into array, I assume, your method should return a List. Regarding of how to call and consume results from the rest service, as per Luts Horn comment, you need to use some sort of client side library, for example jquery.
You can look here http://www.tutorialspoint.com/jquery/jquery-ajax.htm

Maintaining WebAPI endpoints in JavaScript

I was wondering if there were any good techniques in keeping your WebAPI controller routes in sync with the client side.
For instance, you have a WebAPI controller BooksController. On the client you could invoke a method by calling the endpoint:
$.get('books/1');
Then one day you decide to rename the controller, or add a RoutePrefix. This breaks the client side code, as the endpoint has changed.
I came across the library WebApiProxy, which looks interesting. Does anyone have a good approach to solving this problem? Is there a reason to use string literals on the client that I may be overlooking?
I created a blog bost on te subject. Take a look :)
http://blog.walden.dk/post/2017/02/02/export-all-your-asp-net-webapi-endpoints-to-json
Im working on a post consuming it in javascript.. Anyway, this code exports the endpoints runtime, and will work on refactorings and route changes. It exports uri parameters as well, they can be used to be parsed in javascript and replaced with values from the client.
The simplest way to achieve waht you want, is to use the built-in ApiExplorer in ASP.NET WEBAPI. It searches for all "ApiController" implementations, and reads the route-attribute metadata.
public class EndpointManager
{
public IEnumerable<ApiMethodModel> Export()
{
//Use the build-in apiexplorer to find webapi endpoints
IApiExplorer apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
//exclude endpoints without the attribute
var apiMethods = apiExplorer.ApiDescriptions.Select(ad => new ApiMethodModel(ad)).ToList();
return apiMethods;
}
}
You can create an endpoint that returns that generated data.
[RoutePrefix("api/endpoint")]
public class EndpointApiController : ApiController {
[HttpGet]
[Route("all")]
public IEnumerable<ApiMethodModel> All()
{
var endpoints = new EndpointManager().Export();
return endpoints;
}
}
Now all the endpoints can be reached at "/api/endpoint/all"
Here is an sample I was talking about in my comment to your question:
function getUrl(uri) {
var bookRoute = /books(.*?)/i;
var otherRoute = /something(.*?)/i;
if(uri.match(bookRoute)) {
return uri.replace(bookRoute, "http://localhost/webapi/books$1")
}
if(uri.match(otherRoute)) {
return uri.replace(otherRoute, "http://mydomain/api/something$1")
}
return uri;
}
alert(getUrl("books/1"));
alert(getUrl("something/realy/different/1"));
All you need is to define the routes in the body of your function.

Debug ServiceStack POST Request Deserialization

I have a use case where I am posting a complex object with an array member using jQuery. E.g.:
data: {
obj1: obj1,
arr1: [ ... ]
}
On the server I have implemented a ServiceStack service. The automatic request mapping on the server produces nulls for the request members, but if I extract the Request.GetRawBody(), and then use ServiceStack.Text.JsonSerializer.DeserializeFromString, I get what I need.
It would be useful to debug the actual deserialization and see what is missing. Anyone know how to do this?
Examples:
Pass in a flat object
Define a simple request object with a few fields:
public class Request
{
public string Name { get; set; }
}
Make a jQuery ajax call:
$.ajax({
//...
data: {
name: 'John Doe'
}
});
The call works, the server receives the object with "John Doe" name property.
Pass object with child-object
public class Request
{
public Caller Caller { get; set; }
}
public class Caller
{
public string Name { get; set; }
}
Then make a call from jQuery:
$.ajax({
// ...
data: {
caller: {
name: 'John Doe'
}
}
});
After the call, the "caller" property of the request on the service is "null", so this approach is not working.
Conclusion
In my original assessment I was referring to an object and array combination. I guess the problem is in getting a simple sub-object to serialize/deserialize. Does this means the concept is not supported, or am I passing the object in incorrectly?
If you really think its something wrong with the actual deserialization then I would recommend downloading the source code from github and trying to create failing unit tests. If you think its with the json deserialization then download the ServiceStack.Text project. Otherwise you should download the main ServiceStack project. Reading the existing unit tests are quite informative to how the entire project works.
However, chances are it is invalid json notation. It is often useful to reverse engineer the json by comparing the results from Serializing your DTO to what you are actually passing into the ajax call.
Updated: Your json should look like this:
{"Caller":{"Name":"John Doe"}}
The easy way to check this is to do the following:
var r = new MyRequest() {Caller = new Caller() {Name = "John Doe"}};
var json = r.ToJson();
I have figured out the issue, hope the answer helps others. It turns out that $.ajax is sending the content type as form url encoded (which is clearly documented in the jQuery documentation, I had just missed it):
http://api.jquery.com/jQuery.ajax/
Setting the contentType to 'application/json' resolved the issue, now all data is properly deserialized on the server.

Parsing json into java objects with other object attribue in spring-mvc

I have an object of type element and this has an attribute of type theme. when I create a new element is represented by a theme select in the view, and the primary key is the value of the items in the select, when I send with json, spring try to create an object element and the next error is show
/element: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.example.Theme, problem: no suitable creator method found
at [Source: org.mortbay.jetty.HttpParser$Input#dd0099; line: 1, column: 31]
this is my code in spring MVC
public class Element {
private String name;
private String type;
private Theme theme;
private String description;
// Get - Set
}
Theme Class
public class Theme {
private String name;
private String description;
// Get - Set
}
Method in the controller
#RequestMapping(method=RequestMethod.POST)
public #ResponseBody String create(#RequestBody Element element){
elementManager.saveElement(element);
return "exito";
}
and the javascript is this
$("#element").submit(function() {
var element = $(this).serializeObject();
$.postJSON("element", element, function(data) {
});
return false;
});
i hope someone can help me.
Based on your comment containing the JSON you send the server, I would say the issue is the JSON itself.
Your server is expecting a value along the lines of this:
{"name":"rooms","type":"Doc","theme":{"name":"themeName", "description":"themeDescription"},"descrip‌​tion":"They are realy big"}
You should fetch the object theme from where it is stored, and create the proper JSON. If the Theme is looked up at the client, you will need to change the Element to have a String theme attribute, and do the lookup on the client.

Passing Objects from Views/Javascript to MVC Action

I am using MVC.
I have a view model which contains a Business object.
I need to post this Business Object back to a controller action using AJAX.
For now, I am using Url.Action function to create my request Url for AJAX and pass the Business Object id as a request parameter to the action. I then have to retrieve the object from the database to use it.
Is there a way (using Json) to pass this object as an Object? The object is shown below
public class BusinessObject : BaseBusinessObject
{
public virtual string Id { get; set; }
public virtual IDictionary Data { get; set; }
public virtual IDictionary Collections { get; set; }
}
The controller action should ideally have a deifinition like ...
public ActionResult DOThis(BusinessObject bo) {}
What you are looking for is FORM Binding, there are lot of resources available, This link gives you some insight.
You should use the JsonResult for going from the server to the client. http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=399#start
The DefaultModelBinder will take care of the binding to the server. There is also a section in this page talking about calling from JQuery to the server and getting back the JsonResult.
Hope this helps!

Categories