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... :-)

VJs Tip Of The Day - September 16th 2004

Xcopy Deployment

Xcopy command is used to easily copy all the files of a .Net application to a target installation directory... For applications that do not require any further registration Xcopy is command is the simplest way to distribute your .Net applications...

Do note that Xcopy command does not copy the hidden and system files... Also note that Xcopy creates files with the archive attribute set, whether or not this attribute was set in the source file...If you have a disk that contains files in subdirectories and you want to copy it to a disk that has a different format, you should use the Xcopy command instead of Diskcopy. Since the Diskcopy command copies disks track by track, it requires that your source and destination disks have the same format. Xcopy has no such requirement. In general, use Xcopy unless you need a complete disk image copy or you wish to copy the system files.

PS: All I ever needed to Know, Most of what I needed to know about how to live, And what to do and how to be, I learnt in Kindergarten. Wisdom was not at the top of the Graduate school mountain, But there in the sandbox at Nursery school. These are the things I learned: Share everything. Play fair. Don’t hit people. Put things back where you found them. Clean up your own mess. Don’t take things that aren’t yours. Say sorry when you hurt somebody. ......Be aware of wonder. Remember the little seed in the plastic cup. The roots go down and the plant goes up and Nobody really knows how or why, but we are all like that....
These are the wonderful words of Robert Fulgam... Read his book "All I Need To Know, I Learnt in Kindergarten" and do remember- "Technology should not overwhelm you"...

Wednesday, September 15, 2004

VJs Tip Of The Day - September 15th 2004

Resource File Generator Tool

Resource file generator tool is used to convert resource file in the form of .txt or .resx files to common language runtime binary .resources files... These files can be compiled into satellite assemblies..

This utility can do conversions in other directions too and uses following classes to do the conversions
ResourceReader Class
ResourceWriter Class
ResXResourceReader Class
ResXResourceWriter Class

The exe name for the tool is ResGen.exe... If you search MSDN with the keyword you will find ample information...

PS: I was wondering when would people start using MSDN to search MSDN and not Google... I am trying to develop this good habit... :-)

Tuesday, September 14, 2004

VJs Tip Of The Day - September 14th 2004

Quick MultiThreading
This is some real quick good info for specific scenarios... If you are writing some workflow logic of yours and in-between you realize that you want to perform some tasks which would be time consuming but actually are also apart from your actual business logic and so you would not want your business logic to waste on performance by waiting for those tasks to complete... Some of the examples of such tasks would be printing, cleaning back-end, doing logging or tracing functionality etc...
Well this is when the System.Threading.ThreadPool class comes real handy... There is a static method called QueueUserWorkItem... You can call this method with the method that you want to execute Asynchronously... The Threadpool will use the first available thread to process your request... Now your main business logic does not need to wait for this function to finish...
Now this function can as well give a call back but then it depends upon your requirements...
Read more about it on MSDN... Click Here...
PS: This tip is a result of my discussions with Matt, a colleague of mine... We often discuss interesting technical stuff in our "Leisure At Work" (LAW can never be illegal right!!)

Note: Caution on multithreading... You should know that if different threads are gonna use the same resource then multithreading might cause performance hits as well... Thanks Kathleen for reminding...

Monday, September 13, 2004

VJs Tip Of The Day - September 13th 2004

ToolTip in Windows

Well if you have been doing Web development for a long time in .Net now, if you switch to windows it would pretty much possible for you to search for the standard ToolTip property for all the controls and guess what you won't find it... :-) Windows UI is much more richer than web and so the windows controls try to leverage that... For this reason there is a special ToolTip control which is provided to you in the windows environment which you can associate with any of your controls...
Now what are some of its advantages the code below will tell you:

ToolTip vjsTip = new ToolTip();
vjsTip .InitialDelay = 1500;
vjsTip .ReshowDelay = 1000;
vjsTip .SetToolTip(this.txtZipCode, "You need to provide a zip code only if you are in US or Canada");

Similarly you also have GetToolTip() method... Well so go ahead and try explore more on the ToolTip control...

PS: Hope you all are doing fine!!...How did it feel when a forcible mail did not drop into your mailbox for so many days??... Good!!..Bad!!...Well, after giving you a small break, I am back again to bug you, make you take your pill daily... But if you do not like the pills then drop me a mail I will try that they don't reach you... Otherwise, the second season has begun... :-)

Monday, September 06, 2004

Very Limited Access To Internet

Hi All,
I have very limited access to internet as of now and I will be getting a new connection set up at my home only by Sept 11th 2004... I have my entire mailing list as well all my work on my laptop/CDs... Only after my internet connection is up I would be able to update any further posts or send tips...
Please bear with me till then...
best wishes,
Vishal Joshi
If You Think YOU CAN... You Can...

Tuesday, August 31, 2004

VJs Tip Of The Day - August 31st 2004

COM Callable Wrapper(CCW) - In simple terms -CCW is the special wrapper created over your .Net classes so that they appear as COM objects to other COM components... If your .Net application needs to be called by other COM components you need to make sure that CCW is created over your .Net classes...

Runtime Callable Wrapper (RCW) - In simple terms - RCW is a special wrapper created over COM components so that they appear as .Net components to other .Net components... If your .Net components call other COM components then you need to make sure that RCW is created over the COM components that your application calls...

PS: I will be shifting to Milwaukee, WI tomorrow... Till I get my new home set up, I might not be having any access to internet so probably would not be able to send in Tips for a while... I apologize in advance for the same and will try to get back to grove ASAP...

Monday, August 30, 2004

VJs Tip Of The Day - August 30th 2004

Maintaining State Across ASP.Net Pages - Continued 4

Due to the weekend you might have lost touch... In that case do browse through the previous tips on the blog site... The current mail is in continuation of previous tips...

There is a possibility of InvalidCastException, which may come in case of using properties with Server.Transfer... If you think for a while you can very easily conclude the possible causes...
1.) SecondPage is called from a page other than the FirstPage
2.) SecondPage is directly loaded
3.) SecondPage is called from any other page using response.redirect

In such a scenario do make sure that you catch this exception and ignore it...

PS: You know blogspot has provided search facility for the blogs... So now if you want to search some specific tip in my blog you can use that search facility and you will get the tip right over there... :-)

Friday, August 27, 2004

VJs Tip Of The Day - August 27th 2004

Maintaining State Across ASP.Net Pages - Continued 3

Yesterday we discussed on NOT having second parameter to be true in Server.Transer() method while transferring data of first page to next page using properties... Visit the previous tips to follow up...
Now the answer to "WHY" not true... Well, I was trying that out yesterday and I got an exception message:
"The View State is invalid for this page and might be corrupted"...

On exploring more I discovered that: It is that "EnableViewStateMac"* property of the page(which we discussed few days back)is set to true by default... If this property is true ASP.Net makes a check to find out if the viewstate was modified or not when the page was posted from the client... Now as in case of Server.Transfer's second parameter being true what happens is that all the form variables (including viewstate) of the first page is preserved and sent to second page... Here due to EnableViewStateMac being true a check is made by ASP.Net but now as you are no more in first page so it is but obvious that this check will fail... And as in case of properties option without setting second parameter of Server.Transfer as true also the values are transferred so you can as well pass it to be false...
As such you can also make "EnableViewStateMac" as false but that would not be a good idea from security perspective...

*MAC stands for Message Authentication Check

PS: You know Sudhakar Sadasivuni, a fellow MVP has helped to get all our MVP blogs at one place at the site http://www.mvpblog.com... I bet you will find loads of information here so do visit it when you find time...

Thursday, August 26, 2004

VJs Tip Of The Day - August 26th 2004

Maintaining State Across ASP.Net Pages - Continued 2

Hi Folks,
I apologize for abruptly stopping the tips... I was not having any access to internet for the last few days... I am shifting to Milwaukee, Wisconsin to join in as a .Net System Architect in an MNC... I will remain busy during this transition but will ensure that I do not display this abrupt behavior again... The tips of Aug 23rd, 24th and 25th are up there on my blog site(Click Here) The current tip is in continuation of the previous tips so please do visit the site and catch up before you move ahead...


