ASP.NET Core: Injecting your DB Context into your Controllers

What is Dependancy Injection?

The type of Dependency Injection ill be looking at today can be categorized as “Constructor Injection”.  The idea is that we will inject the needed classes into the constructor, rather than creating or instantiating new objects, thus achieving loose coupling between objects.

When classes are designed with DI in mind, they are more loosely coupled because they do not have direct, hard-coded dependencies on their collaborators. This follows the Dependency Inversion Principle, which states that “high level modules should not depend on low level modules; both should depend on abstractions.” Instead of referencing specific implementations, classes request abstractions (typically interfaces) which are provided to them when the class is constructed. Extracting dependencies into interfaces and providing implementations of these interfaces as parameters is also an example of the Strategy design pattern.
– MS Docs

Dependency Injection is setup in the ConfigureServices method of Startup.cs
This ConfigureServices method is responsible for setting the things that can be injected into our constructors.

Each services.Add extension method adds (and potentially configures) services. For example, services.AddMvc() adds the services MVC requires.
– MS Docs

In this example I will focus on setting up DB Contexts. To learn more about registering your own services check out Microsoft’s docs here.


Creating a New ASP.NET Core Web Application

When you create a new ASP.NET Core Web Application with Authentication your ConfigureServices method and appsetting.json are set up automatically for you. This is a good place to start. You will see that AddDBContext() is in ConfigureServices and the connection string is stored in appsettings.json.  It should look something like this…

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            .................
        }
appsettings.json

{
 "ConnectionStrings": {
 "DefaultConnection": "Server=XXXXXX,1433;Initial Catalog=XXXXXX;Persist Security Info=False;User ID=XXXXXXX;Password=XXXXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
 }
}

This is great, and if it is a part of a new web application, then migrations is auto setup for you.  But what if you have another database that you want to build a model for, set up its context, then inject into your controllers…

Injecting an existing DB and DB Context

If you would like to learn how to “reverse engineer” your database tables into a c# model, check out this post.

If you ran the linked above “scaffold” command to create your model and context, you will see that the  connection string is set in the OnConfiguring() method or you new context.


        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer(@"XXXXXt;Database=XXXXX;user id=XXXXX;password=XXXXX;");
        }

Delete the entire above OnConfiguring() method. Replace it with a constructor for your context (below) and pass it the DB  options that we will setup next, in our Startup.cs class

        public SunstackContext(DbContextOptions<MyNewContext> options) : base(options)
        {
            //any changes to the context options can now be done here
        }

Next, we want to add the database’s connection string to appsettings.json

  "ConnectionStrings": {
    "DefaultConnection": "Server=XXXXX,1433;Initial Catalog=XXXXX;Persist Security Info=False;User ID=XXXXXX;Password=XXXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
    "MyNewConnection": "XXXXXX,1433;Initial Catalog=XXXXX;Persist Security Info=False;User ID=XXXXX;Password=XXXXX;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  },

And then we hook up this DBContext to your services in ConfigureServices()

        public void ConfigureServices(IServiceCollection services)
        {

            // Add User DB connection
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Add My New DB connection
            services.AddDbContext<MyNewContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MyNewConnection")
                ));

            ..........

        }

At this point everything should build!!
We now have the new context setup and ready to inject into a controller.  The last step is very easy, just add our new service to ANY controller’s constructor, here is  simple example.

    public class FileManagerController : Controller
    {
        MyNewContext _myNewContext;

        public FileManagerController(MyNewContext context)
        {
            _myNewContext = context;
        }

    }

 

Angular, Kendo-UI, ASP.NET, and Server Side Paging

It was hard to find a good Angular and ASP.NET example of server side grouping, sorting, and filtering.  Kendo does have good documentation, and examples, but filtering through all the noise can be exhausting.  So here I will show how to setup some basic kendo grid page sorting and filtering.

First you will need to add the following to your app

  • Kendo.Mvc
  • kendo.aspnetmvc.min.js

