I am in a situation where I possibly can influence a decision about some web service work on the C# side and need some nice info (ammunition) that I can use to choose what I think would be better(JSON).
Could anyone give me any help as to the pros and cons of each? One of things that I like about JSON is that is it much cleaner to maintain, it supports any web browser(i think) and it supports(i am pretty sure) the ability to send non-primitive objects across the pipe. If IIS can do all of those things then please inform me differently. thanks!
If the decision is for the data transport, is best to use JSON than xml, since the footprint is smaller, the translation from the string to the object is easily supported in all languages (javascript, C#), you can use JSON services to communicate cross domains (which fails if you are using an XML web service).
a non primitive data type is transformed to a JSON string, you can have really complex objects in JSON format, the only issue you may find is the Date transformation, but if the code is only for your company, that may not pose a problem since the serialization and de-serialization will be the same.
you can find the description of JSON here.
To be able to get more help you will have to be more specific on what do you want to do.
Related
I have some CLR-based procedures in my SQL Server database that need to consume a RESTful web service, POSTing lists and retrieving collections of statuses.
I thought I could use the JavaScriptSerializer and use JSON, but I'm having a lot of trouble getting the SQL Server to let me (JSON.NET and System.Script.Serialization not being a assemblies I'm allowed to play with, apparently, and the dependency trees gets kinda ugly).
So then I thought, I could use the XmlSerializer, but it seems to be expecting a lot of metadata (contract-style) stuff that the REST service doesn't provide, and it doesn't seem to let you cast your resultant XML to a particular type (like Dictionary<int, string>, or decimal[]) like I would expect with the JavaScriptSerializer or the JSON.NET serializer.
I've spent the last hour looking for what seems like it should be a simple answer, or a simple method, and I'm hoping my Google-fu just has ebola. I can't find any official recommendation on how to do this, and it seems crazy to even contemplate rolling my own serializer/ deserializer when this has to come up all the time.
How do you parse RESTful service requests and responses from a CLR assembly without going through code heroics?
Create POCOs that match the XML you are trying to parse (you can use annotations to make the object model match the XML model), then use XMLSerializer to parse to a object graph of those POCOs.
This site will help you make that work, since normally the system generates dynamic assemblies to accomplish this (and SQL won't like that):
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/3fa5dce3-b0f3-44f8-9b7b-65439f1c98ae/cannot-deploy-xmlserializers-clr-assemblies
Are you sure this has to be done/should be done at all in the database?
I am porting a SOAP WCF service to REST. So far, I found out that receiving a complex type as a response does not require pretty much anything. However, my problem is that the request is complex type also. It has 2 fields, one of them is string, the other is a list of another complex type.
I thought to make it WebGet because its basically a search method which asks for certain parameters and returns the resuls.
How should I go about doing this ? What is/isn't recommended ?
Note that I do not have much experience in WCF, apologies if I have missed something obvious.
If you want to conform to REST conventions but keep the same request structure, you're probably going to have to serialize the complex type array, url encode it, and pass it as a parameter. This will probably generate very long URLs, which could be a problem. Using POST is more practical, but as #Aron notes this is not consistent with REST, since POST should only be used for updates, not queries.
Instead of trying to copy the SOAP request structure, I'd suggest you think about what this service is doing and re-conceive the input options in a way that can neatly fit into parameters. If you're exposing this interface to 3rd parties, they're going to be baffled by the array of complex types regardless of how you express it.
Based on your feedback and considering your constrained by the fact that you have no control over the class that does the actual work, here it's my suggestion:
Use a post to that endpoint, the complex query. It's true that it's not following the letter of rest, but it's a step closer to utilizing https verbs and no one should knock you for it.
You should also consider defining separate endpoints for the methods in the old SOAP architecture, less points of failure. This approach is closer to an RPC, remote procedural call, but that is better than a POX, plain old xml which is what SOAP is.
Hope this helps, by the way if you read Fielding's dissertation on REST, you're not fully REST until you also implement Hypermedia, but that's an opinionated subject.
I'm just starting out really with WCF and Web Services in general. I have a pretty firm understanding on the purposes behind them and how they work, but I was wondering what the capabilities with them are if you wished to return something other than Text; such as a straight HTML form, or an image.
I've done some simple googling but alas all I can find is how to handle data passed from a form, rather than how to return a form.
I hope someone could give me a good starting point on what I should be looking at. I looked at a thread stating to look at Streaming with WCF but that may seem a bit excessive and was wondering if someone could give me some general advice and input.
Many thanks,
Ronald.
WCF services can return any object that the runtime can seralize. We return custom objects in our services with no issues, provided it's a .NET Client consuming them. Other languages may have to work harder to de-serialize complex objects.
(Meaning you have to write more code because non-Visual Studio IDE's probably won't know how to auto-generate the required client code.)
It probably depends on the actual binding but, for the sake of simplicity, assume that you bind your WCF service over http. Then, everything you pass to and from the service should somehow be translated to string. Simple types, ints, doules, strings, are easily convertible. Compound types - also, as they consist of simple types. When it comes to specific types like images or html forms, you always try to find a way to convert them at one side and convert back on the other side. In many cases the serializer can do it for you, for example if you return byte[], the data will be encoded as base64 string. If the serializer fails for some reason, you have to find your own way to pass your specific types. Please also remember that for WCF, it is you to select a particular serializer:
http://nirajrules.wordpress.com/2009/08/26/wcf-serializers-xmlserializer-vs-datacontratserializer-vs-netdatacontractserializer/
WCF is designed to build web API using standard or custom protocols. If you use the default configuration, WCF will output objects serialized using SOAP, but JSON is available too, for instance.
WCF is certainly able to output plain HTML, but it isn't designed with this goal in mind. It is meant to be used for communication between processes.
I've looked at quite a few of the questions on the site, but I'm still having trouble fulling understanding where to begin.
I've never done anything with webservices before, so bear with me.
The current project I've been assigned is to write a webservice that queries a database and returns the data back to the client. (using .NET 2008 programming in C#)
So far, I've been able to do basic data types no problem, but I'm not 100% sure where to go from there. I've been returning an XmlDocument type, but I'm not sure that that's the best way, or even the correct way to do it.
Currently creating an ASP.NET Web service, though it's been suggested I use a WCF Web service.
Can anyone shed light on where to go from here? Or perhaps a a link to a tutorial on sending and recieving large amounts of data via webservices?
EDIT: The answers are great so far, but I'm still not 100% sure how to answer. I think the webservice will be interacted with a combination of client programs, but also websites, if that is all possible... That's how new I am to this.
Depending on the structure of the data that you're sending back to the client, I wouldn't recommend using XmlDocument as the return type. It will add a lot of unnecessary bulk to your response.
You really didn't state the protocol that you want to support, but if you're transporting data via HTTP, then sending your data back to the client as a JSON-formatted string would streamline it better.
You can define that you're returning your complex type formatted as JSON like this:
[WebGet(ResponseFormat=WebMessageFormat.Json, UriTemplate="GetComplexObject/{id}")]
public MyComplexType GetComplexObject(int id){
//do work to get your object
return myObject;
}
WCF will take care of serializing your object as JSON if MyComplexType is defined as a DataContract...
[DataContract]
public class MyComplexType{
[DataMember]
String Name {get;set;}
}
If you're looking for REST-ful services, then WCF is probably the preferred approach using the WebHttp functionality.
The WCF team put together a great series of walk-throughs on using WCF WebHttp (which is new to .NET 4). They assume a little knowledge of web http programming, but they're pretty good and hopefully help put you on the right track.
I hope this helps!! Good luck.
http://msdn.microsoft.com/en-us/library/ms733127.aspx
WCF uses this concept of a data contract - which provides serialization help on complex objects.
If you decide to use WCF there is a tutorial available at : http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx .
In general, this article gives a walk through of building an ASP.NET web service that sends JSON.
JSON is faster than XML, and is becoming a standard for most new web services. I highly recommend the JSON.NET library for JSON serialization.
There are two ways that I have implemented this using a regular ASPX.NET web service:
Have the same underlying object libraries on the client and the server and functions to translate the data from the web service object to the client object.
Have the same underlying object libraries on the client and the server and pass data to/from the server as a string representation of the data object (usually XML format, but could be JSON or another similar format)
The first option I found is VERY cumbersome. The web service will claim that its versions of the libraries are unique, even if you have the same classes/objects on both the server and the client. Even if the namespace is the same, the object returned from the web service will have the web service namespace in it somewhere, so you have to write functions to convert them. I know of a way to fix this, but it is not worth the effort, at least not for me.
The second option is the one I am using right now. I again have one library on both client and server. It has objects that get and hold data from the database. I then have generic utility functions that serialize objects to and from XML strings. When I send data from the server I serialize it to an XML string on the server and deserialize it at the client. I do the reverse when sending data to the server. I also break up large amounts of data being passed to/from the web service to reduce errors and data transfer time.
WCF may be better. Never used it. But the above is what I have done with standard web services.
The best way to send data back to client it's throught xml, because almost all languages know how to handle xml document.
If you want to return something that it's in some way language dependent is't not worst to implement if you want your web service to be implemented using virtually all languages posible.
Another posibility is to return json objects.
I think this question is like clay pidgeon shooting.. "pull... bang!" .. shot down.. but nevertheless, it's worth asking I believe.
Lots of JS frameworks etc use JSON these days, and for good reason I know. The classic question is "where to transform the data to JSON".
I understand that at some point in the pipeline, you have to convert the data to JSON, be it in the data access layer (I am looking at JSON.NET) or I believe in .NET 4.x there are methods to output/serialize as JSON.
So the question is:
Is it really a bad idea to contemplate a SQL function to output as JSON?
Qualifier:
I understand trying to output 1000's of rows like that isn't a good idea - in fact not really a good idea for web apps either way unless you really have to.
For my requirement, I need possibly 100 rows at a time...
The answer really is: it depends.
If your application is a small one that doesn't receive much use, then by all means do it in the database. The thing to bear in mind though is, what happens when your application is being used by 10x as many users in 12 months time?
If it makes it quick, simple and easy to implement JSON encoding in your stored procedures, rather than in your web code and allows you to get your app out and in use, then that's clearly the way to go. That said, it really doesn't take that much work to do it "properly" with solutions that have been suggested in other answers.
The long and short of it is, take the solution that best fits your current needs, whilst thinking about the impact it'll have if you need to change it in the future.
This is why [WebMethod] (WebMethodAttribute) exists.
Best to load the data to to the piece of program and then return it as JSON.
.NET 4 has a support for returning json, and i did it as a part of one ASP.NET MVC site and it was fairly simple and straightforward.
I recommend to move the transformation out of the sql server
I agree with the other respondents that this is better done in your application code. However... this is theoretically possible using SQL Server's ability to include CLR assemblies in the database using create assembly syntax. The choice is really yours. You could create an assembly to do the translation in .net, define that assembly to SQL Server and then use contained method(s) to serialize to JSON as return values from your stored procedures...
Better to load it using your standard data access technique and then convert to JSON. You can then use it in standard objects in .NET as well as your client side javascript.
If using .net mvc you serialize your results in your controllers and output a JsonResult, there's a method Controller.Json() that does this for you. If using webforms an http handler and the JavascriptSerializer class would be the way to go.
Hey thanks for all the responses.. it still amazes me how many people out there have the time to help.
All very good points, and certainly confirmed my feeling of letting the app/layer do the conversion work - as the glue between the actual data and frontend. I guess I haven't kept up too much with MVC or SQL-2008, and so was unsure if there were some nuggets worth tracking down.
As it worked out (following some links posted here, and further fishing) I have opted to do the following for the time being (stuck back using .NET 3.5 and no MVC right now..):
Getting the SQL data as a datatable/datareader
Using a simple datatable > collection (dictionary) conversion for a serializable list
Because right now I am using an ASHX page to act as the broker to the javascript (i.e.
via a JQuery AJAX call), within my ASHX page I have:
context.Response.ContentType = "application/json";
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
I can then issue: json.serialize(<>)
Might seem a bit backward, but it works fine.. and the main caveat is that it is not ever returning huge amounts of data at a time.
Once again, thanks for all the repsonses!