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 →

Tuesday, 21 November 2017

HTTP Requests with Observables- Angular 2

Making HTTP requests is a vital operation in the life of most front-end applications. Angular 2, which is the hottest thing right now has a really cool way of doing that. Actually that is what we are going to cover together today in this tutorial. We will learn how how to make HTTP requests using RxJs Observable library.

What are Observables?
Observables are similar to promises but with major differences that make them better. The key differences are:

ObservablesPromise
Observables handle multiple values over timePromises are only called once and
will return a single value
Observables are cancellablePromises are not cancellable
The ability of observables being able to handle multiple values over time makes them a good candidate for working with real-time data, events and any sort of stream you can think of.

Being able to cancel observables gives better control when working with in-flow of values from a stream. The common example is the auto-complete widget which sends a request for every key-stroke.

If you are searching for angular in an auto-complete, the first request is with a and then an. The scary thing is that an might come back with a response before a which produces a messy data. With observables, you have better control to hook in and cancel a's because an is coming through.

Observables is an ES7 feature which means you need to make use of an external library to use it today. RxJS is a good one. RxJS also provides Observable operators which you can use to manipulate the data being emitted. Some of these operators are:
Map
Filter
Take
Skip
Debounce
Above is a list of popular operators you will encounter in most projects but those are not all.
Meet the Angular 2 HTTP Service

The service class has the following structure:
Product.service.cs

import { Product } from '../../models/product';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import { environment as env } from '../../../environments/environment';
import { AuthService } from '../../services/auth.service';

@Injectable()
export class ProductService {
  private baseUrl = '';
  private headers: any;
  private options;

  constructor(private http: Http, private authService: AuthService) {
    // this.headers = new Headers({ 'Content-Type': 'application/json' });
    this.options = new RequestOptions({ headers: new Headers({ 'authorization': this.authService.user.token,
     'Content-Type': 'application/json' }) });
    this.baseUrl = env.apiAddress;
  }

  getAll(): Observable<Product[]> {
    return this.http.get(`${this.baseUrl}/product`, this.options)
     .map((res: Response) => res.json())
     .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  get(id: string): Observable<Product> {
    return this.http
      .get(`${this.baseUrl}/product/${id}`, this.options)
      .map((res: Response) => {
        return res.json();
      })
      .catch((error: any) => Observable.throw('Server error'));
  }

  add(product: Product): Observable<Response> {

    return this.http
      .post(`${this.baseUrl}/product`, JSON.stringify(product), this.options)
      .catch((error: any) => Observable.throw('Server error'));
  }

  update(product: Product): Observable<Response> {
    return this.http
 .put(`${this.baseUrl}/product/${product._id}`, JSON.stringify(product), { headers: this.headers })
      .catch((error: any) => Observable.throw('Server error'));
  }

  delete(id: string): Observable<Response> {
    return this.http
      .delete(`${this.baseUrl}/product/${id}`)
      .map((res: Response) => {
        return res;
      })
      .catch((error: any) => Observable.throw('Server error'));
  }
}

We have imported the required libraries for our service to behave as expected. Notice that the observable we spoke about has also been imported and used. The map and catch observable operators which will help us to manipulate data and handle errors respectively has also been imported. Then we inject HTTP in the constructor and keep a reference to the base url of our API.

With the map operator, we call the .json method on the response because the actual response is not a collection of data but a JSON string.

NOTE: Angular 4.3 uses JSON response by default. Therefore, you can get rid of that line if you are using the latest version of Angular.


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.
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 routes: Routes = [
{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 userService: UserService) {}; 

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',
component: ArtistComponent,
canActivate: [OnlyLoggedInUsersGuard, AlwaysAuthGuard], 
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 {CanActivateChild} from "@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',
component: ArtistComponent,
canActivate: [OnlyLoggedInUsersGuard, AlwaysAuthGuard],
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 →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)