Setting Up Your Server Side Code

Here is an example in the Kendo docs.

We will use a kendo object called “DataSourceRequest” which will hold information about sorting, grouping, filtering, and ordering.  When used with “ToDataSourceResult()” the list we are returning will automatically be filter down to the parameters that are defined in “DataSourceRequest”. Its pretty slick.

using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;

namespace Test.Example
{

    public class ExampleController : Controller
    {
        // GET api/Example/Get
        [HttpGet]
        public DataSourceResult Get([DataSourceRequest]DataSourceRequest request)
        {
            IList <item> myListToReturn = [Your array of object to return here];
            return myListToReturn.ToDataSourceResult(request);
        }

    }

}

Setting Up Your HTML

I will keep the grid’s “data source” and the grid’s “options” separate just to make things slightly easier to understand. In practiced, they can easily be combined.

<div class="container-fluid" ng-controller="exampleController">
    <div kendo-grid k-options="kendoGridOptions" k-data-source="kendoGridDataSource"></div>
</div>

 

Setting Up Your Angular Conroller

In you angular controller, set up “kendoGridOptions” and “kendoGridDataSource”.


angular.module('myApp', ['kendo.directives']);

angular
    .module('myApp')
    .controller('exampleController', exampleController) 

exampleController.$inject = ['$scope', "$http"];
function exampleController($scope, $http) {

    //Set the grid's options
    $scope.kendoGridOptions = {
        sortable: true,
        groupable: true,
        selectable: true,
        resizable: true,
        pageable: {
            pageSizes: [15, 25, 50, 100, 500]
        }
    };

    //set the data source
    $scope.kendoGridDataSource = {
        transport: {
            read: function (options) {
                var webapi = new kendo.data.transports.webapi({ prefix: "" });
                var params = webapi.parameterMap(options.data);
                $http.get("/api/Example", { params: params })
                    .success(function (data) {
                        options.success(data);
                    })
                    .error(function (data) {
                        options.error();
                    });
            }
        },
        serverPaging: true,
        serverSorting: true,
        serverFiltering: true,
        serverGrouping: true,
        serverAggregates: true,
        pageSize: 15,
        schema: $.extend({}, kendo.data.schemas.webapi, { data: "Data", total: "Total", errors: "Errors" })
    };
};

 

Other Kendo Links

Here are a couple other posts that I have done about Kendo-UI’s Grid tools

Power BI – Connect to your secure API

Power BI’s web portal and desktop application are slightly different, but this tutorial will work for both.

