Dec 22, 2017

Write JavaScript code that accepts an array of integer and output the sum of two largest integers from array. But the sum of those two largest integers should be even number.

Write JavaScript code that accepts an array of integer and output the sum of two largest integers from the array. But the sum of those two largest integers should be even number.

Example:

#1
var int_array = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// should output 7+9 = 16

#2
var int_array = [9, 5, 3, 2, 8, 14, 5, 7, 3, 11, 12]

// should output 12+14 = 26

Following is the solution to the above interview question.

 

//var int_array = [1, 2, 3, 4, 5, 6, 7, 8, 9];
 var int_array = [9, 5, 3, 2, 8, 14, 5, 7, 3, 11, 12];
 var first_max_number = Math.max.apply(null, int_array); //Find first max number
 
 var index = int_array.indexOf(first_max_number);
 if (index > -1) { //Once get max number pop from array
  int_array.splice(index, 1);
 }
 
 var second_max_number =0;
 for (i=0; i < int_array.length; i++){ //for second max number 
   second_max_number = Math.max.apply(null, int_array); //find second max number
  if(isEven(first_max_number) && isEven(second_max_number)){ // check both number should be event or odd
   break; //Once condition get satisfy, break the look 
  }else if(isOdd(first_max_number) && isOdd(second_max_number)){
   break;
  }
 
  index = int_array.indexOf(second_max_number);
  if (index > -1) { //pop second max number from the array
   int_array.splice(index, 1);
  }
 }
 var sum = first_max_number + second_max_number;
 alert(first_max_number +" + "+ second_max_number +" = "+ sum);
 
 function isEven(n) { //check event number
  return n % 2 == 0;
 }

 function isOdd(n) { // check odd number
    return Math.abs(n % 2) == 1;
 }

Hope it will help you to in the future.

What is the difference between state and props in ReactJs

There are many times we play with state and props in javascript how it's different in react.

Those who don't know about the difference of state and props So I thought it will be a good idea to write a blog post about it.

You may ask, if data is only flown downwards from components to components, how could we access data we need from the previous component?
The answer to that is props.

React uses props to transfer data we need to different components.

Props and state are related.For parent-child communication, simply pass props.

Use state to store the data your current page needs in your controller-view.

Use props to pass data & event handlers down to your child components.

These lists should help you while working with data in different components.

Props:
- Props is immutable.
- Used to pass data down from your view-controller.
- Better performance
- Use this to pass data to child components

State:
- State is mutable
- Should be managed in your view-controller.
- Worse performance
- Don't access this to from child components, pass it down with props instead

The state of one component will often become the props of a child component.

Props are passed to the child within the render method of the parent as the second argument to React.createElement() or, if you're using JSX, the more familiar tag attributes.
 
The parent's state value of childsName becomes the child's this.props.name.

From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:
 this.setState({ childsName: 'New name' });

and React will propagate it to the child for you.

A natural follow-on question is: what if the child needs to change its name prop?

This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged.

The parent would then subscribe to the event by passing a callback handler.
 

The child would pass its requested new name as an argument to the event callback by calling,
 e.g.,  this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

Dec 11, 2017

Create your first Vue.js application using Visual Studio Code (VS Code)


Going to create Vue.js application using Visual Studio Code before going to create the application, I assume that you already familiar with Visual Studio Code editor.

If you are not aware of it so let me take opportunity to help on this. Visual Studio Code is an open source and free editor from Microsoft. So anyone can use as a free software for the web development.

You can download from here and use for the web development.

Once you open the VS Code its a welcome page open.

Now we are going to create new project/folder (choose your project path). I have created new folder VueJsWithVSCode.

Its an empty folder at moment so we are going to create the first file index.html.

Here, I am going to create simple Vue.js application which will help to understand to beginner.

Vue is a progressive framework for building user interfaces. Vue code library focus on view layer only, and is easy to pick up and integrate with other libraries or existing projects.

Created index.html file with basic html coding. Once you have ready with basic setup of html page.

Going to add Vue library. There is a multiple way to add Vue library.

1. If you are aware of NPM then you can use of Vue npm to install the package.
2. You can use vue-cli to create the application but do not recommend that beginners start with vue-cli.
3. You directly include vue library on your index.html file.
 
