Sunday, February 24, 2008

Normalization Techniques in C# 3.0

What do you get from this post?

In this post I would talk elaborately about implementing Normalization Techniques like BCNF Decomposition, 3NF Synthesis and pre-requisites like Test for Losslessness, finding minimal cover of a given set of functional dependencies, etc. I would not be posting the entire source code here, as the intention of this post is to help users get started to write "real" code but not to make their life simple by pasting the code. So the code snippets I paste would be "images" and not text! I apologize for my sadism but I would not like it when my students rip off source code off Google and submit it.

Following this would not only help you learn Normalization techniques but also give you better idea about C# 3.0 features and how to apply them in a real situation. If you are looking at this post, then probably you know C#.

What will I learn?

  1. BCNF Decomposition Algorithm
  2. 3NF Synthesis
  3. How to find if a schema is in BCNF?
  4. How to find the minimal cover of the set of functional dependencies?
  5. How to find the closure of an FD?
  6. Using C# 3.0 Extension Methods
  7. Using Object Initializers
  8. Using Lambda Expressions in C#
  9. Using Linq to write compact code
  10. A lot other stuff ....

Did I mention, it took only 540 lines of code to implement both the BCNF Decomposition and 3NF synthesis?

Assumptions

This post assumes you are familiar with what Normalization is. You have a schema R and a set of Functional dependencies, then normalization is a  technique to split the schema R into set of sub-schemas Ri such that each sub schema is in a particular normal form.

Most highly recommended normal forms are the BCNF and 3NF. 3NF is a less strict normal form than the Boyce-Codd Normal form. There are so called the "design algorithms" that researchers have proposed to normalization a given schema.

What is BCNF?

I would not talk about definitions here. If you need elaborate answers then visit this link at Wikipedia. Simply put, a table Ri is said to be NOT in BCNF if there is atleast one functional dependency X->Y that satisfies the schema such that X is not a candidate key. I talked about a relation not being in BCNF because that is what matters during implementation, as you will see later. A positive definition would be : Ri is said to be in BCNF if the Left hand side of all its FDs is a candidate key.

Getting started

Clearly if we are going to implement normal forms, we would need to represent a "Relation", a "Functional Dependency", etc. So the way I organized the system can be seen below. It is a class diagram taken from Visual Studio. Click on the figure below to look at the classes involved.

ClassDiagram

Relation class

The heart of the implementation is the Relation class. Think properly, how do you define relation mathematically? What interests you about relation? Well, for me, I am bothered with the R and the set of functional dependencies and that is what I have in my relation class.

Relation class

You can notice that I have a list of Functional Dependencies. I represent each FD as a seperate class called "FunctionalDependency". Assume for now that you have such a class. So what next? You might be interested to implement a closure algorithm, right? But I implemented in FunctionalDependency class. I would talk about the methods when and where required. For now, let us move on to the other important class

FunctionalDependency class

So again, the same question - What do you think should be the state of an object that represents a functional dependency? Well, again my answer is that it should have LHS,RHS(where LHS->RHS is the FD),  an equivalent "R" which is nothing but LHS+RHS. Also it would be good if we have a member that states if this FD violates BCNF or not? We might also use this member for other instances too where it might violate a different condition. So the functional dependency state would like shown below.

Functional Dependency C#

