Nested Component Angular

A Component in Angular can have child components. Also, those child components can have their own further child components. Angular seamlessly supports nested components.In this post, we’ll see how to build components designed to be nested within other components and how to establish communication between the nested component and its parent.
Step 1: Create Parent and child Component

child.componet.ts

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() title: string;
  constructor() { }

  ngOnInit() {

  }

}

Step2: Now in template child.componet.html

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  childTitle: string;
  constructor() { }

  ngOnInit() {
    this.childTitle = 'This is message from parent to child';
  }

}

parent.component.html

<div>
<h1>I'm a Parent component</h1>
</div>

child.component.chtml will be:

<h2>{{title}}</h2>

Let’s look at the code again, We’ll using Input property to get the values from the parent.If a nested components wants to receive input from its container, it must expose a property to that container. We use the Input Decorator to decorate any property in the nested components class. In here, we wanna the childTitle pass in the nested component.
Adding input to our import statement

import { Component, OnInit, Input } from '@angular/core';

If the nested component wants to send information back to its container, it can raise an event. The nested component exposes an event it can use to pass output to its container using the @Output decorator. In this case , the property type must be an event. The only way a nested component can pass data back to its container, is with an event. The data to pass is called the event payload.
So the modified chid.component.ts would be:

import { Component, OnInit, Input, Output } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Output() notify: EventEmitter = new EventEmitter();
@Input() title: string;
  constructor() { }

  ngOnInit() {

  }
  onClick() {
    this.notify.emit('Click from nested child that subsribe in parent ');
  }
}

You can see I have imported Event Emitter from angularcore
child.component.html

parent.component.ts

import { Component, OnInit } from '@angular/core';

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

  childTitle: string;
  constructor() { }

  ngOnInit() {
    this.childTitle = 'This is message from parent to child';
  }

  onNotify(message: string): void {
    alert(message);
  }
}

parent.component.html


<div>
  <h1>I'm a Parent component</h1>

</div>

Services in Angular

In real time Angular UI component should focus on presenting data and delegate data access to a service. Services in angular could be singleton and lazy instantiated.services. Singleton service gets created when angular app components need them using $injector. Lets jump directly and create a sample service. We are using public api to get the stock quote and display on UI.

code will looks like stockservice.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class StockService {

  constructor(private http: Http) { }
  getStockPriceLive() {
    return this.http.get('https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=MSFT,FB,AAPL&apikey=demo')
      .map(res => res.json());
  }
}

servicesamplecomponent.ts file looks like:

import { Component, OnInit } from '@angular/core';
import { StockService } from '../stock.service';

@Component({
  selector: 'app-service-sample',
  templateUrl: './service-sample.component.html',
  styleUrls: ['./service-sample.component.css']
})
export class ServiceSampleComponent implements OnInit {
 stock: any[];
  constructor(private stockService: StockService) { }

  ngOnInit() {
    this.getLiveStockPrice();
  }

  getLiveStockPrice() {
    this.stockService.getStockPriceLive().subscribe((result) => {
      console.log(result['Stock Quotes']);
      this.stock = result['Stock Quotes'];

    });
  }
}

Now display on UI:
Screen Shot 2018-03-11 at 2.07.57 PM
As we can see we created a stock service for loosely-coupled communication between classes.The StockService injected into a component is created with another component, Service sample.HttpClient is Angular’s mechanism for communicating with a remote server over HTTP. HttpClient.get returns the body of the response as an untyped JSON object by default. Next sample we will try to make API call that returns an observable collection of objects.

 

Angular 5 Sample 1

