Skip to content

.NET Native – Make your Windows store apps start up to 60% faster – Part 2

The .NET Native developer preview installs on top of Visual Studio 2013 Update 2 RC.

Compiling your project in .NET Native mode

After your project is loaded, make sure you have configured your app to compile to a specific architecture like x86 or ARM. .NET Native compiles to native code, so you need to target a real machine type instead of Any CPU. There are couple of ways to do this.

  1. The solution property page.
  2. In the handy drop down in the toolbar (next to debug/release drop down)

Once you’ve selected a supported machine type you’re ready to enable your project for .NET Native compilation. Right-click on the project name and you’ll see the “Enable for .NET Native” option has appeared. (OK, it was always there, but if you selected it without selecting x64 or ARM you’d get an error.)

Selecting this actually causes a few things to happen. First, it creates a new file for your project called “default.rd.xml”. This file contains runtime directives that help the .NET Native compiler understand what metadata and type information needs to be preserved in order for your app to run correctly, so things like reflection mostly just work, even though you are statically compiling everything!

Second, selecting “Enable for .NET Native” builds your app. Visual Studio will also run a static analysis tool on your app to give a quick read on whether you are using any feature that’s not yet in the preview release. This will generate a “.NET Native Code Generation Compatibility Report” that will pop up with information about your app. Also, you can always rerun the static analysis from your project’s context menu.

If your app is like most Store apps, you’ll see this in the Compatibility Report, meaning you’re ready to test your app thoroughly with .NET Native.

If your app uses many complicated patterns or yet to be implemented features (e.g., WCF), you might instead get some workarounds and guidance.

.NET Native Resources

.NET Native – Make your Windows store apps start up to 60% faster

Microsoft announced ty he first release of .NET Native. The major advantage of .NET Native Apps being able to start up to 60% faster and have a much smaller memory footprint. This first developer preview allows you to develop and test apps with this new compiler and offers you the C++ performance with the productivity of C# enabling best of both worlds.

This developer preview currently enables building apps for Windows Store on ARM & x64 architectures. Today’s preview supports Windows Store applications. It will continue to evolve and improve native compilation for the range of .NET apps.

.NET Native continues to provide first-class .NET developer experience in Visual Studio. You will get a great edit/compile/debug environment with productivity enhancements like Edit & Continue and code refactoring. You continue to upload MSIL apps package to Windows Store. Microsoft Compiler on the cloud compiles the app using .NET Native in the Store, self-contained app package that’s customized to the device where the app is installed.

Some of the most popular Windows Store apps on Surface devices are already running on .NET Native. This includes applications such as Wordament and Fresh Paint, which are seeing multi-second startup wins.

Download the .NET Native developer preview

Going Deep Channel 9 Video on .NET Native

Await my next article on Getting Started with .NET Native soon.

Entity Framework: There is already an open DataReader associated with this Command

“There is already an open Datareader associated with this Command” error message is often caused by iterating through a resultset while trying to open another result set.

 This error can be fixed by enabling Multiple Active Result Sets (MARS) in your Entity Framework Connection String. How to enable the same in a bit.

 Multiple Active Result Sets (MARS) is a feature that works with SQL Server to allow the execution of multiple batches on a single connection. When MARS is enabled for use with SQL Server, each command object used adds a session to the connection.

 Note: A single MARS session opens one logical connection for MARS to use and then one logical connection for each active command.

Enabling and Disabling MARS in the Connection String

The MARS feature is disabled by default. It can be enabled by adding the “MultipleActiveResultSets=True” keyword pair to your connection string. “True” is the only valid value for enabling MARS. The following example demonstrates how to connect to an instance of SQL Server and how to specify that MARS should be enabled.

string connectionString = “Data Source=MSSQL1;” +
“Initial Catalog=AdventureWorks;Integrated Security=SSPI;” +
“MultipleActiveResultSets=True”;

Alternative to MARS

Alternatively to using MARS (MultipleActiveResultSets) you can write your code so you dont open multiple result sets.