Going to add first vue app on index page.
 
{{ message }}
 

var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  }
})
This looks pretty similar to rendering a string template, but Vue has done a lot of work under the hood. The data and the DOM are now linked, and everything is now reactive.
Binding with element attribute.
How to text interpolation using bind element attributes.
 
Hover your mouse over me for a few seconds to see my dynamically bound title!
 
var app2 = new Vue({
  el: '#app-2',
  data: {
    message: 'You loaded this page on ' + new Date().toLocaleString()
  }
})
After adding code and run it. you will see the following line of message on the screen. Once you mouse hover on the text you will get the dynamic text which was bind with the title attribute.

 

Its a simple application for the newbie for Vue.js. 

Nov 20, 2017

JSON support to ignore property at run time of null value

Nowadays, NuGet packages make developer life easy. Today going to talk more about Newtonsoft.Json NuGet package one of the feature.

Many times developer, don't want all fields to be serialize and part of that string which fields value as Null.

Because of nowadays developer playing JSON string to object and object to JSON string and its common.

Some time such requirement like only those fields need to save in JSON string which have values.

JSON property support to ignore the fields run time. which value has Null.
 
class Client
{
    public int Id { get; set; }
    public string Name { get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string NickName { get; set; }    
}

How to use JsonProperty(NullValueHandling = NullValueHanding.Ignore)
 
Client client = new Client
{
    Id = 1,
    Name = "Kalpesh",
    NickName = null,   
};

string json = JsonConvert.SerializeObject(client );
JSON output string look like
 
{Id:1,Name:"Kalpesh"}
Check the output JSON string and get better idea about the NickName field.

Json string only produced the Id and Name fields as output JSON string and ignore NickName field.

Nov 18, 2017

SSRS display date format with st nd rd th

How to do we achieve date format in SSRS.
- Using inbuilt format method to achieve date format in SSRS.
 
=format(cdate(Parameter!ReportingDate.Value),"dd.MM.yyyy")

Using above format method to achieving 21.10.2016 date.
If you want to date format like 21st October 2016 then there is no inbuilt method support to SSRS.
So for the need to write a custom code on the report (.rdl file).

Right click and goto report property and select code section and write to following code.
 
Public Function ConvertDate(ByVal mydate As DateTime) as string
  Dim myday as integer
  Dim strsuff As String
  Dim mynewdate As String
  'Default to th
  strsuff = "th" 
  myday = DatePart("d", mydate)
  If myday = 1 Or myday = 21 Or myday = 31 Then strsuff = "st"
  If myday = 2 Or myday = 22 Then strsuff = "nd"
  If myday = 3 Or myday = 23 Then strsuff = "rd"
  mynewdate = CStr(DatePart("d", mydate)) + strsuff + " " +      CStr(MonthName(DatePart("m", mydate))) + " " + CStr(DatePart("yyyy", mydate))
 return mynewdate
End function

Call above function =Code.ConvertDate(Parameter!ReportingDate.Value), will get the output result as a date format 21st October 2016.

Reference link - https://stackoverflow.com/questions/32712572/format-datetime-day-with-st-nd-rd-th

Jul 23, 2017

Create your first React Component

We have learned in the previous post. How to create React Application using create-react-app npm.

It's very simple and easy to create React Application. Now time to create first React Component.

Assume, you already learn how to create React Application using create-react-app and start to understand the structure what it's provided by default.

If you check inside the folder there were App.js file.

Default code provided by application once you create it.

Now we are going to create our first component and will add on App component.

Create new file First.js and add following code.
 
import React, { Component } from 'react';

class First extends Component {
  render() {
    return (
      
This is the first component
); } } export default First;
Check above code and there is the html code. Span tag inside the div tag and added style on span tag for text color.

Under span tag text is "This is the first component".

Once First.js file code is completed that mean we have completed our first component code.

How to use this component into other components. We can import the First component wherever we need to use.

We have App component in the application so we are going to import the First component into App component.
 
import First from './First'
Once we are done with import then we can use First component into App component html section.



Refer above image with marked red box. the first one is the import statement and the second one how to use the First component.

After adding the First component. refresh the page you will see the blue color text which is written on the First component.


Once you able to see the blue text line on your browser that means you are done with your First component.

Congratulation!! for the first step toward to learning React.

Hope you like this post. Stay tuned for the upcoming post.



Jul 22, 2017

Create your first React Js Application

We are going to create first React Js Application. Nowadays React is very popular and booming in the market.

For creating React App. We are using npm and install some frameworks.

So let’s begin by installing react in our environment. We’ll use the create-react-app javascript framework.
 npm install -g create-react-app
Now we can create the project template using above command.
 create-react-app first-app
It will take some time to install all the module related to React.
Once installation complete, go the folder "first-app" and run the command npm start
cd first-app
npm start
It will start the server on 3000 port. Default application will look like this.
Congratulations, your first application is ready.

Now you can do your customization based on your requirement start by editing the file index.html.

Hope you like this simple way to create React application using some frameworks.

For customization, you have to require knowledge React component and other stuff.



Jun 25, 2017

What is new in ASP.NET Core 2.0 Preview

At Build 2017, Microsoft announced ASP.NET Core 2.0 Preview 1.
This blog post is about new features of ASP.NET Core 2.0 Preview.

1. ASP.NET Core meta-package
ASP.NET Core meta-package that includes all features that you need to build an application. Developer no need to pick and choose individual ASP.NET Core features in separate packages as all features are now included in a Microsoft.AspNetCore.All package in the default templates. If there are features you don’t need in your application, our new package trimming features will exclude those binaries in your published application output by default.


2. Simplified Host Configuration
A new default Web Host configuration, codifying the typical defaults of the web host with the WebHost.CreateDefaultBuilder() API. This adds Kestrel, IIS configuration, default configuration sources, logging providers, and the content root.
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup()
            .Build();
}

