Wednesday, August 18, 2010

Best way to end ASP.NET session

There are mainly three methods in Session object which serve similar purpose.

1. Session.Clear(): This will immediately remove all objects stored inside Session object. Session object basically stores a collection of key(string) vs value(object). After calling this, you will find Session.count equals to zero but Session object itself will still be alive and you can again add new key/value items to it.

2. Session.RemoveAll(): It behaves exactly the same way as Session.Clear. It just wraps Session.RemoveAt at one shot. You can specify index in Session.RemoveAt to remove items one by one. You can also call Session.Remove and pass key to remove that key/value pair item. It could be slower than Session.Clear which essentially is made just to clear all the items.

3. Session.Abandon(): If you have used Session.Clear or Session.RemoveAll, though you have got rid of any and all objects stored in session but session object itself remains alive and could be used further. Session.Abandon just cancels the current session and session object gets destroyed.
The only point to remember here is that if you have used Session.Abandon, it will just mark the session to be destroyed but nothing will happen to session object for that request. As soon as the current request gets completed, session object will be canceled. So don't get surprised if nothing looks to happening to session object just after calling the abandon method, in the next request, you will find that session object to be destroyed and a new one to be created.

Take your web application offline without any change in web server or application

This might come handy when you are in maintenance mode of your application and you want to let your user know it. How would you do it without shutting down your application or without writing additional code to redirect all requests?
The only thing you have to do is to create a file with name app_offline.htm, decorate it however you want and just put it inside the root directory of your application. Rest everything will be taken care of .NET handlers. All users visiting to your site will automatically see your offline page.
Whenever you want your application to be up, just remove that file and that's it.

Tuesday, June 29, 2010

Ternary operator in VB.Net

If you are looking for ternary operator in VB.NET similar to C++,C#, Javascript etc if(expression?truepart:falsepart) then let me tell you that VB.NET offers a similar function to do that

you can write

