Using JSON.NET with RESTful WCF service in .NET 4 - wcf

Has anyone got a RESTful WCF service (in .NET4) successfully using JSON.NET to do serialization/deserialization?
What's the best approach?

Can you provide a few more details about what you're trying to do with JSON.NET? I'm not exactly sure what scenarios you're trying to deal with -- but I'll give you my general experience with JSON.NET and WCF RESTful services.
I've built a number of WCF RESTful services that are called, primarily, by my client app using jQuery's AJAX functionality. Generally, I have not had to use JSON.NET as the JsonSerializer does a fine job of serializing my return values (single values or List<T> collections) perfectly fine and can navigate through the object without issue.
The times that I've had to use JSON.NET is when I'm sending a JSON object as part of my POST variables that I've serialized on the client using the JSON2.js library. JSON.NET has done a fine job of serializing and deserializing those values without issue, too.
I like JSON.NET -- haven't had any issues. Honestly, when I started out, I thought I would use it a lot, but have found that I only need it for edge cases. Generally I rely on the built-in JSON serialization and deserialization capabilities in WCF.
I hope this helps. Please let me know if you need more info or if there are specific scenarios you're trying to handle, and I'll update my answer accordingly. Thanks!

Related

Existing SOAP service and new Angular Web App

We have an established WCF SOAP service. Its interface is defined in WSDL, from which C# classes are generated for our server (customers generate client-side bindings in various languages, from the same WSDL). The WSDL has a current version, which we can change a bit, and old versions, which we can't change or drop without a deprecation period, consultation etc. The SOAP requests tend to be complicated, having multiple XML namespaces within the same request.
The WCF SOAP service has a lot of "smarts" in it, and provides exactly the kinds of fetching and reporting facilities that we need for a new Web application that we need to make. We hope to use AngularJS for the client side of that. But these complex SOAP requests aren't easy to make in JavaScript world. If only we had a REST service, we could use angular Resource service. If not that, then a server that spoke JSON, albeit in an RPC style like SOAP, would run a fairly close second.
I've had various ideas for how the impedance mismatch between our server and client might be mitigated. But nothing sounds quick or easy.
I've thought of: -
Write a new REST service. Exactly what the client-side wants, but a serious piece of new development.
WebHttpBinding looks to offer something. But seems to me like it requires C# markup of custom attribute (how to achieve when our C# is generated from WSDL) and possibly wouldn't support our complex types
Obtain or write loads of client-side JS to abstract away calling SOAP services. But, unless this can be auto-generated from the WSDL, it's a huge amount of client-side code to write.
Write an IDispatchMessageFormatter for the server, to accept some JSON format of messages that I invent. Sounds hard, especially as good examples of people implementing and integrating IDispatchMessageFormatter seem hard to come by.
Write a MessageEncoder to swap between JSON and XML. But this isn't really an encoding operation, as became very clear when I tried to write it!
I'm searching for suggestions.
Generally, I recommend a REST service for any AngularJS development and have wrapped a number of legacy systems with Node.js API servers. Of course there is a massive amount of "it depends", but generally most projects will be happier and more productive following that route.
Some Things To Think About
How well does your current SOAP API fit the user interface requirements?
Are you experienced with Express, Sinatra, Flask or other micro-framework that allow rapid development of REST APIs? I find I can build a solid Node.js Express API server in a couple of hours and then extend it as I build the AngularJS application out.
How experienced are you with AngularJS? It's a more advanced project to build a complex data layer client-side.
Six Reasons Why REST is Important for AngularJS
It's much faster to write Angular code using $resource and $http. Get the API right is a good recommendation for effective AngularJS development. Indeed, you could argue that AngularJS is designed for REST, and that's why plain JavaScript works for the model (see 2).
Angular's plain-old JavaScript object data model works well with a REST API that speaks JSON that matches the user interface. However, issues arise when there isn't a good fit- Angular doesn't have a formal data model so you end up writing an lot of code trying to rationalize your API to work well with Angular. 3rd party libraries like breeze.js may offer some solution, but it's still awkward.
You can scale easily with caching. It's easy to add Redis or memcache or Varnish or other common HTTP caching solutions into the mix. Resource-based abstractions are perfect for caching strategies due to the transparency and idempotency of a REST api.
Loose coupling of front-end and server- it will be easier to support changes to the backend if you migrate off SOAP or need to integrate with other services.
It's generally easier to test JSON APIs separately from AngularJS logic, so your test suites will be simpler and more effective.
Your new REST API will be easier to leverage for future AngularJS and JSON-oriented projects.
I hope that helps.
Cheers,
Nick

Injecting Services In Deserialized Data Contract Proxies

I'm using Autofac with WCF integration in a project. I'm trying to figure out a way to lazy initialize data contract proxy collection properties to avoid transferring entire object graphs across the wire.
My current plan is to inject the WCF service in each deserialized data contract so they call the service, get the collection property data and initializes it.
My question is: Is there a way to tell Autofac to inject services in each data contract proxy deserialized at the client? Like some tweaking at the DataContractSerializer or something.
(No service locator, please...)
Thanks!
Unfortunately there is nothing like this available "out of the box" with Autofac. There is something similar in Autofac's MVC integration, but that's because MVC has a more specific integration point for that sort of thing (IActionInvoker).
You might be able to write a custom client-side behavior that intercepts certain known types (like collections) on the client and swaps in a lazy-initialized collection. There's a similar question here asking about how to swap the DataContractSerializer out at runtime. You could use a mechanism like that.

Should i use httphandlers or web services?

I have a simple scenario where i want to output only json to the user.Now should i use a simple httphandler, call it from jquery and get the json or create a WCf service?
I want to use WCf service but don't see any advantage, maybe someone can point few of them and scenarios.
Anything would be suffice. Your thoughts are in correct direction, why to create a wcf service and increase the overload(maintaince, deployment etc).
If you are using Ajax, Look in to PageMethods, which would even free you from creating a separate HTTPHandler and you could call your code behind methods directly in your javascript.
I am assuming you are using asp.net.

Consuming a WCF Rest Service with WP7

I have a WCF Restful Service that returns JSON objects that my iPhone and Android apps consume nicely. This is my first attempt at building something like this and I left WP7 till last as my background lies with C# and VS2010. But it seems it’s not going to be a simple as I had guessed.
So I guess I have three questions:
1, Can I consume JSON objects in WP7? If so does anyone know of a tutorial?
2, if not, can I use the existing service and build some new contracts for consumption in WP7? Or,
3, do I need to build a whole new service?
Option one is most desirable but either way, I need to develop for all three operating systems so does anyone know the best type of model to bring this all together???
Cheers,
Mike.
Yes, but not with the channel factory / proxy programming model which you may be used to with WCF. REST services are usually consumed by using some simpler classes such as WebClient. You can use the JSON libraries (DataContractJsonSerializer is in the WP7 profile) then to deserialize the data you receive. Even the untyped JSON (the System.Json classes from the System.Json.dll on Silverlight), while not officially in the profile, they kind of work on WP7 as well (I've seen a few people simply referencing the SL library on a WP7 project).
If you want proxy support, you can add a new endpoint to the service using BasicHttpBinding, which is supported in WP7; if you don't need it, see 1).
No. See 1) and 2).
Try this to deserialize a JSON object:
public static T Deserialize<T>(string strData) where T : class
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
byte[] byteArray = Encoding.UTF8.GetBytes(strData);
MemoryStream memoryStream = new MemoryStream(byteArray);
T tRet = serializer.ReadObject(memoryStream) as T;
memoryStream.Dispose();
return tRet;
}
I find a totally wcf-based approach more interesting.
This is a good post that addresses this issue
http://blogs.msdn.com/b/carlosfigueira/archive/2010/04/29/consuming-rest-json-services-in-silverlight-4.aspx

Can I use Json serialization in WCF service?

I am going develop a WPF windows based application. I want to work with Entity Framework Self Tracking Entities and WCF. I was wondering if using Json is possible/recommended? If yes, please assist me; is there any tutorial that can help?
You can use the DataContractJsonSerializer to serialize the messages. You will have to use a REST based service (WebHttpBinding) as SOAP mandates XML as the message payload.
You can tell WCF to use the DatcontractJsonSerializer on the service side by settings in the WebGet and WebInvoke attributes but on the client side you will have to manually use this serializer as REST doesn;t have a metadata standard and therefore you have to create the requests and manage responses in a more manual fashion
Here is a reasonable guide to using Json and REST support in WCF
However, what is your driver to using Json? WCF is much more geared to SOAP based interaction currently (although the WCF 4.5 WebApi is going to address that to quite a degree). As your client is WPF you don't seem to gain alot from using Json