Wednesday, 2 November 2016

Building your first asp.net core application.

Introduction

In this post, we are going to get started with building an asp.net core application using visual studio 2013. As my last article stated aspnet core is meant to work in visual studio 2015, but in this post, I will show you how to develop asp.net core application using using visual studio 2013. So here is a list of things we have to do before getting started:

  1. First update your .net framework to the latest version (as of this writing version 4.6.2).
  2. Download and install .net targeting pack for .net framework 4.6. Dot net targeting pack enables you to build application targeting .net framework 4.6 in visual studio 2013 and visual studio 2012 or other third-party ides.
  3. Create a Windows Console Project.
  4. Create a file named project.json in the root of the project and add the following code snippet
{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        },
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
      },
      "imports": "dnxcore50"
    }
  }
}

Then install the following nuget packages:

  1. Microsoft.Aspnetcore.Hosting
  2. Microsoft.Aspnetcore.Server.Kestrel
After that, add a Startup.cs file to the root of your application with the codes below:

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.Run(context =>
        {
            return context.Response.WriteAsync("Hello from ASP.NET Core!");
        });
    }
}

Then update the main method of your console application:

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

After that, right-click on the project in your solution explorer, select "Add>Existing Item". Then navigate the following path [solution root]\packages\Libuv.[version]\runtimes\[os]\native. Then select libuv.dll. After adding the dll to your application, right-click on it and select properties, then change "Copy to output directory" to "copy always". Then you're good to go.

Conclusion
In this post, I have shown you how to create an asp.net core application using visual studio 2013. In the next series of posts, we will have a look at the underside of asp.net core and at what can be achieved with it. 

Saturday, 29 October 2016

Getting started with asp.net core


Introduction
The not so recent change of Microsoft's CEO has brought with it a great new wave of changes and innovations from Microsoft. One of the most notable of this is Microsoft's move towards open sourcing many if not all of its development stack. Microsoft and the developer community has embraced the transparency of open source software.  In this post, I going to introduce asp.net core.

So what is asp.net core?
The asp.net team describes asp.net core as "an open source web framework for building modern web applications and services". It went ahead to say that asp.net core is a framework used for building a scalable web applications that can serve millions of users and requests and made to work with complex web capabilities like web api's, forms over data and real time communications etc.

In other words, asp.net core is the open source version of asp.net. It was built from scratch as a replacement of asp.net and also a framework meant to run on virtually any platform or environment.

Some of the features included in this new framework are:

  1. New modular HTTP request pipeline.
  2. Ability to run multiple .net framework versions side by side.
  3. Cloud-ready environment configuration.
  4. Ability to see changes without recompiling the project.
  5. You can either self-host the project or go with the good old IIS.
  6. Can be run on the .net core or on the full .net framework.
  7. It consists of modular components with minimum overheard.
  8. Finally the source code and bits for this new framework is open-sourced in GitHub.
Also, Asp.net core promises some new benefits. These are:
  1. open source.
  2. Modularity.
  3. Unified mvc and web api.
  4. Dependency injection and middleware.
  5. Developer productivity
  6. Cross-plaform capability.
For more explanation of some of these benefits visit Intertech


Getting started

To get started with using asp.net core you will need to:
  1. For windows users only: Install the .net core sdk using visual studio. (visit here for instructions on how to download and install visual studio 2015). 
  2. For windows users with visual studio 2013 already installed: There are a few hoops for you guys to pass through before developing asp.net core app in visual studio 2013. Though working developing asp.net core in visual studio 2013 is not recommended. These are some of the steps to take
  • First update your .net framework to the latest version (version 4.5.2 will do). Version 4.5.1 will work but Microsoft has ended support for it.(Read for more details).
  • Create a console application targeting the latest .net framework you just installed.
  • Using nuget, download and install the following packages: Microsoft.Aspnetcore.Hosting and  Microsoft.aspnetcore.server.kestrel

For Linux and Mac OS users: Sorry I don't work in any of those environment yet (my bad) so am just gonna point you guys to the direct source.
Conclusion
In this post, I have introduced you to asp.net core, some of its features and the reason why you should switch over to this brand new framework. You should be aware that although the asp.net core is production ready, it has not been fully battle tested and not all the components that you are used and love working with in the good old asp.net is ready yet for asp.net core. But it wouldn't hurt to take it for a spin and see how it feels to work in this new framework.

In the subsequent posts, I will write tutorials about this new framework. Stay tuned.

Tuesday, 28 June 2016

Getting started with fluent migrator

Introduction

