Tag Archives: .net courses

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

ASP.NET Core Identity – Add Email Confirmation

In today’s age of digitalisation, you would wish to confirm that the email address entered by the user at the time of creating an account actually belongs to him. So, that verification becomes important. ASP.NET Core helps an easy way to do that.

The email verification step in ASP.NET Core Identity works in the following manner:

  • You produce an email verification token
  • Next you send an email to the user’s email address with a link that contains the user’s ID and above generated token.
  • The user clicks on the email verification link and if there is no issue it is marked verified.
  • When the user attempts a log-in to the system you next check if his email is verified or not and allow or deny the access.

ASP.NET Core Identity gives most of the functionality required to use the above steps, you need an external aide. You require a mechanism to send emails through your code. In .NET Framework , System.Net.Mail classes is used for the same. There is no direct equivalent in .NET Core. You must use some third-party NuGet packages. For the sake of our example I am going to stick with SmtpClient class from .NET Framework’s System.Net.Mail namespace.

Let’s begin!

First of all make changes in the Project.json to use .NET Framework rather than .NET Core. You can do it like this :

“frameworks”: {

“net452″: {

“frameworkAssemblies”: {

“System.Net”: “4.0.0.0”

}

}

}

Then open the AccountController and modify its Register() POST action as shown below:

[HttpPost]

[ValidateAntiForgeryToken]

public IActionResult Register(RegisterViewModel obj)

{

if (ModelState.IsValid)

{

MyIdentityUser user = new MyIdentityUser();

user.UserName = obj.UserName;

user.Email = obj.Email;

user.FullName = obj.FullName;

user.BirthDate = obj.BirthDate;

IdentityResult result = userManager.CreateAsync(user,

obj.Password).Result;

if (result.Succeeded)

{

if(!roleManager.RoleExistsAsync(“NormalUser”).Result)

{

MyIdentityRole role = new MyIdentityRole();

role.Name = “NormalUser”;

role.Description = “Perform normal operations.”;

IdentityResult roleResult =

roleManager.CreateAsync(role).Result;

if(!roleResult.Succeeded)

{

ModelState.AddModelError(“”,

“Error while creating role!”);

return View(obj);

}

}

userManager.AddToRoleAsync(user, “NormalUser”).Wait();

//send confirmation email

string confirmationToken = userManager.

GenerateEmailConfirmationTokenAsync(user).Result;

string confirmationLink = Url.Action(“ConfirmEmail”,

“Account”, new { userid = user.Id,

token = confirmationToken },

protocol: HttpContext.Request.Scheme);

SmtpClient client=new SmtpClient();

client.DeliveryMethod = SmtpDeliveryMethod.

SpecifiedPickupDirectory;

client.PickupDirectoryLocation = @”C:\Test”;

client.Send(“test@localhost”,user.Email,

“Confirm your email”,

confirmationLink);

return RedirectToAction(“Login”, “Account”);

}

}

return View(obj);

}

The code calls the GenerateEmailConfirmationTokenAsync() method of UserManager class by passing on the MyIdentityUser object. This call returns a confirmation token for that user. For verifying an email address you require a user’s Id and his confirmation token. A URL is formed using Url.Action() that points to the ConfirmEmail action of the Accountcontroller. The URL contains the user’s Id and the confirmation token in the query string.

Then the code develops a SmtpClient object and configures it such that outgoing emails are stored in the Test folder. This is done only for testing. In a real application you will need a better way like a 3rd party component. Then the code sends an email using the Send() method of SmtpClient. The from address, to address, subject and the body is marked.

The above code will create an email to be sent to the user with a URL. You can go to your C:\Test and open the email stored there in any text editor such as Notepad. A sample verification URL is given below:

http://localhost:49310/Account/

ConfirmEmail?userid=d333fcd6-ac33-4d16-b17e-ed4096a567de&token=….

For the sake of clarity the actual token is not shown above. But you can see how the query string contains “userid” and “token” values.

Clicking on this link will take the user to ConfirmEmail() action of Account controller. The ConfirmEmail() action is shown below:

public IActionResult ConfirmEmail(string userid,string token)

{

MyIdentityUser user= userManager.FindByIdAsync(userid).Result;

IdentityResult result= userManager.

ConfirmEmailAsync(user,token).Result;

if(result.Succeeded)

{

ViewBag.Message = “Email confirmed successfully!”;

return View(“Success”);

}

else

{

ViewBag.Message = “Error while confirming your email!”;

return View(“Error”);

}

}

The ConfirmEmail() action receives the user’s ID and confirmation token from the query string. Inside, the code finds the MyIdentityUser whose Id matches with the one sent through the query string. Then ConfirmEmail() method of UserManager is called to confirm the user’s email The ConfirmEmail() method requires the MyIdentityUser object and the confirmation token.