What you can do is to retrieve the data to memory, that way you will not have the reader open. It is often caused by iterating through a resultset while trying to open another result set.

Lets say you are doing a lookup in your database containing these:

We can do a simple solution to this by adding .ToList() like this:

var largeBlogs = context.Blogs.Where(b => b.Posts.Count > 5).ToList();

This forces entityframework to load the list into memory, thus when we iterate though it in the foreach loop it is no longer using the data reader to open the list, it is instead in memory

I realize that this might not be desired if you want to lazyload some properties for example. This is mostly an example that hopefully explains how/why you might get this problem, so you can make decisions accordingly.

Enabling Internationalization (i18n) in ASP.NET MVC 3 or ASP.NET MVC 4 using Resource Files

If you have an MVC 3 or MVC 4 application and you want to enable Internationalization in your application, you have few common places where you might want to do that:

1. Display Names in models – These typically appear as labels in a view for the model when we use @Html.LabelFor extension method.

2. Validation error message in models – These are validation error messages like "xxxxx field is required", "password length should not exceed {n} characters" etc.

3. Normal labels in your views

Before jumping into enabling i18n in your application there are some initial steps that needs to be followed.

1. Create one or more resource files as required by your application. For the article, let’s name the resource files as MyTestResource.resx and MyTestResource.ES.resx (Spanish language resource)

2. It’s recommended in a MVC application not to use normal resource folders like App_GlobalResources, App_LocalResources.

3. You can probably create a "Resources" folder with your required resources files.

4. Once your resource files are created, you need to change the few properties of the resource file viz. "Build Action" to "Embedded Resource" and "Custom Tool" to "PublicResXFileCodeGenerator" as shown in the screenshot below.

image

5. Repeat the above steps for all the resource files in your application.

