Entity Framework Core 1.0 : Reverse Engineering the Model (Database First Development)

This article uses Entity Framework Core 1.0.0

Database First Microsoft docs here

and here are the steps to build out your model from an existing database (aka. reverse engineer).

Create a new ASP.NET Web Application

c1.PNG

 

Open up your Package Manager Console

  1. Open Tools > NuGet Package Manager > Package Manager Console

    After we type in a command, the packages will automatically install in the background.  While the install is in progress you will see “(Restoring…)” next to the projects References folder.

  2. Type these 3 commands in the Package Manager Console: Install-Package Microsoft.EntityFrameworkCore.SqlServer –Pre
    Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
    Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design –Pre

Your Package Manager Console should look something like this:

pmc.PNG

Open up your project.json file

  1. Add “Microsoft.EntityFramworkCore.Tools” to the “tools” section. It should end up looking something like this:
"tools": {
  "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview1-final",
    "imports": [
      "portable-net45+win8+dnxcore50",
      "portable-net45+win8"
    ]
  },
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": {
    "version": "1.0.0-preview1-final",
    "imports": "portable-net45+win8+dnxcore50"
  }
},

Run Auto Scaffold Command in Package Manager Console  (First Option)

  1. First, create a folder in your project named “Models”
  2. Second,  run this command in the Package Manager Console with your server and db info (note: single quotes around connection string, very unusual)
Scaffold-DbContext "'Server=SERVERNAME;Database=DATABASENAME;Trusted_Connection=True;'" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

if connecting to a secure db, use something like this (note: no single quotes needed here! effin crazy!)

Scaffold-DbContext "Server=SERVERNAME;Database=DATABASENAME;user id=USERNAME;password=USERPASSWORD;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

After successfully running the above command, your project should now look something like this:

models.PNG

Run Auto Scaffold Command in Command Prompt  (Second Option)

Another way to run these commands is through the Command Prompt.  To run the scaffold command, open up your command prompt and navigate to the projects root folder.  Then run a command that looks like this:

dotnet ef dbcontext scaffold "Server=SERVERNAME;Database=DATABASENAME;user id=USERNAME;password=USERPASSWORD;" Microsoft.EntityFrameworkCore.<wbr />SqlServer -o Models  --context MyDBDataContext --verbose

Thats it! This is suppose to become easier with the new version of Visual Studio.  Also, if your wondering how to get your SQL Server Views into your data context, check out this post.

 

Create your first ASP.NET Core 1.0 App From Scratch

A quick walk through of ASP.NET Core 1.0 on how to set up a MVC application from a “Blank” project.  Part 2, will demonstrate how to add Angular to your Core 1.0 App.

Create your web app!

Open up Visual Studio and select File > New > Project.  If you have ASP.NET Core 1.0 or higher installed (here is the .Net Core Installation guide) you should see and exciting new category under Templates > Visual C#  called .Net Core!
c1.PNG

  1. Select “ASP.NET Core Web Application”, give it a name, and click “OK”.
  2. Select the “Empty” template if asked.

Setup Project.json

Open up your project.json file. This will be new to you if you haven’t played with previous releases of vNext.

What is project.json?

Introduced in the first versions of ASP.Net vNext (which is now called ASP.NET Core), the project.json file defines your package metadata, your project dependencies and which frameworks you want to build for. (relatively similar to ASP.NET 4.x’s package.config). You can remove or add a dependency from this file. When you do, you’re solution will automatically be updated to reflect those changes. You can also set what frameworks you want your app to compile across here! Note that Microsoft has stated that project.json may go away around the time the next version of Visual Studio is released. The idea is that settings will move back to the .csproj file to enable better integration with MSBuild in that time frame.