The result of ConfirmEmail() is checked and if all goes well a success view is displayed in the browser.

Here is the final step. You need to add some checking in the Login() action that checks whether a user’s email has been verified or not. So, open the Login() POST action and modify it as given below:

[HttpPost]

[ValidateAntiForgeryToken]

public IActionResult Login(LoginViewModel obj)

{

if (ModelState.IsValid)

{

var user = userManager.FindByNameAsync

(obj.UserName).Result;

if (user != null)

{

if (!userManager.IsEmailConfirmedAsync

(user).Result)

{

ModelState.AddModelError(“”,

“Email not confirmed!”);

return View(obj);

}

}

var result = loginManager.PasswordSignInAsync

(obj.UserName, obj.Password,

obj.RememberMe,false).Result;

if (result.Succeeded)

{

return RedirectToAction(“Index”, “Home”);

}

ModelState.AddModelError(“”, “Invalid login!”);

}

return View(obj);

}

If IsEmailConfirmedAsync() returns false or not verified, an error message is displayed to the user, otherwise the login process continues.

We conclude 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

ASP.NET Core Identity And How It Allows Password Reset

In today’s article we shall discuss how to enable password reset such that users can reset their passwords and get a new password.

The password reset steps in ASP.NET Core Identity works in the following manner:

  • A user mentions that he wants to reset his password. He next specifies his UserName.
  • The system generates a password reset token
  • The system sends an email to the user along with a link to reset the password which contains the password reset token.
  • The user clicks on the password reset link and is presented with a form where a new password can be supplied.
  • The system resets the password after assessing the token and then gives a new password to the user.

To enable password reset, you have to add a view model class and a couple of views. Let’s start here….

Open the Login view and change it to include another form to reset the password. The following mark-up shows the new form.

<h1>Reset Your Password</h1>

<form asp-controller=”Account”

asp-action=”SendPasswordResetLink”

method=”post”>

<table>

<tr>

<td><label asp-for=”UserName”>User Name :

</label></td>

<td><input name=”UserName” type=”text” /></td>

</tr>

<tr>

<td colspan=”2″>

<input type=”submit”

value=”Reset Password” />

</td>

</tr>

</table>

<strong>@ViewBag.Message</strong>

<div asp-validation-summary=”All”></div>

</form>

Did you notice that the above form contains textbox for entering user name and submits to the SendPasswordResetLink() action.

The SendPasswordResetLink() action is given below:

public IActionResult SendPasswordResetLink(string username)

{

MyIdentityUser user = userManager.

FindByNameAsync(username).Result;

if (user == null || !(userManager.

IsEmailConfirmedAsync(user).Result))

{

ViewBag.Message = “Error while

resetting your password!”;

return View(“Error”);

}

var token = userManager.

GeneratePasswordResetTokenAsync(user).Result;

var resetLink = Url.Action(“ResetPassword”,

“Account”, new { token = token },

protocol: HttpContext.Request.Scheme);

// code to email the above link

// see the earlier article

ViewBag.Message = “Password reset link has

been sent to your email address!”;

return View(“Login”);

}

The SendPasswordResetLink() action gets the username as given by the user on the Login view. It then produces a password reset token using GeneratePasswordResetTokenAsync() method of the UserManager. The GeneratePasswordResetTokenAsync() method accepts a MyIdentityUser object whose password is to be reset.

Then a URL is generated containing the password reset token in the query string. The URL points to the ResetPassword() action (discussed next). Note that the code that actually sends an email has been omitted for the sake of clarity. A sample URL looks like this:

http://localhost:49310/Account/ResetPassword?token=….

Before you develop the ResetPassword() actions and the ResetPassword view, add new view model class – ResetPasswordViewModel – in the Models folder. This class is mentioned below:

public class ResetPasswordViewModel

{

[Required]

public string UserName { get; set; }

[Required]

[DataType(DataType.Password)]

public string Password { get; set; }

[Required]

[DataType(DataType.Password)]

public string ConfirmPassword { get; set; }

[Required]

public string Token { get; set; }

}

The ResetPasswordViewModel contains four properties – UserName, Password, ConfirmPassword and Token. The Token property holds the password rest token generated earlier.

The ResetPassword() GET action displays ResetPassword view for supplying the new password.

public IActionResult ResetPassword(string token)

{

return View();

}

The markup of ResetPassword view is as follows:

@model ResetPasswordViewModel

<h1>Reset Your Password</h1>

<form asp-controller=”Account”

asp-action=”ResetPassword”

method=”post”>

<input type=”hidden” asp-for=”Token” />

<table>

<tr>