So why the hell did I  chose R, LHS,RHS all to be strings? An example of R would be like "ABCDEFGH" where each letter corresponds to an attribute. So instead of working hard with a list or an array, it would be easier to work with strings(we have string#ToCharArray() to our rescue). But this would require us to write a set of methods that would let you perform set like operations on the strings. For example, if you merge two schemas "ABC" and "BCD" you expect to get "ABCD". But a string + would give you "ABCBCD". So we need a method like "ABC".SetAdd("BCD") which would give return "ABCD" instead of "ABCBCD". So here comes the extension methods.

How do we implement extension methods in C#?

The important point to remember is that extension methods should be implemented in static classes only. The methods I implemented that perform "set-operations" on strings are SetAdd(),SetMinus(),SetEquals(). The code implemented makes good use of LINQ extension methods. And since I intend to concentrate on Normalization in this post, I would skip detailed explanation about extension methods.

Extension Methods in C#

Note that the class is static and the method is static. Another point to note that the first parameter is marked as "this string" meaning we wish to make SetMinus() as an extension method to the string class. After this, we could use SetMinus() as shown below.

string s = "Krishna";
string output = s.SetMinus("kna");
Console.WriteLine(output);//prints "rish"

In the above method, I am just taking all the characters in the "x" which are not in the string set that is to be "minus"d. See how sweet LINQ and Lambda expressions are.


The other methods are listed. I hope you understand the statements, if not, drop me an email so that I can write down explanation. Note that all these methods are in the same static class StringUtilities.


Extension methods in C#


The SetAdd() makes use LINQ expressions to find all the unique characters that are in setToAdd and that are not in the actual expression. It also makes clever use of LINQ aggregator method Distinct(). One thing I noticed is that as a beginner developer you would pride in writing programs with more lines of code. But as you mature as a developer you would enjoy writing compact code and these days nothing gives me more satisfaction than writing one liner or two liner to do a good job.


Anyway now that we are set to start, we can now look at how decomposition is implemented. For programing sake, I have a super class called Decomposition which can be seen in the class diagram above. The class listing is shown below.


image


The static method GetUnpreservedDependencies() is not yet implemented and the idea is to implement it using Armstrong's axioms.


The method IsLossLess() takes in a Decomposition object and returns true if the decomposition is lossless and false otherwise. This is used to test our implementation of both BCNF decomposition and 3NF Sythesis - both of which are theoretically lossless. The Decomposition class defines an abstract method ApplyDecomposition() which should be implemented by the inheriting classes. It returns the list of decomposed schemas which is also the "DecomposedSchemas" property. I know schemas is not a correct word and a plural for schema is just schema, so forgive me. Now let us look at the BCNF Decomposition algorithm.


BCNF Decomposition in C#


The algorithm to implement BCNF Decomposition is




  1. Add the current relation (of type Relation) to the list of DecomposedSchemas.


  2. Get all the schema that is not in BCNF. Check the Relation for BCNF violation using the method InBCNF(Relation r) which is listed as shown below.
    Test for BCNF C#


  3. If there are no such schema that violate BCNF, then you quit.


  4. For any schema sch that is not in BCNF, do the following steps.



    1. Pick a functional dependency that violates BCNF. There is a method in Relation#GetViolations() that returns a list of violating FunctionalDependencies. Its implementation is shown below.
      Get BCNF Violations
      A dependency "dep" violates BCNF if its closure does not result in R, the actual schema. The closure is computed using all the Dependencies in the relation. It is defined in the FunctionalDependency class as listed below.
      Database Closure in C#
      The algorithm is taken from the book Database Systems:An Application Oriented Approach


    2. Having picked a FD(x->y) that violates BCNF, you now get two relations called r (right) and l (left), where l = FD.EquivalentR (which is x+y) and r = (sch.R - FD.RHS)+FD.LHS (Which is Y). You add both the schema to the DecomposedSchemas collection.


  5. Return the list of decomposed schema.

The code listing for the entire BCNF Decomposition is shown below.
 BCNF Decomposition in C#


Just a recap of what we have seen till now in this post. We have looked at how to compute closure in C#, how to implement the BCNF decomposition algorithm, how to use extension methods, how to use LINQ query to fetch unique characters. For this section, finally we will look at how to test the BCNF Decomposition we implemented. The output you see would be something like this.
BCNF Decomposition Output window
The main method is shown below.
Running the example 


You can see a very badly highlighted method GetRelation3() which returns a Relation. The method listing is shown below. This method also shows on how we actually constructed our relation.
 Object Initializers Usage - relation demo


In the above code you can see other sample relations too. But look at the syntax for Object initializers. (the one marked in yellow). For both Relation as well as FunctionalDependency creation, we have made use of the beautiful initializers saving us atleast 50 lines of code for all the examples.


So how did we test for losslessness?


Testing for losslessness in decomposition


The key is the theorem which states


"If a closure of Ri gives R, then the decomposition is lossless".


The implementation is simple. For all subschema obtained, we compute its closure using the dependencies of the original schema. It the resultant of the closure gives R for any of the subschema, then the decomposition is lossless. Now you might be confused and might be wondering if you need to write new code! to compute closure for schema. The answer is no! remember you have implemented closure method in the FunctionalDependency class. You can create a new FD whose LHS is Ri and RHS is empty and then call the method GetCLosure(). This works like magic and without any additional code! The complete code is listed below. Notice that we are not bothered if the decomposition is BCNF Decomposition or 3NF synthesis. We can check for any such decomposition for its losslessness nature.
Test for losslessness BCNF/3NF Decomposition


Now that we have looked at BCNF Decomposition and also a good C# 3.0 features that enables developers write some good compact code, we would look at 3NF synthesis in the next post. I hope this post is informative enough to get you started. I have shown all the code and with clever reading of Class diagram picture and the snippets you should be able to implement the decomposition algorithm by yourself.

Creating your own XamlPad

When I was learning WPF Development through the Petzold’s book, in Chapter 19 the author talks a lot about XamlReader (and less about Xaml as such ;), Guess Petzold likes to code more than what he likes to design). Anyway during this I implemented my own XamlPad called “Buddi-XamlPad” which has two meanings

  1. Buddi is my nickname
  2. Buddi in Telugu mean “small”.