Migrations are a structured way to alter a database schema and are an alternative to creating lots of sql scripts that have to be run manually by every developer involved. It acts like the version control system for an application database allowing a team to easily share the schema. Also, it aides in the evolution of a schema used several physical databases

Fluentmigrator is the .net migration framework. Database migrations was first started in ruby on rails applications and soon afterwards every languages had their own migration framework.

Typically any modification onthe schema of a database typically involve dding/removing new table or columns to/from the database. So the basic concept of most migration frameworks is to just move the schema of the database forward or backward in time. Fluentmigrator is no different as it has both an “Up” method (ie: forward through time) and a “Down” method (ie. backwards through time).

The basic unit of fluent migrator is an abstract class called “Migration” that has two virtual methods “Up” and “Down”. So your migration classes will have to derive from these class and implement those methods. Also you will decorate your migration class with a migration attribute that takes a long value as identifier. Commonly, most programmers use time stamps such as YYYYMMDDHHMM as their identifier. This identifier is  used in sorting the execution order of the migration classes. Lower numbers are executed first. Migrations can also be run out of sequence depending on how they were checked in. For example if migration 12, 14 and 15 is checked in before migration 13 these migrations will be executed, but it does not prevent migration 13 from being executed.

Using FluentMigrator

To use fluentmigrator, install the nugget packages a class library of your project (It is highly recommended to install into a new class library specifically meant for migration).



Nuget packgaes


Install-Package FluentMigrator

Install-Package FluentMigrator.Tools


Then create a concrete class that derives from the abstract "Migration" class and implement the virtual methods as shown below.


[Migration(2016060280140)]
    public class CreateTableMigration: Migration
    {
        public override void Down()
        {
            //Creates a table with three columns
            Create.Table("Profiles")
                .WithColumn("Id").AsInt32().NotNullable().PrimaryKey().Identity()
                .WithColumn("FirstName").AsString().NotNullable()
                .WithColumn("LastName").AsString().NotNullable();

             //creates an index on the FirstName column of the table.
            Create.Index("Fst_Index")
                .OnTable("Profiles")
                .OnColumn("FirstName")
                .Ascending()
                .WithOptions().NonClustered();

            //creates an index call "Lst_Index" on the LastName column of the table.
            Create.Index("Lst_Index")
               .OnTable("Profiles")
               .OnColumn("LastName")
               .Ascending()
               .WithOptions().NonClustered();

            // Inserts data into the table using anonymous classes
            Insert.IntoTable("Profiles")
                .Row(new {FirstName = "John", LastName = "Doe"})
                .Row(new {FirstName = "Jane", LastName = "Doe"});

             //Inserts a column called id if it does not already exist.
            if (!Schema.Table("Profiles").Column("Id").Exists())
            {
                Create.Column("Id")
                    .OnTable("Profiles")
                    .AsInt32()
                    .NotNullable()
                    .PrimaryKey()
                    .Identity();
            }
            
        }

        public override void Up()
        {
            Delete.Table("Profiles");
        }
    }

The Fluent Interface

The fluent migrator fluent api allows one to create tables, columns, indexes, foreign keys, insert data into tables and most other constructs you will need to manipulate a database.

It works by populating a semantic model that is used to analyze and apply migrations in batch. The fluent api is available in the migration class with five (5) root expressions which are:
  1.  Create: This expression allows you to create a table, column, index, foreign key and     schema.
  2.  Delete: This expression allows one to delete a table, column, foreign key and a     schema. You can also delete multiple column using the “Column” extension method.
  3.              Alter: This expression allows you to alter existing tables and columns.
  4.              Execute: This expression allows you to execute a block of sql, or a script by name (ie. myscript.sql) or an embedded sql script.
    Note: To embed a sql script, add the file to your migration project and change the build action property to Embedded Resource.
  5. Rename: This expression allows you to rename a column or a table.

Data Expressions: This expressions allows you to insert a row into a table using an anonymous data type for the row contents.

Insert.IntoTable("Profiles")
                .Row(new {FirstName = "John", LastName = "Doe"})
                .Row(new {FirstName = "Jane", LastName = "Doe"});

AllRows Attribute

You use this attribute when you want to add a non-nullable column without specifying a default value. Note you can also you SetExistingRows() methods to add a predefined value to a newly created column.

//Update table
            Update.Table("Profiles").Set(new {DateJoined = DateTime.Today}).AllRows();

IfDatabase Expression

This expression allows you to execute conditional expression depending on the type of database in use. Currently fluentmigrator supports these databases:
  1.        SqlServer (this includes Sql Server 2005 and Sql Server 2008)
  2.        SqlServer2000
  3.             SqlServerCe
  4.         Postgres
  5.         MySql
  6.        Oracle
  7.       Jet
  8.      Sqlite.