<td><label asp-for=”UserName”></label></td>

<td><input asp-for=”UserName” /></td>

</tr>

<tr>

<td><label asp-for=”Password”>

New Password</label></td>

<td><input asp-for=”Password” /></td>

</tr>

<tr>

<td><label asp-for=”ConfirmPassword”>

Confirm New Password</label></td>

<td><input asp-for=”ConfirmPassword” /></td>

</tr>

<tr>

<td colspan=”2″>

<input type=”submit”

value=”Reset Password” />

</td>

</tr>

</table>

<div asp-validation-summary=”All”></div>

</form>

The ResetPassword view POSTs to ResetPassword() POST action. This action is given below:

[HttpPost]

public IActionResult ResetPassword

(ResetPasswordViewModel obj)

{

MyIdentityUser user = userManager.

FindByNameAsync(obj.UserName).Result;

IdentityResult result = userManager.ResetPasswordAsync

(user, obj.Token,obj.Password).Result;

if (result.Succeeded)

{

ViewBag.Message = “Password reset successful!”;

return View(“Success”);

}

else

{

ViewBag.Message = “Error while resetting the password!”;

return View(“Error”);

}

}

The ResetPassword() POST action gets ResetPasswordViewModel object which has the user name, new password and the password reset token. It then calls ResetPasswordAsync() method of UserManager in an effort to reset the user’s password to the new value. If all goes fine the IdentityResult will succeed. Accordingly a success message or an error message is displayed to the user.

We conclude the discussion here. 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

How To Develop Web API in ASP.NET Core

To mention, developing Web API in ASP.NET Core is equivalent to decorating Web API in ASP.NET MVC with a few differences. The differences are mentioned below in brief:

  • Web API is not a separate framework. It got merged with ASP.NET Core MVC.
  • Previously a Web API class used to inherit from ApiController base class. Due to the merging mentioned above, the Web API doesn’t inherit from ApiController, in fact it inherits from the same Controller class that other controllers also inherit from.
  • As Web API is just another controller, you are free to have as many actions you want. Of course, to create a REST style service you still need to have those standard Get(), Post(), Put() and Delete() actions as before.
  • You can define the HTTP verb and action mapping at the action level using features like [HttpPost], [HttpPut] and [HttpDelete].

With the above overview, let’s build a simple REST style Web API that performs CRUD operations on the Customers table of the Northwind database.

Start by creating a new ASP.NET Core project using VS and pick the Web API project template.

The project contains ValuesController in the Controllers folder. Take note that the ValuesController inherits from Controller base class just like any other MVC controller.

Rename the default Web API class to CustomerServiceController. You will require database support for your service and hence you need to add NuGet packages for Entity Framework Core. You can do that through Project.json file:

….

“Microsoft.EntityFrameworkCore”: “1.0.1”,

“Microsoft.EntityFrameworkCore.SqlServer”: “1.0.1”

….

Take the Startup class and modify as shown below:

public class Startup

{

public void ConfigureServices

(IServiceCollection services)

{

services.AddMvc();

services.AddEntityFrameworkSqlServer();

}

public void Configure

(IApplicationBuilder app)

{

app.UseStaticFiles();

app.UseMvc(routes =>

{

routes.MapRoute(

name: “default”,

template: “{controller=Home}

/{action=Index}

/{id?}”);

});

}

}

The ConfigureServices() method sums up MVC and Entity Framework Core to the services collection. The Configure() method configures the MVC routing. This routing is not required by the Web API as such but is needed for local clients while consuming the Web API (as you will see in later parts).

Then add Models and Views folders to the project. Add Customer model class in the Models folder as given below:

[Table("Customers")]

public class Customer

{

[Key]

public string CustomerID { get; set; }

public string CompanyName { get; set; }

public string ContactName { get; set; }

public string Country { get; set; }

}

The Customer class is decorated with [Table] attribute that maps it to the Customers table. It contains four public properties namely CustomerID, CompanyName, ContactName and Country. The CustomerID is marked as the primary key using the [Key] attribute.

Then add NorthwindDbContext class to the Models folder and write the following code to it:

public class NorthwindDbContext:DbContext

{

public DbSet<Customer> Customers { get; set; }

protected override void OnConfiguring

(DbContextOptionsBuilder optionsBuilder)

{

optionsBuilder.UseSqlServer(“data source=.;

initial catalog=northwind;

integrated security=true”);

}

}

The NorthwindDbContext class acts as the DbContext for our data access and inherits from the DbContext class. The NorthwindDbContext defines Customers DbSet. The OnConfiguring() method configures the DbContext to use the SQL Server database with the specified connection string. Ensure to adjust the connection string to suit your need.

Now, open the CustomerServiceController and type the following code:

[Route(“api/[controller]“)]

public class CustomerServiceController : Controller

{

[HttpGet]

public List<Customer> Get()

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.OrderBy(

i => i.CustomerID).ToList();

}

}

[HttpGet("{id}")]

public Customer Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

return db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

}

}

[HttpPost]

public string Post([FromBody]Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Customers.Add(obj);

db.SaveChanges();

return “Customer added successfully!”;

}

}

[HttpPut("{id}")]

public string Put(string id, [FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return “Customer modified successfully!”;

}

}

[HttpDelete("{id}")]

public string Delete(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var obj = db.Customers.Where(

i => i.CustomerID == id).SingleOrDefault();

db.Customers.Remove(obj);

db.SaveChanges();

return “Customer deleted successfully!”;

}

}

}

Take note of the following about the Web API you have created:

  • The CustomerServiceController is designed with [Route] feature that configures the routing for the Web API. The route adds /api is written after the name of the controller. So, our Web API will be located at /api/CustomerService.
  • The Web API comprise of five actions namely Get(), Get(id), Post(), Put(), Delete().
  • The HTTP verb to action mapping is done using the features – [HttpGet], [HttpPost], [HttpPut] and [HttpDelete] respectively.
  • The Customer parameter of the actions is model bound and makes use of the [FormBody] feature which indicates the parameter values that will be coming from the request’s body.
  • These features also specify the id route parameter when necessary.

Here in this article we shall not discuss the details of the Entity Framework Core code that is present in these actions. If you worked with EF before that code must be familiar to you. The above mentioned actions generally implement CRUD (create, read, update and delete) operations for the Customers table.

Ok. This completes the CustomerService Web API. Run the application and see the result. If all goes well you should see JSON customer objects removed in the browser.

Return of the IActionResult and HTTP status codes

In the above example the actions gave back the specific types like List<Customer>, Customer and string. However, that’s not required. You might return a generic IActionResult from all the Web API action methods. This technique gets easy when you want to indicate HTTP status codes along with the return values.

Consider the Put() method given below:

[HttpPut("{id}")]

public IActionResult Put(string id,

[FromBody] Customer obj)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

db.Entry(obj).State = EntityState.Modified;

db.SaveChanges();

return new ObjectResult

(“Customer modified successfully!”);

}

}

The Put() now returns IActionResult in place of a string. Inside, the code develops a new ObjectResult object to return a string value back to the caller. The ObjectResult sets the HTTP status code to 200 (Ok) and then returns the specific value to the caller. All the actions of our CustomerService Web API can be modified to use this technique.

If you don’t want to return anything from an action (void) then you can use NoContentResult object instead of ObjectResult. The NoContentResult returns HTTP status 204 (no content).

You can also use certain inbuilt methods to indicate the HTTP status code. Some of them are mentioned below:

  • Ok() : Gives back HTTP status code of 200 (ok).
  • BadRequest() : Gives back HTTP status code of 400 (bad request).
  • NotFound() : Gives back HTTP status code of 404 (not found).

The following code shows Get(id) action modified to use NotFound() method.

[HttpGet("{id}")]

public IActionResult Get(string id)

{

using (NorthwindDbContext db =

new NorthwindDbContext())

{

var data= db.Customers.Where

(i => i.CustomerID == id).SingleOrDefault();

if(data==null)

{

return NotFound(“Invalid CustomerID!”);

}

return new ObjectResult(data);

}

}

As you can see, the code now checks whether data is null or not. If it is null it indicates that the CustomerID was not found in the database and hence NotFound() method is called with a custom error message.

We conclude the discussion here.

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

Consume ASP.NET Core Web API using jQuery

In the article we shall discuss to create a Web API using jQuery. A Web API can be created by local clients or remote clients. Local clients are housed in the same web application as the Web API. Remote clients are the clients that are not part of the Web API application.

To tell about web applications, a typical local client takes a form of jQuery Ajax driven user interface that consumes the Web API. For instance, consider a simple page shown below:

The above client to the CustomerService Web API comprise of a dropdown list and 4 textboxes. The dropdown list has a list of present CustomerIDs. Selecting a CustomerID gives the other textboxes the respective values. You can change the values and click on Update button to save them. To insert a new Customer, do specify its CustomerID in the textbox besides the dropdown list, fill in other details and press the Insert button. Finally, to erase a Customer, select its CustomerID from the dropdown list and click on the Del button.

To design this page, add a new controller – HomeController – in the Controllers folder. Also add Index view and write the following HTML markup into it:

<h1>Customer Manager</h1>

<form>

<table border=”1″>

<tr>

<td>Customer ID :</td>

<td>

<select id=”customerid”></select>

OR

<input id=”newcustomerid” type=”text” />

