WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Thursday, November 29, 2012

HttpWebRequest - 500 Internal Server Error - Faulty JSON



So while making a web request from a C# application and if you end up hitting a 500 Internal Server error its usually because of the following or atleast this is what most google would talk about:

As a note, Internal Server Error is on the server side, The server crapped out on something
Most common issues that's not related to your actual code:
  • Maybe Invalid authentication or invalid credentials
  • Maybe invalid contenttype being passed
  • Maybe wrong request method (GET instead of POST or vice-versa)
  • Maybe invalid content length being posted
  • Or even maybe because of some proxy issue
But I came across something very strange recently while doing a Http POST from a c# WebPI application to a REST based WCF service. So it seems like the Newtonsoft JSON.NET that come's along with WebAPI (NuGet) is serializing the DateTime object to JSON a bit differently. The old JSON.NET library converted DateTime value into Ticks while the new JSON.NET library is coverting it to a string. Following is an example of old and new JSON.NET library:

New JSON.NET Library: Old JSON.NET Library: So it seems that WCF is unable to deserialize the new DateTime format and fails during deserialization of input as the DateTime types are different. One solution to this problem is to serialize the object to JSON using the JavascriptSerializer (System.Web.Script.Serialization namespace). Example code:

Labels: , , , ,

Thursday, March 15, 2012

WCF Data Contract Versioning

One of the greatest challenges when building any Webservice especially if it involves various clients connected is the issue of versioning. Following is possible version changes that WCF can handle by default:

Adding new Parameters to an OperationClient unaffected. New parameters initialize to default values at the service
Removing parameters from an operationClient Unaffected. WCF ignores old parameters, data lost at the service
Modifying Parameter typesException will occur if the incoming type from client is different from server
Modifying return value typesException will occur
Adding new operationsClient unaffected. Will not invoke operations it knows nothing about
Removing operationsException. It would be unknown action header


Operation contract changes possible solutions:
1) Service contract Inheritance
2) Brand new service contract with new namespace

Data contract changes
1) Adding IExtensibleDataObject
* ExtensibleDataObject is basically Key-Value dictionary
* This dictionary holds properties that old or future code contracts don’t have
* Basically it preserves the properties that don’t exists in the request or response
* Need to use svcutil.exe or visual studio reference to utilize this.
- By default all proxy class’s have this

Example:

Labels: ,

Automapper setup in WCF

Unlike Asp.NET, WCF has no global.ascx file where we can instantiate global objects for the life of the AppPool or until IIS restarts. Most programmers at some time would have used Object mappers such as AutoMapper etc. Automapper by far is my favorite of object mappers, simple to use and easy to configure. But AutoMapper requires the object properties be mapped between Source type and Destination type before any mapping is executed. This can be fairly easily be achieved in Asp.net by creating the mapping in global.ascx thus automapper is ready to map objects when requests are made. But in WCF, since it’s stateless there is no global class that is executed once for the lifetime of the service. But there are other ways to go around this global execution.

One such way is to create a ServiceBehavior that is executed when the Service is initialized. Following is how it’s done:

Step 1, is to create ths ServiceBehavior which would bind to all services and calls’ the automapper initialization function



Note: following namespaces are required for the above code to work


Having the ServiceBehavior an Attribute type, we can pick and choose services to provide more control. And in the AutomapBootstrap class we define the mappers



Having a static function helps in not creating a new AutomapBootstrap object on every service request. This same technique can be used if you use ServiceLocators (IOC) which requires global initialization.

Labels: , ,

Async WCF web-Services

In the world of Scalable programming, it’s all about Event Driven or Asynchronous programming. Event driven, callback based programming like node.js have taken the programming world by storm and few .NET based open source Event driven servers like KayakHttp (OWIN) have it’s uses but when it comes to Asp.NET MVC or WCF, asynchronous programming can be achieved using Tasks based programming approach. Do remember that Asynchronous programming model requires a good data access/interaction system design. A good async design can provide better scalability and potentially high server throughput. NOTE: higher throughput is server handling more requests and not speedier execution (some cases, yes)

