Monday, 26 March 2018

Angular 2 - Forms

Developing forms requires design skills (which are out of scope for this page), as well as framework support for two-way data binding, change tracking, validation, and error handling, which you'll learn about on this page.

Template-driven forms
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';

  declarations: [
  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 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 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 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 class="form-group">
    <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" class="btn btn-primary">Register</button>

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";

  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) {
  ngOnInit() {

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

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

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

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

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:

var express = require('express');
var app = express();
var routes = require('./routes');  //  refs a routes.js file where most of our code will be written.
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.

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}); () { });

// 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) {
        } else {
            res.setHeader("Content-Type:", "application/json");
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:'/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));;

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;;

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.
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.

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;    

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     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 →


ADFS (1) ADO .Net (2) Ajax (1) Angular (1) Angular Js (17) Angular2 (28) ASP .Net (14) Authentication (1) Azure (1) Breeze.js (1) C# (50) CD (1) CI (2) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DevOps (4) DI (4) Dotnet (22) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (50) NodeJS (7) RDLC (1) Report (1) SDLC (1) Sql Server (30) SSIS (3) SSO (1) SSRS (2) UI (1) WCF (13) Web Api (11) Web Service (1) XMl (1)