Now that, we have the resource files in place, we can start replacing the English hard coded labels and error messages with the resource names in the label. To do this, I am going to take a small model which is used for registering new users into any application.

    public class RegisterExampleModel
    {
        [Required]
        [Display(Name = "User name")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Password is required")]
        [StringLength(100, ErrorMessage = 
            "The {0} must be at least {2} "+ 
            "characters long", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", 
            ErrorMessage = "The password and " + 
            "confirmation password do not match")]
        public string ConfirmPassword { get; set; }
    }

Internationalizing the Model

As you can see in our RegisterExampleModel, we have display name, error messages hard coded and is available only in English. The main advantage of doing internationalization in the model is that, these resource files will be ones that will be used when you use LabelFor and ValidationMessageFor @Html.LabelFor(m => m.UserName) or @Html.ValidationMessageFor(m => m.UserName).

Internationalizing display names in the model

Let’s discuss about changing display names in the models. Display names are very easy to replace in models. To do this, add an entry in the resource files say "resUsername" as the name and Value as your English text. Do the same in your other language resource files lets say Spanish and give the value as your Spanish translation for username.

Username in English Resource file

clip_image001

Username in Spanish Resource file

clip_image001[8]

Once you done this all your resource files, now let’s update the model code to use the value in the resource file rather than hard coded English text.

[Display(Name = "resUsername", 
    ResourceType = typeof(MyTestResource))]

The resUsername is the name of our resource in our resource file and the ResourceType points to MyTestResource resource file.

You can also repeat the same for Password and Confirm Password display names that we have in our model.

Internationalizing error messages in the model

For all the error messages that you have in the model, create resource file entries. Once this is done, we need to update the model. Updating models for the error messages are slightly different from what we did with the display names above.

All the model validation annotations comes with an optional parameter of NamedParameters. We are going to use this NamedParmeters for internationalizing our error messages in the model using two named parameters viz. ErrorMessageResourceName and ErrorMessageResourceType.

To use the resources that we have created in the Required annotation of the password field, we change the existing annotation which is

[Required(ErrorMessage = "Password is required")]

to

[Required(ErrorMessageResourceName = "resPasswordRequired",
    ErrorMessageResourceType = typeof(MyTestResource))]

Once we accomplish this for all the error messages our model might look like this.

public class RegisterModel
{
    [Required]
    [Display(Name = "resUsername", 
        ResourceType = typeof(MyTestResource))]
    public string UserName { get; set; }

    [Required(ErrorMessageResourceName = 
        "resPasswordRequired",
        ErrorMessageResourceType = typeof(MyTestResource))]
    [StringLength(100, ErrorMessageResourceName = 
        "resPasswordError",
        ErrorMessageResourceType = 
        typeof(MyTestResource), 
        MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", 
        ErrorMessageResourceName = "resConfirmPasswordError",
        ErrorMessageResourceType = typeof(MyTestResource))]
    public string ConfirmPassword { get; set; }
}

Using resources files in your Views

Now that we done with internationalizing the model, let’s do it for normal labels and error messages that you will be using in your views.

Let’s assume you have some header which have hard coded English text like below in your view.

<hgroup class="title">
    <h1>Register</h1>
    <h2>Create New Account</h2>
</hgroup>

Create a resource file entries for English text Register and Create New Account and let’s call it say resRegister and resCreateNewAccount respectively.

Now replace the hard coded English text with respective resource names

<hgroup class="title">
    <h1>@MyTestResource.resRegister</h1>
    <h2>@MyTestResource.resCreateNewAccount</h2>
</hgroup>

I think this article gives you an exhaustive list of steps to add internationalization to your application.

Please do add your comments of how else would you like to internationalize your application and I can see if either I can update this article or create a new one.

await, WhenAll, WaitAll

If you have worked on asynchronous operations in .NET, its more probable that you have used Task class for wrapping asynchronous class. Although this class was officially introduced in .NET 4.0, the programming model for consuming tasks was much more simplified in C# 5.0 in .NET 5.0 with the addition of the new async/await keywords. In a nutshell, you can use keywords to make asynchronous calls as if they were sequential, and avoiding in that way any fork or callback in the code. The compiler takes care of the rest.

var allResults = new List<Result>();
foreach(var provider in providers)
{
  var results = await provider.GetResults();
  allResults.AddRange(results);
}
return allResults;

You see, the above code was using the await keyword to make multiple calls in parallel. Something the code did not consider was the overhead this code implied after being compiled.

There are two additional methods you can use to wait for the results of multiple calls in parallel, WhenAll and WaitAll.

WhenAll creates a new task and waits for results in that new task, so it does not block the calling thread. WaitAll, on the other hand, blocks the calling thread.

class Program
{
    private static Func<Stopwatch, Task>[] funcs = new Func<Stopwatch, Task>[] { 
        async (watch) => { watch.Start(); await Task.Delay(1000); 
            Console.WriteLine("1000 one has been completed."); },
        async (watch) => { await Task.Delay(1500); 
            Console.WriteLine("1500 one has been completed."); },
        async (watch) => { await Task.Delay(2000); 
            Console.WriteLine("2000 one has been completed."); watch.Stop(); 
            Console.WriteLine(watch.ElapsedMilliseconds + "ms has been elapsed."); }
    };
    static void Main(string[] args)
    {
        Console.WriteLine("Await in loop work starts...");
        DoWorkAsync().ContinueWith(task =>
        {
            Console.WriteLine("Parallel work starts...");
            DoWorkInParallelAsync().ContinueWith(t =>
                {
                    Console.WriteLine("WaitAll work starts...");
                    WaitForAll();
                });
        });
        Console.ReadLine();
    }
    static async Task DoWorkAsync()
    {
        Stopwatch watch = new Stopwatch();
        foreach (var func in funcs)
        {
            await func(watch);
        }
    }
    static async Task DoWorkInParallelAsync()
    {
        Stopwatch watch = new Stopwatch();
        await Task.WhenAll(funcs[0](watch), funcs[1](watch), funcs[2](watch));
    }
    static void WaitForAll()
    {
        Stopwatch watch = new Stopwatch();
        Task.WaitAll(funcs[0](watch), funcs[1](watch), funcs[2](watch));
    }
}

After running this code, the results were very concluding.

Await in loop work starts…

1000 one has been completed.

1500 one has been completed.

2000 one has been completed.

4532ms has been elapsed.

Parallel work starts…

1000 one has been completed.

1500 one has been completed.

2000 one has been completed.

2007ms has been elapsed.

WaitAll work starts…

1000 one has been completed.

1500 one has been completed.

2000 one has been completed.

2009ms has been elapsed.

The await keyword in a loop does not really make the calls in parallel.

Read All Text from Textfile with Encoding in Windows RT

A simple extension for reading all text from a text file in WinRT with a specific encoding, made as an extension to StorageFile.

public static class StorageFileExtensions 
{ 
    async public static Task<string> 
        ReadAllTextAsync(this StorageFile storageFile) 
    { 
        var buffer = await FileIO.
            ReadBufferAsync(storageFile); 
        var fileData = buffer.ToArray(); 
        var encoding = Encoding.GetEncoding
            ("Windows-1252"); 
        var text = encoding.GetString
            (fileData, 0, fileData.Length); 
        return text; 
    } 
}

Generic Sorting using C# and Lambda Expression

This code below will help you sort any collection without needing to write special code for each data type, however if you need special ordering you can still do it. Leave a comment and let us know if you need something special to be added to the below code.

public static IOrderedEnumerable<T> Sort<T>(IEnumerable<T> toSort, 
Dictionary<string, SortingOrder> sortOptions)
{
    IOrderedEnumerable<T> orderedList = null;

    foreach (KeyValuePair<string, SortingOrder> entry in sortOptions)
    {
        if (orderedList != null)
        {
            if (entry.Value == SortingOrder.Ascending)
            {
                orderedList = 
                orderedList.ApplyOrder<T>(entry.Key, "ThenBy");
            }
            else
            {
                orderedList = 
                orderedList.ApplyOrder<T>(entry.Key,"ThenByDescending");
            }
        }
        else
        {
            if (entry.Value == SortingOrder.Ascending)
            {
                orderedList = 
                toSort.ApplyOrder<T>(entry.Key, "OrderBy");
            }
            else
            {
                orderedList =
                toSort.ApplyOrder<T>(entry.Key, "OrderByDescending");
            }
        }
    }

    return orderedList;
}

private static IOrderedEnumerable<T> ApplyOrder<T>
    (this IEnumerable<T> source, string property, string methodName)
{
    ParameterExpression param = Expression.Parameter(typeof(T), "x");
    Expression expr = param;
    foreach (string prop in property.Split('.'))
    {
        expr = Expression.PropertyOrField(expr, prop);
    }
    Type delegateType = 
    typeof(Func<,>).MakeGenericType(typeof(T), expr.Type);
    LambdaExpression lambda = 
    Expression.Lambda(delegateType, expr, param);

    MethodInfo mi = typeof(Enumerable).GetMethods().Single(
                    method => method.Name == methodName
                    && method.IsGenericMethodDefinition
                    && method.GetGenericArguments().Length == 2
                    && method.GetParameters().Length == 2)
            .MakeGenericMethod(typeof(T), expr.Type);
    return (IOrderedEnumerable<T>)mi.Invoke
            (null, new object[] { source, lambda.Compile() });
}
}

