Wednesday 28 December 2016

Lambda Expressions and Expression Trees: An Introduction

Introduction

This article will introduce you to lambda expressions and expression trees – two new related features coming up in the newest version of C# and the .NET runtime. You will learn how to create them, and how to use them to enhance and simplify your C# code. Knowledge of the concepts behind delegates in the .NET framework is assumed.

Let's start by brushing up on anonymous methods, since the concepts behind them will help in understanding lambda expressions.

Anonymous Methods

.NET 2.0 introduced a new construct: anonymous methods. Instead of declaring a named method in your class and then referencing the method by name when creating a delegate:

bool MatchNumbersBelow10(int n)
{
return n<10;
}
...
int GetNumber(List<int> numbers)
{
//gets the first number smaller than 10 in the list
return numbers.Find(MatchNumbersBelow10);
}

.you can write the method directly where it is used:

int GetNumber(List<int> numbers)
{
//gets the first number smaller than 10 in the list
return numbers.Find(
delegate(int n)
{
return n<10;
}
);
}

As you can see, in the above sample we are passing in a special kind of nameless inline method as a delegate directly to the numbers.Find() method. The advantages of this "anonymous method" syntax are: 1. You don't have to clutter up your class with private methods that are only used once in order to pass some custom code to a method.
2. The code can be put in the place it's used in, rather than somewhere else in the class.
3. The method doesn't have to be named.
4. The return type is inferred from the signature of the delegate type that the anonymous method is being cast to.
5. You can reference local variables in the "outer" method from within the anonymous method.

Anonymous Method Rules

The rules for defining an anonymous method are simple: 1. Don't declare a return type - it is inferred from the delegate signature.
2. The keyword delegate is used instead of a method name, since anonymous methods are only ever accessed via a delegate.
3. Declare the method's arguments to match the signature of the delegate, just like you would when declaring a normal method to pass as a delegate.
4. Don't declare variables whose names conflict with variables in the outer method in which the anonymous method is declared.

Lambda Expressions

C# 3.0 and the .NET 3.0 Runtime introduce a more powerful construct that builds on the anonymous method concept. It allows you to pass an inline expression as a delegate, with minimal syntax. Instead of the anonymous method we declared above:

delegate (int n)
{
return n<10;
}

...we can do:

n => n<10

It looks shorter and more concise, doesn't it? But how does it work? The basic form for a lambda expression is:

argument-list => expression

In the example above, we have an argument named n, implicitly typed as int, then the lambda operator (=>), then an expression which checks to see whether n is smaller than 10. We can use this lambda expression as input for the Find() method:

//gets the first number smaller than 10 in the list

int result=numbers.Find( n=> n<10);

To understand better how the lambda expression syntax differs from the anonymous method syntax, let's turn our example anonymous method:

delegate(int n)
{
return n<10;
}

...into its lambda-expression equivalent:

n=> n<10

We don't need the delegate keyword, so take it out.

(int n)
{
return n<10;
}

Let's replace the braces with a => lambda operator to make it an inline lambda expression.

(int n) => return n<10;

Let's replace the braces with a => lambda operator to make it an inline lambda expression.

(int n) => return n<10;

The return keyword isn't needed (or even legal) because an expression is always a single line of code that returns a value. Also, remove the semicolon, because n<10 is now an expression, not a full statement.

(int n)=> n<10

Now, that's already a usable lambda expression - but we can simplify it just a bit more. The type of the argument can be inferred as well by the compiler, so we can remove the type declaration for the argument.

(n)=> n<10

We can also take out the parenthesis now, because we don't give the types of the arguments.

n=> n<10

And there's our final lambda expression!
As you can probably see just by that example, the big advantage of lambda expressions in normal coding is that the syntax is more readable and less verbose. This becomes quickly more important the more complex code becomes. For example, when we just add one more argument, take a look at the difference between the length and readability of an anonymous method vs. a lambda expression:

