Friday, November 19, 2004

VJs Mega Tip Of The Day - November 19th 2004

Whidbey Days - ASP.Net 2.0 Page Life Cycle

ASP.Net 2.0 Page Life Cycle

Abstract
This article talks about the way ASP.Net 2.0 page life cycle works, it discusses the way ASP.Net page is created and displayed.

More Information
It is important for ASP.Net programmers to understand how their page is created/processed and displayed by ASP.Net framework. Sometimes many unexpected behaviors are seen in case incorrect data is accessed before or after certain page events. Below is the information on how System.Web.UI.Page methods execute. For keeping the article more users friendly and also to avoid incorrect method calls for not-recommended methods, I have discussed only those methods which I felt a user should know about.

Without further delay let us start from the html source that is written for the page. First of all the html source needs to be parsed to process the page. This is done by a method in the Page called AddParsedSubObject(). Unless you override it, this method will automatically add Literal controls to page’s control collection. This is done by first creating a control collection by calling CreateControlCollection() method.

As the child controls are parsed in the page the method AddedControl() is called which is usually triggered when a control is added to another control’s control collection. As ASP.Net pages can be viewed on various devices the method ResolveAdapter() returns the control adapter which is responsible for rendering the control on the specific device or browser requesting the ASP.Net page.

DeterminePostBackMode() is then invoked to find out what is the post back mode used for the request. If the POST method is used for postback the web form information is returned from the Context object. If the GET method is used for postback, the information from query string is returned. If the page is being requested for the first time, null is returned, many of us are used to writing code in which we check the postback property and execute specific logic, this is the method that helps the framework to get our this specific code running correctly.

More granular control on the page life cycle is available in ASP.Net 2.0. Now we have got additional events like “PreX” and “XComplete” to insert our logic before and after the usual “X” events, which we have been working with. The first such event to fire is PreInit(). This is the very beginning of page’s initialization and after the completion of this personalization information is loaded and if there is any page theme then it is initialized. I have talked more about these concepts earlier on the blog. Click Here for more information.

After the PreInit() of the page, ResolveAdapter() for individual child controls is called and then each of the control’s Init event is fired. What is interesting to note is that Init event of the child control is fired before the Init event of the page and many a times in developing complex ASP.Net applications if user plays with these events, without enough information, then unexpected behavior might resulted.

After the Init event of the control, the TrackViewState() method is triggered which will track the view state changes posted to server. It is important to know that when control’s view state data is being tracked with the state bag, page’s Init event and TrackViewState() are not yet fired. This also results into unexpected behavior in case users are writing custom controls or probably their own base page.

After the TrackViewState() of the child controls, the Init event of the page is fired. This event initializes the page and then TrackViewState() of the page is fired which tracks the changes to the page’s state bag

After the TrackViewState() for the page is called InitComplete() event is fired. This is the signal that initialization of the page and its child control is done. Though what a user should know is that ViewState for the page or the controls is not yet restored, if user tries to do anything before this data is restored the required changes in the data from the client which expected may not appear.

The view state is restored in the method LoadViewState() after whose completion ViewState data is available for a user to work on.. There is then EnsureChildControls() method which is invoked which makes sure that the page’s child controls get created.
In ASP.Net 2.0 a PreLoad() event available which would probably be the right place for user to play around with objects before the universally used load event is fired. For people who are writing base page classes and who want to perform certain tasks before standard page load event this is the right place to put their custom logic into.
After PreLoad() event, the Load() event of the page is fired. There is no need to explain what one can do with this event, isn’t it. But what should be known is that page load event is fired before the control load event unlike Init event which is fired first for the child controls and then for the page. This also many times takes custom control writers by surprise as they are expecting the control load to occur before actually the user logic on page load is executed.
So after the page Load() event, control Load() event is triggered and then the custom events like button clicks and others are fired. Many a times users want some specific functionality to be executed in their base pages, just after these postback events but also before PreRender when the pre rendering logic starts. This kind of development methodology has created issues when the derived classes call base methods before or after their custom logic when otherwise was expected. That is the place where LoadComplete() event of the page will come to use. The LoadComplete() will be called after the custom event execution for the child control is over but PreRender is not started.
After the LoadComplete() event PreRender() event of page is triggered followed by the PreRendering of each child controls. PreRender() event has always been the right place to put in the last logic before ViewState is saved. But now there is a PreRenderComplete() event which is fired after all the PreRender events of the child controls are fired, this will now be the last chance to change the data before SaveViewState() of the page is fired.
After the SaveViewState of the page; the control SaveViewState() is fired. SaveViewState() will save the changes that have happened to the data till that point and then the page will be ready to be rendered.
LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium() are called before LoadViewState() and after SaveViewState() respectively. As the name indicates the ViewState is persisted so that it can be used later in the next call. I will talk in detail about how these methods work later, but as of now it is just good to know what they do.
After the SavePageStateToPersistenceMedium(), SaveStateComplete() is fired, which indicates that saving the state of the page is now complete.
After this the rendering of the page begins. First the CreateHtmlTextWriter() is fired to create the HTML text writer and then page and control Render are called. If the user wishes to change the look and feel of the way their control is rendered this is the event to do it. When the Render method completes Unload() for each child control is called and then each child control’s Dispose() is called. After disposing all the child controls, the page Unload() event is fired and then the Page’s Dispose() is called.

In case of error, the execution directly jumps to the error handling and then to unload and dispose events skipping the events in-between. This thus covers the major execution of ASP.Net page life cycle.

Below is a quick summary of the methods in their invocation order:
System.Web.UI.Page.AddParsedSubObject
System.Web.UI.Page.CreateControlCollection
System.Web.UI.Page.AddedControl
System.Web.UI.Page.ResolveAdapter
System.Web.UI.Page.DeterminePostBackMode
System.Web.UI.Page.PreInit
System.Web.UI.WebControl.ResolveAdapter
System.Web.UI.WebControl.Init
System.Web.UI.WebControl.TrackViewState
System.Web.UI.Page.Init
System.Web.UI.Page.TrackViewState
System.Web.UI.Page.InitComplete
System.Web.UI.Page.LoadPageStateFromPersistenceMedium
System.Web.UI.WebControl.LoadViewState
System.Web.UI.Page.EnsureChildControls
System.Web.UI.Page.LoadViewState
System.Web.UI.Page.PreLoad
System.Web.UI.Page.Load
System.Web.UI.WebControl.Load
System.Web.UI.WebControl.OnClick
System.Web.UI.Page.LoadComplete
System.Web.UI.Page.PreRender
System.Web.UI.WebControl.PreRender
System.Web.UI.Page.PreRenderComplete
System.Web.UI.Page.SaveViewState
System.Web.UI.WebControl.SaveViewState
System.Web.UI.Page.SaveViewState
System.Web.UI.Page.SavePageStateToPersistenceMedium
System.Web.UI.Page.SaveStateComplete
System.Web.UI.Page.CreateHtmlTextWriter
System.Web.UI.Page.Render
System.Web.UI.Page.RenderChildren
System.Web.UI.WebControl.RenderControl
System.Web.UI.Page.CreateHtmlTextWriter
System.Web.UI.WebControl.Unload
System.Web.UI.WebControl.Dispose
System.Web.UI.Page.Unload
System.Web.UI.Page.Dispose


There are many methods which I have skipped and many methods which we discussed are called multiple times on the basis of the existing conditions, I have intentionally not discussed them, though what I have tried is to make the user understand the things that happen in the background for a page to work.

So this is how a single ASP.Net page’s HTML comes on to our browser. Indeed quite a bit amount of work behind the scenes right!! I hope you will be able to unleash the potential of all these additional options available to you in Whidbey timeframe. These are some of the reasons why I am so passionate about Microsoft Technologies; they just keep getting better with every new release.

PS: The above is my understanding of the Whidbey (ASP.Net 2.0) page life cycle, if you think I have missed something or something is incorrectly mentioned then please do drop in a mail at Vishal_Joshi@MVPs.org so that I can make the necessary corrections.

PPS: Today marks the completion of second season of VJs Tip Of The Day series. I shall be back with the thrid season in new year 2005... Till then wish you best luck and a wonderful festive season...

Thursday, November 18, 2004

VJs Tip Of The Day - November 18th 2004

Whidbey Days - Sharing Types Across Web Service Proxies

I do not know how many of you have faced this problem but I have always had a complain that about not being able to share types across different web service proxies... Take this scenario... I have a business application which exposes many different web services... These web services might be sharing some common object across themselves... For example Lets say I have a Auto Insurance application... I build one web service to do Policy related jobs and the other to do Premium related jobs but then in both the condition my Automobile object goes along... Now, as my proxy generator will generate service proxy for each of the service individually so I will get two Automobile classes and if I have a single client application dealing with it I will have to either create different namespaces or do some manual editing...
Although the editing might not be much the problem is that regeneration causes those changes to go away... Also there needs to be some documentation around this problem etc... Well enough of problem statement, I think you must have got it by now... :-) Anyways, in Whidbey the problem is resolved...
The WSDL exe has a switch called /sharetypes and you can give the services for which you want to share the types and it will do it for you... The syntax will be something like...

Wsdl.exe /sharetypes http:(doubleSlash)AutoInsuranceServics/PolicyService.asmx?wsdl http:(doubleSlash)AutoInsuranceServics/PremiumService.asmx?wsdl


PS: A quick observation, I see many posts and queries on our UserGroups and Newsgroup which are so simple that typing just the first word in the google (also MSDN sometimes... Just kidding!!.. :-)) will result into sufficient information to answer the query... The point which I want to make is that it is also important to develop a good habit to try resolve to our own queries, ourselves... No one knows everything, but each one of us learn over a period of time right!!... Asking our own usergroup peers is not wrong but then at times its spoon feeding, it just makes us develop a bad habit... All I am saying is let us just try to make sure that we have exhausted all the resources at our end either time or material before we ask it out; might be trying for another 10 minutes will give us the answer we want!!...
Please do not get me wrong, do not stop asking me questions whenever you feel like, I do try answering as many as I can and I continue doing that!! (but now after the vacation.. :-))

Wednesday, November 17, 2004

VJs Tip Of The Day - November 17th 2004

Whidbey Days - Page.GetValidators method

Yesterday we talked about ValidationGroups now here is an application of the same... System.Web.UI.Page has now got GetValidators method... The signature of the method looks like below...

public ValidatorCollection GetValidators(string validationGroup)

Basically System.Web.UI.Page has got a property called "Validators"... This property was always there and it use to return back all the validators of a page... This property will ofcourse exist for Whidbey too but now this special method adds extra value...

As the signature indicates the GetValidators method will accept a string which will be validationGroup name which you have given to your validation controls and give you back a strongly typed collection of Validator Controls... If you do not pass the string name of validation group here it will return back the default validation group... This would be the same group which will be given by the Validators property...

I would recommend using this method as you would have a generic way of accessing the validators and if the group name is passed dynamically your page logic will work in both the cases...

PS: An easy way to find out how important you are to someone is to find out whether your contact number is stored in the phone book of that person... If someone does not care to store your number with them somewhere then PROBABLY he/she is not dependant on you in anyways...



Tuesday, November 16, 2004

VJs Tip Of The Day - November 16th 2004

Whidbey Days - BaseValidator.ValidationGroup property

I am not sure how many of you have thought about this but many a times there use to be scenarios when you wanted that not all the validation controls on the page behave and validate in the same set... So here is the option for you... There is a property in Whidbey BaseValidator which is called ValidationGroup...
This property takes a string value and is a easy way to group your different validation controls in a group...

As this is a property of BaseValidator it is automatically inherited in all the rest of the validation controls...

How to visualize the use of it... Say for example I have a text box and I have a range validator, required field validator, regular expression validator all associated with it... I want to group all of these validators together then I set all of their ValidationGroup property to a fixed value and then they get grouped... Easy isn't it...

PS: "Tangential Theory" - This a new word coined by me... What does a tangential theory means? Well tangential theory is a philosophical theory of special kind... It is a theory or a thought which might touch you but will probably not effect you or intersect you often... It is a theory which will give you a chance to think about and conclude whether it does interset your mind waves just at a tangent or will eventually somewhere intersect to create a larger impact... In nutshell, Tangential Theory gives you the point from which you can start analyzing... I would refer many of the PS: that come along the technical tips as tangents of the tangential theory... Enough for now right!!

Monday, November 15, 2004

VJs Tip Of The Day - November 15th 2004

Whidbey Days - Page.SetFocus method in ASP.Net

Many have struggled to do simple thing like setting up focus in ASP.Net page... Well not anymore... There is a simple method called Page.SetFocus in System.Web.UI.Page class in Whidbey...

Look at the signature of the method

public void SetFocus(Control) where the parameter is the control on which the focus needs to be set...

There is also an overload for the method available which takes string

public void SetFocus(String) where the parameter is the clientID of the control to set focus on...

There are two exceptions which this method can throw; they are ArgumentNullException in case the clientID or control to set focus on are null... The method also throws an InvalidOperationException in case the method is called after PreRender event of the page as after that the setting the focus is not possible...

Simple and Nice way isn't it... :-)

PS: November 19th will be temperory end of "Second Season" for tip of the day... I will be off for a one month long vacation and will catch up with you guys again in new year 2005 in the "Third Season"...

Wednesday, November 10, 2004

VJs Tip Of The Day - November 10th 2004

Debugging mess due to Whidbey Beta 1

My first gift from Whidbey... I had installed Whidbey alpha on my machine which had VS.Net 2002... After installing alpha my VS.Net 2002 ASP.Net applications could not be debugged... I tried all possible things but could not get it working again... Finally when I had to work on my previous apps and had no option I thought it was alpha version issue and so uninstalled alpha and started carrying on...
Now I have installed Whidbey beta 1 refresh and just to add to my worst fears again my older VS.Net web apps could not be debugged... Interestingly this time I installed Whidbey on virtual pc still the problem comes...
Just for your information if I get debugging issues with VS.Net I first do all the below possible things:

-I make myself a member of Debugger Users and VS Developers...
-I registered ASP.Net of appropriate framework version by aspnet_regiis -I (found in ...\WINDOWS\Microsoft.NET\Framework\VERSION FOLDERS (e.g v1.1.4322) -I have my ASP.Net debug property set to be true in the project properties...
-I check my web config file settings too....
- I also try to manually attach the apnet_wp.exe to debug the app...
-I check my machine.config file and see if the processModel tag is enabled... (found in ...\WINDOWS\Microsoft.NET\Framework\VERSION FOLDERS\CONFIG) -I use the world famous ASP.Net version switcher utility made by Denis (http://www.vishaljoshi.blogspot.com/2004_04_01_vishaljoshi_archive.html)...
-I do the same stuff which ASP.Net version switcher does manually also...
-I also run dotnetfx.exe once again just to be sure...

If none of the above solves my problem, I try to assume that something else is wrong... Btw, finally for the above issue I was informed by Dr Colin Brown, MVP that this is a reported bug for Whidbey and probably next version (beta 2) should solve it...

But then these are the problems which you embrace when you embrace a new technology... :-)

PS: Even after all these things... Whidbey is a cool thing to start working on ASAP... :-)

Tuesday, November 09, 2004

VJs Tip Of The Day - November 9th 2004

Xml Schema Generator Utility

.Net Framework provides a command line utility called xsd.exe which can do various Xml schema related tasks... If you provide xml file to the utility it can generate a schema for it... If you provide an assembly it can generate schema for the its types... If you provide it with a schema file (.xsd) then it will generate class code for you in the language of your choice...
It can also convert a .xdr file to a .xsd file... If you want to know more Click Here

PS: I am trying to work a little bit on Whidbey these days so I will try to post in interesting stuff on that...

PS: Today was "Father's Day" to me... It was my dad's birthday today and so I believe ideally that should be father's day to me right!!... Happy Father's day to me and little bro... Sometimes my mind denies to accept the days selected by companies like Archies and Hallmark to celebrate "Mother's Day" and "Father's Day"... I sometimes feel its a big marketing strategy but then I console myself that there is nothing wrong in making your father feel special twice right!!... Anyways, Happy Birthday Baba...

Friday, November 05, 2004

VJs Tip Of The Day - November 5th 2004

XmlDocument on WebService

This is just an observation which you can make... If there is a web method in your webservice which takes or returns a parameter of type System.Xml.XmlDocument then it gets converted into System.Xml.XmlNode on the client side (if you are using .Net on both the ends and adding web reference via wsdl.exe)...

ie if your service web method definition looks like below...
_
Public Function GetXmlDoc(ByVal Id As Integer, _
ByVal doc As XmlDocument) As XmlDocument
End Function

The proxy definition of the same method will look like below...
Public Function GetXmlDoc(ByVal Id As Integer, ByVal doc As System.Xml.XmlNode) As System.Xml.XmlNode
Dim results() As Object = Me.Invoke("GetXmlNode", New Object() {Id, doc})
Return CType(results(0),System.Xml.XmlNode)
End Function


It is an understood behavior that for WSDL you are always receiving a XmlNode if it is a document for you then you are suppose to implicitly convert the same into a XmlDocument...

I do wish that there was a special indication in WSDL which could inform the proxy generator whether a node is expected or a document is, but that is more to do with the WSDL file format right!!...

PS: Have a wonderful weekend... :-) If you are reading this mail on Monday then decide right away that you got to have a wonderful next weekend... If you were 'requested' to work over this weekend even if you had to do something for yourself at that time, then better start taking lessons on 'being affirmative'...
:-) If you have not seen the movie "Office Space" then make sure you grab it from somewhere and watch it next weekend... To an extent it helped me laugh at my own doomed situation... :-)

Thursday, November 04, 2004

VJs Tip Of The Day - November 4th 2004

Whidbey - Partial Classes

In Whidbey it would be possible to split huge class files into multiple parts... The keyword used for that is partial... The same keyword works for struct or an interface... When the assembly is compiled then all these files will be merged into one... This can be usually useful when multiple people have to work on same class or when autogeneration is used...
Due to autogeneration getting more and more popular now days the problem that exits currently is that if you modify any code in autogenerated files then again autogeneration with updates causes loss of the manual changes made... by using partial classes you can seperate the autogenerated and manually coded files...

