Tuesday, May 31, 2011

Parallel Processing in .NET 4.0

I was reading about the new features of .net 4.0 today and found the new parallel processing feature really interesting. The new parallel processing class is called “Task” and it is available in the namespace “System.Threading.Tasks”

The example given below is a comparison of how functions are called in thread model and in the new parallel task way. Though I have included the time taken for to execute the task by each method (thread and task), this example is not specifically to compare performance. It is more about the difference in invoking functions.

I used VS2010 express edition for this test. Though it is easy to do the threading tests in console application, I did this in web application. I implemented ‘ICallbackEventHandler’ and did the example in the “RaiseCallbackEvent” function. For simplicity you can use a console application also.

1) Create a function which does looping as given below

 public string Task1(int iCount)
            DateTime dtStart = DateTime.Now;
            StringBuilder oBuilder = new StringBuilder();
            for (int i = 0; i < iCount; i++)
            DateTime dtEnd = DateTime.Now; 
            string strReturn = "Time Taken for Method2 " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString(); 
            return strReturn;
2) Since the “ThreadStart” object takes a pointer to void function, I created 4 other functions to test “Thread”
private void Task1Thread()
str1 = "\n" + Task1(500000);
private void Task2Thread()
str2 = "\n" + Task1(600000);

private void Task3Thread()
str3 = "\n" + Task1(700000);

private void Task4Thread()
str4 = "\n" + Task1(800000);
3) And then I wrote the code to call the functions as below.
DateTime dtStart = DateTime.Now;
switch (eventArgument)
case "1":// sequential 
data = Task1(500000);
data = data + "\n" + Task1(600000);
data = data + "\n" + Task1(700000);
data = data + "\n" + Task1(800000);
case "2": //Task - the NEW parallel processing way in .NET 4.0

Task<string> mytask1 = Task<string>.Factory.StartNew(() => Task1(500000));
Task<string> mytask2 = Task<string>.Factory.StartNew(() => Task1(600000));
Task<string> mytask3 = Task<string>.Factory.StartNew(() => Task1(700000));
Task<string> mytask4 = Task<string>.Factory.StartNew(() => Task1(800000));

data = mytask1.Result;
data = data + "\n" + mytask2.Result;
data = data + "\n" + mytask3.Result;
data = data + "\n" + mytask4.Result;

case "3":// Thread – common method of multi threading in .NET 1.1, 2.0

Thread oThread1 = new Thread(new ThreadStart(Task1Thread)); 
Thread oThread2 = new Thread(new ThreadStart(Task2Thread));
Thread oThread3 = new Thread(new ThreadStart(Task3Thread));
Thread oThread4 = new Thread(new ThreadStart(Task4Thread));



data = str1 + str2 + str3 + str4;

DateTime dtEnd = DateTime.Now;
string finalTime = "Total Time Taken - " + dtStart.ToLongTimeString() + "- " + dtEnd.Subtract(dtStart).TotalMilliseconds.ToString();

data = data + "\n" + finalTime;

You can see that calling methods using “Task” object is much easier than thread. And also its more efficient than using thread.

Friday, May 20, 2011

ASP.NET and HighCharts

High charts (http://www.highcharts.com ) is a really nice tool to generate graphs/reports on web applications. This article is about how to use high charts in ASP.Net and also shows how to pass data from .net to high chart control (JS/JQuery function) using JSON.

The charts generated by HighCharts control are really nice and have lots of client side features like zoom, selecting/highlighting series etc.

Before starting the example, we need two JS files for this. Both can be obtained from high charts website (http://www.highcharts.com ). The javascript file required are ‘highcharts.js’ and ‘jquery-1.4.1.min.js’

Ok..now let us develop an ASP.NET web application which displays high-chart graph.

1 Create a new web application using Visual Studio

2 Include the two js files inside the head tag of default.aspx

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="Scripts/highcharts.js"> </script>

3) Now we need X and Y coordinate data to generate the graph. Let us first create X-axis data. Since we are going to generate a revenue graph, let us include year as X-axis. Add the below code in code behind page, in page_load event

/*X axis coordinates*/
List<int> lstXaxis = new List<int>();

4) Create public properties for X and Y axis so that they can be accessed from aspx page.

public string Series1 { get; set; }
public string Xaxis { get; set; }

5) Using JavascriptSerializer, convert the x-axis data to Json

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
Xaxis= oSerializer.Serialize(lstXaxis);

6) Let us now generate Y-axis data (revenue data). Create a class to store the Y-axis data

public class ChartEx
public string name { get; set; }
public List<int> data{ get; set; }

7) Fill Y-axis object with data and serialize it using Javascript serializer

/*Series1 - Yaxis*/
ChartEx oEx = new ChartEx();
oEx.data = new List<int> ();

oEx.name = "Revenue";

JavaScriptSerializer oSerializer1 = new JavaScriptSerializer();
Series1= oSerializer1.Serialize(oEx); ;

8) Create a div container in aspx page. The graph will be rendered in this container.

<div id="container" > </div >

9) Now call the Javascript function to draw the graph and pass the serialized C# object to javascript function. (Place the below code inside script tags)


