Friday, June 22, 2012

Northwind-mania: Reading Categories table using MVC 3.0, Entity Framework, and KnockoutJS

This lesson demonstrates how one can easily display the contents of the Categories table in the Northwind database on a web page using KnockoutJS:

Pre-requisites:

  • Visual Studio 2010
  • MVC 3.0
  • Northwind database
  • SQL Server Express
  • NuGet

Step 1:

In Visual Studio click: File >> New Project. On the next dialog choose: Web >> ASP.NET MVC 3.0 web application and give your application a decent name as shown below:

image

Step 2:

On the next screen, choose “Internet Application”.

image

Step 3:

In Solution Explorer, right-click on Reference and select “Manage NuGet Packages …”.

image

Step 4:

Enter “knockout” in the search field on the top right-hand-side of the next screen. Select “knockoutjs” then click on the “Install” button.

image

The knockoutjs JavaScript file will be contained in your project in the Scripts directory:

image

Step 5:

Right-click on the “Models” folder: Add >> New Item:

image

Add an “ADO.NET Entity Data Model (Visual C#)” item named “NorthwindModel.edmx”:

image

Select “Generate from database” then click “Next”.

image

Choose the appropriate Northwind database connection then click Next.

image

Click on the checkbox beside Tables, then click the “Finish” button.

image

Step 6:

Replace the Index() action in the HomeController.cs with the following code:

public ActionResult Index() {
   using (NorthwindEntities ctx = new NorthwindEntities()) {
       var categories = from c in ctx.Categories
                        select new { c.CategoryID, c.CategoryName };

       ViewBag.Categories = categories.ToList();

       return View();
   }
}

Step 7:

Open the index.cshtml file in the Views/Home directory. Drag and drop the “knockout-2.1.0.js” from the Scripts folder into the index.cshtml file above the <h2> tag. This produces the <script> tag pointing to the JavaScript file.

Step 8:

Replace the contents of the <p>..</p> section with the following:

<ul data-bind="foreach: categories">    
    <li><span data-bind="text: $data.CategoryName"></span></li>
</ul>
<script type="text/javascript">   
    var viewModel = {        
        categories: @Html.Raw(Json.Encode(ViewBag.Categories))    
    };   
    ko.applyBindings(viewModel);
</script>

Step 9:

Run the application by hitting F5. You should see the following web page:

image

If you look at the page view source, you should notice the following JSON data in the <script> section:

<script type="text/javascript">   
  var viewModel = {        
      categories: [
         {"CategoryID":1,"CategoryName":"Beverages"},
         {"CategoryID":2,"CategoryName":"Condiments"},
         {"CategoryID":3,"CategoryName":"Confections"},
         {"CategoryID":4,"CategoryName":"Dairy Products"},
         {"CategoryID":5,"CategoryName":"Grains/Cereals"},
         {"CategoryID":6,"CategoryName":"Meat/Poultry"},
         {"CategoryID":7,"CategoryName":"Produce"},
         {"CategoryID":8,"CategoryName":"Seafood"}
      ]    
  };   
  ko.applyBindings(viewModel);
</script>

Thursday, June 7, 2012

Northwind-mania: Generating a strongly-typed DbContext class + persistence ignorant classes from the Northwind Entity Framework model

In this lesson you will learn how to create simple domain classes from the Northwind EDMX Entity Framework model.

Pre-requisites:

  • Visual Studio 2010
  • Entity Framework 4.1 or later
  • ASP.NET MVC 3.0 or later
  • Northwind database

Step 1:

Download and install the EF 4.x DbContext Generator for C# into your Visual Studio 2010.

Step 2:

Start Visual Studio 2010 and create a new project based on the “ASP.NET MVC 2 Web Application” project type.

image

Select the Internet Allocation template.

image

Step 3:

Add an Entity Framework model for your Northwind database. This is done as follows:

Right-click your Models folder and choose Add >> New Item. Select “ADO.NET Entity Data Model” and name it NorthwindModel.edmx.

image

On the  next dialog, select “Generate from Database” then click on “Next”.

image

Select your appropriate data connection to the Northwind database then click Next.

image

Select all tables by clicking on the checkbox beside Tables then click on Finish.

image

Compile your application with Shift + CTRL + B so that your classes become visible to your project.

Step 4:

Right-click anywhere on your model and select “Add Code Generation …”.

image

If you have installed the EF 4.x DbContext Generator for C# in step 1 above, you will see the EF 4.x DbContext Generator option. Select that option. give the model the name NorthwindModel.tt then click on the Add button.

image

You may see a security warning. Click on the checkbox beside “Do not show this message again”

image

The simple POCO domain classes are created together with the DbContext class.

image

Let us first take a peek at one of the smallest domain classes, the Region entity.

public partial class Region {
  public Region() {
      this.Territories = new HashSet<Territory>();
  }

  public int RegionID { get; set; }
  public string RegionDescription { get; set; }

  public virtual ICollection<Territory> Territories { get; set; }
}

Note how very simple the Region class is. Next, let us look at the DbContext class file named NorthwindModel.Context.cs.

public partial class NorthwindEntities : DbContext {
  public NorthwindEntities() : base("name=NorthwindEntities") { }

  protected override void OnModelCreating(DbModelBuilder modelBuilder) {
      throw new UnintentionalCodeFirstException();
  }

  public DbSet<Category> Categories { get; set; }
  public DbSet<CustomerDemographic> CustomerDemographics { get; set; }
  public DbSet<Customer> Customers { get; set; }
  public DbSet<Employee> Employees { get; set; }
  public DbSet<Order_Detail> Order_Details { get; set; }
  public DbSet<Order> Orders { get; set; }
  public DbSet<Product> Products { get; set; }
  public DbSet<Region> Regions { get; set; }
  public DbSet<Shipper> Shippers { get; set; }
  public DbSet<Supplier> Suppliers { get; set; }
  public DbSet<Territory> Territories { get; set; }
}

Since we do not need the EDMX model anymore, go ahead and delete NorthwindModel.edmx file.

Conclusion:

This post shows you how you can take an Entity Framework EDMX model and create from it a simple POCO model based on the DbContext class.

Wednesday, May 30, 2012

Speaking at DevTeach 2012 in Vancouver

I will be giving two talks at DevTeach in Vancouver as follows:

  • oData on Wednesday May 30, 2012 from 4:30 PM to 5:45 PM
  • Silverlight 5 on Thursday May 31, 2012 from 8:00 AM to 9:15 AM
So far it has been a great show. I especially enjoyed the Speakers dinner at Richard Campbell's house last night. We had a blast.

Thursday, April 12, 2012

Northwind-mania: Exposing restful data using Web API

I will be demonstrating a series of technologies using the well known Nothwind database. I regularly use this sample database from Microsoft for demos because of its simplicity. I am calling the blog series “Northwind-mania”.

My first post is on Web API.

MVC 4.0 provides a new template that exposes restful data through a new feature named Web API. I am using Visual Studio 2010 for this article. Follow these steps to create a simple application based on the Northwind database and Web API.

Pre-requisites:

  • Visual Studio 2010
  • Northwind database

1. Download and install ASP.NET MVC 4.0.

2. In Visual Studio 2010, Click on File >> New Project. Choose the “ASP.NET MVC 4 Web Application” template.

image

3. On the next window, choose the “Web API” project template.

image

4. The next step is to add the Northwind data model. Right click on the Models folder then select Add >> New Item.

image

5. Select “Data” in the left pane, click on “ADO.NET Entity Data Model”. Name the model “NorthwindModel.edmx”. Finally, click on the “Add” button.

image

6. On the “Entity Data Model Wizard”, select “Generate from database” then click on Next.

image

7. Configure a connection to your Northwind database on the next window then click Next.

image

8. Select all tables by clicking on the checkbox beside Tables, then click Finish.

image

9. Hit “CTRL SHIFT B” in order to compile the application.

10. Delete the ValuesController.cs file in the Controllers folder as we will not need this file.

image

11. Right click on the Controllers folder then select Add >> New Item… >> Web API Controller Class.

image

12. Since we will be exposing the data in the Categories table using Web API, name the controller CategoryController then click on the Add button.

image

13. Replace the methods in CategoryController.cs with the following code in the CategoryController class:

NorthwindEntities ctx = new NorthwindEntities();
public IEnumerable<Category> GetAllCategory()
{
   return ctx.Categories.ToList();
}

public Category GetCategoryById(int id)
{
   var category = ctx.Categories.FirstOrDefault((c) => c.CategoryID == id);

   if (category == null)
   {
       var resp = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
       throw new HttpResponseException(resp);
   }
   return category;
}

public IEnumerable<Category> GetCategoryByName(string name)
{
   return ctx.Categories
       .Where(c => c.CategoryName.Contains(name))
       .Select(c => c);
}

14. Click on F5 to run your application.

image

15. In order to access the restful Category data, add “api/category” to the address URL. If you are using IE, you may see the following dialog at the bottom of your browser. This is because JSON data is being send from your server application to the browser.

image

If the above happens, the easiest work-around is to copy the URL into another browser like Chrome. This should result in all categories being displayed as shown below:

image

The above was rendered using the following method in the controller:

public IEnumerable<Category> GetAllCategory() {
   return ctx.Categories.ToList();
}

To view category with id=7, simply add /7 to the URL:

image

This was rendered with the following controller method:

public Category GetCategoryById(int id) {
   var category = ctx.Categories.FirstOrDefault((c) => c.CategoryID == id);

   if (category == null) {
       var resp = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
       throw new HttpResponseException(resp);
   }
   return category;
}

To view category with CategoryName of Produce, replace “7” with “?name=produce”:

image

Finally, the above was rendered by the following method:

public IEnumerable<Category> GetCategoryByName(string name)
{
   return ctx.Categories
       .Where(c => c.CategoryName.Contains(name))
       .Select(c => c);
}

Friday, March 30, 2012

"Failed to connect to device as it is pin locked" error

I experienced the error "Failed to connect to device as it is pin locked." while deploying a Windows Phone 7 application onto my Samsung Focus phone. The solution was:

1) Login to your apphub account at http://create.microsoft.com/
2) Click on your profile name in the top right-hand corner of the screen
3) On the page that displays next, click on the "devices" link.
4) Delete the device that you are not able to deploy on. In my case, I just had one device.
5) Close the AppHup page
6) Start Zune
7) Register the phone using the following application: Start >> All Programs >> Windows Phone SDK 7.1 >> Windows Phone Developer Registration
8) Go back into Visual Studio and deploy your application into the phone device.

