Archive

Archive for December, 2011

A Case for going ORM-less

December 22, 2011 6 comments

Problem Statement
I spend a lot of time architecting and designing software infrastructures to make the development of enterprise applications easy. For example, in Silverlight or WPF, I have spent a lot of time trying to make the development cycle for other developers easier so that they can focus primarily on business requirements and less on infrastructure and ceremony. Data access is an area within Microsoft technologies that, I believe, needs to be re-examined as a whole.

There once was a time when we had really nice products that allowed us to build business solutions without really needing to worry about the database. Microsoft Access, Microsoft Visual FoxPro, and DBase come to mind. In those days we didn’t need to worry about the model or the database and we just “developed” our applications. Granted these were the classical 2-tier architectures but boy you sure could develop software quickly. I still have clients today that launched their businesses off of products like these.

Unfortunately, we have gone to the other extreme of the pendulum and are being forced to use a new paradigm such as Object Relational Mapper (ORM) in conjunction with our regular development. Regardless of what technology you use, this has become extremely painful especially when developing for Silverlight.

If you have worked in Silverlight or any other environment where you are forced to make service calls asynchronously, you quickly realize just what a pain it is to solve the data access problem. Regardless whether you use WCF RIA Services, WCF Data Services, or roll your own WCF service, you still have a lot of work and maintenance ahead of you. When you think of all the service operations you need to expose, it can become a very time-consuming task to maintain.

Let’s look at the layers involved in building a Silverlight application and what it takes to save data over the wire. Consider the following diagram:

Because we are dealing with a distributed architecture, I wanted to show you what is required both on the server and on the client.

Server
As you can see we have our database layer. This is just a simple representation of where your data is being stored. For most corporate applications, this means a relational database like that of Microsoft SQL Server.

Since we are focusing on Microsoft technologies, we are going to come face to face with Entity Framework. Entity Framework is a database agnostic ORM that allows us to manage our relationships in several ways.

  • Database First – we build the database model first and then reverse engineer the database to build out the entities.
  • Model First – we build the entity model using the Entity Framework designer. This creates our entities and database as we go.
  • Code First – we create the object model first and provide some hooks to synchronize creating the database.

I am going to discuss the Database First approach here. This assumes that you already have your database created and ready for you to use. Next you create an Entity Framework model. Creating the EDMX file is pretty easy and you are presented with the designer surface that represents your models.

If we were building a Windows Presentation Foundation (WPF), Windows Forms, ASP.NET Web Forms, or ASP.NET MVC application, we would be okay going this far and stopping since our code-behind for our views or viewmodels could, in theory, have a reference to the Entity Framework ObjectContext and start manipulating data from there. However, this is not the case for Silverlight or any client that must make service requests over the wire. With Silverlight, we add more salt to our wounds since it does not use the same binaries as does the rest of WPF and Web development and thus we can’t share a common entity library.

In order for us to use the Entity Framework, we need to use something like WCF RIA Services, WCF Data Services, or expose our own WCF services. We will use the standard WCF RIA Services example. You do this by adding a new Domain Service class to your project. This has to be done after you have completed creating your Entity Framework model and compiled your web project at least once.

In order for us to get access to our data in Silverlight, we need to have the ability to send and receive requests over the web. WCF RIA Services does this by allowing us to create a Domain Service on the server and creating a hidden set of files on the client that exposes the proxy as to how we communicate with the service.

Client
Now let’s look at what happens on the right side of the diagram. In the hidden folder that Visual Studio generates, we now have access to a Domain Context that allows us to communicate with the server. We then usually wrap the models that are exposed by the generated code in our own classes. Typically this is done by using ViewModels but we could use Controllers or any other paradigm. Finally, we use data-binding in our XAML to finish the job of getting our data to our end-users.

Done! You may think this is great but this is a huge problem for any shop that does a lot of agile development and is constantly changing the backend data model. These changes have a ripple effect which forces us to try and keep our Entity Framework model in sync with the data model. You then must drop your WCF RIA Services objects that were created and re-create them. Because WCF RIA Services generates code into a hidden folder on the client, it is very hard for you to just modify one entity and only generate the change for that one item. It is has been the case that you have to drop the Domain Service and metadata file and re-generate.

Analysis
Can you feel my pain yet? Even with Code First, there is no way to avoid the static proxy that is generated on the client to support communicating across the web. Wouldn’t it be nice if we could just get rid of all of these added tools and headaches and go back to how we developed software in the past? If you look at all the different ORMs tools out there on the market, you are either forced to develop your code in a certain way such as using “virtual” for your properties, how about being required to use navigation properties which are meaningless in our object-oriented architecture? We shouldn’t need all of this baggage just to have the ability to persist data back to a database.

