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