//anonymous method
numbers.Sort(delegate(int x, int y){ return y-x; });
//lambda expression
numbers.Sort((x,y)=> y-x);

And in a more complex example, with multiple delegate properties, compare anonymous methods:

ControlTrigger trigger= new ControlTrigger ();
trigger.When=delegate(Control c, ThemePart t)
{
return c.Enabled && c.MouseOver;
};
trigger.Action=delegate(Control c, ThemePart t)
{
t.Visible=true;
};
trigger.ExitAction=delegate(Control c, ThemePart t)
{
t.Visible=false;
};

...with lambda expressions:

ControlTrigger trigger=new ControlTrigger();
trigger.When=(c,t)=> c.Enabled && c.MouseOver;
trigger.Action=(c,t)=> t.Visible=true;
trigger.ExitAction=(c,t)=> t.Visible=false;

Features and Rules

Return type and name cannot be specified explicitly (just as with anonymous methods). The return type is always inferred from the delegate signature, and there is no need for a name since the expression is always handled as a delegate.
You can omit parentheses for the argument list if the expression has one argument:

n => n<10

...unless its argument has an explicitly-declared data type:

//Type explicitly declared for an argument - have to include parentheses!
(string name)=> "Name: " + name

If the expression has more than one argument or has no arguments, you must include the parentheses.
A lambda expression doesn't have to return a value if the signature of the delegate it is being cast to has a return type of void:

delegate void EmptyDelegate(); … EmptyDelegate dlgt= ()=> Console.WriteLine("Lambda without return type!");

The code used in a lambda doesn't have to be a single statement. You can include multiple statements if you enclose them inside a statement block:

Action<Control> action=
control=>
{
control.ForeColor=Color.DarkRed;
control.BackColor=Color.MistyRose;
});

In this form, the lambda more closely resembles an anonymous method, but with a less verbose syntax. Lambda statement blocks are not supported by the VS IDE in the LINQ Preview, so they will be underlined as a syntax error. However, they will compile and run correctly in spite of the IDE's lack of support. You can access local variables and arguments in the outer method from within the expression, just as you can do with anonymous methods.

void GetMatchesFromList(List<int> matchValues) { List<int> numbers=GetNumbers(); //Get a list of numbers to search in. //Get the first number in the numbers list that is also contained in the //matchValues list. int result=numbers.Find(n=> matchValues.Contains(n)); }

Uses

Lambda expressions are nifty anywhere you need to pass a little bit of custom code to a component or method. Where anonymous methods were useful in C# 2.0, lambda expressions really shine in C# 3.0.
Some examples are expressions for filtering, sorting, iterating, converting, and searching lists (using the useful methods introduced in .NET 2.0):

List<int> numbers=GetNumbers();
//find the first number in the list that is below 10
int match=numbers.Find(n=> n<10);
//print all the numbers in the list to the console
numbers.ForEach(n=> Console.WriteLine(n));
//convert all the numbers in the list to floating-point values
List<float> floatNumbers=numbers.ConvertAll<float>(n=> (float)n);
//sort the numbers in reverse order
numbers.Sort((x, y) => y-x);
//filter out all odd numbers
numbers.RemoveAll(n=> n%2!=0);

Lambda Expression Trees

There's another powerful feature of lambda expressions that is not obvious at first glance. Lambda expressions can be used as expression trees (hierarchies of objects defining the components of an expression – operators, property access sub-expressions, etc) instead of being directly turned to code. This way, the expressions can be analyzed at runtime.

To make a lambda expression be treated as an expression tree, assign or cast it to the type Expression, where T is the type of the delegate that defines the expression's signature.

Expression<Predicate<int>> expression = n=> n<10;

The expression tree created by the expression defined above looks like this:

As you can see, Expression class has a property called Body, which holds the top level expression object in the expression tree. In the case of the expression above, it is a BinaryExpression with a NodeType of ExpressionType.LT (LessThan). The BinaryExpression object has a Left property that contains the sub-expression to the left of the operator – in this case, a ParameterExpression whose Name property is set to "n". It also has a Right property that contains the sub-expression to the right of the operator – in this case, a ConstantExpression whose value is 10.

This expression tree can also be created manually like this:

Expression<Predicate<int>> expression = Expression.Lambda<Predicate<int>>(
Expression.LT(
Expression.Parameter(typeof(int), "n"),
Expression.Constant(10)
),
Expression.Parameter(typeof(int), "n")
);

An expression tree can be compiled and turned into a delegate using the Compile() method of the Expressionclass:

//Get a compiled version of the expression, wrapped in a delegate Predicate predicate=expression.Compile(); //use the compiled expression bool isMatch=predicate(8); //isMatch will be set to true

The Compile() method dynamically compiles IL code based on the expression, wraps it in a delegate so that it can be called just like any other delegate, and then returns the delegate.

Uses

As shown above, the properties of the expression tree objects can be used to get detailed information about all parts of the expression. This information can be used to translate the expression into another form, extract dependency information, or do other useful things. Microsoft's Database Language-Integrated Query (DLinq) technology, to be introduced in the upcoming version of the .NET Runtime, is based on translation of lambda expressions to SQL at runtime.
I am working on a component that will allow you to do simple automatic binding via expressions, like this):