So the xamlpad is like a small-xamlpad like application. It does nothing but render your xaml and it is really really stupid. If you are looking for a better xamlpad than what that ships with VS SDK, then you better take a look at Kaxaml (notstatic.com) which is very good and it has good Xaml intellisense!

Anyway, lets get started with Buddi-XamlPad.

  1. My application is as shown below.

Capture

  1. You have a class called BuddiXamlPad which has a static method GetXamlWindow(). It returns an instance of Window which you can run in your application by saying “new Application().Run(BuddiXamlPad.GetXamlWindow())”
  2. The code for the BuddiXamlPad class is shown below.
class BuddiXamlPad
{
static Window wi;
static RichTextBox rtb;
static Button outputButton;
public static Window GetXamlWindow()
{
wi =
new Window();
Grid gd =
new Grid();
gd.ColumnDefinitions.Add(
new ColumnDefinition());
gd.ColumnDefinitions.Add(
new ColumnDefinition());

outputButton =
new Button();
outputButton.Content =
"Your XAML output!";
gd.Children.Add(outputButton);
Grid.SetColumn(outputButton,
0);
outputButton.Click += ButtonClick;

rtb =
new RichTextBox();
rtb.Name=
"xaml";
rtb.AcceptsReturn =
true;
gd.Children.Add(rtb);
Grid.SetColumn(rtb,
1);
wi.KeyDown += WinKeyDown;
wi.Content = gd;

wi.Title =
"Buddi rocks with this XamlPad!";
return wi;
}

private static void WinKeyDown(object sender, KeyEventArgs args)
{
if(args.Key == Key.F5)
ProcessXaml();
}
private static void ButtonClick(object sender,RoutedEventArgs args)
{
ProcessXaml();
}
public static void ProcessXaml(){
try{
TextRange tR =
new TextRange(rtb.Document.ContentStart,rtb.Document.ContentEnd);
string xaml = tR.Text;
StringReader reader =
new StringReader(xaml);

//Append Xaml Namespace
XmlDocument xd = new XmlDocument();
xd.Load(reader);
xd.DocumentElement.SetAttribute(
"xmlns","http://schemas.microsoft.com/winfx/2006/xaml/presentation");
StringBuilder sb =
new StringBuilder();
StringWriter sw=
new StringWriter(sb);
xd.Save(sw);

//Now Read the complete XAML.
XmlReader xmlReader = new XmlTextReader(new StringReader(sb.ToString()));
object obj = XamlReader.Load(xmlReader); //Get the objects of the corrs. Xaml
outputButton.Content = obj;
}
catch(Exception ex){ MessageBox.Show(ex.Message);}
}
}

The code is pretty simple, the only problem I initially faced was that I had to add “xmlns” to the WPF namespace to the root of the xaml I write into the RichTextbox, which is kind of lame if not fixed. So I used Xml API to read the Xaml as XML and added the namespace. Isn’t it fun? Not many comments in the code but hey its all like 40-50 lines and I don’t think anyone would be bothered to look at it. Wish, I had time so that I would have done something good but given my masters’ thesis and other projects I do, I hardly have any time left.

Well the point is that it is pretty much possible to write good applications with .NET Framework and with every release it is getting bigger and better. Microsoft Rocks!

Application = Code + Markup : My opinion

