Archive

Posts Tagged ‘WCF Web API’

Good-bye WCF Web API…Hello ASP.NET Web API

March 5, 2012 1 comment

With the new beta release of ASP.NET MVC 4, the old WCF Web API has now been moved to ASP.NET. We are still able to use the Web API without any dependence on MVC. You can even self host your Web API to remove even the need for IIS.

I have written a series of posts that cover the WCF Web API asd it is the transportation mechanism that I have chosen for my ORM-less data access framework called, Gofer. I am in the process of porting Gofer over to the ASP.NET Web API and I will have a series of posts that will cover and show the differences between the old and the new. I will also be adding some more advanced posts on using Gofer and taking full advantage of the library.

Finally, with this release, I will be making Gofer open-sourced as well as continue to release it via NuGet and will have SpecFlow tests for you to see the library and how it works.

If you want to make sure you are ready, I recommend you download SpecFlow and NUnit so that you can play with the code.

There is a lot going on right now and plenty of “goodness” to use in your next project, so stay tuned!

Gofer – Silverlight

January 4, 2012 9 comments

In our last post, we used Gofer in a Console application and got data from a SQL Server database as well as creating the database from our domain model. Today, we are going to be doing the same thing but we will be doing this with Silverlight.

First, start by create a new Silverlight 5 application.

Make sure that you do NOT enable WCF RIA Services!

Next, we are going to setup of the web project first and then move over to the Silverlight project once we are done. Let’s start with getting Gofer from NuGet. Right-click on your References folder and select Manage NuGet Packages. Next, type in “Gofer” as your search criteria. Select Gofer.Sample as your choice. This package comes with the Gofer library as well as with some helper files to make testing this easier.

Gofer.Sample has a dependency on SwitchBlade and ValueInjecter.

SwitchBlade is another package that I wrote that allows you to host Razor templates outside of ASP.NET and IIS. I will be covering SwitchBlade in a future post.

ValueInjecter is a package like AutoMapper but much more convention-based and easier.

We are also going to need to use Ninject as our DI/IOC container. We will use NuGet to install this package as well:

Finally, we will need the WCF Web API from NuGet as well:

Moving on from adding all of our packages, you will also notice that you have two new template folders for your CRUD and DDL operations. You can modify these templates to shape how you want your SQL code to look when it is used by Gofer.

You will also notice two new files:

Domain.cs – This file represents a sample domain model. It is very similar to what you would see from a Northwind with some slight modifications.

TestDriver.cs – This file is a test driver class that allows us to test Gofer. We will be using a Silverlight version of this file instead. DELETE this file from the project as we do not need it.

Next, let’s add a Global.asax file to the project and modify as shown below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Web.Routing;
using Microsoft.ApplicationServer.Http;
using Ninject;
using Domain;
using Gofer;

namespace GoferSilverlight.Web
{
    public class Global : System.Web.HttpApplication
    {
        public const string NAMESPACE = "Domain";
        public Func<Type,bool> PREDICATE = x => x.Namespace == NAMESPACE;

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.SetDefaultHttpConfiguration(new WebApiConfiguration()
            {
                CreateInstance = (serviceType, context, request) => CreateInstance(serviceType),
                EnableTestClient = true
            });

            RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(PREDICATE);
        }

        private object CreateInstance(Type serviceType)
        {
            object result = null;
            IKernel kernel = new StandardKernel();
            try
            {
                // The following is a sample entry for using the MapServiceRoute method:
                // RouteTable.Routes.MapServiceRoute<GoferService<Customers>>("Customer");
                // Hence the reason we need to pull the generic type from the GoferService.
                var genericType = serviceType.GetGenericArguments().FirstOrDefault();
                SchemaRules rules = GetRules(genericType);
                kernel.Bind(serviceType).ToSelf().WithConstructorArgument("rules", rules);
                result = kernel.Get(serviceType);
            }
            catch { }

            return result;
        }

        #region Rules