File Activation in Windows 8 RT

The code sample for file activation on MSDN is lacking some code so a simple way to pass the file clicked to your MainPage could be:

protected override void 
    OnFileActivated(FileActivatedEventArgs args)
{
    var page = new Frame();
    page.Navigate(typeof(MainPage));
    Window.Current.Content = page;
 

    var p = page.Content as MainPage;
    if (p != null) p.FileEvent = args;
    Window.Current.Activate();
}

And in MainPage:

public MainPage()
{
    InitializeComponent();
    Loaded += MainPageLoaded;
}
void MainPageLoaded(object sender, RoutedEventArgs e)
{
    if (FileEvent != null && FileEvent.Files.Count > 0)
    {
        //… do something with file
    }
}

Browser Specific Extensions of HttpClient

REST is having a great impact on service/API development because it offers a way to access a service without requiring any specific library by embracing HTTP and its features. ASP.NET Web API makes it very easy to quickly build RESTful HTTP services.

These HTTP services can be consumed by a variety of clients including browsers, devices, machine etc. With .NET framework 4.5, we can use HttpClient to consume/send/receive RESTful HTTP services (for .NET framework 4.0, HttpClient is available as part of the ASP.NET Web API download). The HttpClient class provides a bunch of helper methods (example DeleteAsync, PostAsync, GetStringAsync, etc.) to consume a HTTP service very easily. ASP.NET Web API added some more extension methods (for example PutAsJsonAsync, PutAsXmlAsync, etc.) into HttpClient to further simplify usage.

