Friday, September 30, 2016

Publish data driven ASP.NET MVC 5 app to Azure from Visual Studio 2015

This tutorial attempts to help one easily publish an ASP.NET web application to Azure. An Azure subscription can be obtained through MSDN, Microsoft Imagine (formerly known as Dreamspark), or simply get a free one month $250 trial account from https://azure.microsoft.com/en-us/free/.
For students, get a free account from https://catalog.imagine.microsoft.com/en-us. Although this account is limited in services, it allows a student to host web applications using SQL Azure. Scroll further down the page and click on “Activate Azure benefits for Students”.

image
Once you have secured a subscription, you can go ahead and create an ASP.NET MVC 6 web application. For this tutorial, I am using the free Visual Studio 2015 Community Edition, which you can download and install from https://www.visualstudio.com/downloads/.

Let’s get started. We will first create an ASP.NET MVC 5 web application.
  • Start Visual Studio 2015
  • File >> New >> Project
  • Templates >> Visual C# >> Web >> ASP.NET Web Application (.NET Framework)
  • I named the web application “TryAzureDeploy”. Go ahead and give it whatever name you fancy.
image
  • Click OK.
  • Under “Select a template” select MVC and leave “Host in the cloud” and “Add unit tests” unchecked:
image
  • Click OK.
  • Once the application is created, build it by hitting “Shift + Ctrl + B” on your keyboard.
  • Run the application by hitting “Ctrl + F5” on your keyboard. You will see a fully functional ASP.NET MVC app that looks like this:
image
Our next task is to deploy the app to Azure. Before we do that, it is necessary to install the latest Azure SDK in your Visual Studio before you continue. To do that, click on “Tools >> Extensions and Updates…”
image

Click on Updates on the left-side. If there is an outstanding Azure SDK update, you will see it in the list. At the time of writing, the latest Azure SDK update was version 2.9.5. Make sure you install the latest outstanding version.

image

Before we publish our web application, let us create a database server and database on Azure. Point your browser to https://portal.azure.com and login. Click on “SQL databases” on the left-side:

image
The next step is to create a database server and a database instance. To do that, click on “+ Add” at the top.
image

Once you are done creating the database server and database instance, return to Visual Studio. Right click on the project and select “Publish…”

image
This results in the next dialog being displayed.
image

Click on “Microsoft Azure App Service”.

image

Click New.

image

After you enter the missing data, click on “Create”. This takes you back to the publish wizard’s connection phase.

image

Click Next. At this stage, we will need to get the connection string of the database that was previously created. Return to the Azure portal in your browser and click on your new database:

image

Click on “Show database connection string”.

image

Copy the “ADO.NET (SQL Authentication)” connection string. Paste it into a text editor like notepad.exe. Replace {your_username} and {your_password} with the appropriate username and password for the database server. Thereafter, copy and paste the connection string with the correct username and password into the “ApplicationDbContext (DefaultConnection)” field.

image

Click Next.

image

We are now good to publish. This may take a few minutes. Once it is done, the new website will be open in your default browser. Go ahead and register a new user.

image

image

image

Successfully registering a new user means that the website is indeed working with SQL Azure. Pat yourself on the back.




Saturday, September 24, 2016

SQL Server LocalDB and Code-First .NET Core console application

In this post we will look at building a simple command line .NET Core application that works with SQL Server. The database is created using the Code First development paradigm. The database table will look like this:
image

1) Create a working directory named InstituteSqlServer.

2) From within a command prompt in that folder, type: dotnet new. This creates a Hello-World .NET Core command-line application.

3) Using Visual Studio Code, navigate to the InstituteSqlServer folder to open the project.

4) Open Program.cs , change the namespace to InstituteSqlServer and save the file.

5) To build the “Hello World” command-line app and run it, execute the following commands from the command prompt:
dotnet restore
dotnet build
dotnet run
6) Since we will be accessing SQL Server using Entity Framework, we will need to add the following to the dependencies block of the project.json file:

"Microsoft.EntityFrameworkCore": "1.0.1",
"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.Extensions.Configuration": "1.0.0",
"Microsoft.Extensions.Configuration.Json": "1.0.0"

7) Add another tools section to the project.json file as follows:
"tools": {
  "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview2-final",
    "imports": [
      "portable-net45+win8+dnxcore50",
      "portable-net45+win8"
    ]
  }
}
8) At this stage, it is appropriate to restore all the additional dependencies that we will be using. Therefore, run the following command at the command prompt:

dotnet restore

9) Add a folder named “Models” and add to it a C# class file named Student.cs. Add the following code to Student.cs:
using System;
using System.Collections.Generic;

namespace InstituteSqlServer.Models {
  public class Student {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Major { get; set; }
    public DateTime DateOfBirth { get; set; }