3. @page Directive
Create pages without controllers in ASP.NET Core with the new RazorPages capabilities.  Just create a Pages folder and drop in a cshtml file with the new @page directive to get started.

4. Cloud Debugging 
Debugging your application in the cloud is easier than ever with integrated Azure Application Insights and diagnostics when debugging in Visual Studio and after deploying to Azure App Service.

5. Authentication 
- A newly revamped authentication model that makes it easy to configure authentication for your application using DI.

- New templates for configuring authentication for your web apps and web APIs using Azure AD B2C

- New support in ASP.NET Core Identity for providing identity as a service. Updated templates decouple your apps from their identity concerns standard protocols (OpenID Connect, OAuth 2.0). Easily migrate apps using ASP.NET Core Identity for authentication to use Azure AD B2C or any other OpenID Connect compliant identity provider.

- Build secure web APIs using ASP.NET Core Identity. Acquire access tokens for accessing your web APIs using the Microsoft Authentication Library (MSAL)

For a full list of changes see the release notes.

May 14, 2017

Pass By Value and Pass By Reference in C#



This blog post for the beginner, those who have started his career in .Net technologies.

It's a common question in the interview interviewer and many have a misconception and given the wrong answer during the interview.

In .NET Framework, all objects are by default passed by value not passed by reference either it is a Value Type (Primitive types like int, char, double, etc.) or Reference Type (class, interface, delegate, string, etc.).

Let's see the example and clear the doubt.

1. Pass By Value
- Already, mention all objects passed by value default. So if you create any method and pass any parameters. It's a Pass By Value default.

That means, in other words, It will copy value one object to another object. Check the example of a Primitive type.
int x = 5;  
     int y = 5;  
     Cal(x, y);  
     Console.WriteLine(x + y);  
     public void Cal(int x, int y)  
     {  
       x = 10;  
       y = 6;  
       Console.WriteLine(x + y);  
     }  

Here you can see, we have pass parameter x and y into Cal method as Pass By Value.
The default value of x and y variable is 5. When we call Cal method and assign values inside the method to x, y to 10 and 6. After assigning the new value and print the value it will be the sum of x,y = 16.

After calling Cal method then we have another Console.WriteLine that result will be for the sum of x,y = 10 because of when we pass the parameter values to Cal method it will copy the value to x,y to the parameters of x,y.

So when we reassign values to x,y inside the method it will not change the values of outside method variables of x,y.

