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 →

Tuesday 19 September 2017

ExpressJs Router

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Express router is a class which helps us to create router handlers.
Each route can have one or more handler functions, which are executed when the route is matched.
var express = require('express')
var app = express()

app.METHOD(PATH, HANDLER)
  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.
The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:
app.get('/', function (req, res) {
  res.send('hello world')
})

Respond to POST request on the root route (/), the application’s home page:
app.post('/', function (req, res) {
  res.send('Got a POST request')
})

Respond to a PUT request to the /user route:
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})

Respond to a DELETE request to the /user route:
app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})

Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.

The above code is an example of routes that are defined for the GET, POST, PUT, DELETE methods to the root of the app.

Express supports the following routing methods that correspond to HTTP methods:
get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, patch and search.
There is a special routing method, app.all(), which is not derived from any HTTP method. This method is used for loading middleware functions at a path for all request methods.

In the following example, the handler will be executed for requests to “/isValid” whether you are using GET, POST, PUT, DELETE, or any other HTTP request method that is supported in the http module.
app.all('/isValid', function (req, res, next) {
  console.log('Accessing the Validate method...')
  next() // pass control to the next handler
})

Route paths
Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.

The characters ?, +, *, and () are subsets of their regular expression counterparts. The hyphen (-) and the dot (.) are interpreted literally by string-based paths.

If you need to use the dollar character ($) in a path string, enclose it escaped within ([ and ]). For example, the path string for requests at “/data/$book”, would be “/data/([\$])book”.

Query strings are not part of the route path.

Here are some examples of route paths based on strings.

This route path will match requests to the root route, /.
app.get('/', function (req, res) {
  res.send('root')
})

This route path will match requests to /about.
app.get('/about', function (req, res) {
  res.send('about')
})

This route path will match requests to /random.text.
app.get('/random.text', function (req, res) {
  res.send('random.text')
})

Here are some examples of route paths based on string patterns.

This route path will match acd and abcd.
app.get('/ab?cd', function (req, res) {
  res.send('ab?cd')
})

This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', function (req, res) {
  res.send('ab+cd')
})

This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so on.
app.get('/ab*cd', function (req, res) {
  res.send('ab*cd')
})

This route path will match /abe and /abcde.
app.get('/ab(cd)?e', function (req, res) {
  res.send('ab(cd)?e')
})

Examples of route paths based on regular expressions:

This route path will match anything with an “a” in the route name.
app.get(/a/, function (req, res) {
  res.send('/a/')
})

This route path will match butterfly and dragonfly, but not butterflyman, dragonflyman, and so on.
app.get(/.*fly$/, function (req, res) {
  res.send('/.*fly$/')
})

Route parameters
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.

Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

Route handlers
You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.

More than one callback function can handle a route (make sure you specify the next object). For example:
app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...')
  next()
}, function (req, res) {
  res.send('Hello from B!')
})

Response methods
The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
MethodDescription
res.download()Prompt a file to be downloaded.
res.end()End the response process.
res.json()Send a JSON response.
res.jsonp()Send a JSON response with JSONP support.
res.redirect()Redirect a request.
res.render()Render a view template.
res.send()Send a response of various types.
res.sendFile()Send a file as an octet stream.
res.sendStatus()Set the response status code and send its string representation as the response body.
app.route()
You can create chainable route handlers for a route path by using app.route(). Because the path is specified at a single location, creating modular routes is helpful, as is reducing redundancy and typos. For more information about routes, see: Router() documentation.
Here is an example of chained route handlers that are defined by using app.route().
app.route('/book')
  .get(function (reqres) {
    res.send('Get a random book')
  })
  .post(function (reqres) {
    res.send('Add a book')
  })
  .put(function (reqres) {
    res.send('Update the book')
  })

express.Router
Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.
The following example creates a router as a module, loads a middleware function in it, defines some routes, and mounts the router module on a path in the main app.
Create a router file named apiRoutes.js in the app directory, with the following content:

const express = require('express'),
httpStatus = require('http-status');
const router = express.Router()

let users = [{
name: 'suraj',
address: 'noida',
contact: '9876543210'
}];

// middleware that is specific to this router
router.use(function timeLog (reqresnext) {
 if(req.params.id == 0) {
res.json({"message" : "You must pass ID other than 0"});    
}
else {
console.log(req.methodreq.url); // log each request to the console
   next();}
})

router.get('/', (reqres=> {
res.status(httpStatus.OK).send(users);
}).post('/', (reqres=> {
const obj = req.body;
users.push(obj);
res.status(httpStatus.CREATED).send("created");
});

// Handle 404 error. 
// The last middleware.
router.use("*",function(req,res){
res.status(httpStatus.NOT_FOUND).send('404');
});

module.exports = router

Then, load the router module in the app:
const expressrequire('express'),
bodyParserrequire('body-parser'),
apiRoutes=require('./server/routes/apiRoutes');

const appexpress();        

//application/json
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

// apply the routes to our application
app.use('/api',apiRoutes);

const port = process.env.PORT || 1300;

app.listen(portfunction() {
console.log('App listening on port ${port}!');
});

The body-parser module provides middleware for parsing JSON, plain text,
or just returning a raw Buffer object for you to deal with as needed.
app.use(bodyParser.json()) basically tells the system that you want json to be used.

Installation: $ npm install body-parser API: var bodyParser = require('body-parser')

Conclusion
With the inclusion of the Express 4.0 Router, we are given more flexibility than ever before in defining our routes. To recap, we can:
  1. Use express.Router() multiple times to define groups of routes
  2. Apply the express.Router() to a section of our site using app.use()
  3. Use route middleware to process requests
  4. Use route middleware to validate parameters using .param()
  5. Use app.route() as a shortcut to the Router to define multiple requests on a route
  6. With all the ways we can define routes, I'm sure that our applications will benefit going forward. Sound off in the comments if you have any questions or suggestions.

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