Monday 26 March 2018

Angular Forms

Angular provides two different approaches to handling user input through forms: reactive and template-driven. Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.

Template driven: With the template driven approach you basically apply directives, such as ngModel, in your template. Based on these directives Angular will create formcontrol objects. This approach is good for building simple forms with basic validation (required, minlength, maxlength,...).

Reactive forms: With the reactive approach you basically need to create new instances of the formcontrols and formcontrolgroups in your component. Reactive forms are the best choice for building complex forms and are better in case you have the intention to implement unit testing for your formsClick here for example

Choosing an approach
Reactive forms and template-driven forms process and manage form data differently. Each approach offers different advantages.

Reactive forms provide direct, explicit access to the underlying forms object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms.

High-level Differences between Template-driven and Reactive Forms
Below are some of the high-level differences between the two types:
  • Template-driven forms make use of the "FormsModule", while reactive forms are based on "ReactiveFormsModule".
  • Template-driven forms are asynchronous in nature, whereas Reactive forms are mostly synchronous.
  • In a template-driven approach, most of the logic is driven from the template, whereas in reactive-driven approach, the logic resides mainly in the component or typescript code. 
Template-driven forms rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're easy to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit.

Reactive form can be used in the following situation
  • Complex forms with more number of fields.
  • Multiple complex validation are there. Custom validations are required
  • Require JSON structure to be send with the values in the form.
  • We can get entire form in a structured way by using "form.value"
If we have 4 fields First Name, Last Name, Email, Phone Number in reactive form.

HTML code will be

<form [formGroup]="form">
    First Name <input formControlName="firstName">
    Last Name <input formControlName="lastName">
    Email <input formControlName="email">
    Phone Number <input formControlName="phoneNumber">
</form>

We can get the values from the form like below
{
"firstName": "FName",
"lastName": "LName",
"email": "test@123.com",
"phoneNumber": "123"
}
by calling form.value, where form is FormGroup Variable that we created.

Template Driven Form : It can be used when using simple forms. Like login page. With the two way data binding. We can simply assign value to variable from ui and vice versa.

Simple example is if we are givng two way binding for the below input.
<input [(ngModel)]="username">

We can simply display the value that user is giving in the UI.
<p>Hello {{username}}!</p>

You can build forms by writing templates in the Angular template syntax with the form-specific directives and techniques described in this page.

You'll learn to build a template-driven form that looks like this:

1- Create a new project named EmployeeForm:
ng new EmployeeForm

2- Chnage the directory
cd EmployeeForm

3- Install the angular forms module in your project 
npm install Forms

4- Add the Employee Model class
ng generate class EmployeeModel

It will generate a employee-model.ts file insrc/app directory.

5- Add members in the class file.

export class EmployeeModel {
public employeename: string ;
public Email: string;
public Username:string;
public Password: string;
}


6- Add a new Component named empcomponent

ng generate component empcomponent

It will generate required files for component in app directory. see the below screenshot.


7- Add the Form Module and newly created component in AppModule class.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { EmpComponentComponent } from './emp-component/emp-component.component';

@NgModule({
  declarations: [
    AppComponent,
    EmpComponentComponent
  ],
  imports: [
    BrowserModule, FormsModule
  ],
  providers: [],
  bootstrap: [EmpComponentComponent]
})
export class AppModule { }

8- Add the below html in emp-component.component.html file.

<div class = "container">
   <h1>Employee Form</h1>
   <form #form="ngForm" class="form-horizontal" (ngSubmit)="SaveData(form)">

  <div class="form-group">
    <label class="col-sm-2 control-label">Name</label>
    <div class="col-sm-10">
      <input type="text" name="employeename" class="form-control" #employeename="ngModel" [(ngModel)]="model.employeename" required />
      <div *ngIf="employeename.errors && (form.submitted || employeename.dirty)" class="text-danger">
        <span [hidden]="!employeename.errors.required">Please Enter Name</span>
      </div>
    </div>
  </div>