4.) Using Properties with Server.Transfer: Make your first page in such a way that you expose the required values in next page as properties in the first page... Then use Server.Transfer to go to the next page(keep the second parameter as false here, WHY SO WE WILL TALK TOMORROW)... Now in the next page using context handler you can get all the properties of the first page...

I am not writing the first page code as it is just simply adding values into properties and calling Server.Transfer and I believe you all know how to do that...

CODE SNIPPET

NextPage Code:

if(Context.Handler != null)
{
string strInternalVariableOfNextPage;
FirstPage objFirstPage = new FirstPage();
objFirstPage = (FirstPage)Context.Handler;
//Note that SomeValue is a public property of First Page
strInternalVariableOfNextPage = objFirstPage.SomeValue;
}
PS: I like receiving mails that blast me on not sending the tips... This keeps me motivated so thanks to all those who wrote in those mails...

Wednesday, August 25, 2004

VJs Tip Of The Day - August 25th 2004

Maintaining State Across ASP.Net Pages - Continued 1

3.) Using HttpContext/RequestParams with Server.Transfer: We discussed adding to session yesterday, similarly you can add to HttpContext as well and this eliminates the cleaning code required in the next page like the way it is required in Session... There are other advantages too...

If you use Server.Transfer then all your control values are automatically transferred to the next page you do not have to add anything to the context explicitly here rather just access the values in the coming page... The code example will show this more clearly...

If you have certain values other than the above mentioned then you have to do certain special operations to explicitly add them in the first page and retrieve them in the second...

CODE SNIPPET

FirstPage Code:
//These are the special values being added to context
//we will retrieve them in the next page
context.Items.Add("specialVariableName", "specialVariableValue");
//We set the second parameter of Server.Transfer to True this will help
//sending certain values automatically
Server.Transfer("NextPage.aspx", True);


NextPage Code:
string strValueOfFirstPageTextBox;
string strSpeciallyAddedValue;
//Use Request.Params to get values of the standard variables
//which get automatically transferred
strValueOfFirstPageTextBox = Request.Params.Get("firstPageTextBox")
//Use HttpContext to get the values specially added
strSpeciallyAddedValue = context.Items("specialVariableName")

Tuesday, August 24, 2004

VJs Tip Of The Day - August 24th 2004

Maintaining State Across ASP.Net Pages

We will talk about two standard methods of maintaining state across ASP.Net pages today... The more sophisticated methods will be discussed from tomorrow onwards...

1) Using QueryString : You can pass values of one page to another page using Query strings... This is an old ASP custom but for security reason not always recomended in ASP.Net

2) Using Session : You can also pass values of one page to another by storing them in session... Use of session is pretty simple and we have discussed that earlier as well (Click Here)... But do understand the fact that Session variables are to store user specific information which is unique to each user and not each page... Also do note that if you forget to clean the session variables in the next page you might land up increasing the session size like anything effecting performance of your application...

Monday, August 23, 2004

VJs Tip Of The Day - August 23rd 2004

Steps to Enable Automatic Transactions in .Net

We have discussed all these steps earlier but now we will club them together to see how you go about doing it....
1. Add TransactionAttribute to your class
2. Derieve your class from ServicedComponents class
3. Give strong name to your assembly
4. Register your class for COM+ services using Regsvcs.exe


Friday, August 20, 2004

VJs Tip Of The Day - August 20th 2004

Transactions in .Net - Using Services of COM+

To use the services of COM+ and transactions you need to register the assembly that contains you class (transactional) with the COM+... You can do so manually by using .Net Services Installation Tool (Regsvcs.exe)... Well if your client is managed client then you do not need to do this registeration as CLR will do it for you but if you know that at sometime your clients can be unmanaged then it is always useful to register your assembly manually...

Thursday, August 19, 2004

VJs Tip Of The Day - August 19th 2004

TransactionOption

We are getting into the details of TransactionOption today...

1. TransactionOption.Disabled implies that automatic transactions cannot control the object... Still if you want this object to support transaction then it can be done by manual transactions...