A WCF service having async operations can provide a higher server throughput since the server is not longer waiting for the operation to complete to serve the next request. Off-course an Async design pattern adds complexity to the system. Following is how to provide a async operation:

Step 1, in the service interface we need to let the OperationContract know it’s a async operation



Step 2 is make the function call Async by providing a Begin and End operation. Basically Begin method is called when operation starts and End Method is the callback function when the operation completes execution. Following is the same function as above but with Begin and End




Step 3, once the operations are modified with Begin and End methods in the Service Interface, we need to build out the functions in the actuall Service Class.




In BeginGetData function, a new async Task is spawned with a return value of “string” and once the method “GetData” is executed the callback function is called. Task.ContinueWith is trigged only once the value is returned or if there is any unhandled exception thrown. In EndGetData function, basically takes the result and returns back to the calling client.

An example of calling client:




To learn more about Tasks, MSDN should be a good starting point [http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx]

Labels: , ,

WCF REST Service Operation Description

Having a REST based Service enpoints (Article 1) can be a nightmare to query if the parameters are not known already. This parameter suspense can be avoided by enable Web Helper in the WCF configuration.

AS part of the enpointBehaviour you can add the following to provide operation Description



would add http based service description like the following:



The operations can be explored by clicking on the Method link and this would provide you with request and response parameters names and type.

Labels: ,

WCF - REST Endpoints JSON

With more public facing websites providing access to their data, it is quite necessary for the API to be of KISS [Keep it simple Stupid] by design. Long gone are the days with services being SOAP and XML based. REST [Representational State Transfer] based endpoints is the way to go now.a.days. REST based urls are both SEO friendly and much for cleaner URI and easier to remember. When it comes to API design, a REST based endpoint provides a simple and clean URI for it to be consumed.

In .NET world, REST based endpoints can easily be created in an ASP.NET MVC application either by using Routes or by URL rewriting. But in the case of WCF (Windows communication Foundation) REST based endpoints are not provided out-of-the-box. To make this happen we can either configure WCF manually (this article) or we could use frameworks like WCF Web API (which is now called ASP.NET WebAPI and would be part of ASP.NET MVC 4.0) and ServiceStack.NET. The idea behind both the frameworks (SS.NET & WebAPI) is to provide REST based out of the box support for XML, JSON and ODATA (in webapi).

To configure WCF to provide REST based enpoint we need to first enable “ASPNETCompatibility” and have the REST endpoint bind to “webHttpBinding”. In the WCF web.config, following changes would be needed:



Step 1 is to enable aspNETCompatibility we need modify the “serviceHostingEnvironment” to turn on compatibility.


Step 2 is to create a endpoint behaviour to enable http based GET/POST requests. We create the following behavior and provide it with a name for reference:



Step 3 is to hook up the webservice to this behavior either at its default URI location or a custom URI location. Following is a json endpoint for the service:



For WCF Service to allow http based requests we need to bind the service to “webHttpBinding”. webHttpBinding is used to configure endpoints for Web services that are exposed through HTTP requests instead of SOAP messages. Do keep in mind, the contract is the Interface namespace of the service being exposed.

Step 4 is now to enable ASPNEtCOmpatibility in the Service Class



Note: ASpNETCompatibilityRequirements attribute is based of “System.ServiceModel.Activation” namespace.

Step 5 is offcourse to let the service to know if the output is a JSON or XML response. In the service interface, the methods attributes needs to be defined:



Note that Request and Response format can be JSON or XML and also Method could be either POST or GET. URI Template is the method name that will be exposed thru the service.

You are DONE!

You can access the service using the SVC URI like http://localhost/Service1.svc/json/{method}

NOTE: If you would like to add a SOAP based URI endpoint to provide a WebApi style service interface, you can add the following endpoint to the service section



JSON endpoint : http://localhost/Service1.svc/json/{method}
SOAP endpoint: http://localhost/Service1.svc/soap/
WSDL: http://localhost/Service1.svc?wsdl

Labels: , ,