</td>

</tr>

<tr>

<td>Company Name :</td>

<td><input id=”companyname” type=”text” /></td>

</tr>

<tr>

<td>Contact Name :</td>

<td><input id=”contactname” type=”text” /></td>

</tr>

<tr>

<td>Country :</td>

<td><input id=”country” type=”text” /></td>

</tr>

<tr>

<td colspan=”2″>

<input type=”button” id=”insert”

value=”Insert” />

<input type=”button” id=”update”

value=”Update” />

<input type=”button” id=”delete”

value=”Delete” />

</td>

</tr>

</table>

<br />

<div id=”msg”></div>

</form>

To initiate the Web API you created earlier, you will use jQuery Ajax. So, sum up Scripts folder under the wwwroot folder and place jQuery library into it

Also, add a <script> reference to the jQuery library in the <head> section of the Index view.

<script src=”~/Scripts/jquery-3.1.1.min.js”></script>

There are 5 jQuery Ajax calls needed by our client. They are as follows:

  • No sooner a page loads in the browser, the dropdown list must be filled with all the existing CustomerIDs. This is done by bringing the Get() Web API action through jQuery Ajax.
  • When you select a CustomerID from the dropdown list its details such as CompanyName, ContactName and Country are shown in the respective textboxes. This is done with the Get(id) Web API action from the change event handler of the dropdown list.
  • Clicking Insert, Update and Delete buttons call the Post(), Put() and Delete() Web API actions respectively, again through jQuery Ajax.

Next write the first Ajax call.

Filling the dropdown list with CustomerIDs

