Monthly Archives: February 2017

First MVC 6 and EF 7 Application (with Empty Project Template)

Part 1

If you are one of that techie who is tracking the progress of ASP.NET 5, you probably know that RC 1 of ASP.NET 5 is available now. This article explains how a simple MVC 6 application could be developed from ground up by using an Empty Project Template. This article is based on the following software:

  • Visual Studio 2015

  • ASP.NET 5 RC 1

  • Entity Framework 7 RC 1

Before you start you need to ensure that you have installed them correctly before you proceed further.

Let’s start here!

Open VS 2015 and select File—–New—-Project menu option. In the New Project dialog choose ASP.NET Web Application, give some project name and click OK button.

In the project template dialog, select Empty under ASP.NET 5 Preview Templates section.

Next, open Project.json file in the VS editor. The Project.json file is a JSON file and contains the entire project configuration like project dependencies, target frameworks and much more. For this example, you have to add some NuGet packages required to develop and run the application. You can enhance project dependencies in two ways:

  • Right click on the References node and choose Manage NuGet Packages. This is very similar to MVC 5.x projects. Once added the NuGet package entries are automatically added to the Project.json file.

  • Add NuGet package dependencies in the Project.json file.

Let’s make use of the later approach.

We won’t go into every minute details of each and every package in this article. It is sufficient to mention that:

  • Microsoft.AspNet.Mvc is the core MVC 6 package

  • Microsoft.AspNet.Mvc.TagHelpers contains tag helpers (discussed later)

  • EntityFramework.MicrosoftSqlServer provides Entity Framework 7 support

Then, right click on the project and choose Add > New Item to open the Add New Item dialog.

Select ASP.NET Configuration File from the list, name it AppSettings.json and click on Add to add the file to project root folder.

The AppSettings.json file has the entire application specific configuration. There is a difference between Project.json and AppSettings.json. The former stores project configuration that is necessary to compile and run the project. The later stores application configuration utilized in the code.

Next you have to add four folders under the project root namely Models, Views, Controllers and Classes. The purpose of the first three is quite obvious. The Classes folder will store other classes required in the application such as a DbContext class. You can give any other name to this folder.

Then add a class called AppSettings in the Classes folder and write the following code:

public class AppSettings

{

public static string ConnectionString { get; set; }

}

The AppSettings class has a single static property – ConnectionString – that intends to hold the database

connection string. This property is taken from the Startup class as discussed recently. Once assigned you can reach out the database connection string from anywhere in the application.

Now open Startup.cs file. The code from the Startup class is implored whenever the application runs. You will find that the Startup class has two methods – ConfigureServices() and Configure(). Both of them have special meaning to the framework and hence their name must remain unchanged.

Edit the Startup file to include a few namespaces and a public constructor.

using Microsoft.AspNet.Hosting;

using Microsoft.Dnx.Runtime;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.PlatformAbstractions;

using Microsoft.Data.Entity;

using MVC6Demo.Classes;

namespace WebApplication1

{

public class Startup

{

public Startup(IHostingEnvironment env,

IApplicationEnvironment app)

{

}

public void ConfigureServices(IServiceCollection services)

{

}

public void Configure(IApplicationBuilder app)

{

}

}

}

Take note of the namespaces at the top. They are needed by the code that you will fill in these methods sooner. Also take note that the constructor accepts two parameters: IHostingEnvironment and IApplicationEnvironment. These 3 methods are executed by the framework in the same order – Startup(), ConfigureServices() and Configure().

Next, add the following code to the Startup() constructor.

public Startup(IHostingEnvironment env,

IApplicationEnvironment app)

{

ConfigurationBuilder builder = new ConfigurationBuilder();

builder.SetBasePath(app.ApplicationBasePath);

builder.AddJsonFile(“appsettings.json”);

IConfigurationRoot config = builder.Build();

AppSettings.ConnectionString = config.Get<string>

(“Data:DefaultConnection:ConnectionString”);

}

The Startup constructor mainly reads the AppSettings.json file and stores the database connection string into the AppSettings class. The ConfigurationBuilder class is responsible for reading and loading the configuration information. The SetBasePath() method sets the base path where the configuration file(s) is located. The ApplicationBasePath means the physical path of the project’s root folder.

The AddJsonFile() adds AppSettings.json file to the list of configuration files to be processed. You can have multiple configuration files per project. The Build() method reads the configuration and returns it as an instance of IConfigurationRoot.

To read it, you can use Get<T>() method on the IConfigurationRoot object. Now the database connection string could be accessed from anywhere in the application in typed manner.

Then modify the ConfigureServices() method as shown below:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFramework().AddSqlServer();

}