Dim displayName As String = "FirstName"
Dim myName As String = IIf((displayName = "FirstName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Abhishek"
 myName = IIf((displayName = "SurName"), "Abhishek", "Tiwari")
Console.WriteLine(myName) 'will write "Tiwari"

Please note that IIf is just a function which takes first input as an expression, evaluate it and return second input (if expression is evaluated to true) or return third input (if expression is evaluated to false).

There is a gotcha in using IIf function, it works little bit differently than ternary operator in C#. It basically evaluates both input (irrespective of expression evaluating to true or false). In Other languages, expression will be evaluated first and then based on the result other inputs will be evaluated.

for e.g.

Dim dict As New Dictionary(Of String, String)
Dim d = IIf(dict.ContainsKey("A"), dict("A"), Nothing)

will result in "KeyNotFound" exception although someone will assume that it should return Nothing without throwing exception.

Fortunately VB.Net 9 provides conditional operator (If) to be used as ternary operator too and it works exactly the same way the ternary operator works in C# or other language.


Dim dict As New Dictionary(Of String, String)
Dim d = If(dict.ContainsKey("A"), dict("A"), Nothing)

Note that I have used "If" instead of function "IIf" and later one will execute successfully and return Nothing without throwing any exception.

Friday, June 25, 2010

Visual Studio 2010 crashing after unlocking windows XP

Good features come from Microsoft with plenty of bugs around. I am enjoying the powerfulness of Visual studio 2010 with VB.NET 10. Lots of new features have been added in VB.NET 10 (read my article http://aspnettechstuffs.blogspot.com/2010/06/cool-vbnet-10-features.html ) and VS 2010 beautifully runs on top of them. I was living in a wonderful shell until one day I found VS 2010 started crashing everytime I unlock my windows XP machine. This gave me lots of trouble since everytime VS crashed it did not save any of my modified document and recovery options too did not be of too help everytime.
I checked my event log and found following errors logged

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.CodedUITestPackage, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

.NET Runtime version 2.0.50727.4927 - Fatal Execution Engine Error 


Faulting application name: devenv.exe, version: 10.0.20506.1,


I could not reproduce the issue so far after disabling my hardware acceleration of my computer. Hope it may help you as well. If that does not work, you can also try to look into your VS 2010 Tools -> Options -> General -> Visual Experience and disable the hardware acceleration if it is enabled there.

you can disable hardware accelartion of windows as following

Cool Visual Studio 2008/2010 extensions (plugins)

I have found couple of very useful VS extensions. I would like to recommend them to everyone using Visual studio 2008 or 2010. They are absolutely free to use.

VS Command: Some of the interesting features of my choice are as following ( please refer http://mokosh.co.uk/vscommands/#download for all details)
  • Grouping & Ungrouping items – you can group and ungroup items using IDE, something you would normally need to edit project file (DependentUpon) 
  • Locate in solution - some people don’t like auto tracking of current item in solution explorer but would like to locate current item on demand. It’s now easy to achieve, simply rightclick in code editor, select ‘Locate in Solution’ from context menu and current item will be highlighted in solution explorer.  
  • Copy/Paste As Link  - You can create shortcuts to files and group them for later instant use
  • Copy/Paste Referencessupports assembly, project and ActiveX references
  • Open Command Prompt - Opens Visual Studio Command Prompt in a location of selected item (solution,project, project item or reference).
  • Open File Location
    Open file location works on solution items, link items and references.
  • Build Summary

    1. Build Output has a summary section appended at the end of it.
    2. The summary contains information about time it took to build each project and total build time.
Download link:
VSCommands 2008
VSCommands 2010

Power Command: Interesting features of my choice (read full article on Power Command for VS 2008 and Power Command for VS 2010 ) You will get download link from same articles.

  • Email CodeSnippet - To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet. 
  • Undo Close - This command reopens a closed document , returning the cursor to its last position. To reopen the most recently closed document, point to the Edit menu, then click Undo Close. Alternately, you can use the CtrlShiftZ shortcut.
    To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window. The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.
  • Collapse Projects - This command collapses a project or projects in the Solution Explorer starting from the root selected node.
  • Copy As Project Reference - This command copies a project as a project reference to the clipboard. It can be executed from a project node.
  • Extract Constant - This command creates a constant definition statement for a selected text. Extracting a constant effectively names a literal value, which can improve readability. This command can be executed from the code editor by right-clicking selected text.
Productivity Power Tools:  

Productivity Power Tools

          Tuesday, June 22, 2010

          Nullable type in vb.net

          Since relational database support null values for every types, it makes sense that your application should also support null values. Reference types can directly take null values but value types are always initialized with their default values that makes it difficult to figure out whether they contain some actual value or not.
          One way developers used to achieve this by assigning some hypothetical value to a value type so that at any point of time looking at the value they would come to know whether that value type variable actually has been assigned or not.
          With .Net 2.0 it has been possible to create nullable value types that means you can assign a null value to a value type with keeping all other value type advantages intact. Nullable types can be declared in following manner

           Dim myNullable As Nullable(Of Integer)
           myNullable = 4
          Dim mynull As Integer? = 4

          if you are interested to know what type it returns for myNullable and myNull so it is "Integer?" in both of the cases. Interestingly Integer? is nothing but a wrapper over Integer class which provides an additional functionality.

          Nullable types contain a property called HasValue which provides you a better way to find out whether any value has been assigned by any time to your variable or not

          Dim hasSomeValue As Boolean = myNullable.HasValue

          will return me true or false based on myNullable has a null value or a valid integer.

          nullable types are initialized with 'NULL' in C# and with 'NOTHING' in vb.net

          cool vb.net 10 features

          I would like to introduce you new vb.net 2010 features some of which have been missing since long and developers were always craving for them. These new features are bundled with VB.Net in .NET framework 4.0 and they will surely going to improve developer's productivity and code quality .

          Implicit line continuation: You don't need to put underscore character at the end of the line to make compiler understand that this line is extending to next line. Though underscore is still needed in couple of cases for e.g. declaring attribute at the top of function or class. e.g.

          Dim s As String = "Hello" &
          "World"

          is a valid statement. Ofcourse if you want to make it more readable you should still use underscore as continuation

          Dim s As String = "Hello" _ 'using underscore otherwise it would be difficult
          & "World" 'to understand if line is extended to next line or not


          Auto implemented properties: Like C# in VB.NET too you don't need to write get/set functions if they are meant to be used as default. for e.g.

          Public Class Student
          Property Age As Integer
          Private _name As String
          Public Property Name() As String
          Get
          Return _name
          End Get
          Set(ByVal value As String)
          _name = value
          End Set
          End Property
          End Class

          You can see Property "Age" is auto implemented and we don't need to explicitly write its get/set functions. Internally compiler will automatically generate the fields starting with underscore.


          Object initializer: Now like C#, it is possible in vb.net to set object properties during the time of its initialization. We can construct the earlier mentioned Student class object as following

          Dim myStudent As New Student With {
          .Age = 20,
          .Name = "Abhishek"
          }


          Multiline lambda or Anonymous methods: Earlier vb.net used to support single line anonymous method only which made using lambda or anonymous method bit annoying. you had to write statements something like this
          Dim mySub = Sub() Debug.WriteLine("Difficult to write complex implementation")

          but now with vb.net 10 you can write multiline anonymous methods with ease

          Dim mySub = Sub(newStudent As Student)
          Dim myStudent As New Student With {
          .Age = 20,
          .Name = "Abhishek"
          }
          newStudent = myStudent
          End Sub

          Implicitly typed or inferred local variables (Anonymous types): If you have worked in C#, it's exactly how 'var' is used in C#. The object type is inferred from the value it has been assigned. for e.g.

          Dim myInt = 4
          Dim myString = "Abhishek"
          Dim myStudent = New Student With {.Age = 20, .Name = "Abhishek"}

          Here how compiler is going to read it
          Dim myInt As integer = 4
          Dim myString As string= "Abhishek"
          Dim myStudent As Student= New Student With {.Age = 20, .Name = "Abhishek"}

          In C# you cannot assign a null value to anonymous type ('var') but if the type of object is already inferred, you can assign a null value to it for e.g.
          in C#
          var myObj = null //not possible
          *********************
          var myStudent = New Student
          myStudent = null //works

          in VB.Net
          Dim myObj = nothing 'works
          myObj will be inferred as 'object' type

          There are few more new features which I would love to mention in my next couple of posts for e.g. LinqToXML, QueryComprehension, Extension Methods etc.

          Happy reading!!!

          Thursday, June 10, 2010

          Sending disabled asp.net control's value in Request

          Use the SubmitDisabledControls property to specify whether to force controls disabled on the client to submit their values when the page posts back. This allows the disabled controls to preserve their values after the page posts back to the server. When the SubmitDisabledControls property is set to false, controls on the form that have been disabled using client script will not be submitted to the server the next time the page posts back. As a result, any values stored by the disabled controls are lost. To allow the disabled controls to preserve their values after the page posts back to the server, set the SubmitDisabledControls property to true.

          SubmitDisabledControls property can be set on PageLoad or inside form tag in aspx page.

          Monday, June 7, 2010

          System.Web.UI.Pair

          The Pair class is used as a basic structure to store two related objects. It is a utility class that is used in various ways throughout ASP.NET, such as during page state management tasks or in configuration section handlers. You can use the Pair class in your own code anywhere that you need a structure to contain two related objects.

          Through following example I am going to illustrate it's use in control state.

          Suupose you are overriding any ASP.NET control (for eg. GridView) and lets say view state is off. Now in this case we can use control state to store some custom properties.
          Protected Overrides Function SaveControlState() As Object
          'Get the state from base class

          Dim baseState As Object = MyBase.SaveControlState()

          'Combine this state with objects you want to store and return
          'the final object.
          Return New Pair(baseState, CurrentPageIndex) 'Where CurrentPageIndex is some custom property.
          End Function


          Protected Overrides Sub LoadControlState(ByVal savedState As Object)
          Dim pair As Pair = savedState
          If Not IsNothing(pair) Then
          'Give the base class its state.
          MyBase.LoadControlState(pair.First)
          'Now process the state you saved.
          CurrentPageIndex = pair.Second
          End If
          End Sub

          Sunday, June 6, 2010

          Override non-virtual (nonoverridable in vb.net) methods

          You might wonder if there is a possibility to override nonvirtual or nonoverridable (vb.net) methods. Suppose you are using a third party software then you may need to override some of its methods which are not declared as virtual, this is also a likely requirement when you are writing a wrapper to some existing controls/software/functionality.
          This is actually not overriding the actual function but it is called hiding the base class implementation and this can be implemented as following

          vb.net implementation:


           Class myBaseClass
                  Public Function MyNonOverridableMethod() As String
                      Return "I am not overridable"
                  End Function

              End Class

              Class myDerivedClass
                  Inherits myBaseClass
                  Public Shadows Function MyNonOverridableMethod() As String
                      Return "I overrode my base class function"
                  End Function

              End Class

          Note that I have used keyword "shadows" here, which tells the runtime that these two functions are separate implementations (not correlated) in their respective classes.

          now when I call them from Main


          Sub Main()
                  Dim b As myBaseClass = New myDerivedClass()
                  Console.WriteLine(b.MyNonOverridableMethod())

                  Dim d As myDerivedClass = New myDerivedClass()
                  Console.WriteLine(d.MyNonOverridableMethod())

                  Console.ReadLine()

              End Sub

          This will print me
          "I am not overridable"
          "I overrode my base class function"

          you can see, that this is still using runtime polymorphism, on runtime it sees that the function being called is not virtual so it has to be called from variable reference type (not the type of the object got created). Has the function being declared virtual, runtime will call it from the type of the object that has been created but not from the type of the reference pointer it is holding.(in case of base class function being declared virtual/nonoverridable and derived class overriding it, the previous example would always be printing "I overrode my base class function").

          C# implementation for same:


          public class myBaseClass
           {
            public string MyNonOverridableMethod()
            {
             return "I am not overridable";
            }
          
           }
          
           public class myDerivedClass : myBaseClass
           {
            public new string MyNonOverridableMethod()
            {
             return "I overrode my base class function";
            }
          
           }
          The only difference is that "Shadows" keyword is replaced by "New".
          calling from Main will reproduce the same result.
          
          
          
          
          public static void Main()
          11    {
          12        
                  myBaseClass b = new myDerivedClass();
          14        Console.WriteLine(b.MyNonOverridableMethod());
          15
          16        myDerivedClass d = new myDerivedClass();
          17        Console.WriteLine(d.MyNonOverridableMethod());
          18
          19        Console.ReadLine();
          20
          21    }
          22