To create a basic MVC app you will need to add the following dependencies to project.json:

  • “Microsoft.AspNetCore.Mvc”: “1.1.0”
  • “Microsoft.AspNetCore.StaticFiles”: “1.1.0”
  • “Microsoft.Extensions.Configuration.FileExtensions”: “1.1.0”
  • “Microsoft.Extensions.Configuration.Json”: “1.1.0”

And you will need to make sure “buildOptions: preserveCompilationContext” is set to true. After making these changes, your project.json should now look like this:

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.1.0",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.0",
    "Microsoft.Extensions.Configuration.Json": "1.1.0"
 
  },
 
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },
 
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
 
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
 
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
 
  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },
 
  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Save and compile the project.json file and you should see that these packages have been added to your project’s references.

c2.PNG

Add the  ASP.NET Cofiguration file

Right-click your project > Add New… > Select new ASP.NET Configuration File and name it appsettings.json

c4.PNG

What is appsettings.json?

This is used to do some of what the web.config previously did.  It is hooked up to the applications Startup.cs file and can be used to set up things like database connections and logging preferences.

Setup Startup.cs

The Startup.cs file will look the same as it did in RC1.  The 3 main things we will change for our basic example application are the following:

  • Add a Startup() constructor method and link it to appsettings.js
  • Add the MVC service to ConfigureServices()
  • Configure the MVC the default routes (this replaces the old route config file) and tell the app to use static files in Configure()

