Tuesday, August 21, 2012

Why,What and How "Delegate" (Part -2)

Hi folks !!

We came to second example of our "Delegate" concept. Please read the first part (previous post) if you haven't done yet.

Heading of our second example is "I want to observe you". You can see real power of the delegate in this example.

Before digging into the source code,  i will explain back ground of this example.

"A husband is there who suspects his wife that she got an affair with some one. He feels that her boyfriend resides in an apartment called "ThisIsLife". Daily following his wife when she goes out became a problem for the husband. Rather than he following her, he wanted to get information when ever she enters that Apartment. 

For that, he executed one simple plan. He knows that when ever any visitor enters that apartment he need to write his/her details in the register. Our husband given bribe to the watchman of the apartment and asked him send message when ever any entry made into the register."

This is the scenario. This scenario has been translated into source code as shown below.


 Here, there are two classes. Line 3- 12 is the Apartment class. As our doubtful husband given bribe to the watchman, he created one method in this class called "WriteInApartmentRegister".

What this method will do ?

It raises an Event.



How this event is created ?

Simple. Just in two lines using our "Delegate".



Here, in delegate declaration, one parameter called "name" has been defined. Our husband wanted to know name of the person entering to the apartment.You can declare delegate in your own way with number of parameters you need based on your requirement.

Now comes our husband class (Line 14-30).

He knows, Apartment object is having an event called "NewEntry" and it takes name of the person as parameter. He also knows, by simply hacking that event, he can get the name of the person that event is holding.



See what he has done. In the constructor of his class, he has taken Apartment object's NewEntry event and given address of his own method which is "IsSheMyWife". That means, when ever NewEntry event is raised "IsSheMyWife" method will be called.



Now he can happily check value in the name variable and take necessary action.

Now classes are ready. How to call them ?

As usual.



That's it. When ever "WriteInApartmentRegister method called, IsSheMyWife method will also be called.

Simple. Isn't it ?

It will be nice yaar. Just write this in code, debug and see how it works.

I'm sure. You will like it.

Shall i say "bye" for now ?

Bye!!    

Saturday, August 18, 2012

Why,What and How "Delegate" (Part -1)


My apologies if you are waiting for the LINQ stuff as promised in my previous post. Those are on the way. In the mean time please have a look at the concept called "Delegate".

With your permission I'm starting.
 
I think when any one reads delegate, the first doubt he might get is, "Why all this non-sense ?". We can directly call the required method. Why this loop line ? If you are also getting the same feeling then let me tell you, you are not alone. Just Google "Why delegate ?". You will be getting 10's of links.

When i thought of writing about delegate, i was bit hesitant because i felt my article will become one among many of the already available unclear content on this subject. Still i decided to go ahead. If you feel something is clear after reading my attempt, take it otherwise sorry for wasting your time.

Thing is, delegate is not complex. It is a simple concept. Only problem is you might not found many scenarios which demands using it. That's why it looks alien or unknown or can be ignored concept.

I do not want to give any theory or definition part of it. I would like to go with practicals. I will give you two examples. If you need theory then I'm sure you won't appreciate this post. If you have done some initially study on delegate and not clear or confused about it then these examples may help you.

Here we go.

Example 1 : I want to steal your method

Mr.Nokia is a software professional.

One Sunday, he thought of designing a new class and declared it like below


Before writing any other code, he went to toilet leaving his class like this. His wife saw the name of this class and without any reason (as usual) she got angry on him and written one method like below.



Mr.Nokia came back from the toilet, got really angry by seeing it but could not say anything. He quietly kept this method as is. But he decided, he should never call this method from any application.

Here came the twist.

One day his sister rang him and asked him for a similar method to take revenge on her husband family. Now, he realized the importance of the method his wife has written.But still he doesn't want to call it.

After some thought he did like this.

He created similar method like his wife's method. He followed that signature of both the methods absolutely same. Otherwise, he knows that he cannot call it.



Then he declared variable for this definition