Check the example of Reference Type.
var user = new User { FirstName = "Kalpesh", LastName = "Satasiya" };  
     ShowUserName(user);  
     Console.WriteLine(user.FirstName +" "+ user.LastName);  
     public void ShowUserName(User user)  
     {  
       user.LastName = "S";  
       Console.WriteLine(user.FirstName +" "+ user.LastName);  
     }  

For the above example, we have to create User class with FirstName and LastName properties.

We want to show username so for that created ShowUserName method and pass user object as a Pass By Value same as the above primitive example.

After creating the object and assign the values FirstName="Kalpesh" and LastName="Satasiya".

Now calling ShowUserName method and passing user object. So user object value copies to ShowUserName method parameter.

Inside the ShowUserName method, we are reassigning the value to LastName="S".

Time to print the user name and it will print the "Kalpesh S" as an output of Console.WriteLine.

Still, we have one more Console,WriteLine statement pending to execute and that output will be the "Kalpesh Satasiya".

So when you pass an object as a parameter. It does not mean to change the value of object inside the method will reflect outside method variables.

It will just copy the object value and assign to parameter object value.

2. Pass By Reference
- Pass By Reference means it will passing the reference of the memory location.

Lets understanding with examples of  Pass By Reference of Primitive type.
 int x = 5;  
     int y = 5;  
     Cal(ref x, ref y);  
     Console.WriteLine(x + y);  
     public void Cal(ref int x, ref int y)  
     {  
       x = 10;  
       y = 6;  
       Console.WriteLine(x + y);  
     }  

In the above example, you can see it. We have used the same example which we have used on Pass By Value with few modifications.

Here we are calling Cal method with x,y parameters and also mention the "ref" keyword with parameters that it means we are passing the reference, not the values.

Once we are calling the Cal method and inside the method, we are doing to change the value of x,y.  It will also reflect the values of outside the Cal method variables of x,y.

Console.WriteLine statement of Cal method will print an output the sum of x,y = 16.

Also, the Same output will be the print of outside the Console.WriteLine statement.

For Pass By Reference of Reference type object.
 var user = new User { FirstName = "Kalpesh", LastName = "Satasiya" };  
     ShowUserName(ref user);  
     Console.WriteLine(user.FirstName +" "+ user.LastName);  
     public void ShowUserName(ref User user)  
     {  
       user.LastName = "S";  
       Console.WriteLine(user.FirstName + " " + user.LastName);  
     }  

The Same example we are going to used which we have used in Pass By Value of Reference type with few modifications.

You can see only modifications are added "ref" keyword into the parameter.

When we calling the ShowUserName at time user object with ref keyword as well also added ref keyword at ShowUserName method implementation with user parameter.

Let's check the output of both the Console.WriteLine statement.

ShowUserName method Console.WriteLine output is "Kalpesh S".
Also, the same out of outside the method Console.WriteLine statement is "Kalpesh S".

Why both out is same? because we are passing the reference object as the parameter into the method so inside the method any changes on user object properties will be reflected on the passing object outside the method.

Hope it will help you to clear the concept of Pass By Value and Pass By Reference in C#.

Apr 29, 2017

Taken session on Microsoft Cognitive Service at Azure BootCamp 2017


It was a great day for me and thanks to Ahmedabad User Group and Microsoft to given me a great opportunity to take the session at Azure BootCamp 2017 event held on 22nd April 2017.

I was part of this event from a couple of years as an audience but this year as a speaker.

From the morning I was very excited to attend the event and take session because it was my first session in front of such kind of audience.

Day started with Keynote which was given by Mahesh Dhola

Then day's first session by Jalpesh Vadgama on Microsoft Bot Framework.


Next session was by Nirav on Logic Apps and Azure Functions.

Before lunch, the last session was by me on Microsoft Cognitive Service
Here is my presentation on Microsoft Cognitive Service


Lunch time, everybody enjoyed the delicious food.
After lunch few more session which was taken by Prabhjot Bakshi, Kaushal Bhavsar, and Mahesh Dhola.
It was a great event and learn from the various sessions.

Hope audience also enjoyed and learn new stuff.


Mar 26, 2017

What's new in C# 7

C# 7 is the latest version of C# language and its available in Visual Studio 2017.
Let us check one by one what's new in C#.

1. Out Variables
You can declare out variable as a parameter to the method where they are used.