Getting API Data

  1. Open up Power BI and select “Edit Queries”.
  2. Click “New Source” and select “Blank Query”.
  3. Next, select “Advanced Editor”.

    Capture.PNG

  4. In the editor, enter the API’s address and any header information needed for that api.
    let
         apiUrl = "https://xxxxxxx/api/info",
         options = [Headers =[#"Subscription-Key"="xxxxxxxxxxxxxxxxxxxxx"]],
         result = Web.Contents(apiUrl , options)
    in
         result
    

    Capture.PNG

  5. After you add the Query, you will then need to “Connect”. In Power BI Desktop, a warning message pops up letting you know this. Click “Edit Credentials”

    Capture.PNG

  6.  The Access Web content pop-up will show a few different ways to set up you API credentials.  For this example, we just needed to include a “Key” in the header. Since we already did that, all we have to do is press “Connect”.

 

Thats it! You should now be connected and see the results of the api call.  You can “drill” into the results and select what information and object are important to you.  As you do this, check out “Advanced Editor” again.  You will see that slight changes are made to it as you configure the data you want.

Creating your first ASP.NET Core 1.0 Web API with Swashbuckle

Using ASP.Net Core 1.0 Visual Studio 2015 I will walk through how to create a Web API. We will add some basic documentation and hook it up with Swashbuckle and Swagger. The end result is gonna be AWESOME!

Setup the Project

  1. Open up Visual Studio and create a new .Net Core.
    1.PNG
  2. Select the “Web API” template.2.PNG
  3. After the project has been created we need to tell it to export an XML document when it builds. This will allow us to generate a XML doc that will hold our swagger info and comments.
    Right Click the Project > Select “Properties” > Select “Build” > check XML documentation file > Save3.PNG

Setup Project.json and Startup.cs

  1. 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 4x’s package.config). You can remove or add a dependencies from this file. When you do, youre 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 Visual Studio 15 is released. The idea with that move is that settings will move back to the .csproj file to enable better integration with MSBuild in that time frame.

  2. Since we selected the Web API template, the core API dependencies and tools were automatically added to both these files when this project was created. So all we need to do is add the Swashbuckle dependency to the project.json file.- “Swashbuckle”: “6.0.0-beta902”

    Your dependencies property should now look like this:

      "dependencies": {
        "Microsoft.NETCore.App": {
          "version": "1.0.0",
          "type": "platform"
        },
        "Microsoft.AspNetCore.Mvc": "1.0.0",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
        "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
        "Microsoft.Extensions.Configuration.Json": "1.0.0",
        "Microsoft.Extensions.Logging": "1.0.0",
        "Microsoft.Extensions.Logging.Console": "1.0.0",
        "Microsoft.Extensions.Logging.Debug": "1.0.0",
        "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
        "Swashbuckle": "6.0.0-beta902"
      }
    
  3. Next, open up Startup.cs.  In the ConfigureServices method you will need to know the path to your xml comments file which will be automatically generated for you. This path will come from GetSwaggerXMLPath().  Make sure to add the correct xml file name, it will be named [project name].xml.  You also will need to add the swagger service and configure a few properties as shown below:
     private string GetSwaggerXMLPath()
     {
     var app = PlatformServices.Default.Application;
     return System.IO.Path.Combine(app.ApplicationBasePath, [Your Project Name].xml);
     }
    public void ConfigureServices(IServiceCollection services)
    {
                // Add framework services.
                services.AddMvc();
    
                // Swagger services.
                services.AddSwaggerGen();
                services.ConfigureSwaggerGen(options =>
                {
                    options.SingleApiVersion(new Info
                    {
                        Version = "v1",
                        Title = "Test API",
                        Description = "Jesse's Test API",
                        TermsOfService = "None",
                        Contact = new Contact() { Name = "JESSE.NET", Email = "info@test.com", Url = "www.JesseDotNet.com" }
                    });
                    options.IncludeXmlComments(GetSwaggerXMLPath());
                    options.DescribeAllEnumsAsStrings();
                });
    }
    

    You should see the new XML file in your bin folder after you Build. Build your project and check for that now. It will be named [project name].xml

  4. Lastly, add the swagger middle-ware to the Configure method like below:
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
       app.UseMvc();
    
       app.UseSwagger();
       app.UseSwaggerUi();
    }
    

You should now be able to see your Swagger page. Run the project and navigate to http://localhost:XXXXX/swagger/ui/index.html

4.PNG

Add Swag Documentation to your API controllers!

First lets quickly go over what Swagger and Swashbuckle are:

Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment. With a Swagger-enabled API, you get interactive documentation, client SDK generation and discoverability.

-swagger.io

Swashbuckle is basically, a implementation of Swagger for ASP.NET

In addition to its Swagger generator, Swashbuckle also contains an embedded version of swagger-ui which it will automatically serve up once Swashbuckle is installed. This means you can complement your API with a slick discovery UI to assist consumers with their integration efforts. Best of all, it requires minimal coding and maintenance, allowing you to focus on building an awesome API!

-Swashbucket git repo

Now, to get our shiny new Swagger UI to show documentation of our API lets open up ValuesController.cs and add a new method to play with its comments and attributes.

