Archive for category WCF

Ninject + WCF Docs

I’ve recently started using Ninject, having previously only used Unity as my IoC container, but it seems the internet is scarce of any documentation. I’ve employed the WCF extension, and found this handy guide on how to get up and going with it. www.aaronstannard.com/post/2011/08/16/dependency-injection-ninject-wcf-service.aspx

ps- This is my 200th blog post! Woohoo!

No Comments

WCF Services with both JSON and SOAP endpoints

A quick example of how to set this up in the web.config.

Services, in this example, can be accessed

  • using JSON via localhost/Services/MyService.svc/HelloWorld or..
  • using SOAP on localhost/Services/MyService.svc/soap/HelloWorld
  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

    <services>
      <service behaviorConfiguration="WebServiceBehavior" name="Demo.Web.Services.MyService">
        <endpoint address="" binding="webHttpBinding" contract="Demo.Web.Services.IMyService" behaviorConfiguration="jsonBehavior" />
        <endpoint address="soap" binding="basicHttpBinding" contract="Demo.Web.Services.IMyService"/>
      </service>
    </services>

    <behaviors>
      <endpointBehaviors>
        <behavior name="jsonBehavior">
          <webHttp defaultOutgoingResponseFormat="Json" />
        </behavior>
      </endpointBehaviors>

      <serviceBehaviors>
        <behavior name="WebServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <bindings>
      <webHttpBinding>
        <binding crossDomainScriptAccessEnabled="false" name="httpBinding" />
      </webHttpBinding>
    </bindings>

  </system.serviceModel>

No Comments

Why ASMX web services are not an excuse anymore with WCF 4.0 – Pablo M. Cibraro (aka Cibrax)

Why ASMX web services are not an excuse anymore with WCF 4.0 – Pablo M. Cibraro (aka Cibrax).

No Comments

WCF 404.3 Errors

I built a WCF service recently which would run fine in the visual studio test web server, but when i tried to actually hit it from real life IIS7 also on my local box, i receievd the following error:

HTTP Error 404.3 – Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

Luckily, i found the solution on David Waddleton’s blog and it was as simple as turning on a windows feature in add remove programs- on my vista box i had to go to Control Panel > Programs and features > Turn on/ off Windows features > Microsoft.NET framework 3.0 and tick the WCF activitation options!

No Comments

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

, ,

No Comments

Properties getting “k__BackingField” appended to their name in the WSDL file

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.

No Comments

Making your WCF Service compatible with legacy .net 1.1 applications

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.

No Comments