Saturday 30 December 2017

SingleOrDefault Vs FirstOrDefault

 SingleOrDefault() Vs. FirstOrDefault() in LINQ Query


Single() / SingleOrDefault()
First () / FirstOrDefault()
Single() - There is exactly 1 result, an exception is thrown if no result is returned or more than one result. 
SingleOrDefault() – Same as Single(), but it can handle the null value.
First() - There is at least one result, an exception is thrown if no result is returned.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
Single() asserts that one and only one element exists in the sequence.
First() simply gives you the first one.
When to use
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
When to use
Developer may use First () / FirstOrDefault() anywhere,  when they required single value from collection or database.
Single() or SingleOrDefault() will generate a regular TSQL like "SELECT ...".
The First() or FirstOrDefault() method will generate the TSQL statment like "SELECT TOP 1..."
In the case of Fist / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.
Continue Reading →

Wednesday 27 December 2017

Web API Filters

Web API includes filters to add extra logic before or after action method executes. Filters can be used to provide cross-cutting features such as logging, exception handling, performance measurement, authentication and authorization.

Filters are actually attributes that can be applied on the Web API controller or one or more action methods. Every filter attribute class must implement IFilter interface included in System.Web.Http.Filters namespace. However, System.Web.Http.Filters includes other interfaces and classes that can be used to create filter for specific purpose.

The following table lists important interfaces and classes that can be used to create Web API filters.

Filter TypeInterfaceClassDescription
Simple FilterIFilter-Defines the methods that are used in a filter
Action FilterIActionFilterActionFilterAttributeUsed to add extra logic before or after action methods execute.
Authentication FilterIAuthenticationFilter-Used to force users or clients to be authenticated before action methods execute.
Authorization FilterIAuthorizationFilterAuthorizationFilterAttributeUsed to restrict access to action methods to specific users or groups.
Exception FilterIExceptionFilterExceptionFilterAttributeUsed to handle all unhandled exception in Web API.
Override FilterIOverrideFilter-Used to customize the behaviour of other filter for individual action method.
As you can see, the above table includes class as well as interface for some of the filter types. Interfaces include methods that must be implemented in your custom attribute class whereas filter class has already implemented necessary interfaces and provides virtual methods, so that they can be overridden to add extra logic. For example, ActionFilterAttribute class includes methods that can be overridden. We just need to override methods which we are interested in, whereas if you use IActionFilter attribute than you must implement all the methods.

Visit MSDN to know all the classes and interfaces available in System.Web.Http.Filters.

Let's create simple LogAttribute class for logging purpose to demonstrate action filter.

First, create a LogAttribute class derived from ActionFilterAttribute class as shown below.

Example: Web API Filter Class

public class LogAttribute : ActionFilterAttribute 
 {
    public LogAttribute()
    {

    }
       

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionExecutedContext.ActionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");
    }
}

In the above example, LogAttribute is derived from ActionFilterAttribute class and overrided OnActionExecuting and OnActionExecuted methods to log in the trace listeners. (You can use your own logging class to log in textfile or other medium.)

Another way of creating LogAttribute class is by implementing IActionFilter interface and deriving Attribute class as shown below.

Example: Web API Filter Class

