Jan 28, 2017

Encryption and Decryption in Asp.Net Core

Asp.Net Core provides encryption and decryption feature for API data protecting.

It's easy to use encryption and decryption provides by Asp.Net Core framework.

Let us see the sample of the code with encryption and decryption in Asp.Net Core API application.

For the demo, I have created an Asp.Net Core API.

On Values Controller, inject IDataProtector interface for encryption and decryption.
        private readonly IDataProtector _protector;

        public ValuesController(IDataProtectionProvider provider)
        {
            _protector = provider.CreateProtector(GetType().FullName);
        }

Once _protector variable assigned from the constructor then you can use for the encryption and decryption.

From the _protecor variable, you can use encryption using Protect method and decryption using Unprotect method.

The full source code looks like below and I have used dummy string for the demo.
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.DataProtection;

namespace AspNetCoreEncryptionAndDescription.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IDataProtector _protector;

        public ValuesController(IDataProtectionProvider provider)
        {
            _protector = provider.CreateProtector(GetType().FullName);
        }

        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            var encrypted = _protector.Protect("This is for testing!!");
            var decrypted = _protector.Unprotect(encrypted);
            return new string[] { encrypted, decrypted };
        }
    }
}

Hope you like Encryption and Decryption in Asp.Net Core.

Jan 22, 2017

Multiple master pages in Angular2 and TypeScript Application

Today, I am a cover very hot topic in the market. Which are an Angular2 and TypeScript.

How to create multiple master pages in Angular2 and TypeScript application.

Normally in the application, public and secure pages are there. I mean to access those pages without login its a public and those pages access after the login which is secure.

So we are going to cover public and secure pages master pages.

Let's go step by step to create and configure the application to support multiple master pages.

Step 1: Create Angular2 using angular CLI

Step 2: Once you created the application and its running without any errors.

Step 3: Create layout folder under the src\app folder

Step 4: Once you created layout folder, now time to create public and secure component respectively to create under own folder
 - So your folder structure look like for layout is

  1. Src\App\layout\public - Foder public component which represents the public master page.
  2. Src\App\layout\secure - Folder secure component which represents secure master pages.

Step 5: Now time to create routes file for each layout folders of public and secure
- Before creating routes file under layout folders, require creating root level public and secure folders for public and secure pages.

- Once you created root level folders for public and secure then we are going to add component respectively login and home page on public and secure folders.

- Let's create routes file for each layout folder and add routing information of both folders.

Step 6: Once routes file created (public,route.ts & secure.route.ts) Now time to configuration time for routing.

1. public.routes.ts file
import { LoginComponent } from './../../public/login';
import { Routes, RouterModule } from '@angular/router';


export const PUBLIC_ROUTES: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: 'login', component: LoginComponent }
];
2. secure.routes.ts file
import { HomeComponent } from './../../secure/home';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './../../../common/auth.guard';

export const SECURE_ROUTES: Routes = [
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
];

Step 7: Once folder level routes define then we are going to configure root level routing using child routes.
-Going to create root level routes file(app-routing.module.ts)
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './../common/auth.guard';
import { SecureComponent, SECURE_ROUTES } from './layout/secure';
import { PublicComponent, PUBLIC_ROUTES } from './layout/public';
/**
 * Route constant 
 */
const routes: Routes = [
    { path: '', redirectTo: 'login', pathMatch: 'full' },
    { path: '', component: PublicComponent, data: { title: 'Public Views' }, children: PUBLIC_ROUTES },
    { path: '', component: SecureComponent, canActivate: [AuthGuard], data: { title: 'Secure Views' }, children: SECURE_ROUTES },
    { path: '**', redirectTo: 'login' }
];

/**
 * App routing module
 */
@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [RouterModule]
})
export class AppRoutingModule { }

Step 8: Last but important point doesn't forget to add router-outlet tag on following files.
1. app.component.html
2. layout\public\public.component.html
3. layout\secure\secure.component.html
<router-outlet></router-outlet>

You can find source code on my Github repository

Hope you like it and happy coding!!

Jan 8, 2017

Create Angular2 Application using Angular CLI and Asp.Net Core

Going to talk more about the latest and the hot topic of the current trend in the market. It's an Angular2 and Asp.Net Core.

The Angular2 CLI makes it easy to create an  Angular2 application else it's very complex configuration for developers.

Good news for those developers, who loved to work with asp.net using visual studio IDE because we will see how to work Angular2 application using visual studio IDE.

The first fall we will create an empty asp.net core solution.

We have created an empty solution so we need to add some packages to support MVC and static files.
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0"

Once above packages configured and restored completed than requiring to modified StartUp class to support configurations.

1. On ConfigureServices method add services.AddMvc();
2. On Configure method add following configurations.
       app.UseMvc();
       app.UseStaticFiles();
Also, add some redirect related configuraiton.

