Feeds:
Posts
Comments

Archive for October, 2005

Modules in Visual Basic .NET


If you are a Visual Basic 6 programmer getting your feet wet with Visual Basic .NET, you would certainly go through an unavoidable phase which involves a mixture of happiness and sadness – the pain of finding some feature of VB6 not being supported in VB.NET and the happiness of finding that some of your other favourite features are still there. If you loved writing your functions in modules when you used to program in VB6, you can rest assured that the VB.NET team has gone some length to keep you happy.

In case you never programmed in VB6, you would be wondering what a module is. Its a convenience offered by VB6 to write functions (you can have variables in a module too). You can access the functions (or variables) in a module just like calling global functions (or variables) i.e. by omitting the module name as prefix.

Please note that the CLR has no notion of a module. Then how come we still have modules in VB.NET? In a moment we will see how the VB.NET team manages to keep the CLR as well as the VB6 programmer happy.

Let us create a module as follows :


Public Module TestModule
Public Sub TestFunction()
Console.WriteLine(“Test function of TestModule called !”)
End Sub
End Module

You can call the TestFunction from outside the module in two ways:
– TestModule.TestFunction()
– TestFunction

The first method would give us some clue as to what happens to a module when it is compiled. Yes, you are right, it will be compiled into a class and all of its members will be Shared (static). But wait, if that is the case then how is it possible to make the function call in the second way? The VB.NET team has more tricks in their bag it seems. To make it possible to call the TestFunction as if it were a global function, an attribute is applied to it – Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute. For the casual programmers this completes the illusion – the VB6 module is still there in VB.NET. The rest of us who does not believe in magic, would look under the hood and find the truth. For this purpose you will need to find a good friend in ILDASM (or a similar tool, if you so prefer).

Here is the declaration of our TestModule in IL :


.class public auto ansi sealed TestModule
extends [mscorlib]System.Object
{
}

From this declaration that we find that our module has been compiled to a class TestModule which is sealed (means NotInheritable). Thus you cannot use a module as a base class. Although not obvious from this declaration, we should be aware of two things :
– all members are implicitly Shared (this can be verified by looking at the IL for the function). You cannot explicitly declare a member as Shared, it will result in a compilation error.
– you cannot create an instance of this class.

But if you think about it again, the class is NotInheritable (sealed) and you cant create an instance of it either, which means that the class should be MustInherit (abstract). A class cannot be NotInheritable and MustInherit at the same time, but then how do we explain this apparent paradox ? The compiler pulls a trick here. The class isnt made abstract, instead the compiler just “forgets” to add a default constructor. We know that if we dont define any constructor for a class, the compiler will automatically add one for you (the default constructor). In the case of Modules, VB.NET wont allow you to write a constructor manually. Neither will it add a constructor automatically for you when it compiles the module. It is the absence of the constructor that prevents the creation of an instance of a Module.

If you are a C# programmer, you would have but one doubt – how can you use a VB.NET Module from C#?
If you expose a Module from a VB.NET library and use it in a C# project, we wouldnt have any problem if we just call the functions like we are calling static functions declared in a class. We are forced to use the Type prefix (the name of the Module) unlike in VB.NET where we could simply invoke the function by omitting the module name. We cant create an instance of the the Module, just like in VB.NET.

If you think that all is well with Modules, then you havent heard the full story. If we have 2 modules in your project and both contain functions with same name and signature, then we are forced to prefix the Module name to resolve the ambiguity. This issue is caught by the compiler and is not much of a problem. But you we could get in trouble if there are two functions of same name and signature in two modules which reside in different assemblies. The compiler would look in the modules of the current assembly for a match before it would look in external assemblies. This makes perfect sense but can catch us off gaurd if we arent aware of the possiblity, especially if multiple developers work on the same module. It would be better to prefix the Module name to prevent such problems – we might end up calling a function in a Module in the local assembly when we really wanted to call a function residing in a Module in an outside assembly.

Read Full Post »