Binding binding=new Binding();
binding.SourceObject=src;
binding.DestObject=dest;
binding.SourceExpression=(src,dest)=> src.Name +
" – added on "+src.Date.ToString();
binding.DestExpression=(dest)=>dest.Text;
binding.Bind();

The Binding object would analyze the expression tree specified in the SourceExpression property, find all binding dependencies (in this case the Name and Date properties of the source object), attach listeners to their property change events (NameChanged and DateChanged, or else PropertyChanged), and set the property specified in the destination expression when the events are raised to keep the property value of the destination up-to-date.

Another usage would be a dynamic filter that automatically keeps a list control up-to-date based on changes to the text entered in a filter textbox. All you would have to do to set up the dynamic filter would be:

listControl.Filter=(item)=> item.Name.StartsWith(textBox.Text);

Whenever textbox.Text changes, the filter expression would be run on all the items, and those not matching the filter expression would be hidden.
Another thing that expression trees are potentially useful for is lightweight dynamic code generation. You can build an expression tree manually as I described above, then call Compile() to create a delegate, and then call it to run the generated code. It is much easier to use expression tree objects to generate code than to try to output the IL manually.


How To Automate Build Process of ASP.NET Websites using Jenkins and MSBuild

How to build ASP.NET websites using Jenkins

Introduction

Jenkins offers out of the box build solution for Web application, but it becomes difficult to build an ASP.NET website. This article describes step by step how websites can be built using Jenkins.

Background

I had to offer an auto building solution to one of the clients that I was working for. It was an ASP.NET wesite and had dependant projects also. Jenkins could build web applications seamlessly. But there when it comes to website, it becomes an issue.

Using the Code

Pre-requisites

Install Visual Studio .NET 4.0
Install SQL Server management studio 2008 R2
Install Tortoise SVN
Download and install Jenkins Windows native package from http://jenkins-ci.org/

Download and Install MSbuild Extension pack from the below mentioned location:

Setting up Jenkins for Source Code

Add Plugin to Jenkins

1. Open the URL http://localhost:8080/ in browser.
2. Click on Manage Jenkins.
3. Navigate to "Manage Plugin" section.
4. Click on available tab.
5. Install Msbuild plugin(Click on install without restart).
6. Restart Jenkins.

Creating a New Project in Jenkins

1. Follow all the steps mentioned in "Add plugin to jenkins".
2. Click on New job.
3. Choose "Build a free-style software project" option. Add job name and click on "OK". It creates a new project to be built.

Configuration of the Project