e.g.
// This is the first file.cs
public partial class SameClass
{
public void AutoGenratedMethod()
{
}
}
// This is the second file.cs
public partial class SameClass
{
public void ManuallyCodedMethod()
{
}
}

PS: Next time you get a speeding citation do not pay it off directly... It is better to appear in the court if possible and explain your scenario, judges are usually understanding and if they do not reduce the fine they will probably reduce the points on your drivers licence... It also gives an implied message that you are concerned about your citation and so are ready to appear in the court... Many US states also provide you with an attorney to fight for you in case you have not hired one... :-)

Kathleen has added below points

Partial classes helps with code generation only in minimilast scenarios.
While it is very important there, derivation will remain the prime mechanism for customization - although not everyone has wandered down that road far enough to realize it.

Wednesday, November 03, 2004

VJs Tip Of The Day - November 3rd 2004

out parameters and proxy class in web services

There is a interesting thing to know about 'out parameters' in web services... Consider a scenario in which you have a web method which returns void but has some out parameters... When you try to create a proxy (when you add web reference to your web service), you can notice that the first out parameter is converted into return value on the proxy side...
This is important to know because if you are exposing your webservice without return value and only out parameters then you would definitely have a reason to do so and such behavior of the proxy generator might be unexpected, but that is how WSDL understands it and so you have to live with it...

For more information on the topic Click Here

PS: SharpReader is one of the most widely used RSS Aggregator... You can subscribe to many blogs via RSS after installing the same... You can download SharpReader for free at http://www.sharpreader.net/ and then click on File->Open RSS feed you can then type the RSS feed url for the blog and click subscribe... RSS feed url for all blogspot sites are similar to mine which is http://vishaljoshi.blogspot.com/atom.xml

Tuesday, November 02, 2004

VJs Tip Of The Day - November 2nd 2004

Why A HashTable Cannot be Xml Serialized

Javeed has posted the below question and it was probably a well asked question... Please read the mail below...

-----Original Message-----
From: Javeed Shaikh
Sent: Tuesday, November 02, 2004 10:17 PM
To: Vishal_Joshi@MVPs.org
Subject: Re: VJs Tip Of The Day

Hi Vishal,

I would like to know why a HashTable cannot be serialized?. Answer should be other than it is not inherited from some Interface, because this is the answer i got from many forums but no satisfactory answer.

Kind Regards

Javeed

Answer
There are many classes in .Net which cannot be xml serialized and they have their own reasons behind it... Ofcourse the default answer to a question -Why a particular class is not getting serialized? Is that it does not implement ISerializable, but it is good sometimes to reason out why did the .net class library team not implement ISerializable for them and many a times even if ISerializable is implemented why does Xml Serialization still is not truly functional for these classes... Wouldn't it be nice to have all the framework data carrying classes serializable (let's not get into this!!)... Well, here is the reason for Hashtable... The reason can be tweaked and extended to members which implement IDictionary...
For members with indexers XmlSerializer expects the index to be an integer, in case of hash-table its a key-value pair and thus not necessarily an integer... This makes the default HashTable not serializable for XmlSerializer...
Thus calling the below method will throw an error at the text marked bold...

Imports System.IO
Imports System.Xml.Serialization
Class DoSerialization...
Public Sub Serialize(ByVal hst As Hashtable)
Dim serializer As New XmlSerializer(GetType(Hashtable))
Dim writer As New StreamWriter("C:\Hastable.xml")
serializer.Serialize(writer, hst)
End Sub

The error thrown in the above code will be:
"An unhandled exception of type 'System.InvalidOperationException' occurred in system.xml.dll
Additional information: There was an error reflecting 'System.Collections.Hashtable"

and now perhaps the reason must be evident as to why there is a reflecting error...

How do you work around for this problem... Easy way would be to copy the content of the hash table into something that is serializable (e.g. array) and then on the other end again deserialize the same back into a hash table if it is that important to use a hash table... :-)

Further comments are invited...

PS: There have been rumors about MS Student Ambassadors being paid and doing favored jobs for Microsoft for personal benefits... Folks like Student Ambassadors, Community Stars, MVPs etc are volunteers who are passionate about their respective technologies and so are evangelists for the same, they do not expect anything in return... A very active student ambassador named Sriram Krishnan, who is associated with CNUGStudent and other community activities has replied on one such allegation... Me and many others in the MVP community had appreciated Sriram's mail and I requested him to allow the mail transcripts to be posted on the blog... Below are the details (read from bottom up)...

-----Original Message-----
From: Sriram Krishnan
Sent: Tuesday, November 02, 2004 1:48 AM
To: 'Vishal Joshi'
Subject: RE: request

Go ahead - its time people heard our side of the story. And thanks for the kind words - nice to know that all you guys are there to back me up :-)

Sriram

-----Original Message-----
From: Sriram Krishnan [mailto:ksriram@gmx.net]
Sent: 01 November 2004 13:17
To: 'rms@gnu.org'
Subject: Microsoft Student Ambassadors and .NET presentations

Hi,

A friend of mine forwarded me your views on Microsoft Student
Ambassadors and .NET sessions. I'm one of the Microsoft Student
Ambassadors involved in this and I wanted to reply to
clear up some of the misconceptions in the original mail. But I thought an intro on MSAs and that we do would be appropriate.
Before anything else, let me state that I have huge
respect for the GNU movement and for you personally. I do not want to enter into any argument on our differing views- but rather give you the full story as I fear you have formed a opinion without having all the facts. I admit that my views differ - but I am a technology
enthusiast and I run 2 different GNU/Linux distros at home . So by no means am I a
'M$ spy'. Microsoft roped me in as a student ambassador after seeing some of efforts to spread technology awareness. They do not pay me in any way - apart from the odd t-shirt and CD, everything we do is on our own and is not motivated by any benefit from
Microsoft. And I'm not looking for a job there either - I've already got a job in an Indian company which I plan to take up when I finish college. By the way, Microsoft is deceiving people when they say this is an open standard", since in the US they are trying to patent some
aspects of it. It could be useful to bring that up and expose it.
I'm not sure whether you've been told the entire story. We never wanted to do a session on Microsoft .NET. It would be *highly* improper for us to talk about any proprietary software in a GLUG meeting. I have no intention of doing that. What I wanted to talk about was Mono - as we felt that the Mono license was good enough for the meeting.I admire Miguel and his team and the work they are doing. However, we were told that Mono was not acceptable
as though the license is ok, it is *tainted* as Microsoft is behind the original technology. I totally understand that logic and would have been happy to let it go if that logic had been followed without any break. However, this same group had recently had a session on
Java, whose roots are definitely not free and Sun, to this date, hasn't published their source code. What I ask is - why the double standards? Isn't proprietary software unacceptable at a GLUG meeting? Why allow a demo of Java but not a demo of Mono?
We were asked to do a session on DotGNU. I personally disagree with some of the things that the DotGNU page says and Mono is the better-known of the two. When I wanted to have a debate about this on the mailing list(which ballooned into a flame war) or during the
session itself, I was told to go pound sand and not to send any more mails on the topic. The moderator wasn't even interested in listening to the views of the members as a lot of members did express an interest in Mono.I'm very disappointed that a GNU group doesn't believe in hearing other people's opinions and in rational debate.
Let me make something very clear - at no point was I talking about Microsoft or any proprietary software. I talked and intended to talk only of Mono and of its license and the Mono teams views (from their faq page). I understand that you and several others have reservations over Microsoft's ECMA standards. However Sun's Java process is not even an open standard - so why allow Java and show me the door?

From what you are saying, it sounds like they are starting phony "open source" groups. Can you find any specific statements that you can quote? We could embarrass them badly by documenting this, but we need specific quotes, specific proof.

You are very right in asking for proof. I am well-aware of the differences between open source and proprietary software. What we form are usergroups, not too different from the communities you see on Usenet , or Apple Mac fans, for example. Every month or so, we ( a bunch of .NET enthusiasts) meet at a place where one of us takes a session on some aspect of .NET. I try and encourage people not familiar with .NET to come and attend. Let me make one thing *very*
clear - we do not call ourselves an 'open' group or try to pretend to be something we're not. We want people to attend who know fully well what kind of sessions they're attending. I do not have any intention of trying to fool or misguide people by calling our groups 'open' or calling Microsoft software 'open source'. I do talk about Rotor and Microsoft's Shared Source License.
However,I know that the SSCLI is not a license that is accepted by the FSF. I do not fool people by telling them that it is an 'open source' license. In fact, during my sessions, I highlight
the part of the license where it says people cannot make any commercial
profit and other key differences between this and the GPL. We do not want people to think that Shared Source is something it is not - we want people to only use Shared Source only when they *completely* understand what the license is about. I have at no point of time
called Rotor as 'free software' - what I have said is that 'Rotor is a free download' which is meant to inform students that they don't have to pay to download it. IANAL, and I tell students that the Shared Source license and the GPL are very different and then encourage them to find out the specifics for themselves. And at no point in my sessions do I deride the GPL or any other open source license or claim that the SSCLI is better. I want to tell people what it is and that it is out there - people can make an informed choice for themselves.