        private SchemaRules GetRules(Type type)
        {
            var result = new SchemaRules();
            result.AssemblyOf(type)
                .ShouldMap(PREDICATE)
                .GetSchema();

            result.PerformMigration = true;
            result.ForceNewMigration = false;

            return result;
        }

        #endregion

    };
}

UPDATE: I added a Fun<Type,bool> predicate so you could easily add your own logic for both the “RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(PREDICATE)” and the .ShouldMap(PREDICATE) calls.

If you are curious as to what is going on here, please refer to my post Building a Generic Service using WCF Web API – Part II as it walks you through all of these steps.

One thing to point out here is that we are using the same SchemaRules class.

SchemaRules – This tells the Gofer engine what conventions to use for its data access. There is a ton that you can override with this class and we will take a look at that in a later post but this is the bare minimum that you need to get going. Also, you will see two properties that tell the engine whether or not to perform a migration as well as force the migration, meaning that it will drop the database and recreate it if necessary.

There is one last change that you need to put in place before we can test our service. We will need to modify the Web.config. The following is a sample Web.config that you can pattern against for yourself:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="DB_NAME" value="Example" />

    <add key="DDL_ConnectionString" value="Provider=SQLOLEDB;Server=(local);Database=master;Integrated Security=SSPI;" />
    <add key="DDL_DatabaseType" value="4" />

    <add key="ConnectionString" value="Data Source=(local);Initial Catalog=Example;Integrated Security=SSPI;" />
    <add key="DatabaseType" value="3" />

    <add key="TemplatePath" value="C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\CRUD_Templates" />
    <add key="DDL_TemplatePath" value="C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\DDL_Templates" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

If we run the application, you will see a blank screen but we can still test our service:

I am using the database that I tested with the previous post. Therefore, I knew I had at least one record in the Customers table. Based on the results of the service, I can see that I am getting back a good JSON response.

Ok, our service is ready, now let’s shift gears and see what we must do to test this on the Silverlight side.

We want to share our domain for both the client and server. Right-click your Silverlight project and select “Add | Existing Item…”. Navigate to the web project and select the Domain.cs file and click the down arrow to “Add As Link”. This will give us the domain model definition in our Silverlight project.

Next, let’s add our Gofer.Silverlight package from NuGet. Right-click on the References folder and select Manage NuGet Packages. Next, type in “Gofer” as your search criteria. Select Gofer.Silverlight as your choice.

Gofer.Silverlight has a dependency on Async CTP and HTTP Contrib which are provided as part of the install.

Async CTP is a library that helps make asynchronous programming easier.

Http Contrib is a library that helps make calling the WCF Web API easier from clients such as Silverlight.

You will also notice that a “readme.txt” file added to the project. If you open the file, you will see the you need to add the following code snippet to the constructor of your App.xaml.cs file:

HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

I wrote a blog post here when I ran into some strange issues trying to test my services for PUT and DELETE behaviors.

Okay, let’s add the following TestDriver.cs class to the Silverlight project:

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Gofer.DataAccess;
using Domain;

namespace GoferSilverlight
{
    public class TestDriver
    {
        public void Run()
        {
            var repo = new SilverlightRepository("Customers");
            var cust = new Customers()
            {
                CompanyName = "Bubba's Repair",
                ContactName = "Billy Bob",
                ContactTitle = "Owner",
                Address = "100 Pecan Street",
                City = "Columbia",
                PostalCode = "29661",
                Country = "USA",
                Phone = "(803) 836-1212",
                Fax = "(803) 836-1213"
            };
            repo.Create<Customers>(cust,
                (item) =>
                {
                    if (item == null)
                    {
                        // Handle data here....
                    }
                },
                (error) =>
                {
                    if (error == null)
                    {
                        // Handle error here....
                    }
                }
            );            
        }
    };
}

As you can see, this is very similar to what we used in the Console application but all calls are asynchronous and I also wanted to have a unique callback for success and errors. If the database did not exist, you could run this just like the Console code and a new database would be created as long as you had the PerformMigration property set to “true” in your Global.asax.cs file.

