Monday, May 31, 2010

index your site by search engines

  • As soon as you create a new blog or site, submit it to google, this will help google to index and cache your site little bit faster.   http://www.google.com/addurl/
  •  How will you let the whole world know about your updated content. Google may crawl your blog one day or there might be no day at all. I found autoping service to be very useful in this case. which can automatically ping to all search engines about your content almost as soon as you update them. http://autopinger.com/default.aspx
  • put your blog url to as many places as you can. for e.g you can give your blog URL in your facebook, linkedin, orkut, twitter profile. You can use tools like bloglink (in linkedin) which will bring your every new post before whole world or atleast to people in your network.
  • Create new account at BlogCatalog( http://www.blogcatalog.com/ ) and mybloglog ( http://www.mybloglog.com) and ( http://www.blogratedirectory.com )and submit your blog. These sites are indexed very frequently and soon after submitting your blog you will find it listed in google search results.
  • you can submit your site to some search engines. If your site gets started coming up as the result in one of the search engine, it is highly likely that it will start coming up as the result from other search engine too. for e.g. on every update submit your site to http://www.activesearchresults.com/
  • the most important of above all is to create backlinks from other popular sites to your site. As many backlinks you will create, as good your site indexing and ranking will be. for e.g. create an account to aspnet forum ( http://forums.asp.net/ ) submit your queries, answer other people queries but don't forget to mention your site or blog name everytime. these forums are indexed every day and hence so your blog or site name. There is an option to mention  your blog or site name while creating your signature, by doing so you will never bother to mention everytime your site name since your signature will be appended to your every post.
  • integrate google analytics ( http://www.google.com/analytics/ ) with your site to see how your visitors like you and add more and more of content of visitors' choice
  • Your site is as good to be indexed as popular it is and the popularity of your site would be decided by the no. of visitors of your site. You would like to attract new visitors but like to keep your old visitors and crave them to visit your site again and again. To keep your visitors alive on your site, give them options to subscribe to your site and its content. Provide them all easy options to subscribe to your site through its feed.
  • checkout other good articles

Friday, May 28, 2010

Some important web statistics

Browsers: Internet explorer is rapidly losing their market giving way to firefox to rule over the web. While most of the web browsers are making themselves compliant to latest HTML5, IE8 is the most incompatible browser for HTML5.
html5 compatability 2
taken from: http://www.readwriteweb.com/archives/46_of_internet_users_ready_for_html5.php

check out the following browser statistics


Browser Statistics Month by Month

2010IE8IE7IE6FirefoxChromeSafariOpera
April16.2%9.3%7.9%46.4%13.6%3.7%2.2%
March15.3%10.7%8.9%46.2%12.3%3.7%2.2%
February14.7%11.0%9.6%46.5%11.6%3.8%2.1%
January14.3%11.7%10.2%46.3%10.8%3.7%2.2%


taken from: http://www.w3schools.com/browsers/browsers_stats.asp

Not to mention that web developers should start seriously thinking of making their application run smoothly on Firefox and Chrome as well.

Kindly note that here I do not want to correlate between HTML5 and market share, I just want to share some fronts on which IE is still improving itself to keep its feet still and firm in the market.
In my IE9 preview http://aspnettechstuffs.blogspot.com/2010/05/ie9-preview.html article, I have shared some links where tech pundits have criticized Microsoft for their poor vision and low sightedness. Google is backing HTML5 big time and so is Firefox. Microsoft was reluctant to make changes and do any kind of experiment with IE. The time went on and Firefox made itself 46% HTML5 compliant in its version 3.5 that wide opened MS eyes and now they are trying hard to put any and everything in IE9 that all their competitor browser has but not IE8.
Netscape, Opera, Safari just to name few started glory but later vanished by IE. With robust security, less loading time, less CPU usage, hundreds of smart addins (all developed by open source community) on the same line Firefox is pushing IE back all the corners.

Display resolution: web developers should concentrate making their application usable for resolution 1024*768 or more. check out this statistics

DateHigher1024x768800x600640x480Unknown
January 201076%20%1%0%3%


taken from: http://www.w3schools.com/browsers/browsers_display.asp

There are other interesting statistics as well mentioned on renowned w3schools site, if it interests you, please follow this link
http://www.w3schools.com/browsers/default.asp

Thursday, May 27, 2010

Script# (JavaScript with C#)

There is a good news for people who are expert in C# but are afraid to write complex code in JavaScript. Microsoft has already started working on it and their first internal release has already happened. C# compiler will  compile a class to .js file (instead of IL). You need to import certain libraries and implement IScriptlet to start with. Please note that most of the oops related functionalities like Inheritance, Polymorphism, delegates etc can smoothly be translated into javascript. Couple of C# features like Generics etc are currently kept out of conversion to script.
You might be aware of the fact that the Google has already done the same. They are using J2EE classes which can be converted to javascript. There is another company Morfik who are said to be pioneer into this. They are going to provide this functionality for C#, Java, Pascal and VB (visual basic).

My hats off to Nikhil Kothari with whose vision this javascript compiler will soon be reality in coming days. Please read his blog to know more on Script#
http://www.nikhilk.net/ScriptSharpIntro.aspx

javascript parseInt function

There are few internals of parseInt function which you must know before using this function.

  • complete signature of function is parseInt(string,radix). radix is an optional argument which is used as the base of the integer (can be any value from 2 to 36 including) to evaluate your string against
  • if input string starts from any valid number (0-9), parseInt function will return an integer after evaluating against the default base or the base you specified, otherwise will return NaN(not a number) for e.g. parseInt(2abc) will return 2 while parseInt(a2bc) will return Nan
  • If input string starts from 1-9, the default base will be used as 10. if input string starts from 0, the default base used will be 8 (octal). Please note that people assume it to some kind of bug in function when then do parseInt(09) and it returns them value 0.
Please be careful using parseInt function if your input string may start from 0. the best practice is to always specify radix.



good to read: http://www.devguru.com/technologies/ecmascript/quickref/parseint.html

Wednesday, May 26, 2010

Detailing of onkeyup, onkeydown and onkeypress javascript events

Developers need to be very careful while using these events because they don't work the same way as they look like. onkeydown and onkeyup events are fired when a keyboard key is pressed and released subsequently. these events will give you the keycode of the key only.
onkeypress event is also fired when you press a key but this event will give you the charcode of the key only. infact if you try to get the keycode from the event, it will give you the same value as charcode.

Now you might be wondering what is the difference in keycode and charcode and why there is two different type of implementation and which event needs to be captured and implemented and when?

Keycode: This value just tells you which key on the keyboard user actually pressed.
Charcode: This value is basically ascii value of the resulting character coming out of the key pressed.

so for e.g. if i press 'a' or 'A', keycode value will remain the same but charcode value will differ for both.

It is worth to mention here that there are few keys in the keyboard which does not emit any resulting character for e.g. arrow keys, for such keys the onkeypress events will not be fired.

Which events to be used:  it is upto your requirements. Let say I have a requirement of allowing users to type numbers only in a textbox, I would prefer to use "onkeypress" event, and put a check for ascii value of numbers only. I wouldn't be interested to know what else user is typing and I would prefer to leave arrow/backspace/esc etc keys unnoticed since they don't emit any characters eventually.

If I have a requirement in which I would like to handle the above situation in more granular way for e.g. I won't let user hit the ENTER button or focus out by pressing ESCAPE button, I would prefer to get hold of all the characters with their keycode and use onkeydown event.

If I have a requirement that I want to do some action based on what key is pressed (but don't want to play around with the key itself), I would prefer to use onkeyup event. for e.g. having accelerator keys in the dialog box so let say close my dialog as soon as key 'o' from OK of dialogbox is pressed and released.

Before winding up this article let me give you some examples to make it more clear for you.

Pressed char 'a':
keydown
keyCode is 65
charCode is 0

keypress
keyCode is 97
charCode is 97

keyup
keyCode is 65
charCode is 0


Pressed some 'arrow' key:
keydown
keyCode is 37
charCode is 0

keyup
keyCode is 37
charCode is 0



keypress did not fire

IE9 preview

All browsers are trying to comply in their latest versions with newly introduced HTML5 which is seen as future of web. HTML5 supports media files playing on browser with no plugins installed and this is seen as diminishing Flash and silverlight in future. IE9 is going to use interoperable markup (that means same markup can be interpreted for different versions, machines or settings). IE9 is going to use new compiler of javascript that will optimize page loading by keep on compiling the code, behind the screen without interrupting the page load. IE9 is also going to use new CSS3 standards which is yet to be standardized across the browsers.

Read more

Test IE9 features at

Monday, May 24, 2010

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe

This looks quite confusing but that means that all the static/shared functions of this type are using synchronization mechanism inbuilt(with lock or monitor) to update any static data so that threads simultaneously accessing that methods may not corrupt your data and as a developer you don't need to be worry of synchronizing it.
Whilst in the case of any instance variable of that type/class you have to write your own synchronization mechanism to prevent multiple parallel threads modifying the data.

Please go through following articles to know how internally ASP.NET synchronize the objects using sync blocks.
http://msdn.microsoft.com/en-us/magazine/cc188793.aspx

Friday, May 21, 2010

ByVal and ByRef in VB.NET

I found it very useful. It will clear your doubts about when to pass arguments byval and when to pass byref.


When-to-Pass-VBNET-Arguments-as-Reference-Types-Versus-Value-Types

How to assign one object to another in ASP.NET (similar to variant assignment in ASP)

In ASP.Net there is no variant type. We have object type equivalent to variant. While assigning the object (variant in ASP) to something (another object), we should keep in mind that this object will be assigned byRef while in ASP the same (variant) was getting assigned byVal. The ASP equivalent of assigning variant in ASP.NET is to assign clone of the object (shallow copy) instead of object itself (deep copy). for eg: Incorrect: Dim variantA as Object Dim variantB as Object for i = 0 to 3
variantA = arrValue( i )
          variantB( i ) = variantA
next Correct: Dim variantA as Object Dim variantB as Object for i = 0 to 3
variantA = arrValue( i )
  variantB( i ) = variantA.Clone()
next In Incorrect e.g., the values at earlier indices of variantB will be overwritten with last value of variantA in every iteration. Eventually values at all the indices of variant B will be equal to arrvalue(3) (last value).

How to migrate from ASP to ASP.NET

If you are using ASP, it is still not too late for you to migrate into latest ASP.NET. If you are worrying about the effort and the time for migration let me share with you my experience which may save you significant time and help you to migrate your project.

  • To start with you need to have Microsoft Visual Studio 2003. 
  • Install ASP to ASP.NET migration Assistant tool from http://www.asp.net/downloads/archived-v11/migration-assistants/asp-to-aspnet
  • After installing it, inside Visual Studio you will find a new option available under File -> Open -> Convert. Please go through this link http://www.asp101.com/articles/john/asptoaspnet/default.asp
  • Run this tool on your project completely, kindly note that your application will be converted using VB.NET language only. If you want to use C# language, you can find plenty of online converters. But it would be ideal to use VB.NET since it is syntactically almost same as ASP. 
  • Now let me tell you one of the major problem you may face. After converting your project completely to ASP.NET you would like to compile it to make it run and to your surprise you will end up getting hundreds of errors. Most of the errors would come due to your ASP style of coding in which  developers try to use many variable as global and share them across the asp pages. Since ASP is an interpreted language so if any used variable is available at runtime it won't yell. ASP.NET being a compiled language needs all variables or methods to be available at compile time.
  • To overcome the nightmares that came due to difference in interpreted vs compiled language processing, we used following methodology
    • All ASP pages which were included inside other ASP pages but were not used in showing UI. We renamed their extensions to .inc. This way ASP.NET compiler will ignore all pages with .inc extension and they will be included within your aspx page as if they were in ASP. Let me go into more details suppose you had a.asp & b.asp which were using a helper page c.asp. Now if a.asp is using some variable which is declared in c.asp or c.asp is calling a method which is declared in b.asp, after conversion and compilation you will get build error from both a.aspx and c.aspx. ASP.NET will try to compile each individual .aspx page and it will create a dynamic class and put all your code (inside script tag) within that and then try to compile. It will expect that your class (code inside script tag) has all dependency available which is essentially not there in our case. When we rename our c.aspx to c.aspx.inc and include it inside a.aspx and b.aspx. ASP.NET compiler will not compile c.aspx.inc separately but when it will go compiling a.aspx and b.aspx it will include c.aspx.inc code in that (as if they were part of those pages) and now a.aspx and b.aspx both will get compiled.
    • We made sure that there should not be any .inc file inside a .inc file. You have to put all dependency/include file of a UI page (aspx) within that page. This will prevent you the problems coming due to multilevel nesting of files and cyclic dependency. But it is all upto you, you may keep your ASP like structure as it is and yet make it run.
    • .inc file should not have any variable declared inside the file. We moved all the variables from .inc file to the page where .inc file is included. This way every page had its own contained local variables and there is no conflict with other pages. You may create another inc file which can include all variables used inside your any of inc and insert that file on every aspx page. This is again upto you how you want to implement it.
    • If a method is used in an inc file which is defined in another inc file but the second inc file was originally not included in your ASP page (now aspx) then just for the heck of preventing the compilation error don't include the "not required" inc file (basically try to maintain the same file include structure as you had in your ASP application). We initially started including the inc files which were not originally part of ASP page and ended up including almost all the inc files. To prevent compilation error, you need to create stub method/variable. for e.g. if a method Public Sub Test()  ... end Sub is causing this issue because it is implemented inside an inc file which was not included originally in your ASP page, then you just need to declare an object in you UI page as following Public Dim Test As Object. That means your aspx page (which is essentially a class) should have implementation of only those methods which are actually used inside it. If compiler is crying for some method which is actually not used inside your page but compiler needs it because of some dependency issue, you just create an empty implementation of that sub/function (instead of including a file where that method is implemented).
    • If the above mentioned method Test takes some arguments then you can provide a stub implementation of that as well for e.g. Public Sub Test (arg1 , arg2) 'no implementation End Sub. that is still better than including the complete file just the heck of stopping compilation error.
    • You may come across some object assignment issues. Please read this to know how to fix them http://aspnettechstuffs.blogspot.com/2010/05/how-to-assign-one-object-to-another-in.html
    • If you are using COM, you may need to fix few more things, read it  http://aspnettechstuffs.blogspot.com/2010/05/vbnet-to-interop-com-dll-call-failed.html
  • You will initially convert your project compatible to framework 1.1. Then after you have to follow a vertical development or horizontal whatever suits to your development cycle and slowly include all the best practices and coding guidelines. 
  • Since .net provides backward compatibility, you can use the same project in framework 2.0 and later slowly enhance it.
  • Read my small presentation to know the need of migration http://docs.google.com/present/edit?id=0AW5WT4_yjBDJZGdia3pqN2RfMWN0MzJybmY4&hl=en
If you get stuck somewhere, please write me a mail. I would try my best to resolve you query.
I strongly recommend to get out of ASP and use ASP.NET. you have to invest some time initially but later you will get immense benefits and a highly scalable application.


Tuesday, May 18, 2010

"IsNothing" vs "Is Nothing"

People have found using "is nothing" more readable and object oriented. If we talk about the performance, you should look at the disassembled code and you would find that "Is Nothing" internally uses inbuilt function "IsNothing" that means that direct function call would be little bit faster.
If you are making the use of one over other as a practice then you should also think of when you use them during negation, what would you prefer
"not isnothing(myobj)" or "isnot myobj nothing"

IsNothing function being a VB function is not type safe, so if  you pass a value type to this function, the value type will automatically be boxed and evaluated. If you check value type against "is nothing" statement then it will throw runtime error.

Conclusion: IsNothing might be preferable if you have come from VB background and want to write defensive code. But if you are worried of type safety, use "Is Nothing".

Reference: http://bytes.com/topic/visual-basic-net/answers/352342-isnothing-vs-nothing

Hope this helps!!

Monday, May 17, 2010

How to debug Javascript & ASP

Writing alert in javascript and Response.Write in ASP to debug has been quite traditional. It just gives you an idea of the variable value runtime, what if
  • You want to frequently change the variable’s value on runtime to do some test
  • You want to step over or step into the function
  • There is a big variant (ASP) or object/Array (Javascript) and you just don’t know its dimension but want to see it all
There could be tons of reasons, you need a good debugging tool. I here tell you some simple tricks to ease your job.
Prerequisite: Microsoft Visual Interdev (comes with Microsoft Visual Studio 6.0)
Debug Javascript: By default, javascript debugging is disabled in browser. To enable it, Open IE, Go to
 Tools -> Internet Options -> Advanced -> Browsing
  1. Uncheck “Disable Script Debugging (Internet Explorer)”
  2. Uncheck “Disable Script Debugging (Other)”
  3. Check “Display a notification about every script error”
  4. Uncheck “Show friendly HTTP Error Messages”
Now whichever line you want to start debugging with in Javascript, just write keyword debugger before that and run your page.
What will happen next: You will be prompted with an error (“A runtime error has been occurred, do you want to debug?”). Now click Yes and choose visual Interdev to debug. You will find interpreter halted on your “debugger” line. Now you can debug it as you debug any other language. Cool Eh!!!
Debug ASP: VBScript is generally preferred as server side language in ASP. Like javascript, vbscript debugging is by default off in IIS. To enable it, Type inetmgr on run prompt, (it will open your IIS (web server) config) Now browse to your app directory under IIS Right click Go To
 Properties -> Configuration -> Debugging
  1. Check “Enable ASP server-side script debugging
  2. Check “Enable ASP client-side script debugging
Now whichever line you want to start with, write keyword stop before that. Now run your page.
What will happen next: You will be prompted with an error (“A runtime error has been occurred, do you want to debug?”). Now click Yes and choose visual Interdev to debug and Bingo!!! You can debug your ASP code like anything.

VB.Net to interop COM dll call failed for variant/object

 I converted one ASP application to VB.Net using Microsoft ASP migration assistant utility. It was interesting
to see that the utility created all the required interop dlls for my unmanaged COM components. so I saved my time in
running tlbimp on each COM/EXE/DLL(unmanaged) or by using Visual studio. Cool Eh!!
I found one very interesting and quite unexplored issue (atleast i didnot get much on googling Smile ) that was                                                                                           my call from managed environment to unmanaged got failed for no obvious reason. Prima facie, I got feeling
that it happened due to some wrong marshalling of data which eventually proved true.
Let me staright jump into the issue by one example and explain its fix.
my backend (C++) has one API implementation something like this
CFoo::CreateMyList(
                        /*[in]*/   VARIANT*                     vSomeInVaiant,
                        /* [out] */ VARIANT*             pvSomeOutVariant,
                        /* [in] */ BOOL bSomeBoolean,
                         BOOL*                         bRetVal )

my default VB.Net code (after conversion) was something like this,
blnRetVal = CFoo.CreateMyList(vSomeInVaiant, vSomeOutVariant, bSomeBoolean)
this call was ending up in some unhandled exception resulting a crash in application. To dig more I disassembled
my interop. I found the intermediate signature in my interop dll something like this
.method public hidebysig newslot abstract virtual
        instance int32  CreateMyList([in] object  marshal( struct) vSomeInVaiant,
                                            [out] object&  marshal( struct) pvSomeOutVariant,
                                             [in] int32 bSomeBoolean,
                                             ) runtime managed internalcall
{
  .custom instance void [mscorlib]System.Runtime.InteropServices.DispIdAttribute::.ctor(int32) = ( 01 00 03 00 00 00 00 00 )
} // end of method IFoo:::CreateMyList
 when I hardcoded vSomeInVaiant in backend, everything worked fine. that meant the runtime marshaller is not able to do
 his job properly for in variant. I donot owe to whatever fix I am going to tell you now.

 I read it somewhere that by default VB.Net passes everything byref so I needed a way to pass it byVal. I found a workaround.
 you enclose your variant (I'm sorry Object in managed env.) inside parantheses. that will make your runtime to evaluate it
 as an expression first and then it will be forced to pass byVal.

 the next thing i did was

 blnRetVal = CFoo.CreateMyList((vSomeInVaiant), vSomeOutVariant, bSomeBoolean)

 believe me the trick worked seamlessly. I applied this trick everywhere in my project and it worked.

 To summarize it,

 pass in variant enclosed in parantheses
 pass out variant as it is
 pass in/out variant ( never tried so far Frown ), you need to let me know.

 I am open to more discussion on this. I will be obliged for any comment.

Inheritance and Polymorphism in Javascript

You must read http://aspnettechstuffs.blogspot.com/2010/05/inheritance-in-javascript.html before going further, I am going to use example from that

creating person class

function Person()
{
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";
}

Inheriting Man class from Person

Man.prototype.constructor = Man; 
Man.prototype = new Person;

writing Man class now

function Man()
{
    this.color = "black";
}

Adding few properties in prototypes directly

Person.prototype.legs = 4;
Man.prototype.legs = 2;
Man.prototype.hair = "black";

creating objects
var p = new Person;
var m = new Man;

The prototype chain for m will look as following

On the same line you can create prototype chain for object p. Now to verify if your objects are actually inherited try following

alert(m instanceof Man);  //will pop up true
alert(m instanceof Person); // will pop up true


Reference: http://mckoss.com/jscript/object.htm

Inheritance in JavaScript

You may know it before that we can implement OOPs concepts in Javascript. I am going to demonstrate here one of them "Inheritance in Javascript".
Before going head let me tell  you some facts about javascript

  1. In javascript every function can be used to create an object out of it with "new" operator. 
  2. Javascript objects are hashed and interpreted that means you can add any property to them on runtime. 
  3. Every function (when used as class) is inherited by an inbuilt function(class) called "prototype" of that function. the constructor of your function/class is implemented inside the prototype of your function/class. So whatever properties or methods you add in prototype would be available to all objects of your function/class by default.
  4. When any property/method is accessed from an object, interpreter first tries to find it inside the object itself, if it is not there then it looks into prototype class of that object and keeps on going up in its prototype chain unless it finds it. the super base of any object is prototype of "object" class itself. If it does not find it after crawling upto "object" prototype then it throws error of "undefined" or "not found".
Now let me give you an example how to implement inheritance

function Person()
{
    this.eyes = 2;
    this.legs = 2;
    this.color = "white";
}

Now I want to derive another class Man out of it
to do so you need to write as following

Man.prototype.constructor = Man; //this line will tell that man object will be instantiated from its own prototype
Man.prototype = new Person;  //this line will  hook Person into Man's prototype chain

Please note that you have to write the above two lines before creating Man class

now I am writing a "Man" class

function Man()
{
    this.color = "black";
}

just to explain you how you can add some properties/methods in objects prototype directly, you can refer following example

Person.prototype.legs = 4;
Man.prototype.legs = 2;
Man.prototype.hair = "black";

Ok, now I am going to create an object of Man class

var m = new Man(); //m is an  object of Man

alert(m.color); // the interpreter will look into class Man first and will popup black
alert(Man.prototype.color); // since prototype of Man does not contain color property, it will move up the prototype chain and will look into Person prototype and popup "white"
alert(m.legs); //legs are not defined in object "m", it will look ito prototype of "m" and will pop up 2


I hope you must have understood by now how this whole inheritance is going to work. This is not different than how you find it working in C#/VB.Net or any other language.


Common Myth Regarding ViewState in ASP.NET

Through this article I want to figure out a very common misconception about viewstate.
Most ASP.NET developers think that the ASP.NET ViewState is responsible for holding the values of controls such as TextBoxes so that they are retained even after postback. But this is not the case.

Let’s take an example to understand above.
Place a web server TextBox control (tbControl) and a web server Label control (lblControl).
Set the “Text” property of label and textbox to “Initial Label Text” and “Initial TextBox Text” respectively and set the “EnableViewState” property of both the controls to false.
Place two button controls and set their text to “Change Label Text” and “Post to Server”. First button changes label’s text by handling button click event and second button only does the postback.

private void btnChangeLabel_Click(object sender, System.EventArgs e)
{
lblControl.Text = "Label's Text Changed";
}

On running this application, you can see the initial texts in the controls as you have set.

Now, change the text in TextBox and set it to “Changed TextBox Text”. Now click the Post to Server button. What happens is that the textbox retain its value, in spite of the ViewState property being set to false.

The reason for this behavior is that ViewState is not responsible for storing the modified values for controls such as TextBoxes, dropdowns, CheckBoxList etc., i.e., those controls which inherit from the IPostBackDataHandler interface. After Page_Init(), there is an event known as LoadViewState, in which the Page class loads values from the hidden __VIEWSTATE from the field for those controls (e.g., Label) whose ViewState is enabled. Then the LoadPostBackData event fires, in which the Page class loads the values of those controls which inherit from the IPostBackDataHandler interface, (e.g., TextBox) from the HTTP POST headers.

Now, on clicking “Change Label Text” button which changes label text programmatically (made by above mentioned event handler), then on clicking “Post to Server”, page reloads and programmatic change was lost i.e. label text changes to initial value – “Initial Label Text”.
This is because the Label control does not inherit from the IPostBackDataHandler interface. So the ViewState is responsible for persist its value across postbacks, and since viewstate has been disabled, the Label loses its value after clicking the “Change Label Text” button.
Now enable the ViewState for the Label control, and you can see the modified value (“Label's Text Changed”) after clicking the same button.

So we conclude that controls which inherit from the IPostBackDataHandler interface will retain their values even if the ViewState has been disabled, as their values are stored in HTTP POST headers.

Thursday, May 13, 2010

Only one XML comment block is allowed per language element.

You can not write two different XML element blocks on top of one method. For e.g.

for e.g.
''' <summary>
'''
''' </summary>

''' <summary>
'''
''' </summary>

will show you error. Please note that it is not necessary to use inbuilt XML nodes. even if I write as following it will show me the error

'''Because of this line you will see the error.
''' <summary>
'''
''' </summary

XML comment block must immediately precede the language element to which it applies. XML comment will be ignored.

That simply means that XML comments should be the first immediate thing over any method or wherever you apply. You can not write any comment after XML comments and before method. To reproduce same,
write a XML comment block and just after that write one single line comment and you will get this error for e.g.

'''XML comment below
''' <summary>
''' my summary
''' </summary>
''' <remarks>No Remarks</remarks>
'Because of this line you will see the error

VS editor displays "__o is not declared" error

This generally happens when you use render blocks in your aspx pages. Basically in order to provide intellisense at design time, VS assigns the value inside the block to a temporary variable "__o". It defines the variable whereever it first encounters the render block. so let say if your very first render block is inside if block then the variable "__o" scope would be within that block only and any other render block statement outside the if block will show design time error.
to reproduce this issue, copy and paste following lines of code in your aspx


<% If True Then %>
<%=1%>

<%

Else
%>

<%=2 %>
<%

End If%>

Although the VS editor does not show this error consistently but if you don't want to touch your existing code and get rid of this annoying error(though does not affect your actual compilation) then just place a blank render block above all so that the "__o" variable scope goes page level and the variable would be accessible everywhere.

Now paste the following code and compare it with above code, you will find that just by adding a blank render block fixed the issue

<%="" >
<% If True Then >
<%=1>

<%

Else
>

<%=2 >
<%

End If>

Wednesday, May 12, 2010

Export to Excel does not work in SSL

This looks to be very much IE specific issue. This happens when server sends following information in header
Pragma=No-cache
Cache-Control=no-cache
For IE to open an excel file it first needs to temporarily cache/store it in its default Temporary Internet Files folder and then launch it from there. If it gets aforementioned information in the header then it will not be able to save it on disk at temporary location and you might get some error like "file not found or does not exist".

To fix it you need to check following things

1. Look into the code where you are generating response (to be launched in excel), make sure you are not setting content to be expired immediately. This can be done by following manners. You need to remove following lines to make export to excel work in SSL.
response.CacheControl = "no-cache"
response.AddHeader("Pragma", "no-cache")
response.ExpiresAbsolute = System.Date.FromOADate(Now.ToOADate - 1)

2. I am not sure about other webserver like Apache but if you are using IIS then you need to do as following
a) Right Click on default Website
b) Go to HTTP-HEADER
c) See if "Enable Content Expiration" checkbox is checked
d) if it is checked then see if underneath "Expires Immediately" is checked, you need to uncheck it

Please note that "Enable Content Expiration" works only for SSL so you won't find the same issue with same setting of IIS using Http.

Bind custom objects to gridview

You can bind list of flat structured objects only to gridview. I had a requirement where I wanted to bind list of composite object without using templates. I could not find any good article on Google. After putting some thought after how it is possible to achieve the same using templates, I could do it by making a custom class which inherited from Gridview bound field and I overrode its GetValue function as following.

Public Class CompositeBoundField
Inherits BoundField

Protected Overrides Function GetValue(ByVal controlContainer As Control) As Object
Dim item As Object = DataBinder.GetDataItem(controlContainer)
Return DataBinder.Eval(item, Me.DataField)
End Function


End Class

Now lets discuss how it can be used. Lets assume that my datasource object consist list of object of class "MyData" which is composed of objects from class "MyDataA", "MyDataB" as following

Class MyData
Public oA As new MyDataA
Public oB As new MyDataB
End Class

Class MyDataA
Public Property A as string 'please use the correct syntax of declaring property
End Class

Class MyDataB
Public Property B as Integer 'please use the correct syntax of declaring property
End Class

I must be binding datasource to my gridview something like as following
mygridview.datasource = ds 'ds is some prepoulated list of objects of MyData
mygridview.bind()

Before that you need to create your custom columns from your custom bound field class as following

Dim oColumn1 As New CompositeBoundField
oColumn1.DataField = "MyDataA.A"
Dim oColumn2 As New CompositeBoundField
oColumn2.DataField = "MyDataB.B"

(you can write a common function to achieve this or may use select statement)

What will happen now? After adding the column list to grid when it binds to its datasource, it uses reflection to populate its data for which grid will internally use GetValue method of bound field class. Because of our customboundfield class, it will now return you object of MyDataA.A and MyDataB.B which grid can lookup in datasource and get the data.

The good part of this approach is that your object could be nested at any level and you can still bind it with grid.

Which control triggered the postback

In general, all ASP.NET controls with having autopostback property enabled, emit following HTML.
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}

whenever any control triggers the postback, its id is set in hidden variable __EVENTTARGET and any other related information is set in __EVENTARGUMENT. ASP.NET uses its inbuilt __doPostBack script function to pass these values on form submit. You might have guessed it now, that to know which control caused the postback get it from Request.Item("__EVENTTARGET")

It is worth to mention here that the above mentioned approach does not work in case of ASP Button or ImageButton. If you see the page HTML source, you will be surprised that no additional hidden variable or inbuilt __doPostBack function is rendered (this will be the case if your page has only Buttons/ImageButtons but no other control having autopostback property).
The reason is that ASP.NET button or ImageButtons are rendered as default html "SUBMIT" button for which you don't need any additional logic of posting. Because of which Request.Item("__EVENTTARGET") will get you nothing. In this case you will explore that button/imagebutton id value is posted in form which you can retrieve by iterating request.

so your final code would be something like this

Function GetControlIdWhichTriggeredPost() As String
Dim ctrlId As String = Request.Item("__EVENTTARGET")
If String.IsNullOrEmpty(ctrlId) Then
For Each strId As String In Request.Form
Dim oCtrl As Control = Page.FindControl(strId)
If Not IsNothing(oCtrl) AndAlso oCtrl.GetType.Name = "Button" Then
Return strId
End If
Next
End If
Return ctrlId
End Function