1. Click on the newly created project.
2. Click on configure.
3. Under "Source Code Management", choose Subversion module option.
4. Fill the 'Repository URL' textbox with the corresponding sourcecode URL of SVN.
5. Exp- http://svn.xyz.com/svn/admin
Note- It may ask for credentials. Please fill the credentials for SVN (which you use to log in to SVN) so that Jenkins application can access
SVN. Refer to the below image.

5. Click on 'Add build Step' button and choose 'Build a Visual Studio project or solution using MsBuild' option.
6. Fill the details as shown in the below image:
7. Click on save.
8. Build the project.
9. Build details can be seen on the console output section on the left hand navigation panel.

MSbuild script code (The MSbuild script file that was added in the previous step - SourceCodeBuild.msbuild)

<Project ToolsVersion="4.0"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
< PropertyGroup>
< ProductVersion>10.0.11107</ProductVersion>
< TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
</PropertyGroup>
<Target Name="PrecompileWeb">
<AspNetCompiler
VirtualPath="/TestWebSite"
PhysicalPath="C:\Test-CI\SourceCode\TestWebSite"
TargetPath="c:\precompiledweb\TestWebSite\"
Force="true"
Debug="true" />
</Target>
< /Project>


Tuesday 27 December 2016

Understanding decision making statements in C#

Decision making statements help you to make decision based on certain conditions. These conditions are specified by a set of decision making statements having boolean expressions which are evaluated to a boolean value true or false. There are following types of decision making statements in C#.

01. If statement

An if statement consists of a boolean expression which is evaluated to a boolean value. If the value is true then if block is executed otherwise next statement(s) would be executed.

You can have multiple if statement as shown below-
public class Example
{
static void Main()
{
int a = 5, b = 2;
int result = a / b;
if (result == 2)
{
Console.WriteLine("Result is 2");
}
if (result == 3)
{
Console.WriteLine("Result is 3");
}
}
}


/* Output
Result is 2
*/ You can also do nesting of if statement means an if statement inside another if that is called nested if statement.

02.If-Else statement

An if-else statement consists of two statements – if statement and else statement. When the expression in an if-statement is evaluated to true then if block is executed otherwise the else block would be executed.

public class Example
{
static void Main()
{
int a = 5, b = 6;
int result = a - b;
if (result > 0)
{
Console.WriteLine("Result is greater than zero");
}
else
{
Console.WriteLine("Result is smaller than or equal to zero");
}
}
}
/* Output
Result is smaller than or equal to zero
*/


03.If-Else-If statement or ladder

The If-Else-If ladder is a set of statements that is used to test a series of conditions. If the first if statement meet the result then code within the if block executes. If not, control passes to the else statement, which contains a second "if" statement. If second one meet the result then code within the if block executes. This continues as a series of else if statements. A default else code block may execute when no condition has been evaluated to true.

If-Else-If ladder must contain more specific case at the top and generalize case at the bottom.
public class Example
{
static void Main(string[] args)
{
char grade = 'B';
if (grade == 'A')
{
Console.WriteLine("Excellent!");
}
else if (grade == 'B')
{
Console.WriteLine("Well done");
}
else if (grade == 'D')
{
Console.WriteLine("You passed");
}
else if (grade == 'F')
{
Console.WriteLine("Better try again");
}
else
{
Console.WriteLine("You Failed!");
}
}
}
/* Output
Well done
*/

04.Switch statement

Switch statement acts as a substitute for long If-Else-If ladder that is used to test a series of conditions. A switch statement contains one or more case labels which are tested against the switch expression.

When one case matches the value with the result of switch expression, the control continues executing the code from that label. When no case label contains a matching value, control is transferred to the default section, if it exists. If there is no default section, no action is taken and control is transferred outside the switch statement.

public class Example
{
static void Main(string[] args)
{
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("You Failed!");
break;
}
}
}
/* Output
Well done
*/


Key points about Switch statement

