Thursday, November 29, 2012

Synchronizing SharePoint 2010 user profile with AD

There could be scenarios like these:

- an employee changed his or her name
- an employee changed their mobile phone number
- etc …

The profile information in SharePoint is outdated and needs to be refreshed from AD, where the information is more recent.

The powershell command to do this is:

Get-SPUser –Web http://site | Set-SPUser –SyncFromAD

This command cycles through all the SharePoint users and updates the profile. If you come across any errors it is because there are some accounts in SharePoint or on the local server environment that do not exist in SharePoint. If you go into the appropriate SharePoint site you will notice that profiles have been updated.

Thursday, October 18, 2012

SharePoint 2010 Web Part Error: A Web Part or Web Form Control on this page cannot be displayed or imported. You don’t have Add and Customize Pages permissions required to perform this action

 

I deployed  a SharePoint 2010 on a customer’s system. At first, everything worked OK when users with elevated privileges were testing the part. However, soon after read-only users started experiencing the above error. If a user’s privilege was escalated to “Designer”, it would start working again.

The solution to the problem is to find the SharePointProjectItem.spdata file associated with the web-part and change the IsSafeAgainstScript to true in the <SafeControl..> element.

For Example:

<SafeControls>
    <SafeControl Name="SafeControlEntry1"
        Assembly="$SharePoint.Project.AssemblyFullName$"
        Namespace="Medhat.Ca.MyWebpart"
        TypeName="*"
        IsSafe="true"
        IsSafeAgainstScript="true" />
</SafeControls>

The explanation for this error is that users with privileges below "Design” are not allowed to add web-parts into web pages.

Saturday, September 8, 2012

Dual boot Windows 8 from a VHD file under Windows 7

Windows 8 has been available on MSDN for almost a month now. In addition, Windows 8 is now available to students under the Dreamspark program. At the moment, there are many among us who are using Windows 7 as our main operating system on our laptops and desktops. Some of us are willing to explore Windows 8 without necessarily losing our Windows 7 environment. A good way to accomplish this is to install Windows 8 as a VHD instance.

image

The assumption here is that you are installing Windows 8 on a computer that already has Windows 7.

Here are some advantages to using a VHD file to dual boot from:

  1. You can easily backup the VHD drive, thus backing up your entire Windows 8 operating system. It is particularly useful to do a backup of the VHD file right before installing a major piece of software that could potentially mess up your environment.
  2. You can move your VHD file from one computer to another.
  3. It acts exactly as if the Windows 8 operating is installed directly on a separate partition on your hard drive.
  4. You need not go through the pain of creating any additional partition on your hard drive.

Below are the steps you need to follow in order to accomplish this.

Steps for Installing Windows 8 in a VHD drive

  • Create a DVD (or bootable USB) from the ISO image that you obtained with Windows 8 on it.
    • To create a bootable USB from your ISO image, download a free utility from Microsoft at http://tinyurl.com/4qfdm4x.  Here’s what the download looks like:

image

    • To create a bootable DVD from your ISO image, place a blank DVD in the drive and simply double click on the ISO file. Windows 7 has a built-in application named “Windows Disk Image Burner”.

image

Alternatively, you can use any other application that is capable of burning a DVD from an ISO file. I recommend a freely available application named “imgburn” that I use and like.
  • Reboot your computer from the DVD (or USB). This may require you to get into the BIOS settings of your computer in order to rearrange the boot sequence of your various storage devices.

image

  • At the “Install Windows 8” screen, hit the Shift-F10 keys to open a command prompt.
  • When at the command prompt, type "diskpart <enter>". Wait until you see the command prompt “DISKPART >”.
  • In order to see a list of all available volumes, type "list volume <enter>". Identify the drive name that has ample available disk space which you want to install the VHD into. The drive letter will be under the column entitled “Ltr”.
  • In this example, we will create the VHD file on drive D:. Make sure to replace D: with the appropriate drive letter that fits your situation. You can create either a fixed or dynamic VHD file:
    • Creating a fixed VHD file: A fixed VHD file will allocate the entire maximum size that you set, regardless of whether or not the operating system uses that much space. Note that once you set a size, you cannot increase it in future, so make sure you are reasonably generous in choosing a maximum size. The following command assumes that you will be allocating a fixed VHD drive of 40GB (1GB = 1024 MB):
    • create vdisk file=D:\win8.vhd maximum=40960

      Note: In the command above, substitute D: with the drive letter that suits your situation. You can use any other name you like instead of win8.
    • Creating a dynamic expandable VHD file: A dynamic VHD file will initially be as large as the data used by the VHD. This can grow to the maximum size set when you create the VHD file. In the example below I will create a dynamic VHD drive that can grow to a maximum size of 40GB:
    • create vdisk file=D:\win8.vhd maximum=40960 type=expandable

  • Wait until the VHD drive has been 100% created. Next we need to select the VHD that was created. This is done by entering a command similar to the one below, depending on the drive letter and VHD file name you used:
  • select vdisk file=D:\win8.vhd
  • The next step is to attach to the VHD file. This is done with the the command:
  • attach vdisk
  • At this point we have done all that is necessary to create a VHD file and attach to it. We can now exit the DISKPART prompt. To do so, enter the following command:
  • exit

  • Close the command prompt window by clicking on the X located on the top-right-hand side of the window. We can now continue with the regular Windows 8 install.
  • Click “Next” on the “Windows Setup” dialog.

