What is new in ASP.Net vNext

ASP.Net vNext is the next version of ASP.Net Framework. As part of ASP.NET vNext, the MVC, Web API, and Web Pages frameworks are being merged into one framework, called MVC 6. The new framework removes a lot of overlap between the existing MVC and Web API frameworks.

ASP.Net vNext Features.

  • Side by side support – ASP.NET vNext will support true side by side support, developers can deploy ASP.Net vNext along with web applications, each app can run different versions of .NET vNext side-by-side and upgrade separately, all on the same machine.
  • Lean and Faster – ASP.NET MVC 6 has no dependency on System.Web.dll. ASP.NET vNext is a subset of .Net Framework, which is around 11 MB in size, and it is composed of a collection of NuGet packages.
  • Single Programming model – MVC, Web API, and Web Pages are merged into one framework, called ASP.NET MVC 6. The new framework uses a common set of abstractions for routing, action selection, filters, model binding etc. Dependency injection is built into the framework.
  • Enhanced Developer Experience – vNext uses the Roslyn compiler to compile code dynamically, so developer can edit a code file, refresh the browser, and see the changes without rebuilding the project.
  • Open Source – Microsoft has released entire source code open source via the .NET Foundation. You can see the source at https://github.com/aspnet and follow progress on vNext in real time.

ASP.NET vNext is not backwards compatible with existing ASP.NET applications. However, the current frameworks (Web Forms 5, MVC 5, Web API 2, Web Pages 3, SignalR 2, and Entity Framework 6) will continue to ship in Visual Studio, and will be fully supported in ASP.NET vNext.

Creating Hello World application in ASP.Net vNext

  • Start VS 2014 CTP
  • On the Start Page, click New Project, and then in the New Project dialog, select the C# / Web templates
  • Select the ASP.NET vNext Empty Web Application template, name the project HelloWorld, and click OK.
    New vNext Empty Web Application

    New vNext Empty Web Application

  • One of the vNext feature was it is lean, Microsoft has re-written the Framework and project / solution structure. You will not find the web.config, *.csproj files.
    Solution Explorer with vNext Files

    Solution Explorer with vNext Files

    • Global.json – file helps to support project-to-project references. It also makes it easy to separate test code under a different folder, but still be able to reference application projects from your test projects. This is the Global.json file for empty vNext web application. The “sources” element, indicating the “src” folder is the parent folder for finding project references.
      {
          "sources": [ "src" ]
      }
      
    • Project.json – The project.json file contains a list of dependencies for the project and a list of build output configurations. It can also include a list of commands.
      {
          "dependencies": {
              "Microsoft.AspNet.Server.IIS" : "1.0.0-alpha4"
          },
          "frameworks" : {
              "aspnet50" : { },
              "aspnetcore50" : { }
          }
      }
      

      Dependencies section lists all the dependencies of your application. These are defined by name and version, the runtime loaders will determine what should be loaded. Frameworks section lists target frameworks that will be built, and dependencies that are specific to the configuration. This snippet will build for Desktop (aspnet50) or Core CLR (aspnetcore50). You can find more details about the Project.json schema from github link. Frameworks you can configure using Project property pages, by default application will be using ASP.Net 5.0 Framework. Once you change the Active Target Framework, Visual Studio will update the references appropriately.

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net

      Active Target Framework is ASP.Net Core

      Active Target Framework is ASP.Net Core

      Active Target Framework is ASP.Net Core

    • Startup.cs – By default, the vNext hosting environment expects to find a startup class named Startup. This class must contain a Configure method that takes an IBuilder parameter, and you configure the HTTP pipeline inside this Configure method. The empty project creates the class with nothing in the Configure method. If you were worked in Owin / Katana project, Startup.cs is similar to Owin Startup file. This is the default Startup.cs file for empty vNext application.
      using System;
      using Microsoft.AspNet.Builder;
      
      namespace HelloWorld
      {
          public class Startup
          {
              public void Configure(IApplicationBuilder app)
              {
                  // For more information on how to configure your application, 
                  //visit http://go.microsoft.com/fwlink/?LinkID=398940
              }
          }
      }
      

      To enable MVC in the HTTP pipeline you’ll add a NuGet package and configure the Startup class.

  • In the project.json, you need to add reference of Microsoft.AspNet.Mvc package. The project.json file supports intellisense.
    Intellisense in Project.json for packages

    Intellisense in Project.json for packages

    Intellisense in Project.json for package version as well

    Intellisense in Project.json for package version as well

    "dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-alpha4",
        "Microsoft.AspNet.Mvc": "6.0.0-alpha4"
    }
    

    Once you save the changes, Visual Studio will detect the changes and download the required nuget packages (You can find the details from output window).

  • Now you need to configure the application to use MVC. You can do it by modifying the Startup.cs file, configure() method.
    using Microsoft.AspNet.Builder;
    using Microsoft.Framework.DependencyInjection;
    namespace HelloWorld
    {
        public class Startup
        {
            public void Configure(IApplicationBuilder app)
            {
                app.UseServices(services =>
                {
                    services.AddMvc();
                });
    
                app.UseMvc();
            }
        }
    }
    

    If you didn’t add the using Microsoft.Framework.DependencyInjection, you won’t get services.AddMvc() method. The AddMvc method adds the MVC framework services to the dependency injection system. The UseMvc method configures MVC default settings such as routes.

  • Next create a folder called Controller and add a controller class, HomeController.cs. Also create Home folder inside Views folder, and add a razor view – Index.cshtml. (You won’t get option like Add View by right clicking on Controller method.)
    Solution Explorer - With Controllers and Views

    Solution Explorer – With Controllers and Views

  • Press F5 to start the application. voilà, you have created your first HelloWorld ASP.Net vNext application.