<div class="form-group">
    <label class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="text" name="Email" class="form-control" #Email="ngModel" [(ngModel)]="model.Email" required pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"/>
      <div *ngIf="Email.errors && (form.submitted || Email.dirty)" class="text-danger">
        <span [hidden]="!Email.errors.required">Please Enter Email</span>
        <span [hidden]="!Email.errors.pattern">Please Enter Correct Email</span>
      </div>
    </div>
  </div>
    <div class="form-group">
    <label class="col-sm-2 control-label">Username</label>
    <div class="col-sm-10">
      <input type="text" name="Username" class="form-control" #Username="ngModel" [(ngModel)]="model.Username" required minlength="3"/>
      <div *ngIf="Username.errors && (form.submitted || Username.dirty)" class="text-danger">
        <span [hidden]="!Username.errors.required">Please Enter Username</span>
        <span [hidden]="!Username.errors.minlength">Username must have atleast 3 chars</span>
      </div>
    </div>
  </div>
  <div class="form-group">
    <label class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" name="Password" class="form-control" #Password="ngModel" [(ngModel)]="model.Password" required />
      <div *ngIf="Password.errors && (form.submitted || Password.dirty)" class="text-danger">
        <span [hidden]="!Password.errors.required">Please Enter Password</span>
      </div>
    </div>
  </div>

 <div class="form-group">
    <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" class="btn btn-primary">Register</button>
    </div>
  </div>
   </form>
</div>

9- Add the below required code in emp-component.component.ts file

import { Component, OnInit } from '@angular/core';
import { EmployeeModel } from '../employee-model';
import { NgForm } from "@angular/forms";

@Component({
  selector: 'app-emp-component',
  templateUrl: './emp-component.component.html',
  styleUrls: []
})
export class EmpComponentComponent implements OnInit {

  model: EmployeeModel;
  constructor() { 
     this.model = new EmployeeModel();
  }
  SaveData(form: NgForm) {
    if (form.valid) {
      console.log(this.model);
      alert('valid!');
    }
  }
  ngOnInit() {
  }
}

10- Now replace the app-root component with emp-component in index.html file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>EmployeeForm</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <!-- <app-root></app-root> -->
  <app-emp-component></app-emp-component>
</body>
</html>

11- Now all the task has been done. now run the application.

ng serve
12- You can see the validation error in the above form. with the correct data form will be submitted.

13- Fill the correct data and click on Register button. It will display the message from server side.

All Done!


Continue Reading →

Thursday 22 March 2018

Breeze.js- Basics

Breeze.js is a client side JavaScript library that manages rich data. It is used for data management on client side using javascript.
If you store data in a database, query and save those data as complex object graphs, and share these graphs across multiple screens of your JavaScript client, Breeze is for you.
A Breeze client can communicate to almost any server technology including Node.js running Express with a MongoDB database. See Breeze-MongoDB integration in action
Client side Requirements:

Standard Breeze requirements:
  1. Breeze.debug.js or Breeze.min.js
  2. Q.js
  3. Ajax library - usually jQuery
Additional MongoDB requirement:
  1. Breeze.dataservice.mongo.js - a Breeze dataservice adapter that handles all of the MongoDB -specific client-side work involved in communicating with the MongoDB–backed service. 
Server side requirements

1- breeze-mongodb from npm - a node package that handles all of the server-side details of communicating between a Breeze client and a MongoDB-backed service.

npm install breeze-mongodb

Basics
You will write Breeze specific code in your Node server application to handle the following types of operations.
  • Querying
  • Saving
Breeze/MongoDB - Server side processing
The examples assume you’ll launch in node a JavaScript file containing standard node/express boilerplate that looks something like this:

server.js
var express = require('express');
var app = express();
var routes = require('./routes');  //  refs a routes.js file where most of our code will be written.
app.use(express.bodyParser());
app.use(app.router);
app.use(errorHandler);
Almost all of the Breeze/MongoDB code shown in these examples is assumed to be part of a “routes.js” file. Below is the beginning of such a file that opens a MongoDB database called “MyNorthwindDatabase”.

Assume a MongoDB server is running with access to this database.

routes.js
var mongodb = require('mongodb');             // MongoDB support package   
var breezeMongo = require('breeze-mongodb');  // Breeze MongoDB support package
var fs = require('fs');                       // Access to the local file system.

// Connect to a database.
var host = 'localhost';
var port = 27017;
var dbName = 'MyNorthwindDatabase';
var dbServer = new mongodb.Server(host, port, { auto_reconnect: true});
var db = new mongodb.Db(dbName, dbServer, { strict:true, w: 1});
db.open(function () { });

// route definitions begin here …