    public static List<Student> GetSampleStudents()   {
      List<Student> students = new List<Student>() {
        new Student {
          FirstName = "Ann",
          LastName = "Lee",
          Major = "Medicine",
          DateOfBirth = Convert.ToDateTime("2004/09/09")
        },
        new Student
        {
          FirstName = "Bob",
          LastName = "Doe",
          Major = "Engineering",
          DateOfBirth = Convert.ToDateTime("2005/09/09")
        },
        new Student {
          FirstName = "Sue",
          LastName = "Douglas",
          Major = "Pharmacy",
          DateOfBirth = Convert.ToDateTime("2006/01/01")
        },
        new Student {
          FirstName = "Tom",
          LastName = "Brown",
          Major = "Business",
          DateOfBirth = Convert.ToDateTime("2000/09/09")
        },
        new Student {
          FirstName = "Joe",
          LastName = "Mason",
          Major = "Health",
          DateOfBirth = Convert.ToDateTime("2001/01/01")
        }
      };
      return students;
    }
  }
}
The above code defines the properties of a Student class and adds a static method GetSampleStudents() that retrieves some sample data.

10) We will save the database connection string in a configuration JSON file. Create a file named appsettings.json in the root of your project with the following content:
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=InstituteDB;Trusted_Connection=True;"
  }
}
11) It is necessary to have a helper method that reads name/value pairs from the appsettings.json configuration file. To this end, we will create a class file named Utility.cs in the Models folder that fulfills this task. This file contains the following code:
using Microsoft.Extensions.Configuration;
namespace InstituteSqlServer.Models {
    public class Utility {
        public static string GetConnectionString(string key) {
            // Defines the sources of configuration information for the
            // application.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json");

            // Create the configuration object that the application will
            // use to retrieve configuration information.
            var configuration = builder.Build();

            // Retrieve the configuration information.
            var configValue = configuration[key];

            return configValue;
        }
    }
}
12) Add another C# class file to the Models folder named InstituteContext.cs with the following code:
using Microsoft.EntityFrameworkCore;
namespace InstituteSqlServer.Models {
    public class InstituteContext : DbContext {
        public DbSet<Student> Students { get; set; }
        protected override void OnModelCreating(ModelBuilder builder) {
            builder.Entity<Student>().HasKey(m => m.Id);
            base.OnModelCreating(builder);
        }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  {
            string constr = Utility.GetConnectionString("ConnectionStrings:DefaultConnection");

            optionsBuilder.UseSqlServer(constr);
        }
    }
}
13) When the application is built, the .dll file is created in a directory somewhere under the bin folder. We need to make sure that the appsettings.json file is also copied to the same directory as the .dll file so that it can be read by the application. This is accomplished by adding the following to the “buildOptions” section of the project.json file:

"copyToOutput": {
  "include": [ "appsettings.json" ]
}
14) It is time to build our application. At a command-prompt in the project folder, type the following command:
dotnet build
15) It is now possible for us to create the database using Entity Framework’s code-first paradigm. While in the command prompt, execute the following two EF commands:
dotnet ef migrations add FirstMigration
dotnet ef database update
Upon completion of the above EF commands, the database will have been created.

16) We are now in a position to add and retrieve data to and from the database. Add the following two methods to your Program.cs file:
private static void addStudents() {
    using (var db = new InstituteContext()) {
        db.Students.AddRange(Student.GetSampleStudents());
        var count = db.SaveChanges();
        Console.WriteLine("{0} records saved to database", count);
    }
}
private static void displayStudents() {
    using (var db = new InstituteContext()) {
        Console.WriteLine();
        Console.WriteLine("All students in database:");
        foreach (var s in db.Students) {
            Console.WriteLine("{0}\t{1}\t{2}", s.Id, s.FirstName, s.LastName);
        }
    }
}
17) Resolve the namespace for the Student and InstituteContext classes in Program.cs.

18) Replace the Main() method on Program.cs with the following:
public static void Main(string[] args) {
    addStudents();
    displayStudents();
}
19) This final step is the most exciting. If you run the application, it should add data to the Students table in the database and retrieve its contents. Can’t wait, lets do it. Execute these commands from the command prompt:
dotnet build
dotnet run

20) You can celebrate if you see the following results:
Project InstituteSqlServer (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
5 records saved to database
All students in database:
1 Ann Lee
2 Bob Doe
3 Sue Douglas
4 Tom Brown
5 Joe Mason

In order to use this application on Linux or the Mac, it is advisable to use the SQLite database instead of SQL Server. This is the topic for my next post.


Related Posts:

SQLite DB and Code-First .NET Core console application
PostgreSQL DB and Code-First .NET Core console application

Building a simple command-line application using .NET Core and Visual Studio Code

I am planning to write a series of blogs posts to introduce application and web developers to the all new .NET Core framework. This article is intended as an introductory lesson on the very basics of .NET Core. Unlike previous version of the .NET framework, .NET Core is open source, cross platform, cross device, small, and fast.

Our first task is to build a simple command-line application with .NET Core version 1.0.0. We will use the light weight Visual Studio Code for our text editor.

1) Create a working folder named “Institution”