After the above changes have been made, your Startup.cs should now look like this:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace NewProject
{
    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Lastly, add your Controllers and Views

Right-Click your project and add 3 new folders.

  • Controllers folder
  • Views folder
  • Home folder, inside of the Views folder

Next, right-click the Home folder and add a new MVC View Page. Name it “Index.cs” and add some “Hello World” text to it.

After adding these folders and file, your project will now look like this:

c3.PNG

Finished!!!!

Check out the final project on GitHub
Build and run your application.  Congrats on keeping up with the cutting edge of .Net

Publish existing .Net Application to GitHub: Visual Studio 2015

I just went the past year without using GitHub 😦  The projects I have been working on since then have relied only on TFS.  This blog post is an attempt to re-remember how to publish and existing project (In my case, an ASP.NET Web App) and now that its written I wont have to re-remember it next time!

Getting Set Up

  • Set up a GitHub account here.
  • Download GitHub Extension for Visual Studio here.
  • Connect Visual Studio to your GitHub account by clicking on the green plugin. Then selecting “Manage Connections”.
    Capture.PNG
  • After you’re connected, navigate back to the Team Explorer’s Home page. Select “Settings”.

    1.PNG

  • Next, enter your GitHub Username and Email.  Also, set your default repository location.  This is where your projects should be in order to publish them up to GitHub.

    2.PNG

Publish a Project or Solution to GitHub

  • Create any project or solution you like, or open up and existing one.  Either move or save your new project to the Default Repository Location that you entered above.   For this example I’m going to create a new ASP.NET Web Application and I will save it to C:\WorkSpace\GitHub
  • Right click the Solution and select “Add Solution to Source Control”.

    3.PNG
    You should see this in the output window
  • Next, reopen Team Explorer and select “Sync”. You should see a few different option, since we are publishing to GitHub choose that option.

    4.PNG

  • Enter some comments and then click “Publish”!

    5.PNG

  • After you click “publish”, log into GitHub and you should see your project there!

    6.PNG

 

Commit and Push changes

  • Open up your solution and make any change you want to it or any projects within it. Save those changes > Right-Click solution > select “Commit”
    You should see the changes dialog, similar to below.
    If you don’t see this, then go back to the Team Explorer and click “Changes”.

    7.PNG

  • After entering some comments,  select “Commit All”. You can also select “Commit All and Push”, but I’m going to split this up into two separate steps for this tutorial.

 

Next, let’s push this commit to our GitHub repository.  To do this go to the Team Explorer and click “Sync”.

8.PNG

  • Check it out above, its your commit!  Now just click “Push” to publish it to GitHub!  That’s the last step. If you go to your GitHub page you should see your commit and its comments.

9.PNG

Kendo UI Grid and AngularJS: Formatting and Filtering JSON Dates and other tricks

I want to go over some more advanced Kendo UI Grid settings when using Angular and when receiving a list of records in a JSON format.  For some examples of setting up a simpler/basic Kendo Grid with Angular.js check out this blog post.

One of the best things about the Kendo UI Grid is how customization it is.  But with great flexibility comes some complication.  I’ve found it easiest to split my angular grid variables into 2 separate pieces:

  • The Kendo Data Source
  • The Kendo Grid Options

The HTML

<div kendo-grid k-options="kendoGridOptions" k-data-source="kendoGridDataSource"></div>

Defining the Kendo Data Source

Add the following to your angular controller.  You will see that we are dealing with an array of JSON objects.  By default, the JSON object is treating each field as a string and so we will need to tell the data source which fields to define as numbers and dates.

//Set up grid data source and schema
$scope.kendoGridDataSource = new kendo.data.DataSource({
    data: jsonArrayHere,
    pageSize: 15,
    schema: {
        model: {
            fields: {
                Created_Date: {
                    type: "date",
                    parse: function (data) { if (data == null) return null; return new Date(data); }
                },
                Start_Date: {
                    type: "date",
                    parse: function (data) { if (data == null) return null; return new Date(data); }
                }
                Project_Count: { type: "number" },
                Record_ID: { type: "number" }
                }
              }
            }
});
 

Defining the Kendo Grid Options

//Set up grid options and properties
                   $scope.kendoGridOptions = {
                       toolbar: ["excel", "pdf"],
                       excel: {
                           fileName: "ExampleA.xlsx",
                           allPages: true,
                       },
                       pdf: {
                           fileName: "ExampleB.pdf",
                           allPages: true,
                       },
                       sortable: true,
                       groupable: true,
                       selectable: true,
                       resizable: true,
                       columnMenu: true,
                       pageable: {
                           pageSizes: [15, 25, 50, 100, 500]
                       },
                       filterable: {
                           extra: false,
                           operators: {
                               date: {
                                   gt: 'After',
                                   lt: 'Before',
                                   eq: 'Equal to'
                               },
                               string: {
                                   contains: "Contains",
                                   startswith: "Starts with",
                                   eq: "Is equal to",
                                   neq: "Is not equal to"
                               }
                           }
                       },
                       columns: [
                       { field: "Record_Name", title: "Name", template: "<a href=\"../team/details/#: Record_ID #\">#: Record_Name #</a>" },
                       { field: "Created_Date", title: "Date Created", template: "#if(Created_Date != null) {# <div>#= kendo.toString(kendo.parseDate(Created_Date), 'MM/dd/yyyy') #</div>#} #" },
                       { field: "Start_Date", title: "Date Started", template: "#if(Start_Date != null) {# <div>#= kendo.toString(kendo.parseDate(Start_Date), 'MM/dd/yyyy') #</div> #} #" },
                       { field: "LookupField", title: "Lookup Filter Example", filterable: { multi: true } },
                       { field: "Project_Count", title: "Count" },
                       { field: "Record_ID", title: "ID", hidden: true },
                       { field: "Hidden_Field", title: "Hidden Example", hidden: true }
                       ]
                   };

What did we just do?

4.PNG

Capture.PNG

 

toolbar: [“excel”,”pdf”]: Here I am adding two buttons to the top of the grid. One to export the grid data as a excel spreadsheet and the other as a PDF. Just below the “toolbar:” property I am setting the file name and page properties of each export.

columnMenu: true  – I like to have all of the search, sort, and filter actions tucked away inside a drop-down for every column.  To do this set the “columnMenu” property.

filterable: {}  – I only want to show a few filter options depending on the field type.  It is within here that I set those filter operators.

column links  –  To have text in a column show up in the grid as a link, check out the “Record_Name” template above.  This example displays the name, but creates a link based upon its “Record_ID”.

column dates  –  Check out the templates of “Created_Date” and “Start_Date” to see how to format dates javascript dates to ‘MM/dd/yyyy’.  You’ll notice that I have to first check for a null date value and then convert it into a string otherwise the grid would display unwanted date information.

columns [{filterable: { multi: true }}]  – This enables filtering via a checkbox list in the grid filter menu.  Pretty cool stuff.  More information and example of this.

columns [{hidden: true}]  –  Hide the column by default, but list it in the column menu dropdown so that the user can choose to add it to the data grid.

ASP.NET Core 1.0 RC2 Environment Variables

This post has been updated to reflect Core 1.0 RC2 which was release mid may 2016.

Getting Started

A full list of environment variables can be founder here.
In RC 1, the environment variables  are set up in Properties > launchSettings.json.

1ls.PNG

What are Environment Variables?

“ASP.NET Core introduces improved support for controlling application behavior across multiple environments, such as development, staging, and production. Environment variables are used to indicate which environment the application is running in, allowing the app to be configured appropriately.” – from docs.asp.net

In short, its common and easy to set up different environments such as:

  • Development
  • Staging
  • Production

And these “environments” have “environment variables” that can affect what your application does during run-time. Further more, you can build logic into your application, instructing it to perform different behaviors based upon its “environment”.

The ASPNETCORE_ENVIRONMENT variable

The ASPNETCORE_ENVIRONMENT (formerly known as ASPNET_ENV) variable defines what environment you are running in,  and if you have a startup class ending with this name then it will be call the configure method of that class instead of Startup.cs. e.g. StartupDEV if ASPNETCORE_ENVIRONMENT is equal to DEV

Startup.cs

To reference your hosting environment in Startup.cs you will need to inject IHostingEnvironment. IHostingEnvironment is needed because it contains a property name “EnvironmentName”.  You can inject this into any method, but we want to inject it into the Startup() method.

public Startup(IHostingEnvironment env)
{
    // Set up configuration sources.
    var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json");
  
    if (env.IsEnvironment("Development"))
    {
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    else if (env.IsEnvironment("Staging"))
    {
        //else if staging
    }
    else
    {
        //else... do something cool
    }
  
    builder.AddEnvironmentVariables();
    Configuration = builder.Build().ReloadOnChanged("appsettings.json");
}

You can also reference them this way:

env.IsDevelopment()
env.IsProduction()
env.IsStaging()

Here is a list from the doc.asp.net blog listing examples of features you would only want in production.

  • Turn on caching
  • Ensure all client-side resources are bundled, minified, and potentially served from a CDN
  • Turn off diagnostic ErrorPages
  • Turn on friendly error pages
  • Enable production logging and monitoring (for example, Application Insights)

And here is an example of turning on  Application Insights only for production:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
  
            if(env.IsProduction())
            {
                app.UseApplicationInsightsRequestTelemetry();
                app.UseApplicationInsightsExceptionTelemetry();
            }
  
  
            app.UseStaticFiles();
  
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Setting your Environment Variable and launchSettings.json

There are a few ways to set your Environment Variables.  You can add the variable to your machine in your control panel under Advanced System Settings > Environment Variables (but you would have to do this to all of the places you run/test/develop) OR you can hard code some variable values in launchSetting.json for certain situations.

I prefer to do the latter for dev and staging.
The below example will set your ASPNETCORE_ENVIRONMENT to “Development” when running in Visual Studio, it will set it to “Staging” when published to a staging site. For production, if you have a system environment variable named ASPNETCORE_ENVIRONMENT (set to “Production”) wherever you host your production site, your app will then be set to “Production”.
Note: the variables them-self are case insensitive.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:XXXXX",
      "sslPort": XXXXX
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "web": {
      "commandName": "web",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Staging"
      }
    }
  }
}