Wednesday, April 25, 2007

Asynchronous Programming Model - 2.0

I have been reading about the Asynchronous Programming Model in Jeffrey Rithcer's book CLR via C#. I have really enjoyed reading it and i thought of writing something about it.

The Asynchronous Programming Model (APM), as implemented by Delegates, consists of three parts:

- BeginInvoke,
- EndInvoke and
- Rendezvous techniques.

BeginInvoke starts an algorithm, impelmented via a method, on a new thread. EndInvoke retrieves the result of that method. The Rendezvous techniques allow you to determine when the asynchronous operation has completed.

There are three different types of Rendezvous techniques you can use to retrieve the results of an asynchronous delegate invocation

1. Wait Till Completion
2. Polling
3. Method Callback

Wait Till Completion
Wait-Till-Completion is implemented via EndInvoke. Calling this method will block the current thread until the results of the asynchronous method are available. This is the least effective method, because it eliminates all the benefits of APM.
private delegate string StringReturningDelegate();
private void Main()
{
// create an instance of the delegate pointing to a method that takes ten seconds to complete.
StringReturningDelegate fd = new StringReturningDelegate (MethodThatTakes10SecondsToComplete);
// Begin invocation of this delegate
IAsyncResult result = fd.BeginInvoke(null, null);
// Immediately call EndInvoke, which will block for, oh, say, right about ten seconds
string s = fd.EndInvoke(result);
Console.Write(s);
Console.Read();
}
// A method that takes 10 seconds, then returns a string private string.
MethodThatTakes10SecondsToComplete()
{
Thread.Sleep(10000);
return "Done!";
}
Polling
In this technique, you check a property of the IAsyncResult object called IsCompleted. This property will return false until the async operation has completed.

// a delegate for a method that takes no params and returns a string.
private delegate string StringReturningDelegate();
private void Main()
{
// create an instance of the delegate pointing to a method that takes ten seconds to complete
StringReturningDelegate fd = new StringReturningDelegate (MethodThatTakes10SecondsToComplete);
// Begin invocation of this delegate
IAsyncResult receipt = fd.BeginInvoke(null, null);
Console.Write("Working");
// Poll IsCompleted until it returns true; Sleep the current thread between checks to reduce CPU usage
while (!receipt.IsCompleted)
{
Thread.Sleep(500);
// wait half a sec
Console.Write('.');
}
string result = fd.EndInvoke(receipt);
Console.Write(result);
Console.Read();
}
// A method that takes 10 seconds, then returns a string
private string MethodThatTakes10SecondsToComplete()
{
Thread.Sleep(10000);
return "Done!";
}
Method Callback
In this technique, you pass a delegate to the BeginInvoke method that will be called when the asynchronous operation has completed. It will not block your execution, or waste any CPU cycles. This is the most effective emthod of Rendezvous.
//a delegate for a method that takes no params and returns a string.
private delegate string StringReturningDelegate();
private void Main()
{
// create an instance of the delegate pointing to a method that takes ten seconds to complete.
StringReturningDelegate fd = new StringReturningDelegate (MethodThatTakes10SecondsToComplete);
// Begin invocation of this delegate
fd.BeginInvoke(AsyncOpComplete, null);
// Do tons of work here. No, seriously.
Console.Read();
}
/// /// Retrieves the results of MethodThatTakes10SecondsToComplete when called asynchronously/// ///
The IAsyncResult receipt.
private void AsyncOpComplete(IAsyncResult receipt)
{
// Cast to the actual object so that we can access the delegate
AsyncResult result = (AsyncResult)receipt;
// retrieve the calling delegate
StringReturningDelegate gsld = (StringReturningDelegate)result.AsyncDelegate;
// Retrieve our results; this is guaranteed not to block, as the async op is complete
string result = gsld.EndInvoke(receipt);
//write the result to the console
Console.Write(result);
}
// A method that takes 10 seconds, then returns a string
private string MethodThatTakes10SecondsToComplete()
{
Thread.Sleep(10000);
return "Done!";
}

Scientists break internet speed record

A group of researchers in the Internet2 consortium has set a new record for sending data through the Internet at more than nine gigabits per second.The team broke the old record of 7.67 Gbps, which was set last December. Using modified protocols, they were able to send data across a 20,000 mile path at a constant rate of 9.08 Gbps.At this speed, a high definition version of a movie could be downloaded in just a few seconds, instead of over 40 hours on a typical broadband connection.....

