Archive for category Web Services
Getting started with WCF and REST web services
I’m building some REST WCF services at the moment and found this great guide online www.robbagby.com/rest/rest-in-wcf-blog-series-index
The HiREST stuff shows you how to create fully fledged REST services utilising all of the HTTP verbs.
Heres a quick summary of the most useful bits;
The service itself is just added to the project as a normal WCF service. The following needs adding to the Web.config to setup the end
points;
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="AJAXFriendly">
<enableWebScript />
</behavior>
<behavior name="RESTFriendly">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service name="MyNamespace.AjaxServiceClassName">
<endpoint address=""
behaviorConfiguration="AJAXFriendly"
binding="webHttpBinding"
contract="CatalogService" />
</service>
<service name="MyNamespace.RESTServiceClassName">
<endpoint address=""
behaviorConfiguration="RESTFriendly"
binding="webHttpBinding"
contract="MyNamespace.IRESTServiceInterfaceName" />
</service>
</services>
</system.serviceModel>
Remember the class names in the web.config need to be fully qualified.
An example class for passing around the service;
[DataContract]
public class ProductData
{
[DataMember]
public int ProductId;
[DataMember]
public string ProductName;
[DataMember]
public string Description;
[DataMember]
public decimal Price;
[DataMember]
public string ProductImage;
}
The service itself is just a normal WCF service so consists of its usual two parts- the interface and the class. Here’s an example interface
demoing the various access methods and return serialisations;
[ServiceContract]
public interface IRESTServiceInterfaceName
{
// responds to a GET request to www.mysite.com/Servicename.svc/products/
// return is serialised to JSON
[OperationContract]
[WebGet(UriTemplate = "products/", ResponseFormat = WebMessageFormat.Json)]
List<FlotChartSeries> GetProducts();
// responds to a GET request to www.mysite.com/Servicename.svc/products/{product_id}
// return is serialised to JSON
[OperationContract]
[WebGet(UriTemplate = "products/{product_id}", ResponseFormat = WebMessageFormat.Json)]
List<FlotChartSeries> GetProductById(string product_id);
// responds to a GET request to www.mysite.com/Servicename.svc/products?brand={brand}
// return is serialised to JSON
[OperationContract]
[WebGet(UriTemplate = "products?brand={brand}", ResponseFormat = WebMessageFormat.Json)]
List<FlotChartSeries> GetProductsByBrand(string brand);
// responds to a POST, but still passing a bunch of parameters into the querystring
// no return type
[WebInvoke(Method = "POST", UriTemplate = "product/{product_id}/rate?score={score}")]
[OperationContract]
void PostProductAppRating(string product_id, string score);
// accepts a POST with a JSON encoded product data, to allow for an update
// no return
[WebInvoke(Method = "POST", UriTemplate = "product/{product_id}", RequestFormat = WebMessageFormat.Json)]
void PostProductUpdate(string product_id, ProductData data);
//responds to a PUT- passing a querystring variable for the filename- it expects the body of the push request to be a file stream
// no return type
[WebInvoke(Method = "PUT", UriTemplate = "products/{product_id}/desktopimage?filename={file_name}")]
[OperationContract]
void PutProductImage(string product_id, string file_name, Stream fileContents);
}
Note the variables in the curly braces must match the real parameters to the method signitures for the value to be automatically mapped.
Responses are generally done using HTTP response codes. At the top of each method you need to grab the current WebOperationContext which
will allow you to set the return codes;
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK; // .. if everything is ok!
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.BadRequest; // on error
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Created; // after an insert
// all of the http response codes are mapped here
ctx.OutgoingResponse.SetStatusAsNotFound(); // if record cannot be found or similar
Properties getting “k__BackingField” appended to their name in the WSDL file
Posted by shawson in .net, C#.net, WCF, Web Services on December 7th, 2009
I was finding k__backingField was being appended to all my object properties when exposed via my a WCF service, in the WSDL. The solution it turns out was simple- just had to make my class a [DataContract] and mark the properties as [DataMember].
via WCF Data Contracts and “k__BackingField” Property Naming – Nathan Bridgewater.
Making your WCF Service compatible with legacy .net 1.1 applications
Posted by shawson in .net, C#.net, WCF, Web Services on December 7th, 2009
I’m building an error tracking service which all our future web project will report to, so we can track and tag all our various systems problems from one place- this is currently done with email which is a bit of a nightmare!
According to Microsoft, traditional ASMX web services are now considered “Legacy technology” (!) so I thought I would buite the bullet and build the new services using WCF.
This was fairly painless until I tried to consume the web service in some old .net 1.1 web apps- when trying to add the web reference I received this error message;
Web ReferenceslocalhostReference.map(1): Custom tool warning: DiscoCodeGenerator unable to initialize code generator. No code generated.
I found a great article over on the MSDN – and all it takes is a small change to the web.config, fiddling with, my old friend, the httpBindings.
I had to swap out the default bindings put in by .net;
<endpoint address="" binding="wsHttpBinding" contract="HachetteErrorTracker.IErrorLog">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
For this one;
<endpoint
address=""
binding="basicHttpBinding" bindingNamespace="http://errortracker.localhost/"
contract="HachetteErrorTracker.IErrorLog"
/>
How to: Configure WCF Service to Interoperate with ASP.NET Web Service Clients.
The provided URI scheme ‘http’ is invalid; expected ‘https
Posted by shawson in .net, C#.net, VB.net, Web Services on June 30th, 2009
Going from dev to live, where the dev system referenced dev version of web services, but the live system has to reference live versions which are HTTPS i recieved this error;
The provided URI scheme ‘http’ is invalid; expected ‘https
This is resolved simply by updating the web.config file and setting the security tag’s mode attribute from None to Transport;
<bindings> <wsHttpBinding> <binding name="WSHttpBinding_IWSHttpService" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" /> <security mode="Transport"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="None" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> </binding> </wsHttpBinding> </bindings>
Visually build XPath using “Sketch Path”
Posted by shawson in Web Services, XML, XPath on June 30th, 2009
Paul found an awesome tool fopr visually parsing XML files and building XPath statements, called Sketch Path available for download here
Quick XML serialisation of an object..
Posted by shawson in .net, C#.net, Web Services, XML on June 25th, 2009
Quick code snippet for taking a serialisable object, serialising to XMl then spitting out a string for you to write out to a debug log or something- i used this for spitting back the responses I was getting from a web service call i was making
StringBuilder sb_xml = new StringBuilder();
XmlSerializer s = new XmlSerializer( typeof( Hachette.Checkout.Vista.Stock.ProductStockLiteResultResponse ) );
StringWriter w = new StringWriter(sb_xml);
s.Serialize(w, ws_response);
w.Close();
Response.Write("<!-- Response = " + sb_xml + " -->");
Web Services Debugging with Fiddler 2
Posted by shawson in .net, C#.net, Web Services on May 26th, 2009
We have a bunch of e-commerce web services available here and we have the envyable task of supporting numerous third party developers using a plethora of different languages, which often don’t have native support for SOAP web services, meaning they have to hand craft their SOAP calls. Seeing that we are totally dot net, we only ever interface with our services using the proxy classes generated from the WSDL files by the .net framework so when they send us reams of XML with a few question marks it’s difficult for us to diagnose the fault.

Fiddler2 Web Service SOAP Debugging
The answer I’ve found is to use Fiddler2 which is a HTTP sniffer application which monitors all your HTTP traffic and allows you to inspect whats going on. So fire up fiddler2 FIRST, then fireup your test application (which generates the web service calls), place a call and watch it being logged on fiddler.
It’s imperative that you start Fiddler FIRST though or it won’t hook in and capture your SOAP calls!
You can download Fiddler 2 from here
As you can see from the screen shot on the right, the outgoing request is shown in the top right pane, and the response in the bottom right.