2. TransactionOption.NotSupported implies that object context will always be created without transaction for this object no matter whether a transaction is already existing...

3. TransactionOption.Supported implies that if transaction exists the object will run under it, if it does not exist it will run without transaction...

4. TransactionOption.Required implies that if transaction exists the object will run under it, if it does not exist a new transaction will be created...

5. TransactionOption.RequiresNew implies that the a new trasaction is started for every request...

PS: Trivandrum User Group in India launches its own site... First bold move by any User Group in India and I bet it is for good... visit
http://www.t-mug.org/membersite.aspx to see for yourself...

Wednesday, August 18, 2004

VJs Tip Of The Day - August 18th 2004

Transaction Attribute for your class

We discussed that for our class to participate in transactions we need to do certain things... Now we will talk about what those certain things have to be...

One of the things that you need to do is to apply Transaction attribute to your class... You would apply it just before your class declaration... It would look something like:

[Transaction(TransactionOption.Supported)]

Now if you are familiar with COM+ transactions then TransactionOption has values which are very similar to COM+ transaction options...

The TransactionOption values can be Disabled, NotSupported, Supported, Required, RequiresNew... Out of these Required is the default...

Tuesday, August 17, 2004

VJs Tip Of The Day - August 17th 2004

Transactions in .Net

We talked about Transactions in .Net a few days back... We learnt that how they can be automatic or manual...Now ,we will talk about Automatic Transactions this whole week... Hopefully it will be interesting and useful...

Automatic Transaction manages transaction boundaries for you... But again it manages the boundaries on the basis of what you suggest it to do (you do that by attributes which we will talk in a couple of days... ) The transaction flows from one object to other as instructed... Within its scope, it includes, the objects that are suppose to participate in transactions and leaves out the objects that are not suppose to participate...

Note: Nested transactions are not possible in Automatic model...

PS: I sent a document to my team for review... Two days later a friend/collegue wrote to me that I had sent the wrong document... Till now no reviewer other than her has got back (out of 6-7 in the list)... I was wondering about the chances of reviewers not opening the review attachments which someone sends and also chances of them getting mad if the document was never sent, interstingly both the chances are equally bright... :-)

Monday, August 16, 2004

VJs Tip Of The Day - August 16th 2004

Design Days: Caching and Performance

Usually we assume that Caching is done to improve performance, well it is true but at the same time it may deteriorate the performance as well... It many a times depends on the Cache Hit Ratio... And you should definitely consider your Cache Hit Ratio [CHR] before considering your caching strategy...
To make it more clear consider a scenario in which you cache the state list of a country... Now if user has to select one of the available states then there are bright chances that your cache hit is a success.... It might be a good idea to cache the list instead of retrieving it from the data source all the time...
Now consider that you cache product list for a store like Walmart... You might have millions of product in the database and it is very unlikely that the product selection will lie in the correct category and type... There are more likely chances of miss than of hit, but you will lose time in searching the cache, so here is when you should consider hitting the data source instead of caching...
Now there are options other than caching and there might be other factors governing the decisions, this is just a design suggestion...

PS: 15th August was India's Independence Day... Please accept my belated wishes for a Happy Independence Day... Jai Hind... (Hail India!!)

Friday, August 13, 2004

VJs Tip Of The Day - August 13th 2004

If you want to use the services provided by COM+ in your .Net then you write Serviced Components...

To write serviced components you will have to include the namespace of System.EnterpriseServices... You will also have to inherit you class from ServicedComponent

PS: For My Records(FMR) - I am travelling to Omaha, NE to celebrate my friends Birthday...

Wednesday, August 11, 2004

VJs Tip Of The Day - August 12th 2004

ViewState Encryption- Considerations

Well to add to yesterday's tip, there are few more tips, rather considerations to come on the way related to viewstate encryption...

If you are using SSL for your webpages then you would want to reconsider whether you need this encryption of ViewState seperately or not as your whole data will be encrypted anyways...

The other point is webfarm scenario... When deploying your webapp to Webfarm without sticky sessions if AutoGenerate option is on (which is by default) then there are chances that your each request will go to different machine and ViewState decryption will fail there... You will have to do synchronization activities in this scenario...

Note: Sticky session is a scenario in which, once the first request in a session is served by a particular server all the consecutive requests for that session will be directed to the same server...


PS: I was wondering that if someone reads one useful article from MSDN daily, (note: JUST ONE useful article) how many days would it take for him/her to become "Most Knowledgeable Person" around there... Think about this, I smile when I come up with a number out of my hat... :-)

Tuesday, August 10, 2004

VJs Tip Of The Day - August 11th 2004

Encrypting View State

Few days back we talked about ViewState being Base64 Encoded and that it moves back and forth from client to server... Now if you wish to encrypt the ViewState for security reasons then below is the way to achieve the same...
You have to change your web.config file... In the system.web section of the web.config file you need to add the below tags

<pages enableViewStateMAC="true"/>
<machineKey validation="3DES"/>

PS: Note that here validation="3DES" causes the encryption... enableViewStateMAC causes the check that ViewState is not actually tampered...

VJs Tip Of The Day - August 10th 2004

Processing Transactions in .Net

.Net components do support transactions, the only thing is that you have to do some extra work to achieve the same... .Net framework supports two kind of transactions models
1.) Manual Transactions
2.) Automatic Transactions

Manual Tranactions is used in case of ADO.Net, message queuing etc... Automatic Transactions are available for ASP.Net, Web Services, .Net Components etc... .Net classes can also use the services of COM+ but they need to be registered with COM+ for doing so... We will talk more about Transactions in .Net in time to come...

PS: Is it a good idea to send in some code snippets in Tips?? If so do let me know, I do not want the tips to be cumbersome to read...

Monday, August 09, 2004

VJs Tip Of The Day - August 9th 2004

Changing Reference to different version of external assembly

Consider a scenario when your application is referencing version 1.0.1.1 of "SomeAssembly" in GAC... Now you realize that there are some major bugs in that assembly and you want your assembly to reference the new version of the assembly (say 1.0.2.0) and you do not want to go ahead and recompile your code for that... What would you do... Well here is the answer... You would go and change the configuration file with similar updates to the ones I am writing below...


<configuration>
<runtime>
<assemblybinding xmlns="urn:schemas-microsoft-com:asmv1">
<publisherpolicy apply="no">
<dependantassembly>
<assemblyidentity publickeytoken="whatever" name="SomeAssembly">
<publisherpolicy apply="no">
<bindingredirect newversion="1.0.2.0" oldversion="1.0.1.1">
</dependantassembly>
</assemblybinding>
</runtime>
</configuration>


PS: You can achieve the same with different methods as well this is just one of them

Friday, August 06, 2004

VJs Tip Of The Day - August 6th 2004

Common Type System - Value Types vs Reference Types

Value Types and Reference Types are two basic types of CTS... Value Types are allocated on the stack and Reference Types are allocated on Managed heap... How this thing works is that the value of the "Value Types" is allocated on the stack where as in case of "Reference Types" the value i.e. the object itself resides in the heap but there is a pointer to the object in the memory...

Considering this differences value types are faster but consume the process memory....
"Reference types don't consume this process memory but then they become slower... When value types are copied then the value is copied as a whole on the stack, when reference types are copied then only the references are copied on the stack..., when to use Reference Types as compared to Value Types and visa-versa is based on various other factors also so do take time to decide when to use what..."
Value types are usually native data types like int, float, char, enums etc... Reference types mostly include string, classes and some other user defined types...

PS: I wrote Value types to be allocated on heap in my second paragraph only Kathleen was able to find that out... You guys do write back when you see such gross errors... Thanks Kathleen...

Thursday, August 05, 2004

VJs Tip Of The Day - August 5th 2004

Design Days: View State Performance Tips


In controls like listbox controls, items added to the list are carried between client and server via view state... When the list of items become considerably large it starts hitting the performance and increasing the traffic between client and server... To avoid this set the EnableViewState property of the control to be false... By this unnecessary data will not move back and forth to the server... Though, do note that by doing so your selected items will no longer remain selected after postback and you will have to write special code to achieve this functionality...
The same problems are also faced in controls like Datagrid so do ensure that you use View State judiciously and give enough thoughts while designing your application...