In the next post I will discuss about deployment. Happy Programming :)

What is new in C# 6.0

Today I got a chance to look into C# 6.0 features. Thanks to ORTIA(Technology innovation division of Orion India Systems), for providing me the MSDN subscription. :)

  1. Exception filters : Exception filters lets you specify a condition for a catch block. The catch block gets executed only if the condition is satisfied.
    try
    {
        throw new CustomException(10);
    }
    catch (CustomException ex) if (ex.ErrorCode == 10)
    {
        Console.WriteLine("Error code is 10");
    }
    catch (CustomException ex) if (ex.ErrorCode == 20)
    {
        Console.WriteLine("Error code is 20");
    }
    

    The above code will write 10, as the Error code property is set to 10.

  2. Declaration expressions – This feature simply allows you to declare local variable in the middle of an expression.
    string Id = "10";
    int result = 0;
    if(int.TryParse(Id, out result))
    {
        Console.WriteLine(result);
    }
    

    The above code snippet can be re-written as like the following in C# 6.0

    string Id = "10";
    if (int.TryParse(Id, out int result))
    {
        Console.WriteLine(result);
    }
    
  3. using static – This feature allows you to specify a particular type in a using statement after that all static members of that type will be accessible is subsequent code.
    using System.Console;
    
    namespace HelloWorldCS6
    {
        class Program
        {
            static void Main(string[] args)
            {
                WriteLine("Hello C# 6.0");
            }
        }
    }
    
  4. Auto property initializer – With C# 6 initialize auto properties just like a field at declaration place.
    class HelloWorld
    {
        //Initiailizing auto property.
        public string Name { get; set; } = "dotnetthoughts";
        //Readonly autoproperty initialization.
        public bool IsExists { get; } = true;
    }
    
  5. Primary Constructor – This feature helps to capture parameters of primary constructor to fields, in the class for furthur processing. When declaring a primary constructor all other constructors must call the primary constructor using :this().
    class HelloWorld(string name)
    {
        public string Name { get; set; } = name;
    }
    
  6. Dictionary Initializer – C# made the Dictionary more cleaner.
    var dictionary = new Dictionary<int, string>()
    {
        { 10, "A" },
        { 20, "B" }
    };
    

    Can be re-written like this

    var dictionary = new Dictionary<int, string>()
    {
        [10] = "A",
        [20] = "B"
    };
    

Note : These are experimental features, you have to explicitly enable this, otherwise VS2014 will show an error, while compiling like this. – Feature ‘primary constructor’ is only available in ‘experimental’ language version.

Experimental feature error - VS 2014

Experimental feature error – VS 2014

You can do this manually editing the project file.(I didn’t found any option to do this via Visual Studio.) You can open the *.csproj file in your favorite text editor and add the following line.