There is nothing phony about us or in our love for technology. I understand that you may not agree - but please do understand that I'm not a thief or a spy trying to fool people. I've asked Joe Steeve (the moderator of the GLUG-Madurai) to attend our sessions to see for himself
what we talk about but he hasn't turned up once. However, as someone who has done
over 10-15 of these sessions, let me assure you that these sessions are usually about some intricate aspect of .NET and the only time we've spoken of GNU/Linux is when people have asked us whether .NET can be run on Linux.

2. Recruit a couple of people to pretend to be interested in joining, go to the meeting, and speak up within it to identify the lies.
I have been saying this for a long time. I try and encourage discussion and debate in our group and would love to have other points of views. However, I'm afraid they won't see any choice quotes bashing GNU/Linux or the Free software movement. What they'll see is a *lot* of technical information on Microsoft software.

4. Treat the MSA program and its representatives as liars. Don't treat them as respectable or legitimate.
I object to this - how have I lied? Our opinions differ , yes. But I do not try to fool people. And the original mail had accused me of lying - I would like to see some proof of this 'lying'. Proprietary software nutcase I may be, spy or liar, I am not.

I regret that you have been pulled into this and not been given the whole story. I do not agree with some of the things the FSF says,but I do not think that means I'm a liar or evil in some
way.I sent you this mail as I'm highly saddened that someone I admire a lot and someone whose work I use everyday(I'm an Emacs fan) has branded me without getting all the facts.
It is possible I am misguided - I am only 20 years old. But I'm not consciously trying to harm anyone or fool anyone.

Thanks,
Sriram



-------- Original Message --------
From: Richard Stallman
A MSA who was pestering me for a DotNET session at
GLUG-Madurai argued that DotNET being an Open Standard, I should not
object him promoting it in the GLUG.

When he said this, he was taking advantage of a broader
misunderstanding. The idea of GNU/Linux is to be free
software; "open standard", even if that is true, is not good
enough if the software itself is non-free.

So it looks like we need to educate all GLUGs (and
LUGs, if they will listen) to recognize and teac that people should not promote
non-free software--regardless of the details.

By the way, Microsoft is deceiving people when they say
this is an "open standard", since in the US they are trying to patent some
aspects of it. It could be useful to bring that up and
expose it.

The lesson that I learn from these people is to
outrightly reject their requests. They are not worth the trouble.

We should always refuse to give developers of non-free
software a platform to speak. However, saying that this is "not worth the
trouble" is misleading, because it is implies there is some
potential good to be achieved--if only it were easier to do.

What they are doing is bad, pure and simple. There is
no good in it.

M$ through its Micro$oft Student Ambassadors
is doing a large scale mobilisation in colleges amongst the
student community. They wrap their stuff under
labels such as "M$s Open Source venture", "Open Technology", etc..
They are forming student groups in colleges.

From what you are saying, it sounds like they are
starting phony "open source" groups. Can you find any specific statements
that you can quote? We could embarrass them badly by documenting
this, but we need specific quotes, specific proof.

If you could go to a meeting where they try to recruit
new people, and make a recording so that you can quote them exactly, that
would be useful too.

Once we have solid proof, we could use various methods
to organize against them.

1. Make handouts denouncing them as a fraud. Whenever
they have an event, a few of you can stand near the door and hand
out copies to whoever is attending. In effect, stage a quiet and simple
protest against each of their meetings, accusing them of lying.

2. Recruit a couple of people to pretend to be interested in
joining, go to the meeting, and speak up within it to identify the lies.

3. Write articles for student newspapers about the deception.

4. Treat the MSA program and its representatives as liars.
Don't treat them as respectable or legitimate.

5. Call on the university to close the program down for lying.
Even if this campaign does not succeed, it will generate public
awareness that will be useful in all ways. So renew the campaign each
year!




Monday, November 01, 2004

VJs Tip Of The Day - November 1st 2004

Serialization Constructor

For your class to be serialized by Xml Serializer it is needed that it has a default constructor... For your class, if you only have a constructor which takes some fixed arguments and does not have a constructor which takes in no arguments the serializer is not able to create an instance of your class to serialize and so it fails with an error..

An unhandled exception of type 'System.InvalidOperationException' occurred in system.xml.dll

Additional information: ApplicationName.ClassName cannot be serialized because it does not have a default public constructor.

Similarly error might also occur in case you are using Activator class's Create instance method for some type which does not have default public constructor and you are not passing the constructor parameters...

So in short if it is not harming the base functionality it is always good to have default constructor for your class...

PS: Most of the manufacturing industries have got their "Labor Unions" in place... These bodies have helped putting a check on unscrupulous and inhumane employers from illtreating their employees... Manufacturing industries have been here since ages, but IT industries have just came into being... How about starting "ILU (Information technology Labor Union)" which will be a social regulatory body that will be a registered organization with WTO and funded by all the "good IT employers"... Being registered in the organization will help employers to go up the ladder in the "Best Companies To Work For" list/awards; also not getting any complains registered against the company in ILU would help... Moreover this body will be a neutral regulatory body and thus any employee working in any IT firm can register a complain and this body will make sure that no injustice will happen to the employee... This body can help employees raise rightful voices which would be given just 'lip services' or even worst deaf ear otherwise... I am planning to write a white paper on this idea; but then I am not sure whom to forward it to... If you have any tips let me know...
BTW, just FYI my employer is treating me really very well, but then I wish everyone feels the same about their employers too... Well this is a big IP I am sharing out on the blog... So the copy rights notice goes along with... If you want to start something of this sort contact me and we will get it rolling... :-)

Thursday, October 28, 2004

VJs Tip Of The Day - October 28th 2004

ASP.Net worker process restarts before the timeout values are reached...

Sometimes your application might err out and if you check the event log you may get an error like "aspnet_wp.exe (PID: Number) was recycled because it was suspected to be in a deadlocked state. It did not send any responses for pending requests in the last 'whatever' seconds"... This would happen even if your ScriptTimeout or Session.Timeout has not reached... Well the reason is the setting in the machine.config file (located in C:\Windows\Microsoft.NET\Framework\v1.1.4322\CONFIG -> version, windows etc folders might be different for you)...
In the section of the Machine.config file, change the responseDeadlockInterval configuration setting to a value higher than your timeout values... Basically this error happens because ASP.Net worker process is restarted as there was no response for the period of deadlock interval specified and so the deadlock detection mechanism restarts the aspnet_wp.exe assuming that it was in deadlock...
This info is useful when you have long running processes and also might be during debugging...

PS: Its a conception that debugging software is not really always easy... And when the software is written by someone else its even more difficult... Sometimes even if you diagnose the problem area; resolving it is even more difficult... Did you realize that same is with humans... I feel, debugging a human is virtually impossible ... And especially if that person is not yourself... Even if you identify what is wrong with that person it is next to impossible to correct it... Oh I wish this debugging things would be easier, I would had been full time "Person Debugger"... would had corrected every buggy person... :-) Just kidding... Lately, I have realized that debugging myself itself is not possible for me, leave alone anyone else... I wake up at uncertain times (sometimes people wish me good afternoon when the day has just begun for me), I sleep at uncertain times (sometimes when I should wish myself good morning, I wish good night), I am trying to fix this problem since I was in high school but instead it has grown more serious with every passing day, there is no solution it seems... I think there should be newsgroups for resolving "person bugs" also... "If you have faced similar issues then plz let me know the solution... Thanks in advance...":-)


Wednesday, October 27, 2004

VJs Tip Of The Day - October 27th 2004

MethodBase.IsFinal & MethodBase.IsVirtual

MethodBase is a class in System.Reflection. IsFinal is a boolean property of this class. If you dynamically want to find out whether a given method can be overridden or not then merely checking IsVirtual flag is not good enough... Look at the following example... Again out of the box running code... Just copy in IDE and run...

Below is our BaseClass... It implements IComparer... It might be any interface I am just taking IComparer for example...

using System.Collections;
public class BaseClass : IComparer
{

public int Compare(object x, object y)
{
return 0;
}

}
Below is our DerivedClass... It does not implement IComparer as its base already does... But still it wants a Compare method in its own way... So it needs to hide the base implementation (not a good OO practice always but this is for example sake)

public class DerivedClass : BaseClass
{
//Note if you do not use new the Derived class will not compile
public new int Compare(object x, object y)
{
return 1;
}

}

So now as usual our quick windows form app... Add reference to System.Reflection and also our class library which contains above two classes in here...

using System.Reflection;

private string CallMeOnButtonClick()
{
string displayText = String.Empty;

Type t = typeof(VirtualTest.BaseClass);
displayText += t.GetMethod("Compare").IsVirtual.ToString();
displayText += t.GetMethod("Compare").IsFinal.ToString();

Type t1 = typeof(VirtualTest.DerivedClass);
displayText += t1.GetMethod("Compare").IsFinal.ToString();
displayText += t1.GetMethod("Compare").IsVirtual.ToString();

}
The displayText at the end will be TrueTrueFalseFalse...

What does this mean... in BaseClass we did not mark Compare method to be Virtual still it came out to be Virtual... This is because it is a implementation of an Interface and so it is automatically marked virtual inside Interface... So it returns us that the method was actually virtual....
Now even the IsFinal flag for BaseClass.Compare is True... This means that even though it might be internally virtual but still it is the final implementation of the method... You can no more override it in the derived class... If you try to put overrides keyword in DerivedClass's Compare method declaration it will not compile giving error that the method is not marked virtual or abstract in the base class... Do note that your IsVirtual value was true for this method though... :-)