/// <summary>
/// New example api endpoint that returns a int.
/// </summary>
/// <remarks>Pass in a int and this method will add 10 to it and then return it.</remarks>
/// <param name="valueA"></param>
/// <returns></returns>
[HttpGet("ExampleGet/{valueA:int}")]    //inline constraints - route matching does NOT happen if valueA is not a int with this ':int' setting.
[Produces(typeof(int))]                 //adds model and schema to swagger very helpful for passing around objects. 
[Consumes("application/json")]          //Tell this action to only accecpt json objects. Without it, it will accept anything<img width="16" height="16" class="wp-smiley emoji" draggable="false" alt=":)" src="https://s1.wp.com/wp-content/mu-plugins/wpcom-smileys/simple-smile.svg" style="height: 1em; max-height: 1em;">
public IActionResult ExampleGet(int valueA)
{
    try
    {
        valueA = valueA + 10;
        return this.Ok(valueA);
    }
    catch (Exception)
    {
        return this.BadRequest("Fail!");
    }
}

After adding the above method our page will look like this:
5.PNG

and if we try to pass it a non integer into this new endpoint we will get this:
6.PNG

Finished! Congrats!

There is still much to learn, I’d recommend checking out the dotNetConf videos for more .Net Core info.  Also is should be noted that our project above just used the default response formatting which is JSON. The response  data can be configured to things like XML by setting formatters in Startup.cs

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.&lt;wbr /&gt;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"
      }
    }
  }
}

Entity Framework Core: Modeling and Connecting to SQL Views

This post is based on EF Core 1.0 and it will be strictly about adding SQL Views to your Model and Data Context.  If you are interested on how to connect your EF Core 1.0 project to a SQL Server DB then check out this other post about how to reverse engineer and scaffold your SQL Server DB.

The state of EF Core 1.0 and VS2015
Unfortunately, that nice UI you were used too that allowed you to connect and select the tables and views to be mapped out, does not yet exist.  After setting up your project and project.json file you will run a script in the Command Prompt or in the Nuget Package Manager to connect and build out you EF model.  Will look a lil something like this:

Command Prompt Scaffle Command

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

Nuget Package Manager Scaffle Command

Scaffold-DbContext "'Server=SERVERNAME;Database=DATABASENAME;Trusted_Connection=True;'" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

The above commands hook you up to your DB and creates a Model folder that contains all your newly generated classes and DataContext.cs.  But what about my views!?!?  Well, since your DataContext.cs is connected to your DB, you do technically have access to everything in that DB, including SPROCs and Views.  These Views just dont get created for you and there is no real way to access them except through inline SQL or manually adding them.  So lets manually add them together!

Create a new Class for your View

  1. Your project should have a Models folder (if you did everything here). Right click that Models folder and select Add > New Item.. > Class
  2. Name the Class “Team_View” and add this code to it.
    public class Team_View
    {
    public int Team_ID { get; set; }
    public int? Players_Count { get; set; }
    public double? Total_Wins { get; set; }
    public double? Total_Losses { get; set; }
    }
    
    

Add your new View’s Class to DataContext.cs

  1. In the Models folder, open up xxxxDataContext.cs. This file was automatically generated for you.
  2. In this class add this class object:
    public virtual DbSet<Team_View> Team_View { get; set; }
    
  3. In  OnModelCreating(ModelBuilder modelBuilder) add:
    modelBuilder.Entity<Team_View>(entity => { entity.HasKey(e => e.Team_ID); });
    
  4. Your DataContext should now look something like this
    public virtual DbSet<Team_View> Team_View { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.Entity<Team_View>(entity => { entity.HasKey(e => e.Team_ID); });
    
    .......
    }
    

Also, note that the DataContext is a “Shared” class.  So if you don’t want to re-write this code every time you run the update scaffold command, putting code like this Team_View code in a separate shared DataContext.cs file may be the way to go.

Thats It!
You now have access you your View! AND you now have a Class for that view! You can now call it from any lambda/LINQ  query that your want.