If you are a C# developer with no knowledge of Visual Basic.NET, probably you would like to read this instead.

If you have programmed in C# and VB.NET you would have noticed that the languages are very similar and there exists a line-to-line correlation with the same program written in these languages. In fact many people say that C# is just VB.NET with curly brackets (or vice-versa if you prefer). Many tools exist that provide translation from VB.NET to C# and viceversa at a good accuracy. But when I wrote my eventhandling tutorial in C#, I decided that a VB.NET version is also needed because there is some difference between the two, albeit on a superficial layer.EventHandling mechanism in VB.NET provides better flexibility than that of C#. Although the underlying paradigm remains same, the VB.NET compiler provides some shortcuts which can be a real convenience (it actually depends on the developer’s mindset whether it is actually a convenience or not).
There are 2 ways by which a Publisher can publish an event and 2 ways to handle it. The first method is to declare a delegate and an event seperately.


Namespace VBEvents
Public Class Publisher

Public Delegate Sub StateChangedEventhandler(ByVal sender As Object, ByVal args As EventArgs)
Public Event StateChanged As StateChangedEventhandler

Public Sub CauseStateChange()
Console.WriteLine(“Publisher going to raise event”)
RaiseEvent StateChanged(Me, EventArgs.Empty)
End Sub
End Class
End Namespace

Here we can see that there is a Delegate that defines the eventhandler’s signature and a Event of the same type as the delegate. To raise an event we use the RaiseEvent keyword. Everything straightforward so far. Now lets see the second method.


Namespace VBEvents
Public Class AnotherPublisher
Public Event StateChanged(ByVal sender As Object, ByVal args As EventArgs)

Public Sub CauseStateChange()
Console.WriteLine(“AnotherPublisher going to raise event”)
RaiseEvent StateChanged(Me, EventArgs.Empty)
End Sub
End Class
End Namespace

Here we combined the the delegate and event declaration into one as

Public Event StateChanged(ByVal sender As Object, ByVal args As EventArgs)

Note that this is a convenience provided by the VB.NET compiler and that the IL produced as similar in either cases. The compiler automatically creates a delegate for you and names it by appending “EventHandler” to the Event’s name. Thus the final outcome is one and the same. This method is not available in C#.Now lets look at the subscription process. The first method is to subscribe is shown here :


Namespace VBEvents
Public Class Subscriber

Private m_Pub As Publisher

Public Sub New(ByVal pub As Publisher)
m_Pub = pub
‘subscribe
AddHandler pub.StateChanged, AddressOf pubEventHandler
End Sub

Private Sub pubEventHandler(ByVal sender As Object, ByVal args As EventArgs)
Console.WriteLine(“Handled event raised by ” & sender.GetType().ToString())
End Sub

Public Sub RemovePubHandling()
‘unsubscribe
RemoveHandler m_Pub.StateChanged, AddressOf pubEventHandler
End Sub
End Class
End Namespace

Here we use AddHandler to subscribe to an event and RemoveHandler to unsubscribe.The second method uses the WithEvents keyword on a reference to the publisher to tell the compiler that we are interested in handling the events that this publisher would raise. To specify which method acts as the eventhandler for which event, we use the “handles” keyword.


Namespace VBEvents
Public Class AnotherSubscriber
Private WithEvents m_anotherPub As AnotherPublisher

Public Sub New(ByVal anotherpub As AnotherPublisher)
m_anotherPub = anotherpub
End Sub

‘eventhandler for StateChanged event
Private Sub pubEventHandler(ByVal sender As Object, ByVal args As EventArgs) Handles m_anotherPub.StateChanged
Console.WriteLine(“Handled event raised by ” & sender.GetType().ToString())
End Sub

Public Sub RemoveAnotherPubHandling()
RemoveHandler m_anotherPub.StateChanged, AddressOf pubEventHandler
End Sub
End Class
End Namespace

