DCSIMG
December 2010 - Posts - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

December 2010 - Posts

Installing a Production Server for ASP.NET MVC 2

Installing a Production Server for ASP.NET MVC 2

Two days ago I was asked to help with a production server installation. Installing a Production Server for ASP.NET MVC 2In the customer environment they built an ASP.NET MVC 2 application which they wanted to deploy. I found a very excellent post that Jon Galloway wrote about this subject and used it in at customer. In the post I’ll summarize some of the options that I used when we installed the production server for ASP.NET MVC 2

Web Platform Installer

I wrote about the WebPI in the past. This option is the best option for installing all the server components and not only ASP.NET MVC. It will require that you have a desktop access to the server (remote connection or direct access). At the customer this option didn’t work. For some reason the installation asked that a Visual Studio 2008 SP1 will be installed on the server. Since it is a production server the existence of VS is not necessary.

Bin Deployment

In this option you deploy all the MVC assemblies within your application. Phil Haack wrote about this option and you can explore his post from here. I didn’t like this option since I preferred that the server will have the relevant assemblies installed in it. Since there are other MVC applications in develop which will be hosted in the customer’s server we didn’t choose this option at the end (although they used it in the first place) .

AspNetMVC2 MSI installer

In this option you can download the installer for the ASP.NET MVC 2 and install it. Running the installer will install the MVC runtime along with MVC tooling. At the customer the MSI produced the same error that the WebPI raised. What we did was to open the MSI package and install only the runtime environment. To achieve that you can run from command line the following instruction:
AspNetMVC2_VS2008 /x:[your directory name] 
After the MSI will open to the directory you wrote go to the mvcruntime directory and run the installation of the runtime. After doing that the MVC runtime was installed on the production server.

Summary

Lets sum up, I gave few options for installing a server for ASP.NET MVC deployment. The best way is to use the WebPI but at the customer we didn’t have this privilege. I encourage you to read what Jon Galloway wrote in his post since it really help me.

Sela College Channel (Beta) is Broadcasting

Sela College Channel (Beta) is Broadcasting

My company Sela has created a project which is on air currently. Sela College Channel (Beta) is BroadcastingSela infrastructure team created an internet broadcasting channel which will broadcast content about topics related to computers (focusing on development and testing). In the channel you can watch sessions from open houses we conduct, sessions that were taken from courses that Sela deliver, experts sessions, conferences sessions and more. Also, you can register to the channel and upload your own content which will then be a part of the channel library. In the channel there are currently 156 sessions (the majority content is in Hebrew) which you can watch. I encourage you to take a look at the channel:

Enjoy!

EF Feature CTP5: Inheritance Scenarios with Code First Fluent API

EF Feature CTP5: Inheritance Scenarios with Code First Fluent API

One of the interesting features of Code First fluent API is the ability EF Feature CTP5: Inheritance Scenarios with Code First Fluent APIto configure inheritance in your model. Since one of the strengths of an O/RM solution is its ability to map inheritance then this feature is a must in every mapping scenario (may it be Model first, Database First or Code First). In this post I’ll show how to configure inheritance by using the fluent API.

Revisiting Entity Framework Inheritance Types

In the past I wrote a series of posts about inheritance mapping in Entity Framework which you can read here:

Configure Inheritance Using Code First Fluent API

In the previous CTPs in order to create inheritance we had to use the MapHierarchy method which was very tedious. In this version the MapHierarchy method was replaced by the Map method (and not in all the inheritance mapping scenarios you’ll need to use it). Lets explore the inheritance types:

Table per type (TPT) inheritance
In order to create this type of mapping all you have to do is to use the ToTable method:

public class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  public string Title { get; set; }
  public string Days { get; set; }
  public DateTime Time { get; set; }
  public string Location { get; set; }
  public int Credits { get; set; }    
 
  #endregion
}
 
public class OnLineCourse : Course
{
  #region Properties
 
  public string CourseURL { get; set; }
 
  #endregion
}
 
public class SchoolEntities : DbContext
{
  #region Properties
 
  public DbSet<Course> Courses { get; set; }
 
  #endregion
 
  #region Methods
 
  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Course>()
      .ToTable("Courses");
 
    modelBuilder.Entity<OnLineCourse>()
     .ToTable("OnLineCourses");
  }
 
  #endregion
}

You start with creating the inheritance in the model itself (OnLineCourse inherit from Course) and then in the DbContext’s OnModelCreating method you specify that every type will be mapped to its own table using the ToTable method.

