Sunday, October 2, 2016

Visual Studio Team Service (VSTS) – checkin ASP.NET Core WebAPI into VSTS

In this post I will show you how to develop a simple ASP.NET Core WebAPI application in Visual Studio 2015 and check-it into Visual Studio Team Services (VSTS).

Pre-requisites: It is assumed that you already have a VSTS account and that you are using Visual Studio 2015 (or later).

1) File >> New >> Project

2) Templates >> Visual C# >> Web >> ASP.NET Core Web Application (.NET Core)

image

image

3. Hit “Ctrl + F5” to see what our application looks like.

image
4. You will notice a controller named ValuesController.cs that spits out string values. Let’s rename the controller file name to CartoonController.cs

5. Edit the launchSettings.json file under Properties and change all instances of api/values to api/cartoon. There are two instances that will be changed.

6. Unzip images.zip and copy the folder under wwwroot. The folder structure will look like this:

image

7. In the CartoonController class, replace the contents of the Get() action method with the following code:
string webRootPath = _hostingEnvironment.WebRootPath;
string[] characters = System.IO.Directory.GetFiles(webRootPath + "/images");

List<string> charactersList = new List<string>();
foreach (var item in characters) {
  string relativeAddress = System.IO.Path.GetFileName(item);
  relativeAddress = "images/" + relativeAddress;
  charactersList.Add(relativeAddress);
}
return charactersList;
8. The Visual Studio WebAPI template does not allow static files to be served. Therefore, we will need to change that by the appropriate middleware. Add the following dependency into the project.json file:
"Microsoft.AspNetCore.StaticFiles": "1.0.0"
Thereafter, add this method call in the Startup.cs file’s Configure() method, just before app.UseMvc();
app.UseStaticFiles();
9. Let’s test what we have done so far. Hit “Ctrl + F5” to run the application. You should see a page like this in your browser:

image

10. Change the URL in the address bar to serve one of the images by replacing api/cartoon with images/bambi.png (for example). You should see the appropriate image being displayed in your browser:

image

11. Next, let us work on the next action method that allows us to get an individual cartoon character. Replace the Get(int id) method with the following code:
[HttpGet("{name}")]
public string Get(string name) {
  return "images/" + name + ".png";
}
12. Tweak your browser address URL so that it makes a request for (say) bambi by requesting /api/cartoon/bambi. You will get a response that looks like this:

image

At this stage, our web app is ready for adding into source control. In this tutorial we will add it to VSTS.

13. Create a new project in VSTS.

image

14. Click on “Invite a friend” and add team members.

image

15. Back in Visual Studio 2015, go into the “Team Explorer” pane and click on the “Manage connections” button that looks like a plug:

image

16. You are taken to the “Connect” page:

image

17. Click on the “Manage Connections” link >> Connect to team project.

image

18. Click on the “Servers” button.

image

19. Click on the “Add” button and enter the URL of the team site.

image

20. You will next see all the VSTS sites that you can participate in:

image

21. Click on Close.

image

22. Select the team project (in the example above it is ‘Cartoon Characters API’) then click on Connect.

image

23. At this stage, it is necessary to map a local directory to the server project. Click on the “Configure your workspace” link in the Team Explorer pane in Visual Studio 2015.

image

24. Navigate to the location of the project on your local file system then click on “Map & Get”.

image

25. Back in “Team Explorer”, click on “Pending Changes”.

image

26. There does not appear to be any included changes. However, there is a link that shows detected changes. Click on that link.

image

27. Click Promote. You will see that all the files that make up your project are now included.

image

28. We can now commit our files to VSTS.

image

29. Enter a comment then click Checkin. All the code is now on VSTS. You can share it with the team, collaborate on it, and version the code.

30. If you back into VSTS in your browser and select the project that we uploaded our files to, we can see that it has all been pushed to the server. Here’s the code for the Startup.cs file in VSTS:

image

Continue with this post if you decide to use Azure for continuous integration with Azure.

Saturday, October 1, 2016

PostgreSQL DB and Code-First .NET Core console application