After including all, how startup class looking as below.
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.Use(async (context, next) =>
        {
            await next();

            if (context.Response.StatusCode == 404 &&
                !Path.HasExtension(context.Request.Path.Value) &&
                !context.Request.Path.Value.StartsWith("/api/"))
            {
                context.Request.Path = "/index.html";
                await next();
            }
        });

        app.UseMvc();
        app.UseStaticFiles();
    }
}

Now, Asp.Net core application is ready so we will create an angular application.

For the Angular application, we are going to create Class Library because it will show in visual studio.
Before we move ahead please visit angular cli website.

The first fall we are going to install npm angular cli globally.
npm install -g angular-cli

After installing above npm, we are going to create Angular2 Application using the class library project.

so open command prompts and navigate to project\src\ClientApp folder and write the following command to create Angular2 Application.
ng new ClientApp

It will take a while to create an application and install npm packages.

Once all set, run the application using ng serve so it will run on http://localhost:4200.

If you want to run the angular application from asp.net core application for that require the following configuration on angular-cli.json. file.

set up outDir path because its default is "dist" folder
 "outDir": "../../Angular2CliAspNetCore/wwwroot"

Once you have done above configuration than build the angular2 application with the following command so it will build and copy the content of the angular2 application on mention output directory so you can directly run the asp.net core application with angular2.
ng build

Whenever you want to deploy this application then first required to execute above command and then public asp.net core application for the deployment.

For the source code, you can visit my Github repository.

Hope you like it!!

Jan 7, 2017

xUnit integration testing with an In Memory Database in Asp.Net Core App

Today, We are going to cover xUnit integration testing with an In Memory database in Asp.Net Core.

I assumed you already work with Asp.Net core application so we are not going to discuss about asp.net core and xUnit.

You can find the source code from my Github repository.

Source code, I have created asp.net core application and one class library. Class library for integration testing purpose created.
Lets see step by step

Step 1: If you have already asp.net core application than create new project (Class Library) for integration testing

Step 2: Once class library created, require to following dependencies on project.json file
"Microsoft.EntityFrameworkCore.InMemory": "1.1.0",
"xunit": "2.2.0-beta2-build3300",
"dotnet-test-xunit": "2.2.0-preview2-build1029",

Also add "testRunner" on project.json file.

Step 3: Once all dependency added than its look like following
{
  "version": "1.0.0-*",
  "testRunner": "xunit",
  "dependencies": {
    "Microsoft.EntityFrameworkCore.InMemory": "1.1.0",
    "xunit": "2.2.0-beta2-build3300",
    "dotnet-test-xunit": "2.2.0-preview2-build1029",
    "NETStandard.Library": "1.6.0",
    "InMemoryDatabaseAspNetCore.Model": "1.0.0-*"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      }
    }
  }
}

Step 4: Now, all set regarding configuration so we looking for code.
Step 5: Create new class file, in our example we are create UserTest.cs
Step 6: For In Memory Database, we are going setup on constructor level and pass options to Context.
private InMemoryContext _context;
public UserTest()
{
    var builder = new DbContextOptionsBuilder<InMemoryContext>();
    builder.UseInMemoryDatabase();
    var options = builder.Options;
    _context = new InMemoryContext(options);
}
Here you can check we have use InMemoeryData with builder builder.UseInMemoryDatabase()

Step 7: Time to write test cases, we have written following sample test case for user
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InMemoryDatabaseAspNetCore.Model;
using Microsoft.EntityFrameworkCore;
using Xunit;

namespace InMemory.Test
{
    public class UserTest
    {
        private InMemoryContext _context;
        public UserTest()
        {
            var builder = new DbContextOptionsBuilder<InMemoryContext>();
            builder.UseInMemoryDatabase();
            var options = builder.Options;
            _context = new InMemoryContext(options);
        }
        [Fact]
        public void RunTests()
        {
            AddUser();
            GetAllUser();
            UpdateUser();
        }

       
        private void AddUser()
        {
            // Act
            var user = new ApplicationUser()
            {
                Email = "satasiya.kalpesh2006@gmail.com",
                Birthday = new DateTime(1988, 10, 21),
                Gender = "Male",
                Name = "Kalpesh Satasiya",
                UserName = "kalpeshsatasiya",
            };

            _context.Users.Add(user);
            var newUser = _context.SaveChanges();
            // Assert
            Assert.NotNull(newUser);
        }

        private void GetAllUser()
        {
            var users = _context.Users.Select(x=>x).ToList();
            Assert.NotNull(users);
            Assert.True(users.Any(), "Not record found");
        }

        private void UpdateUser()
        {
            var users = _context.Users.Select(x => x).ToList();
            if (users.Any())
            {
                users[0].UserName = "KalpeshSatasiyaTest";
                users[0].Email = "satasiya.kalpesh2006Test@gmail.com";
                users[0].Name = "Kalpesh Satasiya";
                users[0].Country = "India";

                _context.Users.Update(users[0]);
                var updateUser = _context.SaveChanges();
                Assert.NotNull(updateUser);
            }

        }

    }
}

Step 8: Run test cases.

Hope you like it and visit my Github Repository for source code