function DrawMyGraph1 () {

chart = new Highcharts.Chart({
chart: {
renderTo: 'Container',
defaultSeriesType: 'area'
title: {
text: 'Revenu'
subtitle: {
text: 'Source: Test '
xAxis: {
categories: <%=Xaxis %>
yAxis: {
title: {
text: 'Revenue Vs Profit'
tooltip: {
formatter: function () {
return this.series.name + ' produced ' +
Highcharts.numberFormat(this.y, 0) + 'revenue in ' + this.x;
series: [<%=Series1 %>]

Done ! Now run the application and you can see the hightchart graph rendered in UI.

There are a lot of useful client side functionalities provided by this graph component like - zooming , highlighting specific graphs etc. Try it out an you will be amazed by how powerful this tool is.

Thursday, May 19, 2011

Video Streaming in ASP.NET using Silverlight

This article is about how to use Silverlight to stream videos in ASP.Net application.

I used Visual Studio 2010 express edition and Silverlight 4.0 (ASP.NET 4.0) for this example. In below example we will just focus on a simple video streaming example. We will look at how to implement progress bar, stop/start buttons etc in another post.

So, let us look at how to create an ASP.NET web application with video streaming.

1 Create a new Silverlight application from Visual studio 2010. Visual studio creates a test web application to test the Silverlight application. So you will have two projects in the solution.

2 In MainPage.xaml ,drag and drop the media element from toolbor. Or include the below XAML in the page

<MediaElement Height="153" HorizontalAlignment="Left" Margin="24,150,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="462" AutoPlay="true" />

3. We have to now provide the video file path for the media element to play . For this test, I copied a video clip to a folder named “Video” in the test web application. Note that I did not copy the file to the Silverlight project folder, but it was placed inside the test web application.

4. Get the URL for the video file. (For my test it was http://localhost:[portnumber]/Video/WindowsMedia.wmv")

5.Set the path of the video file in the MediaElement.

<MediaElement Height="153" HorizontalAlignment="Left" Margin="24,150,0,0" Name="mediaElement1" VerticalAlignment="Top" Width="462" Source="http://localhost:[portnumber]/Video/WindowsMedia.wmv" AutoPlay="False" / >

That’s it ! Now run the application and you can see the video getting rendered in the web site.

We will look into how to implement progress bar , start/stop buttons etc in another post. Till then, happy coding!

Tuesday, May 17, 2011

ASP.NET and Json

JSON (Javascript Object Notation) is a language independent open standard for representing data. It is human readable and light weight compared to XML. JSON can be used to serialize objects and transmit data.

So - how do you convert .net objects to JSON and pass to javascript function. I could not find a good/simple example on this, which lead me to write the below example.

As always – lets go directly to example and see JSON and .net at work .

1) Create an ASP.Net application. Create a class which we will pass to javascript (client side) as JSON
public class ChartEx
public string name { get; set; }
public List<int> data{ get; set; }

2) In the page load of default.aspx ,create an instance of the object and fill data
ChartEx oEx = new ChartEx();
oEx.data = new List();

oEx.name = "Revenue";

3) Create a public property for the page.

public string Series1 { get; set; }

4) Serialize the object using Javascript serializer (in namespace Sytem.Web.Script.Serialization) And set serialized data to the public property.

JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string strData = oSerializer.Serialize(oEx);
Series1 = strData;

5) Access the public property from ASPX page JS function inside script block
function ShowAlert()
var sdata =<%=Series1 %> ;

6) And call the js function in Load event of the page as given below.
<body onload="ShowAlert();">

Run the application and we can see that the .net object is serialized to a JSON object which can be now be used by a JS function. Isn’t that awesome (and easy)?

Monday, May 2, 2011

jQuery Basics

I wanted to learn jquery for long time, but kept postponing since it is possible to do most of the normal client functions that I do (like validation, showing alerts, pop up etc) using classic javascript itself. But when it comes to complex functions (like fading out/fading in controls or animation), doing it in javascript becomes difficult. And you have to worry about browser compatability too.

Thats the reason why I started to learn jQuery.... and it was pretty easy and really helpful.

Given below are the steps that I followed in creating a simple example.

1) The first thing to do is to download the jquery Js file from http://jquery.com/. (When I downloaded the file the version was "jquery-1.5.1.min.js")

2) Create an html file and include the download js file in the html file

<script src="Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>

Ok... now we are ready to start using jQuery. Elements are accessed in jQuery as $("#controlId")... the same code in javascript would be "document.getElementById("controlId").

3) Let us set a value in textbox using jQuery

a) First Create a textbox and button control in html as given below

<input type="text" id="txtBox1" value="test" />

<input type="button" value="Set Value" onclick="SetValue();" />

b) Set text "Hello World" in text box using jQuery as given below

function SetValue() {
$("#txtBox1").val("Hello world")

Wasn't that easy. Let us look at some other simple functions of jQuery.

Fade Out

function FadeOut() {

Fade In

function FadeIn() {

Let us now see how to animate a div

Include a div element in html
<div id="divAnimate" class="ui-dialog" style="display:none;border:1px solid gray;width:0px;">
<div class="ui-widget-header" style="width:300px;">
Just a box

Include 2 buttons to invoke 'hide' and 'display' animations

<div class="codeBlock">
<input type="button" value="Animate-Display" onclick="Animate_Display();" />
<input type="button" value="Animate-Hide" onclick="Animate_Hide();" />
</div >

Include script for "hide" and "display" functions

function Animate_Display() {
$("#divAnimate").css({ "display": "block", "overflow": "auto" });
$("#divAnimate").animate({ width: "300px",height:"300px" }, 1000);
function Animate_Hide() {
$("#divAnimate").animate({ width: "0px", height: "0px" }, 1000, function() {
function Animation_Complete() {
$("#divAnimate").css({ "display": "none", "overflow": "auto" });