SQL Profiling
If you have used NHibernate or EntityFramework, it is almost mandatory to profile what these ORMs are producing as SQL. It is unfortunate that the SQL code that gets generated is so horribly ugly. This is yet another area where we have gone the wrong direction and are allowing tools to dictate how our code should look and run instead of allowing the developer to define these rules.

How do we proceed?
In the next coming posts, I am going to be discussing a solution that is really based on what we had before. A going back to the basics, if you will. I will be presenting to you a library that will allow you to develop code the way you want but still have the ability to do data access the way you want it.

Although I am not a big fan of ORMs, I believe that I would categorize what I will be presenting as a micro-ORM. This approach will be very much convention over configuration based with a fluent application programming interface (API) to allow you to override the default conventions. You may think that this is basically Fluent NHibernate or Code First all over again but I will show you how this approach differs in its mechanism for providing a rich yet flexible data access. Another aspect that I will be presenting is that you will be the full author of the SQL that is used during data access. We will be using templates and you can use them out of the box or you can customize them to meet your coding style and requirements in your company.

Closing
If you have read my posts on the WCF Web API, I am using this as the backbone for my data transport. Without the flexibility and power of the WCF Web API, I would be just presenting another static solutions but I am able to provide a rich generic model here that allows you to do very little scaffolding to get access to your data.

In the next post, I will introduce the solution I came up with to solve the issues I find with the current way we write data driven applications, especially in Silverlight.

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: , , ,

Building a generic service using WCF Web API

December 19, 2011 1 comment

Now that we have taken a look at the new WCF Web API let’s see what it takes to build a generic service that will work for both Silverlight and web requests. In this example we are going to basically mock our database so that we can focus completely on the service itself. In a later post I will go over what it takes to support this generic service with a generic data access layer.

As of this post, Preview 6 is available from the WCF Web API.

Okay, let’s look at what we have for our generic service below:

namespace Gofer.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ServiceModel.Web;
    using System.ServiceModel;
    using System.Net.Http;
    using System.Json;
    using System.Net;
    using Microsoft.ApplicationServer.Http.Dispatcher;

    [ServiceContract]
    public class GoferService<T> where T : class, new()
    {
        #region Member Variables

        private DataAccessRules _rules;
        public DataAccessRules Rules
        {
            get { return _rules; }
            set { _rules = value; }
        }

        #endregion

        #region ctor

        public GoferService(DataAccessRules rules)
        {
            _rules = rules;
        }

        #endregion

        #region Web Methods

        #region Get

        [WebGet(UriTemplate = "")]
        public HttpResponseMessage<List<T>> Get()
        {
            try
            {
                var repo = new Repository<T>(Rules);
                var result = repo.Get().ToList();
                var response = new HttpResponseMessage<List<T>>(result);
                return response;
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage();
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }
        }

        #endregion

        #region Insert

        [WebInvoke(UriTemplate = "", Method = "POST")]
        public HttpResponseMessage<T> Insert(T item)
        {
            var typeName = typeof(T).Name;
            if (item == null)
            {
                var error = new HttpResponseMessage(HttpStatusCode.NotFound);
                error.Content = new StringContent(string.Format("{0} not found!", 
					typeName));
                throw new HttpResponseException(error);
            }

            try
            {
                var schema = (from c in Rules.Schemas 
							  where c.ClassName == typeName 
							  select c).FirstOrDefault();
                var pkey = schema.GetPrimaryKey(schema.ClassName);
                var repo = new Repository<T>(Rules);
                int id = repo.Insert(item);
                ReflectionHelper.SetPropertyValue(item, pkey, id);
                var response = new HttpResponseMessage<T>(item);
                response.StatusCode = HttpStatusCode.Created;
                return response;
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage();
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }
        }

        #endregion

        #region Update

        [WebInvoke(UriTemplate = "{id}", Method = "PUT")]
        public HttpResponseMessage<T> Update(T item, int id)
        {
            var typeName = typeof(T).Name;
            if (item == null)
            {
                var error = new HttpResponseMessage(HttpStatusCode.NotFound);
                error.Content = new StringContent(string.Format("{0} not found!", 
					typeName));
                throw new HttpResponseException(error);
            }

            try
            {
                var repo = new Repository<T>(Rules);
                repo.Update(item);
                var response = new HttpResponseMessage<T>(item);
                response.StatusCode = HttpStatusCode.Ok;
                return response;
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage();
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }
        }

        #endregion

        #region Delete

        [WebInvoke(UriTemplate = "{id}", Method = "DELETE")]
        public HttpResponseMessage<int> Delete(int id)
        {
            try
            {
                var repo = new Repository<T>(Rules);
                return repo.Delete(id);
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage();
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }
        }

        #endregion

        #endregion
    };
}

NOTE: I have simplified this service a bit to show you how to build your own generic service.

