Free E-Book from Microsoft on Parallel Programming

Leave a comment

Design Patterns for Decomposition and Coordination on Multicore Architectures
Colin Campbell, Ralph Johnson, Ade Miller and Stephen Toub. Foreword by Tony Hey
A book that introduces .NET programmers to patterns for including parallelism in their applications. Examples of these patterns are parallel loops, parallel tasks and data aggregation with map-reduce. Each pattern has its own chapter. Each chapter includes a description of the problem, an example of where the pattern is applicable, and code that implements the solution. On this site you will find; a preliminary draft of the book, the accompanying code samples and answers to the end of chapter questions.

You can read this book for from following URL

http://msdn.microsoft.com/en-us/library/ff963553.aspx

Parallel Programming Framework 4.0 Part 3 – ParallelLoopSate

Leave a comment

Control over program execution is very important. These things we are listening and learning from the time we started with programing. We used to control the execution with the help of If else, Switch, loops. In the case of loops we used to break the execution of the loop with the help of break keyword.

But in case of Parallel programming things are bit different. We can’t use break in Parallel.For or Parallel.ForEach. Solution for this problem is using ParallelLoopState Class. The instance of this class is provided within the body of the loop by Parallel class itself.

Have a look to the following example



class Program·
{
static void Main(string[] args)
{
long size = 0;

string[] urls = { 
"http://towardsnext.wordpress.com",                                  
"http://yahoo.com",                                  
"http://microsoft.com",                                  
"http://google.com",                                 
"http://aol.com",                                 
"http://rediff.com"                              
};

Parallel.ForEach(urls, (url, parallelLoopState, index) =>
{

if (size > 100000)
{
                    parallelLoopState.Stop();·
Console.WriteLine("Breaking Thread, Index Cancelled : " + index.ToString());
}
else

WebClient client = new WebClient();·
Console.WriteLine("Element Index : {1} Downloading : {0} ", url, index);
                    size += client.DownloadString(url).Length;·

Console.WriteLine("Total Size downloaded till now: " + size);
}
});

Console.ReadLine();
}

In this example we are having three parameter url, parallelLoopState and index



url is a data we passed to this body delegate

parallelLoopSate is the instance of the ParallelLoopState class provided by the Parallel Class 

index of the element of that datasource on which we are running are parallel for each. It tell on which element of the source this current body loop is working on

In the above sample we are checking about the size of the content downloaded till now, if it is going beyond 100000 bytes we are telling to the loop to stop iterating further. We achieved this by using parallelLoopState.Stop() function. There is another function available to perform the same task parallelLoopState.Break().

Yes you are right there is a difference between parallelLoopState.Stop() and parallelLoopState.Break(). in case parallelLoopState.Break we use it typically where data source is ordered and if we call break in the loop on 5th element then all the element further to that will not be executed but below and upto 5th element (means 0-4) will be executed, where as in case of parallelLoopState.Stop it will let no other iteration further.

Parallel Programming Framework 4.0 Part 2 – Parallel.ForEach

Leave a comment

Let us talk about Data Parallelism, which means concurrent opertaion over collections, array etc.

Parallel.For and Parallel.ForEach, These methods are available in the System.Threading.Tasks.Parallel class. While working with Parallel for or Parallel foreach collections or array are partitioned so that multiple threads can work concurrently on it. We will talk about how to use the parallel foreach as well as about other functionality associated with it

To understand more about it, let us look at the example given below. In this example we have to download the webpages content and for this we will use parallel.foreach



using System;
using System.Net;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication1
{    
class Program    
{        
static void Main(string[] args)        
{            
string[] urls =  { "http://towardsnext.wordpress.com",                                  
"http://yahoo.com",                                  
"http://microsoft.com",                                  
"http://google.com",                                 
"http://aol.com",                                 
"http://rediff.com"                              
};            

Stopwatch stopWatch = new Stopwatch();            

//Regular foreach and downloading content            
Console.WriteLine("Regular Foreach");
            stopWatch.Start();            
foreach (string url in urls)            
{                
WebClient client = new WebClient();                
Console.WriteLine("Downloading : " + url);
                client.DownloadString(url);            
}            
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());
            stopWatch.Stop();            

Console.WriteLine("Parallel Foreach");
            stopWatch.Restart();            
Parallel.ForEach(urls, url =>            
{                
WebClient client = new WebClient();                
Console.WriteLine("Downloading : " + url);
                client.DownloadString(url);            
});            
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());
            stopWatch.Stop();            

Console.ReadLine();        
}    
}
}

Output :