public class LogAttribute : Attribute, IActionFilter
{
    public LogAttribute()
    {

    }
    public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
    {
        Trace.WriteLine(string.Format("Action Method {0} executing at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        var result = continuation();

        result.Wait();
            
        Trace.WriteLine(string.Format("Action Method {0} executed at {1}", actionContext.ActionDescriptor.ActionName, DateTime.Now.ToShortDateString()), "Web API Logs");

        return result;
    }

    public bool AllowMultiple
    {
        get { return true; }
    }
} 

In the above example, deriving from Attribute class makes it an attribute and implementing IActionFilter makes LogAttribute class as action filter. So now, you can apply [Log] attributes on controllers or action methods as shown below.

Example: Apply Web API Filter on Controller

[Log]
public class StudentController : ApiController
{
    public StudentController()
    {
            
    }

    public Student Get()
    {
        //provide implementation  
    }
}

So now, it will log all the requests handled by above StudentController. Thus you can create filters for cross-cutting concerns.

Continue Reading →

Wednesday 29 November 2017

Enterprise Library DAAB - C# .Net

Enterprise Library Data Access Application Block In C# .NET
What is a Data Access Application Block (DAAB)?  A Data Access Application Block encapsulates the performance and resource management best practices for accessing Microsoft SQL Server databases. It can easily be used as a building block in your own .NET-based application. If you use it then you will reduce the amount of custom code you need to create, test, and maintain. It comes with a single assembly with a class that has many useful methods. It reduces the amount of custom code.
A Data Access Application Block provides the following benefits:
  • It uses the functionality provided by ADO.NET 2.0 and with it, you can use ADO.NET functionality along with the application block's functionality.
  • It reduces the need to write boilerplate code to perform standard tasks.
  • It helps maintain consistent data access practices, both within an application and across the enterprise.
  • It reduces difficulties in changing the database type.
  • It relieves developers from learning different programming models for different types of databases.
  • It reduces the amount of code that developers must write when they port applications to different types of databases. Read more in http://msdn.microsoft.com/en-us/library/cc309168.aspx.
Install Enterprise Library
Please follow this link to download the Enterprise Library:
Create a new MVC web application.
Make the below changes in your web.config file.
Add a DAL Folder in your project. Add a Baseclass and add the below code in the baseclass.
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MVC_ADO.DAL
{
    public class BaseClass
    { 
        public virtual Database GetDatabase()
        {
            Database db;
            db = DatabaseFactory.CreateDatabase("MasterDB");
            return db;
        }      
    }
}
Add a EmployeeModel class and add the below code

using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace MVC_ADO.DAL
{
    public class EmployeeModel : BaseClass
    {
        Database db = null;
        public override Database GetDatabase()
        {
            return base.GetDatabase();
        }

        public DataSet GetEmployee()
        {
            try
            {
                db = GetDatabase();
                DataSet ds = new DataSet();
                DbCommand dbCommand = db.GetStoredProcCommand("PROC_GET_EMPLIST");
                // db.AddInParameter(dbCommand, "@IP_UserID", DbType.Int32, UserID);
                //db.AddOutParameter(dbCommand, "@OP_strException", DbType.String, 200);

                ds = db.ExecuteDataSet(dbCommand);
                return ds;
            }
            catch
            {
                throw;
                // ds = null;
                //strException = ex.Message.ToString();
            }
        }
    }
}
Note: Create the PROC_GET_EMPLIST Stored Procedure in SQL Server.

Now Call the GetEmployee Function from your Controller.


using System.Web.Mvc;
using MVC_ADO.DAL;

namespace MVC_ADO.Controllers
{
    public class HomeController : Controller
    {
        EmployeeModel model = new EmployeeModel();
        public ActionResult Index()
        {
            var list = model.GetEmployee();
            return View();
        }
    }
}
You will get the list of all employees from Employee table.
Continue Reading →

Thursday 16 November 2017

Router Guards- Angular 2

Protecting routes is a very common task when building applications, as we want to prevent our users from accessing areas that they’re not allowed to access, or, we might want to ask them for confirmation when leaving a certain area. Angular’s router provides a feature called Navigation Guards that try to solve exactly that problem. In this article, we’d like to take a look at the different types of guards and how to implement them for actual use cases.

Guard Types
There are different guard types we can use to protect our routes:

CanActivate: Checks to see if a user can visit a route.
CanActivateChild: Checks to see if a user can visit a routes children.
CanDeactivate: Checks to see if a user can exit a route.
Resolve: Performs route data retrieval before route activation. https://angular.io/
CanLoad: Checks to see if a user can route to a module that lazy loaded.

For a given route we can implement zero or any number of Guards.
We’ll go through the first three as the last two are very advanced use cases and need lazy loading modules which we we haven’t covered.

CanActivate
Guards are implemented as services that need to be provided so we typically create them as @Injectable classes.
Guards return either true if the user can access a route or false if they can’t.

Lets create a simple CanActivate guard.
First we need to import the CanActivate interface, like so:

import {CanActivate} from "@angular/router";

Then lets create an Injectable class called AlwaysAuthGuard which implements the canActivate function, like so:
class AlwaysAuthGuard implements CanActivate {
    canActivate() {
    console.log("AlwaysAuthGuard");
    return true;
    }
    }
This guard returns true all the time, so doesn’t really guard anything. It lets all users through but at the same time our guard logs "AlwaysAuthGuard" to the console so we can at least see when it’s being used.
We need to provide this guard, for this example lets configure it via our NgModule, like so:
@NgModule({
    .
    .
    providers: [
    .
    .
    AlwaysAuthGuard
    ]
    })

Finally we need to add this guard to one or more of our routes, lets add it to our ArtistComponent route like so:
const routesRoutes = [
    {path: ''redirectTo: 'home'pathMatch: 'full'},
    {path: 'find'redirectTo: 'search'},
    {path: 'home'component: HomeComponent},
    {path: 'search'component: SearchComponent},
    {
    path: 'artist/:artistId',
    component: ArtistComponent,
    canActivate: [AlwaysAuthGuard], 
    children: [
    {path: ''redirectTo: 'tracks'},
    {path: 'tracks'component: ArtistTrackListComponent},
    {path: 'albums'component: ArtistAlbumListComponent},
    ]
    },
    {path: '**'component: HomeComponent}
    ];

We added our AlwaysAuthGuard to the list of canActivate guards for this route.

Note: Since it holds an array we could have multiple guards for a single route.
Note: If this was a canActivateChild guard we would be adding it to the canActivateChild property and so on for the other guard types.

Now every-time we navigate to the ArtistComponent route we get "AlwaysAuthGuard" printed to the console so we know that the AlwaysAuthGuard is working.

OnlyLoggedInUsersGuard

The most typical use case for the CanActivate guard is some form of checking to see if the user has permissions to view a page.
Normally in an Angular application we would have a service which held whether or not the current user is logged in or what permissions they have.

Lets create another guard called OnlyLoggedInUsersGuard which only allows logged in users to view a route.
@Injectable()
class OnlyLoggedInUsersGuard implements CanActivate { 
constructor(private userServiceUserService) {}; 

canActivate() {
console.log("OnlyLoggedInUsers");
if (this.userService.isLoggedIn()) { 
return true;
else {
window.alert("You don't have permission to view this page"); 
return false;
}
}
}

We created a new CanActivate guard called OnlyLoggedInUsersGuard
We inject and store UserService into the constructor for our class.
If the user is logged in the guard passes and lets the user through.
If the user is not logged in the guard fails, we show the user an alert and the page doesn’t navigate to the new URL.
Finally we need to add this guard to the list of guards for our search route, like so:
{
    path'artist/:artistId',
    componentArtistComponent,
    canActivate: [OnlyLoggedInUsersGuardAlwaysAuthGuard], 
    children: [
    {path: ''redirectTo: 'tracks'},
    {path: 'tracks'component: ArtistTrackListComponent},
    {path: 'albums'component: ArtistAlbumListComponent},
    ]
    }

We add OnlyLoggedInUsersGuard to the list of guards for our route.

Now when we try to navigate to the search view we are blocked from doing so and shown a window alert.

If we want to redirect users to a login page we may inject Router into the constructor and then use the navigate function to redirect them to the appropriate login page.

Note: So the rest of the samples in this chapter work we will change the isLoggedIn function on our UserService to return true instead.

CanActivateChild
As well as CanActivate we also have CanActivateChild which we implement in similar way.
Lets do the same as the CanActivate example and create a guard called AlwaysAuthChildrenGuard.
import {CanActivateChildfrom "@angular/router";

class AlwaysAuthChildrenGuard implements CanActivateChild {
canActivateChild() {
console.log("AlwaysAuthChildrenGuard");
return true;
}
}

Note: Remember to provide it on our NgModule

We add the guard to the canActivateChild child property on our ArtistComponent route
{
    path'artist/:artistId',
    componentArtistComponent,
    canActivate: [OnlyLoggedInUsersGuardAlwaysAuthGuard],
    canActivateChild: [AlwaysAuthChildrenGuard],
    children: [
    {path: ''redirectTo: 'tracks'},
    {path: 'tracks'component: ArtistTrackListComponent},
    {path: 'albums'component: ArtistAlbumListComponent},
    ]
    }

Now every-time we try to activate either the ArtistTrackListComponent or ArtistAlbumListComponent child routes it checks the AlwaysAuthChildrenGuard to see if the user has permission.

CanDeactivate:
Guard ask permission to discard unsaved changes.





Continue Reading →

Saturday 23 September 2017

MongoDB - Installation and Setup

Here you will get to know about Installation and setup of MongoDB for your NodeJS Application.
you need to just follow the below steps.

1- First of all you need to install MongoDB in your System.
    Url : https://www.mongodb.com/download-center#community


2- Now Install the Mongochef (A GUI for MongoDB)

3- Create a folder in C:/ named "data" and inside data folder create a "db" folder. (MongoDb default data directory)

4- Set user envoirenment variable for mongodb server bin path “C:\Program Files\MongoDB\Server\3.4\bin” 



5- You can also run mongodb as a windows service by setting following path
     mongod --dbpath="C:\data\db" --logpath="C:\data\db\log.txt" --install

open the cmd with administration mode. change the directory to mongodb server bin. and run the above command.


6- The above command will create the window service. now open the service.msc and start the service.


7- Now mongodb is ready to use. open the mongo.exe from “C:\Program Files\MongoDB\Server\3.4\bin”


8- Now you can run mongo commands. see the below screenshot.


9-  Open the Studio3T(Mongochef) to run mongodb from GUI.


10- Click on Connect button. Create a new connection and click on Save button.


11- Click the connect button. your Mongodb is ready to use in the GUI.

Thanks





Continue Reading →

Friday 22 September 2017

Routing - Angular

What are the main routing Component?
Angular provides 3 different components for routing configuration:

Routes is the configuration to describe application’s different routes
RouterOutlet is a “placeholder” component that holds the view for each route
RouterLink is a directive to link to routes

Routes:
Routes is an object to describe the routes of the application.

const routesRoutes  = [
    { path: ''redirectTo: 'login'pathMatch:'full' },
    { path: 'login'component: LoginComponent },
    { path: 'home'component: HomeComponent ,
     children: [
      { path: ''component: DashBoardComponent },
      {path: 'events'component: EventsComponent}
     ]},
    { path: 'register'component: RegisterComponent },
    { path: 'about'component: AboutComponent },
    { path: '**'component: p404Component },
   ];

We have configure routes which is an array of Route. Each entry of the array is The complete list of possible fields used in this configuration are as following:
  • path – url of the route used by the matcher DSL.
  • component –name of the target component.
  • pathMatch – specifies the matching strategy, example : full.
  • redirectTo -url that will replace the current matched segment in case of redirection.
  • outlet – name of the outlet used as a placeholder for the component. If there is no outlet it would be placed in <router-outlet>
  • canActivate – array of DI tokens used to find CanActivate handlers.
  • canActivateChild – array of DI tokens used to find CanActivateChild handlers.
  • canDeactivate – array of DI tokens used to find CanDeactivate handlers.
  • children-  is an array used to define nested routes.
Router Directives
Angular RouterModule has 3 different directives. Such as:
  1. router-outlet
  2. router-link
  3. routerLinkActive
router-outlet:
router-outlet is a component from angular/router library. The router is the placeholder to display views inside  <router-outlet> tags. As the routes changes, the view inside the <router-outlet> tags also change accordingly.

<div class="container">
<router-outlet></router-outlet>
</div>

router-link:
router-link directive is an alternative of HTML href property. The syntax is as following:
<div class="navbar navbar-default">
<a class="navbar-brand" [routerLink]="['/']">Angular App</a>
<ul class="nav navbar-nav">
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/about','2']">About Us</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/inheritance']">Inheritance</a>
</li>
</ul>
</div>
If we want to pass the queryParams in an object , we can also do that as following:
<a [routerLink]="['/about', {id:'2'}]">About Us</a>
Or
<a [routerLink]="['/about','2']">About Us</a>
routerLinkActive:
The RouterLinkActive directive toggles css classes for active RouterLinks based on the current RouterState. This cascades down through each level in our route tree, so parent and child router links can be active at the same time. To override this behavior, we can bind to the [routerLinkActiveOptions] input binding with the { exact: true } expression. By using { exact: true }, a given RouterLink will only be active if its URL is an exact match to the current URL.
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>

How to  handle Routing in Angular2?

There are following steps to complete achieve this Goal, such as

  • Create App Router Module
     a. Configuration different Paths
  • Import RouterModule to AppModule
  • Create Router-Outlet view and associated component
  • setup router-link directive
Defining Routes
Let’s create a file called app.routes.ts in the root of the app folder. This file will describe the configuration for routers for the application. 
import { NgModule } from '@angular/core';
import { RoutesRouterModule } from '@angular/router';
import { DatabindingComponent } from './databinding/databinding.component';
import { AboutComponent } from './about/about.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { ChildComponent } from './inheritance/child.component';

const routesRoutes = [
path: ''component: DatabindingComponent },
path: 'about/:id'component: AboutComponent },
path: 'inheritance'component: ChildComponent },
path: '**'redirectTo: 'notfound'pathMatch:'full' }
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }

Then the last route we will add is a wildcard route. This will match any routes that we have defined. This is also why we added the redirect. If we didn’t, our app would start at this route since we start from a route that is not defined, an empty route.

After adding the redirect, any route that we type that doesn’t exist will get our error page.

Here the routes has been passed as the argument to RouterModule.forRoot() so that the RouterModule in our imports is able to use the RouterOutlet and RouterLink components in this module. Create Router-Outlet view and associated component

For this example, we have placed a placeholder on app.component.html as following:

<div class="container">
<router-outlet></router-outlet>
</div>

The Main AppComponent

import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}

Setup router-link directive

Now we have to write the router-link to place the actual link on html. Therefore, we change the app.component.html and add the router link as following:

<div class="navbar navbar-default">
<a class="navbar-brand" [routerLink]="['/']">Angular App</a>
<ul class="nav navbar-nav">
<li routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Data Binding</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/about','2']">About Us</a>
</li>
<li routerLinkActive="active">
<a [routerLink]="['/inheritance']">Inheritance</a>
</li>
</ul>
</div>
<div class="container">
<router-outlet></router-outlet>
</div>

RouterModule.forRoot versus RouterModule.forChild
There are two methods we can invoke using RouterModule in order to register routes.

In case we declare the top-level routes of our application, we need to use RouterModule.forRoot. This method will register the top-level routes and return the routing module that should be imported by the root module of the application.

If we want to define routes in a lazy-loaded module and import the module returned by the invocation of the forRoot method, we'll get a runtime error. This is because the forRoot method will return a module with providers, which should be imported only once, by the top-level module. In order to register nested routes in a lazy-loaded module, we will need to use the forChild ...

Some Points to know: 
  • The routerLink directive tells the router where to navigate when the user clicks the link.
  • The routerLinkActive directive is used to add the active bootstrap class to the HTML navigation element whose route matches the active route.
  • The router-outlet directive is used to specify the location where we want the routed component's view template to be displayed.
  • The routerLink, routerLinkActive and router-outlet directives are provided by the RouterModule which we have imported in our application root module.
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives