Posts Tagged ‘ASP.NET MVC’


I had a great time Tuesday night speaking at the Greenville Spartanburg Developers Guild.  Thanks to all who came out to the presentation!

Here are the slides and sample code:

Slides and Sample code

Hope you enjoy…


I will be speaking Tuesday, May 15 at the Greenville Spartanburg Developers Guild in Greenville, SC on ASP.NET MVC4 and Web API.

Here is my presentation summary:

Microsoft likes big stacks! Look at Windows Presentation Foundation (WPF) or, better yet, Windows Communication Foundation (WCF). With either of these “foundations”, you start out a noob and you come out the other side a freak’in Ph.D in Quantum Physics. It doesn’t have to be that hard! There has to be a better way.

Well, Microsoft has been definitely been going the right direction. If you have followed any of the work on the WCF Web API, then you know how awesome this stuff is. This is its new home but you can still self host just like you could before. We are talking about a Web API that is heavily Convention-Over-Configuration based! Gone are the days of looking through a myriad of documentation as to how to setup your web.config file. Those days are over and you will be surprised at how nice the new stack is.

Look forward to seeing you there!


I had a great time speaking to the WNC Developers Guild and the Triad Developers Guild and the Columbia Enterprise Developers Guild. Here are the slides and code samples.

Slides and Code Samples

Thanks to all who came out and showed up!


March 15, 2012 1 comment

I will be speaking this evening, March 15 at the WNC .NET Developers Guild in Asheville, NC on ASP.NET MVC4 and Web API. I will also be doing the same presentation on Thursday, March 22 at the Triad Developers Guild in Greensboro, NC and also on Wednesday, April 11 at the Columbia Enterprise Developers Guild in Columbia, SC.

Here is my presentation summary:

Microsoft likes big stacks! Look at Windows Presentation Foundation (WPF) or, better yet, Windows Communication Foundation (WCF). With either of these “foundations”, you start out a noob and you come out the other side a freak’in Ph.D in Quantum Physics. It doesn’t have to be that hard! There has to be a better way.

Well, Microsoft has been definitely been going the right direction. If you have followed any of the work on the WCF Web API, then you know how awesome this stuff is. This is its new home but you can still self host just like you could before. We are talking about a Web API that is heavily Convention-Over-Configuration based! Gone are the days of looking through a myriad of documentation as to how to setup your web.config file. Those days are over and you will be surprised at how nice the new stack is.

Look forward to seeing you there!

A Case for going ORM-less

December 22, 2011 6 comments

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Raleigh Code Camp

November 2, 2011 Leave a comment

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

Categories: English Tags: , , , , ,

Test your website from your mobile device while still developing in Visual Studio

October 18, 2011 8 comments

As you continue to develop new applications and come up with solutions for many new devices, it becomes necessary to be able to test your code in a quick and efficient manner. Sometimes, deploying your code to a web server just for testing does not make sense. It may even be too time consuming to deploy even to your local instance of IIS if all you want to do is view a quick change you made.

The problem with trying to do this while using Visual Studio is that you are always debugging your code using a http://localhost:/xxx address and this does not allow other devices to hit this address directly. Here is a trick/hack that I have learned that may save you some time while developing your web applications.

1. Visual Studio will automatically use Cassini for hosting web projects. We want to change this to use IIS Express as shown in the figure below:

2. Please note that I changed the path of the Project Url to use the computer name along with the port. The original url was pointing to “localhost”.

3. If you hit F5, the application will still not work. Here comes the trick/hack.

4. We need to modify the binding information that IIS Express holds for this application. Open up an instance of Windows Explorer and navigate to the following location providing your own user name and drive letter:
[drive letter]:\Users\[user name]\Documents\IISExpress\config

5. Here we are going to make a modification to the application.config file. It is important to make a backup of this document in case you make a mistake and want to rollback.

6. Navigate the XML document to the following XPath location:

7. Here we will have a listing of all the websites that we are using against IIS Express. Go down to the site that you are wanting to expose as seen in the figure below:

8. Change the binding information from “localhost” to your computer name.

9. Save and close the file.

10. Restart IIS Express. Go to the tray icon and stop IIS Express as shown below:

11. You will be presented a dialog about stopping IIS Express.

12. Finally, hit F5 and run your application.

13. You can now test your site from your mobile device or tablet without deploying. This will allow you to make changes and browse to the location without any added workflow to your development process.

Although, I use this internally when I am developing applications where I need to see the results on a real device, I still think this is a hack and should be treated with caution.

Hope this helps…

Async CTP (SP1 Refresh) Installs successful but does not work

August 31, 2011 Leave a comment

It turns out that if you have ASP.NET MVC 3 installed, you are out of luck being able to install the Async CTP (SP1 Refresh). As of right now, these two technologies do not play well together. It will look like it installed correctly and it will even say that it installed correctly but it will not work.

This is a known problem and hopefully will be fixed in the near future. You can read more about this on Scott Guthrie’s blog. You can also find the steps on how to remove ASP.NET MVC 3 by going to Drew Miller’s blog so that you can use the Async CTP.

Hope this helps…

Categories: English Tags: ,

Using ICustomTypeProvider in Silverlight 5 beta with JSON and ASP.NET MVC 3

June 3, 2011 6 comments

One of the really powerful new features in Silverlight 5 is the new interface ICustomTypeProvider. This allow us to have a dynamic way to bind to objects that we don’t know the shape of until at runtime. There are three blog posts that you need to read before continuing forward. Please read this post by Alexandra Rusina. In it she provides a nice implementation for ICustomTypeProvider. The other post is by Jeremy Likness. In his post he expounds a little more on what Alexandra provided and gives us the ability to parse JSON. The last post, basically gives us an easy way to format our JSON so that we can see it in a human readable format instead of what it looks like once we pull it from the stream.

This post basically will takes us from the point where Jeremy and Alexandra left us and use ASP.NET MVC 3 to act as our service host for getting data across the wire.

Ok, let’s get started. First of all, I created a blank solution called “CustomTypeProvider”.

Next, I added a new Silverlight 5 project. When asked, I changed the host to be a ASP.NET MVC project. I gave the name of the Silverlight project, “CustomerTypeProvider.Silverlight” and the web host, “CustomTypeProvider.Web”.

I like to use Caliburn.Micro whenever I can and I opted to use the latest version of Caliburn.Micro in my Silverlight project. I used NuGet to pull down the package. It is as easy as right-clicking your References and selecting, “Add Library Package Reference”. Once the dialog appeared, I changed it to online and entered, “Caliburn.Micro” in the search and installed it once it appeared.

I basically followed the steps provided in the web page that comes up in Visual Studio once Caliburn.Micro’s package is installed. I also added the following assembly references:

  • System.Json
  • System.ComponentModel.DataAnnotations
  • System.Windows.Controls.Data

Let’s look at the code necessary for the web first:

namespace CustomerTypeProvider.Web.Controllers
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Collections;
    using System.Data.SqlClient;

    public class HomeController : Controller
        public JsonResult GetCustomers()
            var data = LoadCustomers();
            return Json(data, JsonRequestBehavior.AllowGet);
        public JsonResult GetOrders()
            var data = LoadOrders();
            return Json(data, JsonRequestBehavior.AllowGet);
        public JsonResult GetQuery(string query)
            var data = LoadQuery(query);
            return Json(data, JsonRequestBehavior.AllowGet);
        private List<Customer> LoadCustomers()
            List<Customer> result = new List<Customer>();
            result.Add(new Customer() { FirstName = "Matt", LastName = "Duffield" });
            result.Add(new Customer() { FirstName = "Dean", LastName = "Duffield" });
            return result;
        private List<Order> LoadOrders()
            List<Order> result = new List<Order>();
            result.Add(new Order() { ContactName= "Matt Duffield",
              OrderDate= DateTime.Now, OrderNumber = 100 });
            result.Add(new Order() { ContactName = "Dean Duffield",
              OrderDate = DateTime.Now, OrderNumber = 101 });
            return result;
        private ArrayList LoadQuery(string query)
            ArrayList objs = new ArrayList();

            //SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;User Id=myUsername;Password=myPassword;");
            SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=Northwind;Integrated Security = SSPI;");
            //SqlCommand cmd = new SqlCommand("SELECT TOP 10 [CustomerID],[CompanyName],[Address],[City],[Region],[PostalCode],[Country]  FROM [Customers]", conn);
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataReader r = cmd.ExecuteReader();
            while (r.Read())
                    CustomerID = (r["CustomerID"] is DBNull ? "" : r["CustomerID"]),
                    CompanyName = (r["CompanyName"] is DBNull ? "" : r["CompanyName"]),
                    Address = (r["Address"] is DBNull ? "" : r["Address"]),
                    City = (r["City"] is DBNull ? "" : r["City"]),
                    Region = (r["Region"] is DBNull ? "" : r["Region"]),
                    PostalCode = (r["PostalCode"] is DBNull ? "" : r["PostalCode"]),
                    Country = (r["Country"] is DBNull ? "" : r["Country"])

            return objs;

        public class Customer
            public string FirstName { get; set; }
            public string LastName { get; set; }
        public class Order
            public int OrderNumber { get; set; }
            public DateTime OrderDate { get; set; }
            public string ContactName { get; set; }

Okay, so there is a little going on but we will start from the top. We basically have three public methods at the top:

  • GetCustomers()
  • GetOrders()
  • GetQuery(string query)

The first two call helper methods that basically create a generic List<> with some sample data and pass it back to the calling method.  The third is a little more dynamic in that it uses ADO.NET to create a SqlConnection, SqlCommand, and finally a SqlDataReader.  It executes the query passed in and then loops through the data reader to shapes a new object that gets added to an ArrayList.  The ArrayList then gets passed back to the calling method. One thing to note about the data reader loop is that we are checking for DBNull and giving it a default value. This is necessary on the client side so that we can infer the type information.

In each of the corresponding methods above, a new Json object is created passing in the data that was returned from the helper methods as well as a second parameter is set to allow the Get verb.

Now let’s move on to the client side.  In the client side, I have to folders that are of interest:

  • Formatting
  • Framework

In the Formatting folder is the logic necessary to format the JSON stream that comes from the web make it human readable.

In the Framework folder is the logic that I took from Alexandra Rusina’s and from Jeremy Likness’ blog posts.  I won’t go into detail in these classes since there are separate posts by each of them dedicated to the classes.  What I will show you is the ShellView and ShellViewModel to see how we get this data and render on screen.

Let’s take a look at the ShellView:

<UserControl x:Class="CustomerTypeProvider.Silverlight.ShellView"
    <Grid Background="White" Margin="5">
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="Auto" />
        <sdk:DataGrid AutoGenerateColumns="True"
            ItemsSource="{Binding Path=ResultsPaneItems}"
        <TextBox x:Name="JsonResult" AcceptsReturn="True"
                 Grid.Column="1" Grid.Row="0" 
                 Width="400" VerticalScrollBarVisibility="Auto" 
        <StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal">
            <Button x:Name="LoadCustomers" Content="Load Customer" Margin="5" />
            <Button x:Name="LoadOrders" Content="Load Orders" Margin="5" />
            <Button x:Name="LoadQuery" Content="Load Query" Margin="5" />

Because I am using Caliburn.Micro, my XAML is very clean.  We see a DataGrid that has it’s ItemsSource property bound to collection property called, “ResultsPaneItems” object.  We also see a TextBox that is bound to a property called, “JsonResult” as well.  Finally, we see three buttons that call the three corresponding web methods.
Looking at the ShellViewModel we see the following:

namespace CustomerTypeProvider.Silverlight 
    using System.ComponentModel.Composition;
    using System.Collections.ObjectModel;
    using Core.Framework;
    using Core.Framework.Formatting;
    using Caliburn.Micro;
    using System;
    using System.Net;
    using System.Json;
    using System.IO;
    using System.Diagnostics;

    public class ShellViewModel : Screen, IShell 
        public ObservableCollection<CustomType> ResultsPaneItems { get; private set; }
        private string _jsonResult;
        public string JsonResult
            get { return _jsonResult; }
                _jsonResult = value;
                NotifyOfPropertyChange(() => JsonResult);

        #region ctor

        public ShellViewModel()
            ResultsPaneItems = new ObservableCollection<CustomType>();



        public void LoadCustomers()

        public void LoadOrders()
        public void LoadQuery()
            string query = "SELECT TOP 10 [CustomerID],[CompanyName],[Address],[City],[Region],[PostalCode],[Country]  FROM [Customers]";
            LoadResultsPane("/home/GetQuery?query=" + query);

        private void LoadResultsPane(string uri)
            ResultsPaneItems = new ObservableCollection<CustomType>();

            Uri serviceUri = new Uri(uri, UriKind.Relative);
            WebClient downloader = new WebClient();
            downloader.OpenReadCompleted += (s, e) =>
                // Load the JsonArray from the service call.
                StreamReader sr = new StreamReader(e.Result);
                var content = sr.ReadToEnd();
                JsonResult = new JsonFormatter(content).Format();
                var jsonArray = JsonArray.Load(e.Result) as JsonArray;
                if (jsonArray == null) return;

                // Pull the first record as a template.
                var template = jsonArray[0] as JsonObject;
                if (template == null) return;

                // Use the template to get type information.
                var jsonHelper = new JsonHelper<CustomType>(template);

                // Iterate over the results and add to the underlying collection.
                foreach (var item in jsonArray)
                    var customType = new CustomType();
                    jsonHelper.MapJsonObject(customType.SetPropertyValue, item);
            // Retrieve the data.


Okay, let’s start from the top and work our way down. First we see that declaration of the ResultsPaneItems collection. Next we see the property for the JsonResult string. In the constructor, we initialize the collection.

Next, we have the three methods that respond to the corresponding buttons. All three of them call a helper method called, “LoadResultsPane(string uri)”. It is this method that does all of the heavy lifting. The only difference in the methods is that the last one also passes in the query as part of the query string to the GetQuery method on the controller.

In the LoadResultsPane(…) method, we are initializing the ResultsPaneItems to a new collection. Note that this collection is of type CustomType. This is important since we want each button click to load a fresh set of data. Next we use the Uri and WebClient objects to perform the OpenReadAsync(…) call. This is an asynchronous call and that is we we have an anonymous delegate in the form of a lambda expression stating what to do when the call comes back. Inside the expression, we create a StreamReader object off of the Result. We read the stream so that we can use our formatter class and display the raw JSON that was just returned to us. Next we create a JsonArrary and load the same Result object trying to cast it to a JsonArrary object. If that is successfuly, then we use the first row as a representation of the data so that we can type it accordingly. If you recall, this is why we had the test for DBNull in the data reader loop on the controller. Finally, we loop over the JsonArrary and create a CustomType object. We use the JsonHelper provided by the previous blog posts and then add it to our collection.

That is all there is to it. You now have a very dynamic model in which you can data bind to any object that is sent from the server. You no longer need to know about it. The server-side code could be further abstracted so that you had a completely generic solution instead of the hard-coding I have shown in the loop of the data reader.

Here is a sample screen shot of the application:

You can download the sample code here. Don’t forget that this solutions works only for Silverlight 5 beta.
Hope you enjoy…

Building a Windows Phone 7 App using JSON/ASP.NET MVC Data Service Layer

May 25, 2011 8 comments

I had a great time speaking at Charlotte’s Enterprise Developers Guild last night. Here is a link to my slides and sample code.

Thanks again to everyone who came out!