Multiple databases type (as specified above) can be passed into the IfDatabase Expression.

IfDatabase("SqlServer", "Postgres")
                .Create.Table("Users")
                .WithIdColumn()
                .WithColumn("Name").AsString().NotNullable();

Schema.Exists Expressions

This expression allows you to write conditional migrations that gets executed based on some preexisting schema. For example you can write a migration checking if some columns already exists before adding it.

if (!Schema.Table("Profiles").Column("Id").Exists())
            {
                Create.Column("Id")
                    .OnTable("Profiles")
                    .AsInt32()
                    .NotNullable()
                    .PrimaryKey()
                    .Identity();
            }

Conclusion

Fluent migrator is a simple but powerful framework used in managing and migrating different versions of your database schema in c#. One  major advantage is that the code can be checked into a version control system as it provides a neat interface for growing or regressing your schema without resorting to multiple sql scripts.

In this post, I have tried to give you a brief but detailed introduction to fluent migrator. In the next we will go inroad into the various usage scenario and how one can use nant, commandline, fluentmigrator.runner to execute migration class. Thanks.

References





Saturday, 15 August 2015

Make sure you have a well documented schedule and time table for any project if you are an independent developer.



Although it was not of recent that I discovered the need for a written design document, schedule and plans. But it was until recently that I realized that I do need one. You know I pride myself with having a retentive memory, you know typically all those stuff that classic nerds are known for. So I guessed I kind of dismissed the idea that having a well written design document is not for me. But damn I was wrong.



Ways in which not having a well thought out design document can undermine your effort.


1. Lack of prioritization: This is one of the greatest disadvantage of not having a design document. This is because without any structure to all your work and effort, you will be implementing features on the spur of the moment basis and not on their importance basis. Without structure, your project will be haphazardly developed, without flow and unorganized. Also and most importantly, you will be consistently missing your schedules.


2. Lack of focus: Without a well written design document, I discovered in my experience that I usually lack focus. This is because most times even when you want to work on the project, you will be at loss at what feature set you will implement. And the result of these is lost productivity times and thereby leading to delayed project.


3. Improper implementation of your project feature set: Without a written document, most features in your project will be improperly implemented as it is not well thought out. One good thing about having a well written project document, is that it will help you think about the project that you are developing and on how its features will function under different conditions.


4. Lack of schedule and timeline for further project development and enhancement: Not having any design document often leads to incomplete feature set and can hamper further project development even after the project is completed and shipped and this often leads to having a software that does advance and grow as the requirements of its users changes.


5. Buggy Software: In the absence of any design document, the end product is usually buggy as there is no form or shape taken to develop the project and this goes on to affect the testing of the project and also it tends to lead to software that is often hard to extend and maintain.


Conclusion

Not having a well written document can undermine your efforts in various ways as a independent developer. Before embarking on any project of any considerable size, it is important that one  must do his due diligence and create a well written design document and not the usual vague on the memory on the go type that many people are usually okay with. 


Monday, 29 June 2015

Sending emails from a background thread in asp.net mvc


Introduction
In the current application am working on I encountered a problem, and that is how to send an email from the backend. This problem was unique as there are currently no nuget project tackling this problem, because the available asp.net mvc email sending packages (like Mvc Mailer, Postal) can only send mail in the context of a request. In this post we are going to look at how to send mails in the background while making effective use of views to order and style your mail.

In this project, we are going to need 2 essential nuget packages: RazorEngine, PreMailer. So fire up your visual studio, create an asp.net mvc project and add the following package in nuget manager console.

Install-Package RazorEngine

This nuget package allows you to use razor to build robust template. Since we only want to be sending professional looking emails, we are going to use it in creating our message body so as to enable to style it appropriately instead of using string concatenation or ordinary text.

Install-Package Premailer.net

This nuget package will be used in converting page head style blocks to inline styles as most email clients dont render perfectly if you don't inline its css.

In this project, we are going to utilize Quartz, to schedule that our email to sent 5 minutes after it was created. So add Quartz also to your project

Install-Package Quartz




The next thing to do is to create a folder where your mail templates will live. Its not a must for you to create the folder inside the Views Directory but its advisable to create the folder where you can easily access it from the root of the AppDomain.

After that create a base mail layout inside the 'mails template' folder. This will serve as the layout for your emails, as it will help in the styling of the emails like the one shown below:


1:  @model dynamic  
2:  @using System.Web.Optimization  
3:  <!DOCTYPE html>  
4:  <html>  
5:  <head>  
6:    <style rel="stylesheet">  
7:      body {  
8:        background-color: #bbb;  
9:        font-family: arial helvetica sans-serif;  
10:        font-size: 16px;  
11:        line-height: 1.557;  
12:        margin: 0;  
13:        padding: 0;  
14:      }  
15:      .mailBody {  
16:        margin: 15px auto;  
17:        width: 750px;  
18:        padding: 0 10px 10px;  
19:        background-color: #fff;  
20:        -ms-border-radius: 5px;  
21:        -moz-border-radius: 5px;  
22:        -webkit-border-radius: 5px;  
23:        border-radius: 5px;  
24:      }  
25:      .header {  
26:        background-color: #2478BF;  
27:        margin: 0;  
28:        padding: 10px;  
29:      }  
30:      .logo {  
31:        text-align: center;  
32:        color: #fff;  
33:      }  
34:      .col-md-8 {  
35:        position: relative;  
36:        min-height: 1px;  
37:        padding-right: 15px;  
38:        padding-left: 15px;  
39:      }  
40:      .btn {  
41:        padding: 10px 15px;  
42:        display: block;  
43:        background-color: #2478BF;  
44:        color: #fff;  
45:        text-decoration: none;  
46:        text-align: center;  
47:        -ms-border-radius: 5px;  
48:        -moz-border-radius: 5px;  
49:        -webkit-border-radius: 5px;  
50:        border-radius: 5px;  
51:        border: 1px solid #206cac;  
52:      }  
53:      .col-md-offset-2 {  
54:        margin-left: 16.66666667%;  
55:      }  
56:      .container {  
57:        width: 750px;  
58:        margin: 0 auto;  
59:      }  
60:      .center {  
61:        width: 350px;  
62:        margin: 10px auto;  
63:      }  
64:      .clearfix:before,  
65:      .clearfix:after {  
66:        display: table;  
67:        content: " ";  
68:      }  
69:      .clearfix:after {  
70:        clear: both;  
71:      }  
72:      .float-right {  
73:        float: right;  
74:      }  
75:    </style>  
76:  </head>  
77:  <body class="container" style="background-color: #bbb;">  
78:    <div class="mailBody">  
79:      <header class="header">  
80:        <h3 class="logo">Welcome to <a href="http://oursite.com">Our site</a></h3>  
81:      </header>  
82:      <div>  
83:        @RenderBody()  
84:      </div>  
85:      <div class="clearfix">  
86:        <hgroup class="float-right">  
87:          <h5>Yours sincerely</h5>  
88:          <span>Kings, Admin</span>  
89:        </hgroup>  
90:      </div>  
91:    </div>  
92:  </body>  
93:  </html>  


The next thing to do is to go ahead and create view templates that will be used by the email sender to compile your emails.

1:  @using BackgroundMailSender.Common.MailWorker  
2:  @model Message  
3:  @{  
4:    Layout = "_MailLayout.cshtml";  
5:  }  
6:  <div>  
7:    @Message.Body  
8:  </div>  

Then lets create classes that we be using to pass message to our background sender. We will call the class Message.cs


1:  namespace BackgroundMailSender.Common.MailWorker  
2:  {  
3:    public class Message  
4:    {  
5:      public string Fullname { get; set; }  
6:      public string Body { get; set; }  
7:      public string Title { get; set; }  
8:      public string To { get; set; }  
9:    }  
10:  }  

//Here is the email class

 public class Email
    {
        public Email(string to)
        {
            if (!CommonHelper.IsValidEmail(to))
                throw new ArgumentNullException(to, "This is not a valid email address!");
            Priority = MailPriority.Normal;
            To = to;
        }
        public string To { get; private set; }
        public string Message { get; set; }
        public MailPriority Priority { get; set; }
        public string Title { get; set; }
    }
}


Here is our EmailWorker class.