In previous posts I showed how to build console .NET Core applications that use the EF Code First model to connect with SQL Server (http://blog.medhat.ca/2016/09/codefirst-with-net-core-command-line.html) and SQLite (http://blog.medhat.ca/2016/10/codefirst-with-net-core-console.html). In this post we will look at building a simple console .NET Core application that works with database server PostgreSQL. The database is created using the Code First development paradigm.
This is taken from https://www.postgresql.org/about/:
PostgreSQL is a powerful, open source object-relational database system. It has more than 15 years of active development and a proven architecture that has earned it a strong reputation for reliability, data integrity, and correctness. It runs on all major operating systems, including Linux, UNIX (AIX, BSD, HP-UX, SGI IRIX, Mac OS X, Solaris, Tru64), and Windows. It is fully ACID compliant, has full support for foreign keys, joins, views, triggers, and stored procedures (in multiple languages). It includes most SQL:2008 data types, including INTEGER, NUMERIC, BOOLEAN, CHAR, VARCHAR, DATE, INTERVAL, and TIMESTAMP.
You can download PostgreSQL from https://www.postgresql.org/download/. Make sure you remember the password you entered because it belongs to the default super user named “postgres”.
After you download and install the software you can run the PostgreSQL management console by finding and launching “pgAdmin 4”.

image

When you double click on “PostgreSQL 9.6”, you will be prompted for the “postgres” password which you entered during installation. You can save the password if you enable the “Save Password” checkbox.

image

In the real world, you would not save the password in a production environment. I am saving the password for convenience as I am, essentially, in a test environment.

You can create a database named “test” and experiment with these SQL queries:
CREATE  TABLE employee (id SERIAL PRIMARY KEY, name VARCHAR(30) );
INSERT INTO employee (name) VALUES ('SAM');
SELECT * FROM employee;
This would create an employee table in the test database:

image

The command-line utility of PostgreSQL is psql. Find and launch SQL Shell (psql). Choose default values for Server [localhost], Database [postgres], Port [5432] and Username [postgres]. However, when prompted for “Password for user postgres:”, put the password you entered during installation.
To use the test database, enter “\c test;”. Remember to terminate all psql commands with the semicolon (;).

Next, let us view the contents of our employee table. Enter the following in the psql shell:
SELECT * FROM employee;
You should see the following:
id | name
----+------
  1 | SAM
(1 row)
To exit psql type “\q”.

Let is start building a simple console .NET Core app that uses the following Student entity:

image
1) Create a working directory named InstitutePostgreSQL.

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

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

4) Open Program.cs and change the namespace to InstitutePostgreSQL then save the file.

5) To build the “Hello World” console app and run it, execute the following from the command prompt:
dotnet restore
dotnet build        (optional)
dotnet run
6) Since we will be accessing PostgreSQL using Entity Framework, we will need to add the following to the dependencies block of the project.json file:
"Microsoft.EntityFrameworkCore": "1.0.1",
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.2",
"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 new additional dependencies that we will be using. Therefore, execute the following 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 InstitutePostgreSQL.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": "User ID=postgres;Password=password;Host=localhost;Port=5432;Database=InstituteDB;Pooling=true;"
  }
}
Ensure that you enter the correct password for username postgres.

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 InstitutePostgreSQL.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 InstitutePostgreSQL.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.UseNpgsql(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 appsettings.json is also copied to the same directory as the dll file so that it can be read. 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:
dotnet build
15) We can now 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 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.

18) Replace the Main() method in Program.cs with the following:
public static void Main(string[] args) {
    addStudents();
    displayStudents();
}
19) This final step is the most revealing. If you run the application, it should add data to the Students table in the database and retrieve its contents. Excited … lets do it. Execute the following from the command prompt:
dotnet build
dotnet run
20) If all goes well, you see the following results:
All students in database:
1       Ann     Lee
2       Bob     Doe
3       Sue     Douglas
4       Tom     Brown
5       Joe     Mason
Since we are using PostgreSQL with .NET Core, this application can run equally well on Windows, Linux and the Mac. This is also true of SQLite discussed in a previous post.

Related Posts:

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

SQLite DB and Code-First .NET Core console application

In a previous post (http://blog.medhat.ca/2016/09/codefirst-with-net-core-command-line.html), I showed how to build a console .NET Core app that uses the EF Code First model with SQL Server. In this post we will use SQLite instead. The advantage of SQLite is that it is free, stable and runs on Windows, Linux, Mac, IoS, Android, etc…

A useful utility that comes in handy when working with the SQLite database is SQLiteStudio. Download SQLiteStudio from: http://sqlitestudio.pl/?act=download. Extract the ZIP file and place contents in a separate folder. Run SQLiteStudio.exe.

In this post we will look at building a simple console .NET Core application that works with SQLite. The database is created using the Code First development paradigm. We will build a simple console .NET Core app that uses the following Student entity:
image

1) Create a working directory named InstituteSQLite.

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

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

4) Open Program.cs and change the namespace to InstituteSQLite then save the file.

5) To build the “Hello World” console app and run it, execute the following from the command prompt:
dotnet restoredotnet build                 (optional)dotnet run
6) Since we will be accessing SQLite 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.Sqlite": "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 new additional dependencies that we will be using. Therefore, execute the following at the command prompt:
dotnet restore
9) Add a folder named “Models” and add to it a C# class file named Student.cs. with the following code:
using System;
using System.Collections.Generic;
namespace InstituteSQLite.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 dummy 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": "Data Source=institute.sqlite"
  }
}
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 InstituteSQLite.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 InstituteSQLite.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");
            string path = System.IO.Directory.GetCurrentDirectory();
            constr = constr.Replace("=", "=" + path + "\\");

            optionsBuilder.UseSqlite(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. 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:
dotnet build
15) We can now 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 can now add and retrieve data to and from the database. Add the following 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.

18) Replace the Main() method in Program.cs with the following code:
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 the following from the command prompt:
dotnet build
dotnet run
20) If all goes well, you see the following results:
All students in database:
1       Ann     Lee
2       Bob     Doe
3       Sue     Douglas
4       Tom     Brown
5       Joe     Mason

Because we are using SQLite with .NET Core, this application will run equally well on Windows, Linux and Mac platforms.


Related Posts:

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

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.