The difference between these two methods is that in the second method the subscription is done statically (i.e.its hardcoded that a procedure will act as the eventhandler for a particular event while in the first method we can dynamically choose the eventhandler. The unsubscription process is same for either methods. Note that you can assign different instances of the publisher class to the withevents variable thereby handling events raised by different objects. But the downside is that there is a performance problem associated with assignment to a withevents variable. For more details on this, see Jeff Richter’s most excellent book – Applied Microsoft.NET Programming with VisualBasic.NET.If you were really paying attention you should be wondering how the “Withevents” does its trick. If we make assignment to a WithEvents variable, how will the compiler subscriber to that instance and unsubscribe from the previous instance that the variable referred to? To see whats really happening load up ILDASM (which should be your best friend if you want to see whats happening under the hood) and you can see that the compiler adds two methods to access the withevents variable. If your withevents variable is named m_Pub, the methods will be named get_m_Pub and set_m_Pub. When you make an assignment to a withevents variable, the compiler will check whether the variable currently refers some instance or not. If it refers to some instance, we unsubscribe from that instance and then subscribe to the new instance (this is what creates the performance problem which I referred to in the last paragraph).

C# makes use of the overloaded += and -= operators for subscription while VB.NET uses AddHandler and RemoveHandler for the same purpose. If you use ILDASM, we can see that the compiler creates two procedures in the publisher class behind your back for the subscription and unsubscription processes. If you event is named myEvent, the procedures will be called add_myEvent and remove_myEvent.

P.S. I know the code formatting sucks, but it would be a hell of a job to manually format it, but maybe I would do it some other time

Read Full Post »

The Tipping Point

I wrote this some months ago, but forgot to publish it at that time. It has been quite some time since a read a book from start to finish. In fact it has been years. Last week, Abhishek and Prasanth had come to Bangalore and I went to The Forum with them. In LandMark I saw a low priced edition of The Tipping Point. I have been seeing Blink: The Power of Thinking without Thinking on the top sellers list for quite some time and I knew that The Tipping Point was written by the same author (Malcolm Gladwell). So I thought I would give the book a try. I was planning to go home on 31st, so anyway I would be getting some time to read. I started reading the book on that evening itself. After reading through the first few pages, i was not quite impressed. But soon the book started picking momentum. The book has something special about it, there is no cute jugglery with words, it is written in a very straightforward manner without the slightest attempt to make himself sound smart. The core of the book is an explanation of how epidemics get started. An epidemic is not be taken only in the medical sense, it also refers to how all of a sudden certain behavioural patterns emerge which produce a sweeping change. The previous sentence actually doesnt do justice to the contents. It is almost like a thriller story, the author first mentions about an epidemic and analyzes the causes that we associate with the epidemic. Then the twist comes – slowly we are put into an entirely different perspective which sometimes leaves us spell-bound, the facts sometimes so strange that we cant even believe it.This book presents a very interesting read. As I mentioned earlier, I read this book from cover-to-cover in 2-3 days, something which I havent done in years. I would give it 4.5 stars out of 5.

Read Full Post »

Amazon Review

I spend a lot of time reading the reviews of books at Amazon. That gives a better idea of what books to buy if I’m interested in learning about a particular topic. I wouldnt say that all reviews are correct or would be made with an impartial mindset, but in general you would get an overall impression of the book. Several times I was tempted to write a review myself, but I always kept postponing it. This week I did it. I wrote my first review for C.J.Date’s Database In Depth. You can see the review here. The book is simply great. I would highly recommend it to all of those who are working with databases or would like to have a good knowledge of Relational Theory.

Read Full Post »

The contents of this blog may not interest you as did its title, because its a technical one. I have decided to include more technical articles (inspite of the fact that there are gazillion tech blogs out there) not because I think this one is going to be better than them but just because it would help me understand things in a better way. So my technical rants are just for my own benefit. If anyone else gets something useful out of these blogs, that would be a real pleasant bonus.

I was also confused as to how my approach should be. Should I write it in such a way that non-techies would also understand it ? Or should I aim at the developers who have atleast a general idea of what a class is? Although I would like to go the first way, there are atleast three reasons I am forced to go with the second option.
1)I dont think non-techies would like to dig deep into the .NET trenches irrespective of the way I present things.
2)Most of the people who read my blog are technical people.
3)I wouldnt be able to do justice to the real topic at hand, if I have to write so much explaining the context to the layman which is so painfully obvious to techies.