In case of Derived class we get IsVirtual to be false, it is obvious because we have shadowed the base implementation and also have no virtual keyword associated with the method here... IsFinal is false here as it is not coming from a interface or any such source which forces it to be true...

So in short... unless and until you do not have both - "IsFinal as False" and "IsVirtual as True" you can override a method...

PS: If you want to get more inquisitive try to derive a third class here... Mark your method as "virtual new" in 2nd Class and override in 3rd class... Try to study the results... If you felt a little bit confused over the whole explanation then try and feel what "Flags" do to any class... The more flags you have more your reader is going to confused... Btw, did we talk about "MethodBase.IsHideBySig" anytime... That also plays a role in above examples... :-)

PPS: Typing the line "?System.Reflection.Person.MoodInfo().GetMood("Vishal",System.Reflection.BindingFlags.Today)" in the immediate window of VS.Net 2003 debugger resulted into "Bad, Very Bad, Very Very Bad, Very Very Very Bad, Very Very Very Bad.................................................................................." :-)

Tuesday, October 26, 2004

VJs Tip Of The Day - October 26th 2004

Converting Collection to Array

Some days back we talked about the way we create a strongly typed collection (Check Oct 14th 2004 Tip)... Now say this collection is returned somewhere and the consumer does not need the collection but needs array of the objects inside the collection...
To make it more clear... Say you have a object "X" and its collection is called "CollectionX"... Now there is a method which is defined in a following way...

public CollectionX GetAllXObjects()


The consumer of this method realizes that he does not want the collection but just something like

public X() GetAllXObjects()

What can be most simply do... Write a method inside the CollectionX class and return back this.InnerList.ToArray(typeOf(X))

The reason for mentioning this is that Innerlist is a protected property and so the consumer will not be able to access it unless he inherits your collection and then tries to access it...

When is it that you are likely to face above situation...? Is is when you are working with webservices and any strongly typed collection on the server side is converted into array of the type inside the WSDL... :-)


PS: Ackg: This came up with my discussion with a colleague Matt...

Monday, October 25, 2004

VJs Tip Of The Day - October 25th 2004

Properties Converted in Public Fields in Proxies

This is an interesting thing which Web Services users should know... Especially if they are working with Visual Studio .Net...
If you have a web service which is passing custom types in the methods... for e.g. you have a method called GetPerson() which returns "Person" object; which internally has FirstName, LastName etc as properties...
Now when you reference the web service, the automatic proxy generator will create Person Class on the client side too but it will create this class with public variables as FirstName, LastName etc rather than properties...
How does this make a difference... Well it does when you start binding those classes with anything else...

You can use CodeDOM to work around it but it sometimes becomes unnecessary deviation...

I would like to invite expert discussion on why not the Microsoft's automatic proxy generator, which generates proxy from WSDL, itself create properties for every public variables... There would be less chances of anyone using public variables; rather mostly they will be used as properties only... And even if they are not used as properties on server side, having properties on the client end is not a bad thing to do... I probably am missing something here but after seeing many people struggling with the same problem, this is what obviously comes to my mind...

PS: Friends and Gifts - I am usually, really confused about what gifts should be bought for whom... So I directly ask "Dear, what would you like as a present?"... reply comes -"Oh no nothing, nothing at all...you are visiting that itself is so nice... " Now when you visit people and that too after a long long time, internally somewhere in their minds they expect that you will bring some presents... What those presents would be is also probably being guessed, but without speaking of it aloud.. Now the funny part in my case is that they are guessing and I am not able to guess what they are guessing... I probably so go to the store and land up buying stuff for myself... :-) I have lately purchased over 5 T-Shirts which I would had never bought if not for those humble buddies of mine... So for benefit of people like me, I would like to appeal that please do precisely tell people what you want as a gift when they ask you... That will make you happy to get the gift you want and even the person in front happier as he will probably no more struggle in a tournament against the whole Consumer Goods Market Vs himself... :-)

Friday, October 22, 2004

VJs Tip Of The Day - October 22nd 2004

Structures - A Discussion

Today's tip is not a tip but is a discussion... Yesterday I had a discussion with a friend of mine over Structures and their presence in .Net... Here are the abstracts of our discussion... Below mentioned are educated guesses and I do not claim 100% gurantee for the information to be correct... I welcome any debates over the topic and would be glad to to learn more in the process... I shall update the related discussion on the blog, along with acknowledgements, in time to come...

A simple question!!... Should we ever use Structures in managed .Net development at all? and if so then when?

Here are some of the thoughts...
We all know that a structure is a value type and a class is a reference type, other than this what else, how does it help us answer our questions... Well, we should also know that inheritance is not possible with structure so anyways for such class specific uses we should never use structures... As sturcture is a value type, it is an obvious thought that structures will be faster but is it really true?
Consider the following... You are using a structure with 4 properties; the data type for all these properties is string. Now string is a reference type so where does string go... Structure is a value type and it resides on the stack; string is a reference type it should reside on the heap, right!!... We should agree that string will not get automatically unboxed to get into stack and it is not possible also...Now if all your properties go and stay on the heap because they are reference type then where is the advantage of struct being faster??
So few of the situations where you could use structures over classes is when you know all the internal datatypes to the structure are value types... If you know that you have stuff like just integers and charcters in a class then you can as well have it as a structure and prevent GC from getting burdened with collection of the class...
Other instance where you could use structures is when your interoperability demands it and that is probably the primary reasons for existance of strctures... It is also probably the ease that C++ developers whould have coming to .Net...
We should also care to think that Structure is sequential data type and so the data is allocated as it comes, there is no management with the memory done here... In case of class as it is on the heap and so the memory can be managed, this can ensure that proper compression and alignment of memory happens which is not controlled in structures... But as we talked earlier the drawback with classes is that even though your object might no more be used you are not sure when GC will come and clear it and moreever it is also more work for the background thread...
Well these are some of the thoughts... There were more but they would lead to firecrackers so am holding on to them.... You guys are welcome to post in your comments and ideas...

PS: What a struggle it is to adopt to a new Version Control System; this can be briefly explained by someone like me in atleast over 2000 words essay... In just past 1 year I have used VSS, RMS, Dimensions, StarTeam, Sourcegear Vault and I don't know what not... As usual I messed up this time too... My work for over 1 week was swallowed by the Version Control just as if it was a magician and I was its sole spectator... As usual again I kept looking onto the screen and saying "It can't be... common it must be somewhere... search the machine... Ohhhh no no, it can't be... " Well these Version Control Systems are irreversible magicians in my case... Many came tried something and finally said to me, you are dumb, how could you do that... and then again... "Oh!! it can't be..."; But you know what, I just realized that it's a friday today... I will think about this crap on Monday... This time I really need to go to the "TGI Friday", the name 'Thank God It's Friday' really means something to me today...



Thursday, October 21, 2004

VJs Tip Of The Day - October 21st 2004

Structure Vs Classes - The finer ones

This one is a double tip as yesterday there was none... This is information + TODO exercise... Spend some time here to copy the below code in VS.Net and try running it.. It will run out of the box you won't have to trouble yourself a lot... Btw, its VB again... Don't ask me why, the silly reason is that I made a VB project by mistake and did not want to delete the folders...

Well the information below talks subtle difference between classes and structure and the way it effects Reflection...

Setting Properties via Reflection


Make a class library and paste the below code in the default class created...

Imports System.Reflection


Namespace VJ
Public Class GoodBoy
Private _setMeIfYouCan As String
Public Property SetMeIfYouCan() As String
Get
Return _setMeIfYouCan
End Get
Set(ByVal Value As String)
_setMeIfYouCan = Value
End Set
End Property
End Class

Public Structure BadBoy
Private _setMeIfYouCan As String
Public Property SetMeIfYouCan() As String
Get
Return _setMeIfYouCan
End Get
Set(ByVal Value As String)
_setMeIfYouCan = Value
End Set
End Property
End Structure

Public Class Setter
Public Function SetClass(ByVal newString As String) As Boolean
Dim gb As New GoodBoy
Dim gbType As Type = GetType(GoodBoy)
Dim propInfo As PropertyInfo = gbType.GetProperty("SetMeIfYouCan")
propInfo.SetValue(gb, newString, Nothing)
If (newString.Equals(gb.SetMeIfYouCan)) Then
Return True
End If
End Function

Public Function SetStructure(ByVal newString As String) As Boolean
Dim bb As New BadBoy
Dim bbType As Type = GetType(BadBoy)
Dim propInfo As PropertyInfo = bbType.GetProperty("SetMeIfYouCan")
propInfo.SetValue(bb, newString, Nothing)
If (newString.Equals(bb.SetMeIfYouCan)) Then
Return True
End If
End Function

End Class
End Namespace


Make a windows application... On the form drag and drop a button... Paste following code for the button... Remember to reference your class library into the windows app...

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim setter As New VJ.Setter
Dim flag As Boolean
flag = setter.SetClass("I am a GoodBoy")
flag = setter.SetStructure("Life Sucks")
End Sub



