<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Matt Duffield</title>
	<atom:link href="http://mattduffield.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://mattduffield.wordpress.com</link>
	<description>One developer to another...</description>
	<lastBuildDate>Wed, 15 Feb 2012 13:14:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='mattduffield.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Matt Duffield</title>
		<link>http://mattduffield.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://mattduffield.wordpress.com/osd.xml" title="Matt Duffield" />
	<atom:link rel='hub' href='http://mattduffield.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Silverlight 5: Building Rich Enterprise Dashboards</title>
		<link>http://mattduffield.wordpress.com/2012/02/15/silverlight-5-building-rich-enterprise-dashboards/</link>
		<comments>http://mattduffield.wordpress.com/2012/02/15/silverlight-5-building-rich-enterprise-dashboards/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 12:50:35 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Author]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[Dashboards]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=962</guid>
		<description><![CDATA[I am very happy to announce that the book that I co-authored has been published and is now available for purchase on Amazon! Here is a link to my publisher: PactPub Here is the link on Amazon: Amazon I have been busy these past several months but it has been worth it!<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=962&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I am very happy to announce that the book that I co-authored has been published and is now available for purchase on Amazon!</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/02/silverlight-dashboard.jpg"><img src="http://mattduffield.files.wordpress.com/2012/02/silverlight-dashboard.jpg?w=600" alt="" title="Silverlight Dashboard"   class="alignnone size-full wp-image-963" /></a></p>
<p>Here is a link to my publisher:</p>
<p><a href="http://www.packtpub.com/microsoft-silverlight-5-for-enterprise-dashboards/book">PactPub</a></p>
<p>Here is the link on Amazon:</p>
<p><a href="http://www.amazon.com/gp/product/1849682348/ref=s9_simh_gw_p14_d4_g14_i1?pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_s=center-2&amp;pf_rd_r=06B59W1QWGMJGMGGCT5A&amp;pf_rd_t=101&amp;pf_rd_p=470938631&amp;pf_rd_i=507846">Amazon</a></p>
<p>I have been busy these past several months but it has been worth it!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/962/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/962/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/962/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=962&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2012/02/15/silverlight-5-building-rich-enterprise-dashboards/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/02/silverlight-dashboard.jpg" medium="image">
			<media:title type="html">Silverlight Dashboard</media:title>
		</media:content>
	</item>
		<item>
		<title>Gofer &#8211; Silverlight</title>
		<link>http://mattduffield.wordpress.com/2012/01/04/gofer-silverlight/</link>
		<comments>http://mattduffield.wordpress.com/2012/01/04/gofer-silverlight/#comments</comments>
		<pubDate>Wed, 04 Jan 2012 03:11:59 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Code First]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[Gofer]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[HTTP Service]]></category>
		<category><![CDATA[HTTP Service API]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Razor]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SwitchBlade]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=938</guid>
		<description><![CDATA[In our last post, we used Gofer in a Console application and got data from a SQL Server database as well as creating the database from our domain model. Today, we are going to be doing the same thing but we will be doing this with Silverlight. First, start by create a new Silverlight 5 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=938&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In our last <a href="http://wp.me/pRaLl-eO">post</a>, we used <em>Gofer</em> in a Console application and got data from a <em>SQL Server</em> database as well as creating the database from our domain model.  Today, we are going to be doing the same thing but we will be doing this with <em>Silverlight</em>.</p>
<p>First, start by create a new <em>Silverlight 5</em> application.  </p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-new-silverlight-application.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-new-silverlight-application.png?w=600" alt="" title="GoferSilverlight - New Silverlight Application"   class="alignnone size-full wp-image-939" /></a></p>
<p>Make sure that you do NOT enable <em>WCF RIA Services</em>!</p>
<p>Next, we are going to setup of the web project first and then move over to the <em>Silverlight</em> project once we are done.  Let&#8217;s start with getting <em>Gofer</em> from <em>NuGet</em>.  Right-click on your <em>References</em> folder and select <strong>Manage NuGet Packages</strong>.  Next, type in &#8220;Gofer&#8221; as your search criteria.  Select <strong>Gofer.Sample</strong> as your choice.  This package comes with the <em>Gofer</em> library as well as with some helper files to make testing this easier.</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-nuget-package.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-nuget-package.png?w=600&#038;h=337" alt="" title="GoferSilverlight - NuGet Package" width="600" height="337" class="alignnone size-full wp-image-940" /></a></p>
<p><em>Gofer.Sample</em> has a dependency on <em>SwitchBlade</em> and <em>ValueInjecter</em>.</p>
<p><em>SwitchBlade</em> is another package that I wrote that allows you to host <em>Razor</em> templates outside of <em>ASP.NET</em> and <em>IIS</em>.  I will be covering <em>SwitchBlade</em> in a future post.  </p>
<p><em>ValueInjecter</em> is a package like <em>AutoMapper</em> but much more convention-based and easier.</p>
<p>We are also going to need to use <em>Ninject</em> as our DI/IOC container.  We will use <em>NuGet</em> to install this package as well:</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-ninject-nuget-package.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-ninject-nuget-package.png?w=600&#038;h=337" alt="" title="GoferSilverlight - Ninject NuGet Package" width="600" height="337" class="alignnone size-full wp-image-943" /></a></p>
<p>Finally, we will need the <em>WCF Web API</em> from <em>NuGet</em> as well:</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-web-api-nuget-package.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-web-api-nuget-package.png?w=600&#038;h=337" alt="" title="GoferSilverlight - Web API NuGet Package" width="600" height="337" class="alignnone size-full wp-image-944" /></a></p>
<p>Moving on from adding all of our packages, you will also notice that you have two new template folders for your <em>CRUD</em> and <em>DDL</em> operations.  You can modify these templates to shape how you want your SQL code to look when it is used by <em>Gofer</em>.</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-solution-explorer.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-solution-explorer.png?w=600" alt="" title="GoferSilverlight - Solution Explorer"   class="alignnone size-full wp-image-945" /></a></p>
<p>You will also notice two new files:</p>
<p><em>Domain.cs</em> &#8211; This file represents a sample domain model.  It is very similar to what you would see from a Northwind with some slight modifications.</p>
<p><em>TestDriver.cs</em> &#8211; This file is a test driver class that allows us to test <em>Gofer</em>.  We will be using a Silverlight version of this file instead.  DELETE this file from the project as we do not need it.</p>
<p>Next, let&#8217;s add a <em>Global.asax</em> file to the project and modify as shown below:</p>
<p><pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using System.Web.Routing;
using Microsoft.ApplicationServer.Http;
using Ninject;
using Domain;
using Gofer;

namespace GoferSilverlight.Web
{
    public class Global : System.Web.HttpApplication
    {
        public const string NAMESPACE = &quot;Domain&quot;;
        public Func&lt;Type,bool&gt; PREDICATE = x =&gt; x.Namespace == NAMESPACE;

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.SetDefaultHttpConfiguration(new WebApiConfiguration()
            {
                CreateInstance = (serviceType, context, request) =&gt; CreateInstance(serviceType),
                EnableTestClient = true
            });

            RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;Customers&gt;(PREDICATE);
        }

        private object CreateInstance(Type serviceType)
        {
            object result = null;
            IKernel kernel = new StandardKernel();
            try
            {
                // The following is a sample entry for using the MapServiceRoute method:
                // RouteTable.Routes.MapServiceRoute&lt;GoferService&lt;Customers&gt;&gt;(&quot;Customer&quot;);
                // Hence the reason we need to pull the generic type from the GoferService.
                var genericType = serviceType.GetGenericArguments().FirstOrDefault();
                SchemaRules rules = GetRules(genericType);
                kernel.Bind(serviceType).ToSelf().WithConstructorArgument(&quot;rules&quot;, rules);
                result = kernel.Get(serviceType);
            }
            catch { }

            return result;
        }

        #region Rules

        private SchemaRules GetRules(Type type)
        {
            var result = new SchemaRules();
            result.AssemblyOf(type)
                .ShouldMap(PREDICATE)
                .GetSchema();

            result.PerformMigration = true;
            result.ForceNewMigration = false;

            return result;
        }

        #endregion

    };
}
</pre></p>
<p><strong>UPDATE</strong>:  I added a Fun&lt;Type,bool&gt; predicate so you could easily add your own logic for both the &#8220;RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;Customers&gt;(PREDICATE)&#8221; and the .ShouldMap(PREDICATE) calls.</p>
<p>If you are curious as to what is going on here, please refer to my post <a href="http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api-part-ii/">Building a Generic Service using WCF Web API &#8211; Part II</a> as it walks you through all of these steps.</p>
<p>One thing to point out here is that we are using the same <em>SchemaRules</em> class.</p>
<p><em>SchemaRules</em> &#8211; This tells the <em>Gofer</em> engine what conventions to use for its data access.  There is a ton that you can override with this class and we will take a look at that in a later post but this is the bare minimum that you need to get going.  Also, you will see two properties that tell the engine whether or not to perform a migration as well as force the migration, meaning that it will drop the database and recreate it if necessary.</p>
<p>There is one last change that you need to put in place before we can test our service.  We will need to modify the <em>Web.config</em>.  The following is a sample <em>Web.config</em> that you can pattern against for yourself:</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;DB_NAME&quot; value=&quot;Example&quot; /&gt;

    &lt;add key=&quot;DDL_ConnectionString&quot; value=&quot;Provider=SQLOLEDB;Server=(local);Database=master;Integrated Security=SSPI;&quot; /&gt;
    &lt;add key=&quot;DDL_DatabaseType&quot; value=&quot;4&quot; /&gt;

    &lt;add key=&quot;ConnectionString&quot; value=&quot;Data Source=(local);Initial Catalog=Example;Integrated Security=SSPI;&quot; /&gt;
    &lt;add key=&quot;DatabaseType&quot; value=&quot;3&quot; /&gt;

    &lt;add key=&quot;TemplatePath&quot; value=&quot;C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\CRUD_Templates&quot; /&gt;
    &lt;add key=&quot;DDL_TemplatePath&quot; value=&quot;C:\Users\Matt\Documents\visual studio 2010\Projects\GoferSilverlight\GoferSilverlight.Web\DDL_Templates&quot; /&gt;
  &lt;/appSettings&gt;

  &lt;system.web&gt;
    &lt;compilation debug=&quot;true&quot; targetFramework=&quot;4.0&quot; /&gt;
  &lt;/system.web&gt;
  &lt;system.serviceModel&gt;
    &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot; /&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre></p>
<p>If we run the application, you will see a blank screen but we can still test our service:</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/goferconsole-service-test.png"><img src="http://mattduffield.files.wordpress.com/2012/01/goferconsole-service-test.png?w=600&#038;h=476" alt="" title="GoferConsole - Service Test" width="600" height="476" class="alignnone size-full wp-image-948" /></a></p>
<p>I am using the database that I tested with the previous post.  Therefore, I knew I had at least one record in the <em>Customers</em> table.  Based on the results of the service, I can see that I am getting back a good <em>JSON</em> response.</p>
<p>Ok, our service is ready, now let&#8217;s shift gears and see what we must do to test this on the <em>Silverlight</em> side.</p>
<p>We want to share our domain for both the client and server.  Right-click your <em>Silverlight</em> project and select &#8220;Add | Existing Item&#8230;&#8221;.  Navigate to the web project and select the <em>Domain.cs</em> file and click the down arrow to &#8220;Add As Link&#8221;.  This will give us the domain model definition in our <em>Silverlight</em> project.</p>
<p>Next, let&#8217;s add our <em>Gofer.Silverlight</em> package from <em>NuGet</em>.  Right-click on the <em>References</em> folder and select <strong>Manage NuGet Packages</strong>.  Next, type in &#8220;Gofer&#8221; as your search criteria.  Select <em>Gofer.Silverlight</em> as your choice.</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-gofer-silverlight-nuget-package.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-gofer-silverlight-nuget-package.png?w=600&#038;h=337" alt="" title="GoferSilverlight - Gofer.Silverlight NuGet Package" width="600" height="337" class="alignnone size-full wp-image-949" /></a></p>
<p>Gofer.Silverlight has a dependency on Async CTP and HTTP Contrib which are provided as part of the install.</p>
<p><em>Async CTP</em> is a library that helps make asynchronous programming easier. </p>
<p><em>Http Contrib</em> is a library that helps make calling the <em>WCF Web API</em> easier from clients such as <em>Silverlight</em>.  </p>
<p>You will also notice that a &#8220;readme.txt&#8221; file added to the project.  If you open the file, you will see the you need to add the following code snippet to the constructor of your <em>App.xaml.cs</em> file:</p>
<p><pre class="brush: csharp;">
HttpWebRequest.RegisterPrefix(&quot;http://&quot;, WebRequestCreator.ClientHttp);
HttpWebRequest.RegisterPrefix(&quot;https://&quot;, WebRequestCreator.ClientHttp);
</pre></p>
<p>I wrote a blog post <a href="http://wp.me/pRaLl-dc">here</a> when I ran into some strange issues trying to test my services for <em>PUT</em> and <em>DELETE</em> behaviors.</p>
<p>Okay, let&#8217;s add the following TestDriver.cs class to the Silverlight project: </p>
<p><pre class="brush: csharp;">
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Gofer.DataAccess;
using Domain;

namespace GoferSilverlight
{
    public class TestDriver
    {
        public void Run()
        {
            var repo = new SilverlightRepository(&quot;Customers&quot;);
            var cust = new Customers()
            {
                CompanyName = &quot;Bubba's Repair&quot;,
                ContactName = &quot;Billy Bob&quot;,
                ContactTitle = &quot;Owner&quot;,
                Address = &quot;100 Pecan Street&quot;,
                City = &quot;Columbia&quot;,
                PostalCode = &quot;29661&quot;,
                Country = &quot;USA&quot;,
                Phone = &quot;(803) 836-1212&quot;,
                Fax = &quot;(803) 836-1213&quot;
            };
            repo.Create&lt;Customers&gt;(cust,
                (item) =&gt;
                {
                    if (item == null)
                    {
                        // Handle data here....
                    }
                },
                (error) =&gt;
                {
                    if (error == null)
                    {
                        // Handle error here....
                    }
                }
            );            
        }
    };
}
</pre></p>
<p>As you can see, this is very similar to what we used in the Console application but all calls are asynchronous and I also wanted to have a unique callback for success and errors.  If the database did not exist, you could run this just like the Console code and a new database would be created as long as you had the <em>PerformMigration</em> property set to &#8220;true&#8221; in your <em>Global.asax.cs</em> file.</p>
<p>The final step to get this to work is to add the following code to the constructor of your MainPage.xaml.cs file:</p>
<p><pre class="brush: csharp;">
TestDriver td = new TestDriver();
td.Run();
</pre></p>
<p>If you add a couple breakpoints as shown below, you should be ready to run the application:</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging.png?w=600" alt="" title="GoferSilverlight - Debugging"   class="alignnone size-full wp-image-951" /></a></p>
<p>When the debugger hits your breakpoint, you should see something similar to the following:</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging-results.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging-results.png?w=600" alt="" title="GoferSilverlight - Debugging results"   class="alignnone size-full wp-image-952" /></a></p>
<p>That&#8217;s it!  This may seem like a lot of moving pieces to get this working but once you get in the groove, you will see that this is so much easier than dealing with proxies and hidden code generated files from <em>Visual Studio</em>.  I personally really like this approach and I look forward to getting your response as well.</p>
<p>In the next couple of posts, I will be digging deeper into to <em>Gofer</em> as a whole to show you everything that you can do.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/938/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/938/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/938/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=938&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2012/01/04/gofer-silverlight/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-new-silverlight-application.png" medium="image">
			<media:title type="html">GoferSilverlight - New Silverlight Application</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-nuget-package.png" medium="image">
			<media:title type="html">GoferSilverlight - NuGet Package</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-ninject-nuget-package.png" medium="image">
			<media:title type="html">GoferSilverlight - Ninject NuGet Package</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-web-api-nuget-package.png" medium="image">
			<media:title type="html">GoferSilverlight - Web API NuGet Package</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-solution-explorer.png" medium="image">
			<media:title type="html">GoferSilverlight - Solution Explorer</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/goferconsole-service-test.png" medium="image">
			<media:title type="html">GoferConsole - Service Test</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-gofer-silverlight-nuget-package.png" medium="image">
			<media:title type="html">GoferSilverlight - Gofer.Silverlight NuGet Package</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging.png" medium="image">
			<media:title type="html">GoferSilverlight - Debugging</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofersilverlight-debugging-results.png" medium="image">
			<media:title type="html">GoferSilverlight - Debugging results</media:title>
		</media:content>
	</item>
		<item>
		<title>Gofer &#8211; Console</title>
		<link>http://mattduffield.wordpress.com/2012/01/03/gofer-console/</link>
		<comments>http://mattduffield.wordpress.com/2012/01/03/gofer-console/#comments</comments>
		<pubDate>Tue, 03 Jan 2012 00:30:30 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Code First]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[Gofer]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[HTTP Service]]></category>
		<category><![CDATA[HTTP Service API]]></category>
		<category><![CDATA[IIS]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Razor]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[SwitchBlade]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=918</guid>
		<description><![CDATA[By now, I am sure that you are tired of reading and just want to play with whatever I have been talking about. Well, that is exactly what we are doing to do. First, start by creating a new Console Application. Next we are going to access my libraries using NuGet. Right-click on your References [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=918&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>By now, I am sure that you are tired of reading and just want to play with whatever I have been talking about.  Well, that is exactly what we are doing to do.</p>
<p>First, start by creating a new <em>Console Application</em>.  Next we are going to access my libraries using <em>NuGet</em>.  Right-click on your <em>References</em> folder and select <strong>Manage NuGet Packages</strong>.  Next, type in &#8220;Gofer&#8221; as your search criteria.  Select <strong>Gofer.Sample</strong> as your choice.  This package comes with the Gofer library as well as with some helper files to make testing this easier.</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/gofer-packages.png"><img src="http://mattduffield.files.wordpress.com/2012/01/gofer-packages.png?w=600&#038;h=336" alt="" title="Gofer Packages" width="600" height="336" class="alignnone size-full wp-image-925" /></a></p>
<p><em>Gofer.Sample</em> has a dependency on <em>SwitchBlade</em> and <em>ValueInjecter</em>.  </p>
<p><em>SwitchBlade</em> is another package that I wrote that allows you to host <em>Razor</em> templates outside of <em>ASP.NET</em> and <em>IIS</em>.  I will be covering <em>SwitchBlade</em> in a future post.  </p>
<p><em>ValueInjecter</em> is a package like <em>AutoMapper</em> but much more convention-based and easier.</p>
<p>You will also notice that you have two new template folders for your <em>CRUD</em> and <em>DDL</em> operations.  You can modify these templates to shape how you want your SQL code to look when it is used by <em>Gofer</em>.</p>
<p><a href="http://mattduffield.files.wordpress.com/2012/01/goferconsole-solution-explorer.png"><img src="http://mattduffield.files.wordpress.com/2012/01/goferconsole-solution-explorer.png?w=600" alt="" title="GoferConsole - Solution Explorer"   class="alignnone size-full wp-image-929" /></a>  </p>
<p>You will also notice two new files:</p>
<p><em>Domain.cs</em> &#8211; This file represents a sample domain model.  It is very similar to what you would see from a Northwind with some slight modifications.</p>
<p><em>TestDriver.cs</em> &#8211; This file is a test driver class that allows us to test <em>Gofer</em>.</p>
<p>In your <em>Program.cs</em> file, add the following code snippet to your <em>Main</em> method:</p>
<p><pre class="brush: csharp;">
TestDriver td = new TestDriver();
td.Run();
</pre></p>
<p>Here is what the <em>TestDriver</em> class looks like:</p>
<p><pre class="brush: csharp;">
public class TestDriver
{
    public void Run()
    {
        SchemaRules rules = new SchemaRules();
        rules.AssemblyOf&lt;Customers&gt;()
            .ShouldMap(x =&gt; x.Namespace == &quot;Domain&quot;)
            .GetSchema();

        rules.PerformMigration = true;
        rules.ForceNewMigration = true;

        var repo = new Repository&lt;Customers&gt;(rules);
        var cust = new Customers() {
                CompanyName = &quot;Bubba's Repair&quot;,
                ContactName = &quot;Billy Bob&quot;,
                ContactTitle = &quot;Owner&quot;,
                Address = &quot;100 Pecan Street&quot;,
                City = &quot;Columbia&quot;,
                PostalCode = &quot;29661&quot;,
                Country = &quot;USA&quot;,
                Phone = &quot;(803) 836-1212&quot;,
                Fax = &quot;(803) 836-1213&quot;
        };
        var id = repo.Insert(cust);
        var ds = repo.Get().ToList();

        Console.WriteLine(&quot;Press any key to exit...&quot;);
        Console.ReadKey();
    }
};
</pre></p>
<p>As you can see, we are using two main classes from <em>Gofer</em>:  <em>SchemaRules</em> and <em>Repository</em>.</p>
<p><em>SchemaRules</em> &#8211; This tells the <em>Gofer</em> engine what conventions to use for its data access.  There is a ton that you can override with this class and we will take a look at that in a later post but this is the bare minimum that you need to get going.  Also, you will see two properties that tell the engine whether or not to perform a migration as well as force the migration, meaning that it will drop the database and recreate it if necessary.</p>
<p><em>Repository</em> &#8211; This is our data access class that facilitates getting data from the Gofer engine.</p>
<p>There is one last change that you need to put in place before you continue.  The package will have also provided you with an <em>App.config</em> that you will need to complete.  The following is a sample <em>App.config</em> that you can pattern against for yourself:</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;DB_NAME&quot; value=&quot;Example&quot; /&gt;

    &lt;add key=&quot;DDL_ConnectionString&quot; value=&quot;Provider=SQLOLEDB;Server=(local);Database=master;Integrated Security=SSPI;&quot; /&gt;
    &lt;add key=&quot;DDL_DatabaseType&quot; value=&quot;4&quot; /&gt;

    &lt;add key=&quot;ConnectionString&quot; value=&quot;Data Source=(local);Initial Catalog=Example;Integrated Security=SSPI;&quot; /&gt;
    &lt;add key=&quot;DatabaseType&quot; value=&quot;3&quot; /&gt;

    &lt;add key=&quot;TemplatePath&quot; value=&quot;C:\Users\Matt\Documents\Visual Studio 2010\Projects\GoferConsole\GoferConsole\CRUD_Templates&quot; /&gt;
    &lt;add key=&quot;DDL_TemplatePath&quot; value=&quot;C:\Users\Matt\Documents\Visual Studio 2010\Projects\GoferConsole\GoferConsole\DDL_Templates&quot; /&gt;
  &lt;/appSettings&gt;
&lt;/configuration&gt;
</pre></p>
<p>I used the name &#8220;Example&#8221; for the name of the database we will be using for data access.  There are two connection strings since we will have one for our data access as well as one for our creation statements.  You will see two different <em>DatabaseType</em> values you can leave for now.  We will go into how you can go against any back-end system in a future post.  Finally, there are two paths for the <em>CRUD</em> and <em>DDL</em> templates.  Make sure that you update the paths to the directory where these folders are located on your machine.</p>
<p>If you run your application and you left <em>PerformMigration</em> to true, <em>Gofer</em> will create the database for you.  It will then try and insert a new record and the pull all records from the Customers table.</p>
<p><strong>NOTE</strong>:  I did need to change my project type from the <em>Client Profile</em> to the full <em>.NET 4 Framework</em>.</p>
<p>Here is one last tidbit, if you put a break point after your insert statement, you can access a <em>SqlTrace</em> property on the <em>Repository</em> instance.  This will show you what was executed and any error messages coming back from <em>SQL Server</em>.  This is really helpful especially when you are migrating changes over to the database.  <em>Gofer</em> does this automatically when you have the <em>PerformMigration</em> property set to true.</p>
<p>In my next post, I will be basically doing the same thing but using <em>Gofer</em> over the web for <em>Silverlight</em> without any need for a proxy!  My main goal for <em>Gofer</em> is simplicity and allowing us to get back to focusing on our business rules and domain models.  Gofer has a lot of extensibility and we will be going into this in future posts as well.</p>
<p>If you start playing with this, remember that it is the tip of the iceberg and I will be going into more depth on multiple levels.  Hope you like&#8230; </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/918/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/918/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/918/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=918&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2012/01/03/gofer-console/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/gofer-packages.png" medium="image">
			<media:title type="html">Gofer Packages</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2012/01/goferconsole-solution-explorer.png" medium="image">
			<media:title type="html">GoferConsole - Solution Explorer</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing Gofer &#8211; Getting Back to Basics</title>
		<link>http://mattduffield.wordpress.com/2012/01/02/introducing-gofer-getting-back-to-basics/</link>
		<comments>http://mattduffield.wordpress.com/2012/01/02/introducing-gofer-getting-back-to-basics/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 23:00:27 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Code First]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Fluent NHibernate]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[HTTP Service]]></category>
		<category><![CDATA[HTTP Service API]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[WCF Web API]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=912</guid>
		<description><![CDATA[One of the key driving forces for using Gofer is to allow developers to focus on business requirements and not worry about infrastructure and ceremony. The other motivating factor is to remove the overhead of maintenance and coding that is required to keep our domain models in sync with our database model or vice versus. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=912&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the key driving forces for using Gofer is to allow developers to focus on business requirements and not worry about infrastructure and ceremony. The other motivating factor is to remove the overhead of maintenance and coding that is required to keep our domain models in sync with our database model or vice versus.</p>
<p>Let’s build a list of requirements that a good solid data access layer should provide:</p>
<ol>
<li>Easy to use API without the need for Attributes or custom coding in our domain model. We shouldn’t need to provide navigation properties or make our properties virtual just to get the data access to work.</li>
<li>Convention-based rules implementation to provide the 80/20 rule of getting things right and allowing the developer to override the rules at the domain object/property level.</li>
<li>Provide the ability to customize the SQL generation via templates. This will allow for each development shop to ensure that the SQL generated meets their coding standards.</li>
<li>Allow the developer to shape their data requests in a compile-time friendly manner. This should be supported in the following areas:
<ul>
<li>Filtering options – we want to be able to use lambda expressions to allow us to filter our objects at pretty much any level of our object graph.</li>
<li>Load options – this allows the developer to use lambda expressions to define what objects they wish to eager load regardless of what level in the object graph.</li>
<li>Order options – this allows the developers to use lambda expressions to define in what order they wish to have their objects hydrated. This is very powerful in that we can order sub-collections all in a single request.</li>
</ul>
</li>
<li>Flexible coding strategy that supports both 2-tier and n-tier development. This means that we can use pretty much the same model to access data regardless if we are developing a Silverlight application or a WPF application.</li>
<li>Ability to provide synchronization between the domain model and the data model. Should be able to provide a schema comparison and allow the developer to decide what to do. This means that we can do silent migrations or generate a SQL file for execution at a later time. You should also be able to force a migration whenever a data access operation is performed per the developer’s digression.</li>
<li>Ability to trace to a log or console the SQL that get generated during runtime.</li>
</ol>
<p>These are the ideal requirements that I have for my data access layer. I am sure many of you already see this answered in Entity Framework Code First or Fluent NHibernate but I wanted both an ORM and a transport mechanism in one. I also don&#8217;t want to deal with proxy classes when making requests over the web. That is why my solution uses HTTP Service APIs.</p>
<p>In the next post we will take a look at Gofer using a Console application.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/912/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/912/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/912/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=912&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2012/01/02/introducing-gofer-getting-back-to-basics/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>
	</item>
		<item>
		<title>A Case for going ORM-less</title>
		<link>http://mattduffield.wordpress.com/2011/12/22/a-case-for-going-orm-less/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/22/a-case-for-going-orm-less/#comments</comments>
		<pubDate>Thu, 22 Dec 2011 17:43:48 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Code First]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF Data Services]]></category>
		<category><![CDATA[WCF RIA Services]]></category>
		<category><![CDATA[Windows Forms]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=902</guid>
		<description><![CDATA[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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=902&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><strong>Problem Statement</strong><br />
I spend a lot of time architecting and designing software infrastructures to make the development of enterprise applications easy.  For example, in <em>Silverlight</em> or <em>WPF</em>, 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 <em>Microsoft</em> technologies that, I believe, needs to be re-examined as a whole.</p>
<p>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.  <em>Microsoft Access</em>, <em>Microsoft Visual FoxPro</em>, and <em>DBase</em> 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.  </p>
<p>Unfortunately, we have gone to the other extreme of the pendulum and are being forced to use a new paradigm such as <em>Object Relational Mapper</em> (ORM) in conjunction with our regular development.  Regardless of what technology you use, this has become extremely painful especially when developing for <em>Silverlight</em>.</p>
<p>If you have worked in <em>Silverlight</em> 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 <em>WCF RIA Services</em>, <em>WCF Data Services</em>, or roll your own <em>WCF</em> 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.</p>
<p>Let’s look at the layers involved in building a <em>Silverlight</em> application and what it takes to save data over the wire.  Consider the following diagram:</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/data-access-over-the-web.png"><img src="http://mattduffield.files.wordpress.com/2011/12/data-access-over-the-web.png?w=600&#038;h=450" alt="" title="Data Access over the Web" width="600" height="450" class="alignnone size-full wp-image-901" /></a></p>
<p>Because we are dealing with a distributed architecture, I wanted to show you what is required both on the server and on the client.</p>
<p><strong>Server</strong><br />
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 <em>Microsoft SQL Server</em>.</p>
<p>Since we are focusing on <em>Microsoft</em> technologies, we are going to come face to face with <em>Entity Framework</em>.  <em>Entity Framework</em> is a database agnostic <em>ORM</em> that allows us to manage our relationships in several ways.  </p>
<ul>
<li><em>Database First</em> – we build the database model first and then reverse engineer the database to build out the entities.</li>
<li><em>Model First</em> – we build the entity model using the Entity Framework designer.  This creates our entities and database as we go.</li>
<li><em>Code First</em> – we create the object model first and provide some hooks to synchronize creating the database.</li>
</ul>
<p>I am going to discuss the <em>Database First</em> approach here.  This assumes that you already have your database created and ready for you to use.  Next you create an <em>Entity Framework</em> model.  Creating the <em>EDMX</em> file is pretty easy and you are presented with the designer surface that represents your models.  </p>
<p>If we were building a <em>Windows Presentation Foundation</em> (WPF), <em>Windows Forms</em>, <em>ASP.NET Web Forms</em>, or <em>ASP.NET MVC</em> 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 <em>Entity Framework ObjectContext</em> and start manipulating data from there.  However, this is not the case for <em>Silverlight</em> or any client that must make service requests over the wire.  With <em>Silverlight</em>, we add more salt to our wounds since it does not use the same binaries as does the rest of <em>WPF</em> and <em>Web</em> development and thus we can’t share a common entity library.</p>
<p>In order for us to use the <em>Entity Framework</em>, we need to use something like <em>WCF RIA Services</em>, <em>WCF Data Services</em>, or expose our own <em>WCF</em> services.  We will use the standard <em>WCF RIA Services</em> example.  You do this by adding a new <em>Domain Service</em> class to your project.  This has to be done after you have completed creating your <em>Entity Framework</em> model and compiled your web project at least once.  </p>
<p>In order for us to get access to our data in <em>Silverlight</em>, we need to have the ability to send and receive requests over the web.  <em>WCF RIA Services</em> does this by allowing us to create a <em>Domain Service</em> 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.</p>
<p><strong>Client</strong><br />
Now let’s look at what happens on the right side of the diagram.  In the hidden folder that <em>Visual Studio</em> generates, we now have access to a <em>Domain Context</em> 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 <em>ViewModel</em>s but we could use <em>Controller</em>s or any other  paradigm.  Finally, we use data-binding in our <em>XAML</em> to finish the job of getting our data to our end-users.</p>
<p>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 <em>Entity Framework</em> model in sync with the data model.  You then must drop your <em>WCF RIA Services</em> objects that were created and re-create them.  Because <em>WCF RIA Services</em> 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 <em>Domain Service</em> and metadata file and re-generate.</p>
<p><strong>Analysis</strong><br />
Can you feel my pain yet?  Even with <em>Code First</em>, 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 <em>ORM</em>s 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.  </p>
<p><strong>SQL Profiling</strong><br />
If you have used <em>NHibernate</em> or <em>EntityFramework</em>, it is almost mandatory to profile what these <em>ORM</em>s are producing as <em>SQL</em>.  It is unfortunate that the <em>SQL</em> 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.</p>
<p><strong>How do we proceed?</strong><br />
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.</p>
<p>Although I am not a big fan of <em>ORM</em>s, I believe that I would categorize what I will be presenting as a <em>micro-ORM</em>.  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 <em>Fluent NHibernate</em> or <em>Code First</em> 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 <em>SQL</em> 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.</p>
<p><strong>Closing</strong><br />
If you have read my posts on the <em>WCF Web API</em>, I am using this as the backbone for my data transport.  Without the flexibility and power of the <em>WCF Web API</em>, 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.</p>
<p>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 <em>Silverlight</em>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/902/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/902/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/902/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=902&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/22/a-case-for-going-orm-less/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/data-access-over-the-web.png" medium="image">
			<media:title type="html">Data Access over the Web</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a generic serivce using WCF Web API &#8211; Part IV</title>
		<link>http://mattduffield.wordpress.com/2011/12/21/building-a-generic-serivce-using-wcf-web-api-part-iv/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/21/building-a-generic-serivce-using-wcf-web-api-part-iv/#comments</comments>
		<pubDate>Wed, 21 Dec 2011 12:52:13 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Async CTP]]></category>
		<category><![CDATA[NuGet]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF Web API]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=887</guid>
		<description><![CDATA[So now that we have covered building our service and testing it with Test Client. Let&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=887&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>So now that we have covered building our service and testing it with <em>Test Client</em>.  Let&#8217;s now get started and see what it takes to actually build a <em>Silverlight</em> client.  The WCF Web API does not have code to directly support <em>Silverlight</em> but luckily there is another project on CodePlex that does just that.  There is a fork <a href="https://hg01.codeplex.com/forks/xamlcoder/wcfhttpcontrib">here</a> that has the source code that you will need to get this to work.  Also, we will be using the <a href="http://www.microsoft.com/download/en/details.aspx?id=9983">Async CTP</a> to help make developing in <em>Silverlight</em> a little bit easier.</p>
<p>Okay, so let&#8217;s see what is required to create a <em>Silverlight</em> project.  The web portion for hosting the service is complete and we can use it as it is with our <em>Silverlight</em> project.  </p>
<p>In the Silverlight project, I added references to the <em>Async CTP</em> and the <em>HttpContrib</em> libraries.  </p>
<p>Next I update my <em>App.xaml.cs</em> to look as follows:</p>
<p><pre class="brush: csharp;">
public App()
{
	this.Startup += this.Application_Startup;
	this.Exit += this.Application_Exit;
	this.UnhandledException += this.Application_UnhandledException;

	InitializeComponent();

	HttpWebRequest.RegisterPrefix(&quot;http://&quot;, WebRequestCreator.ClientHttp);
	HttpWebRequest.RegisterPrefix(&quot;https://&quot;, WebRequestCreator.ClientHttp);
}
</pre></p>
<p>If you do not provide the last two lines of code, you will not be able to perform <em>PUT</em> or <em>DELETE</em> operations as <em>Silverlight</em> will default to use the browser&#8217;s network stack.  You can read more about this in my blog post <a href="http://wp.me/pRaLl-dc">here</a>.</p>
<p>Next, we create a link to the domain classes that was used for testing in my previous posts.</p>
<p>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 <em>MainPage.xaml</em> file:</p>
<p><pre class="brush: csharp;">
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(&quot;Customers&quot;);
            repo.Get&lt;Customers&gt;(
                (item) =&gt;
                {
                    if (item == null)
                    {
						// do something.
                    }
                },
                (error) =&gt;
                {
                    if (error == null)
                    {
						// display the error.
                    }
                }
            );
        }
    };
}
</pre></p>
<p>The main code to look at is the <em>Get()</em> method.  In it we are using a new class, &#8220;SilverlightRepository&#8221;.  This class wraps up our usage of the <em>HttpContrib</em> libraries as well as the <em>Async CTP</em>.  It exposes a method <em>Get&lt;&gt;</em> that takes in two <em>Action&lt;&gt;</em> 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.</p>
<p>Let&#8217;s look at the <em>SilverlightRepository</em> class now:</p>
<p><pre class="brush: csharp;">
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:  &quot;http://localhost:18561/Customers&quot;;
        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 += &quot;:&quot; + Application.Current.Host.Source.Port;
            }
            _uri = &quot;http://&quot; + hostName + &quot;/&quot; + service;
        }

        #endregion

        public void Get&lt;T&gt;(Action&lt;List&lt;T&gt;&gt; completed,
            Action&lt;string&gt; 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&lt;T&gt;(queryProvider);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteAsync();

            task.ContinueWith(t =&gt;
            {
                Execute.OnUIThread(() =&gt;
                {
                    if (!t.IsFaulted &amp;&amp; t.IsCompleted &amp;&amp; t.Result != null)
                    {
                        Debug.WriteLine(&quot;{0}: {1}&quot;, typeName, t.Result);
                        completed(t.Result.ToList());
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Create&lt;T&gt;(T item, 
            Action&lt;T&gt; completed,
            Action&lt;string&gt; onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery&lt;T&gt;();

            query.Create(item);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =&gt;
            {
                Execute.OnUIThread(() =&gt;
                {
                    if (!t.IsFaulted &amp;&amp; t.IsCompleted &amp;&amp; t.Result != null)
                    {
                        Debug.WriteLine(&quot;{0}: {1}&quot;, typeName, t.Result);
                        completed(t.Result);
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Update&lt;T&gt;(T item, 
            int id, 
            Action&lt;T&gt; completed,
            Action&lt;string&gt; onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery&lt;T&gt;().Update(id, item);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =&gt;
            {
                Execute.OnUIThread(() =&gt;
                {
                    if (!t.IsFaulted &amp;&amp; t.IsCompleted &amp;&amp; t.Result != null)
                    {
                        Debug.WriteLine(&quot;{0}: {1}&quot;, typeName, t.Result);

                        completed(item);
                    }
                    else
                    {
                        string msg = GetExceptionMessage(t.Exception);
                        onError(msg);
                    }
                });
            });
        }
        public void Delete&lt;T&gt;(T item, 
            int id, 
            Action&lt;T&gt; completed,
            Action&lt;string&gt; onError) where T : class
        {
            string typeName = typeof(T).Name;
            string uri = Uri;
            SimpleHttpClient client = new SimpleHttpClient(uri);

            var query = client.CreateQuery&lt;T&gt;().Delete(id);

            string queryString = query.GetFullyQualifiedQuery(client).ToString();

            var task = query.ExecuteSingleAsync();

            task.ContinueWith(t =&gt;
            {
                Execute.OnUIThread(() =&gt;
                {
                    if (!t.IsFaulted &amp;&amp; t.IsCompleted)
                    {
                        Debug.WriteLine(&quot;{0}: {1}&quot;, 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
    
    };
}
</pre></p>
<p>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 <em>Uri</em>.  Note that the way we are constructing the <em>Uri</em> is friendly for both developing and testing your application and running in production.</p>
<p>Next, we simply call the <em>Get&lt;&gt;</em> method passing in the corresponding type.  We then use the helper <em>SimpleHttpClient</em> class exposed by the <em>HttpContrib</em> libraries.  This class really makes it easy for use to consume the service that has been exposed.  We then create an <em>IHttpQueryProvider</em> instance by passing in the client object to the constructor of the <em>HttpQueryProvider</em> class.  We let the <em>IHttpQueryProvider</em> create our full query for our request and then we use the <em>Async CTP</em> to execute the request asynchronously.</p>
<p>We use the <em>ContinueWith</em> 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 <em>UI</em> thread.  </p>
<p>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 <em>Action&lt;&gt;</em> delegate with the results.</p>
<p>If we encountered an error then we execute the error <em>Action&lt;&gt;</em> delegate with the error message.</p>
<p>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 <em>Get&lt;&gt;</em> method, we used the IHttpQueryProvider to create our query but all other verb requests can come directly from the <em>SimpleHttpClient</em> directly calling the <em>CreateQuery(&#8230;)</em> method.</p>
<p>You have also noticed that I have a <em>GetExceptionMessage(&#8230;)</em> 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 <em>InnerException</em> property to get the real message from the server.</p>
<p>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 <em>NuGet</em> that will provide this functionality for you as well as give you data access.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/887/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/887/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/887/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=887&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/21/building-a-generic-serivce-using-wcf-web-api-part-iv/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a generic service using WCF Web API – Part III</title>
		<link>http://mattduffield.wordpress.com/2011/12/20/building-a-generic-service-using-wcf-web-api-part-iii/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/20/building-a-generic-service-using-wcf-web-api-part-iii/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 18:41:17 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TestClient]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF Web API]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=872</guid>
		<description><![CDATA[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. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=872&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Before we write our client applications, I wanted to first introduce you to the power of the <em>Test Client</em> 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 <em>Fiddler</em> or any custom browser tool.  It allows you to test all of the verbs that you are exposing.</p>
<p>In order for this to work you must ensure a single property, &#8220;EnableTestClient&#8221;, is set to true in our <em>Global.asax.cs</em> file:</p>
<p><pre class="brush: csharp;">
protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.SetDefaultHttpConfiguration(new WebAPIConfiguration()
    {
        CreateInstance = (serviceType, context, request) =&gt; CreateInstance(serviceType), 
        EnableTestClient = true
    });

    RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;Customers&gt;(ACCOUNT);
    RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;rv_o_Organization&gt;(EGOV);
}
</pre></p>
<p>Now, that we have turned on our ability to use the <em>Test Client</em>, let&#8217;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 <em>Test Client</em> show us:</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client.png?w=600&#038;h=415" alt="" title="Test Client" width="600" height="415" class="alignnone size-full wp-image-881" /></a></p>
<p>It is very easy to access the <em>Test Client</em> for any of your services by simply appending &#8220;/test&#8221; 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.</p>
<p>At the center-top of the screen, we see a placeholder for the <em>HTTP</em> 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.</p>
<p>Finally, we have the Send button below the Body and then we see the Response section.</p>
<p>If you click on the first item in the Resources list, we get the following screen shot:</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-get.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-get.png?w=600&#038;h=414" alt="" title="Test Client - GET" width="600" height="414" class="alignnone size-full wp-image-877" /></a></p>
<p>As you can see, the default <em>Request</em> is going to be <em>GET</em>.  You can also see that the <em>URL</em> for the request is also provided by default.</p>
<p>If we click in the textbox for the <em>HTTP</em> verbs and see what our other options are:</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-get-or-post-verbs.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-get-or-post-verbs.png?w=600&#038;h=194" alt="" title="Test Client - GET or POST verbs" width="600" height="194" class="alignnone size-full wp-image-876" /></a></p>
<p>Based on the <em>URI</em>, we only get the verbs that are supported with each request.  <em>GET</em> and <em>POST</em> are the only two verbs that are supported with this request.</p>
<p>We are going to change the Headers from &#8220;*/*&#8221; to &#8220;application/json&#8221;.  This will ensure that the response will come back in <em>JSON</em>.</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-configure-headers.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-configure-headers.png?w=600&#038;h=216" alt="" title="Test Client - Configure Headers" width="600" height="216" class="alignnone size-full wp-image-873" /></a></p>
<p>Now we can click on the <em>Send</em> button and see what the result looks like for a simple <em>GET</em>:</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-getting-existing-records.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-getting-existing-records.png?w=600&#038;h=476" alt="" title="Test Client - Getting existing records" width="600" height="476" class="alignnone size-full wp-image-878" /></a></p>
<p>We get to see quite a bit of information once we get a response.  We see the <em>Request</em> time, <em>Response</em> time, and <em>Duration</em>.  We see the <em>Response code</em>, <em>Headers</em>, and finally the <em>Body</em> 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.</p>
<p>We seen what happens when we perform a <em>GET</em>, now let&#8217;s try and add a new record by performing a <em>POST</em>.</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-adding-a-new-record.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-adding-a-new-record.png?w=600&#038;h=445" alt="" title="Test Client - Adding a new record" width="600" height="445" class="alignnone size-full wp-image-882" /></a></p>
<p>First, we change the verb to <em>POST</em>.  We can leave the headers as they are.  We then select the format of the body to <em>JSON</em>.  We then write in our <em>JSON</em> 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.</p>
<p>What about an <em>Update</em> or <em>Delete</em> operation?  Well, we now need to select the next item on the <em>Resources</em> 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 <em>PUT</em> or <em>DELETE</em>.</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-put-or-delete-verbs.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-put-or-delete-verbs.png?w=600&#038;h=179" alt="" title="Test Client - PUT or DELETE verbs" width="600" height="179" class="alignnone size-full wp-image-879" /></a></p>
<p>We will leave the verb as a <em>PUT</em>.  We need to provide the primary key to the record is in the path of the <em>URL</em>.  Next we change the format of the body to <em>JSON</em> 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.</p>
<p><a href="http://mattduffield.files.wordpress.com/2011/12/test-client-deleting-an-existing-record.png"><img src="http://mattduffield.files.wordpress.com/2011/12/test-client-deleting-an-existing-record.png?w=600&#038;h=444" alt="" title="Test Client - Deleting an existing record" width="600" height="444" class="alignnone size-full wp-image-875" /></a></p>
<p>Deleting a record is even easier.  All we need to do is change the verb to <em>DELETE</em> and ensure that the primary key to the record is in the path of the <em>URL</em>.  Next we hit <em>Send</em> and await our response.  We get a <em>Response code</em> of 200 and we are returned the total number of records affected by the delete.</p>
<p>The <em>Test Client</em> feature of the WCF Web API makes developing and testing services very fast with very little hassle.  I simply hit <em>F5</em> on my solution and then navigate my browser to the corresponding service I want to test.  </p>
<p><strong>NOTE:</strong>  Make sure that your <em>JSON</em> is in the correct format or it may never hit your breakpoint.</p>
<p>That&#8217;s it for now.  We will cover creating <em>Silverlight</em> and <em>Console</em> test clients in the next post.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/872/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=872&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/20/building-a-generic-service-using-wcf-web-api-part-iii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client.png" medium="image">
			<media:title type="html">Test Client</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-get.png" medium="image">
			<media:title type="html">Test Client - GET</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-get-or-post-verbs.png" medium="image">
			<media:title type="html">Test Client - GET or POST verbs</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-configure-headers.png" medium="image">
			<media:title type="html">Test Client - Configure Headers</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-getting-existing-records.png" medium="image">
			<media:title type="html">Test Client - Getting existing records</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-adding-a-new-record.png" medium="image">
			<media:title type="html">Test Client - Adding a new record</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-put-or-delete-verbs.png" medium="image">
			<media:title type="html">Test Client - PUT or DELETE verbs</media:title>
		</media:content>

		<media:content url="http://mattduffield.files.wordpress.com/2011/12/test-client-deleting-an-existing-record.png" medium="image">
			<media:title type="html">Test Client - Deleting an existing record</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a generic service using WCF Web API &#8211; Part II</title>
		<link>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api-part-ii/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api-part-ii/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 20:44:58 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF Web API]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=867</guid>
		<description><![CDATA[Okay, so we now have our service definition in place. Let&#8217;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: Just like any of the other examples you have seen with the WCF Web API, we are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=867&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Okay, so we now have our service definition in place.  Let&#8217;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:</p>
<p><pre class="brush: csharp;">
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 = &quot;Domain&quot;;
        public const string EGOV = &quot;Domain2&quot;;

        protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.SetDefaultHttpConfiguration(new WebApiConfiguration() 
                {
                    CreateInstance = (serviceType, context, request) =&gt; CreateInstance(serviceType),
                    EnableTestClient = true 
                });

            RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;Customers&gt;(ACCOUNT);
            RouteTable.Routes.MapServiceRouteForAssemblyOf&lt;rv_o_Organization&gt;(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&lt;GoferService&lt;Customers&gt;&gt;(&quot;Customer&quot;);
                // 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(&quot;rules&quot;, rules);

                result = kernel.Get(serviceType);
            }
            catch { }

            return result;
        }

        #region Rules

        private DataAccessRules GetAccountAtAGlanceRules(Type type)
        {
            var result = new DataAccessRules();
            result.AssemblyOf(type)
                .SetConnectionStringKey(&quot;aag_ConnectionString&quot;)
                .ShouldMap(x =&gt; x.Namespace == &quot;Domain&quot;);
            return result;
        }
        private DataAccessRules GetEgovRules(Type type)
        {
            var result = new DataAccessRules();
            result.AssemblyOf(type)
                .SetConnectionStringKey(&quot;emgov_ConnectionString&quot;)
                .ShouldMap(x =&gt; x.Namespace == &quot;Domain2&quot;);
            return result;
        }

        #endregion
    };
}
</pre></p>
<p>Just like any of the other examples you have seen with the WCF Web API, we are using the <em>Routes</em> property off of the <em>RouteTable</em> and calling the <em>SetDefaultHttpConfiguration</em>.  We are doing something a little special in that we are using a lambda expression to call the <em>CreateInstance(&#8230;)</em> method as well as passing in the service type.  On the next two lines of code, we see that we are calling the <em>MapServiceRouteForAssemblyOf&lt;T&gt;(&#8230;)</em> generic extension method.  It is the combination of the <em>CreateInstance()</em> method and the <em>MapServiceRouteForAssemblyOf&lt;T&gt;(&#8230;)</em> generic extension method that makes everything work correctly.</p>
<p>Let&#8217;s look at the <em>CreateInstance()</em> 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 <em>MEF</em> or <em>Unity</em> or whatever you wanted as well.  Next I am interrogating the <em>Type</em> 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 <em>MapServiceRouteForAssemblyOf&lt;T&gt;(&#8230;)</em> call.</p>
<p>Finally, I call the <em>Bind</em> method on the <em>IKernel</em> object and tell it to pass in the newly created <em>DataAccessRules</em> object as a constructor parameter.  I then ask the <em>kernel</em> to resolve the service type that was originally passed into the method and return that new object.</p>
<p>So far, we have seen how we are setting up our <em>DI</em> container and injecting a <em>DataAccessRules</em> object into the constructor.  What we haven&#8217;t seen yet is how we are getting data access for all of our domain objects.  Let&#8217;s take a look at the individual methods that get us our <em>DataAccessRules</em> object and then we will turn our attention to how we handle this for all of our domain objects.</p>
<p>Our <em>DataAccessRules</em> objects are created by either the <em>GetAccountAtAGlanceRules(&#8230;)</em> method or the <em>GetEgovRules(&#8230;)</em> method.  The thing to take into consideration here is we are telling the rules object what connection string to use from the <em>web.config</em> file as well as specifying the namespace that we only want to load our objects from.</p>
<p>Now let&#8217;s shift gears and take a look at the <em>MapServiceRouteForAssemblyOf&lt;T&gt;(&#8230;)</em> generic extension method.</p>
<p><pre class="brush: csharp;">
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&lt;T&gt;(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 =&gt; x.Namespace == domain);

            foreach (var item in types)
            {
                string routePrefix = item.Name;
                Type gs = typeof(GoferService&lt;&gt;);
                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(&quot;routes&quot;);
            }

            var route = new WebApiRoute(routePrefix,
                new HttpServiceHostFactory() { Configuration = configuration }, serviceType);
            route.Constraints = new RouteValueDictionary(constraints);
            routes.Add(route);
        }
    };
}
</pre></p>
<p>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 <em>MapServiceRouteForAssemblyOf&lt;T&gt;</em> 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.</p>
<p>Let&#8217;s look at one last piece of the puzzle, the <em>web.config</em>:</p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
    &lt;add key=&quot;aag_ConnectionString&quot; value=&quot;Data Source=(local);Initial Catalog=AccountsAtAGlance;Integrated Security=SSPI;&quot; /&gt;
    &lt;add key=&quot;emgov_ConnectionString&quot; value=&quot;Data Source=(local);Initial Catalog=emgov_data;Integrated Security=SSPI;&quot; /&gt;
  &lt;/appSettings&gt;
  &lt;system.serviceModel&gt;
    &lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot;/&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre></p>
<p>As you can see, this is one of the reasons why I love the <em>WCF Web API</em>.  There is nothing but the bare minimum required.  I can now add as many connection strings as I want to the <em>web.config</em> and I only have to go to the <em>Global.asax.cs</em> file to make sure that it is wired in correctly.</p>
<p>In the next post, we will look at what the client side code looks like.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/867/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/867/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/867/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=867&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api-part-ii/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>
	</item>
		<item>
		<title>Building a generic service using WCF Web API</title>
		<link>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 19:45:06 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=856</guid>
		<description><![CDATA[Now that we have taken a look at the new WCF Web API let&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=856&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now that we have taken a look at the new WCF Web API let&#8217;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.</p>
<p>As of this post, Preview 6 is available from the WCF Web API.</p>
<p>Okay, let&#8217;s look at what we have for our generic service below:</p>
<p><pre class="brush: csharp;">
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&lt;T&gt; 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 = &quot;&quot;)]
        public HttpResponseMessage&lt;List&lt;T&gt;&gt; Get()
        {
            try
            {
                var repo = new Repository&lt;T&gt;(Rules);
                var result = repo.Get().ToList();
                var response = new HttpResponseMessage&lt;List&lt;T&gt;&gt;(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 = &quot;&quot;, Method = &quot;POST&quot;)]
        public HttpResponseMessage&lt;T&gt; Insert(T item)
        {
            var typeName = typeof(T).Name;
            if (item == null)
            {
                var error = new HttpResponseMessage(HttpStatusCode.NotFound);
                error.Content = new StringContent(string.Format(&quot;{0} not found!&quot;, 
					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&lt;T&gt;(Rules);
                int id = repo.Insert(item);
                ReflectionHelper.SetPropertyValue(item, pkey, id);
                var response = new HttpResponseMessage&lt;T&gt;(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 = &quot;{id}&quot;, Method = &quot;PUT&quot;)]
        public HttpResponseMessage&lt;T&gt; 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(&quot;{0} not found!&quot;, 
					typeName));
                throw new HttpResponseException(error);
            }

            try
            {
                var repo = new Repository&lt;T&gt;(Rules);
                repo.Update(item);
                var response = new HttpResponseMessage&lt;T&gt;(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 = &quot;{id}&quot;, Method = &quot;DELETE&quot;)]
        public HttpResponseMessage&lt;int&gt; Delete(int id)
        {
            try
            {
                var repo = new Repository&lt;T&gt;(Rules);
                return repo.Delete(id);
            }
            catch (Exception ex)
            {
                var response = new HttpResponseMessage();
                response.Content = new StringContent(ex.Message);
                throw new HttpResponseException(response);
            }
        }

        #endregion

        #endregion
    };
}
</pre></p>
<p>NOTE:  I have simplified this service a bit to show you how to build your own generic service.</p>
<p>The first thing to note with this service is the <em>ServiceContract</em> 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 <em>DataAccessRules</em>.  Basically, this object allows me to specify what connection string to use that is stored in the <em>web.config</em> 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.</p>
<p>Next, we see the <em>Get</em> method.  This method allows us to get our data.  As of Preview 5, we don&#8217;t need to provide an empty string for the default <em>UriTemplate</em> but I decided to show it to you anyways.  With the Get method, I am returning an HttpResponseMessage&lt;List&lt;T&gt;&gt; object.  I have a <em>Repository</em> object that provides access to all my underlying data.  I have the repository return me a list of items of type <em>T</em> and then create a new <em>HttpResponseMessage</em> passing in the List&lt;T&gt; to the constructor.  By default the status code of the object set to <em>Ok</em> which is equivalent to <em>200</em>.  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.</p>
<p>We can now look at what is required for inserting new records.  This method uses a <em>WebInvoke</em> attribute compared to the <em>WebGet</em> that we saw in our get method.  With the <em>WebInvoke</em> attribute we handle all other HTTP verbs that we want to use.  For this request, we are going to handle a <em>POST</em>.  This method returns an instance of an <em>HttpResponseMessage&lt;T&gt;</em> 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 <em>Expression&lt;&lt;Func&lt;string,string&gt;&gt;</em> and allows delayed evaluation.  It isn&#8217;t until the <em>GetPrimaryKey</em> method is executed that the <em>Expression&lt;Func&lt;string,string&gt;&gt;</em> is evaluated.  This is a handy trick as it allow us to define rules per object or namespace by passing in a lambda expression.</p>
<p>Once we have the name of the key, we then go ahead and use the <em>Repository</em> object and <em>Insert</em> a new record.  What we do next is use some reflection to set the underlying object key property with the value returned by the <em>Repository</em>.  Finally, we create an instance of an <em>HttpResponseMessage&lt;T&gt;</em> passing in the generic instance as well as setting the <em>StatusCode</em> to <em>Created</em>.  We handle any exceptions in this method exactly the same.</p>
<p>The <em>Update</em> method basically operates the same.  It uses a <em>PUT</em> operation.  The <em>Repository</em> passes the generic object and performs the <em>Update</em>.  The method returns an <em>HttpResponseMessage&lt;T&gt;</em> object once the operation successfully completes.  </p>
<p>The final operation is the <em>Delete</em>.  It uses a <em>DELETE</em> operation.  The <em>Repository</em> passes the integer value and performs the <em>Delete</em>.  The method returns an <em>HttpResponseMessage&lt;int&gt;</em> object once the operation successfully completes.  </p>
<p>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.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/856/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/856/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/856/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=856&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/19/building-a-generic-service-using-wcf-web-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>
	</item>
		<item>
		<title>Introducing the WCF Web API</title>
		<link>http://mattduffield.wordpress.com/2011/12/19/introducing-the-wcf-web-api-2/</link>
		<comments>http://mattduffield.wordpress.com/2011/12/19/introducing-the-wcf-web-api-2/#comments</comments>
		<pubDate>Mon, 19 Dec 2011 13:39:23 +0000</pubDate>
		<dc:creator>mattduffield</dc:creator>
				<category><![CDATA[English]]></category>
		<category><![CDATA[Mobile]]></category>
		<category><![CDATA[REST]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[WCF RIA Services]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://mattduffield.wordpress.com/?p=852</guid>
		<description><![CDATA[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&#8217;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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=852&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>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&#8217;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.</p>
<p>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.</p>
<p>With WCF Web API, because I don&#8217;t have to worry about a client-side proxy, I don&#8217;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.</p>
<p>If you haven&#8217;t played with the <a href="http://wcf.codeplex.com/">WCF Web API</a>, 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.</p>
<p>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.</p>
<p>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.</p>
<p>You can read up on the WCF Web API documentation <a href="http://wcf.codeplex.com/">here</a>. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/mattduffield.wordpress.com/852/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/mattduffield.wordpress.com/852/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/mattduffield.wordpress.com/852/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=mattduffield.wordpress.com&amp;blog=12672759&amp;post=852&amp;subd=mattduffield&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://mattduffield.wordpress.com/2011/12/19/introducing-the-wcf-web-api-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<georss:point>0.000000 0.000000</georss:point>
		<geo:lat>0.000000</geo:lat>
		<geo:long>0.000000</geo:long>
		<media:content url="http://1.gravatar.com/avatar/746d76a8d9687e58f60d6f90f29ccdb3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">mattduffield</media:title>
		</media:content>
	</item>
	</channel>
</rss>