In this sample program we have used foreach as well as parallel.foreach. In this case Parallel.foreach will be faster since it will instantiate more than one task to download the webpages where as in normal or regular foreach it will be downloading one by one.

Parallel Programming Framework 4.0 Part 1

Leave a comment

Parallel Programming is a one of the major thing in discussion now a days. Framework 4.0 is having Parallel Programming as one of the major feature. As we know that now a days computers are having multi-cores (dual ,quad and even more) and in near future the number of cores will increase significantly. To Leverage these advantage of hardware microsoft has given the library to support the enhanced parallel programming. It includes, new runtime, new class libraries and diagnostic tools.

These will help developer to write efficient code to get maximum out of the machine without getting into difficulties of the threading and thread pools. Architecture of the parallel computing by microsoft

High level Architecture

We can start our Journey with Task Parallel library (TPL). User can use TPL to get the maximum performance from the code by adding parallelism and concurrency to the applications. It will help user(developers) to utilize all the processors that are available. TPL can partition the work, schedule the threads on the thread pools, state management and cancellation and various low level details. In this way TPL hides complexity of the low level handling of the threads and scheduling

Parallel programing using TPL is very much useful to achieve full utilization of the processors, but doing parallel code for simple tasks will have negative effect on the performance. So we have to look for a need and place where we should implement it.

Google Maps with ASP.NET MVC

Leave a comment

ASP.Net MVC

Once again i am back to my blog. In these days i was working on my project, which i developed using ASP.NET MVC. In that project i was in need of using google maps, for which i tried some of the things and i was able to use it. So i want to share that part with you. In this post i will be telling about “how to use the Google maps with ASP.net MVC”. It is a very simple application in which we will just put the marks(push pin) on the map and will send them back to controller to save them. Later on those can be again used to show it back in the Maps.

Google Map

First we will start with creating a new MVC project. To get the mark form the user we have to show him a map(google). To show him the map we are going to use the javascript function and for that we have to include the javascript api file given by google. http://www.google.com/jsapi?key=[You Key]. You have to get this key from the google so that you can access the map api. http://code.google.com/apis/maps/signup.html

After creating a new project open the index.aspx page in the view section of the project. There in the source view add the following code to get the map

with following lines we are adding the API file


<asp:Content ID"indexHead" ContentPlaceHolderID="HeadContent" runat="server">

<script type="text/javascript" src="http://www.google.com/jsapi?key=[YourKey]"></script>

Following is the code to load the google map in the webpage. You can get the same code from google documentation also with more extra functions and features. But what extra we are doing here is, we are adding all the points in the array so that we can send it back to the controller.


<script type="text/javascript">
var allMarks = [];
google.load("maps", "2");

//This function will help us to add the mark at
//location where user has double clicked. Then
//we will add all the marks in our array so that
//we can send it back to the controller
function initialize() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
map.setUIToDefault();
GEvent.addListener(map, "dblclick", function(overlay, latlng) {
if (latlng) {
var mark = new GMarker(latlng);
allMarks.push(latlng);
map.addOverlay(mark);
}
});

}
google.setOnLoadCallback(initialize);

Following function is used for sending the data to the controller. It is ajax call with the data as the array and the description. We will be calling the controller with action name. Here we are creating a object GMap containing the data


//This function will be called for saving the mark
//for that it will send the data back to the controller
function saveMap() {

//gmap object with all values of the map mark
var gmap = {
Locations: allMarks,
Description: Description.value
}

//Ajax call for saving the data at the server. It will send the gmap
//object tot the server
            $.ajax({
type: "POST",
url: "/Home/Create",
data: gmap
});
}
</script>

</asp:Content>

That is it. After doing all this we have to write one create function in the HomeController.cs class. Have a look to the following code


public ActionResult Create(GMap gmap)
{
Session["MapData"] = gmap;
return View();
}

As you can see here we have used a GMap type. That type you can create as following


public class GMap
{
public object[] Locations { get; set; }
public string Description { get; set; }
}

Finally we are done with it. Now you can see the following screenshots to get an idea how it is working. Also you can download the sample from here

Google Map in ASP.NET MVC application

Action getting data from the webpage

.Net RIA Service Part 1

Leave a comment

What is a .Net RIA Service

It is set of libraries and tools given, to help develop the Rich internet application in much easier fashion. When we develop silverlight application we need to interact with the server for various reasons. Now .Net RIA Service will make that much easier and better.

In our normal silverlight application we used to interact with the server from the client code to move data in async fashion and managing it. But now .NET RIA Service will just hide it all from you and handles all those stuff. You can concentrate more on what to do with data rather than how to get the data.

It is link between the presentation layer and business logic layer. You can add various kind of validation also to be performed.