I recently started working with Windows Presentation Foundation for a Simulation Project that I would be starting today. I needed to simulate Graph traversal using Animations and with WPF around, doing Graphics would be great and simple. So, I started browsing my University Library for WPF books and could lay my hands upon the awesome book “Application = Code + Markup”. I know WPF Unleashed is a good one but having seen some fight on the blog-world about which book is better; I decided I would be reading both the books and come up with some opinion! I should say Petzold’s book is one of the best you can lay your hands upon. It has no narration or graphics to attract you but it gives you the knowledge that you are looking for. Not once in these 7 years of Professional CS studies did I ever read 4 chapters without a break – I did that now with Petzold’s book. For a person like me who just “glances” books and does not read it, I myself was surprised that I read the chapters so well and took notes, which I would be sharing in this post shortly. I like a book that gives me information in every line that I read. Quiet a lot of books does not do that and tries to sell you the stuff more than to teach you. Anyway Application = Code + Markup is not such a book and it truly is worth every cent you invest in. Another book that I am looking forward is Scott Hanselman’s ASP.NET 3.5 in C# and VB. I preordered it two months back and am eagerly waiting for its release. I hope to fill the gap in my ASP.NET skills with that book. As a resolution I also decided I would post every week about what I did that week.

Friday, February 22, 2008

Creating Reflection in WPF

I have been playing with WPF for a while ... and I could create something like this... a button with reflection.

Thursday, February 21, 2008

Phone Interview Question ...

I read this amazing article on how to get a phone interview right ...
http://steve.yegge.googlepages.com/five-essential-phone-screen-questions

I think it is a must read for everyone - experienced and inexperienced students like myself. I feel I can answer atleast 80% of what is asked over there except the REGEX part of it, which I really have no clue. My RegEx is supported heavily by Google and I somehow feel lazy to learn RegEx. Anyway there was one such question, which I lift from the link i gave above.

Let's say you're on my team, and I've decided I'm a real stickler for code formatting. But I've got peculiar tastes, and one day I decide I want to have all parentheses stand out very clearly in your code.

So let's say you've got a set of source files in C, C++, or Java. Your choice. And I want you to modify them so that in each source file, every open- and close-paren has exactly one space character before and after it. If there is any other whitespace around the paren, it's collapsed into a single space character.

For instance, this code:

foo (bar ( new Point(x, graph.getY()) ));

Would be modified to look like this:

foo ( bar ( new Point ( x, graph.getY ( ) ) ) ) ;

I tell you (as your manager) that I don't care how you solve this problem. You can take the code down to Kinko's Copies and manually cut and paste the characters with scissors if you like.

How will you solve this problem?


My solution is very simple and I do not use RegEx, yet I could complete it in 3-4 minutes. Probably one with RegEx experience can do it in a minute. Also, the code shown below might be bugged and I did not test it yet. So in case you find a bug, let me know before I figure it out myself.

def sampleCode = " foo (bar ( new Point(x, graph.getY()) ));"
sampleCode = sampleCode.replace(" (","(");
sampleCode = sampleCode.replace("( ","(");
sampleCode = sampleCode.replace(" )",")");
sampleCode = sampleCode.replace(") ",")");
sampleCode = sampleCode.replace(")"," ) ");
sampleCode = sampleCode.replace("("," ( ");
sampleCode = sampleCode.replace(" "," ");
println("Expected : foo ( bar ( new Point ( x, graph.getY ( ) ) ) ) ;")
println "Obtained : "+sampleCode.trim()

So do I get a job at Amazon?? Or atleast a phone interview call!

Monday, February 18, 2008

Processing videos in Java

In this post, I would like to share with the visitors on how to

  1. How to load videos into Java using JMF
  2. How to extract frames from a video file like avi,mpg,etc using Java Media Framework.