Observations: The first time flag will become true next time it will be false... i.e. Even though your reflection calls on structure will execute sucessfully (without throwing any exception) the properties will not get set...
The values within the structure in this case do not get modified by reflection and so if you want to use reflection anytime for your entities make sure you declare them as classes...

There is a candy and special mention for a person who will give explanation behind the occurrance... (ofcourse more detailed that value type/reference type one... :-))

PS: Most common pets people have are either cats or dogs... Usually, people who love dogs don't like to have cats as pets and probably so is true visa versa also... Now, this "Pet Phenomenon" is slowly engulfing us to such an extent that I have heard people saying "I am DogMan... I hate cats"... and so on... Well that "DogMan" thing struck me right away... DogMan, CatWoman, DogWoman, CatMan... believe me if I were a dog and I heard a man saying that he was a 'DogMan' I would really feel proud... I think pets can have comeptition in their gatherings as to how many humans did they convert into DogMans, DogWomans and so on... Once they achieve considerable success in this mission, they will eventually move up the quality ladder and will have targets like converting DogMans into BullDogMans, GreyHoundMans and so on... :-) So the next time you want to see a smile on the face of your pet, stand in public with the pet (especially when other people's pets are around) and annonce to everyone that you are a "DogMan" or ..... :-) Btw, I am a DogMan... :-)

Tuesday, October 19, 2004

VJs Tip Of The Day - October 19th 2004

Targeting Different Web Service URL Dynamically

When we add a web reference it is usually assumed that it is going to point to a fixed WSDL file... Well this can be changed or made configurable and here is how you can do it...
After you add a web reference to a web service... Right click the web reference and go to the properties... You will find property namely "Web Reference Url" which states the url of the WSDL file of the service... There is another property called "Url Behavior" which is set to Static by default... This is the property which you need to set to "Dynamic"... Once you are done setting the same... In the config file of your application add the following key....

<appSettings><add key="SearchEngine.Google.GoogleSearch" value=http://localhost/MyOwnSearchService/SillySearch.asmx/></appSettings>

In the value part of the config file you can change the value to any other WS that you feel like... Consider this in your design in case you are likely to change the Web Service or are often likely to keep yourself updated with the changes that the provider is doing...

PS: Corollary To Earlier Mail: Again I am feeling 24 hours are not enough.. Today even the Starbucks got closed before I could reach there, sit and ponder... It was cold outside and no one was jogging with his dog either, it seems that sometimes what ever perspective you take the day still seems to be bad... :-) Well the consolation today is that if everyday was very good and easy then where is fun in life... :-)

Monday, October 18, 2004

VJs Tip Of The Day - October 18th 2004

Interface Based Activation

This is especially for all those early programmers who use to do Interface based programming... We use to do runtime late binding in which we came know the ProgId of the component to be created only at runtime... This use to make dynamic creation of unknown classes easy... Now in case of .Net how do we do it? It is incorrect to assume that we need assembly reference or atleast the name when you are coding the consumer class... Well here is the alternative way...

Let us take an example... I have various locations to store my data, like Xml, SQL Server, Resource File etc... Now I need to select the DataAccess at runtime based on config or registry settings or something like that and I also need to have the option of adding any other data store in the time to come.... What do I do?

(Special VB.Net edition... Kathleen, Anand M and other VB fans can all be happy... :-))


'Your data structure can be defined below
Public Structure DataEntity
Private something As integer
End Structure

'I will define an interface called IDataStore
Public Interface IDataStore
Function GetDataById(ByVal id As Integer) As DataEntity
Sub UpdateExisitingData(ByVal id As Integer, ByVal entity As DataEntity)
Function InsertNewData(ByVal entity As DataEntity) As Integer
End Interface

'Sample class to get your config settings
Public Class GetConfigValues
Public Shared Function GetConfig(ByVal key As String) As String
'This will go at runtime to some config place to get the details as per the key passed
'If your company is using SQL as datastore then it can get connection string as param
'and the SQL access class as the class name and so on...
If (key.ToLower().Equals("constructorparam")) Then
Return String.Empty
ElseIf (key.ToLower().Equals("classname")) Then
Return "AssemblyName.ClassnName"
End If
End Function
End Class

'Below is the generic class which exposes the Interface in a special way
Public Class GenericDataAccess

Private objRuntimeStore As IDataStore
Public Sub New()
Dim objConstructParams(0) As Object
'GetConfigValues is your custom class to get your config settings
objConstructParams(0) = GetConfigValues.GetConfig("ConstructorParam")
'The class name should have the fully qualified name i.e. the assembly name too
Dim storeClassFullName As String = GetConfigValues.GetConfig("ClassName")
objRuntimeStore = CType(Activator.CreateInstance(Type.GetType(storeClassFullName, _
False, True), objConstructParams), _
IDataStore)
End Sub


Public Function GetDataById(ByVal id As Integer) As DataEntity
Return objRuntimeStore.GetDataById(id)
End Function

Public Sub UpdateExisitingData(ByVal id As Integer, ByVal entity As DataEntity)
objRuntimeStore.UpdateExisitingData(id, entity)
End Sub

Public Function InsertNewData(ByVal entity As DataEntity) As Integer
Return objRuntimeStore.InsertNewData(entity)
End Function
End Class



PS: The code and example is just to demonstrate one of the way by which you can hook up with a class at runtime... Do not consider this to be ideal design methodology or coding practice example... If you write back to me saying this can be better done in x or y way all I can do is probably agree with you... :-), but it would be nice if see this as a solution to a very specific problem...

Friday, October 15, 2004

VJs Tip Of The Day - October 15th 2004

IComparable Interface

This interface is a mode to do comparison of two objects of a given type... This is used when you want to provide ordering/sorting capabilities for you object...

If you have an array of your object and you wish to call the sort method on that array, the implementation of this interface will help do the sorting... To implement IComparable you need to override the CompareTo method in the following way

int IComparable.CompareTo(object obj)
{
Person objPerson =(Person)obj;
return String.Compare(this.firstName.Trim() & this.lastName.Trim()
,objPerson.firstName.Trim() & objPerson.lastName.Trim());

}


PS: There is a wonderful festival celebrated in Gujarat, India called Navratri which is beginning this weekend... Nav-Ratri means Nine-Nights and that's how long the festival is celebrated... In this festival there are folk dances done called Garbas and Dandiyas... Dandiya is the folk dance which is done by holding small sticks in hand and making rhythmic moves and touching the sticks in the hands of your partner... In Gujarat, you would find nearly all the streets flooded upto dawn with people in cultural dresses during this festival... In my home town Baroda, Gujarat there are grounds set up where close to 10,000 (probably even more) people can dance at the same time... As usual even in these cultural events girls get free admission and guys have to buy passes to enter the dance floors... One fine day we will have to start... "Men's libralization" movement...
Btw, we have Navratri celebrations nearly in every city of US too... Though not that grand but not bad at all... So this weekend will be fun...

Thursday, October 14, 2004

VJs Tip Of The Day - October 14th 2004

Custom Collection Properties

We see many properties in .Net controls which have collection of items... Example can be items collection for drop down list which contains selected as boolean; Name as string and value as string...

If you need collection properties for your class or custom control... This is what you do...
First make a class whose collection you require... Say for example you need collection of Names, and each name is a class having three other properties like FirstName, LastName and MiddleName... So you first will have to make your class "Name" and then the next class "NameCollection"... The name collection will inherit from CollectionBase... Then you override the required functions to achieve your functionality...

Below link will help you learn more... Click Here

PS: I am undergoing a skin treatment with liquid nitrogen now...There was this small little tiny invisible kind of wart like thing on my toe which had never bothered me till I had one regular visit to my dermatologist... While waiting for the doc, I saw some flyers on the neary by table, unfortunately i picked them up and read all of them, discovering the various possible deadly diseases skin can develop, I thought I should show this thing too, may be it is starting of Squamous cell or might be even Malenoma... So I showed my toe to him... He concluded that it was nothing serious but we should still treat it for my own good... Ofcourse I had to agree to anything that was for my own good and moreover I did not want to die a ignorant death coz of late discovery by a unaware fool like myself... So there I was, a healthy running fella getting liquid nitrogen sprays on my feet...I bet if 00.08% of 78.08% of nitrogen in atmosphere becomes liquid we all would die, believe me thats how liquid nitrogen is... Earlier I was running now for some days it is difficult to walk... That whatever thing on the toe is has remained as it always was and will need 2 more weeks of treatment... Folks, I have decided one thing, which I want you too to consider - Even if life gets boring at times do not, DO NOT try to research various possibilities of various unheard illness attacking you... Well!! I was kidding... liquid nitrogen is fun... all of you check your skin and find where you can have them... :-)

Wednesday, October 13, 2004

VJs Tip Of The Day - October 13th 2004

VB.Net InterOp with C# - Optional Parameters

Have you ever wondered about the way VB.Net Optional parameters work with C#... Here is small little exercise to find more... I wrote a simple assembly, with a simple class, with a simple method in VB.Net as follows:

Public Class VBOptionalParamsClass
Public Function OptionalParams(ByVal id As Integer, _
Optional ByVal str As String = "", _
Optional ByVal flag As Boolean = False _
) As Boolean
Return True
End Function
End Class

Then I wrote simple winform exe, with a single button in C#... From here I called the VB.Net assembly as follows:

private void button1_Click(object sender, System.EventArgs e)
{
MyNamespace.VBOptionalParamsClass cls = new MyNamespace.VBOptionalParamsClass();
cls.OptionalParams(1,"something",true);
}

Now the point worth noting here is that all the optional variables in VB.Net became regular variables in C#... I was wondering why couldn't C# compiler create automatic overloads for all those optional variables... Well I do understand that permutation combinations will land up making 16 methods out of 4 optional variables but then there can some way by which only "incremental overloading" {my term} is done... for example in C# I could have

cls.OptionalParams(1)
cls.OptionalParams(1,"something")
cls.OptionalParams(1,"something",true)

I wonder what other implications could be like code repetition in MSIL for all methods or whatever, but then this is just a thought...

With that let us also look at the way MSIL for the method with optional parameters look like... Here we go...

.method public instance bool OptionalParams(int32 id,
[opt] string str,
[opt] bool flag) cil managed
{
.param [2] = ""
.param [3] = bool(false)
... goes on further}

What you can note here is that ther is a [opt] keyword which is thrown into MSIL by the compiler... and also the first lines of the method def contain the default values for the string and boolean parameters which are passed as optional parameters...

That is also one of the reasons why in VB.Net you cannot have Optional parameters without default value...

In anycase while writing your code in VB.Net do make sure that you do not have any Optional values (atleast not in the public interface) as it will not solve its whole big purpose in case your assembly is going to be used by many other apps whose coding language is unknown...


PS: I apologize for not being able to send any tip yesterday... I got caught up in a lengthy discussion with my friend over something more managable and less complicated than software - LIFE... {intentional strong pun was intended!!) just as footer, After more than 2 hours of telphonic conversation I had ended up finding it more unmanagable and more complicated than what I started with... As a result it was better to go to sleep than to think about trivial issues technology... :-)

Monday, October 11, 2004

VJs Tip Of The Day - October 11th 2004

Pagination in ASP.Net DataGrid

Quick steps to work out pagination in your datagrid.. Go to your data grid properties... Set AllowPaging property to true... Set the PageSize to your desired page size... Now go to events section in the properties... You have to override PageIndexChanged Event... In the event handler... Write code similar to the one below:

private void dgdImages_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
//Change the current page index to the new one
dgdImages.CurrentPageIndex = e.NewPageIndex;
//Update your data if required
dgdImages.DataSource = CreateDataSource();
//bind the data again
dgdImages.DataBind();
}

That's it... Your datagrid does not need to make your page long scrollable now... Do note though that if you change the data in the background and the new data does not contain as many pages as your current page index now you might land up getting exceptions... So make sure that you do the necessary work there...


PS: I was driving my car today, trying to rush home from work, had to do some groceries and go to library to return books and read a martin fowler's new design pattern discussion and cook and have dinner and then go to photocopy some legal documents... Oh!! I felt... 24 hours are just not enough sometime... Then I saw a guy casually walking his dog and listening to his discman... I passed by and then pulled over... Thought for while...where was I actually going wrong, why was his life so different and nicer than mine... Why life has to be unjust, just to me.. And you know what I did next... Drove to Starbucks coffee house... Took a nice tall mocha and spent 30 minutes thinking of my own design pattern... I am paying $2 fine on the library books now and I spent $5 extra at the coffee house but then Ahh!! what a realization... My life was not much different than his, it was just in the way I looked at it...

Sunday, October 10, 2004

VJs Tip Of The Day - October 8th 2004

switch case statement

If you face an error like "Control Cannot fall from one case lable ('case:1') to another" while using switch statement in C# then the reason for that is you are not using a break statement after every case and compiler tells you that in case of switch statement the flow cannot continue from one case to annother...
Well VB.Net folks don't have that problem... Btw do make sure that you always have a default:break; statement for failover situations in the switch...

PS: I know this tip has silly, (everyone knows kind of) information but I got a little bit busy with my photography... The same no work on weekend philosophy...

Thursday, October 07, 2004

VJs Tip Of The Day - October 7th 2004

Serializing Exceptions for Special Purposes

We should be aware that Exception class implements ISerializable interface for its serialzing needs. If we derive our own exception from ApplicationException and we anticipate chances of our exceptions to be marshalled across process boundaries we need to add [Serializable] attribute to our custom exception... Along with that we might have to implement ISerializable which can be done in the following way:

Have this special contructor and add each private member variable that you want to persist

protected customException(SerializationInfo info, StreamingContext context):base(info,context)
{
_myProperty = info.GetString("_myProperty")
}

Override the GetObjectData method

public override void GetObjectData(SerializationInfo info, Streamingcontext context)
{
info.AddValue("_myProperty", _myProperty)
base.getObjectData(info, context)
}

PS: While browsing through the Microsoft site I found that MS is offering a free skill assesment for .Net (usually worth $40) to everyone... Click Here for details

Wednesday, October 06, 2004

VJs Tip Of The Day - October 6th 2004

Error Redirection in case of Html or ASP Pages

I am not sure how many of you remember our old tip somewhere in the month of June... It was about the way to set Error Redirection page from web.config and how SmartNavigation options makes it goes crazy and work around for that... Well Click here if you want to read it...

What I wanted to add on to that tip today was that the settings that you do in the web.config files do not work for any .htm or .asp pages... i.e. If a user requests an .htm or .asp page which is not available then then your setting statuscode="404" redirect="pagenotfound.htm" in the webconfig will not work for that you will have to go within IIS metabase to configure the same.

The other interesting fact here is that if you did a xcopy deployment of your applyication then these settings will have to be manually copied to the deployment web server...:-)

PS: When things don't turn out the way you want them to be try and think "Today is the first day of the rest of my life... Let me start afresh with new determination and vigour..."

Tuesday, October 05, 2004

System.Data.OracleClient not working

This is third time that this question has come up and perhaps it is good to have solution up there at the blog...
Please read down to up...
hi vishal,
Thank you very much for your help. I downloded that dll and it worked by adding reference.
I also found 1 more solution. Similar to microsoft, oracle provides driver as well which is downloadable frm its site. Its abt 80 MB.
Regards,
veeral Oza
--------------------------------------------------------------------------------
From: Vishal Joshi [mailto:Vishal_Joshi@MVPs.org]
Sent: Wednesday, October 06, 2004 7:28 AM
To: Veeral Oza; gangadhara.deepadiah@morganstanley.com; 'Sarang Datye'; sdatye@yahoo.com; scripthappens@hotmail.com
Subject: RE:
Please go manually and add reference to Program Files\Microsoft.NET\OracleClient.Net\System.Data.OracleClient.dll it should work then... If you do not have the same dll on your machine then go to the below location to download and install it on your machine...
http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=4F55D429-17DC-45EA-BFB3-076D1C052524
warm regards,
Vishal Joshi
Microsoft MVP .Net
If You Think YOU CAN... You Can...
--------------------------------------------------------------------------------
From: Veeral Oza [mailto:VeeralO@KPITCummins.com]
Sent: Tuesday, October 05, 2004 7:34 AM
To: gangadhara.deepadiah@morganstanley.com; Sarang Datye; sdatye@yahoo.com; vishal_joshi@mvps.org; scripthappens@hotmail.com
Subject:
Hi,
To connect to a oracle 9i database, we have to start with this syntax
Imports System.Data.OracleClient(for VB.Net)
I do hav dotnet framework 1.1 running on my PC, but it still gives me an error
"Namespace or type 'oracleclient' for the Imports
'System.Data.oracleclient' cannot be found."
The connectivity works fine with SQL server.
What might be the reason that I m getting this error?
Regards,
Veeral Oza
Systems Executive

VJs Tip Of The Day - October 5th 2004

Cache.Insert Method & Call Back function

System.Web.Cache has a Insert method where by you can insert values inside the cache. This method has various overloads and what is worth knowing about one of its overload is the Callback function it provides... You can provide your own callback function here which will be triggered when a the item you just inserted is removed from the cache. This callback function gives you the key of the item removed, the item itself as well as the reason why it was removed. The reason is given back as an enum which can be either dependency changed, expired, removed or underused...
You can use this callback function to write your custom logic on what you would want to do when the item gets removed. for e.g. To retrieve this item from where ever is a CPU intensive job, you do not want it to be done at runtime... Then within this call back function you can spawn another thread to restore this item into cache...
Alternatively if the item was dependant on a file and file change was the reason it got removed you can do you alternate processing... You can also do a logging of cache item removal by anyone in the application by using this callback...
In short this is a useful callback function and you should look upon the options...

Refer the link for further information: Click Here

PS: A friend of mine (Deepa C) sends a good morning mail every morning... She has some amazing information and my favorite Calvin & Hobbes cartoon strip in the mail every time, today she wrote a notable information which I thought I should share with you folks... "The slogan on New Hampshire license plates is 'Live Free or Die'. These license plates are manufactured by prisoners in the state prison in Concord." (for non-US readers - Vehicle plates in most of the states of US carry a slogan representing the state)

Monday, October 04, 2004

VJs Tip Of The Day - October 4th 2004

Assembly.GetCallingAssembly() Method