First Angular 5 sample code in VS Code. This code sample will maintain an array of object customers locally and search button will demonstrate how we can attach an event and how to use a stractureal directive (*ngFor) in angular. I have created a component called detail.
The cod ein detail.component.ts:

 import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {
  customers: any[];
  public LoadCustomers(filterText: string): void {
    this.customers = [
      { id: 1, Name: 'Tom Paul' },
      { id: 2, Name: 'John Doe' },
      { id: 3, Name: 'Jijo Venginikkadan' },
      { id: 4, Name: 'Alex George' },
    ];

    if (filterText !== '') {
      const filteCustomerList: any[] = [];
      this.customers.forEach(cust => {
        console.log(cust.Name);
        console.log(filterText);
        if (cust.Name.toLowerCase().includes(filterText.toLowerCase())) {
          filteCustomerList.push(cust);
        }
      });
      this.customers = filteCustomerList;
    }
  }
  constructor() { }

  ngOnInit() {
    this.LoadCustomers('');
  }
  OnCustomerSearch(searchTerm: string): void {
    console.log(searchTerm);
    this.LoadCustomers(searchTerm);
  }

}

Template detail.component.html would looks like:

<div class="form-group">
  <div class="md-col-4">
    Enter Student Name:
  </div>
  <div class="md-col-4">
    
  </div>
</div>

  Search

<table class="table table-responsive table-bordered table-striped">
  <thead>
    <tr>
      <th>Customer ID</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{{s.id}}</td>
      <td>{{s.Name | uppercase}}</td>
    </tr>
  </tbody>
</table>

Using context.Database.Log

In my recent project there was a requirement to develop a logging system each query performed by Entity framework should be logged with time stamp. It was all in the air when we started addressing performance tuning.
A good and common way to find out what’s going on behind the scenes is to use SQL Server profiler to trace all calls to the database. That way, you can see what SQL statements are being executed, how often, and how much time they take.
Logging all database operations can be achieved by assigning the DbContext.Database.Log property with an action that takes a string as a parameter.
When the Log property is set the following activities are logged −

  1. SQL for all different kinds of commands e.g. Queries, including inserts, updates, and 2. deletes generated as part of Save Changes
    3. Parameters
    4. Whether or not the command is being executed asynchronously
    5.. A time stamp indicating when the command started executing
    6. The command completed successfully or failed
    7. Some indication of the result value
    8. The approximate amount of time it took to execute the command

The DbContext.Database.Log property can be set to a delegate for any method that takes a string. Most commonly it is used with any TextWriter by setting it to the “Write” method of that TextWriter. All SQL generated by the current context will be logged to that writer. For example, the following code will log SQL to the console as well as log file:

public partial class MyDBCoreContext : DbContext
{
    static MyDBCoreContext()
    {
        Database.SetInitializer<MyDBCoreContext>(null);
    }

    public MyDBCoreContext(String connectionString)
        : base(connectionString)
    {
        this.Database.CommandTimeout = 240;
        this.Database.Log = DatabaseEfLogger;
    }

    public void DatabaseEfLogger(string sql)
    {
        Debug.Write(sql);
        var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        logger.Debug(sql);
    }
}

Jitbit Integration with .NET

Deliver awesome support to your customers. Jitbit Helpdesk ticketing system is a simple, powerful and easy to deal with. We can either host it in on-premise or cloud-host.There was a recent requuest from one of my client to come up with a simple ticketing system where business can start operating quickly and integrate it with there clinet facing .NET application.The real beauty was , the interface it expose where we can integrate with our Entraprise Apllications. I am going to share few code samples that will be helpful.