Tuesday, April 24, 2007

Google vs. Microsoft: reality check

I know google has been doing great work over the past year or two, but is it that Microsoft is out? I odnt think so. I came across Jobsblog and read quite a few intersting things. I have collected a few of those facts and here they are:

Why Google IS Afraid of Microsoft, Big Time

HIGHLIGHTS FROM THE ARTICLE:
Microsoft pummels Google in the “In-Game Advertsing” space. How? Google buys a small San-Fran company to meet the challenge. Microsoft buys the world-leader in the industry for In-game advertising.
Microsoft delivers a solid uppercut in Voice-activated local directory assistance. How? Google announces an experimental service that may not be available at all times and may not work for all users. (Cute) Microsoft acquires TellMe Networks. Heard of them? Most likely, you’ve been using them for the longest time. Almost half of all directory assistance calls are processed on TellMe’s voice platform, and roughly one in three Americans use Tellme every year to get things done.

Assertion that Microsoft's 'Dead' Doesn't Compute
QUOTES FROM THE ARTICLE:
“When a software runs more than 90% of the desktops on the planet — and will for the foreseeable future — it's simply not dead.”“Windows runs on the vast majority of desktops in the world; Linux and OSX make up less than 10% combined”(Microsoft) “…earned $12.6 billion after taxes in its last fiscal year.

Well this article was written by a guy who currently works for Microsoft (you might have guessed that) and is an ex-googler

Thursday, March 08, 2007

I have been working recently quite extensively on ADO.NET and using data bindings. As we know ADO.NET work very well with DataSets and custom classes to create the entities to represent the data objects. We have decided to use custom classes for our application. We are using object data sources since we have created class entities. I got this piece of code from MSDN which shows a very nice way of using DataBinding. As we can see it is very easy to use and let me tell you from personal experience it is fast as well than using a normal dataset or xml for accessing data.

private void SetupBindings()
{
BindingList orderList =
new BindingList(Order.GetEntityList());
orderBindingSource.DataSource = orderList;
BindingList customerList =
new BindingList(Customer.GetEntityList());
customerBindingSource.DataSource = customerList;
BindingList empList =
new BindingList(Employee.GetEntityList());
employeeBindingSource.DataSource = empList;

}

Thus i reckon .NET winforms provide great support for databindings and it is one of the best options to use.


Wednesday, February 07, 2007

My new PC with Vista Ultimate

Yesterday, i got my shiny new Dell computer with "Windows Vista Ultimate". It is just awesome. It's quite alrite spec machine with Core 2Duo Processor (2.0 Ghz), 2 gig of ram and a 256 mb Nvidia turbocache graphics card.
Windows Vista Ultimate is surely ultimate. It is mind blowing. my favourite key is the windows key and tab, to show multiple windows. The gadgets are obviously cool.
I arranged a short "Windows Vista Launch Event in Croydon". It was nothing official, i just named it as such. My collegaues came over to my palce after work and played around with vista. Even non technical guys are coming today evenning to have a look. Everyone's welcome to come and have a look.....

Saturday, February 03, 2007

Creating custom cultures in .NET

Recently i have been using CultureAndRegionInfoBuilder class to create custom cultures in .NET.

With CultureAndRegionInfoBuilder class you can define a custom culture that is new or based on an existing culture and region. You can specify the culture and region information for example the associated language, sublanguage, country/region, calendar, and cultural conventions to great detail by using specific CultureInfo and RegionInfo classes. The custom culture can also be installed on a computer and subsequently used by any application running on that computer.

I highly recommend using this feature in .NET to create custom cultures for the application.

Wolfgang Loder's Blog

My previous Team Leader Wolfgang Loder has started his new blog. Its called "Loder on Software Development". He has immense software development experience and a great sense of humour too.

His recent entries are:

Video about Rails and Django
Rails - worth the trouble?
Multiple Inheritance with C#
Online Conference AJAX

Check out his blog at:
http://wolfgangloder.wordpress.com/

Do have a read guys and let him know how do you find his posts.

Friday, January 12, 2007

Windows Vista and Office Developer launch - Jan 19-20, 2007

Vista and Office launch time is fast approaching. They are giving FREE copies of Windows Vista and Office for UK developers. As far as i know, attendees to the physical launch will get a choice of either Windows Vista Ultimate, or Office Professional 2007 (but not both). These will be shipped to the attendee after the event. I just cant wait to get my hands on Vista Ultimate.