Monday, March 12, 2012

TechFest 2012 on Saturday Apr 28, 2012 with Scott Guthrie


Date & Time: Saturday April 28, 2012 8:00 AM to 5:30 PM 
Location: BCIT Burnaby Campus, 3700 Willingdon Ave, Burnaby, BC, V5G 3H2
Food: Snacks, Coffee, and Lunch
Wireless Internet Access: FREE
Closest skytrain stations: Brentwood Mall or Metrotown

Topic: TechFest 2012 on Saturday Apr 28, 2012 with Scott Guthrie

In case you have not heard yet, registrations have started for the mother of all Vancouver technology festivals. We call it TechFest 2012 and it is happening on Saturday April 28, 2012. Our keynote speaker is none other than Scott Guthrie himself. Check out Scott's wikipedia page. This is a once-in-a-lifetime opportunity to see Scott Guthrie in person.

There will be six tracks:

- Azure (Sponsored by Microsoft)
- CMS (Sponsored by DotNetNuke)
- OS
- Mobile (Sponsored by Microsoft)
- Development
- Database

You can view the detailed sessions at http://www.vancouvertechfest.com/Sessions.aspx.

Registration:

Early bird special $50 valid until March 31, 2012. Register now.

After March 31, 2012: $75

Sunday, March 11, 2012