Please see some helper methods first:

        public string BuildRequest(string method, IEnumerable&amp;amp;amp;lt;KeyValuePair&amp;amp;amp;lt;string, string&amp;amp;amp;gt;&amp;amp;amp;gt; urlParameters)
        {
            var returnData = &amp;amp;amp;quot;{}&amp;amp;amp;quot;;
            var querystring = new StringBuilder(&amp;amp;amp;quot;?&amp;amp;amp;quot;);
            if (urlParameters != null &amp;amp;amp;amp;&amp;amp;amp;amp; urlParameters.Count() &amp;amp;amp;gt; 0)
            {
                foreach (var item in urlParameters)
                {
                    querystring.Append(item.Key + &amp;amp;amp;quot;=&amp;amp;amp;quot; + item.Value + &amp;amp;amp;quot;&amp;amp;amp;amp;&amp;amp;amp;quot;);

                }
                querystring.Remove(querystring.Length - 1, 1);
            }
            else { querystring.Clear(); }
            return returnData;
        }
        private string ConstructHeader()
        {
            string credentials = new StringBuilder(_Username + &amp;amp;amp;quot;:&amp;amp;amp;quot; + _Password).ToString();
            return new StringBuilder(&amp;amp;amp;quot;Basic &amp;amp;amp;quot; + Convert.ToBase64String(Encoding.UTF8.GetBytes(credentials))).ToString();
        }
        private HttpWebRequest ConstructRequest(string querystring = &amp;amp;amp;quot;&amp;amp;amp;quot;)
        {
            HttpWebRequest ClientWebRequest = (HttpWebRequest)WebRequest.Create(_BaseAdress + querystring);
            IWebProxy proxy = ClientWebRequest.Proxy;
            if (proxy != null)
            {
                NetworkCredential cred = System.Net.CredentialCache.DefaultNetworkCredentials;
                proxy.Credentials = cred;
                WebRequest.DefaultWebProxy = proxy;
            }
            AddAuthenticationHeader(ClientWebRequest);
            ClientWebRequest.Accept = &amp;amp;amp;quot;Application/Json&amp;amp;amp;quot;;
            ClientWebRequest.ContentType = &amp;amp;amp;quot;Application/Json&amp;amp;amp;quot;;
            ClientWebRequest.Method = WebRequestMethods.Http.Get;
            return ClientWebRequest;
        }
        private HttpWebRequest ConstructRequest(string querystring = &amp;amp;amp;quot;&amp;amp;amp;quot;)
        {
            var ClientWebRequest = (HttpWebRequest)WebRequest.Create(_BaseAdress + querystring);
            var proxy = ClientWebRequest.Proxy;
            if (proxy != null)
            {
                NetworkCredential cred = System.Net.CredentialCache.DefaultNetworkCredentials;
                proxy.Credentials = cred;
                WebRequest.DefaultWebProxy = proxy;
            }
            ClientWebRequest.Accept = &amp;amp;amp;quot;Application/Json&amp;amp;amp;quot;;
            ClientWebRequest.ContentType = &amp;amp;amp;quot;Application/Json&amp;amp;amp;quot;;
            ClientWebRequest.Method = WebRequestMethods.Http.Get;
            return ClientWebRequest;
        }

        private string ReadResponse(HttpWebResponse response)
        {
            string ResponseContent = null;
            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                ResponseContent = reader.ReadToEndAsync().Result;
            }
            return ResponseContent;
        }

Now Lets Make some API Calls:

         public JToken GetEntitiesByEmail(string userName)
        {
            var querystring = new Dictionary&lt;string, string&gt; { { &quot;email&quot;, userName } };
            try
            {
                var response = this._helpDeskService.BuildRequest(&quot;UserByEmail&quot;, querystring);
                var result = JToken.Parse(response);
                return result;
            }
            catch (Exception ex)
            {
            }
        }
        public JToken GetEntitiesByUser( string userEmail)
        {
            var querystring = new Dictionary&lt;string, string&gt; { { &quot;email&quot;, userEmail } };
            try
            {
                var response = this._helpDeskService.BuildRequest(&quot;UserByEmail&quot;, querystring);
                var result = JToken.Parse(response);
                var user = result.ToObject&lt;HelpDeskUser&gt;();
                querystring.Clear();
                querystring.Add(&quot;handledByUserID&quot;, user.UserID.ToString());
                return JToken.Parse(this._helpDeskService.ForwardGetRequest(entity, querystring));
            }
            catch (Exception ex)
            {
            }
        }
        public JToken GetHelpDeskTickets( string categoryid)
        {
            var querystring = new Dictionary&lt;string, string&gt;
            {
                { &quot;mode&quot;, &quot;unclosed&quot;},
                { &quot;categoryid&quot;, categoryid },
                { &quot;count&quot;, &quot;100&quot; } 
            };
            try
            {
                var response = this._helpDeskService.BuildRequest(&quot;tickets&quot;, querystring);
                var result = JToken.Parse(response);
                return result;
            }
            catch (Exception ex)
            {
            }
        }
        public string GetCreatedUser()
        {
            var querystring = new Dictionary&lt;string, string&gt;
            {
                { &quot;email&quot;, &quot;jijo@me.com&quot; },
                { &quot;firstName&quot;, &quot;Jijo&quot; } ,
                { &quot;lastName&quot;, &quot;vg&quot; } ,
                { &quot;userName&quot;, &quot;jijo&quot; } ,
                { &quot;sendWelcomeEmail&quot;, &quot;true&quot; }
            };
            try
            {
                var response = this._helpDeskService.HttpPostRequest(&quot;CreateUser&quot;, querystring);
                return response;
            }
            catch (Exception ex)
            {

            }
        }