Tuesday, December 05, 2006

RegistrySecurity class

Recently, i was going through System.Security.AccessControl namespace and i came across DirectorySecurity class, FileSecurity class and RegsitrySecurity class.

I was really impressed by the RegistrySecurity class. it represents the Represents the Windows access control security for a registry key.A RegistrySecurity object specifies access rights for a registry key, and also specifies how access attempts are audited. Access rights to the registry key are expressed as rules, with each access rule represented by a RegistryAccessRule object. Each auditing rule is represented by a RegistryAuditRule object.

This mirrors the underlying Windows security system, in which each securable object has at most one discretionary access control list (DACL) that controls access to the secured object, and at most one system access control list (SACL) that specifies which access attempts are audited. The DACL and SACL are ordered lists of access control entries (ACE) that specify access and auditing for users and groups. A RegistryAccessRule or RegistryAuditRule object might represent more than one ACE.

Monday, October 30, 2006

How cool is that

Heineken is refreshing its supply chain to ensure its beer doesn't reach parts it shouldn't.

Heineken is to trial a tracking system which will tell it exactly where its beer shipments are, even in the middle of the Atlantic. The brewer has deployed the solution to track ten containers full of beer travelling from the UK and the Netherlands to its distribution centre in the US. The project, which it calls "The Beer Living Lab", uses triangulation techniques of both satellites and cellular base stations to locate exactly where the cargo is. The SOA-based architecture will also allow the creation of distributed data sources, rather than Heineken having to run a large central database.

Tuesday, October 03, 2006

Dynamically calling an unmanaged dll from .NET (C#)

I like to keep collecting small snippets of code in my blog, which i know will be useful later on.
Below is the code snippet for "Dynamically calling an unmanaged dll from .NET (C#)" from Jonathans blog on MSDN blogs:

To start and to refresh our memories, let's create a very basic C++ dll that does very little..... your code should resemble the following (check out my previous post for more info on this):

Header file

extern "C" __declspec(dllexport) int MultiplyByTen(int numberToMultiply);

Source code file

#include "DynamicDLLToCall.h"

int MultiplyByTen(int numberToMultiply)
{
int returnValue = numberToMultiply * 10;
return returnValue;
}

As you can probably infer from the function name, an int is passed into this function and it will return the number passed in multiplied by ten. Told you it would be simple.

Now comes the more interesting part, actually calling this dll dynamically from your C# source code. There are two Win32 functions that are going to help us do this:

1) LoadLibrary - returns a handle to the dll in question
2) GetProcAddress - obtain the address of an exported function within the previously loaded dll

The rest is rather simple. We use LoadLibrary and GetProcAddress to get the address of the function within the dll we want to call, and then we use the GetDelegateForFunctionPointer static method within the Marshal class to assign this address to a C# delegate that we define. Take a look at the following C# code:


static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);

[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
}

class Program
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int MultiplyByTen(int numberToMultiply);

static void Main(string[] args)
{
IntPtr pDll = NativeMethods.LoadLibrary(@"PathToYourDll.DLL");
//oh dear, error handling here
//if (pDll == IntPtr.Zero)

IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "MultiplyByTen");
//oh dear, error handling here
//if(pAddressOfFunctionToCall == IntPtr.Zero)

MultiplyByTen multiplyByTen = (MultiplyByTen)Marshal.GetDelegateForFunctionPointer(
pAddressOfFunctionToCall,
typeof(MultiplyByTen));

int theResult = multiplyByTen(10);
Console.WriteLine(theResult);
}
}

The only item worthy of note is the UnmanagedFunctionPointer attribute, which was introduced to version 2.0 of the .NET framework,

Monday, October 02, 2006

Using Settings in C#

The .NET Framework 2.0 allows to create and access values that are persisted between application execution sessions. These values are called settings. We can use settings by accessing the Properties namespace.

There are two types of settings:
Application Settings
User Settings


Settings have four properties:

Name: The Name property of settings is the name that is used to access the value of the setting at run time.
Type: The Type of the setting is the .NET Framework type that the setting represents. A setting can be of any type. For example, a setting that holds a user preference of color would be a System.Color type.
Scope: The Scope property represents how a setting can be accessed at run time. There are two possible values for the Scope property: Application and User. These will be discussed more in this section.
Value: The Value property represents the value returned when the setting is accessed. The value will be of the type represented by the Type property.