The final step to get this to work is to add the following code to the constructor of your MainPage.xaml.cs file:

TestDriver td = new TestDriver();
td.Run();

If you add a couple breakpoints as shown below, you should be ready to run the application:

When the debugger hits your breakpoint, you should see something similar to the following:

That’s it! This may seem like a lot of moving pieces to get this working but once you get in the groove, you will see that this is so much easier than dealing with proxies and hidden code generated files from Visual Studio. I personally really like this approach and I look forward to getting your response as well.

In the next couple of posts, I will be digging deeper into to Gofer as a whole to show you everything that you can do.

Gofer – Console

January 3, 2012 1 comment

By now, I am sure that you are tired of reading and just want to play with whatever I have been talking about. Well, that is exactly what we are doing to do.

First, start by creating a new Console Application. Next we are going to access my libraries using NuGet. Right-click on your References folder and select Manage NuGet Packages. Next, type in “Gofer” as your search criteria. Select Gofer.Sample as your choice. This package comes with the Gofer library as well as with some helper files to make testing this easier.

Gofer.Sample has a dependency on SwitchBlade and ValueInjecter.

SwitchBlade is another package that I wrote that allows you to host Razor templates outside of ASP.NET and IIS. I will be covering SwitchBlade in a future post.

ValueInjecter is a package like AutoMapper but much more convention-based and easier.

You will also notice that you have two new template folders for your CRUD and DDL operations. You can modify these templates to shape how you want your SQL code to look when it is used by Gofer.

You will also notice two new files:

Domain.cs – This file represents a sample domain model. It is very similar to what you would see from a Northwind with some slight modifications.

TestDriver.cs – This file is a test driver class that allows us to test Gofer.

In your Program.cs file, add the following code snippet to your Main method:

TestDriver td = new TestDriver();
td.Run();

Here is what the TestDriver class looks like:

public class TestDriver
{
    public void Run()
    {
        SchemaRules rules = new SchemaRules();
        rules.AssemblyOf<Customers>()
            .ShouldMap(x => x.Namespace == "Domain")
            .GetSchema();

        rules.PerformMigration = true;
        rules.ForceNewMigration = true;

        var repo = new Repository<Customers>(rules);
        var cust = new Customers() {
                CompanyName = "Bubba's Repair",
                ContactName = "Billy Bob",
                ContactTitle = "Owner",
                Address = "100 Pecan Street",
                City = "Columbia",
                PostalCode = "29661",
                Country = "USA",
                Phone = "(803) 836-1212",
                Fax = "(803) 836-1213"
        };
        var id = repo.Insert(cust);
        var ds = repo.Get().ToList();

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
};

As you can see, we are using two main classes from Gofer: SchemaRules and Repository.

SchemaRules – This tells the Gofer engine what conventions to use for its data access. There is a ton that you can override with this class and we will take a look at that in a later post but this is the bare minimum that you need to get going. Also, you will see two properties that tell the engine whether or not to perform a migration as well as force the migration, meaning that it will drop the database and recreate it if necessary.

Repository – This is our data access class that facilitates getting data from the Gofer engine.

There is one last change that you need to put in place before you continue. The package will have also provided you with an App.config that you will need to complete. The following is a sample App.config that you can pattern against for yourself:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="DB_NAME" value="Example" />

    <add key="DDL_ConnectionString" value="Provider=SQLOLEDB;Server=(local);Database=master;Integrated Security=SSPI;" />
    <add key="DDL_DatabaseType" value="4" />

    <add key="ConnectionString" value="Data Source=(local);Initial Catalog=Example;Integrated Security=SSPI;" />
    <add key="DatabaseType" value="3" />

    <add key="TemplatePath" value="C:\Users\Matt\Documents\Visual Studio 2010\Projects\GoferConsole\GoferConsole\CRUD_Templates" />
    <add key="DDL_TemplatePath" value="C:\Users\Matt\Documents\Visual Studio 2010\Projects\GoferConsole\GoferConsole\DDL_Templates" />
  </appSettings>
</configuration>

I used the name “Example” for the name of the database we will be using for data access. There are two connection strings since we will have one for our data access as well as one for our creation statements. You will see two different DatabaseType values you can leave for now. We will go into how you can go against any back-end system in a future post. Finally, there are two paths for the CRUD and DDL templates. Make sure that you update the paths to the directory where these folders are located on your machine.

If you run your application and you left PerformMigration to true, Gofer will create the database for you. It will then try and insert a new record and the pull all records from the Customers table.

NOTE: I did need to change my project type from the Client Profile to the full .NET 4 Framework.

Here is one last tidbit, if you put a break point after your insert statement, you can access a SqlTrace property on the Repository instance. This will show you what was executed and any error messages coming back from SQL Server. This is really helpful especially when you are migrating changes over to the database. Gofer does this automatically when you have the PerformMigration property set to true.

In my next post, I will be basically doing the same thing but using Gofer over the web for Silverlight without any need for a proxy! My main goal for Gofer is simplicity and allowing us to get back to focusing on our business rules and domain models. Gofer has a lot of extensibility and we will be going into this in future posts as well.

If you start playing with this, remember that it is the tip of the iceberg and I will be going into more depth on multiple levels. Hope you like…

Introducing Gofer – Getting Back to Basics

January 2, 2012 Leave a comment

One of the key driving forces for using Gofer is to allow developers to focus on business requirements and not worry about infrastructure and ceremony. The other motivating factor is to remove the overhead of maintenance and coding that is required to keep our domain models in sync with our database model or vice versus.

Let’s build a list of requirements that a good solid data access layer should provide:

  1. Easy to use API without the need for Attributes or custom coding in our domain model. We shouldn’t need to provide navigation properties or make our properties virtual just to get the data access to work.
  2. Convention-based rules implementation to provide the 80/20 rule of getting things right and allowing the developer to override the rules at the domain object/property level.
  3. Provide the ability to customize the SQL generation via templates. This will allow for each development shop to ensure that the SQL generated meets their coding standards.
  4. Allow the developer to shape their data requests in a compile-time friendly manner. This should be supported in the following areas:
    • Filtering options – we want to be able to use lambda expressions to allow us to filter our objects at pretty much any level of our object graph.
    • Load options – this allows the developer to use lambda expressions to define what objects they wish to eager load regardless of what level in the object graph.
    • Order options – this allows the developers to use lambda expressions to define in what order they wish to have their objects hydrated. This is very powerful in that we can order sub-collections all in a single request.
  5. Flexible coding strategy that supports both 2-tier and n-tier development. This means that we can use pretty much the same model to access data regardless if we are developing a Silverlight application or a WPF application.
  6. Ability to provide synchronization between the domain model and the data model. Should be able to provide a schema comparison and allow the developer to decide what to do. This means that we can do silent migrations or generate a SQL file for execution at a later time. You should also be able to force a migration whenever a data access operation is performed per the developer’s digression.
  7. Ability to trace to a log or console the SQL that get generated during runtime.

These are the ideal requirements that I have for my data access layer. I am sure many of you already see this answered in Entity Framework Code First or Fluent NHibernate but I wanted both an ORM and a transport mechanism in one. I also don’t want to deal with proxy classes when making requests over the web. That is why my solution uses HTTP Service APIs.

In the next post we will take a look at Gofer using a Console application.

Building a generic serivce using WCF Web API – Part IV

December 21, 2011 1 comment

So now that we have covered building our service and testing it with Test Client. Let’s now get started and see what it takes to actually build a Silverlight client. The WCF Web API does not have code to directly support Silverlight but luckily there is another project on CodePlex that does just that. There is a fork here that has the source code that you will need to get this to work. Also, we will be using the Async CTP to help make developing in Silverlight a little bit easier.

Okay, so let’s see what is required to create a Silverlight project. The web portion for hosting the service is complete and we can use it as it is with our Silverlight project.

In the Silverlight project, I added references to the Async CTP and the HttpContrib libraries.

Next I update my App.xaml.cs to look as follows:

public App()
{
	this.Startup += this.Application_Startup;
	this.Exit += this.Application_Exit;
	this.UnhandledException += this.Application_UnhandledException;

	InitializeComponent();

	HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
	HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
}

If you do not provide the last two lines of code, you will not be able to perform PUT or DELETE operations as Silverlight will default to use the browser’s network stack. You can read more about this in my blog post here.

Next, we create a link to the domain classes that was used for testing in my previous posts.

Finally, we will write the code to make a request to our generic service. I kept this example simple by simply providing code in the code-behind of the MainPage.xaml file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Domain;

namespace SilverlightTest
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            Get();
        }

        private void Get()
        {
            var repo = new SilverlightRepository("Customers");
            repo.Get<Customers>(
                (item) =>
                {
                    if (item == null)
                    {
						// do something.
                    }
                },
                (error) =>
                {
                    if (error == null)
                    {
						// display the error.
                    }
                }
            );
        }
    };
}

The main code to look at is the Get() method. In it we are using a new class, “SilverlightRepository”. This class wraps up our usage of the HttpContrib libraries as well as the Async CTP. It exposes a method Get<> that takes in two Action<> delegates. If we are able to successfully get data, then the first delegate is fired. If an error is encountered, then the second delegate is fired. This gives us the flexibility to either bind our data or display/log the error message.

Let’s look at the SilverlightRepository class now:

namespace SilverlightTest
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using HttpContrib;
    using HttpContrib.Client;
    using HttpContrib.Http;
    using System.Windows;
    using System.Text;

    public class SilverlightRepository
    {
        private string _uri;  // Example:  "http://localhost:18561/Customers";
        private string Uri
        {
            get { return _uri;}
            }

		#region ctor

        public SilverlightRepository(string service)
        {
            string hostName = Application.Current.Host.Source.Host;
            if (Application.Current.Host.Source.Port != 80)
            {
                hostName += ":" + Application.Current.Host.Source.Port;
            }
            _uri = "http://" + hostName + "/" + service;
        }

        #endregion

        public void Get<T>(Action<List<T>> completed,
            Action<string> onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri.ToString();

            SimpleHttpClient client = new SimpleHttpClient(uri);

            IHttpQueryProvider queryProvider = new HttpQueryProvider(client);

            var query = new HttpQuery<T>(queryProvider);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteAsync();

            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted && t.Result != null)
                    {
                        Debug.WriteLine("{0}: {1}", typeName, t.Result);
                        completed(t.Result.ToList());
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Create<T>(T item, 
            Action<T> completed,
            Action<string> onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery<T>();

            query.Create(item);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted && t.Result != null)
                    {
                        Debug.WriteLine("{0}: {1}", typeName, t.Result);
                        completed(t.Result);
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Update<T>(T item, 
            int id, 
            Action<T> completed,
            Action<string> onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery<T>().Update(id, item);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted && t.Result != null)
                    {
                        Debug.WriteLine("{0}: {1}", typeName, t.Result);

                        completed(item);
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Delete<T>(T item, 
            int id, 
            Action<T> completed,
            Action<string> onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery<T>().Delete(id);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =>
            {
                Execute.OnUIThread(() =>
                {
                    if (!t.IsFaulted && t.IsCompleted)
                    {
                        Debug.WriteLine("{0}: {1}", typeName, t.Result);
                        completed(t.Result);
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }

    #region Helper

        private string GetExceptionMessage(Exception ex)
        {
            string result = null;
            if (ex.InnerException != null)
            {
                result = GetExceptionMessage(ex.InnerException);
            }
            else
            {
                result = ex.Message;
            }
            return result;
        }

    #endregion
    
    };
}

Okay, as you can see we are expecting the name of the service to be passed into the constructor. With the service name we then construct the Uri. Note that the way we are constructing the Uri is friendly for both developing and testing your application and running in production.

Next, we simply call the Get<> method passing in the corresponding type. We then use the helper SimpleHttpClient class exposed by the HttpContrib libraries. This class really makes it easy for use to consume the service that has been exposed. We then create an IHttpQueryProvider instance by passing in the client object to the constructor of the HttpQueryProvider class. We let the IHttpQueryProvider create our full query for our request and then we use the Async CTP to execute the request asynchronously.

We use the ContinueWith method to allow the thread to continue but call a delegate once a response has been returned. One we have a response we make sure that we marshal our data to the UI thread.

Finally, we inspect the response object to ensure that is has not faulted and is completed with data. If we pass this condition, then we execute the Action<> delegate with the results.

If we encountered an error then we execute the error Action<> delegate with the error message.

If you look at the remaining code for the other verbs, you can see that we are following the same pattern. You will notice that with the Get<> method, we used the IHttpQueryProvider to create our query but all other verb requests can come directly from the SimpleHttpClient directly calling the CreateQuery(…) method.

You have also noticed that I have a GetExceptionMessage(…) helper method. When an exception occurs on the server, it get wrapped up with a generic exception object and message. This really does no good to the client and so I am simply pulling the InnerException property to get the real message from the server.

Now that we have covered the service and creating the client, I am sure you are curious how we are getting our data. That is next on our agenda as I will be introducing a set of libraries via NuGet that will provide this functionality for you as well as give you data access.

Building a generic service using WCF Web API – Part III

December 20, 2011 1 comment

Before we write our client applications, I wanted to first introduce you to the power of the Test Client that is provided out of the box when you use the WCF Web API. This is a powerful tool that lets you test your services without ever needing to use Fiddler or any custom browser tool. It allows you to test all of the verbs that you are exposing.

In order for this to work you must ensure a single property, “EnableTestClient”, is set to true in our Global.asax.cs file:

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.SetDefaultHttpConfiguration(new WebAPIConfiguration()
    {
        CreateInstance = (serviceType, context, request) => CreateInstance(serviceType), 
        EnableTestClient = true
    });

    RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(ACCOUNT);
    RouteTable.Routes.MapServiceRouteForAssemblyOf<rv_o_Organization>(EGOV);
}

Now, that we have turned on our ability to use the Test Client, let’s take a look and see what it can give us. Based on the previous posts that we have covered, we are going to access one of the service routes and see what the Test Client show us:

It is very easy to access the Test Client for any of your services by simply appending “/test” to your URL. On the top-left side of the screen, we see two resources. At the bottom-left side of the screen, you see the history off all the requests you have made.

At the center-top of the screen, we see a placeholder for the HTTP verb and the URL of the request. Below this, there is the option to define/view the headers for the request. Below the Headers, we see the Body and can select the format of the request.

Finally, we have the Send button below the Body and then we see the Response section.

If you click on the first item in the Resources list, we get the following screen shot:

As you can see, the default Request is going to be GET. You can also see that the URL for the request is also provided by default.

If we click in the textbox for the HTTP verbs and see what our other options are:

Based on the URI, we only get the verbs that are supported with each request. GET and POST are the only two verbs that are supported with this request.

We are going to change the Headers from “*/*” to “application/json”. This will ensure that the response will come back in JSON.

Now we can click on the Send button and see what the result looks like for a simple GET:

We get to see quite a bit of information once we get a response. We see the Request time, Response time, and Duration. We see the Response code, Headers, and finally the Body of the response. This is pretty nice and it allow us to perform a lot of testing of our service before write a single client.

We seen what happens when we perform a GET, now let’s try and add a new record by performing a POST.

First, we change the verb to POST. We can leave the headers as they are. We then select the format of the body to JSON. We then write in our JSON to represent a new record. Finally we hit Send and wait for the response. With this response, we received a code of 201/Created. The response header and body then return to us the newly created record from the server.

What about an Update or Delete operation? Well, we now need to select the next item on the Resources list. We can check to see what verbs are supported for this request by clicking in the textbox. As you can see, we can perform either a PUT or DELETE.

We will leave the verb as a PUT. We need to provide the primary key to the record is in the path of the URL. Next we change the format of the body to JSON and paste in what we used to create the record but we also include the Id of the record as well as make some modifications. Finally we hit Send and wait for our reponse. We get a Reponse code of 200 and we are echoed back the record in the body of the response.

Deleting a record is even easier. All we need to do is change the verb to DELETE and ensure that the primary key to the record is in the path of the URL. Next we hit Send and await our response. We get a Response code of 200 and we are returned the total number of records affected by the delete.

The Test Client feature of the WCF Web API makes developing and testing services very fast with very little hassle. I simply hit F5 on my solution and then navigate my browser to the corresponding service I want to test.

NOTE: Make sure that your JSON is in the correct format or it may never hit your breakpoint.

That’s it for now. We will cover creating Silverlight and Console test clients in the next post.

Building a generic service using WCF Web API – Part II

December 19, 2011 1 comment

Okay, so we now have our service definition in place. Let’s take a look and see what it takes to get this service exposed in our web project. The first place that we start is the Global.asax.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
using Microsoft.ApplicationServer.Http;
using Domain;
using Domain2;
using Ninject;
using Microsoft.ApplicationServer.Http.Activation;

namespace Gofer.Web
{
    public class Global : System.Web.HttpApplication
    {
        public const string ACCOUNT = "Domain";
        public const string EGOV = "Domain2";

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.SetDefaultHttpConfiguration(new WebApiConfiguration() 
                {
                    CreateInstance = (serviceType, context, request) => CreateInstance(serviceType),
                    EnableTestClient = true 
                });

            RouteTable.Routes.MapServiceRouteForAssemblyOf<Customers>(ACCOUNT);
            RouteTable.Routes.MapServiceRouteForAssemblyOf<rv_o_Organization>(EGOV);
        }

        private object CreateInstance(Type serviceType)
        {
            object result = null;
            IKernel kernel = new StandardKernel();
            try
            {
                // The following is a sample entry for using the MapServiceRoute method:
                // RouteTable.Routes.MapServiceRoute<GoferService<Customers>>("Customer");
                // Hence the reason we need to pull the generic type from the GoferService.
                var genericType = serviceType.GetGenericArguments().FirstOrDefault();
                DataAccessRules rules = null;
                switch (genericType.Namespace)
                {
                    case ACCOUNT:
                        rules = GetAccountAtAGlanceRules(genericType);
                        break;
                    case EGOV:
                        rules = GetEgovRules(genericType);
                        break;
                }

                kernel.Bind(serviceType).ToSelf().WithConstructorArgument("rules", rules);

                result = kernel.Get(serviceType);
            }
            catch { }

            return result;
        }

        #region Rules

        private DataAccessRules GetAccountAtAGlanceRules(Type type)
        {
            var result = new DataAccessRules();
            result.AssemblyOf(type)
                .SetConnectionStringKey("aag_ConnectionString")
                .ShouldMap(x => x.Namespace == "Domain");
            return result;
        }
        private DataAccessRules GetEgovRules(Type type)
        {
            var result = new DataAccessRules();
            result.AssemblyOf(type)
                .SetConnectionStringKey("emgov_ConnectionString")
                .ShouldMap(x => x.Namespace == "Domain2");
            return result;
        }

        #endregion
    };
}

Just like any of the other examples you have seen with the WCF Web API, we are using the Routes property off of the RouteTable and calling the SetDefaultHttpConfiguration. We are doing something a little special in that we are using a lambda expression to call the CreateInstance(…) method as well as passing in the service type. On the next two lines of code, we see that we are calling the MapServiceRouteForAssemblyOf<T>(…) generic extension method. It is the combination of the CreateInstance() method and the MapServiceRouteForAssemblyOf<T>(…) generic extension method that makes everything work correctly.

Let’s look at the CreateInstance() method first. In this method we are setting up our dependency injection (DI) container. I am using Ninject for this example but you could use MEF or Unity or whatever you wanted as well. Next I am interrogating the Type object that was passed in. I know by convention that the only service that I am going to be dealing with is the generic service we created in the last blog post. Because of that, I know that the type is a generic type and I know that it only has one generic argument. Based on the generic type information, I examine what the namespace is for the domain object. I then perform a simple switch statement and get the correct DataAccessRules object for the corresponding namespace. This gives me the flexibility to support multiple domain objects that represent different data models and not need to recompile or do any additions with the exception of the MapServiceRouteForAssemblyOf<T>(…) call.

Finally, I call the Bind method on the IKernel object and tell it to pass in the newly created DataAccessRules object as a constructor parameter. I then ask the kernel to resolve the service type that was originally passed into the method and return that new object.

So far, we have seen how we are setting up our DI container and injecting a DataAccessRules object into the constructor. What we haven’t seen yet is how we are getting data access for all of our domain objects. Let’s take a look at the individual methods that get us our DataAccessRules object and then we will turn our attention to how we handle this for all of our domain objects.

Our DataAccessRules objects are created by either the GetAccountAtAGlanceRules(…) method or the GetEgovRules(…) method. The thing to take into consideration here is we are telling the rules object what connection string to use from the web.config file as well as specifying the namespace that we only want to load our objects from.

Now let’s shift gears and take a look at the MapServiceRouteForAssemblyOf<T>(…) generic extension method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.ApplicationServer.Http;
using Microsoft.ApplicationServer.Http.Activation;
using Gofer.Web;

namespace System.Web.Routing
{
    public static class RouteCollectionExtension
    {
        public static void MapServiceRouteForAssemblyOf<T>(this RouteCollection routes,
            string domain,
            HttpConfiguration configuration = null,
            object constraints = null,
            bool useMethodPrefixForHttpMethod = true)
        {
            var type = typeof(T);
            var domainAssembly = System.Reflection.Assembly.GetAssembly(type);
            var types = domainAssembly.GetTypes().Where(x => x.Namespace == domain);

            foreach (var item in types)
            {
                string routePrefix = item.Name;
                Type gs = typeof(GoferService<>);
                Type constructed = gs.MakeGenericType(new Type[] { item });
                routes.MapServiceRoute(constructed, routePrefix, configuration, constraints,
                    useMethodPrefixForHttpMethod);
            }
        }
        public static void MapServiceRoute(this RouteCollection routes,
            Type serviceType,
            string routePrefix,
            HttpConfiguration configuration = null,
            object constraints = null,
            bool useMethodPrefixForHttpMethod = true)
        {
            if (configuration == null)
            {
                configuration = routes.GetDefaultHttpConfiguration();
            }

            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }

            var route = new WebApiRoute(routePrefix,
                new HttpServiceHostFactory() { Configuration = configuration }, serviceType);
            route.Constraints = new RouteValueDictionary(constraints);
            routes.Add(route);
        }
    };
}

Okay, so if we look at the first method, we see that we are accessing the assembly for which the type belongs. We then load only the objects that match the namespace that was passed into the method. Finally we loop through each type and construct the generic service that we created in our last post. With a single line entry that called the MapServiceRouteForAssemblyOf<T> we are able to map service routes for all of our objects. It is actually the second method that does the routing which is very easy to follow.

Let’s look at one last piece of the puzzle, the web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <appSettings>
    <add key="aag_ConnectionString" value="Data Source=(local);Initial Catalog=AccountsAtAGlance;Integrated Security=SSPI;" />
    <add key="emgov_ConnectionString" value="Data Source=(local);Initial Catalog=emgov_data;Integrated Security=SSPI;" />
  </appSettings>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>
</configuration>

As you can see, this is one of the reasons why I love the WCF Web API. There is nothing but the bare minimum required. I can now add as many connection strings as I want to the web.config and I only have to go to the Global.asax.cs file to make sure that it is wired in correctly.

In the next post, we will look at what the client side code looks like.

Categories: English Tags: , , ,