GetCallingAssembly() is a static method of Assembly class. You can use this method within your class libraries to find out which assembly has actually made a call to your current assembly.
This method can be really useful in case you are doing Logging or tracing functionalities as you often would like to register who was the caller to your assembly. As GetCallingAssembly method returns an assembly to get a simple string format of the full name would be something like:

Assembly.GetCallingAssembly().FullName.ToString()


PS: I have started following a new little practice... Just before I go to sleep while lying in the bed, I spend just two-three minutes to talk to myself about how would I want my tomorrow to be... What can I do with given resources that would make it an ideal day, what are the tasks that I gotta do, what are ones which are out of scope... I do requirements gathering and project planning for my "Project Tomorrow" in these two-three minutes... Believe me its working well... Interesting enough it makes me wonder what good requirements gathering and project planning would do to software projects... :-)

Friday, October 01, 2004

VJs Tip Of The Day - October 1st 2004

Setting Timeouts for WebServices

If your webservice takes a long time to finish its expected task and you wish to increase the timeout values for your webservices following are few things you should look at:

Make sure that you set the desired timeout for your script. You can do that in your webservice by Server.ScriptTimeout = 2000 * 60 //(your value)

Also do note that the timeout for the proxy consuming the webservice should also be modified and should be made more than that the timeout of your webservice itself.
There is a timeout property created for the proxy class generated by WSDL tool you would have to set this property before you call your web service.

eg MyProxyClass objMyProxy = new MyProxyClass()
objMyProxy.Timeout = 5000 * 60 //(note the value is more than the web
// service timeout)
objMyProxy.MyWebMethod("take your time")


PS: At times I might not be able to reply to all the queries that you post to me... Believe me I keep them unread and will get back to them at the earliest leisure... I apologize for the inconvinience...

Thursday, September 30, 2004

VJs Tip Of The Day - September 30th 2004

Generating Proxies for WebServices

If you have created web services and wish to generate proxy classes for your webservices then there is a tool in VS.Net called "WSDL"... This tool will take the location of your .asmx file as a parameter and will dynamically generate proxy class for your web service.
There are various switches used by this class like for eg \l:vb will create the proxy class in vb; \o:C:\MyProxyClass.vb will create the proxy class at a particular location. There are many other options check out MSDN for further information. Click here

PS: I have got infected by new kind of psychological disorder... When I am working I look forward to having fun... When I am having fun I look forward to work... During weekdays I wait for weekends, during weekends I wait for Monday to come and rush back to work... I know such situations are called "Circular referencing" or "Cyclic dependencies" technically but I wonder what is psychological term... Pointers would be appreciated!!

Wednesday, September 29, 2004

VJs Tip Of The Day - September 29th 2004

Build Vs Rebuild in VS.Net

A very basic but a less know question for today... What is the difference between Build and Rebuild solution in VS.Net or why at all we have two...
Well the difference is that Build solution will build only those projects which are changed since the last build... It will not get the changes of the updated embedded resource files...
Rebuild solution will cause everything to be rebuilt no matter whether it was changed or not...

If you are making small projects the differences would not matter much but for large builds these are really useful...
There are advanced differences though but these are something which all should know...

PS: If you wish to add few of your discoveries shoot me an email and I will update folks with tomorrow's tip...

PS:Swapnil B has added to the list and made it explicit that Rebuild will bydefault update your refrences too...

Tuesday, September 28, 2004

VJs Tip Of The Day - September 28th 2004

Activator.CreateInstance

Activator is a class in System namespace... This class is one of the most widely used class to create instances at runtime, of types locally or remotely defined... Usually it returns back an object or an objecthandle... There are lots of overloads of this method and in local scenarios mostly take System.Type() as one of the parameter... Its certain overloads also take typename as string and return back an object handle... This objecthandle then needs to be unwrapped to get back the object... The overload which returns objecthandle is mostly used in remoting...

CreateInstance is a static member of the class and so can be accessed directly without object creation...

PS: Abhishek, Microsoft India MVP lead has helped us get the below information:

Announcing Security Guidance Hands-On Labs Online
Microsoft Learning is pleased to announce the free, worldwide availability of Hands-On Labs 2811, Applying Microsoft Security Guidance, at http://www.microsoftelearning.com/security/.
This offering consists of four 90-minute labs that allow students to apply information and guidance to improve security in a network based on Microsoft Windows. These labs have been enormously successful at live events since their original release in April 2004, with over 12,000 deliveries through Certified Partners for Learning Solutions (CPLS). In addition, these labs have been offered at conferences and events worldwide, including TechEd US, TechEd Europe (highest-scoring labs).
Lab 1: Managing Security Updates

Lab 2: Implementing Server Security

Lab 3: Implementing Client Security for Windows 2000 and Windows XP

Lab 4: Implementing Application Security

Customers can now take these labs for free at home or in the office by registering at http://www.microsoftelearning.com/security/. The labs are conducted using real hardware in a safe online environment built on Microsoft Virtual Server technology. These are the first free hands-on labs online offered by Microsoft Learning and these will be followed by additional free labs on Windows XP Service Pack 2.

Monday, September 27, 2004

VJs Tip Of The Day - September 27th 2004

SoapInclude Attribute

In case of webservice programming you can allow SoapInclude Attribute on your webmethod to make sure that the specific type gets passed by... You use this attribute on your webmethod when in normal circumstances that type would not get passed...
For instance, if you have a class inheriting for a base class and a member is declared of the type base class and later instantiated as derieved, then the derieved class will not get passed across in that scenario on your webmethod you would apply this attribute...

Look at the example below...

<WebMethod(), SoapInclude(GetType(Circle)), XmlInclude(GetType(Circle))> _
Public Function ReturnSomething(ByVal key As String) As Shape
If (key = "Circle") Then
Dim circl As Shape = New Circle()
circl.area = 2
Return circl
End If
End Function

<Serializable()> _
Public Class Shape
Public area As Double
End Class

<Serializable()> _
Public Class Circle
Inherits Shape
Public radius As Double
End Class

Thursday, September 23, 2004

VJs Tip Of The Day - September 23rd 2004

Asynchronous Programming in WebServices

Callback functions are the way to implement Asynchrounous programming in Webservices... We will get into details of this topic sometime but now just an overview...
A client calls the Begin method on the server object and passes a reference to the callback method... The asynchrounous method on the server object finishes execution and gives a call back to the method on the client object... This method in client object now causes the call to End method on the server object.... The End Method then returns the result to the client...
Well why would you do such a thing??... The simple reason can be when your server side execution is really going to take long and you do not want to wait for all that processing to happen...

PS: I just remembered a saying from a wise man, thought I would remind you all of that too...
"If Everything is under control... Then you are not moving fast enough..."

Wednesday, September 22, 2004

VJs Tip Of The Day - September 22nd 2004

Application Domanis

Application Domains are the boundaries within which applications run... Application domains provide an isolated environment to applications, the kindof isolation level that is very similar to process isolation levels, though what is worth nothing is that a process can have multiple application domains within itself... An application running in one app domain cannot directly access code running under other app domain...

Monday, September 20, 2004

VJs Tip Of The Day - September 20th 2004

App Config File not being picked up

Some times you would have done nearly everything right in the windows application but still on trying to access configuration file you would get back null or nothing... Well the problem might be the name that you have used for the config file...

You should know that for a windows based application to pick up app.config file following should be taken care of...
1.) The app.config name should match your assembly name... i.e. if you have myapp.exe then the config file name should be myapp.exe.config...
2.) Also you should know that the config file is picked up for the main or the application which is the starting point... So your app.config file should be attached to that...

PS: There is a small correction to the above tip... Thanks to Darya, an old colleague of mine for pointing it out... I have corrected the blog if anyone can tell me what I corrected then a virtual candy from me to him/her... :-)


PS: I counted that close to 37 people asked me "How are you?" today... Out of these only 7-8 actually waited for me to respond, rest all just walked by... I wondered why such formalities when no one really cares to know, but then I thought - This is atleast a good way of proving our kids that "Man is a social being..."

Thursday, September 16, 2004

VJs Tip Of The Day - September 17th 2004

Callback functions

Callback functions are powerful tools and we should know how to use them... In general a callback function is a reference to a method that you pass to another method... When the second method calls the referenced method , it actually calls back to the first method... This might be a confusing terminology but a code snippet from MSDN will probably help make it clearer...

using System;
using System.Runtime.InteropServices;

public delegate bool CallBack(int hwnd, int lParam);

public class EnumReportApp {

[DllImport("user32")]
public static extern int EnumWindows(CallBack x, int y);

public static void Main()
{
CallBack myCallBack = new CallBack(EnumReportApp.Report);
EnumWindows(myCallBack, 0);
}

public static bool Report(int hwnd, int lParam) {
Console.Write("Window handle is ");
Console.WriteLine(hwnd);
return true;
}
}

Here is the link for you to explore more.... Click Here


PS: I have coined a new term called "Developer's Superstition"... I suffer from this problem often - When code does not seem to behave the way I want it to, knowingly/unknowingly I try things which I know will not work, which I know are technically impossible but still I do just to make myself feel good that I have left no stones unturned... I wonder whether you guys also do such thing... A classic example would be trying to call GC.Collect() method when a StreamReader is not releazing a file even after calling close()...{usually its some other process holding the reference...:-)} I wonder has MS Technologies made me superstitious or is this same everywhere... :-)