Tag: VB

Conditional short-circuit evaluation

I am a long time Visual Basic developer, and I have been using the IIf function for as long as I can remember, when I needed inline evaluation of an expression.

Check out this expression.

Dim expressionResult As Integer = IIf(Not controller Is Nothing, controller.Value, 10)

When using the IIf function, bot the True part of the evaluation, controller.Value, and the False part, 10, are evaluated, no matter what the result of the expression, Not controller Is Nothing. In the case shown, when controller is null, the IIf function will throw an exception, because the True part cannot be evaluated due to controller being null. Fear not, and this is the surprising bit that has eluded me for quite some time; you can just use the “new” If operator with short-circuit evaluation, like this:

Dim expressionResult As Integer = If(Not controller Is Nothing, controller.Value, 10)

This will always return a value. Really simple, isn’t it, and so much easier to read than that comparable and IMHO silly Visual C# notation.

——————————————————– UPDATE ——————————————————–

I just looked closer at the documentation for the If operator, and there’s an overload that take only two arguments; This means that the first argument, shown in the previous example can be omitted. The first argument is evaluated and returned to the caller, unless it evaluates to Nothing. If it evaluates to Nothing, the second argument is returned.

Dim expressionResult As Object = If(controller, otherController)
Advertisements

Remove indentation temporarily for Visual Basic code in Visual Studio 2010

I guess the subject line pretty much says it all… Anyway, I do a lot of documentation on Visual Studio, ASP.NET, Visual Basic, and Visual C#, and I therefore often need to copy code I have created from my development VMs to my Word documents. Now, for blocks of code that is indented in the Code editor in Visual Studio, it is handy to be able to remove the indentation before copying it, but the default set up for Visual Basic prevents this. Turns out it is because it automatically formats the text when you unindent.

Fear not, just click Options on the Tools menu, to open the Options dialog box. In the Options dialog box, in the left pane, expand Text Editor, expand Basic, and then click VB Specific. Clear the Pretty listing (reformatting) of code check box, and click OK.

If you don’t want to turn it back on, you can always resort to using CTRL+K, D to format the open document.

ASP.NET Page base class differences in VB and C#

When you use a base class for your pages in VB and C# there are some subtle differences, if your base class implements event handlers for one or more of the Page events, such as Page_Load. In VB, you can simply use the Handles keyword, like this:

Public Class BasePage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    End Sub
End Class

This way, the Page_Load event will be called in the base class, and the page class derived from it (if the Page_Load event handler is implemented ;-). However, in C# there is no Handles keyword, and adding the AutoEventWireUp to the markup file like this, does not work with a base class:

<%@ Page Language="C#" ... AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %> 

This will only wire up the Page events implemented in the Default class. One way to fix this is to override the OnLoad event in the base class, like this:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    ...

}

Localizing Filter Controls

I am fully localizing a new ASP.NET 4 Dynamic Data web site, and there’s more than meets the eye to doing so. I found that the Boolean filter User Control would not update correctly, when switching languages; it would keep the items (All, True, and False) in the previously selected culture. So, I had a look at the code, after adding the localization calls (no, I don’t localize the exceptions ;-)):

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    If Not Column.ColumnType.Equals(GetType(System.Boolean)) Then
        Throw New InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType))
    End If

    If Not Page.IsPostBack Then
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "AllItems"), String.Empty))

        If Not Column.IsRequired Then
            DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "NotSet"), NullValueString))
        End If

        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "True"), Boolean.TrueString))
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "False"), Boolean.FalseString))
        ' Set the initial value if there is one
        Dim initialValue As String = DefaultValue

        If Not String.IsNullOrEmpty(initialValue) Then
            DropDownList1.SelectedValue = initialValue
        End If
    End If
End Sub

Well, that didn’t take too long to work out; the items are only added to the DropDownList control on the initial page view. Okay, so I modified the code:

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
    If Not Column.ColumnType.Equals(GetType(System.Boolean)) Then
        Throw New InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType))
    End If

    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "AllItems"), String.Empty))

    If Not Column.IsRequired Then
        DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "NotSet"), NullValueString))
    End If

    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "True"), Boolean.TrueString))
    DropDownList1.Items.Add(New ListItem(GetGlobalResourceObject("Strings", "False"), Boolean.FalseString))

    If Not Page.IsPostBack Then
        ' Set the initial value if there is one
        Dim initialValue As String = DefaultValue

        If Not String.IsNullOrEmpty(initialValue) Then
            DropDownList1.SelectedValue = initialValue
        End If
    End If
End Sub

Now that should work, but it doesn’t… Final thing to fix, is to disable view state for the user Control, so I added EnableViewState=”false” to the Control directive in the markup, like this:

<%@ Control Language="VB" CodeFile="Boolean.ascx.vb" Inherits="BooleanFilter" EnableViewState="false" %> 

That works 🙂

Visual Studio 2010 Beta 2 – Option Strict should cause build error when building ASP.NET Web Site

When working with Visual Studio 2010 Beta 2, you can set the default options for Visual Basic in the Options dialog box, which is available by clicking Options on the Tools menu. In the Options dialog box, expand Projects and Solutions and then click VB Defaults. The Options dialog box, opened on the VB Defaults page, is shown here.

optionsdialogbox

Continue reading “Visual Studio 2010 Beta 2 – Option Strict should cause build error when building ASP.NET Web Site”

Visual Basic Bashing

I am a former Microsoft Visual Basic MVP (7 years running) and I love VB. Now, I also do a lot of work in C# and I like to think that I do both programming languages equally well. However, I much prefer VB over C#, and I really dislike some of these morons who have nothing better to do than bash VB with incredibly stupid remarks, such as “VB is a toy language”, “When is Microsoft going to get rid of VB?” In particular the last phrase annoys me. If you don’t like a programming language, fine stick with whatever language you know (if any), but stop spoiling other developer’s joy of using a particular language. I wonder if that particular individual knows that the number of Microsoft supplied .NET based languages are increasing with the release of the .NET Framework 4 and Visual Studio 2010? Actually, I don’t wonder as I’m sure the individual didn’t have that in mind. Sigh…