dotnet thoughts 

a dotnet developer's technical blog

How to create RESTful WCF services

In the current project, I am working with WCF services in .Net 4.0. Few days back I got a question like how can we make a WCF service RESTful. Yesterday I played around it and I could figure out how it works.

In this post I am posting how to create a RESTful time service, which will give the current system time,

http://localhost:8080/TimeService/

and the next method give current time with specified format.

http://localhost:8080/TimeService/ddMMMyyyy

As usual for creating a WCF service you need a service contract. For making WCF services you need special attributes. And you need to add reference of System.ServiceModel.Web. And if you want use custom POCO classes, you need to add the reference of System.Runtime.Serialization.

Here is the Service interface

[ServiceContract]
interface ITimeService
{
    [OperationContract]
    [WebGet(UriTemplate = "/")]
    string GetTime();

    [OperationContract]
    [WebGet(UriTemplate = "/{timeformat}")]
    string GetFormattedTime(string timeformat);
}

The WebGet attribute is enables the GET method in the service. The UriTemplate specifies the address. And all the parameters should be string, and parameter name should be match. It also support POST and PUT protocols.

And here is the implementation

class TimeService : ITimeService
{
    public string GetTime()
    {
        return DateTime.Now.ToString();
    }

    public string GetFormattedTime(string timeformat)
    {
        return DateTime.Now.ToString(timeformat);
    }
}

I am using Self Hosting for this. And here is this Service Host implementation.

static void Main(string[] args)
{
    using (ServiceHost serviceHost =
        new ServiceHost(typeof(TimeService)))
    {
        string baseUri =
            string.Format("http://{0}:8080/TimeService",
            Environment.MachineName);
        ServiceEndpoint serviceEndPoint =
            serviceHost.AddServiceEndpoint(typeof(ITimeService),
            new WebHttpBinding(), baseUri);
        serviceEndPoint.Behaviors.Add(new WebHttpBehavior());
        serviceHost.Open();
        Console.WriteLine(
            string.Format("Server available on the url - {0}",
            baseUri));
        Console.WriteLine("Press <ENTER> to stop listening.");
        Console.ReadLine();
        serviceHost.Close();
    }
}

Here is the screen shot RESTful service running.

RESTful Service Running

RESTful Service Running

And here is the the screenshot of the RESTful service accessing via Internet Explorer.

TimeService - With no parameters

TimeService - With no parameters

TimeService - With format specified on the URL

TimeService - With format specified on the URL

This following code snippet to how to access WCF RESTful service with WebClient.

using (WebClient webClient = new WebClient())
{
    using(StreamReader sr =
        new StreamReader(
            webClient.OpenRead("http://localhost:8080/TimeService/")))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Internet Explorer 9 RTM Released

IE 9 RTM

IE 9 RTM

IE9 RTM is now available for download from http://windows.microsoft.com/en-US/internet-explorer/products/ie/home

DreamSpark Yatra at Kochi

K-MUG student chapter in association with Microsoft is conducting DreamSpark Yatra at Kochi, to help students become aware of the latest technologies & thereby start the journey towards becoming more employable. K-MUG students’ chapter is lead by the Microsoft Student Partners (MSP) – The student volunteers who are specially selected by Microsoft on an annual basis. They are passionate about technology and are keen to help other students realize their potential.

DreamSpark Yatra event will give interested students the opportunity to learn about current and emerging technologies & also get DreamSpark access keys- all at no charge!

The Microsoft DreamSpark program provides professional-level developer and design tools to students at no charge. These Microsoft tools help students to advance their learning and skills through technical design, technology, math, science, and engineering activities.

Agenda & registration Details will be updated soon. Click here for more details

Unit Test Adapter threw exception – Unable to load one or more of the requested types

Today evening while working(?) around unit tests and code coverage, I got an exception from Visual Studio 2010. I wrote two unit test cases and it was passing, then I enabled code coverage in my solution, and the passing unit tests started failing. And I am getting error message like Unit Test Adapter threw exception: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. from Test results window. :( Initially I thought Microsoft PEX is the culprit ;) I searched for the solution and found few solutions;like Clean and Build, but it didn’t worked for me. From another blog I found some other solution like to modify the vsmdi file. But I didn’t tried that option. Later I come to know, I forgot to disable the signing of the assemblies. You can do this selecting Project Properties > Signing > Un-check the sign assembly checkbox. I disabled the signing in the assemblies and it started working. :D

Happy unit testing :)

How find all the types implemented by an interface

Here is code snippet which helps to find all the types from an assembly, which is implemented from a specific interface.

var types = from type in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IPlugin).IsAssignableFrom(type) && !type.IsInterface
select type;

And here is the same which is implemented by lambda expressions.

var types = Assembly.GetExecutingAssembly().GetTypes().Where
    ((type) => typeof(IPlugin).IsAssignableFrom(type));

Happy Coding :)

Older Posts »