Archive for July, 2014

In this post, I am will be explaining you about  building web services in MS.Net using Service Stack.

Introduction to Service Stack

What is service stack? servicestack.net website defines it as “Thoughtfully architected, obscenely fast, thoroughly enjoyable web services for all”


ServiceStack_1

  • A fast, unified and integrated replacement for WCF, WebAPI and MVC and some of the Microsoft based web services.
  • It supports REST, SOAP and Message Queue services out of the box
  • Includes serializers for many formats
  • Provides a code-first ORM
  • User friendly HTML views of data
  • Includes packages for caching, authentication, clients, logging, dependency injection, profiling and much more

One of the key difference of service stack is that it is very fast

  • ORM benchmarks about 12X faster than the entity framework
  • JSON serialization benchmarks about 6X faster than DataContractJSonSerializer that comes with MS.Net

Focuses on the Data Transfer object/Message Pattern

  • Request object – Processor – Response Object
Make a Project

Create a new ASP.NET Web Application by going into Visual Studio and selecting File -> New -> Project on the File menu

Which means we are starting off by making a new “ASP.NET Empty Web Application” however you feel comfortable.

  1. Within Visual Studio navigate to File↓ New → ..
  2. On the left navigate to Templates↓ Other Project Types ↓ Visual Studio Solutions
  3. Select the Blank Solutiontemplate, give it a name, then click the OK button
  4. In your Solution Explorer right click the solution and select Add→ New Project…
  5. In the top-right search box enter NET Empty Web Applicationand select the C# variant
  6. Make sure to select .NET Framework 4 or newer at the top
  7. Give the project a name and click OK

ServiceStack_2

Installing and configuring ServiceStack

Next we need to download and reference ServiceStack. The best way to do this is through NuGet.

Right click on your web project and select Manage NuGet Packages…

  1. Within the left pane select NuGet official package sourceunder the Online category
  2. Search in the top-right for ServiceStack
  3. Select then click the Install button for the following packages:
    • ServiceStack webservice framework: Faster, Cleaner, Modern WCF alternative (ServiceStack)

 Select ServiceStack.Hello>Manage NuGet Packages

ServiceStack_3

Create 2 more new projects called DesktopApp which is a windows application and AuthenticationServiceModel which is a class library as shown below

ServiceStack_4

Application Host
  1. Right click on your web project and select Add→ New Item…
  2. Add a new C# Class file named “AppHost.cs” (under the Code category

Add a new class called AppHost.cs to AuthenticationService

using Funq;
using ServiceStack;

namespace AuthenticationService
{
 public class AppHost : AppHostHttpListenerBase
 {
 public AppHost()
 : base("AuthenticationService", typeof (AppHost).Assembly)
 {
 }

 public override void Configure(Container container)
 {
 }
 }
}
  1. Right click on your web project again and select Add→ New Item…
  2. Add a new C# Global Application Class(Found under the Web category) with the default name of Global.asax
  3. Initialize your app host within the Application_Startmethod of Global.asax.cs
protected void Application_Start(object sender, EventArgs e) {new AppHost().Init();}

 

 

Add Global.asax file with the following code to AuthenticationService

using System;

namespace AuthenticationService
{
 public class Global : System.Web.HttpApplication
 {

 protected void Application_Start(object sender, EventArgs e)
 {
 new AppHost().Init();
 }
 protected void Session_Start(object sender, EventArgs e){}
 protected void Application_BeginRequest(object sender, EventArgs e){}
 protected void Application_AuthenticateRequest(object sender, EventArgs e){}
 protected void Application_Error(object sender, EventArgs e){}
 protected void Session_End(object sender, EventArgs e){}
 protected void Application_End(object sender, EventArgs e){}
 }
}
Web.config

 

While ServiceStack isn’t big on using configuration files we still need to tell ASP.NET to handle requests with ServiceStack.

 

The configuration below allows you to host your webservices from the root path: /

Add the following lines to your web.config file

 