Each case label specifies a constant value. A switch statement can have multiple switch sections, and each section can have one or more case labels. Unlike C and C++, C# does not allow continuing execution from one switch section to the next. It means each switch section must be separated by a break or other jump statement such as goto, return and throw. Unlike If-Else-If ladder, it is not mandatory to put more specific case at the top and generalize case at the bottom since all the switch cases have equal precedence.


Asp.Net MVC Validation Compare Passwords Example

Once we add new model open it and write code like as shown below.


using System.ComponentModel.DataAnnotations;

namespace MVCExamples.Models
{
public class UsersModel
{
[Key]
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
[Compare("Password",ErrorMessage= "Both Password and Confirm Password Must be Same" )]
public string ConfirmPassword { get; set; }
public string Location { get; set; }
}
}


Now open new controller and write the code like as shown below


using System.Web.Mvc;

namespace MVCExamples.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
public ActionResult UserRegistration()
{
return View();
}
}
}

Now right click on UserRegistration method and select Add View

Once click Add View new template will open in that select Template type “Create” and Model class as our “UsersModel” and click Add like as shown below.


jQuery Get All Images (img) Src in Div


$('#divimages').children('img').map(function () {
return $(this).attr('src')
}).get()


<html>
<head>
<title> jQuery Get All the Images in One Div </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#btnGet').click(function () {
var imgs = $('#divimages').children('img').map(function () {
return $(this).attr('src')
}).get()
alert(imgs);
})
})
</script>
</head>
<body>
<b> Get All the Images in Div </b>
<div id="divimages">
<img src="test.png" />
<img src="test2.jpg" />
</div>
<input type="button" id="btnGet" value ="Get Images" />
</body>
</html>



jQuery Display Image Based on Image URL with Example

In jQuery to display image based on the image url entered in textbox we need to write the code like as shown below


<script type="text/javascript">
$(function () {
$('#btnShow').click(function () {
$("#imgTest").attr("src", $("#txtUrl").val());
})
})
</script>

If you want complete example to show the image based on the image url entered in textbox we need to write the code like as shown below

<html>
<head>
<title> jquery show image from url entered in textbox </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(function () {
$('#btnShow').click(function () {
$("#imgTest").attr("src", $("#txtUrl").val());
})
})
</script>
</head>
<body>
<div>
Enter Image URL:<input type="text" id="txtUrl" /> <input type="button" id="btnShow" value ="Show Image" />
</div><br />
<img id="imgTest" />
</body>
</html>



Thursday 1 December 2016

How to Login with LinkedIN in mvc

Let’s first establish what the purpose of this code is, in the first place. For this article, the purpose of the code is to Sign in / Login with LinkedIn, in MVC.

Step 1

First, you need to create an empty MVC application.

  1. On the File menu, click New Project.

  2. In the New Project dialog box, under Project types, expand Visual C#, and then click Web. In the Name box, type "DemoLinkedINLogin", then click on OK.

  3. Now, in the dialog box, click on "MVC" under the ASP.NET 4.5.2 Templates. Then, click on "Change Authentication" on the center of the right side. Select "No Authontication".

Step 2

For signing in / logging in with LinkedIn, first of all we need to create an app in our LinkedIn & then, we need client_id and client_secret of that app. So, here we go for creating an app in Google account.

  1. Log into your LinkedIn account. Use the below link for the same.

    Developer LinkedIN Account

  2. Click on "My Apps" on top menu.

    linkedin

  3. Now, create an app for login API. Click on "Create Application".

    linkedin

  4. Fill all the fields for our new application.

    Note - Enter your localhost URL in "Website URL". After filling the form, click on "Submit" button.

    linkedin

    Now, we need to enter the redirect URL for OAuth 2.0 -- Authorized Redirect URLs:
    linkedin

  5. Finally, you got your client_id and client_secret. As per your need,   select "Default Application Permissions".

    linkedin

Step 3