The ConfigureServices() method specifies the features that are available to your application. In this case your application is made available the services of the MVC framework and the Entity Framework.

Now modify the Configure() method as shown below:

public void Configure(IApplicationBuilder app)

{

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}/{action=Index}/{id?}”);

});

}

The Configure() method tells the framework that you want to use static files feature and MVC features. The static files feature allows you to access static files such as .htm and .html. If you don’t specify this feature and attempt to access the static files you will get an error. Of course, if you don’t need this feature you can skip this line.

The UseMvc() call is important because it not only tells the framework that your application is using MVC but also configures the routing system.

Ok. Now add HomeController to the Controllers folder using the Add New Item dialog. The default HomeController looks like this:

public class HomeController : Controller

{

public IActionResult Index()

{

ViewBag.Message = “Hello from MVC 6!”;

return View();

}

}

Notice that the Index() action returns IActionResult. The Index() action is quite straightforward and simply sets Message property on the ViewBag.

Then add Home subfolder under Views folder. Right click on the Home folder and open the Add New Item dialog again to add Index view to the project.

Add the following HTML markup to the Index view.

<html>

<head>

<title>My First MVC 6 Application</title>

</head>

<body>

<h1>@ViewBag.Message</h1>

</body>

</html>

The Index view simply outputs the Message ViewBag property on the response stream.

Run the application by pressing F5.

We conclude for now. Keep coding!!

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Preparation Of ASP.NET MVC / ASP.NET Core Projects To Utilise Angular 2

With the availability of Angular 2; let’s try hands hands on this new framework. Angular 2 documentation already have many great articles available online; that could guide you to the whole process. In this article we shall discuss how you can prepare your ASP.NET MVC and ASP.NET Core projects to use Angular 2.

Let’s start.

Step 1 :Install NPM

Those who already has NPM installed; this is an optional step. Many programmers prefer to work with NPM from the command prompt instead of using Visual Studio features.

Step 2 : Develop ASP.NET MVC / ASP.NET Core Project

Start by designing a new ASP.NET MVC project using Empty project template. Name it AngularAspNetMvc.

In the same solution you must add ASP.NET Core project using Empty project template. You could also prefer Web Application project template instead of empty project for MVC. Name it as AngularAspNetCore.

Then configure the ASP.NET Core project to use MVC.

Step 3 : Download Angular 2 framework and its dependencies

Before you start coding you should download and install the Angular 2 framework files in your project. This step involves more effort. Actually you need to download Angular 2 and its dependency packages using NPM.

There are two methods to do this task – using NPM command line options and using VS. Here Visual Studio 2015 is used to download the necessary packages.

Select NPM Configuration file item. Name the item as Packages.json (default) and click Ok.

The Packages.json file has all the packages and dependencies needed. Add the following markup into the Packages.json file.

{

“name”: “angular-aspnet”,

“version”: “1.0.0”,

“scripts”: {

“start”: “tsc && concurrently \”npm run tsc:w\”

\”npm run lite\” “,

“lite”: “lite-server”,

“postinstall”: “typings install”,

“tsc”: “tsc”,

“tsc:w”: “tsc -w”,

“typings”: “typings”

},

“license”: “ISC”,

“dependencies”: {

“@angular/common”: “2.0.0”,

“@angular/compiler”: “2.0.0”,

“@angular/core”: “2.0.0”,

“@angular/forms”: “2.0.0”,

“@angular/http”: “2.0.0”,

“@angular/platform-browser”: “2.0.0”,

“@angular/platform-browser-dynamic”: “2.0.0”,

“@angular/router”: “3.0.0”,

“@angular/upgrade”: “2.0.0”,

“core-js”: “^2.4.1″,

“reflect-metadata”: “^0.1.3″,

“rxjs”: “5.0.0-beta.12″,

“systemjs”: “0.19.27”,

“zone.js”: “^0.6.23″,

“angular2-in-memory-web-api”: “0.0.20”,

“bootstrap”: “^3.3.6″

},

“devDependencies”: {

“concurrently”: “^2.2.0″,

“lite-server”: “^2.2.2″,

“typescript”: “^2.0.2″,

“typings”:”^1.3.2″

}

}

Now add a JSON file to the root of the project using the Add New Item dialog. Name it as Typings.json.

Add the following markup into the Typings.json file.

{

“globalDependencies”: {

“core-js”: “registry:dt/core-js#0.0.0+20160725163759″,

“jasmine”: “registry:dt/jasmine#2.2.0+20160621224255″,

“node”: “registry:dt/node#6.0.0+20160909174046″

}

}

Then right click on the Packages.json file and select Restore Packages from the shortcut menu.

All the necessary packages will get downloaded.

Repeat the same method for AngularAspNetCore project.

