Archive

Posts Tagged ‘WCF’

.NET Uri, database not found, and encoding

I ran into an interesting issue when trying to debug some code a while back.  I had written a dynamic that would allow a person to authenticate and then pick a database in which to perform their operations.  For the most part, this system worked well and allowed me to keep things simple.  The part that was trick was that I had written my reporting and dashboard engine to use a single Razor .cshtml file to handle all requests.  It in turn pulled the report definition or dashboard definition XML files from the database.  The problem came when one of the SQL Server databases that the system was deployed was not the default instance but a “named instance“.

In my code, I would simply construct an Uri object and pass in the string that represented the parameters that I needed for the given page.  However, since a named instance uses the ‘\‘ character, this caused some problems as my simple string representation was not encoding the character and thus when the server received the request it was not a valid server name.  I spent hours thinking that it was a problem with the configuration with SQL Server.  It wasn’t until I debugged the .cshtml file that I realized that the name of the server was not coming across correctly and that I was not encoding the name properly.  Here is what I finally came up with to correct the issue:

string address = string.Format("../PreviewReturnSetupBillDesigner.cshtml?
Key={0}&ServerName={1}&DatabaseName={2}",
  101,
  HttpUtility.UrlEncode("monticello\test"),
  HttpUtility.UrlEncode("sample"));

Uri uri = new Uri(address, UriKind.RelativeOrAbsolute);

Previously, I was just passing in the server and database names without encoding them. This worked for all default installations of SQL Server but once you had a named instance in place, all bets were off.

Hopefully this will help anyone from spinning their wheels if they are doing anything similar…

Microsoft Silverlight 5 Data and Services Cookbook

I wanted to continue on reviewing books related to Silverlight 5 and development.  Microsoft Silverlight 5 Data and Services Cookbook states that it has over 100 practical recipes for creating rich, data-driven, business applications in Silverlight 5.  As with my last review, I will go over each chapter and add any gut reactions towards the content it provides.

The book is broken down into 13 chapters as well as an appendix.  On the whole, the book has a lot of content to absorb.  It is broken down into a collection of tips and tricks and common scenarios for using Silverlight in building line of business applications.  I like the concept and idea behind the approach to this book but I find that a lot of corners were cut in getting the book out the door.  I wish that the book had a better quality of code snippets as well as accompanying images as the code samples lack syntax highlighting of any sort and the images are very poor in quality.

Chapter 1 is all about learning the nuts and bolts of Silverlight 5.  This chapter is necessary if you have never written a Silverlight application and need to understand what is required in order to get started using Visual Studio 2010.

Chapter 2 jumps right into covering Data Binding.  This is also a core concept to any XAML technology and I like that they cover it soon so as to get you exposed to the whole data binding programming paradigm.  You are exposed to the classical non-data binding approach and then launch into the concept of a DataContext and how the data binding mechanism works.  We exposed how to create bindings both in XAML as well as in code which is sometimes necessary.  Binding to other elements, and collections is also discussed.  Next, is introduced the interface, INotifyPropertyChanged.  This is by far one of the most important aspects of XAML programming as it facilitates two-way data binding.  We finally come to one of the first instances of a new feature of Silverlight 5, debugging data binding expression.  This is one of the coolest features of Silverlight 5 and makes developing in Silverlight 5 a joy.

Chapter 3 takes our knowledge that we learned from data binding and goes into some advanced topics.  Namely, we are presented with converters, data templates, validating.  Converters are required in most line of business applications as your data binding alone will not satisfy all of your business logic and requirements.  We are also presented TargetNullValue, StringFormat, and FallbackValue as alternatives for using converters.  Another important part of any line of business application is validating user input.  We are presented with NotifyOnValidationError and ValidatesOnExceptions.  In the UI, we are introduced the ValidationSummary control that will automatically receive any BindingValidationError events.  This is nice in that we can present all errors in one concerted location and effort back to the user.  Data Annotations are presented as a means for providing validation rules on your domain objects.  INotifyDataErrorInfo and IDataErrorInfo interfaces are introduced to show how you can validate user input without throwing exceptions.  We finally move away from validation and review data templates.  This is an important concept with any XAML technology and we find good examples of usage here.  With Silverlight 5, we get the ability to use implicit templates and this is covered as well.  For scenarios where we need to binding something different than our current element in the visual tree, we are presented with Ancestor RelativeSource binding now available in Silverlight 5.  Another powerful feature of Silverlight 5 is the ability to create custom markup extensions.  Finally, as with INotifyPropertyChanged works on a single object, we are presented with the INotifyCollectionChanged interface for dealing with change aware collections.