Creating a New Setting at Design Time
You can create a new setting at design time by using the Settings designer. The Settings designer is a familiar grid-style interface that allows you to create new settings and specify properties for those settings. You must specify Name, Type, Scope, and Value for each new setting. Once a setting is created, it can be assessed in code using the mechanisms described later in this article.

To Create a New Setting at Design Time

In Solution Explorer, expand the Properties node of your project.
In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, set the Name, Type, Scope, and Value for your setting. Each row represents a single setting.

Changing the Value of an Existing Setting at Design Time
You can also use the Settings designer to change the value of a pre-existing setting at design time, as described in the following steps:

To Change the Value of an Existing Setting at Design Time

In Solution Explorer, expand the Properties node of your project.
In Solution Explorer, double-click the .settings file in which you want to add a new setting. The default name for this file is Settings.settings.
In the Settings designer, find the setting you want to change and type the new value in the Value column.

Changing the Value of a Setting Between Application Sessions
At times, you might want to change the value of a setting between application sessions after the application has been compiled and deployed. For example, you might want to change a connection string to point to the correct database location. Since design-time tools are not available after the application has been compiled and deployed, you must change the setting value manually in the file.

To Change the Value of a Setting Between Application Sessions


Using Microsoft Notepad or some other text or XML editor, open the .exe.config file associated with your application.
Locate the entry for the setting you want to change. It should look similar to the following example:

This is the setting value


Type a new value for your setting and save the file.
Using Settings at Run Time
Settings are available to the application through code at run time. You can access the value of settings with application scope on a read-only basis, and you can read and write the values of user-scope settings. Settings are available in C# through the Properties namespace.

Reading Settings at Run Time
You can read both application-scope and user-scope settings at run time with the Properties namespace. The Properties namespace exposes all of the default settings for the project by using the Properties.Settings.Default object. When writing code that uses settings, all settings appear in IntelliSense and are strongly typed. Thus, if you have a setting that is of type System.Drawing.Color, for example, you can use it without having to cast it first, as shown in the following example:

this.BackColor = Properties.Settings.Default.myColor;

Saving User Settings at Run Time

Application-scope settings are read only, and can only be changed at design time or by altering the .exe.config file in between application sessions. User-scope settings, however, can be written at run time, just as you would change any property value. The new value persists for the duration of the application session. You can persist changes to user settings between application sessions by calling the Settings.Save method. These settings are saved in the User.config file.

To Write and Persist User Settings at Run Time
Access the user setting and assign it a new value, as shown in the following example:
Properties.Settings.Default.myColor = Color.AliceBlue;

If you want to persist changes to user settings between application sessions, call the Save method, as shown in the following code:
Properties.Settings.Default.Save();

Wednesday, September 20, 2006

Scotland Trip (15/09/2006 - 18/09/2006)

Before I forget let me capture the events and moments:

15: Edinburgh castle,
Hollyrood House, Edinburgh chapel
Authentic Fish and Chips.
16: Old town visit, dads office search, Royal botanical garden, Rosilln village and
chapel(The DaVinci Code Chapel), Authentic scottish beers and excellent food,
nightclub with champs.
17: Muselborough village and beach, John Muir Walk, Dad old house search,
Portobello beach, BenBradley, Champs discussion, Lots of beer.
18: Champs shopping. Mum shopping. Dad calling,I drinking.

Thursday, August 31, 2006

1 year since we finished our Masters Degree

Well its been exactly a year when we finished our dissertation and thus our Master's degree. I just cant believe that time has gone by so fast. I still clearly remember we all working like mad to meet the deadline. Jamie was the first one to finish his dissertation in the whole of the uni i reckon. Ben was struggling to finish his dissertation as well. I remember in the start of august, he was already considering toher options. Writing the actual dissertation (the report) was actually the hardest part for me. Champs and BaoYuan had finished their dissertation early and left Hull. ioulieta was as usual so stressed!!!! We have come a long way from that. Ankur and Rob Miles were cool as it goes with their personality. Ankur i reckon spent equal time in lab and in "Fuel" in July. I partied a lot during July to Aug mid and watched loads of wimbledon. But yeah finally we all got there. Congrats people.

And best of luck for years to come.

Saturday, August 19, 2006