Table per hierarchy (TPH) inheritance
In order to create this type of mapping you need to use the Map method. In the lambda the Map method gets you write the discriminator field and its values using the Requires and HasValue methods. In the following example you can see how to do exactly that:

public class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  public string Title { get; set; }
  public string Days { get; set; }
  public DateTime Time { get; set; }
  public string Location { get; set; }
  public int Credits { get; set; }    
 
  #endregion
}
 
public class OnLineCourse : Course
{
  #region Properties
 
  public string CourseURL { get; set; }
 
  #endregion
}
 
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<Course>()
    .Map(c =>
    {
      c.Requires("Discriminator").HasValue(1);
    })
    .Map<OnLineCourse>(olc =>
    {
      olc.Requires("Discriminator").HasValue(2);
    });
}

Table per concrete type (TPC) inheritance
In order to create this type of mapping you will start as it is a table per type inheritance configuration. The only change is the use of the Map method on the concrete type. In the method lambda you will use the MapInheritedProperties method to indicate it is a concrete type:

public class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  public string Title { get; set; }
  public string Days { get; set; }
  public DateTime Time { get; set; }
  public string Location { get; set; }
  public int Credits { get; set; }    
 
  #endregion
}
 
public class OnLineCourse : Course
{
  #region Properties
 
  public string CourseURL { get; set; }
 
  #endregion
}
 
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<Course>()
    .ToTable("Courses");
 
  modelBuilder.Entity<OnLineCourse>()
   .Map(olc =>
   {
     olc.MapInheritedProperties();
   }).ToTable("OnLineCourses");
}

Here is a simple check to see how the database is created in each inheritance type:

using (SchoolEntities context = new SchoolEntities())
{
  context.Database.Delete();
  var course = new Course
  {          
    Credits = 2,
    Days = "MF",
    Location = "Class 1",
    Time = DateTime.Now,
    Title = "Entity Framework",
  };
  var onLineCourse = new OnLineCourse
  {          
    Credits = 3,
    Days = "WT",
    Location = "Class 2",
    Time = DateTime.Now,
    Title = "Entity Framework On Line",
    CourseURL = "http://www.gilfink.net",
  };
  context.Courses.Add(course);
  context.Courses.Add(onLineCourse);
  context.SaveChanges();

Pay attention that in the TPC inheritance the database will be created properly and the insert will succeed but there will be an exception of overlapping keys (both courses will be created with CourseID of 1 and in the context there will be overlapping).

Summary

Using the Code First fluent API for inheritance is easy. In the post I showed how you can do that using the three main inheritance scenarios in Entity Framework.

Using EF DbContext with WCF Data Services

Using EF DbContext with WCF Data Services

One of the questions that you may ask yourself with the new EF feature CTP5 is how Using DbContext with WCF Data Servicesto embed the new DbContext object inside an OData service or more particularly inside WCF Data Service. This post will supply the solution.

DbContext as WCF Data Service Data Source

Entity Framework has a good integration with WCF Data Services. All you need to do when you create a WCF Data Service with EF is to put the generated ObjectContext as a data source of the service. The following code is a simple WCF Data Service on top of EF ObjectContext:

public class SchoolDataService : DataService<SchoolEntities>
{
  public static void InitializeService(DataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
 
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  }
}

When you will try to do the same with DbContext you will get a surprise. The service will run but when you will try to query the data it expose you will get an error like the following:
The XML page cannot be displayed 
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later. 
 
 
--------------------------------------------------------------------------------
 
The following tags were not closed: feed. Error processing resource 'http://localhost:29753/SchoolDataService.svc/Courses'. 
 
 

The reason for the error is because currently DbContext and WCF Data Services integration isn’t working well. So what can we do for now?
Since the DbContext is a wrapper for the ObjectContext we can expose the ObjectContext itself. In order to do that you will have to override the CreateDataSource method of the service and return the ObjectContext. The following example shows a simple WCF Data Service that uses the DbContext I’ve created in the previous post about EF Feature CTP fluent API:

[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class SchoolDataService : DataService<ObjectContext>
{
  public static void InitializeService(DataServiceConfiguration config)
  {
    config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
 
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
  }
 
  protected override ObjectContext CreateDataSource()
  {     
    var context = ((IObjectContextAdapter)new SchoolEntities()).ObjectContext;      
    context.ContextOptions.ProxyCreationEnabled = false;      
    return context;    
  }    
}

A few things to notice:

  • In the CreateDataSource I cast the DbContext to an interface it implements – IObjectContextAdapter. This interface exposes an ObjectContext property which is the underling context wrapped by the DbContext.
  • You must disable proxy creation because in service scenarios you mustn’t use the change tracking and lazy loading behaviors that are created through runtime proxies.

Summary

DbContext integration with WCF Data Services isn’t supported currently. In order to have a working workaround for that you can use the underling ObjectContext which the DbContext wrap. Hopefully that in the near future this workaround won’t be needed and we will have integration out of the box.

EF Feature CTP5: Raw SQL Query/Command Support

EF Feature CTP5: Raw SQL Query/Command Support

One of the new features that EF feature CTP5 supplies is the support for raw EF Feature CTP5: Raw SQL Query/Command SupportSQL Query/Command through the DbContext. In this post I’m going to show you examples for how you can use this feature. Pay attention that the details I provide might change in the future since its only a CTP and not a release.

DbContext Raw SQL Query/Command Support

EF feature CTP5 supports the execution of raw SQL queries and commands through the DbContext. This behavior resembles the ObjectContext’s same functionality that is exposed by the ExecuteStoreQuery<T> and ExecuteStoreCommand methods. You can use the DbContext's SqlQuery and SqlCommand methods which are exposed by the DbContext.Database property. The results of the method executions can be materialized into entities that can be tracked by the DbContext. Here is an example of how to use these methods:

static void Main(string[] args)
{
  using (SchoolEntities context = new SchoolEntities())
  {
    IEnumerable sqlQuery = context.Database.SqlQuery<Department>("select * from department");
    foreach (Department item in sqlQuery)
    {
      Console.WriteLine(item.Name);
    }
 
    sqlQuery = context.Database.SqlQuery<Course>("GetCoursesOrderByTitle");
    foreach (Course item in sqlQuery)
    {
      Console.WriteLine(item.Title);
    }
 
    var numberOfAffectedRows = context.Database.SqlCommand("DeleteDepartment @DepartmentID", new SqlParameter("DepartmentID", 9));
    Console.WriteLine("Number of affected rows: {0}", numberOfAffectedRows);
  }
}
In the program, that is using the same model from my previous example, I’m executing two queries (one is raw Sql and the other is using a stored procedure) and one command. The result of the execution:
Running Result

Summary

Lets sum up, the new CTP enables the running of raw Sql queries/commands. This can be very useful in scenarios that aren’t enabled by EF or advanced scenarios.

Building N-Tier Applications Using Entity Framework 4 Session Recording

Building N-Tier Applications Using Entity Framework 4 Session Recording

The recordings from the Teched were published yesterday.
Building N-Tier Applications Using Entity Framework 4 RecordingIf you want to see my session about Building N-Tier Applications Using Entity Framework 4 (in Hebrew) you can go to this link.

Enjoy!

EF Feature CTP5 – Code First Fluent API

EF Feature CTP5 – Code First Fluent API

One of Code First main features is the Fluent API. EF Feature CTP5 – Code First Fluent APIThis API can help you to configure the model in order to shape it (and the database) better. In this post I’m going to show a simple example for how to use the Fluent API. Pay attention that the details I provide might change in the future since its only a CTP and not a release.

The Example Model

In the example I’m going to use the following model:

public class SchoolEntities : DbContext
{
  #region Properties
 
  public DbSet<Course> Courses { get; set; }
  public DbSet<Department> Departments { get; set; }
 
  #endregion
 
  #region Methods
 
  protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
  {
    base.OnModelCreating(modelBuilder);
 
    // put here the fluent code
  }
 
  #endregion
}
 
public partial class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  public string Title { get; set; }
  public string Days { get; set; }
  public DateTime Time { get; set; }
  public string Location { get; set; }
  public int Credits { get; set; }
  public int DepartmentID { get; set; }
 
  public virtual Department Department { get; set; }
 
  #endregion
}
 
public class Department
{
  #region Properties
 
  public int DepartmentID { get; set; }
  public string Name { get; set; }
  public decimal Budget { get; set; }
  public DateTime StartDate { get; set; }
  public int Administrator { get; set; }
 
  public virtual ICollection<Course> Courses { get; set; }
 
  #endregion
}

Fluent API Example

After you create your model there are a lot of ways to configure the model using the Fluent API. The main place to do that is in the OnModelCreating method which you override in the DbContext. That method gets a ModelBuilder instance which can be used to configure the model. The following example shows how to write some configuration with the API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  base.OnModelCreating(modelBuilder);
 
  modelBuilder.Entity<Department>().
    Property(d => d.Name).
    IsRequired().
    HasMaxLength(50);
 
  modelBuilder.Entity<Department>().
    Property(d => d.DepartmentID).
    HasDatabaseGenerationOption(DatabaseGenerationOption.None);
 
  modelBuilder.Entity<Department>().
    HasMany(d => d.Courses).
    WithRequired(c => c.Department).
    HasForeignKey(c => c.DepartmentID).
    WillCascadeOnDelete();
 
  modelBuilder.Entity<Department>().
    Ignore(d => d.Administrator);
 
  modelBuilder.Entity<Course>().
    Property(c => c.Title).
    IsRequired().
    HasColumnName("Name");      
}