Session hijacking fix

session hijacking is not something new to discuss.Users are authenticated based on their login credentials (e.g. user names and passwords) and are issued session IDs that will effectively serve as temporary static passwords for accessing their sessions, which makes session IDs a very appealing target for attackers. The moment a user enters his credentials on login to authenticate, these data are stored in the session and cookies are generated in the client browser. When we logeed out we assume session is terminated. But in realiity we can see the cookie values are not deleted from the client browser, even if the session is ended, and such cookie values could be exploited by a hacker to breach into the website’s sensitive zone, without being aware of user name and password. There are several approaches to overcome such session hijacking kinds of attacks. I would like to share one of the approach we did in our client place. You can see Login() and Logout functions getting called on user actions and the caopde make sure that prevent session hijacking

        public ActionResult Logout()
        {
            //Clear all cookies
            var count = Request.Cookies.Count;
            for (int i = 0; i &lt; count; i++)
            {
                var cookie = Request.Cookies.Get(i);
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddHours(-1);
                    cookie.Value = string.Empty;
                    Response.Cookies.Add(cookie);
                }
            }
            Session.Abandon();
            FormsAuthentication.SignOut();
            return RedirectToAction(&quot;Login&quot;, &quot;Account&quot;);
        }
        public ActionResult Login()
        {
            //Clear all cookies. Any cookie set before login should be invalid. since it can enable session fixation attacks
            if (Request.Cookies[&quot;__CKIE&quot;] == null || Request.Cookies[&quot;__CKIE&quot;].Value == string.Empty)
            {
                var count = Request.Cookies.Count;
                for (var i = 0; i &lt; count; i++)
                {
                    var cookie = Request.Cookies.Get(i);
                    if (cookie != null)
                    {
                        cookie.Expires = DateTime.Now.AddHours(-1);
                        cookie.Value = string.Empty;
                        Response.Cookies.Add(cookie);
                    }
                }
                Response.Cookies.Add(new HttpCookie(&quot;__CKIE&quot;, &quot;1&quot;));
                Response.Redirect(&quot;~/Account/Login&quot;, true);
            }
            else
            {
                var cookie = Request.Cookies[&quot;__CKIE&quot;];
                cookie.Expires = DateTime.Now.AddHours(-1);
                cookie.Value = string.Empty;
                Response.Cookies.Add(cookie);
            }
            return View();
        }

AngularJS in MVC with WEBAPI

These days, AngularJS and ASP.NET MVC is getting focus on web development world.In this post we will learn how to combine the best of both worlds and use the goodness of AngularJS in ASP.NET MVC by demonstrating how to use AngularJS in an ASP.NET MVC application. This sample application will help to understand how AngularJS can integrate on MVC UI frame work and call a web API to populate the data.
Controller
A controller is the JavaScript constructor function which contains data and business logic. The controller and the view talk to each other using the $scope object. Scope is nothing but binding. It binds a logical view model to physical model.
Service
A service is the function by which an instance gets created once per application life cycle. Anything shared across the controller should be part of the service. A service can be created in many different ways. The most popular way is by using the service method or the factory method.
Modules
Modules are the functions which contain other functions like a service or a controller. There should be at least one module per Angular app.
This Application has three sections. Before you copy this code please make sure you have created a ASP.NET MVC application ready:
1. Create ASP.NET Web Application using MVC template.
2. Add AngulrJs libraries to the application (This sample use web reference)
3. Create a WEBAPI get method to punch out JSON object.
Create a App.JS file under scripts and copy this code:

var CountryApp = angular.module('CountryApp', []);
CountryApp.controller('CountryController', function ($scope, CountryService) {
    getCountries();
    function getCountries() {
        CountryService.getCountries()
            .success(function (data) {
                $scope.countries = data;
            })
            .error(function (error) {
                $scope.status = 'Unable to load country data: ' + error.message;
            });
    }
});

CountryApp.factory('CountryService', ['$http', function ($http) {
    var CountryService = {};
    CountryService.getCountries = function () {
        return $http.get('/Api/Home');
    };
    return CountryService;
}]);

Copy this code in API controller

        public List<Country> Get()
        {
            return new List<Country>()
            {
                new Country() {Name = "USA",Region = "NA",ID =  1 },
                new Country() {Name = "India",Region = "Asia", ID = 2 }
            };
        }

Index.chtml page will looks like below

<!DOCTYPE html>
    <html >
    <head>
        <title ng-bind="models.helloAngular"></title>
    </head>
    <body>
<div ng-app="CountryApp" class="container">
<div ng-controller="CountryController">
<table class="table">
<tr ng-repeat="r in countries | filter : searchCountry">
<td>{{r.ID}}</td>
<td>{{r.Name}}</td>
<td>
                            {{r.Region}}</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
        <script src="~/Scripts/Controllers/App.js"></script>
     </body>
    </html>

Model class

    public class Country
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Region { get; set; }
    }

Folder stracture should be:
Capture.PNG

Visual Studio Code

‘Hello World’ with Node.js and Visual Studio Code
Visual Studio Code is the first code editor, and first cross-platform development tool – supporting OS X, Linux, and Windows – in the Visual Studio family. At its heart, Visual Studio Code is a code editor. Like many other code editors, VS Code adopts a common UI and layout.
Recently there was a request from the Business team to evaluate Visual Studio Code as a part of project proposal. This has ended up coming up with a sample Hello World Application with Node.js and Visual Studio Code.
Prerequisites: Download Visual Studio Code and Node.Js
Step 1:
As stated above, VSC is directory structure-based. For my tutorial, I’m going to create the folder C:\Samples\HelloWorld.From Windows Explorer, right-click on it and Click on “Open with Code”.
Create Working Folder
Step 2:
Node.js is a JavaScript runtime library. In simple words it is something that we are going to replace IIS. I need some dll to be installed to handle server requests. Go to Admin Command Prompt and inside HelloWorld directory type below commands one after another:
1. npm install express
2. npm install body-parser
3. npm install jquery
After successfully completed this command you will see some files downloaded and added to project folder.
Step 3:
At any administrator command prompt type the following:
1. npm install -g tsd
Step 4:
At the command prompt, inside of the HelloWorld directory, type in the following:
1. npm install tsd
Once you’ve completed these steps, your HelloWorld VSC window should look like the following:
aaaa
Step 5:
Visual Studio Code executes “tasks” for building, deploying, etc. What we must do is configure our own task runner to run our application with Node.js.
1. Click on Ctrl+P will display VCS command prompt , type > Configure Task Runner
2. Upon choosing this option, a .settings folder is created with a file named tasks.json. Delete/Comment everything on it and paste below line:
{
“version”: “0.1.0”,
“command”: “node”,
“isShellCommand”: false,
“args”: [
“app.js”
]
}
Step 6:
While at the command prompt (in your project folder), type the following:
1. node_modules\.bin\tsd install express
2. node_modules\.bin\tsd install body-parser
3. node_modules\.bin\tsd install jquery
Step 7:
Now that the environment has been setup successfully, we need to create a web server configuration file. Node.js will launch a web server instance based on the configuration we specify. If you remember from the previous page, we created a task to execute Node.js and specified an argument of app.js.