The first thing to note with this service is the ServiceContract attribute. As of Preview 6, this is no longer required but I included it for demonstration purposes. As you can see from the contructor, I am using dependency injection (DI) to provide an object called DataAccessRules. Basically, this object allows me to specify what connection string to use that is stored in the web.config file. This is important as I want to make sure that this service is fully generic and allows me to pull data from differing databases.

Next, we see the Get method. This method allows us to get our data. As of Preview 5, we don’t need to provide an empty string for the default UriTemplate but I decided to show it to you anyways. With the Get method, I am returning an HttpResponseMessage<List<T>> object. I have a Repository object that provides access to all my underlying data. I have the repository return me a list of items of type T and then create a new HttpResponseMessage passing in the List<T> to the constructor. By default the status code of the object set to Ok which is equivalent to 200. Finally, since this service must now be marshaled to the client, we want to be very careful that we handle any exceptions and wrap them up in objects that can be used by our clients. Out of the box, the WCF Web API plays very nice with browsers and you can see most of your exceptions without any extra work but it is when we are dealing with clients like Silverlight that we need to be more careful.

We can now look at what is required for inserting new records. This method uses a WebInvoke attribute compared to the WebGet that we saw in our get method. With the WebInvoke attribute we handle all other HTTP verbs that we want to use. For this request, we are going to handle a POST. This method returns an instance of an HttpResponseMessage<T> as well as takes in an instance of the generic type T. We pull the name of the type and put that in a variable. We test for a null input condition and throw the correct exception correspondingly. In our Rules object, we have some metadata that describes how to get the Primary Key for our object. This rule is in the format of a Expression<<Func<string,string>> and allows delayed evaluation. It isn’t until the GetPrimaryKey method is executed that the Expression<Func<string,string>> is evaluated. This is a handy trick as it allow us to define rules per object or namespace by passing in a lambda expression.

Once we have the name of the key, we then go ahead and use the Repository object and Insert a new record. What we do next is use some reflection to set the underlying object key property with the value returned by the Repository. Finally, we create an instance of an HttpResponseMessage<T> passing in the generic instance as well as setting the StatusCode to Created. We handle any exceptions in this method exactly the same.

The Update method basically operates the same. It uses a PUT operation. The Repository passes the generic object and performs the Update. The method returns an HttpResponseMessage<T> object once the operation successfully completes.

The final operation is the Delete. It uses a DELETE operation. The Repository passes the integer value and performs the Delete. The method returns an HttpResponseMessage<int> object once the operation successfully completes.

We now have our generic service defined. In the next post, we will look at what it takes to expose this service from a web project.

Categories: English Tags: ,

Introducing the WCF Web API

December 19, 2011 1 comment

Probably the biggest thing I like about the WCF Web API is that it is REST based. For me, this is very important because I don’t have to create a client proxy to use the service. I like this because it mitigates the amount of maintenance that I have to deal whenever I change the service or make modifications.

Moving over to the WCF Web API has been a natural migration for me. I deal with very large Silverlight applications that, typically, sit on top of WCF RIA Services. This is very painful because the amount of ceremony involved in keeping the solutions up-to-date whenever a model changes in the database.

With WCF Web API, because I don’t have to worry about a client-side proxy, I don’t care about the changes to the service. I still must be careful not to change my existing service calls that I make from the client but this can be controlled. Adding a new column to a table in my database no longers causes a ripple effect throughout my services that using WCF RIA Services would cause.

If you haven’t played with the WCF Web API, I strongly encourage you to take a look at it. It has some really awesome features as well as a great test platform to allow you to test your service all in one place.

By exposing my services using the WCF Web API, I can now consume them from any platform and any device and never need worry about a client proxy. This allows me to use the exact same service that I am using for Silverlight in a tablet based device or a mobile phone. This gives me a lot of flexibility by writing my service once and using it everywhere.

Over the next couple of posts, I am going to be going into greater detail concerning building a generic data access service using the WCF Web API.

You can read up on the WCF Web API documentation here.

Where are all the WPF LOB samples?

December 16, 2011 1 comment

Last night the question was asked at to where a developer could go to look at sample WPF line of business applications. Pete Brown has a blog post that allows you to download the “Book Of WPF” which I highly recommend. Also don’t forget that Visual Studio 2010, Expression Blend, and WebMatrix were also written in WPF.

Here are some other WPF applications that I thought you might like:

Billy Hollis’ famous Staffing application

TempWorks

An application that Marlon Grech been working on

Street Smart Edge

PowerPoint of Sample apps

Family.Show

Task.Show

TurboTax

Lawson Client

Comicster by Matt Hamilton

Halfwit by Matt Hamilton

Hope this helps…

Categories: English Tags: , , ,