Using multiple hosting environments on the same machine in ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. This short post about how to set the hosting environment in ASP.NET Core.

However, if this is a capability you think you will need, you can use a similar approach to the one I use in that post to set the environment using command line arguments.

This approach involves building a new IConfiguration object, and passing that in to the WebHostBuilder on application startup. This lets you load configuration from any source, just as you would in your normal startup method, and pass that configuration to the WebHostBuilder using UseConfiguration. The WebHostBuilder will look for a key named "Environment" in this configuration, and use that as the environment.

For example, if you use the following configuration.

 You can pass any setting value with this setup, including the “environment variable”:

This is fine if you can use command line arguments like this, but what if you want to use environment variables? Again, the problem is that they’re shared between all apps on a machine.

However, you can use a similar approach, coupled with the UseEnvironment extension method, to set a different environment for each machine. This will override the ASPNETCORE_ENVIRONMENT value, if it exists, with the value you provide for this application alone. No other applications on the machine will be affected.

To test this out, I added the MYCOOLPROJECT_ENVIRONMENT key with a value of Staging to the launch.json file VS uses when running the app:

Running the app using F5, shows that we have correctly picked up the Staging value using our custom environment variable:

With this approach you can effectively have a per-app environment variable that you can use to configure the environment for an app individually.

Summary

On shared hosting, you may be in a situation when you want to use a different IHostingEnvironment for multiple apps on the same machine. You can achieve this with the approach outlined in this post, building an IConfiguration object and passing a key to WebHostBuilder.UseEnvironment extension method.

How To Create Help Desk Web Application using ASP.NET Core

How To Create Help Desk Web Application using ASP.NET Core

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. Suppose you work for a small to midsize company that employs 50-100 workers. The Help Desk — a subsidiary of the Information Services Division — is in charge of trouble tickets regarding general PC issues such as email, viruses, network issues, etc. Initially, the Help Desk team stored this information in Excel spreadsheets, but as the company has grown, managing these spreadsheets has become tedious and time consuming.

coverASPNETCORE

The Help Desk has asked you to devise a more efficient solution that could be developed internally, saving the company money. As you start to think about it, the following requirements are apparent: fields for the submitter’s first and last name, as well as their email address. You’ll also need combo boxes for indicating ticket severity (low, medium, high), department, status (new, open, resolved), employee working on the issue, as well as an area for comments. Of all the solutions available, creating an internal help desk Web application with ASP.NET is relatively simple.

In the following article, we’ll see how to implement these features in an ASP.NET help desk Web application using a database-driven approach,
Creating the JavaScript File
Because creating the JavaScript file is the easiest of the work left, we’ll do this next. From the Solution Explorer, follow these steps:

Creating the Help Desk Class

Now that we have our data coming in, we need to be able to record a help desk ticket submission. We need to create an event handler in a class to handle it. Let’s first create a help desk class by doing the following:

  •     Right click the project solution.
  •     Choose Add>New Item.
  •     In the Add New Item window, select Class.cs.
  •     In the name text field, type “HelpDesk” and then click Add.

Double click HelpDesk.cs from the Solution Explorer, which will show the empty class as shown below:

We need to import three libraries as shown below:

The first library (System.Data) allows us to work with stored procedures in ADO.NET, the second (System.Configuration) allows us to reference a connection key from configuration file and the last (System.Data.SqlClient) one allows us to connect to SQL Server.

How To Create ASP.NET Core Web API in Visual Studio 2015

How To Create ASP.NET Core Web API in Visual Studio 2015

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core 1.0 hosting. This tutorial lets us create very basic ASP.NET Core Web API using Visual Studio 2015. We will be creating Contacts API which lets do popular CRUD operations.

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices.

ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. Update 12/10 – Updated to ASP.NET Core 1.0 with EF Core

Step 1 : Contacts API Overview

The Contacts API is very simple, basic Web API which does CRUD operations. I have focused on writing web API rather than integrating it with databases.  This table summaries Contacts API which we’ll create

tble

Step 2: Create ASP.NET Core Web API project

Install ASP.NET Core 1.0