$(document).ready(function () {

var options = {};

options.url = “/api/customerservice”;

options.type = “GET”;

options.dataType = “json”;

options.success = function (data) {

data.forEach(function (element) {

$(“#customerid”).append(“<option>”

+ element.customerID + “</option>”);

});

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above written code makes an Ajax request using $.ajax() method of jQuery. Take notice how the url, type and dataType properties of the options object are specified. Since we wish to start Get() action, the url points to the Web API end point. The HTTP verb used is GET and the response data type is all set to json.

The success function simply fills the dropdown list with a series of <option> element each wrapping a CustoemrID. The error function portrays an error message when something goes wrong while starting the Web API.

Displaying details of a selected customer

The change event handler of the dropdown looks like this:

$(“#customerid”).change(function () {

var options = {};

options.url = “/api/customerservice/” +

$(“#customerid”).val();

options.type = “GET”;

options.dataType = “json”;

options.success = function (data) {

$(“#companyname”).val(data.companyName);

$(“#contactname”).val(data.contactName);

$(“#country”).val(data.country);

};

options.error = function (a, b, c) {

alert(a.responseText);

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

This code is very similar to the previous one. However, it adds the CustomerID whose details are to be fetched to the url. The success function fills the 3 textboxes with CompanyName, ContactName and Country. Do notice something significant- the property names are automatically converted to use camel casing. This way client side code gets to stick with the JavaScript ways of naming the things whereas server side code can continue to stick to the C# ways of naming the things.

To add a new customer

The click event handler of the Insert button is shown below:

$(“#insert”).click(function () {

var options = {};

options.url = “/api/customerservice”;

options.type = “POST”;

var obj = {};

obj.customerID = $(“#newcustomerid”).val();

obj.companyName = $(“#companyname”).val();

obj.contactName = $(“#contactname”).val();

obj.country = $(“#country”).val();

options.data = JSON.stringify(obj);

options.contentType = “application/json”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above written code uses POST verb to make the Web API call. Also, it sets data, dataType and contentType properties. The data property is set to the stringed version of the new customer object. Take note that this new object also uses camel casing while setting the properties. The dataType property is set to html because our Post() action returns a plain string. The contentType property indicates the request’s data type – JSON in this case.

The success function simply displays the message returned by the Post() action into the msg <div> element.

To modify an existing customer

The click event of the Update button is shown below:

$(“#update”).click(function () {

var options = {};

options.url = “/api/customerservice/”

+ $(“#customerid”).val();

options.type = “PUT”;

var obj = {};

obj.customerID = $(“#customerid”).val();

obj.companyName = $(“#companyname”).val();

obj.contactName = $(“#contactname”).val();

obj.country = $(“#country”).val();

options.data = JSON.stringify(obj);

options.contentType = “application/json”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function (a, b, c) {

alert(c);

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

Most of the above program is similar to the code you wrote in the insert click event handler. The CustomerID being changed is added to the url. The HTTP verb is set to PUT.

To Delete a customer

Finally, the code that deletes a customer is mentioned below:

$(“#delete”).click(function () {

var options = {};

options.url = “/api/customerservice/”

+ $(“#customerid”).val();

options.type = “DELETE”;

options.dataType = “html”;

options.success = function (msg) {

$(“#msg”).html(msg);

};

options.error = function () {

$(“#msg”).html(“Error while

calling the Web API!”);

};

$.ajax(options);

});

The above program sets the HTTP verb to DELETE and makes an Ajax call like before.

This finishes the jQuery client to the Web API. Now you need to run the Index view and test all the operations.

We conclude the discussion here. 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

Five Methods To Deal with Errors In ASP .Net

Any real-world web application needs a program to handle errors. In ASP.NET Web Forms there are certain events and custom error pages to deal with them. In ASP.NET MVC there is [HandleError] feature, exception filters and custom error pages to deal. In ASP.NET Core there are a set of methods and, exception filters for you. In this blog topic; I will discuss 5 methods for error handling.

These methods are from the Configure() method of the startup class. They are available as extension methods of the IApplicationBuilder object received by the Configure() method. These extension method generally call the Microsoft.AspNetCore.Diagnostics middleware to get the job done.

To view these methods in action, create a new ASP.NET Core application based on Web Application project template. Then open the HomeController and deliberately put an exception from the Index() action as shown below:

public IActionResult Index()

{

throw new Exception(“This is some exception!!!”);

return View();

}

The code above is quite simple and needs no explanation.

Let’s discuss the 5 methods one by one:

1. UseDeveloperExceptionPage() – Looks after exception details during development

The  UseDeveloperExceptionPage() method is very easy during development stage. To use this method open the Startup.cs file, locate the Configure() method and change it to appear like this:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseDeveloperExceptionPage();

….

….

}

As mentioned earlier this method should be used only during development stage as you don’t want to show the details to the end user. That’s why it is a good idea to call UseDeveloperExceptionPage() method like this:

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

else

{

//something else here

}

Now the UseDeveloperExceptionPage() is housed inside an if block. If the hosting environment is development IsDevelopment() method returns true and only then UseDeveloperExceptionPage() gets called. Otherwise some other error handling code take place.

2. UseExceptionHandler() – Gives the control to custom error handler

This method uses a specified error handler to deal with the exception. The error handler logs the exceptions and show a friendly message to the end user. To use this method first of all open the HomeController and locate the Error() action. This action is added as a part of the Web Application project template and also has the corresponding view – Error.cshtml – inside the Views folder.

Change the Error() action as shown below:

public IActionResult Error()

{

var exception = HttpContext.Features

.Get<IExceptionHandlerFeature>();

ViewData["statusCode"] = HttpContext.

Response.StatusCode;

ViewData["message"] = exception.Error.Message;

ViewData["stackTrace"] = exception.

Error.StackTrace;

return View();

}

The Error() action extracts exception details and sends them to the Error view through ViewData. To grab the exception that was thrown the code uses Features.Get() method on HttpContext. The HTTP status code is obtained using the Response.StatusCode property. The status code, exception message and exception stack trace are stored in ViewData dictionary for the use on the Error view.

Now open Error view and change it as shown below:

<h1>@ViewData["message"]</h1>

<h2>Status Code : @ViewData["statusCode"]</h2>

<div>@ViewData["stackTrace"]</div>

The above code is simple enough for any explanation.

Finally, visit the Configure() method and change it to call UseExceptionHandler().

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

app.UseExceptionHandler(“/Home/Error”);

….

….

}

As you can see, this time we call UseExceptionHandler() method and specify /Home/Error action as a string parameter. So whenever there is any unhandled exception control will be taken to Error() action.

3. UseStatusCodePages() – This shows error pages for HTTP status codes

The two methods discussed above deal with the unhandled exceptions that arise from your code. But, that’s not the only source of errors. At times errors are generated due to internal server errors, non existent pages, web server authorization issues and so on. These errors are reflected by the HTTP status codes such as 500, 404 and 401.

To deal with these errors you can use UseStatusCodePages() method. This method can be used as follows:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePages();

….

….

}

Although the default version permits us to see the HTTP status code, but it is a plain text. So you can format it as an HTML fragment. You can do that as shown below:

app.UseStatusCodePages(“text/html”,

“<h1>Status code page</h1> <h2>Status Code: {0}</h2>”);

The UseStatusCodePages() method now uses HTML markup to render the status code. Notice the use of {0} to output the status code at a specific place within the markup.

4. UseStatusCodePagesWithRedirects() – Perform URL redirection upon error

Many times you might want to handover the control to some action whenever there is some HTTP error (such as 404). It is then, UseStatusCodePagesWithRedirects() comes handy. It sends HTTP status code 302 (Found) to the browser and performs the redirection using the action specified. Take the following code:

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}”);

….

….

}

The code takes UseStatusCodePagesWithRedirects() method and passes /CustomErrorPages/{0} as a string parameter. The {0} placeholder is used only if you wish to pass the status code (such as 404) to the handler. Then sum up another action to the HomeController as shown below:

[Route("/CustomErrorPages/{code}")]

public IActionResult StatusCodeErrors(string code)

{

ViewData["statusCode"] = code;

return View();

}

The [Route] attribute maps /CustomErrorPages to StatusCodeErrors(). The StatusCodeErrors() action accepts code parameter that is the HTTP status code. Make sure to add the StatusCodeErrors view and output the ViewData statusCode value on it.

Note that this response is given by Error view. The {0} placeholder passed 404 to the Error() action. You can conditionally give some different view based on the status code if you so wish. You can also device a mechanism like this:

app.UseStatusCodePagesWithRedirects(“/CustomErrorPages/{0}.html”);

You can now see the code redirects to a separate HTML pages stored as 404.html, 500.html and so on. This way you can display different custom error pages for different status codes.

5. UseStatusCodePagesWithReExecute() – Re-execute the request pipeline with alternate action

The UseStatusCodePagesWithReExecute() is similar to UseStatusCodePagesWithRedirects() in that both executes some alternate action if there is any HTTP error. But, UseStatusCodePagesWithRedirects() does redirection to the alternate action whereas UseStatusCodePagesWithReExecute() re-executes the entire request pipeline and executes the alternate action. The UseStatusCodePagesWithRedirects() sends status code of 302 to the browser and browser address bar reflects the new URL upon redirection. In case of UseStatusCodePagesWithReExecute() the original status code is sent to the browser and the address bar will continue to show the original URL.

You can use the UseStatusCodePagesWithReExecute() method as follows :

public void Configure(IApplicationBuilder app,

IHostingEnvironment env,

ILoggerFactory loggerFactory)

{

….

….

app.UseStatusCodePagesWithReExecute(“/CustomErrorPages/{0}”);

….

….

}

We conclude the discussion here. 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

How to Use Your GPU in .NET

Introduction

This blog topic is going to tell you that a modern Core I7 is most probably the slowest piece of programmable hardware that your PC has. Modern Quad Core CPUs have almost 6 Gflops whereas modern GPUs have about 6Tflops of computational power.

This can dynamically execute simple programs written in a C dialect on your GPU, CPU or both. They are compiled and executed at the run time.

This also shows that GPU programming is not that hard. You will need a little bit of basic programming skills.

Why I need this?

Your PC is a powerful machine. By using only a CPU to execute tasks, you might waste about 90% of its potential.

Basically all data fits into some other numeric arrays.

Instances for a powerful speed up are:

  • Work on images or movies

  • When parallel works are done

  • Save time and energy by using GPU and CPU parallely

  • Use your GPU for a task while have your CPU free for something else

Keep in mind that this topic speaks about OpenCL. Unlike Cuda, it runs on any GPU (Amd, Nvidia, Intel) and also on the CPU. So any program you code can be used on any device. (Even phones)

Tested on NVIDA, AMD, and Intel.

These are the results for some prime calculations:

You can really speed up your program. Native C# is 5 times slower than the best speed you can get on your PC. The speedup factor can approach 500 times in pure multiply and add workloads. It is easy to write a program for your GPU and CPU with this class.

OpenCL code always runs faster than C# on arrays.

How To Use It?

OpenCL programming is very time consuming. This helper project will lessen your programming such that you can focus on the core problem. It is written in C# but could be adapted to any .NET language and also C++.

Suppose you want to know all the prime numbers from 2 to 10^8. Here is a simple implementation in C#

tatic void IsPrimeNet(int[] message)

{

Parallel.ForEach(message, (number, state, index) =>

{

int upperlimit = (int)Math.Sqrt(number);

for(int i=2;i<=upperlimit;i++)

{

if (message[index]%i == 0) //no lock required. every index is independent

{

message[index] = 0;

break;

}

}

});

}

Now take this code and translate to OpenCL-C.
The following
Kernel is declared as a string in a file, inline or in a resource file.

kernel void GetIfPrime(global int* message)

{

int index = get_global_id(0);

int upperl=(int)sqrt((float)message[index]);

for(int i=2;i<=upperl;i++)

{

if(message[index]%i==0)

{

//printf(“” %d / %d\n””,index,i );

message[index]=0;

return;

}

}

//printf(“” % d””,index);

}

OpenCL does cover your kernel in a loop. For simple 1D Arrays, you can get the index by calling get_global_id(0); The upper index is passed when you call the the kernel.

Instead of int[], you can write int* and so on.

You have to pass logics in the same order in which you declared them. You can also call printf inside your kernel to debug later. You can define many methods as you want inside the kernel. You can pick the entry point afterwards by stating Invoke(“Name Here”).

OpenCL C is the same as C but you can’t use pointers and you also have some special data types.

Here is how you can use this project:

Add the Nuget Package Cloo

Add reference to OpenCLlib.dll.
Download OpenCLLib.zip.

Add using OpenCL

static void Main(string[] args)

{

int[] Primes = Enumerable.Range(2, 1000000).ToArray();

EasyCL cl = new EasyCL();

set the accelerator after loading the kernel

cl.Accelerator = Accelerator.Gpu; //You can also

cl.LoadKernel(IsPrime); //Load kernel string here, (Compiles in the background)

cl.Invoke(“GetIfPrime”, Primes.Length, Primes); //Call Function By Name With Parameters

//Primes now contains all Prime Numbers

}

static string IsPrime

{

get

{

return @”

kernel void GetIfPrime(global int* message)

{

int index = get_global_id(0);

int upperl=(int)sqrt((float)message[index]);

for(int i=2;i<=upperl;i++)

{

if(message[index]%i==0)

{

//printf(“” %d / %d\n””,index,i );

message[index]=0;

return;

}

}

//printf(“” % d””,index);

}”;

}

}

With this, you can compile and call upon OpenCL kernels.

If you want to use every bit of computational power of your PC, you can use the class MultiCL. This class splits your work into N parts. Every part is pushed onto the GPU or CPU whenever required. This way, you attain the maximum performance from your PC.

static void Main(string[] args)

{

int[] Primes = Enumerable.Range(2, 1000000).ToArray();

int N = 200;

MultiCL cl = new MultiCL();

cl.ProgressChangedEvent += Cl_ProgressChangedEvent1;

cl.SetKernel(IsPrime, “GetIfPrime”);

cl.SetParameter(Primes);

cl.Invoke(0, Primes.Length, N);

}

private static void Cl_ProgressChangedEvent1(object sender, double e)

{

Console.WriteLine(e.ToString(“0.00%”));

}

Working

This work refers to the Nuget package Cloo. With Cloo, orders to OpenCL are possible from .NET.

It hides the installation details you need to know to use OpenCL and Cloo. To get more information about your kernel or device, use the class OpenCL.

There are 3 classes in this project:

  • EasyCL
  • MultiCL
  • OpenCL

Every call to Invoke calls the corresponding methods in the OpenCL API:

void Setargument(ComputeKernel kernel, int index, object arg)

{

if (arg == null) throw new ArgumentException(“Argument “ + index + ” is null”);

Type argtype = arg.GetType();

if (argtype.IsArray)

{

Type elementtype = argtype.GetElementType();

//ComputeBuffer<int> messageBuffer = new ComputeBuffer<int>(context,

//ComputeMemoryFlags.ReadOnly | ComputeMemoryFlags.UseHostPointer, (int[])arg);

ComputeMemory messageBuffer = (ComputeMemory)Activator.CreateInstance

(typeof(ComputeBuffer<int>), new object[]

{

context,

ComputeMemoryFlags.ReadWrite | ComputeMemoryFlags.UseHostPointer,

arg

});

kernel.SetMemoryArgument(index, messageBuffer); // set the array

}

else

{

//kernel.SetValueArgument(index, (int)arg); // set the array size

typeof(ComputeKernel).GetMethod(“SetValueArgument”).MakeGenericMethod(argtype).Invoke

(kernel, new object[] { index, arg });

}

}

Every time you change the kernel, the program gets recompiled:
For a faster prototype phase, this class tells you why you cannot compile your kernel.

public void LoadKernel(string Kernel)

{

this.kernel = Kernel;

program = new ComputeProgram(context, Kernel);

try

{

program.Build(null, null, null, IntPtr.Zero); //compile

}

catch (BuildProgramFailureComputeException)

{

string message = program.GetBuildLog(platform.Devices[0]);

throw new ArgumentException(message);

}

}

It is very important to know that if your GPU driver crashes or kernels use 100% of your GPU for more than 3 seconds (on pre Win10 machines), the kernel will get aborted. You should dispose the EasyCL object after that.

//If windows Vista,7,8,8.1 you better be ready to catch:

EasyCL cl = new EasyCL();

cl.InvokeAborted += (sender,e)=> Cl_InvokeAborted(cl,e);

private void Cl_InvokeAborted(EasyCL sender, string e)

{

//your logic here

}

What is missed?

You cannot choose if you want to use the host pointer or read write access to int[] passed to the kernel. This seems to be a legacy function.

This class is written for PCs. With VS/Xamarin, it could be easy adapted for phones.

We conclude the discussion here. 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