image

  • Click on the “Install Now” button on the next dialog.
  • The next dialog will ask you for your product key. Enter your product key and click “Next”.
  • Accept the license terms on the next dialog by clicking on the “I accept the license terms” checkbox then click on the “Next” button.
  • The next dialog will enable you to choose whether you want to do an upgrade or custom install. Since we want to install Windows 8 from scratch, we will choose the second option “Custom: Install Windows only (advanced)” by clicking on it.
  • The next window is very critical because it is at this point that you select the drive that will hold the new operating system. The primary manner by which you can identify this drive is by the size of the drive (I.E. in the case of this example it is 40GB) and the fact that it is still “Unallocated Space”.
    • Note that you run the risk of losing data if you choose the wrong drive.
    • Ignore the message “Windows can’t be installed on this drive. (Show details)

    Select the correct drive then click “Next”.

  • The rest is should proceed smoothly. When the installation is finished, Windows 8 will be set as the default operating system. You will, however, be given the option to boot into Windows 7 if you so desire.

Steps for removing the Windows 8 VHD

  • Boot into Windows 7
  • Find the Windows 8 VHD file on your hard drive
  • Delete the Windows 8 VHD file
  • Reboot the computer

Hope this is useful to you.

References:

Tutorial: Windows 8 VHD - Create at Boot to Dual Boot with

Monday, August 27, 2012

Uploading documents into SharePoint 2010 using OData

I experienced some pain when asked to develop a utility to upload documents into SharePoint 2010 using OData. Therefore, I naturally decided on this post in order to save others the pain I went through. This post explains how to do it using a simple client-side C# command-line application:

Step 1:

Create a C# command-line application in Visual Studio 2010 on the same box as your SharePoint 2010 server. Add a proxy to the SharePoint 2010 OData service on your server. This is done by right-clicking on your project “References” node and choosing “Add Service Reference …”.

image

The service that needs to be consumed is listdata.svc. Enter a URL similar to http://myserver/_vti_bin/listdata.svc then click on the “Go” button. Once the service is found, give the service NameSpace the name ListdataServiceReference.

Step 2:

I placed a text file named bogus.txt in the root of my c: drive with some arbitrary content. I also created a document library named BogusDocumentLibrary in the root site of my SharePoint server. Here is the upload() method code for uploading file c:\bogus.txt into the document library named BogusDocumentLibrary.

private static void upload() {
    string sharePointSvc = "
http://myserver/_vti_bin/listdata.svc";

    using (FileStream file = File.Open(@"c:\bogus.txt", FileMode.Open)) {
        ListdataServiceReference.HomeDataContext ctx
            = new ListdataServiceReference.HomeDataContext(new Uri(sharePointSvc));

       // ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;

        string username = "alice";
        string password = "wonderland";
        string domain = "myserver";

        ctx.Credentials = new System.Net.NetworkCredential(username, password, domain);

        string path = "/BogusDocumentLibrary/Bogus.txt";
        string contentType = "plain/text";
        ListdataServiceReference.BogusDocumentLibraryItem documentItem = new ListdataServiceReference.BogusDocumentLibraryItem()
        {
            ContentType = contentType,
            Name = "Bogus",
            Path = path,
            Title = "Bogus"
        };

        ctx.AddToBogusDocumentLibrary(documentItem);

        ctx.SetSaveStream(documentItem, file, false, contentType, path);

        ctx.SaveChanges();
    }
}

Needless to say, you must resolve the missing System.IO namespace.

Context
The name of the proxy class representing your context is named depending on your site’s name. In my case, my site is named home so the proxy context class is HomeDataContext.

Credentials
If you are accessing the service on the same box or domain as the server then it suffices that you pass on the default credentials with “System.Net.CredentialCache.DefaultCredentials”. Otherwise, if you are on a different domain then you should use the technique described in the code above where the username, password, and domain with access rights to the SharePoint site are passed on to the server.

Document Properties
The item proxy class name that represents the document library depends on the name given to it. In my case, I named the document library BogusDocumentLibrary so the item proxy class name is BogusDocumentLibraryItem. Once an instance of this class in instantiated then the various properties such as ContentType, Name, Path, and Title must be set.

Upload document
Finally, these three lines are responsible for uploading the document:

ctx.AddToBogusDocumentLibrary(documentItem);
ctx.SetSaveStream(documentItem, file, false, contentType, path);
ctx.SaveChanges();

Finally, you can call the upload() method from within your main method and it should all work as long as the appropriate server, text file, and document library exist.

Thursday, July 26, 2012

Northwind-mania: Upgrading Northwind.mdf database file from SQL Server 2005/2008 to LocalDB\v11.0