/// <reference path="typings/node/node.d.ts" />
/// <reference path="typings/express/express.d.ts" />
/// <reference path="typings/body-parser/body-parser.d.ts" />
var express = require('express');
var app = express();
app.use('/', express.static('./'));
app.get('/', function(req, res){
    res.sendFile('default.html', { root: __dirname });
});
app.listen(8081);

Step 8:
Finally, let’s create our content page. Create a page named default.html in the home folder. Then, add the following contents:

<html>
  <head>
    <title>Node.js</title>
  </head>
  <body>
    <h1>Hello World!</h1>
    Sample POC code. 
  </body>
</html>

Run the task
Because the task has already been configured previously, we simply need to press Ctrl+Shift+B (for Build). This will execute our task. Provided that we don’t get any errors in our Output window, Node.js will have created a background process in Windows.
Open a web browser and go to the URL configured above (in this case, http://localhost:8081/). Again, provided there are no errors reported in your browser or VSC’s Output window, you should see the contents of your default.html page.
Cancelling the Task
Keep in mind that once I start the Node.js server, it is an child task of VSC meaning that, even though I may not see it, Node.js is running in the background.
To cancel the task in VSC:
Press Ctrl+P
Begin typing: >terminate

Reference Read:
1. https://code.visualstudio.com/Docs
2. https://www.visualstudio.com/en-us/products/code-vs.aspx
3. http://jdav.is/2015/08/05/hello-world-with-node-js-and-visual-studio-code/

JavaScript closure explained

Closures are a way to let a function have persistent, private variables – that is, variables that only one function knows about, where it can keep track of info from previous times.It is an inner function that has access to outer function variables and parameters in addition to its own variables in its scope. In simple words, it is a function inside another function. These functions could be named functions or Anonymous.
Here is a sample closure:
Think about a scenario where we need to keep track of the mouse click happened in a session on a page:

<script type="text/javascript">
    var incrementClickCount = (function () {
        var clickCount = 0;
        return function () {
            return ++clickCount;
        }
    })()
</script>
<input type="button" value="Click Me" onclick="alert(incrementClickCount());" />

SendGrid – SMTP

What is SendGrid ?
SendGrid is for anyone that needs to send email, whether it’s transactional email or marketing emails and campaigns. SendGrid is a cloud-based SMTP provider that allows you to send email without having to maintain email servers. SendGrid manages all of the technical details, from scaling the infrastructure to ISP outreach and reputation monitoring to white list services and real time analytics. SendGrid also provide a robust marketing email API if you want to integrate any of these features into your own application.
SendGrid provides two ways to send email: through our SMTP relay or through our Web API. Please find samples for SMTP replay:

		public static void SmtpSendMessage()
        {
			try
			{
				var mailMsg = new MailMessage();

				// To
				//TODO: To Name should be Configured
				mailMsg.To.Add(new MailAddress("jijo.venginikkadan@gmail.com", "To Name"));
				mailMsg.To.Add(new MailAddress("jijo.venginikkadan@gmail.com", "To Name"));

				// From
				//TODO:From Name should be Configured
				mailMsg.From = new MailAddress("from@example.com", "From Name");

				// Subject and multipart/alternative Body
				//TODO:Subject should be configured
				mailMsg.Subject = "SendGrid Test email";
				//TODO:Body should be configured
				var text = "Hello,\n\nThis is a test message from SendGrid."; ;
				//TODO:Body should be configured
				//const string html = @"<p>html body</p>";

				mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
				mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

				var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
				//TODO:User ID and password should be configured
				//                var credentials = new System.Net.NetworkCredential("UserID", "password123");
				//                smtpClient.Credentials = credentials;

				smtpClient.Send(mailMsg);
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
	  }