To mention AngularAspNetCore project also updates the Dependencies node to reflect the NPM packages.

Step 4 : Add TypeScript configuration file

Before you proceed you need to configure the TypeScript compiler. You can do this by adding tsconfig.json file in the project. You can open the Add New Item dialog and search for TypeScript.

After adding the tsconfig.json file add the below mentioned markup into it:

{

“compilerOptions”: {

“target”: “es5″,

“module”: “commonjs”,

“moduleResolution”: “node”,

“sourceMap”: true,

“emitDecoratorMetadata”: true,

“experimentalDecorators”: true,

“removeComments”: false,

“noImplicitAny”: true,

“suppressImplicitAnyIndexErrors”: true

},

“compileOnSave”: true,

“exclude”: [“node_modules”,”scripts”]

}

The above markup is for AngularAspNetMvc project. The tsconfig.json for AngularAspNetCore looks identical with one difference. The exclude options specify wwwroot folder and not the scripts folder as given below:

{

“compilerOptions”: {

“target”: “es5″,

“module”: “commonjs”,

“moduleResolution”: “node”,

“sourceMap”: true,

“emitDecoratorMetadata”: true,

“experimentalDecorators”: true,

“removeComments”: false,

“noImplicitAny”: true,

“suppressImplicitAnyIndexErrors”: true

},

“compileOnSave”: true,

exclude”: [“node_modules”,”wwwroot”]

}

Step 5 : Design your Angular 2 client side application using TypeScript

Now add a new folder under the project’s root folder. Name it as AngularApp. Then add 3 TypeScript files to this folder : main.ts, app.component.ts and app.module.ts.

Click on No button and add remaining files.

Now, open app.component.ts file and add the following TypeScript code to it.

import { Component } from ‘@angular/core';

@Component({

selector: ‘my-app’,

template: ‘<h1>Angular 2 meets ASP.NET!</h1>’

})

export class AppComponent { }

Similarly, open the app.module.ts file and add the following code:

import { NgModule } from ‘@angular/core';

import { BrowserModule } from ‘@angular/platform-browser';

import { AppComponent } from ‘./app.component';

@NgModule({

imports: [BrowserModule],

declarations: [AppComponent],

bootstrap: [AppComponent]

})

export class AppModule { }

Finally, open the main.ts file and write the following code:

import { platformBrowserDynamic } from

‘@angular/platform-browser-dynamic';

import { AppModule } from ‘./app.module';

const platform = platformBrowserDynamic();

platform.bootstrapModule(AppModule);

After this step your AngularApp folder should look like this:

Ensure to repeat the same process for AngularAspNetCore project.

Step 6 : Configure Angular 2 module loading

This is done using SystemJS. First add a JavaScript file named systemjs.config.js in the project’s root folder.

Write the following code inside the systemjs.config.js file.

(function (global) {

System.config({

paths: {

‘npm:': ‘/scripts/angularframework/’

},

map: {

app: ‘/scripts/angularapp’,

‘@angular/core': ‘npm:@angular/core/bundles

/core.umd.js’,

‘@angular/common': ‘npm:@angular/common/bundles/

common.umd.js’,

‘@angular/compiler': ‘npm:@angular/compiler/bundles/

compiler.umd.js’,

‘@angular/platform-browser': ‘npm:@angular/

platform-browser/bundles/platform-browser.umd.js’,

‘@angular/platform-browser-dynamic': ‘npm:@angular/

platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js’,

‘@angular/http': ‘npm:@angular/http/bundles/

http.umd.js’,

‘@angular/router': ‘npm:@angular/router/bundles/

router.umd.js’,

‘@angular/forms': ‘npm:@angular/forms/bundles/

forms.umd.js’,

‘rxjs': ‘npm:rxjs’,

‘angular2-in-memory-web-api':

‘npm:angular2-in-memory-web-api’,

},

packages: {

app: {

main: ‘./main.js’,

defaultExtension: ‘js’

},

rxjs: {

defaultExtension: ‘js’

},

‘angular2-in-memory-web-api': {

main: ‘./index.js’,

defaultExtension: ‘js’

}

}

});

})(this);

Notice the code marked in bold letters. The first bold line sets the path where Angular 2 framework files are located. On the same lines the second bold line sets the path where your Angular 2 application files will be located. In our example we will store these files under Scripts folder (more on that later).

Ensure to do this step for both the projects.

Step 7 : Add HomeController and Index view

Next add HomeController and Index view in the project. Open the Index.cshtml file and write the following codes into it.

<html>

<head>

<title>Angular 2 meets ASP.NET</title>

<script src=”/scripts/angularframework/core-js/client/shim.min.js”>

</script>

<script src=”/scripts/angularframework/zone.js/dist/zone.js”>