Now, it's Code Time! Before we start the code, we need to note that LinkedIn Login API relies on OAuth 2.0 protocol for granting access.

  1. So, we need to install RestSharp Library because we use RestAPI for OAuth 2.0. For the same, go to Tools > NuGet Package Manager > Package Manager Console.

    Type "Install-Package Restsharp" and hit Enter.

    linkedin

  2. Then, we need to request the Authorization Code.

    URL(GET)

    https://www.linkedin.com/oauth/v2/authorization

    Parameter

    1. response_type: code  
    2. client_id: Your client id  
    3. redirect_uri: Return url of your website  
    4. scope: r_basicprofile  
    Create an Action Method as Below.
    1. public ActionResult LinkedIN() {  
    2.     //Need to install below library  
    3.     //Install-Package Restsharp  
    4.     return View();  
    5. }  
    6. Add View  
    7. for that action method Paste Below code in LinkedIN.cshtml < html > < head > < title > LinkedIN Login API < /title> < /head> < body > < div > < a href = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=enter your client id here&redirect_uri=enter your redirect url here&state=987654321&scope=r_basicprofile"  
    8. class = "btn btn-primary" > Hureee!Login with LinkedIN < /a> < /div> < /body> < /html>  

  3. So. we have already requested for an Authorization code in the above code. Now, we need to handle Response of that request. We got code and state parameter in response.

    By using the below code, we can get "access_token". Then, by using access_token, we can get the basic information about the user.

    Here we go.
    1. Create an ActionResult method to handle Authorization.  
    2. public ActionResult LinkedINAuth(string code, string state) {  
    3.     //This method path is your return URL  
    4.     return View();  
    5. }  

    First, we need to get access_token for same we use RestAPI

    URL(POST)

    https://www.linkedin.com/oauth/v2/accessToken

    Parameter
    1. grant_type: authorization_code  
    2. code: code that is get from Authorization response  
    3. redirect_uri: Return url of your website  
    4. client_id: your client id  
    5. client_secret: your client secret  
    6. public ActionResult LinkedINAuth(string code, string state) {  
    7.     //This method path is your return URL  
    8.     try {  
    9.         //Get Accedd Token  
    10.         var client = new RestClient("https://www.linkedin.com/oauth/v2/accessToken");  
    11.         var request = new RestRequest(Method.POST);  
    12.         request.AddParameter("grant_type""authorization_code");  
    13.         request.AddParameter("code", code);  
    14.         request.AddParameter("redirect_uri""http://localhost:57633/Home/LinkedINAuth");  
    15.         request.AddParameter("client_id""your client id here");  
    16.         request.AddParameter("client_secret""your client secret here");  
    17.         IRestResponse response = client.Execute(request);  
    18.         var content = response.Content;  
    19.     } catch () {  
    20.         throw;  
    21.     }  
    22.     return View();  
    23. }  

    We got the access_token. Now, we get "basic profile detail" of user based on access_token using RestAPI.

    URL(POST)

    https://api.linkedin.com/v1/people/~?oauth2_

    Parameter
    1. access_token: access token that is get from above response  
    2. code: code that is get from Authorization response  
    3. format: json  
    4. public ActionResult LinkedINAuth(string code, string state) {  
    5.     //This method path is your return URL  
    6.     try {  
    7.         //Get Accedd Token  
    8.         var client = new RestClient("https://www.linkedin.com/oauth/v2/accessToken");  
    9.         var request = new RestRequest(Method.POST);  
    10.         request.AddParameter("grant_type""authorization_code");  
    11.         request.AddParameter("code", code);  
    12.         request.AddParameter("redirect_uri""http://localhost:57633/Home/LinkedINAuth");  
    13.         request.AddParameter("client_id""your client id here");  
    14.         request.AddParameter("client_secret""your client secret here");  
    15.         IRestResponse response = client.Execute(request);  
    16.         var content = response.Content;  
    17.         //Get Profile Details  
    18.         client = new RestClient("https://api.linkedin.com/v1/people/~?oauth2_access_token=" + linkedINVM.access_token + "&format=json");  
    19.         request = new RestRequest(Method.GET);  
    20.         response = client.Execute(request);  
    21.         content = response.Content;  
    22.     } catch () {  
    23.         throw;  
    24.     }  
    25.     return View();  
    26. }  
