Command line scaffolding for ASP.NET 5

Standard

Last K-MUG Session, there was a demo related to ASP.NET MVC scaffolding. This post is about scaffolding support in ASP.NET 5. This post uses K runtime for scaffolding, you can do it using Visual Studio 2015 Preview as well.

  • Modify project.json, add “Microsoft.Framework.CodeGenerators.Mvc”: “1.0.0-*” under dependencies.
  • Add “gen”: “Microsoft.Framework.CodeGeneration”, under commands
  • You are done with the configurations. Updated project.json file will look like this.
    {
      "dependencies": {
        "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
        "Microsoft.AspNet.Hosting": "1.0.0-beta1",
        "Microsoft.AspNet.Mvc": "6.0.0-beta1",
        "Microsoft.AspNet.Server.WebListener": "1.0.0-beta1",
        "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-*",
        "EntityFramework.SQLite": "7.0.0-*",
        "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-*",
        "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-*",
        "Microsoft.AspNet.StaticFiles": "1.0.0-*"
      },
      "commands": {
        "webListener": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010",
        "gen": "Microsoft.Framework.CodeGeneration"
      },
      "frameworks": {
        "aspnet50": {},
        "aspnetcore50": {}
      }
    }
    
  • Execute KVM Upgarde command in command prompt, to upgarde your K Runtime.
  • Now execute KPM Restore command in command prompt. It will restore all the required nuget packages for scaffolding.
  • To scaffold the controllers and view, you need to execute the following command – “k gen controller -m TaskItem -dc TaskContext“, where TaskItem is the model class, and TaskContext is the DBContext. (As I am using SQLite, I have created DBContext class, if you are using SQL Server, you don’t require this, scaffolder will generate it for you.) Here is the TaskContext class.
    public class TaskContext : DbContext
    {
    	public DbSet<TaskItem> Tasks { get; set; }
    	protected override void OnConfiguring(DbContextOptions builder)
    	{
    		builder.UseSQLite("Filename=tasksDb.sqlite;");
    	}
    
    	protected override void OnModelCreating(ModelBuilder builder)
    	{
    		builder.Entity<TaskItem>().Key(t => t.Id);
    		base.OnModelCreating(builder);
    	}
    }
    
    

Here is the generated output.

COMMAND LINE SCAFFOLDING FOR ASP.NET 5

COMMAND LINE SCAFFOLDING FOR ASP.NET 5

Customizing scaffolding templates.

Similar to previous versions of MVC, you can customize the templates by modifying the templates. In old versions of MVC, you can find the templates under “C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates” folder, but in ASP.NET 5, NuGet packages are stored on a per-user basis by default. So you can the scaffolding under following location – C:\Users\\.kpm\packages\Microsoft.Framework.CodeGenerators.Mvc\1.0.0-beta1\Templates\, you can modify the contents of the files, and you can re-generate using -f (force) option.

k gen controller -f -m TaskItem -dc TaskContext

Happy Programming :)

Expression Bodied Functions and Properties in C# 6.0

Standard

Expression bodied functions are another syntax simplification in C# 6.0. These are functions with no statement body. Instead, you implement them with an expression, similar to Lamda expressions.

class Calculator
{
    public int Add(int a, int b) => a + b;
    public int Subtract(int a, int b) => a - b;
}

As with most of the features found in C# 6.0, they’re intended to provide a simplified syntax for cases where the implementation is simple. The return type of the expression should match the return type identified in the function declaration. Void methods, don’t return anything. The expression bodied simplification also available for properties (getter only).

New C# 6.0 features

Standard

As part of the Connect(); event, Microsoft introduced VS2015 Preview, which includes C# 6.0 with few more features. (These features are not included in my earlier post What is new in C# 6.0, as I already mentioned these features introduced by Microsoft in the Connect(); event few days back.)

  • nameof operator – nameof operator allows developers to use program elements as text. In MVVM project, you are using property notifications, it is recommended to use strongly typed property notifications, instead of string. Because you are hard coding the property name, if you rename the property, you need to change the string manually. The nameof operator helps you to use the property as the parameter.
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName != value)
            {
                _firstName = value;
                OnPropertyChanged(nameof(FirstName));
            }
        }
    }
    

    Runtime will replace the property with the property name while generating the IL code.

    IL code generated for nameof operator

    IL code generated for nameof operator

  • null conditional dot operator – as the name indicates it for null checking. This helps you to make null checking fade into the background.
    static void PrintBook(Book book)
    {
        var name = book.Name;
        var price = book.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    I have a function like this, which will print the name and price of the book. Please note I am not doing any null check, if the book instance is null, it will throw exception. The null conditional dot operator helps to avoid this validation and processing. If you are invoking a property of null object instance, it will return null for that property as well, it won’t throw null reference exception.

    static void PrintBook(Book book)
    {
        var name = book?.Name;
        var price = book?.Price;
        Console.WriteLine("Name :{0} - Price {1}", name, price);
    }
    

    In case of value types, Visual Studio will treat the type of the variable as nullable, if you use null conditional dot operator.

    null conditional dot operator - with value types

    null conditional dot operator – with value types

  • string interpolation – Another cool feature, which will help you to manage string formatting easy. In the current framework, you need use string.Format function, it little complex, you need to put numeric place holders ({n}) and based on the number you need to set the variables. String Interpolation will help developers to use actual variables as placeholders.
    var message = string.Format("Book Name :{0} Price :{1}", name, price);
    

    Can be re-write like this.

    var message = "Book Name :\{name} Price :\{price}";
    

    It supports IntelliSense for the variable names, also variables can be identified with different color.

    String Interpolation - IntelliSense

    String Interpolation – IntelliSense

You can download VS 2015 Preview from here

Happy Coding :)

First look into Visual Studio Community 2013

Standard

Yesterday Connect(); Event, Scott Guthrie and Soma Somasegar made a number of important announcements for the cloud-first, mobile-first developer. Visual Studio Community 2013 is a new free, fully-featured edition of Visual Studio that lets developers target any platform, from desktop and mobile to web and cloud.

Visual Studio Community 2013

Visual Studio Community 2013

Visual Studio Community 2013 also supports full Visual Studio extensibility, offering access to the ecosystem of over 5000 extensions. You can download it from here. You can also try Visual Studio Community 2013 in Azure VM image.

What is new in Visual Studio Community 2013

  • Professional-grade editing, code analysis, and debugging support – Your favourite Refactor and Debugging features are included.
  • Support for open-source workflows (Git).
  • Compilers for managed languages, C++ and more
  • Cross-platform mobile development including the web, Android, iOS, and Windows Phone with the free Visual Studio Tools for Apache Cordova extension.
  • Take advantage of cloud services with simplified Azure SDK integration, and incorporate modern app analytics and telemetry with Application Insights. Application Insights collects, processes and presents a wide variety of telemetry including performance, usage, availability, exception, crash, environment, log and developer-supplied data from all components of a modern application – including clients (devices and browser), servers, databases and services.
    Application Insights

    Application Insights

  • Access to all the Visual Studio 2013 extensions on the Visual Studio Gallery

Visual Studio Community 2013 includes Update 4, which is a cumulative update of all previous Visual Studio 2013 updates.

Happy Programming :)