Querying with MongoDB
Let’s start on the breeze client which makes a query request to the server. Then we’ll see how routes.js redirects that request to the proper method for query processing.

Client side
Tell Breeze that you’re using MongoDB and everything else is standard Breeze. Put the following line somewhere in your application bootstrapping logic:

breeze.config.initializeAdapterInstance("dataService", "mongo", true);
Querying a MongoDB database from a Breeze client involves nothing more than a standard Breeze EntityQuery such as this one:

var query = EntityQuery.from("Products").where("ProductName", "startsWith", "C"); 
The real point here is that, in general, you cannot tell by looking at the client side code what backend datastore is behind any Breeze query.

Server side
In order to provide the most basic support for Breeze the minimum necessary requirement is simply that you give Breeze an endpoint and then route Breeze to this endpoint.

The routing could look something like this:
app.get('/breeze/Northwind/Products', routes.getProducts);

Thus a Breeze EntityQuery with “Products” in the EntityQuery.from clause is directed to the getProducts method in the routes.js file.

getProducts illustrates the typical implementation of a query processing method:
exports.getProducts = function(req, res, next) {
    // convert a client OData-style query string in the request to a MongoDB query
    var query = new breezeMongo.MongoQuery(req.query);

    // add custom server-side filtering to the query object here...
       query.filter["isDiscontinued"] = false;
     

    // execute the MongoDB query with a callback
    query.execute(db, "Products", processResults(res, next));
}  

// Return the query callback function
// res is the HTTP response object
// next is the Express HTTP pipeline callback
function processResults(res, next) {
    // return a function to process the results of the query
    // here we simply compose a response with the query results as content
    return function(err, results) {
        if (err) {
            next(err);
        } else {
            res.setHeader("Content-Type:", "application/json");
            res.send(results);
        }
    }
}
This is the standard template for most queries. The processResults method can be reused by all of the query methods discussed in this document.

Inside the query method
getProducts composes a query object by parsing the OData-style parameters that the Breeze client has passed in the URL query string and turning them into an equivalent MongoDB query expression. These implementation details are handled automatically by the Breeze MongoQuery class that you imported when you called “require(‘breeze-mongodb’)”.

The Breeze MongoQuery.execute receives three parameters: the database object (db), the name of a MongoDB collection in “MyNorthwindDatabase”, and a callback to process the results returned by MongoDB.

You can further constrain or augment the client query by modifying the Breeze query object before executing it. Continuing with our Products query, we may wish to ensure that no ‘discontinued’ products are ever returned. We’d specify that constraint with the query.filter property.

Saving with MongoDB
We’ll start on the client and return quickly to the server.

Client side
Saving to a MongoDB database from a Breeze client involves nothing more than a standard Breeze EntityManager.saveChanges call such as this one:

return myEntityManager.saveChanges().then(...);
Again, as with queries, in general, you cannot tell by looking at the client side code what backend datastore is behind any Breeze saveChanges call.

Server side
As with queries, in order to support Breeze’s client side EntityManager.saveChanges call, you will need to provide an endpoint and a route to this endpoint. Something like this:

app.post('/breeze/Northwind/SaveChanges', routes.saveChanges);
Here is a simple implementation for routes.saveChanges.

exports.saveChanges = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    saveHandler.save();
};

Validation through save interception
You authorize and validate client save-data with save “interceptors”. You can even modify the save data with interceptors.

Breeze offers two interceptor methods: MongoSaveHandler.beforeSaveEntity and MongoSaveHandler.beforeSaveEntities.

These are methods that you write and breeze calls just before saving the data to the MongoDB database.

exports.saveChanges = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    // write one or both of the following
    // saveHandler.beforeSaveEntity = myCustomBeforeSaveEntity;
    // saveHandler.beforeSaveEntities = myCustomBeforeSaveEntities;
    saveHandler.save();
};

You can define one or both of these methods. Breeze first calls beforeSaveEntity for every entity in the save-set and then calls beforeSaveEntities.

Each method has a distinct purpose:
  • beforeSaveEntity - review and possibly modify or reject each entity individually.
  • beforeSaveEntities - review and possibly modify the entire collection of entities to be saved (the “save-set”). You can modify or remove any of them. You can add more entities-to-save, potentially of types not included in the original save-set.
beforeSaveEntity
Breeze doesn’t define this method; you do. Breeze calls your custom implementation of the beforeSaveEntity interceptor once for each entity in the save-set.