In addition, HttpClient is also an ideal choice for writing integration test for RESTful HTTP service. Since a browser is a main client of any RESTful API, it is also important to test the HTTP service on a variety of browsers, it is also important to test HTTP service on variety of browsers. RESTful service embraces HTTP headers and different browsers send different HTTP headers.

There is a NuGet package which can exactly do this. This NuGet package will add overloads with an additional browser parameter for almost all the helper methods of HttpClient class.

Create/open your test project and install ImranB.SystemNetHttp.HttpClientExtensions NuGet package. Then, add this using statement of your class.

using ImranB.SystemNetHttp;

Then, you can start using any HttpClient helper method which include the additional Browser parameter. For example,

var client = new HttpClient(myserver);
var task = client.GetAsync("http://domain/myapi", 
    Browser.Chrome);
task.Wait();
var response = task.Result;

Here is the definition of Browser,

public enum Browser
{
    Firefox = 0,
    Chrome = 1,
    IE10 = 2,
    IE9 = 3,
    IE8 = 4,
    IE7 = 5,
    IE6 = 6,
    Safari = 7,
    Opera = 8,
    Maxthon = 9
}

These extension methods will make it very easy to write browser specific integration test. It will also help HTTP service consumer to mimic the request sending behavior of a browser. This package source is available on github. So, you can grab the source and add some additional behavior on the top of these extensions.

Testing a REST API is an important aspect of service development and today, testing with a browser is crucial.

Please leave your comments on how you would like to use this HTTPClient Extension in your projects.

Entity Framework Code First Migrations

In this blog post, I am going to talk about Code First Migrations, an Entity Framework feature introduced in 4.3 released February 2012.

Before the addition of Code First Migrations (4.1.4.2 versions), there were three patterns that we developers can follow

  1. CreateDatabaseIfNotExists – Code First would create the database if it does not exist.
  2. DropCreateDatabaseIfModelChanges – Code First will drop and recreate the database if there is a model change.
  3. DropCreateDatabaseAlways – Code First will recreate the database every time one runs the application.

The above options are very much fine if you are in development mode but will prove catastrophic when you have a production database. We cannot lose our data because of the way Code First works.

Migrations solve this problem. With migrations we can modify the database without completely dropping it. We can modify the database scheme to reflect the changes to the model without losing data.

In version EF 5.0 migrations are fully supported and included. Read on to see a demonstration of migrations with a hands-on example. The screenshots below are taken from Visual Studio 2012 Ultimate edition running on a Windows 8.

  1. Create an empty asp.net web application and name it appropriately. Choose C# as the development language.
  2. Add a new web form in your application. Leave the default name.
  3. Create a new folder. Name it CodeFirst.
  4. Add a new item in your application, a class file. Name it Footballer.cs. This is going to be a simple POCO class. Place this file in the CodeFirst folder created above.
public class Footballer
{
    public int FootballerID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public double Weight { get; set; }
    public double Height { get; set; }
}

5. We will have to add Entity Framework 5.0 to our project. Right-click on the project in the Solution Explorer and select Manage NuGet Packages… for it. In the popup window search for Entity Framework and install it.

If you want to find out if indeed EF version 5.0 is installed you can look at references and confirm the same.

6. Then we need to create a context class that inherits from DbContext.Add a new class to the CodeFirst folder. Name it FootballerDbContext. Now that we have the entity classes created, we must let the model know. I will have to use the DbSet<T> property. The code for this class follows.