Installation of Windows 8 Consumer Preview on Oracle's VirtualBox 4.1.8 for Windows

Below are a list of VM technologies that currently support Windows 8:

- Hyper-V in Windows 8 Developer Preview
- Hyper-V in Windows Server 2008 R2
- VMware Workstation 8.0.2 for Windows
- Oracle's VirtualBox 4.1.8 for Windows
- Parallels Workstation 6 for Windows
- Parallels Desktop 4 for Windows
- XenDesktop 5.5

My personal experience with Oracle's VirtualBox version 4.1.8 was smooth. I was able to install both "Windows 8" and "Windows 8 Server" without any problems.

Here are the steps I took for installing Windows 8 (Consumer Preview) on Oracle's VirtualBox 4.1.8 for Windows:

1) Download Orcale's Virtual Box host application from: https://www.virtualbox.org/wiki/Downloads. After you download the product, go ahead and install it.

2) Download the Windows Server 8 (Consumer Preview) 64-bit ISO image file from: http://windows.microsoft.com/en-US/windows-8/iso.

3) Create a directory named Win8ServerCP (or any other name you fancy) somewhere on your hard drive.
Remember this location as this is where we will later store the VM.

4) Start Oracle's VirtualBox

5) On the left side of the toolbar, click on the "New" button.

6) Click "Next" on the "Welcome to the New Virtual Machine Wizard!" dialog.

7) On the next "VM Name and OS Type" dialog, enter/choose the following:

Name:    Windows 8 64-bit Consumer Preview
Operating System:  Microsoft Windows
Version:   Windows 8 (64 bit)

Click "Next"

8) Click Next on the "Memory" dialog.

9) Click Next on the "Virtual Hard Disk" dialog.

10) On the "Welcome to the Virtual disk creation wizard" dialog accept the default file type "VDI (Virtual Disk Image)" and click Next.

11) Click Next on the "Virtual disk storage details" dialog.

12) On the "Virtual disk file location and size" dialog, click on the browse folder icon and navigate to the folder named Win8ServerCP created in step 1 above, then click Save.

Click Next to move on to the next dialog.

13) Click Create on the "Summary" window. It will take a while for the VM file to get created. Be patient.

14) In the left pane, double click on the virtual machine named "Windows 8 64-bit Consumer Preview".

15) Click Next on the "Welcome to the First Run Wizard!" window.

16) On the "Select Installation Media" window, click on the browse folder icon and select the downloaded ISO image file then click Next.

17) Click Start on the "Summary" window.

18) Complete the self-explanatory installation process of the operating system.