Save Example #1:

Ensure that every new Product we add to the database has at least a $.50 surcharge.
function myCustomBeforeSaveEntity(entity) {
    var entityAspect = entity.entityAspect;
    if (entityAspect.entityTypeName === "Product" && entityAspect.entityState === "Added") {
        if (entity.surcharge < .5) entity.surcharge = .5;
    }
    return true;
}
Save Example #2:

Prevent new products from being added to “revoked suppliers” by removing such products from the save-set.
function myCustomBeforeSaveEntity(entity) {
    var entityAspect = entity.entityAspect;
    if (entityAspect.entityTypeName === "Product" && entityAspect.entityState === "Added") {
        if (revokedSupplierNames.indexOf(entity.supplierName) >= 0) return false;
    }
    return true;
}
If the method returns false, breeze will not save this entity. Breeze will continue to evaluate the remaining entities and may save them.

You can throw an exception if you want to terminate the save immediately.

beforeSaveEntities
Your beforeSaveEntities method is granted access to the entire save-set through several public properties on the MongoSaveHandler instance. The MongoSaveHandler instance is the this object within your beforeSaveEntities function.

Save Example #3:

Add 5% to the freight cost on every order saved.
function myCustomBeforeSaveEntities(callback) {
    var orderTypeName = this.qualifyTypeName("Order");
    var orders = this.saveMap[orderTypeName] || [];
    
    orders.forEach(function(order) {
       order.freightCost = order.freightCost * 1.05;    
    });
    callback();
}



Continue Reading →

Wednesday 21 March 2018

Gulp Usage

What is gulp.js and why use it?

There’s no point in investing your time into learning a new tool if you don’t even know what problem it solves. Gulp solves the problem of repetition. Many of the tasks that web developers find themselves doing over and over on a daily basis can be simplified by becoming automated. Automating repetitive tasks = more time to do non repetitive tasks = more productivity.


Gulp is a javascript task runner that lets you automate tasks such as…
  1. Bundling and minifying libraries and stylesheets.
  2. Refreshing your browser when you save a file.
  3. Quickly running unit tests
  4. Running code analysis
  5. Less/Sass to CSS compilation
  6. Copying modified files to an output directory

The gulp workflow
Below is a common workflow for performing certain build operations.
  • We start by defining a task that we would like to accomplish.
  • Within that task, a desired set of files are loaded into the gulp stream to be processed. (Optional) Once files are in the stream, one or more modifications can be made to the files. Because the streams are processed in memory, no file - system writes to temporary directories between modifications are required.
  • Send the new (possibly modified) files to a specified destination

So first, the original files go in, we optionally process modifications to the input files, then we copy the result of our stream to a destination directory.

The simple gulp API
Using gulp is super simple because you don’t have to figure out how a complex API works in order to be productive with it. There are only 4 api’s in gulp!

API                     Purpose
gulp.task             Define a task
gulp.src             Read files in
gulp.dest             Write files out
gulp.watch     Watch files for changes

Installing gulp via npm
The npm package manager comes installed with Node.js. While node.js isn’t a requirement to use gulp, it does make demonstrating it a lot easier. I will be installing gulp from npm locally into my project. Make sure that you’re in your project’s root folder before running the command, otherwise your node modules will be downloaded into the wrong folder.

cd myproject
npm install --save-dev gulp

This will install the gulp node module locally to the project (as opposed to globally). The --save-dev argument lets npm know to update it’s package.json file with a new devDependencies record. devDependencies will need to be resolved at development time, where as dependencies will need to be resolved at run time. Because gulp is a tool to aid us in development, it needs to be resolved at development time.

Creating a gulpfile
A gulpfile is a file that will act as a manifest to define our tasks. Tasks that we want to execute will be found within this file. Whenever we run the command gulp hello-world from the command line, we are telling gulp that we want to run the hello-world task within gulpfile.js.

After creating gulpfile.js within the root of your project, add a basic tasks.

var gulp = require('gulp'); gulp.task('hello-world', function(){ console.log('hello world'); });

require is a function implemented by node (which is an implementation of the CommonJS spec) that will add references to node modules that we have installed. Once we make a reference to the gulp module, we can use it to create a task. Here, our task simply writes to the console window, but you could have it do any number of automated tasks.










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