The title of this blog might have given a clue to what this blog is going to be. Its about programming with events. I just would like to assume that you would be knowing what an event is. If you dont, there aint much use reading the rest of this anyway.

Events are a convenience for modern programming. I will show here how to implement event handling mechanism in C#. Delegates are an integral part of the .NET framework and play a key role in the event handling mechanism. Put simply, delegates are type-safe function pointers.

Let us assume there is a Publisher class which raise an event and a Subscriber class is interested in that event.

using System;

class Publisher
{
private int _state = 0;

public delegate void StateChangeEventHandler(Object sender,EventArgs args);
public event StateChangeEventHandler StateChanged;

public int State
{
get
{
return _state;
}
set
{
_state = value;
if(StateChanged != null)
StateChanged(this,EventArgs.Empty);
}
}
}

The above code can be explained as follows. The publisher class contains 2 key members which allows it to raise events. One is a delegate and the other is the event. The delegate specifies the signature for the event handler methods. Two conventions are usually followed here. First one is regarding the delegate name – it should end with EventHandler. The convention for the event handler signature is to have 2 parameters and the return type as void. The first parameter will be the object that raises the event (the source of the event or in other words, an instance of the publisher). The second parameter will be an instance of a System.EventArgs class or a class that derives from it. There is a well defined logic in this convention. The obvious advantage is the resulting consistency among event handlers. Also, the choice of the first parameter as the event source allows a single event handler to handle events from multiple sources. The event handler can examine the parameter to determine which object raised the event. The requirement for this to work is that the signature specified by the 2 delegates should be same.

In our Publisher class we have an event called StateChanged which will be raised when the State property changes. To raise the event we use this code :


StateChanged(this,new EventArgs());

But the problem is that if no objects have subscribed to this event, you will get a NullReferenceException. To prevent that we need a check :

if(StateChanged != null)
//raise event

Usually we would keep the above code in a separate method like:

private void OnStateChanged(EventArgs e)
{
if(StateChanged != null)
StateChanged(this,e);
}

For additional flexibility we can make this method protected virtual so that derived types can have some control over the firing of events.

protected virtual void OnStateChanged(EventArgs e)
{
if(StateChanged != null)
StateChanged(this,e);
}

Now our Publisher class will look like this :

using System;

class Publisher
{
private int _state = 0;

public delegate void StateChangeEventHandler(Object sender,EventArgs args);
public event StateChangeEventHandler StateChanged;

public int State
{
get
{
return _state;
}
set
{
_state = value;
OnStateChanged(EventArgs.Empty);
}
}

protected virtual void OnStateChanged(EventArgs e)
{
if(StateChanged != null)
StateChanged(this,e);
}

}//~end of Publisher class

Now that we know how to publish and raise events, we can look at how to setup a subscriber.

class Subscriber
{

public void Subscribe(Publisher pub)
{
pub.StateChanged += new Publisher.StateChangeEventHandler(pub_StateChanged);
}

public void UnSubscribe(Publisher pub)
{
pub.StateChanged -= new Publisher.StateChangeEventHandler(pub_StateChanged);
}

private void pub_StateChanged(Object sender,EventArgs args)
{
Console.WriteLine(sender.GetType().ToString() + “‘s State Changed !”);
}
}//~end of Subscriber class

The code is mostly self explanatory. The Subscribe and UnSubscribe methods show how we can subscribe to and unscribe from events using the += and -= overloaded operators. For the eventhandler the name of the method can be anything (the convention is ‘object_event’) but the signature of the event handler should conform to the signature specified by the delegate.