</script>

<script src=”/scripts/angularframework/reflect-metadata/Reflect.js”>

</script>

<script src=”/scripts/angularframework/systemjs/dist/system.src.js”>

</script>

<script src=”/scripts/systemjs.config.js”></script>

<script>

System.import(‘app’).catch(function(err){ console.error(err); });

</script>

</head>

<body>

<my-app>Loading…</my-app>

</body>

</html>

</html>

The codes marked in bold letters are <script> references required by the application.

The <body> has one element <my-app>. This element is handled by Angular 2 component from app.component.ts file.

Step 8 : Develop the project

Build both the projects AngularAspNetMvc and AngularAspNetCore. This will help you compile the C# code but also the TypeScript code. If the compilation is successful you will find that the TypeScript code has been converted to JavaScript code under the AngularApp folder.

Step 9 : Moving all JavaScript files to Scripts folder

It’s time to deploy the JavaScript files. There are two types of JavaScript files you need to take into account:

  • Angular 2 framework files and dependencies
  • Your application’s JavaScript files (see previous step).

You copy all the files under your “Scripts” folder. For an ASP.NET MVC application there is no specific name or location for the scripts folder. For ASP.NET Core applications all scripts must be placed under wwwroot folder. So, do the following:

  • For AngularAspNetMvc project create Scripts folder under the project root.
  • For AngularAspNetCore project create Scripts folder under the wwwroot folder.

There are two ways to copy the files from node_modules and AngularApp folders to the Scripts folder – manual and automated.

For AngularAspNetMvc project do the following from Windows Explorer and not from VS:

  • Copy node_modules folder from project root to the Scripts folder.
  • Rename the newly copied folder to AngularFramework.
  • Copy AngularApp folder from project root to the Scripts folder.
  • Copy Systemjs.config.js file from project root to the Scripts folder.

For AngularAspNetCore project do the following from Windows Explorer and not from VS:

  • Copy node_modules folder from project root to the /wwwroot/Scripts folder.
  • Rename the newly copied folder to AngularFramework.
  • Copy AngularApp folder from project root to the /wwwroot/Scripts folder.
  • Copy Systemjs.config.js file from project root to the /wwwroot/Scripts folder.

Step 10 : Run the application

Now time to press F5.

Make sure to run both the applications and confirm if they behave as expected.

After this you need to add more codes, configuration and functionality as required by your application.

We conclude now….. Enjoy coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information.

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Use Session in ASP.NET Core 1.0

ASP.NET programmers use Session object to store session wide data. To store and retrieve values in Session object is quite straightforward in ASP.NET web forms and ASP.NET MVC. But, ASP.NET Core deals with the session data in a various ways. This article will introduce you to the basics of session data management in ASP.NET Core.

To demonstrate how data could be stored and retrieved in the Session object under ASP.NET Core, develop a new ASP.NET web application. The first step is to reference the needed NuGet package as shown below (Project.json).

“dependencies”: {

“Microsoft.AspNet.Mvc”: “6.0.0-rc1-final”,

“Microsoft.AspNet.Mvc.TagHelpers”: “6.0.0-rc1-final”,

“Microsoft.AspNet.StaticFiles”: “1.0.0-rc1-final”,

“Microsoft.AspNet.Tooling.Razor”: “1.0.0-rc1-final”,

“Microsoft.Extensions.Configuration.Abstractions”:

“1.0.0-rc1-final”,

“Microsoft.Extensions.Configuration.Json”:

“1.0.0-rc1-final”,

“Microsoft.AspNet.Session”: “1.0.0-rc1-final”,

“Newtonsoft.Json”: “8.0.3”

}

As visible, the above configuration makes use of Microsoft.AspNet.Session assembly. Also you will need a reference to Newtonsoft.Json component. The Json.Net component is needed to serialize and de-serialize objects to and from strings.

Then open the Startup.cs file and change the ConfigureServices() and Configure() methods as shown below:

public void ConfigureServices(IServiceCollection services)

{

services.AddMvc();

services.AddCaching();

services.AddSession();

}

public void Configure(IApplicationBuilder app)

{

app.UseIISPlatformHandler();

app.UseSession();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}/

{action=Index}/{id?}”);

});

}

The ConfigureServices() method adds the in-memory caching service and session service by using AddCaching() and AddSession() methods. The Configure() method next indicates that the application uses the session service making use of UseSession() method.

Next add HomeController to the Controllers folder and add the following actions to it:

public IActionResult Index()

{

HttpContext.Session.SetString(“message”,

“Hello World!”);

HttpContext.Session.SetInt32(“count”, 4);

return View();

}

public IActionResult Index2()