While declaring it, he did this intelligent thing. He has given address of his wife's method for it. His sister can use this method without knowing who has created it. At the same time he is also satisfied as he is not touching his wife's method as he hates it.

Finally, he has written the method which his sister actually requested for. She only knows about this method. She doesn't know that this method has no functionality inside and it has been 'delegated' internally to some other method.


Just recap the whole thing in one single hit


As you can see from the above image, it involves just three steps. High light is the second step. There Mr.Nokia can give address of any method as long as signature of that method is matching with the thing declared in Step 1.

Now Mr.Nokia's sister can use this class in her application and can call this method like below.

 
That completes our first example. Is it clear ?
Shall we move on to the second example ?
Yes ?

Not now yaar. I'm exhausted. Please wait. I will come back with my next post with the second example.

Bye for now !

Take care !!

Wednesday, August 15, 2012

Love You LINQ

Don't think why this guy is jumping from framework basics to LINQ. Please understand that this blog is not intended to teach you .net framework concepts one after the other like a text book.

You and me know, there are many wonderful sites already exists in this universe serving the same purpose. My goal is just to present few .net concepts in my own way.Those concepts may not be in a standard tutorial sequence. This time, i decided to jump on to LINQ. Please accept (You have no other choice).

Shall we start ?

Sure ?

From the beginning of my software career, I'm a big fan of SQL. It is a nice questioning language where we can ask questions and give orders to the database in almost plain English like below.

SELECT * FROM GIRLSHOSTEL
SELECT * FROM GIRLSHOSTEL WHERE AGE BETWEEN 18 AND 25
SELECT * FROM GIRLSHOSTEL WHERE COMPLEXION = 'White'

I can simply ask like this and any database should accept my question and return results.

Life is happy and wonderful till i have to ask questions to 'something' which is not a database but contains data. Especially i hate to deal with data in arrays (lists) and also gets vomiting while dealing with data in XML format. I don't know why but the word XPath sounds like a ghost smile to me. Querying from this kind of data is like roller coaster drive.Technically looks simple but emotionally irritating. (Relax..Ajay..don't take it too personal.)

I want to stop my agony here but i can't. You know why, sometimes we will be having collection of objects. For example in the above SQL example, I'm taking data from a database table called "GIRLSHOSTEL". Suppose database is not there. All 100 girls information stored as a collection of girl objects.