We can have static events if we so prefer. If you subscribe to a static event, you will receive notifications from all instances of the Publisher class and if you unsubscribe you will recieve notifications from none. You dont need an instance of the Publisher class to subscribe to a static event. Note that nothing prevents the eventhandler function itself from being a static function.

As a point of interest, it should be mentioned that an event is implemented by a multicast delegate. To handle multiple subscribers it would internally maintain a list of subscribers.

If you didnt guess it till now, the event mechanism follows the Observer design pattern (see Design Patterns by the GoF).

P.S. Sorry about the formatting, I tried my best though 🙂

Read Full Post »

Shocking News !

The most shocking incident I have heard in recent times. I got this mail from a friend. Read On….

Hi!

I would like to bring to notice a certain injustice that I have subjected to at the Bangalore Railway Station (Majestic). On September 30 (Friday), 2005, I had been to the station to see off my fiance and her mother. They took the Karnataka Express (Train #2627) to Jhansi at 6:30 pm.

On my way out I was asked to present my platform ticket by a railway official. On producing the same, the TT turned around and told me “What if I say that you haven’t given me the ticket?” Before I could react, he along with his colleague pushed me into the adjacent enquiry cabin and physically manhandled me. I was slapped several times, my spectacles were grabbed and deliberately crushed by foot, and my phone was flung away from me. The RPF comprising of one RPF and four constables, appeared on the scene. The surrounding public was whisked away. None of the railway police officials cared to listen to me and they started hitting me indiscriminately with lathis. They dragged me out, and all the 4 constables continued hitting me with lathis from Platform 1 to Platform 3/5, till we reached the station master’s cabin. Racist abuses and threats were made on the way. At the station master’s cabin, I was told that I have been charged with a non-bailable offence and would be behind bars for 15 days.

Not for a single moment was I allowed to speak. All of a sudden a stranger came to the scene and he claimed that he was there to help me. Having lost all my physical strength and mental senses, I was happy to see some sort of help. He, claiming to be V Srinivas from Infosys, talked to the officials and the railway police in Kannada. He told me that the only way I was to get out was if I was willing to pay my way through. Being in no state to make a rational choice, I gave him my ATM card and pin. He took one of the RPF chaps along with him and said he would clear the matter. He returned some time later saying that everything was okay now.

I was asked to sign a statement which said that I hit the police and TT in a drunken state. I refused. Finally, they pressurized me to write that I did not produce a platform ticket when asked. I wrote the same and then V Srinivas took me out of the station. He joined me in an auto and took me to the ICICI ATM at Anand Rao circle. He withdrew Rs. 15000 from my ATM and got back. he took the cash under the pretext that while helping me he had left his wallet in the train he had left behind and that he would return the same through his ICICI Internet account. Having broken down mentally I did not realise that I was being cheated. He then took me to a Samsung showroom and tried purchasing a cellphone worth Rs. 18500 with my card. It was only then that I realised what was happening. I grabbed my card back, caught him by the collar, snatched my cash that lay in his pocket, and got into a running auto.

I have now realized that all of this was a plan. There is a strong nexus between the railway officials, the railway police and the fraudster. The railway officials identify a victim who they think is well-to-do, the RPF beat that individual till he has no physical or mental well-being. Then this fraud chap comes on to the scene, takes advantage of the situation, and takes all your cash away. Also, this series of events generally occurs on the last day of the month as they know that the salary gets credited on this day. (This strikes me now because the self-proclaimed Infy employee, V Srinivas, clearly asked me whether I had received my salary. He said that he just wanted to find out if there was cash enough to tackle the case.)

Now three days hence, I have tried to run from pillar to post. I have been forced to miss office hours in my effort to get justice. But I don’t want to give up the fight midway. If any of you are in the media, or have friends/relatives who are in the industry, I’d like to speak with them about this in greater detail. I can be reached on 09886179319 or 08030933067. I believe it would catalyze my efforts.

Also, please pass this email to all the people who reside in Bangalore, so that they don’t fall into the same trap.

Regards,
Nimish V Adani
IIML Batch of 2003
ITBHU Batch of 2001


Read Full Post »