Earn or Learn

Though its a saturday, but i had to go to work due to the huge amount of work left to be done with the deadline approaching.

I was chatting to a friend of mine and he said what am i doing in office on saturday .When people get a job, most of them as far as i know enjoy their work for a few weeks and then it becomes routine job for them. The main purpose of job then is to earn a living and be satisfied.

However as i just finished work i was thinking of the difference between the words "Earn" and "Learn". If any of you did not notice what i mean,
Learn = L + earn.
I also need money, i also want to be really rich but......and yes there is a but here.
Since finishing my Masters Degree last year i have been working as a software developer.I see my work as a learning experience through which i earn, and i dont see it as an income source, where i might learn a bit. i am learning every second of my job. i am exploring new ideas and this gives me immense satisfaction.

I thoroughly enjoy my experience of work. What can be better than getting paid for something you like to do for most of the time of your day.
Thus:

Learn = "Earn through what you love to do"
= Loving the work you are doing + earning.

Another thing which i would love to od and get paid for is travelling. Right now iwant to concentrate on my career as a software developer. However in the future it would be nice if somebody paid me to travel all around the world:).

Even better, a job as a professional software developer where i get to travel a lot and meet new people, see new places. That would be a dream come true job.

Wednesday, August 16, 2006

Web2.0



This picture above shows that I am Web2.0 enabled too....

Tuesday, August 15, 2006

Passed my driving test

I have passed my practical driving test. Today was my test at the DVLA croydon centre.

Today 15th of August is India's Independence Day. I am missing the Parade in delhi, which iused ot watch on TV.

Came across this quote on TFS team blog:

“Imagination is more important than knowledge. For knowledge is limited to all we now know and understand, while imagination embraces the entire world, and all there ever will be to know and understand.” - Albert Einstein

Monday, August 14, 2006

IBM PC turns 25. Incredible history on the way

I know, i am a bit late in posting it..but anyway something to be proud of..

It was a match made in computer heaven.
The May-December marriage of a young company called Microsoft and business powerhouse IBM would change the landscape of offices and homes across the globe.
August 12 (today) is the 25th anniversary of the IBM personal computer launch, a pairing of MS and DOS, Microsoft and the disk operating system.
"MS-DOS moved computer access from a community measured in thousands to one measured in millions
"It was a key transition from the hobbyist and 'geek' environment to business applications".

Several popular home computers existed before the 1981 IBM PC launch. But the regimented business world considered Apple, Commodore, and Radio Shack's Tandy products "toys."
The IBM stamp of approval on a personal computer changed that mentality for good.
"Almost overnight, with IBM introducing the PC, it became OK to use it for real business applications," said Tycho Howle, CEO of nuBridges in Atlanta, a provider of business-to-business services.
Howle remembers with fondness his first desktop PC."In 1981 I had an IBM PC, two-floppy system," Howle said."To give young people these days a comparison: It would take 10 of those floppy disks to be able to hold the music that is on one MP3 song," he said.
A floppy disk is a thin, plastic disk that was coated with a magnetic substance used to store data. Earliest disks were 8 inches wide, more efficient disks shrunk to 5 1/4 inches, then 3 1/2 inches. Unlike a CDs or DVDs of today, the disks were floppy, or flexible.
IBM, the 800 pound gorilla of the business world at the time, flooded trade papers and television with promises that this new device would provide "smoother scheduling, better planning, and greater productivity."
Early '80s status symbol, the first available PCs cost between $1,600 and $6,000. Little about this early version was user, but that has changed considerably over time and they are much cheaper now.

Long live the PC........

Windows Live Writer

I just came to know from MSDN blogs that "Windows Live Writer" Beta is available from today 14th August. Windows Live Writer is a desktop application that makes it easier to compose compelling blog posts using Windows Live Spaces or your current blog service.
Teh cool feaure about writer is you can now author your post and know exactly what it will look like before you publish it.Writer makes inserting, customizing, and uploading photos to your blog a snap. You can insert a photo into your post by browsing image thumbnails through the “Insert Picture” dialog or by copying and pasting from a web page.

Thursday, August 10, 2006

Croydon Life

Police looking for human remains are preparing to begin a finger-tip search of the former home of a convicted paedophile in south London - croydon.
Detectives began an investigation after receiving an anonymous letter last year which claimed human remains linked to events 35 years ago were buried there.

Now that is scary..