All done....


Server Sent Events In MVC

Introduction

In some web applications we need to show real time data to end users. Means if any changes occurs(new data available) in server, it needs to show end user. For instance, you are doing chat in Facebook in one tab of your browser. You opened another tab in same browser and send an a message to same user(with whom you doing chat in previous chat). You will see that message will appear in both the tabs and it is called real-time push.

In order to accomplish above functionality, client sends interval basis AJAX request to server to check if data available. ServerSentEvents(SSE) api which helps server will push data to client when data is available in server.

What is Server Sent Events?


SSE is an acronym and stands for Server Sent Events. It is available in HTML5 EventSource JavaScript API. It allows a web page to get updates from a server when any changes occurs in server. It is mostly supported by latest browsers except Internet Explorer(IE).

Using code

We are going to implement requirement like: there is a link button and click on it, it displays current time in each second interval basis.

In order to achieve the same, we need to add following action in HomeController. It sets response content type as text/event-stream. Next it loops over date and flushes data to browser.
  1. public void Message()  
  2. {  
  3.     Response.ContentType = "text/event-stream";  
  4.   
  5.     DateTime startDate = DateTime.Now;  
  6.     while (startDate.AddMinutes(1) > DateTime.Now)  
  7.     {  
  8.         Response.Write(string.Format("data: {0}\n\n", DateTime.Now.ToString()));  
  9.         Response.Flush();  
  10.   
  11.         System.Threading.Thread.Sleep(1000);  
  12.     }  
  13.       
  14.     Response.Close();  

Once we are done with server side implementation, it's time to add code in client side to receive data from server and displays it.

First it adds a href link which calls initialize() method to implement SSE. Second it declares a div where data will display. Thirdly, it implements Server Sent Events(SSE) through javascript with below steps.
  • In first step it checks whether SSE is available in browser. If it is null then alert to end user to use other browser.
  • In second setp, if SSE is available then it create EventSource object with passing URL as parameter. Next it inject following events.

    • onopen it calls when connection is opened to server
    • onmessage it calls when browser gets any message from server
    • onclose it calls when server closes the connection.
  1. <a href="javascript:initialize();" >Click Me To See Magic</a>  
  2. <div id="targetDiv"></div>  
  3.   
  4. <script>  
  5.       
  6.     function initialize() {  
  7.         alert("called");  
  8.   
  9.         if (window.EventSource == undefined) {  
  10.             // If not supported  
  11.             document.getElementById('targetDiv').innerHTML = "Your browser doesn't support Server Sent Events.";  
  12.             return;  
  13.         } else {  
  14.             var source = new EventSource('../Home/Message');  
  15.   
  16.             source.onopen = function (event) {  
  17.                 document.getElementById('targetDiv').innerHTML += 'Connection Opened.<br>';  
  18.             };  
  19.   
  20.             source.onerror = function (event) {  
  21.                 if (event.eventPhase == EventSource.CLOSED) {  
  22.                     document.getElementById('targetDiv').innerHTML += 'Connection Closed.<br>';  
  23.                 }  
  24.             };  
  25.   
  26.             source.onmessage = function (event) {  
  27.                 document.getElementById('targetDiv').innerHTML += event.data + '<br>';  
  28.             };  
  29.         }  
  30.     }  
  31. </script> 
 
 
 
Figure1: Displays current time

Conclusion

Here we discussed about SSE(Server Sent Events). It is very important API available in HTML5. It helps to push data from server to client when any changes occurs in server side. If you want to use a bidirectional communication channel you can use the HTML5 Web Sockets API. Disadvantage of SSE is it browser dependent. If browser doesn't support SSE then user can't see data, but it is easy to use it. You can also use SignalR for realtime pushing data to end user.

Hope this helps.