you can download these services from here

Now i am developing sample application of RIA Service with silverlight and will post it with complete working details of .net RIA Service

Exam Time

2 Comments

Exams

Hi all i am back now. Sorry for so much of delay :) But in these days i went through various new technologies. Now i will posting on that. First i will post on .NET RIA Service and further on WCF. If anything specific leave a comment for me.

Hi everybody. Thanks for visiting the blog. I am busy with exams so i will not be able to post new articles for few days. But i will try to post various good and nice article listed as soon as possible.

I have a list of nice articles to be posted mainly on following

MVC, JQuery, RESTful Service, RIA Service, WebServices, And others

If you want me to post on some specific topics or issue please leave a comments.

Glimmer jQuery Effects Designer

Leave a comment

Glimmer tool for creating interactive elements using JQuery

Glimmer tool for creating interactive elements using JQuery

It is tool which helps to create interactive elements in the webpage. It is nice tool developed in WPF. You can insert various effects too

Check the following screen shots and visit the glimmer website and check the video. also you can download setup from here

Its a nice tool check at mix

Sample Screen shots of glimmer.

Image Sequence Wizard

Image Sequence Wizard

Event Calendar in MVC application Using jMonthCalendar(JQuery)

18 Comments

A good Jquery plugin is available as Event Calendar which can be download from following location.

http://www.bytecyclist.com/projects/jmonthcalendar/
or
http://code.google.com/p/jmonthcalendar/

I used it in one sample project with MVC and loaded certain events from the controller. Which can in return load from the Model. But for the time being in this sample i returned from the controller it self.


public ActionResult Events(string date)
{
MyEvents event1 = new MyEvents            
{
EventID = 11 ,
StartDate = new DateTime(2009,04,01),
Title = "Meeting with Boss",
Description = "Meeting on product release",
CssClass = "Meeting",
URL= "/Home/EventDetails/11"            
};

MyEvents event2 = new MyEvents            
{
EventID = 12,
StartDate = new DateTime(2009, 04, 01),
Title = "Celebration",
Description = "Fathers birthday",
CssClass = "Birthday",
URL = "/Home/EventDetails/12"            
};

string[] stringlist = new string[2];
stringlist[0] = event1.GetJSONResult();
stringlist[1] = event2.GetJSONResult();

return Json(stringlist);
}


For calling the events it did getJson call from the index page where the jMonthCalendar is shown. It will call one of the function the Controller and in return will get the array of the events which will then be sent to the jMonthCalendar. It will load the events. We can add the URL also so that when user clicks the event he will get the complete detail once again with the help of the controller


<script type="text/javascript">
    $().ready(function() {
var options = {

height: 650,
width: 980,
navHeight: 25,
labelHeight: 25,

onMonthChanging: function(dateIn) {
$.getJSON("http://localhost:1511/Home/Events",
function(data) {

//Array of my events                    
var events = new Array();

//Loop and load all the events and load them into the array
                    $.each(data, function(i, item) {

var oResultData = eval('(' + item + ')');
var event = { "EventID": 5, "Date": oResultData.StartDate,
"Title": oResultData.Title, "URL": oResultData.URL,
"Description": oResultData.Description,
"CssClass": oResultData.CssClass
};

events.push(event);

});

//Load the events into the calendar
                    $.jMonthCalendar.ReplaceEventCollection(events);
$.jMonthCalendar.DrawCalendar(dateIn);
});
return true;
},
onEventBlockOver: function(event) {
return true;
},
onEventBlockOut: function(event) {
return true;
},
onDayLinkClick: function(date) {
return true;
},
onDayCellClick: function(date) {
return true;
}
};

var newevents = [];
$.jMonthCalendar.Initialize(options, newevents);
});</script>


Download the sample from following location

EventCalendar

Here are the screen shot of the application.

Event Calendar in MVC Application

Event Calendar in MVC Application

Detail of selected=

Detail of selected Event

File upload in ASP.NET MVC

21 Comments

Here is a sample for handling upload of a file, In your MVC application. In this sample i used the Dialog box of JQuery, where user will select the file and will click upload


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    

<h2>Files uploaded to server</h2>    

<div id="dialog" title="Upload files">        
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>        
    <% } %>    
</div>
<a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>
</asp:content>


Then we have to handle this request in the respective controller which is specified in BeginForm of our above code (FileContoller) and action name (Upload). Following will be our code in the FileController Controller for the Upload action


public void Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}

RedirectToAction("Index", "File");
}


Download the sample code from here

File upload in MVC with JQuery Dialog

File upload in MVC with JQuery Dialog

Older Entries

Follow

Get every new post delivered to your Inbox.