Now i want to know how many grils are there whose name starts with "Brooke" (When i was in my primary school, "The Blue Lagoon" movie came. Still i cannot forget Brooke Shields. She pushed me into a confusion whether I'm  kid or a teenager).

(Ajay..you are going personal again...come back...)

Where are we ?

Broo...NO..getting data from objects.

How can you do that ?

I don't know how you will do but i will give my keyboard to my team mate and go to canteen.

Please don't stop me here. One more thing i must tell you.

You know text files ?

If you are billing your customer heavily , he will not give GirlsHostel data in a database. He will give it in a comma delimited text file.

He will ask you to get average of all the girls age by reading the text file.

How will you do ?

Don't ask me. I hate looping through text files, splitting, checking..yalk...

I think Microsoft heard my prolonged cry.

They came back to me with a boon of my lifetime.

They came back with a bang.

Boys and Girls..here is LINQ (Language Integrated Query) for you.

Have any kind of data which looks like a list. Just ask it what ever questions you have. It simply  returns the data for you.

For the next few posts i would like to be your loving host on our LINQ journey. In this journey we will be touching Objects, Databases, XML and Datasets via LINQ. We will understand how to question and manipulate all these data sources using our brilliant and intelligent friend LINQ.

Shall i sign-off now ?

Catch you soon.

Friday, August 10, 2012

.Net Framework – A Layman’s View (Part -2)


Hi All,

It is part-2 of our .net framework discussion. I felt myself this post is a boring one as it is pure theory but you should know about this being a .net programmer.

Shall we start?

I think if you are following my posts from the beginning, you might have understood that I like to ask questions. In my school days, I used to feel like if the teacher doesn’t know anything about the subject, he manages it by posting questions to the students. Please do not treat me in the same way.

Anyway here is our conversation. I’m just assuming your responses and writing. I’m also assuming that you are new to .net programming world.

Me: Please consider the below program. Can you write summary of the program in a word document?


  

You: What should I write about the program?
Me: You need to write list of methods/ functions, properties.

You: Ok here it is.

  
Me: Also, Please create one separate class like this.


You: Created.

Me: Please add this class to your first class.
You: Added. Here it is. Just have a look. Is it correct?


Me: Perfect. We will add a call to this class in our program.
You: Ok.




Me: Fine. In the beginning you have created a table of types and methods your program is referring correct?
You: Yes.

Me: Can you update that table with the new type and methods you have added?
You: Ok. Here it is.

Me: Please write all these tables in a notepad and save.
You: Ok saved.

Me: Which name did you give to that file?
You: ObjetList.txt

Me: Give some nice name buddy.
You: What name you think is nice ?

Me: Metadata.
You: Metadata ? Ok all this nonsense you told so far to explain me metadata?

Me: ??????
Me: Nonsense ???

Again  Me: Ok. I will continue the nonsense. In the previous post I said when you click on build project, your .net compiler produced .exe or .dll correct ?
You: Yes. But I did not see any text file there.

Me: No just for your understanding I told like that. Your .net exe or .net dll does consist of above tables data also.  It is called metadata.
You: Then what is manifest ?
Me: You said nonsense?
You: Just for fun. It is my casual punch dialogue.

Me: Never say this to girls.In this example, how many projects did you add to your solution?
You: One only.

Me: If you add two/three projects?
You: If I add ????

Me: If you build, it will generate 2,3 exe’s or dll’s.
You: Ok. Then ?

Me: This will have 2,3 metadata’s correct ?
You: Correct. So…. ?

Me: If I ask you to write list of these 2,3 metadata’s in a separate table, it is called manifest.
You: That means, if only one project is there in the solution then manifest won’t be there. Correct?

Me: Wrong. It will be there with one entry in the table.

Ok guys/gals our discussion closed. I know what you are thinking. Just to give two lines of definitions about metadata and manifest, this fellow wasted 2 pages. Forgive me for this. 

Anyways, I would like to ask you one more question.

In the previous post, I said our compiler produce MSIL. But when this will be converted to machine understandable language?

Let us consider our same example given above. When we press F5, will the whole exe gets converted into 0’s and 1’s ?

Answer is “No”.

Here are the steps this particular example passes through.

  1. Press F5 to run the program 
  2. CLR enters Main method

3. CLR checks what types (dll’s) and methods of those types used in the Main method and stores them like below.





Here Beep method is there in a class called “Console”. Our CLR will not convert Beep IL code into 0’s and 1’s immediately. It is done only when it is called. But it maintains a structure of types and methods this particular method is referring. In this structure, address of Beep method is blank as it is not yet converted from MSIL to 0’s1’s 

      4. Now, Beep method called


      
      5. CLR checks if this method is already converted to 0’s and 1’s. It is not.  That means machine readable form of Beep method is not available.
      6. It goes to the Console dll and gets MSIL of the Beep method
      7. Converts this MSIL of Beep into machine readable language and stores address of that in the structure created above.


1.    


             8. Steps 6 and 7 are performed by one function in the CLR called JIT compiler
      9. Now Beep (999,99)method called


      10. CLR checks in the data structure table if Beep method already converted. 
       
       It is !!

       So JIT compiler will not be called. CLR just takes this address and executes it. This is the reason when you run your .net programs; it will be slow first time and better for the subsequent runs as this conversion process will be skipped. 

      Of course I think you understood from above explanation that, CLR coverts MSIL to 0’s1’s dynamically and store them in the memory when the program is running. If you stop your application then obviously memory will be cleared. If you press F5 again, process will start from step 1.

These same steps will be repeated for all the method during execution of the program.

I hope it is clear to you.

I’m signing off now