What is Configured?

Lets explain what you see in the above code. When I want to configure an entity I use the Entity method with the entity as a generic parameter. Then I’m exposed to the Fluent API and can start configure my model.
In the first line I configure the Name property of the department as required and with length of no more than 50 characters.
In the second line I configure the DepartmentID as non database generated (since by default all the ID will be database generated).
The third line creates a one to many relation between the department and its course collection. You first use the HasMany to indicate the many side and then use the WithRequired to indicate the one side of the relation. The HasForeignKey indicate the foreign key on the many side. The last method, WillCascadeOnDelete, will add cascade delete on the entity graph.
The forth line will force the model to ignore the administrator property of the department and therefore it won’t be generated in the database.
The fifth line indicates that the Title property is required and that in the database the column name will be Name instead of Title.
Here is a simple example of creating data and inserting it to the database:

class Program
{
  static void Main(string[] args)
  {
    using (SchoolEntities context = new SchoolEntities())
    {
      var department = new Department
      {
        DepartmentID = 1,
        Administrator = 2,
        Budget = 100000,
        Name = "Data Access",
        StartDate = DateTime.Now
      };
      var course = new Course
      {
        Credits = 2,
        Days = "MF",
        Location = "Class 1",
        Time = DateTime.Now,
        Title = "Entity Framework",
        Department = department,
      };
      context.Departments.Add(department);
      context.SaveChanges();
    }
  }
}

Running this example will generate a new database by the name ClassLibrary1.SchoolEntities with all the configurations that were written in the OnModelCreating method. If you want to change the generated database name (which is taken from the namespace and context name by default) you need to create a constructor to the DbContext with a call for the base constructor that gets a string as parameter:

public SchoolEntities() :
      base("MySchool")
    {
 
    }

The resulting database:
Database

Summary

Lets sum up, Code First has a very interesting feature of fluent API. The fluent API for model configuration is easy to understand and use. In this post I showed and explain a small portion of the API.

EF Feature CTP5 – Walkthrough For The New DbContext T4 Template

EF Feature CTP5 – Walkthrough For The New DbContext T4 Template

One of the new features in the EF Feature CTP5 that was released yesterday was a new T4 template forEF Feature CTP5 – New T4 Template for DbContext generating DbContext instead of ObjectContext. In this post I’m going to explain what is the new DbContext and then show how to use the new T4 template. Pay attention that the details I provide might change in the future since its only a CTP and not a release.

What is DbContext?

The DbContext is a new lightweight context that was created and provided within the EF Feature package. The DbContext is a wrapper for the ObjectContext (it doesn’t inherit from it). Since not in all development scenarios we need the full feature list of the ObjectContext, the DbContext can help us by exposing only the common functionality that we need. It includes some additional features for our disposal such as OnModelCreating extension point.

Using DbContext T4 Template

In order to use the new T4 template for DbContext you start with your model. The model can be created with the Database First approach or with the Model First approach. The model I’m going to use is the following:
Entity Designer Diagram

When you want to use the T4 template, from the designer surface you will press the right mouse button and press the Add Code Generation Item menu item.Add Code Generation Item

From the Add New Item window choose the new ADO.NET DbContext Generator and give the model an appropriate name:Add New Item
After pressing the Add button two new files will be created and a reference to the new EntityFramework.dll will be added:
Solution Explorer

The first file (SchoolModel.Context.tt) will contain the DbContext and the second file (SchoolModel.tt) will contain the entities. Now you can start coding against the DbContext. In the following example I query the database using the DbContext to find the department with id of 1:

class Program
{
  static void Main(string[] args)
  {
    using (SchoolEntities context = new SchoolEntities())
    {
      var query = context.Departments.Find(1);
      Console.WriteLine("{0} has a DepartmentID of 1", query.Name);
    }
  }
}

The result of the query:
Result

Summary