The class I developed for this purpose is called VideoUtility which is similar to the Image Processing utility I wrote in Java. In order to process Videos in Java, you need to use Java Media Framework, which can be obtained from the Sun Website and should be installed. Note that the JMF sometimes can be installed as a platform dependant package which makes it more efficient than the platform-independent version. Anyway once you download the JMF library, add it to the application classpath. Refer to the code shown below. I appreciate if you keep my copyright intact and if you find proper use of this class, please let me know.

   1: import java.awt.Image;


   2: import java.io.File;


   3: import java.io.FileNotFoundException;


   4: import java.io.IOException;


   5: import java.util.ArrayList;


   6: import javax.media.Buffer;


   7: import javax.media.Manager;


   8: import javax.media.MediaLocator;


   9: import javax.media.NoPlayerException;


  10: import javax.media.Player;


  11: import javax.media.Time;


  12: import javax.media.control.FrameGrabbingControl;


  13: import javax.media.control.FramePositioningControl;


  14: import javax.media.format.VideoFormat;


  15: import javax.media.util.BufferToImage;


  16: /** @author Krishna Vangapandu **/


  17: public class VideoUtility


  18: {


  19:     @SuppressWarnings("deprecation") 


  20: /** * videoFile - path to the video File. */ 


  21: public static Player getPlayer(String videoFile) 


  22:     throws NoPlayerException, IOException


  23:     {


  24:         File f = new File(videoFile);


  25:         if (!f.exists()) throw new FileNotFoundException("File doesnt exist");


  26:         MediaLocator ml = new MediaLocator(f.toURL());


  27:         Player player = Manager.createPlayer(ml);


  28:         player.realize();


  29:         while (player.getState() != Player.Realized);


  30:         return player;


  31:     }


  32:     public static float getFrameRate(Player player)


  33:     {


  34:         return (float)noOfFrames(player)/(float)player.getDuration().getSeconds();


  35:     }


  36:     public static int noOfFrames(Player player)


  37:     {


  38:         FramePositioningControl fpc = (FramePositioningControl)player.getControl("javax.media.control.FramePositioningControl");


  39:         Time duration = player.getDuration();


  40:         int i = fpc.mapTimeToFrame(duration);


  41:         if (i != FramePositioningControl.FRAME_UNKNOWN) return i;


  42:         else return -1;


  43:     }


  44:     /** * * @param player - the player from which you want to get the image 


  45:     * @param frameNumber - the framenumber you want to extract 


  46:     * @return Image at the current frame position */ 


  47:   public static Image getImageOfCurrentFrame(Player player, int frameNumber)


  48:     {


  49:         FramePositioningControl fpc = (FramePositioningControl) player .getControl("javax.media.control.FramePositioningControl");


  50:         FrameGrabbingControl fgc = (FrameGrabbingControl) player .getControl("javax.media.control.FrameGrabbingControl");


  51:         return getImageOfCurrentFrame(fpc, fgc, frameNumber);


  52:     }


  53:  


  54:     public static Image getImageOfCurrentFrame(FramePositioningControl fpc, FrameGrabbingControl fgc, int frameNumber)


  55:     {


  56:         fpc.seek(frameNumber);


  57:         Buffer frameBuffer = fgc.grabFrame();


  58:         BufferToImage bti = new BufferToImage((VideoFormat) frameBuffer .getFormat());


  59:         return bti.createImage(frameBuffer);


  60:     }


  61:  


  62:     public static FramePositioningControl getFPC(Player player)


  63:     {


  64:         FramePositioningControl fpc = (FramePositioningControl) player .getControl("javax.media.control.FramePositioningControl");


  65:         return fpc;


  66:     }


  67:  


  68:     public static FrameGrabbingControl getFGC(Player player)


  69:     {


  70:         FrameGrabbingControl fgc = (FrameGrabbingControl) player .getControl("javax.media.control.FrameGrabbingControl");


  71:         return fgc;


  72:     }


  73:  


  74:     public static ArrayList<Image> getAllImages(Player player)


  75:     {


  76:         ArrayList<Image> imageSeq = new ArrayList<Image>();


  77:         int numberOfFrames = noOfFrames(player);


  78:         FramePositioningControl fpc = getFPC(player);


  79:         FrameGrabbingControl fgc = getFGC(player);


  80:         for (int i = 0;i <= numberOfFrames;i++)


  81:         {


  82:             Image img = getImageOfCurrentFrame(fpc, fgc, i);


  83:             if(img!=null) imageSeq.add(img);


  84:         }


  85:         return imageSeq;


  86:     }


  87:  


  88:     public static ArrayList<Image> getAllImages(String fileName) throws NoPlayerException,IOException


  89:     {


  90:         Player player = getPlayer(fileName);


  91:         ArrayList<Image> img = getAllImages(player);


  92:         player.close();


  93:         return img;


  94:     }


  95: }



The main method of interest here is the "getAllImages()" method which returns all the frames as an arraylist of Images. For the specified filename it obtains a Player that is used to retrieve all the images. The reason I posted this article is that I find quiet a few visits to my blog to my article on Image Processing. I am not sure on how useful that post was but I thought may be there is someone out there who might need to get started to extract frames from videos. I put in a lot of effort and looked up a lot of material to actually come up with some code that makes sense.

Thursday, February 14, 2008

Java Closures : Introduction

Folks have been working on getting closures into the next release of Java - Dolphin or Java 7. In the past I have posted a tiny video on how to work with closures in Groovy.

Go to www.javac.info to download the closures prototype compiler and extract it. Extract the archive using tar command on linux(that is what I use for development and testing out something new on Java).

You can notice a "java" command and "javac" command. Now if you already have JDK in your path(which you should have in order to tryout the prototype compiler), you differentiate between "java" in your path and the "java" in this directory by simply doing a "./".

To compile a Closure Demo you need to say

./javac MyClosureDemo.java 

I put ./ in front of "javac" so as to differentiate between javac which is already in my path.

Now try running these commands...

$java -version
$.
/java -version

You would notice that the one with ./java returns an internal bootstrap version number while the java returns the actual 1.x release.

Lets get started and write a simple closure.Within main() method try this statement.

{String => int} myFirstClosure;
myFirstClosure
= { String name =>name.length() };

Two things to notice :
1. Firstly name is the parameter this closure takes.
2. There is no "RETURN" statement (return). Some of us not happy about the missing return and how it deviates from the-Java-way. Anyway, I do not give a damn. We should be happy about that a lot of people have put in a lot of effort to come up with something so cool. Instead of complaining, appreciate their effort.

Anyway, the last statement with no ; is returned to the closure. If there is no such statement without a ; then its a closure that returns void.

Since it returns an integer, we can declare this closure as

{ String => int } myFirstClosure; 

This is of the format

{ parameters => returnType } identifier 

As like any method, returnType is mandatory.

You invoke the closure by calling the "invoke()" method and passing to it the parameters that the closure takes in.

int Length = myFirstClosure.invoke("Something"); 

Try out the shown closure, save the file and compile using the ./javac the prototype compiler. The compilation should be successful!

Complete Code:

package screencast; // I placed the demos in this package

/**
* This is one of my first demos on how to use closure!
*/
class FirstClosure {

public static void main(String[] args) {

{ String
=> int } myFirstClosure;
myFirstClosure
= { String name => name.length() };
//{formal => returntype } identifier;

String name
= "Bhargav";

int length = myFirstClosure.invoke(name);

System.
out.printf("My name is %s and the length of my name is %d",name,length);

}
}


Ok, if you look at what was generated in the "javax" directory. You should see Interfaces in the package javax.lang.function. Some of the interfaces that I know are I, II, III and a closure is actually translated into these interfaces and its body becomes the body of the invoke() method which these interfaces define! More implementation details here.

Now run the program using

./java screencast.FirstClosure 

And you are done!!!

Get started and refer www.javac.info, there is amazing tutorial posted there!

Saturday, February 09, 2008

Closures in Groovy

The following screencast demonstrates usage of closures in Groovy using very simple examples. Look out for more Groovy Programming Videos ...

Keyword Helper - My posts

Intention of this post is to give link to my posts for popular keywords

How to develop Groovy Programs in Eclipse

C# 3.5

Peer to Peer Programming [C# p2p Programming would be posted soon]

Image Processing in Java (Histogram, Grayscale to Color Image, etc)

StackOverflowException in Java - solution

Using SWT Browser

CapGemini 1st round interview

CapGemin 2nd round Interview

Free Screen Recording tools

Installing Audio Drivers on Linux

These keywords, I picked based on the Google Analytics Reports. I hope to improve traffic and at the same time make it easy for people who hit my website...lame idea I guess! ;)

Asynchronous Programming in .NET (C#)

Asynchronous Programming is supported by several areas in the CLR like Sockets, Remoting, Web Services, File IO, etc. In order to fully take advantage of these features, I think, one should know how to make asynchronous method calls, in the first place.
Asynchronous Calls -> You invoke the method and do not wait for it to complete. Instead you go ahead executing the subsequent calls. This is advantageous for situations where the subsequent code has got nothing to do with this method call. For example, you have obtained some data which you wish to write to a socket. In this situation you might not have to wait until the data is written. In this case, you can write the data asynchronously. Refer to this article for more detailed explanation of APM (Asynchronous Programming Model)
In order to make asynchronous calls, follow the steps...

1. Create the method you wish to call asynchronously.
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}
2. Write a delegate with the same signature as that of your method. Note delegates are declared outside a class or a struct, but not within.