<configuration>
 
 <system.web>
 <compilation debug="true" targetFramework="4.5" />
 <httpRuntime targetFramework="4.5" />

 <httpHandlers>
 <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack, Version=4.0.23.0, Culture=neutral, PublicKeyToken=null" verb="*" />
 </httpHandlers>

 </system.web>
 <!-- Required for IIS7 -->
 <system.webServer>
 <modules runAllManagedModulesForAllRequests="true" />
 <validation validateIntegratedModeConfiguration="false" />
 <handlers>
 <add path="*" name="ServiceStack.Factory"
 type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*"
 preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
 </handlers>
 </system.webServer>
 

</configuration>

 

Just run the web application from Visual Studio and you should be presented with a mostly empty metadata page

ServiceStack_5

I don’t know about your requirements, but when I make web services it often involves me taking data from over here and shoving it down some HTTP tubes over there. ServiceStack makes this workflow really easy.

 

Create the name of your Web Service (i.e. the Request DTO)

Add AuthenticationRequest.cs class to AuthenticationServiceModel project

using ServiceStack;

namespace AuthenticationServiceModel
{
 [Route("/Authenticate", Verbs = "POST")]
 public class AuthenticationRequest : IReturn<AuthenticationResponse>
 {
 public string SystemId { get; set; }
 public string UserName { get; set; }
 public AuthenticationType AuthenticationType { get; set; }
 }

 public enum AuthenticationType
 {
 Windows,
 Basic,
 Aspnet
 };
}
Define what your Web Service will return (i.e. Response DTO)

Add AuthenticationResponse.cs class to AuthenticationServiceModel project

 

namespace AuthenticationServiceModel
 {
  public class AuthenticationResponse
  {
  public string Message { get; set; }
  }
 }
ServiceStack_6

Reference AuthenticationServiceModel class library to AuthenticationService project

using System;
using AuthenticationServiceModel;

namespace AuthenticationService
{
 public class AuthenticationService : ServiceStack.Service
 {
 public object Post(AuthenticationRequest request)
 {
 if (request.AuthenticationType == AuthenticationType.Basic)
 {
 //validate the user name with the password stored in EGIS metadatabase
 }

 if (request.AuthenticationType == AuthenticationType.Windows)
 {
 //validate the user name with Active directory
 }

 if (request.AuthenticationType == AuthenticationType.Aspnet)
 {
 
 }
 return new AuthenticationResponse
 {
 Message = String.Format("Success!. Welcome {0}.", request.UserName)
 };
 }
 
 }
}
Viewing your Web Services

 

That is all it takes to make a service. Yes really, check this out! Run the web project and navigate to the metadata page. It should look similar to what you saw before but now there is a listing with your new service and the various formats that it supports.

ServiceStack_7

 

The Metadata page contains:

  • A list of all your webservices and the endpoints they are available on.
  • A list of coding examples showing you how to call each endpoint a number of different ways.
  • Links to all the XSD types used by your web services
  • Links to the web services SOAP 1.1 / 1.2 WSDLs

 

Click on one of those metadata links like the one for JSON and you should see a nice quick description of how to interact with the service.

ServiceStack_8

This is awesome! Now go make a call to the service: /authenticate. If you are calling a GET method (which is not provided in this sample) you get a nice default HTML view of the data, very handy for a quick look at your output. ServiceStack relies on HTTP header information to determine the right content type. Your browser wants HTML so ServiceStack complies. You can easily override this, try /authenticate?format=json .

Calling Web Services from Fiddler

If we are calling a GET method then we can directly use browser, but in case of POST, PUT or DELETE operations we can use tools like fiddler

In the above example, in order to call authenticate operation, we need to send AuthenticateRequest information to service

From the service metadata we can get a complete description about the request and response structures. For example for JSON request, we can see the sample request and response as mentioned below

ServiceStack_9

 

Type the URL, request body and request content under composer tab and click on execute button

ServiceStack_10

 

 

 

ServiceStack_11

 

ServiceStack_12

 

If you would like to invoke this operation from a desktop client, write the following code to do so

 var client = new JsonServiceClient(url);
 var request = new AuthenticationRequest() 
               {
                SystemId = "EGIS", 
                UserName = "Designer",
                AuthenticationType = AuthenticationType.Basic
              };
 var authenticationResponse = client.Post(request);

 return authenticationResponse.Message;

Now that you’ve got the feel of how easy it is to create a simple web service, experiment and  see how useful servicestack becomes with just a little db code.

 

Thanks & Regards,

Kishore Borra