Chapter 4 is completed dedicated to the Data Grid.  The one aspect that I was curious about was how they demonstrated binding combo boxes to the a column in the data grid.  The sample was very primitive and would not be something you would really be able to use in most data driven scenarios.  I am hoping that as we move to MVVM, we will see better scenarios on this.

Chapter 5 is about Isolated Storage.  This chapter does a good job on covering Isolated Storage and the limitations of Silverlight applications and their security sandbox.  I also liked that they also showed how you could use the Sterling database.

Chapter 6 covers MVVM.  The chapters covers the basics of MVVM as well as introducing MVVM Light and MEF as tools to use with MVVM.  I would have like an introduction on Prism and Caliburn.Micro as well as these are two important frameworks and libraries.  With Caliburn.Micro, they could have provided a nice introduction to architecting rich user interfaces without explicit data binding in your XAML.

Chapter 7 covers services.  Most all line of business applications will require data and since you cannot create a direct connection to the database in Silveright, you will need to access a service.  You presented with services such as ASMX, WCF, REST, and RSS.  I also liked that they also had a section on socket communication in Silverlight as well.  The one complaint I have is that I wished they would have also introduced SignalR as section as this is gaining a lot of popularity in the .NET community.

Chapter 8 takes what we were introduced in the previous chapter and focuses strictly on WCF and ASMX services.  We are exposed with using services that expose data, using Bing as a service.  We get presented with performance tuning by using binary XML.  We also cover a personal favorite of mine, the infamous, “Server Not Found” exception and how to provide more information to the Silverlight client.  Integrating with ASP.NET Authentication is also covered.  Finally, we are presented with uploading files using WCF.

Chapter 9 takes us one step further in our discovery with ASMX and WCF.  Mainly, we cover duplex communication, data encryption, message-based security, using Windows Identity Foundation and, finally, using a ChannelFactory with Silverlight.  Most of these sections are very high level and don’t go any further than a quick sample.  It at least points you in the right direction for further investigation.

Chapter 10 talks about using REST and WCF Data Services.  With REST we cover both XML and JSON formats.  Another sections discusses the limitations to the Silverlight browser stack.  We are then presented with the ClientHttp stack and how we can use the common REST verbs.  Next, we are presented with using WCF Data Services.  We also get presented with Flickr and Twitter and how to use their REST services.

Chapter 11 is dedicated to presenting WCF RIA Services.  While I am not a big fan of WCF RIA Services this chapter does a good job at showing you what you can do with WCF RIA Services.  It walks you through using the class library, getting your data, using a LoadBehavior, server-side queries, sorting, filtering, paging, and finally persisting your data and dealing with transactions and concurrency.

Chapter 12 continues on the WCF RIA Services and shows us some advanced features.  We are shown how to get a user’s identity either by Windows authentication or a custom means.  Next, we are presented with using Windows Identity Foundation and WCF RIA Services.    We then move from authentication to authorization in our services.  We also review how WCF RIA Services supports data annotations and validating user input.  Finally, we are presented with exposing our data via OData endpoints as well as SOAP or a JSON/REST endpoint.

Chapter 13 introduces Windows Phone 7.  This chapter walks you through the WP7 architecture from a developer’s perspective and then concentrates on getting data to the device.  A lot of the same patterns presented in the previous chapters are applicable.  Using push notifications with the cloud is demonstrated.  Local storage using a SQL CE database is presented.  Finally, a sample on using background transfer service is covered for uploading and downloading files in the background.

Appendix.  The appendix walks you through how to find any of the dependencies mentioned in the book.