public class FootballerDBContext : DbContext
{
    public DbSet<Footballer> Footballers { get; set; }


}

Please don’t forget to add (using System.Data.Entity;) in the beginning of the class file.

7. We must take care of the connection string. It is very easy to create one in the web.config. It does not matter that we do not have a database yet. When we run the DbContext and query against it, it will use the connection string in the web.config and will create the database based on the classes. I will use the name “FootballTraining” for the database.

In my case the connection string inside the web.config looks like this.

<connectionStrings>
  <add name="CodeFirstDBContext"
    connectionString="server=.;integrated security=true;
    database=FootballTraining" 
    providerName="System.Data.SqlClient"/>
</connectionStrings>

8. Now it is time to create Linq to Entities queries to retrieve data from the database. Add a new class to your application in the CodeFirst folder. Name the file DALfootballer.cs

We will create a simple public method to retrieve the footballers. The code for the class follows.

public class DALfootballer
{
    FootballerDBContext ctx = new FootballerDBContext();

    public List<Footballer> GetFootballers()
    {
        var query = from player 
            in ctx.Footballers select player;
        return query.ToList();
    }
}

9. Place a GridView control on the Default.aspx page and leave the default name.Add anObjectDataSource control on the Default.aspx page and leave the default name. Set theDatasourceID property of the GridView control to the ID of the ObjectDataSourcecontrol.(DataSourceID="ObjectDataSource1" ). Let’s configure the ObjectDataSource control. Click on the smart tag item of the ObjectDataSource control and select Configure Data Source. In the Wizard that pops up select the DALFootballer class and then in the next step choose the GetFootballers() method.Click Finish to complete the steps of the wizard.

Build and Run your application.

10. As you have expected, you will not be able to see any records in the grid, because we have not inserted any record. The database is created successfully as shown below.

11. Now let’s change the POCO class. Let’s add a new property to the Footballer.cs class.

public int Age { get; set; }

Build and run your application again. You will receive an error. Have a look at the picture below

12. That was to be expected.EF Code First Migrations is not activated by default. We have to activate them manually and configure them according to your needs.

We will open the Package Manager Console from the Tools menu within Visual Studio 2012.Then we will activate the EF Code First Migration Features by writing the command “Enable-Migrations”.

This adds a new folder Migrations in our project. A new auto-generated class Configuration.cs is created. Another class is also created [CURRENTDATE]_InitialCreate.cs and added to our project.

The configuration.cs is shown below.

The [CURRENTDATE]_InitialCreate.cs is shown in the picture below.

13. Νοw we are ready to migrate the changes in the database. We need to run the Add-Migration Age command in Package Manager Console.

Add-Migration will scaffold the next migration based on changes you have made to your model since the last migration was created.

In the Migrations folder, the file 201211201231066_Age.cs is created.

Have a look at the picture below to see the newly generated file and its contents.

Now we can run the Update-Database command in Package Manager Console .See the picture above.

Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the Age migration needs to be applied, and run it.

The EFMigrations.CodeFirst.FootballeDBContext database is now updated to include theAge column in the Footballers table.

Build and run your application.Everything will work fine now.

Have a look at the picture below to see the migrations applied to our table.

14. We may want it to automatically upgrade the database (by applying any pending migrations) when the application launches.Let’s add another property to our Poco class.

public string TShirtNo { get; set; }

We want this change to migrate automatically to the database.

We go to the Configuration.cs we enable automatic migrations.

public Configuration()
{
AutomaticMigrationsEnabled = true;
}

In the Page_Load event handling routine we have to register the MigrateDatabaseToLatestVersion database initializer.

A database initializer simply contains some logic that is used to make sure the database is setup correctly.

protected void Page_Load(object sender, EventArgs e)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion
    <FootballerDBContext, Configuration>());
}

Build and run your application. It will work fine.

Have a look at the picture below to see the migrations applied to our table in the database.

 

I hope this will help to run your migrations in the code. Please add your comments or feedback in the comments section below.