To see the view state of a page right click on displayed page and 'view source', here you will see a long line of junk characters for __VIEWSTATE property... This is the encrypted view state of your controls... Well, that makes me add one more point the performance... All the viewstate data that passes to and comes back from server goes through the cycles of encryption and decryption which in itself is also a costly affair hitting performance...

Note: Ben Miller from Microsoft corrected my silly mistake here... view state is Base64 encoded when it moves back and forth from client to server.... It is not encrypted... Thanks for the correction Ben... Btw, Ben Miller is also ASP.Net MVP Lead of North America... !!


PS: Did you read my suggestion to Microsoft long time back... You will like it... Click Here

Wednesday, August 04, 2004

VJs Tip Of The Day - August 4th 2004

Assemblies Details Introduction

•Assembly has a four part name that uniquely identifies it – Name, Version, Culture & develope
•Version – Major.Minor.Build.Revision
•Culture – Satellite Assemblies contain culture info attribute that indicates the spoken language and country-code
•Public Keys – Used to uniquely identify the developer of a component and provide protection from getting tampered by external sources
using System.Reflection;
[assembly: AssemblyVersion(“1.2.3.4”)]
[assembly: AssemblyCulture(“en-US”)]
[assembly: AssemblyKeyFile(“mykey.snk”)]

PS: Naveeth Krishnan from Trivandrum .Net User Group has suggested me to start writing more about Assemblies so this is the beginning... We will deviate once in a while so that none of us get bored but still we will touch more about Assemblies now...

PPS: Did you read my suggestion to Microsoft long time back... You will like it.. Click Here

Tuesday, August 03, 2004

VJs Tip Of The Day - August 3rd 2004

Design Days - Data Access Ways

This is just a small little thought, which I thought, can be shared... When we try to access data from a table in DataSet many a times we have to use the name of the columns... We have multiple Datagrids bound to each table and many other controls of your page also access data from these tables... Now, just in case your column name changes in the table you would want to have minimum impact on the stuff that you have to change...
As a solution to this you can have DataDefinition class... This class can just return back the name of the columns as properties, you can define these light weight classes if you have less number of tables to be accessed... In any case if you do not follow this approach then it is always advisable to have constants declared at a common location and store your column names in there....
You can later use either these constants or light weight classes to get the column names...

PS: Do note that by introducing such things you can make your design more maintainable but sometimes loose on performance... Take decisions on the basis of what is ideal for your situation... Don't sue a poor fella like me for suggesting, you anyways won't get much... :-)

Kathleen Dollard, Microsoft MVP adds the below:
Use enums. Much faster and far more maintainable....

Monday, August 02, 2004

VJs Tip Of The Day - August 2nd 2004

A design consideration to access Web.Config

If you are going to access Web.config file for various configuration settings of yours e.g. ConnectionString.... Then sometimes it would be a good idea to develop a class specially to access configuration settings, something like a ConfigManager... what this class can inturn do is to access Web.Config file in its constructor to retrieve your configuration settings and fill up private variables and in turn expose them as properties...

The advantage of having this approach is that if you decide to change your source for these settings then you do not have to go to every page and change the way you access the settings you just change your class... Other than this there can be potential situations in which you might decide to encrypt some values in your web.config file later... This security enhancement would otherwise cause all your pages accessing this information change... During such situations it would be ideal to have a class like this...

To add icing to the cake you can make required member variables static so that the class's instance need not be created everytime... Also do try to make sure that every call to your property should not need to query web.config file to access values or else they may degrade performance...

PS: This is a design tip, it may not be perfect design for all situations these are just some of my generic thoughts, if you have anything to dispute please feel free to drop me an email

Binu from Trivendrum User Group has added the below thoughts...
There is one more advantage to this. if you want to deploy the application in different environments (developer sand box/ integration/ QA / production) it would be easy to have this App.Config . The possibility of using different encryption keys / SQL server in different environments is pretty high in real scenario and with the number of builds we deploy before pushing to production corroborates this.
-- Binu