public delegate void AsyncHelloWorld(string message);
3. Within Main() or wherever you wish to make this call, create an instance of this delegate passing the method you wish to be invoked.

AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
4. Invoke the method using BeginInvoke() which returns an instance of IAsyncResult. The first parameter is the parameter that is to be passed to the method HelloWorld. If there are more than one parameters that the method takes, then pass them in the same order. So we should say the BeginInvoke() takes a variable set of parameters and except the last two, the rest of the parameters are passed to the method. The last two parameters are the AsyncCallBack (you pass a method that is to be invoked on completion of execution of this method) and AsyncState. More about the arguments is here.
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
5. This call does not block unlike other method calls and instead proceeds further with execution. Now you might at sometime require to wait until this method is actually executed. In that case you make use of EndInvoke() method which takes in argument as the IAsyncResult object returned by the BeginInvoke().
acm.EndInvoke(res); //wait until the method is completed
6. On completion of execution, this method returns.

The complete code is shown below and is written in Snippet compiler
using System;
using System.Collections.Generic;
//should import the following namespaces...Important!
using System.Runtime.InteropServices;
using System.Threading;

public delegate void AsyncHelloWorld(string message);
public class MyClass
{
public static void HelloWorld(string message)
{
Console.WriteLine("Welcome to my blog : "+message);
}


public static void Main()
{
Console.WriteLine("Method to be called");
AsyncHelloWorld acm = new AsyncHelloWorld(HelloWorld);
IAsyncResult res = acm.BeginInvoke("Krishna",null,null);
//HelloWorld("Krishna");
Console.WriteLine("Method has returned");
acm.EndInvoke(res);
}
}


Asycnhronous Programming Screencast ....
[Developed with DeBugMode Wink]

Friday, February 08, 2008

Passing Command Line Arguments in Visual Studio

Recently, my friend Kishore asked me how to pass command line arguments to applications through Visual Studio. It has been long time since I ever passed any command line args to apps while debugging. For convenience sake, I usually hard code and later change it once I think my app does not break(which is not good ofcourse). Anyway, here is how you do ...

1. Go to Solution Explorer. Right click on the project and click Properties
2. Now in the Properties page that you see, go to Debug tab.
3. In debug tab, go to Start Options Section in which you see a textarea with title "Command Line Arguments"

Simple enough but not as easy as it should be. There should have been a menu item within build which you can use to directly pass arguments to your application. May be, a Visual Studio Add-in could do that, but the add-in development is very painful and the documentation does not match with what Visual Studio 2008 actually gives.

Live Translator Fun

As always, I am big fan of Microsoft products. So the intention of this post is not to make fun of Microsoft or Live products, but something that I felt funny. Take a look at the Live translation of my previous blog entry.
Firstly, I do not understand spanish but still I tried a live translation and I found my code to be really funny after it gets translated. May be there should be some research going on, to identify the context of the text and based on that invoke translation! But until then, I find it funny.

Thursday, February 07, 2008

Static Members in C++

 

Static in C++ mean the same as that in Java. It is a shared member and all objects of type X will have the same copy of static members of X. Look the simple example:

1 #include<iostream>
2 using namespace std;
3 class Boo;
4 class Foo
5 {
6 public:
7 Foo(){}
8 ~Foo(){cout<<"Foo Destructor called"<<endl;}
9 static Boo b;
10 };
11 class Boo
12 {
13 public:
14 Boo() { cout<<"Boo constructor called"<<endl;}
15 ~Boo() { cout<<"Boo destructor called"<<endl;}
16 string getName(){ return "Krishna";}
17 };
18
19 /*In order to access a static member, you need to declare its scope first*/
20 Boo Foo::b;
21
22 int main()
23 {
24 Foo f; //object Foo() is created;
25 Foo g;
26 cout<<"End of code in main"<<endl;
27 }
This example conveys two important points
  • In order to be able to access static member of Foo outside Foo, you should declare it as in the line 20.

  • The memory for static members is allocated only when this declaration in the file scope is made. In Java, memory for static members is allocated the first time you access that class which owns these members. (For clarity, comment out line 20 and run the code again).

  • Irrespective of the member being accessed or not, this declaration invokes the constructor of Boo.