In the previous version, you need to separate the declare out variable and initialize into two statement.
int count;
if(int.TryParse(input, out count))
{
    Response.Write(count)
}

Now, You can write out variable as an argument so no need to write a separate statement.
if(int.TryParse(input, out int count))
{
    Response.Write(count)
}

2. Tuples
Tuples are lightweight data structures that contain multiple fields to represent the data members.

Tuples support more than one data element structure.

You can create a tuple by assigning each member to a value:
var letters = ("a", "b");
Tuples are most useful as return types for private and internal methods. Tuples provide a simple syntax for those methods to return multiple discrete values: You save the work of authoring a class or a struct that defines the type returned. There is no need for creating a new type.
private static (int a, int b) Range(int a, int b)
{
    return (a, b);
}
Call above method and set return values to the variables.
(int a, int b) = Range(a,b)

3. Pattern matching
Pattern matching is a feature that allows you to implement method dispatch on properties other than the type of an object.

Let's see is expression and switch expression

- is expression
public static int sumData(IEnumerable<object> values)
{
    var sum = 0;
    foreach(var item in values)
    {
        if (item is int val)
            sum += val;
    }
    return sum;
}
Above example, item check is int val then sum.

- switch statement updates
Switch statement already part old c# language.
public static int SumData(IEnumerable<object> values)
{
    var sum = 0;
    foreach (var item in values)
    {
        switch (item)
        {
            case int val:
                sum += val;
                break;
        }
    }
    return sum;
}
The match expressions have a slightly different syntax than the is expressions, where you declare the type and variable at the beginning of the case expression.

For other features and more detail visit the Microsoft websites.

Mar 11, 2017

Asp.Net Core Unit Test - Code Coverage using OpenCover


Very important thing is for any developer to write good code without any bugs and easy to understandable to other developers.

I'm not going to talk about coding standard and coding style because it's all depend on company standard and developer to developer.

Today, I'm more talk about Asp.Net Core Unit Test case Code Coverage.

I assumed you already know how to write xUnit test case in asp.net core. If you want to know about xUnit test case then please read this blog

For code coverage, I'm using OpenCover and for the report using ReportGenerator tool.

For both the mentions, OpenCover and ReportGenerator added into project.json file under the Test project.
{
  "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-*",
    "InMemoryDatabaseAspNetCore": "1.0.0-*",
    "OpenCover": "4.6.519",
    "ReportGenerator": "2.5.2"
  },

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

Once you added both the package on project.json file. Now time to create one batch file with below code and place at Test project.
@echo off

SET dotnet="C:/Program Files/dotnet/dotnet.exe"  
SET opencover="C:\Users\%USERNAME%\.nuget\packages\OpenCover\4.6.519\tools\OpenCover.Console.exe"
SET reportgenerator="C:\Users\%USERNAME%\.nuget\packages\ReportGenerator\2.5.2\tools\ReportGenerator.exe"

SET targetargs="test"  
SET filter="+[*]InMemoryDatabaseAspNetCore.* -[.Model]* -[InMemory.Test]* -[.Startup]* -[.Test]* -[xunit.*]* -[FluentAssertions]* -[crypto]*"  
SET coveragefile=Coverage.xml  
SET coveragedir=Coverage

REM Run code coverage analysis  
%opencover% -oldStyle -register:user -target:%dotnet% -output:%coveragefile% -targetargs:%targetargs% -filter:%filter% -skipautoprops -hideskipped:All

REM Generate the report  
%reportgenerator% -targetdir:%coveragedir% -reporttypes:Html;Badges -reports:%coveragefile% -verbosity:Error

REM Open the report  
start "report" "%coveragedir%\index.htm" 


On above batch file, you can set all variables as per your system and project path.

Once setup variables then one important point are filters. Filters are that which mentions the which dll are included\excluded for code coverage.
SET filter="+[*]InMemoryDatabaseAspNetCore.* -[.Model]* -[InMemory.Test]* -[.Startup]* -[.Test]* -[xunit.*]* -[FluentAssertions]* -[crypto]*"  

After all the set, you are ready to run the batch file and it will show the result into the browser and it look like below. Green and red color based on your code coverage.


Hope you like it!!

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