<LangVersion>experimental</LangVersion>

Now it will be like this

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <PlatformTarget>AnyCPU</PlatformTarget>
  <DebugSymbols>true</DebugSymbols>
  <DebugType>full</DebugType>
  <Optimize>false</Optimize>
  <OutputPath>bin\Debug\</OutputPath>
  <DefineConstants>DEBUG;TRACE</DefineConstants>
  <ErrorReport>prompt</ErrorReport>
  <WarningLevel>4</WarningLevel>
  <LangVersion>experimental</LangVersion>
</PropertyGroup>

Happy Programming :)

Force .NET application to run in 32bit process

Due to lack of 64 bit version of few COM libararies, we faced a situation to run our AnyCPU application into 32 bit. You can do this either by setting the Platform target or by using the corflags command.

  1. Using Platform target feature. – This is the simple solution, you can change the Platform target settings from Project Properties > Build tab.

    Platform Target settings from Project Properties

    Platform Target settings from Project Properties

    This will cause the compiler to set the 32Bit flag in the CLR header of the corresponding assembly. Every time we run this application no matter on what type of OS it will execute as a 32bit process. But this solution although simple and straight forward was not a viable solution for us since – as mentioned above – we want to have one and only one version of our product. Thus all components of our package have to be compiled with Platform Target set to Any CPU.

    From VS 2011 onwards there is new compiler flag available “Prefer 32-bit”, which will help a .NET application compiled to x86 will fail to run on an ARM Windows system, but an “Any CPU 32-bit preferred” application will run successfully. Also, the “Prefer 32-bit” checkbox is only enabled for .NET 4.5+ executable projects.

  2. Using corflags command – Similar to the above solution, here as well we are setting the CLR header to 32 bit using a tool called corflags – You can find more details about this tool here. To set the 32Bit flag, open the Developer Command prompt, navigate to the directory where your assembly is and use this command.
    CorFlags.exe Sample.exe /32Bit+
    

    You can use this solution as part of the build, so that you can switch to x64 in future, developer don’t need to worry about any platforms.

Happy Programming :)

Explicit Interface Implementation in C#

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

class Sample : ISample, ISample2
{
    //Both ISample and ISample2 will call this method.
    public int Add(int a, int b)
    {
        return a + b;
    }
}

interface ISample
{
    int Add(int a, int b);
}

interface ISample2
{
    int Add(int a, int b);
}

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.

Explicit Interface Implementation

Explicit Interface Implementation

It is possible to implement an interface member explicitly – creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period.

class Sample : ISample, ISample2
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    int ISample2.Add(int a, int b)
    {
        return a + b + 10;
    }
}

The class member ISample2.Add only available via ISample2 interface, not available through class instance.

var sample = new Sample();
var result = sample.Add(10, 20);
Console.WriteLine(result);  //Will return 30

ISample2 sample2 = new Sample();
var result2 = sample2.Add(10, 20);
Console.WriteLine(result2);  //Will return 40

Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method.

Points of interest.

  • Solves the diamond problem – The “diamond problem” (sometimes referred to as the “deadly diamond of death”[6]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and/or C has overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
  • Improves design – always promotes “Program to interface not implementation” design technique
  • Explicit Interface Implementations are not overridable and cannot be made virtual.
  • Avoid implementing interface members explicitly without having a strong reason to do so. – Understanding explicit implementation requires an advanced level of expertise. For example, many developers do not know that an explicitly implemented member is publicly callable even though its signature is private. Because of this, explicitly implemented members do not appear in the list of publicly visible members. Explicitly implementing a member can also cause unnecessary boxing of value types.
  • Cleaner code / Refactoring is safer – There will be a compiler error if the an interface method is removed in case of explicit interface implementation, however if you implement the method implicitly you can end up with unused ‘orphaned’ public methods.

Do we require Explicit Interface Implementation always? / Should we enforce it as best practice? – Not always, for me it is complicated and confusing. If you found a library from nuget and will check which all interfaces available in it or will you check available public methods in it? Again it is subjective, as MSDN recommends – Avoid implementing interface members explicitly without having a strong reason to do so. If you are developing a framework, I will not recommend explicit interface implementation.

Happy Coding :)