2) Change directory into the “Institution” node and type in
dotnet new
This creates a .NET Core “Hello World” project containing two files: Program.cs and project.json.

3) Start Visual Studio Code and open this project folder. There are two others ways, I know of, that can achieve the same result:
a. In the command-line, change directory to the “Institution” folder and type “code .”. This will open up your project folder contents in Visual Studio Code in the current directory (.).
b. Alternatively, navigate to the “Institution” folder using File Explorer (in Windows). Right-click on the folder and select “Open with Code”.
4) Once in Visual Studio Code, you can view the contents of this file. The Program.cs file looks like this:
using System;
namespace ConsoleApplication {
  public class Program {
    public static void Main(string[] args) {
      Console.WriteLine("Hello World!");
    }
  }
}
The project.json file looks like this:
{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {},
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}
The project.json file has NuGet dependencies necessary to build our console app. You may also notice the presence of another file named project.lock.json. This file is auto-generated and expands on project.json with more detailed dependencies required by your application. There is no need to commit file project.lock.json to source control.

5) Change the namespace from ConsoleApplication to Institution. Also, change the statement Console.WriteLine("Hello World!"); to
Console.WriteLine("Welcome to our institution!");
6) Save and back in the command prompt, type in:

dotnet restore

This instruction causes dependencies to be brought in from the NuGet repository

7) To execute the application, you can simple run the following command from the command-line:

dotnet run

“dotnet run” calls “dotnet build” to ensure that the app has been built, and then calls “dotnet institution.dll” to run the application. You can find the resulting institution.dll file in the bin\Debug\netcoreapp1.0 directory. Notice that the build process does not produce a institution.exe file. This is because we just created a portable app. Instead of creating a portable app, let us produce a self-contained .exe app.

Note that the name of the .dll file is dictated by the name of the primary project folder, and not by the name of your primary class file (Program.cs).

Compiling a self-contained .exe app

We will need to make some changes to the project.json file.

1) Delete the "type": "platform" element from all dependencies.

2) Next, add a new runtimes node as follows:
"runtimes": {
  "win10-x64": {},
  "osx.10.11-x64": {}
}

This causes the build system to generate native executables for the current environment. In Windows, you will build a Windows executable. On the Mac, you will build the OS X executable.
Save the project.json file, then run the following commands from the command-line:
dotnet restore
dotnet build

The self-contained .exe file can be found at bin\Debug\netcoreapp1.0\win10-x64\Institution.exe.
You can execute the institution.exe file by typing the following on the command line while in the Institution folder:
      bin\Debug\netcoreapp1.0\win10-x64\hello.exe
or simply:
      dotnet run
Let us add a Student class to the project. It is good practice to organize our files in folders. This is especially beneficial when you are dealing with large projects. Therefore, create a folder named Model and add to it a Student.cs class file with the following code:

using System;
using System.Collections.Generic;
namespace Institution.Models {
  public class Student {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Major { get; set; }
    public DateTime DateOfBirth { get; set; }

    public static List<Student> GetSampleStudents()   {
      List<Student> students = new List<Student>() {
        new Student {
          Id = 1,
          FirstName = "Ann",
          LastName = "Lee",
          Major = "Medicine",
          DateOfBirth = Convert.ToDateTime("2004/09/09")
        },
        new Student
        {
          Id = 2,
          FirstName = "Bob",
          LastName = "Doe",
          Major = "Engineering",
          DateOfBirth = Convert.ToDateTime("2005/09/09")
        },
        new Student {
          Id = 3,
          FirstName = "Sue",
          LastName = "Douglas",
          Major = "Pharmacy",
          DateOfBirth = Convert.ToDateTime("2006/01/01")
        },
        new Student {
          Id = 4,
          FirstName = "Tom",
          LastName = "Brown",
          Major = "Business",
          DateOfBirth = Convert.ToDateTime("2000/09/09")
        },
        new Student {
          Id = 5,
          FirstName = "Joe",
          LastName = "Mason",
          Major = "Health",
          DateOfBirth = Convert.ToDateTime("2001/01/01")
        }
      };
      return students;
    }
  }
}



























The above code describes a Student class with properties: Id, FirstName, LastName, Major, and DateOfBirth. It also generates some dummy data that can be accessed through the GetSampleStudents() static method.
Back in Program.cs, replace the Main() method with the following:
public static void Main(string[] args) {
  List<Student> students = Student.GetSampleStudents();
  foreach(var i in students) {
    Console.WriteLine("{0}\t{1}\t{2}", i.Id, i.FirstName, i.LastName);
  }
}
Do not forget to resolve the Student and List classes by using the following namespaces:

using System.Collections.Generic;
using Institution.Models;
If you run the application by executing “dotnet run” from the command-line, you should see the following output:

1 Ann Lee
2 Bob Doe
3 Sue Douglas
4 Tom Brown
5 Joe Mason
In future posts, I am hoping to explore more complicated data driven apps developed using .NET Core. Meantime, I hope you benefited from this article.