Open Visual Studio 2015 Update 3, create “New Project” with name “ContactsApi

From ASP.NET Core templates select “Web API” as shown in image (I haven’t selected any Authentication, we will add them later)

apiFirst

Program.cs is newly added file, it’s entry point when application run, that’s right public static void main(). ASP.NET Core apps are considered as console apps.

Step 3: Packages included for ASP.NET Core Web API

The packages included are “MVC”, “EnvironmentalVariables”, “JSON”, “Logging”. (This is generated by default, do not copy this)

Step 4: Creating Contacts model

Contacts class is centre of this Web API project. Its POCO class containing some properties which are self explanatory.

Right click “ContactsApi” solution, create folder “Models“; under this “Models” folder create C# class “Contacts.cs” and copy this code

Step 5: Create and Register repository class for Contacts

The use of repository classes is really optional, but I have added it so that we can connect to any databases later.

Create “Repository” folder under “ContactsApi” solution, we will add one C# interface file and C# class file implementing this interface.

Create “IContactsRepository.cs” interface file in “Repository” folder and copy below code

Create “ContactsRepository.cs” class file, implement “IContactsRepository” and copy below code

ASP.NET MVC 6 provides out of box support for Dependency Injection, we will include that in our “ConfigureServices” method of Startup.cs.  We will see entire code in Step 7

Step 6: Add Contacts API Controller

Its time to add the controller API which acts as Web API. Create “Controllers” folder under “ContactsApi” project solution and add C# class file “ContactsController.cs“; copy below code

Some quick notes of this ContactsController

  1. [Route(“api/[controller]”)] – this used attribute based routing to access the ASP.NET Core Web API.
  2. ContactsRepo is instantiated using dependency injection which we configure in services.cs.
  3. GetAll() is simple HttpGet method which gets all contacts
  4. GetById fetches contact based on mobile phone. Its given HttpGet with Name attribute so that we can use that in Create method to be used for location header.
  5. Create method after inserting contact, returns 201 response and provides location header.

Note: HTTP Status codes are now written as BadReqest(), NotFound()Unauthorized() etc

Step 7: Enable CamelCasePropertyNamesContractResolver

Any Web Api (REST based) should return JSON response in form of Camel Case so that we can sure consume the API in any client. We need to enable CamelCasePropertyNamesContractResolver in Configure Services.

Here is the Startup.cs file which has all code needed for running this Contacts ASP.NET Core Web API.

How to Set Up Angular 2 and TypeScript in a ASP.NET Core Project Using Visual Studio

How to Set Up Angular 2 and TypeScript in a ASP.NET Core Project Using Visual Studio

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core hosting. There are two ways to set up an Angular 2 application. The most preferred way is to use angular-cli, which is pretty simple. Unfortunately, the Angular CLI doesn’t use the latest version. The other way is to follow the tutorial on angular.io, which sets up a basic starting point, but this needs a lot of manual steps.

maxresdefault

There are also two ways to set up the way you want to develop your app with ASP.NET Core. One way is to separate the client app completely from the server part. It is pretty useful to decouple the server and the client to create almost independent applications and to host on different machines. The other way is to host the client app inside the server app. This is useful for small applications, having everything in one place, and it is easy to deploy on a single server.

In this post, I’m going to show you, how you can set up an Angular 2 app, which will be hosted inside an ASP.NET Core application using Visual Studio 2015. The Angular-CLI is not the right choice here because it already sets up a development environment for you and all that stuff is configured a little bit differently. The effort to move this to Visual Studio would be too much. I will almost follow the tutorial on http://angular.io/. But we need to change some small things to get that stuff working in Visual Studio 2015.

Configure the ASP.NET Core Project

Let’s start with a new ASP.NET Core project based on .NET Core. (The name doesn’t matter, so “WebApplication391” is fine). We need to choose a Web API project because the client side Angular 2 App will probably communicate with that API and we don’t need all the predefined MVC stuff.

A Web API project can’t serve static files like JavaScripts, CSS styles, images, or even HTML files. Therefore we need to add a reference to Microsoft.AspNetCore.StaticFiles in the project.json:

And in the startup.cs, we need to add the following line, just before the call of `UseMvc().

Another important thing we need to do in the startup.cs is to support the Routing of Angular 2. If the Browser calls a URL that doesn’t exist on the server, it could be an Angular route. Especially if the URL doesn’t contain a file extension.

This means we need to handle the 404 error, which will occur in such cases. We need to serve the index.html to the client if there was an 404 error on requests without extensions. To do this we just need a simple lambda based MiddleWare, just before we call UseStaticFiles():

Inside the properties folder, we’ll find a file called launchSettings.json. This file is used to configure the behavior of Visual Studio 2015, when we press F5 to run the application. Remove all strings “api/values” from this file, because Visual Studio will always call that specific Web API every time you press F5.

Now we prepared the ASP.NET Core application to start to follow the angular.io tutorial.

Let’s start with the NodeJS packages. Using Visual Studio we can create a new “npm Configuration file” called package.json. Just copy the stuff from the tutorial:

In this listing, I changed a few things:

  • I added “&& gulp restore” to the postinstall script.
  • I also added Gulp to the devDependency to typings.

After the file is saved, Visual Studio tries to load all the packages. This works, but VS shows a yellow exclamation point for errors. Until recently, I didn’t figure out what was going wrong here. To be sure all packages are propery installed, use the console, change directory to the current project, and type npm install

The post install will possibly fail because gulp is not yet configured. We need gulp to copy the dependencies to the right location inside the wwwroot folder, because static files will only be loaded from that location. This is not part of the tutorial on angular.io, but is needed to fit the client stuff into Visual Studio. Using Visual Studio we need to create a new “gulp Configuration file” with the name gulpfile.js:

The task restore copies all the needed files to the Folder ./wwwroot/libs

TypeScript needs some type definitions to get the types and API definitions of the libraries, which are not written in TypeScript or not available in TypeScript. To load this, we use another tool, called “typings.” This is already installed with NPM. This tool is a package manager for type definition files. We need to configure this tool with a typings.config

Now we have to configure TypeScript itself. We can also add a new item, using Visual Studio to create a TypeScript configuration file. I would suggest not to use the default content, but rather the contents from the angular.io tutorial.

The only things I did with this file were to add the “compileOnSave” flag and to exclude the “node_modules” folder from the TypeScript build, because we don’t need to build containing the TypeScript files and because we moved the needed JavaScript to ./wwwroot/libs.

If you use Git or any other source code repository, you should ignore the files generated out of our TypeScript files. In the case of Git, I simply add another .gitignore to the ./wwwroot/app folder.

We do this because the JavaScript files are only relevant to run the application and should be created automatically in the development environment or on a build server, before deploying the app.

The First App

That is all we need to prepare an ASP.NET Core project in Visual Studio 2015. Let’s start to create the Angular app. The first step is to create an index.html in the folder wwwroot:

As you can see, we load almost all JavaScript files from the libs folder. Except a systemjs.config.js. This file is needed to configure Angular2, to define which module is needed, where to find dependencies, and so on. Create a new JavaScript file, call it systemjs.config.js, and paste the following content into it:

This file also defines a main entry point which is a main.js. This file is the transpiled TypeScript file main.ts we need to create in the next step. The main.ts bootstraps our Angular 2 app:

We also need to create our first Angular2 component. Create a TypeScript file with the name app.component.ts inside the app folder:

Conclusion

I propose to use Visual Studio just for small single-page applications because it gets slower the more dynamic files need to be handled. ASP.NET Core is pretty cool to handle dynamically generated files, but Visual Studio still is not. VS tries to track and manage all the files inside the project, which slows down a lot. One solution is to disable source control in Visual Studio and use an external tool to manage the sources.

Another — even better — solution is not to use Visual Studio for front-end development. In a new project, I propose to separate front-end and back-end development and to use Visual Studio Code for the front-end development or even both. You need to learn a few things about NPM and Gulp, and you need to use a console in this case, but web development will be a lot faster and a lot more lightweight with this approach.