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 References – supports 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!!!