Visual Studio 2012 comes with a new small light-weight database named LocalDB\v11.0. You can find out the default database used by Visual Studio 2012 by checking out TOOLS >> Options… >> Database Tools >> Data Connections:

image

If you have a SQL2005 or SQL2008 database and wish to use it in a Visual Studio 2012 application, you should upgrade it to LocalDB\v11.0 format. Here’s what I did when I came across this predicament. I used the usual Northwind.mdf SQL2008 database for this post.

- In Visual Studio 2012  “Server Explorer”, right-click on “Data Connections” and select “Add Connections…”

image

- Click the “Change…” button on the “Add Connection” dialog:

image

- Choose “Microsoft SQL Server Database File” then click OK. You will be returned to the “Add Connection” dialog.

image

- Navigate to the location of your Northwind.mdf file by clicking the “Browse…” button, then click OK.

image

- Visual Studio 2012 will detect that the database is not of LocalDB\v11.0 format and will display this message:

image

- Click “Yes” so that your SQL200x database gets upgraded to LocalDB\v11.0. Upon completion of the upgrade process you will be able to view all your database objects in Server Explorer:

image

Hope this helps.

Tuesday, July 24, 2012

Northwind-mania: Read Northwind oData into a Windows 8 Metro Style C# / XAML application

Once again I will use the well known Northwind database. This time I will demonstrate how easy it is to render an oData feed originating from http://services.odata.org/Northwind/Northwind.svc.

Pre-requisites:

  • Windows 8 Release Preview
  • Visual Studio 2012 RC

Step 1:

In Visual Studio 2012 RC, start a new project as follows:

FILE >> New Project … >> Visual C# >> Windows Metro Style >> Blank App (XAML)

Name the application “Win8ReadOdata” then click OK.

image

Step 2:

We will retrieve data from an oData source at odata.org. In “Solution Explorer”, right-click on References and select “Add Service Reference…”. Enter the address http://services.odata.org/Northwind/Northwind.svc then click on the “Go” button. After the service is found, give the Namespace the name “NorthwindServiceReference” then clock OK.

image

At this point a proxy to the service is created for us.

Step 3:

Open the “MainPage.xaml” document and paste the following XAML code inside of the “Grid” element:

<StackPanel Background="Transparent" VerticalAlignment="Center" x:Name="fullMode" >
        <ListBox Name="categoriesList" Margin="40" Foreground="Blue" Background="Transparent" Height="500">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="100,0,0,10" VerticalAlignment="Center" Orientation="Horizontal" >
                        <TextBlock Text="{Binding CategoryID}" Margin="10,0,0,0" FontSize="26" VerticalAlignment="Center" Foreground="Green"/>
                        <TextBlock Text="{Binding CategoryName}" Margin="10,0,0,0" FontSize="22" VerticalAlignment="Center" Foreground="Red"/>
                        <TextBlock Text="{Binding Description}" Margin="10,0,0,0" FontSize="22" VerticalAlignment="Center"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</StackPanel>

The above markup produces a listbox control that will hold records from the “Categories” table in the Northwind database. We will display the CategoryID, CategoryName, and Description database columns in Green, Red, and Blue colors respectively just so that they are easily distinguishable.

Step 4:

Place the following declaration in MainPage.xaml.cs just before the constructor:

NorthwindEntities ctx = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));

You may need to resolve the NorthwindEntities class.

Put the following code inside the constructor just after this.InitializeComponent().

LoadCategoriesThruOData();

Add these methods to the MainPage.xaml.cs:

private async void LoadCategoriesThruOData()
{
    var results = await Task<IEnumerable<Category>>.Factory.FromAsync(ctx.Categories.BeginExecute(AnotherEndContinuation, ctx), ContinuationDelegate);

    // This fires only after we have a response back.
    this.ParseAndBindData(results);
}

Func<IAsyncResult, IEnumerable<Category>> ContinuationDelegate = EndContinuation;
private static IEnumerable<Category> EndContinuation(IAsyncResult result)
{
    NorthwindServiceReference.NorthwindEntities client = (NorthwindServiceReference.NorthwindEntities)result.AsyncState;
    return client.Categories.EndExecute(result);
}

private static void AnotherEndContinuation(IAsyncResult result)
{
    // Do nothing here.
}

private void ParseAndBindData(IEnumerable<Category> results)
{
    categoriesList.ItemsSource = results;
}

The LoadCategoriesThruOData()  method is responsible for making an async call to the oData service. The ParseAndBindData() method is called once data is successfully received.

After resolving some missing namespaces, run the application by hitting F5. The result should look like this:

image

In future posts I will extend this application with abilities to insert, update, and delete data.

Friday, July 6, 2012

Registered Community Speaker with INETA

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:

INETA Community Speakers Program

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 …”.

image

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.

image

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.

image

image

Ensure that the jQuery, DataJs and KnockoutJs libraries are installed into your project under the Scripts folder as shown below:

image

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:

image

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.

image

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);
}