I am now a registered community speaker with INETA. If you are organizing a technology conference or a user group leader, you can make a request for me to come over and deliver a talk by clicking on the link below:
Friday, July 6, 2012
Tuesday, July 3, 2012
Northwind-mania: Simple example on working with Northwind oData using KnockoutJS
In my previous post I demonstrated how one can easily render data on the client side from the Categories table in the Northwind database using KnockoutJS. This post is a slight variation of my previous post whereby the source of the data is an oData feed originating from http://services.odata.org/Northwind/Northwind.svc.
Pre-requisites:
- Visual Studio 2010
- MVC 3.0
- NuGet
- KnockoutJS
- DataJS
Step 1:
Start a new New Web Site project in Visual Studio 2010 using the ASP.NET Empty Web Site template.
Step 2:
In Solution Explorer, right-click on the top node and select “Manage NuGet Packages …”.
Step 3:
Enter “knockout” in the search field on the top right-hand-side of the next screen. Select “knockoutjs” then click on the “Install” button.
Step 4:
In addition to knockoutjs, we will be using other JavaScript libraries jQuery and DataJS. DataJS facilitates access to oData. Therefore, repeat Step-3 for jQuery and DataJs libraries.
Ensure that the jQuery, DataJs and KnockoutJs libraries are installed into your project under the Scripts folder as shown below:
Step 5:
Add a new page named “Default.htm” to your website.
Open the Default.htm file. Drag and drop the JavaScript files jquery-1.7.2.js, knockout-2.1.0.js and datajs-1.0.3.js from the Scripts folder into the Default.htm file just below the ending </title> tag. This produces the <script> tag pointing to the respective JavaScript files. The page should resemble the following:
<!DOCTYPE>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/datajs-1.0.3.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>
Step 6:
Place the following HTML into the body section of the Default.htm file:
<ul data-bind="foreach: categories">
<li><span data-bind="text: $data.CategoryName"></span></li>
</ul>
<script type="text/javascript">
var ServiceURL = "http://services.odata.org/Northwind/Northwind.svc";
OData.read(ServiceURL + "/Categories?$format=json", CallbackFunction);
function CallbackFunction(data, request) {
var viewModel = {
categories: data.results
};
ko.applyBindings(viewModel);
}
</script>
Let’s analyze the above code. The most important line is:
OData.read(url, CallbackFunction);
The OData.read() function comes from the “DataJS” library. Its first argument is an oData URL, and the second argument is a callback function that is called once a response is received from the server. Notice that the oData URL contains “$format=json” so that data returned from the service is in JSON format.
The callback function reads the JSON data encapsulated in property data.results into the categories property of the KnockoutJS viewModel. Finally, the viewModel is bound to the view with the function call ko.applyBindings(viewModel).
On the view side, data is rendered to the web page as follows:
<ul data-bind="foreach: categories">
<li><span data-bind="text: $data.CategoryName"></span></li>
</ul>
The final state of the web page is:
<!DOCTYPE>
<html>
<head>
<title></title>
<script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/datajs-1.0.3.js" type="text/javascript"></script>
</head>
<body>
<ul data-bind="foreach: categories">
<li><span data-bind="text: $data.CategoryName"></span></li>
</ul>
<script type="text/javascript">
var ServiceURL = "http://services.odata.org/Northwind/Northwind.svc";
OData.read(ServiceURL + "/Categories?$format=json", CallbackFunction);
function CallbackFunction(data, request) {
var viewModel = {
categories: data.results
};
ko.applyBindings(viewModel);
}
</script>
</body>
</html>
This example, of course, a very simplistic. It does, however, illustrate how the various pieces fit together involving KnockoutJS and oData.
Hit F5 in Visual Studio 2010.
You may receive a browser warning because a request is being made to another server at http://www.odata.org. I received the following dialog, and clicked on the “Yes” button:
The output is identical to my previous post. The difference, this time, is that we are using plain HTML and all data access is being done using client-side technologies.
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:
Step 2:
On the next screen, choose “Internet Application”.
Step 3:
In Solution Explorer, right-click on Reference and select “Manage NuGet Packages …”.
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.
The knockoutjs JavaScript file will be contained in your project in the Scripts directory:
Step 5:
Right-click on the “Models” folder: Add >> New Item:
Add an “ADO.NET Entity Data Model (Visual C#)” item named “NorthwindModel.edmx”:
Select “Generate from database” then click “Next”.
Choose the appropriate Northwind database connection then click Next.
Click on the checkbox beside Tables, then click the “Finish” button.
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:
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.
Select the Internet Allocation template.
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.
On the next dialog, select “Generate from Database” then click on “Next”.
Select your appropriate data connection to the Northwind database then click Next.
Select all tables by clicking on the checkbox beside Tables then click on Finish.
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 …”.
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.
You may see a security warning. Click on the checkbox beside “Do not show this message again”
The simple POCO domain classes are created together with the DbContext class.
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
- 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
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.
3. On the next window, choose the “Web API” project template.
4. The next step is to add the Northwind data model. Right click on the Models folder then select Add >> New Item.
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.
6. On the “Entity Data Model Wizard”, select “Generate from database” then click on Next.
7. Configure a connection to your Northwind database on the next window then click Next.
8. Select all tables by clicking on the checkbox beside Tables, then click Finish.
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.
11. Right click on the Controllers folder then select Add >> New Item… >> Web API Controller Class.
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.
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.
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.
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:
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:
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”:
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
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.