{

ViewBag.Message = HttpContext.Session.

GetString(“message”);

ViewBag.Count = HttpContext.Session.

GetInt32(“count”);

return View();

}

The Index() action gets the availability to the Session object through the HttpContext object. The SetString() and SetInt32() extension methods are then used to store a string value and an integer value into the session. Both these methods include two parameters, viz. key name and the value.

The Index2() action makes use of the GetString() and GetInt32() methods are used to recover the prior stored session values. The retrieved values are stored in the ViewBag.

Next, add two views – Index.cshtml and Index2.cshtml – and write the below mark-up in them.

Index.cshtml

<h2>@Html.ActionLink(“Go to Index2″, “Index2″)</h2>

Index2.cshtml

<h2>@ViewBag.Message</h2>

<h2>@ViewBag.Count</h2>

Sometime you need to store complex types – objects – into the session. You can’t do this directly because ASP.NET Core is developed to support distributed sessions. So, you can’t store object references in the session. But you can have your own way to store and retrieve entire objects.

What you can do is that you can convert an object to its JSON equivalent and next store this JSON string data into the session. While obtaining the object stored in the session you have to convert the JSON string back into an object. You can accomplish this object to JSON conversion using the Json.Net component.

Let’s consider you have Employee class as shown below:

public class Employee

{

public int EmployeeID { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

}

And you want to store an Employee object into the session.

To do the object to JSON and JSON to object transformation, you need to write a set of extension methods. Take a look at the following code:

public static class SessionExtensionMethods

{

public static void SetObject(this ISession session,

string key, object value)

{

string stringValue = JsonConvert.

SerializeObject(value);

session.SetString(key, stringValue);

}

public static T GetObject<T>(this ISession session,

string key)

{

string stringValue = session.GetString(key);

T value = JsonConvert.DeserializeObject<T>

(stringValue);

return value;

}

}

The static class SessionExtensionMethods comprise of two extension methods viz. SetObject() and GetObject().

The SetObject() extension method extends ISession. It takes a key name and an object which has to be stored in the session. Inside, SerializeObject() method of JsonConvert is used to change the supplied object into a JSON string. The JSON string obtained thus, is then stored in the session using the SetString() method.

The GetObject() generic extension method accepts a key name. Inside, which reads the JSON string for the specified key and resolves it to get an object. This is performed using the DeserializeObject() method of JsonConvert. The object is next sent back to the caller.

Once the SetObject() and GetObject() extension methods are reader, you can use them as follows:

public IActionResult Index()

{

….

Employee emp = new Employee()

{

EmployeeID = 1,

FirstName = “Nancy”,

LastName = “Davolio” };

HttpContext.Session.SetObject(“emp”, emp);

return View();

}

public IActionResult Index2()

{

ViewBag.Employee = HttpContext.Session.

GetObject<Employee>(“emp”);

return View();

}

Now the Index() action creates an Employee object and stores it in the session using SetObject() extension method. The Index2() action brings back the Employee object using the GetObject() extension method.

In the examples till now you could access the session inside a controller class. At times you might need to access the session inside some class which is not a controller. In these cases you can’t get the HttpContext object inside that class. But, you can use dependency injection to inject IHttpContextAccessor into such a class. The IHttpContextAccessor object next permits you to access the HttpContext.

Let’s quickly see how this is done. Look at the following class:

public class MyHelperClass

{

private IHttpContextAccessor httpContextAccessor;

public MyHelperClass(IHttpContextAccessor obj)

{

this.httpContextAccessor = obj;

}

public string Message

{

get

{

return httpContextAccessor.HttpContext.

Session.GetString(“message”);

}

}

public int Count

{

get

{

return httpContextAccessor.HttpContext.

Session.GetInt32(“count”).Value;

}

}

}

The MyHelperClass class needs to access the session. The code announces a private variable of type IHttpContextAccessor (Microsoft.AspNet.Http namespace). This variable is assigned a value in the constructor. The constructor receives an IHttpContextAccessor object from the DI framework. The Message and Count read-only properties then return the message and count values from the Session.

To mention, you need to register MyHelperClass with the DI framework. You can do so in the ConfigureServices() method in Startup.cs.

public void ConfigureServices(IServiceCollection services)

{

….

services.AddScoped<SessionDemo.Models.MyModel>();

}

To test the functioning of MyHelperClass, change the HomeController as written below:

public class HomeController : Controller

{

private MyHelperClass helper;

public HomeController(MyHelperClass obj)

{

this.helper = obj;

}

….

}

The above code injects MyHelperClass object into the HomeController. You can then use this object to read the message and count keys.

ViewBag.Message = helper.Message;

ViewBag.Count = helper.Count;

We conclude for now. Keep coding!!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Read and Write Cookies in ASP.NET Core 1.0

One of the basic requirements in several web applications is storing and retrieving small pieces of information in cookies. This article will discuss with an instance how ASP.NET Core 1.0 deals with cookies. You will learn here to read and write cookies using ASP.NET Core. You will also know how to configure the cookie properties such as expiration time.

You need to specify some preferences like font name, colour and font size. You can choose a preference from the dropdown list and mention its value in the textbox. Click on the Write Cookie button saves that choice in a cookie. The Is Persistent checkbox controls if the cookies are to be stored on the local disk such that they are read during a different browser session. The read cookies link takes you to another page where the choices are read and applied to a some HTML markup.

Begin by developing a new ASP.NET Core Web Application using VS 2015. Next open the HomeController and add 3 actions to it – Index(), WriteCookies() and ReadCookies().

The Index() action is quite straight and simply returns the Index view to the browser.

public IActionResult Index()

{

return View();

}

The WriteCookies() action writes the cookies and is shown below:

public IActionResult WriteCookies(string setting,

string settingValue,bool isPersistent)

{

if (isPersistent)

{

CookieOptions options = new CookieOptions();

options.Expires = DateTime.Now.AddDays(1);

Response.Cookies.Append(setting, settingValue,options);

}

else

{

Response.Cookies.Append(setting, settingValue);

}

ViewBag.Message = “Cookie written successfully!”;

return View(“Index”);

}

The WriteCookies() method receives 3 parameters viz. setting, settingValue and isPersistent through model binding. The set parameter will be the value selected from the dropdown list. The setting Value parameter will be the value entered in the textbox and isPersistent will point whether isPersistent checkbox is seen or not.

Inside, the code checks the value of isPersistent boolean parameter. If it is correct an object of CookieOptions class (Microsoft.AspNetCore.Http namespace) is created. The CookieOptions class helps you to specify the properties of the cookie as mentioned below:

  • Domain (associated with cookie)
  • Expires (when cookie must expire)
  • Path (specifies path where cookie is applicable)
  • Secure (cookie is sent on https channel only)
  • HttpOnly (client side script can’t reach the cookie)

When you set the Expires property of the cookie to one day from now; the cookie will persist on the client machine for a day. Then a cookie is written to the response using the Append() method of the Cookies collection. The Append() method accepts key, value and CookieOptions object.

The else block of the code simply adds a cookie by setting its key and value.

A ViewBag message points to the user that the choice is stored successfully.

Then append Index view and write the following into it:

<h1>Specify your preferences :</h1>

<form asp-action=”WriteCookies” asp-controller=”Home”>

<select name=”setting”>

<option value=”fontName”>Font Name</option>

<option value=”fontSize”>Font Size</option>

<option value=”color”>Color</option>

</select>

<input type=”text” name=”settingValue” />

<input type=”checkbox” name=”isPersistent”

value=”true” /> Is Persistent?

<input type=”submit” value=”Write Cookie” />

</form>

<h4>@ViewBag.Message</h4>

<h4>

<a asp-action=”ReadCookies” asp-controller=”Home”>

Read Cookies

</a>

</h4>

The Index view renders a <form> shown previous using ASP.NET Core tag helpers and inputs. It also outputs the Message property from ViewBag. A Read Cookies link will take the user to a test page where choices are applied.

Now, append ReadCookies() action to the HomeController and write the below code to it :

public IActionResult ReadCookies()

{

ViewBag.FontName = Request.Cookies[“fontName”];

ViewBag.FontSize = Request.Cookies[“fontSize”];

ViewBag.Color = Request.Cookies[“color”];

if(string.IsNullOrEmpty(ViewBag.FontName))

{

ViewBag.FontName = “Arial”;

}

if (string.IsNullOrEmpty(ViewBag.FontSize))

{

ViewBag.FontSize = “22px”;

}

if (string.IsNullOrEmpty(ViewBag.Color))

{

ViewBag.Color = “Blue”;

}

return View();

}

The ReadCookies() action reads 3cookies with the help of their keys. This is achieved using Cookies collection of the Request object. The cookie values are stored in ViewBag properties. A series of if statements check whether a particular preference is empty and if so assign a default value to it.

The ReadCookies view where these preferences are used is shown below:

<div style=”font-family:’@ViewBag.FontName';

font-size:@ViewBag.FontSize;color:

@ViewBag.Color”>

Hello World!

</div>

The ReadCookies view consists of a <div> element whose style feature makes use of font name, font size and colour specified in the respective ViewBag properties.

This concludes the application. Run it and specify values to the three choices. Don’t check the Is Persistent checkbox during saving the values. Then click on the Read Cookies link.

We conclude now….. Enjoy coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr

Create Custom Tag Helpers in ASP.NET Core

As an ASP.NET programmer we are already familiar with server controls and HTML helpers. What does they do? In simple words they execute some server side logic and generate HTML markup. The HTML markup hence generated is then rendered in the browser. In ASP.NET core you can continue using HTML helpers as in ASP.NET MVC. But, there is a better alternative i.e. the Tag Helpers.

ASP.NET Core tag helpers consist of markup they you place in your views. This markup is special in that it is processed on the server side and renders certain HTML markup. In order to get an idea consider the following Form tag helper:

<form asp-action=”ProcessForm” asp-controller=”Home” method=”post”>

….

….

</form>

The above mark-up indicates that you are using a form tag helper. Notice that the form tag helper has two attributes of the form asp. These attributes mention the action name and the controller name respectively. There is also a method attribute. The asp-action and asp-controller attributes are processed on the server while the method attribute is the standard HTML attribute. The above server side markup gets transformed to this :

<form action=”/home/ProcessForm” method=”post>

….

….

</form>

Tag helpers are better than HTML helpers because they are mark-up friendly. They appear more natural to go along standard HTML markup. What’s more that you can easily build your own custom tag helpers. The article will illustrate how.

The Latestblogposts tag helper – markup

A custom tag helper has two parts: a piece of mark-up that you put in a razor view and a class that houses the processing logic of the tag helper under consideration. Let’s understand with an example. Suppose you are building a blog engine and wish to display a list of latest blog posts belonging to a particular category. You also want to control the number of items being displayed. Considering these requirements let’s say we wish to have this kind of custom tag helper markup in our view:

<latestblogposts Category=”AspNetCore” Count=”10″>

</latestblogposts>

Here, the latestblogpost tag helper puts itself as an independent mark-up element. It has two attributes namely Category and Count. The Category attribute indicates the blog post category or tag to be used (AspNetCore in this case) to pick the latest posts. The Count attribute mentions that 10 items are to be displayed in the latest posts list.

The Latestblogpost tag helper – class

This is the first part of our custom tag helper. Now the remaining part a class named LatestblogpostsTagHelper must be created. This class is shown below:

public class LatestblogpostsTagHelper:TagHelper

{

public string Category { get; set; }

public int Count { get; set; }

public override void Process(TagHelperContext context,

TagHelperOutput output)

{

output.TagName = “div”;

output.Attributes.Add(“class”, “latestBlogPosts”);

using (BlogDbContext db = new BlogDbContext())

{

var query = (from p in db.BlogPosts

where p.Category == Category

orderby p.PublishDate descending

select p

).Take(Count);

StringBuilder sb = new StringBuilder();

foreach(var item in query)

{

sb.AppendFormat(“<h2><a href=’/home/

displaypost/{0}’>{1}</a></h2>”,item.BlogPostID,

item.Title);

}

output.Content.SetHtmlContent(sb.ToString());

}

}

}

Take note of the above code carefully. The LatestblogpostsTagHelper class comes from TagHelper class (Microsoft.AspNetCore.Razor.TagHelpers namespace). The LatestblogpostsTagHelper class has two properties – Category and Count – and an overridden Process() method.

The Category and Count properties belong to the respective attributes used in the tag helper markup. In the Process() method the processing logic of the custom tag helper stays. The Process() method receives TagHelperOutput parameter that is used to render the desired output. The TagName property indicates the HTML tag name of the resultant mark-up (div in this case). The feature collection is made use to set the class feature of the <div> to latestBlogPosts. Then an Entity Framework Core code connects with the data-base and brings records from the BlogPosts table. The BlogDbContext and BlogPost are discussed later.

Notice how the LINQ to Entities query use the Category and Count properties while getting the records. A for each loop then iterates through the latest blog posts and generates a list of hyperlinks for each post. This is done with the help of a StringBuilder. Lastly, SetHtmlContent() method is used to render the HTML fragment.

DbContext and entity class

This completes the Latestblogposts tag helper. Before running the application you must need to add the DbContext and the BlogPost entity class. They are shown below:

[Table(“BlogPosts”)]

public class BlogPost

{

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public int BlogPostID { get; set; }

[Required]

[StringLength(200)]

public string Title { get; set; }

[Required]

public string Content { get; set; }

[Required]

[StringLength(50)]

public string Category { get; set; }

[Required]

public DateTime PublishDate { get; set; }

}

public class BlogDbContext:DbContext

{

public DbSet<BlogPost> BlogPosts { get; set; }

protected override void OnConfiguring

(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(@”data source=.;

initial catalog =BlogDb;

Integrated Security=True;

MultipleActiveResultSets = true”);

}

}

To design a database based on the above DbContext you can use the following commands:

> dotnet ef migrations add MyMigrations

> dotnet ef database update

Of course, you can also designthe database manually and not use these commands.

Using the custom tag helper

In order to use the latestblogposts tag helper successfully on a razor view, it must be made available to the view. You do this using the @addtagHelper directive. You can place this directive either inside the view file itself or better yet inside _ViewImports.cshtml file.

@addTagHelper *,MyWebApplication

The @addTagHelper directive specifies that all the tag helpers (*) from the MyWebApplication assembly (the current web application’s project) are to be made available to the view. You will also get IntelliSense for the custom tag helpers:

After creating the database and adding a few dummy records run the application. The following figure shows a sample run of the application.

If you see the HTML source of the page, you will see this HTML fragment:

<div class=”latestBlogPosts”>

<h2>

<a href=’/home/displaypost/4′>Blog Post Title 2</a>

</h2>

<h2>

<a href=’/home/displaypost/1′>Blog Post Title 1</a>

</h2>

</div>

Tag helpers and Pascal casing

In the above example the tag helper element was <latestblogposts>. What if you wish to use the following tag name?

<Latest-Blog-Posts Category=”AspNetCore” Count=”10″>

</Latest-Blog-Posts>

Here the tag name includes hyphened character. You can’t use hyphen in C# class names. The remedy is to do Pascal casing for the tag helper class name. So, the class name needs to be :

public class LatestBlogPostsTagHelper : TagHelper

{

….

}

The same rule applies for attribute names also. Thus article-category feature would be drawn with ArticleCategory attribute and article-count attribute will communicate to ArticleCount attribute.

Specifying element and attribute mapping manually

In the above example the markup element <latestblogposts> was compared to LatestblogpostsTagHelper class automatically. On the same lines Category and Count attributes were mapped to Category and Count properties automatically. Though this might work well in many situations, at times you might want to specify this mapping. You can do so as mentioned below:

[HtmlTargetElement(“latestblogposts”)]

public class LatestblogpostsTagHelper:TagHelper

{

[HtmlAttributeName(“Category”)]

public string Category { get; set; }

[HtmlAttributeName(“Count”)]

public int Count { get; set; }

….

….

}

As you can see the LatestblogpostsTagHelper class is designed with [HtmlTargetElement] attribute that maps it to the latestblogposts element. Similarly, Category and Count properties are decorated with [HtmlAttributeName] attribute. The [HtmlAttributeName] attribute maps the properties to Category and Count attributes respectively.

Creating tag helpers for standard HTML elements

In the above example we designed a new markup element – <latestblogposts> – to represent a custom tag helper. What if you wish to use a standard HTML element instead of introducing your own? Say for example :

<div article-category=”AspNetCore” article-count=”10″>

</div>

In this case the custom tag helper takes a form of <div> element. The <div> element has two attributes article-category and article-count.

The class that manages the above tag helper is shown below:

[HtmlTargetElement(“div”,Attributes = “article-*”)]

public class LatestBlogPostsTagHelper : TagHelper

{

public string ArticleCategory { get; set; }

public int ArticleCount { get; set; }

public override void Process(

TagHelperContext context,

TagHelperOutput output)

{

output.Attributes.Add(“class”, “latestBlogPosts”);

using (BlogDbContext db = new BlogDbContext())

{

var query = (from p in db.BlogPosts

where p.Category == ArticleCategory

orderby p.PublishDate descending

select p

).Take(ArticleCount);

StringBuilder sb = new StringBuilder();

foreach (var item in query)

{

sb.AppendFormat(“<h2><a href=’/home/

displaypost/{0}’>{1}</a></h2>”,

item.BlogPostID, item.Title);

}

output.Content.SetHtmlContent(sb.ToString());

}

}

}

Notice that the LatestBlogPostsTagHelper class is now decorated with [HtmlTargetElement] attribute. The target element is set to div. Now, there might be several <div> elements on the page. We wish to tell our helper only for a <div> that has article-category and article-count attributes (you could have used any other attribute names). The second parameter sets the Attributes filter to article. This way only the <div> elements having features of the form article are processed by this helper.

We conclude now….. Enjoy coding!

Let us know your opinion in the comments sections below. And feel free to refer Microsoft’s site to gather more information.

If you want to improve your skill in ASP.Net and excel yourself in ASP.NET training program; our institute, CRB Tech Solutions would be of great help and for you. Come and join us with our well structured program for ASP .Net.

Stay connected to CRB Tech for more technical optimization and other updates and information

Don't be shellfish...Buffer this pageEmail this to someoneDigg thisShare on FacebookShare on Google+Share on LinkedInPrint this pageShare on RedditPin on PinterestShare on StumbleUponTweet about this on TwitterShare on Tumblr