You can expect that the EF ecosystem will continue to grow. The new feature CTP adds more functionality for our disposal. One of these features is the new DbContext and also its new T4 template.

Entity Framework Feature CTP5 Released

Entity Framework Feature CTP5 Released

Yesterday, ADO.Net team released the EF feature CTP5. Entity Framework Feature CTP5 ReleasedThe feature CTP contains new features for Entity Framework that are planed to be shipped as a stand alone package in the first quarter of 2011. The main feature in the package is Code First which allows you to define your model using C# or VB.Net classes only. This approach will be added to the previous EF approaches: Model First and Database First to form a better framework for common data access development scenarios. Other features are the lightweight DbContext and DbSets objects, T4 template for generating DbContext and DbSets, Fluent API for Code First that can be used for further configurating of a model and more.
You can download CTP5 from here.

Enjoy!

How to Separate Self-Tracking Entities to Their Own Class Library

How to Separate Self-Tracking Entities to Their Own Class Library

Last week I had a session in Teched Israel 2010 which included approaches for building N-Tier applications on top How to Separate Self-Tracking Entities to Their Own Class Libraryof Entity Framework 4 as the data access technology. During the session I showed an example of how to use the new Self-Tracking Entities (STE) feature. In this post I‘m going to show how easy it is to put the STE in a different class library as a jump start for using this T4 Template in N-Tier scenarios.

What is Self-Tracking Entities?

In EF4 a new feature was introduced – the Self-Tracking Entities (STE). The STE are simple entities that track their own changes instead of EF’s ObjectContext. Every entity implement the IObjectWithChangeTracker interface and has a ChangeTracker property that exposes the tracking mechanism. Using STE enables you to use EF in N-Tier scenarios and gain the ability to track changes on the client side. This of course indicate that we will need a dependency on these entities on the client side (and that we will lose interoperability). In order to do that you will need to separate the entities from the data access layer and to put them in their own class library.

Separating Self-Tracking Entities to Their Own Class Library

You start with two empty class libraries – one for he data access layer and the second for the entities that we are going to generate:
Empty Class Libraries

First create your Entity Framework model in the STEDAL class library. In the EF designer surface use the Add Code Generation Item in order to pick the Self-Tracking Entities T4 Template from the T4 Template options:

Add Code Generation Item

Self-Tracking Entity Generator

Now the STEDAL will look like:

After using STE T4 template

Pay attention that you have two different tt files. The first one (SchoolModel.Context.tt) holds the context and the second one (SchoolModel.tt) holds the entities. The reason for the separation is obvious – to enable you to move the entities to their own class library.
The next step is to cut and paste the entities to the STEEntities class library. When you do that pay attention that you will need to add a reference to System.Runtime.Serialization since the STE use WCF data contracts for serialization. Also you will need to add a reference from the STEDAL to the STEEntities.

STE Class Library

Now we need a simple fine tuning in the T4 template itself. Open the T4 template and at the head of the template locate the following line:

string inputFile = @"SchoolModel.edmx";

This line indicate where is the location for the edmx file. You will want to change it to a relative path to the real location of the edmx file for example:

string inputFile = @"../STEDAL/SchoolModel.edmx";

The reason for doing that is That the STE need the Entity Data Model in order to work properly when we do data access operations.
The last step in the process is to put the context (or the entities if you prefer the opposite) in the same namespace as the entities. This can be achieved by using the SchoolModel.Context.tt file Custom Tool Namespace property. Put the STEEntities there and you finished:

Custom Tool Namespace

Now you can build the solution and start using the libraries.

Summary

Lets sum up, when you want to use the new Self-Tracking Entities feature the first thing to do will be to move the entities to their own class library. The process is very simple and in this post I showed you how to do exactly that.

Quick Tip – HTML5 Intellisense For Visual Studio 2010

Quick Tip – HTML5 Intellisense For Visual Studio 2010

This is something I learnt recently in a meeting with Pete LePage. Mikhail Arkhipov from Microsoft has published a HTML 5 Intellisense add-in for Visual Studio 2010 and 2008.
You can download the add-in from here.
After you install the add-in you can start using HTML5 intellisense by picking its validation schema first:
Picking HTML5

Then you’ll have your intellisense validation schema working and you will be able to use it in order to write HTML5 web pages.
For example in the following images I use the new HTML5 video tag with this intellisense:
Video Intellisense

Video with controls

Since this tool is currently experimental there are a few limitations that comes with it so don’t expect to get all the support for HTML5.

Enjoy!