If you are looking for a book that covers a lot of scenarios in Silverlight concerning data and services than this seems like a good reference for you to have.  At times, I feel that the samples were overly verbose and cluttered but I believe this is more to be the fault of poor publishing.  It would have been nice to have a better rendering of the code snippets and a better quality of the sample images throughout the book.  All in all, I found the book to be a good reference and it will definitely go in my toolbox as a go to book when I am working on a particular scenario.

Mastering LOB Development for Silverlight 5: A Case Study in Action

May 11, 2012 1 comment

I recently picked up a copy of the Mastering LOB Development for Silverlight 5: A Case Study in Action and started going through the book.

If you have never done any development in Silverlight and would like a practical pragmatic example of how to setup your solutions in Visual Studio as well as get exposed to the different frameworks that are available, then this is an excellent choice! The book is broken up into eleven chapters and it starts from introducing you to the basics of developing in XAML and quickly builds upon this knowledge to lead you into understanding windows and controls.

Chapter 3 is about data binding but it doesn’t stress the need for separation of concerns enough. I would have rather seen examples done the right way instead of the easy way. There were no advanced examples of attached properties or use of the System.Windows.Interactivity. The title of this book implies that we will be covering Silverlight 5 but I don’t see a single mention of debugging data bindings which is brand new to Silverlight 5 nor is there any hint of ancestor relative binding, implicit data templates, custom markup extensions, etc.

Chapter 4 is on Architecture but it too is lacking in being truly comprehensive. There is no sign of Prism 4.0 nor is there any mention to Caliburn.Micro. Both of the frameworks are very powerful and more mature than either of the frameworks mentioned in the book. Although both MVVM Light Toolkit is a good tool but MEF is more of a tool for DI/IOC and not a full fledged framework that can handle messaging like event aggregation that the other frameworks provide. Another sad aspect is that there is no mention of compartmentalizing your architecture to only download XAPs on demand. Most Silverlight frameworks support this out of the box.

Chapter 5 talks about data access. The chapter focuses on RIA Services but I find it very problematic that it does not cover any authorization or authentication. It does go into good detail about using RIA Services in conjunction with Entity Framework. However, I have spent way too much time fighting RIA Services to know that it is not appropriate for enterprise level development except for smaller line of business applications. The other common issue I have with this chapter is that it doesn’t address the common scenario of “Server Not Found“. This happens when RIA Services has an exception on the server and this will happen a lot. There are techniques to solve this and it is important for you as the developer to know this.

Chapter 6 discusses Out of Browser applications and this is for the most part has good coverage of the topic.

Chapter 7 is on Testing. This is a good chapter as well but it is unfortunate that it took us until this chapter to get a mention of DI/IOC. Dependency injection and inversion of control is just as important in your architecture and design as it is in your testing projects. I wish they would have covered some of the behavior driven development libraries that are available to you such as SpecFlow. BDD really compliments and makes your development experience so much better.

Chapter 8 is on Error Control. It covers the basics but still doesn’t address how to deal with exceptions on the server.

Chapter 9 is on Integrating with other Web Applications. I personally don’t see this as an important chapter for a book on line of business applications. I would much rather have a consistent architecture and UI instead of dealing with mashups.

Chapter 10 is on Consuming Web Services. This chapter covers the basics but doesn’t go deep as learning WCF requires a book just for itself. I did like that they cover consuming a Twitter API and processing JSON.

Chapter 11 is on Security. It is here that we see our authentication and authorization for both RIA Service and WCF. We also look at what how to make cross domain calls.

This book is a great reference for building line of business applications. Although I believe that it is missing some fundamental topics in building a line of business application and is a little weak on the coverage for Silverlight 5, it is still a very good read and you will walk away armed with good knowledge for building line of business applications.

Hope the review helps…

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.

Raleigh Code Camp

November 2, 2011 Leave a comment

I will be presenting the following topic “Building a Windows Phone 7 App using JSON/ASP.NET MVC Data Service Layer” at the Raleigh Code Camp this weekend. We will take a look at leveraging ASP.NET MVC and JSON to become your best friend from the point of data serialization. Want to build a simple WP7 application? Want a simple way to pass data back and forth from the server? JSON seems to be the obvious choice when developing web applications, how does it work when developing WP7 applications? I am looking forward to it!

Categories: English Tags: , , , , ,