1:  using System;  
2:  using System.IO;  
3:  using System.Net;  
4:  using System.Net.Mail;  
5:  using System.Threading.Tasks;  
6:  using System.Web.Hosting;  
7:  using MailEngine.MailWorker;  
8:  using RazorEngine;  
9:  using RazorEngine.Templating;;  
10:    
11:  namespace BackgroundMailSender.Common.MailWorker  
12:  {  
13:    public class EmailWorker  
14:    {  
15:      private const string EmailTemplatePath = "~/Views/EmailTemplates";  
16:      private string _templatePath = string.Empty;  
17:    
18:      public EmailWorker()  
19:      {  
20:        //Resolve virtual url to file path url  
21:        _templatePath = MapPath(EmailTemplatePath);  
22:    
23:        //Map the Layout path.  
24:        var mailLayoutPath = Path.Combine(_templatePath, "_MailLayout.cshtml");  
25:    
26:    
27:        //Add out layout template.  
28:        var layout = File.ReadAllText(mailLayoutPath);  
29:        Engine.Razor.AddTemplate("_MailLayout", layout);  
30:    
31:    
32:      }  
33:    
34:      /// <summary>  
35:      ///   Maps a virtual path to a physical disk path.  
36:      /// </summary>  
37:      /// <param name="path">The path to map. E.g. "~/bin"</param>  
38:      /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns>  
39:      private string MapPath(string path)  
40:      {  
41:        if (HostingEnvironment.IsHosted)  
42:        {  
43:          //hosted  
44:          return HostingEnvironment.MapPath(path);  
45:        }  
46:        //not hosted. For example, run in unit tests  
47:        string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;  
48:        path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');  
49:        return Path.Combine(baseDirectory, path);  
50:      }  
51:    
52:      private Task Send(Email email)  
53:      {  
54:        Func<Task> funct = () =>  
55:        {  
56:          var message = new MailMessage  
57:          {  
58:            Body = email.Body,  
59:            IsBodyHtml = true,  
60:            Subject = email.Subject,  
61:            Priority = MailPriority.Normal  
62:          };  
63:          message.To.Add(email.To);  
64:    
65:          var smtp = new SmtpClient();  
66:          return smtp.SendMailAsync(message);  
67:        };  
68:    
69:        var task = Task.Run(funct);  
70:        return task;  
71:      }  
72:    
73:      /// <summary>  
74:      /// converts block level css to inline css  
75:      /// </summary>  
76:      /// <param name="razorResult"></param>  
77:      /// <returns>Inlined html</returns>  
78:      private string InlineCss(string razorResult)  
79:      {  
80:        //Create a new Premailer instance, note this can be done using Dependency injection.  
81:        var pm = new PreMailer.Net.PreMailer(razorResult);  
82:    
83:        //Inline css  
84:        var compileResult = pm.MoveCssInline(stripIdAndClassAttributes: true,  
85:          removeComments: true, removeStyleElements: true);  
86:    
87:        return compileResult.Html;  
88:      }  
89:    
90:    
91:      public Task SendMessage(Message mail)  
92:      {  
93:        var task = Task.Run(() =>  
94:        {  
95:          if (mail == null)  
96:            return Task.FromResult(0);  
97:    
98:          string commonTemplates = Path.Combine(_templatePath, "Message.cshtml");  
99:          string cshtml = File.ReadAllText(commonTemplates);  
100:    
101:          //Add a new message template.  
102:          Engine.Razor.AddTemplate("MessageTemplate", cshtml);  
103:    
104:          string result = Engine.Razor.RunCompile("CommonTemplates", typeof (Message),  
105:            mail);  
106:    
107:          //Use Premailer.net to inline css  
108:          var inlineResult = InlineCss(result);  
109:    
110:          var email = new Email  
111:          {  
112:            To = mail.To,  
113:            Body = inlineResult,  
114:            Subject = mail.Title  
115:          };  
116:    
117:          return Send(email);  
118:        });  
119:        return task;  
120:      }  
121:    }  
122:  }  

Notice that in the constructor that the main mail layout was added. This class has 2 major private methods: InlineCss() and Send(). 

The InlineCss method inlines the block level styles in the mail layout into the html 'styles' tag using the Premailer.net which we added in the beginning. While the SendMessage sends the message using the good old 'System.Net.Mail'.

Another class method worth pointing out at is the SendMessage() public method, this method takes in the Message you are sending, compiles it with the prescribed template calls the InlineCss method and then sends out the message by calling the Send() private method. This method serves as the controller  in the mailer service.

Finally add the system.net.mail configuration in your config file.


1:   <system.net>  
2:       <mailSettings>  
3:        <!--Specify a pick up directory for testing-->  
4:        <smtp from="Kings &lt;admin@oursite.com&gt;" deliveryMethod="SpecifiedPickupDirectory">  
5:         <network host="localhost" />  
6:         <specifiedPickupDirectory pickupDirectoryLocation="c:\users\...\documents\emails" />  
7:        </smtp>  
8:       </mailSettings>  
9:     </system.net>  
10:    

There you have it a background email sender that you can use in any project, be it console, winforms, wpf or asp.net project. Hope it helps someone. Here is the full source code in github. Here is the email I sent using the background sender



Feel free and download and play with source code