.NET Blog

Tony Cavaliere

 
My Favourite Albums
  And the Grappa wins.
E-mail me Send mail
Add to Technorati Favorites AddThis Feed Button

Subscribe to Cynot Why Not


Recent posts

Disclaimer

Hey unlike other bloggers I stand by what I say but just in case. The opinions expressed herein are my own except on Tuesday when the second card is not turned up otherwise it ain't worth squat.

© Copyright 2010

Blindly calling RaiseEvent in VB.NET

I have seen far too many examples where VB.NET code does not check to see if there are any listeners prior to raising the event. The C# examples seem to always check. For example, take a look at the MSDN code example for INotifyPropertyChanged. The two snippets below are from this site.

Raising an event in C# taken from MSDN 

public event PropertyChangedEventHandler PropertyChanged;

private void NotifyPropertyChanged(String info) {

    if (PropertyChanged != null) {

        PropertyChanged(this, new PropertyChangedEventArgs(info));

    }

}

Raising an event in VB.NET taken from MSDN 

Public Event PropertyChanged As PropertyChangedEventHandler _
    Implements INotifyPropertyChanged.PropertyChanged
 
Private Sub NotifyPropertyChanged(ByVal info As String)
    RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
End Sub

The above two snippets are fairly typical. The C# example checks to see if there are any listeners and only if there are does it raise the event. Contrast that to the VB.NET code where the RaiseEvent is called regardless of whether there are any listeners to the event.  Both code examples work fine. It would seem in VB.NET the RaiseEvent call will not throw a null exception when there are no listeners.

How do we check for listeners in the VB.NET world. The obvious would be to add If PropertyChanged IsNot Nothing Then but you'll quickly find referencing PropertyChanged in this manner will not compile. The proper way is shown in the listing below.

Checking for subscribers in VB.NET

 

    6     Public Event PropertyChanged( _

    7         ByVal sender As Object, _

    8         ByVal e As System.ComponentModel.PropertyChangedEventArgs) _

    9         Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

   10 

   11     Protected Overridable Sub OnPropertyChanged(ByVal propertyName As String)

   12         If PropertyChangedEvent IsNot Nothing Then

   13             RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))

   14         End If

   15     End Sub

The trick is to add the Event suffix to the event name, in our case PropertyChangedEvent, and check to see whether it has a value. So why don't we not see this code pattern more often. Firstly, it doesn't seem to be well documented and secondly this reference variable is not reported by intellisense.

The question is it good practise to check whether there are any listeners? In C# it is a given, otherwise, a null reference exception will be throw. In VB.NET no exception will be thrown and the call to RaiseEvents will not throw an exception when there are no listeners. But which is faster? I wrote a simple application to check the amount of time it takes to blinding call RaiseEvent versus the check for the existence of the listener. Checking the listeners prior to calling RaiseEvent is about 1.75 faster than just calling RaiseEvent blindly. It should be noted that even though the check is 1.75 times faster, the actual amount of time to call RaiseEvent is extremely small. A call to RaiseEvent with no listeners takes approximately 0.000000008 seconds.

In the end, checking for listeners, in VB.NET, will in all likelihood not impact the performance of the code.

Guess the movie

Why am I such a misfit? I am not just a nitwit. You can't fire me, I quit. Seems I don't fit in.

Currently rated 4.6 by 5 people

  • Currently 4.6/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB.NET
Posted by CynotWhyNot on Tuesday, December 09, 2008 6:38 PM
Permalink | Comments (23) | Post RSSRSS comment feed

Singleton the Generic Way

I'm in the process of writing a session wrapper class. It's purpose is to ensure that all objects placed into session be serializable. When it is complete I will be sure to post the code on my blog.

It soon became apparent that this session wrapper needed to be implemented as a singleton. Why not make use of generics and create a generic singleton. The listing below is a VB.NET implementation of a singleton that can be used for any class.

Listing 1: Singleton using Generics

'Constraints ensuring that the type will be a class and has a constructor.

Public Class Singleton(Of T As {New, Class})

 

    'Property to return a single instance of the type

    Private Shared ReadOnly _instance As New T

    Public Shared ReadOnly Property Instance() As T

        Get

            Return _instance

        End Get

    End Property

 

    'Cannot directly instantiate the class

    Private Sub New()

    End Sub

 

End Class

With the exception of generics, this is a typical .NET implementation of a singleton. Note that the constraints ensure that only types that are classes and have a constructor can be used.

Listing 2 shows how to take a plain class and implement it as a singleton using the above code.

Listing 2: Making use of the Generic Singleton

Singleton(Of Foobar).Instance.foo()

Public Class Foobar

    Sub New()

    End Sub

    Public Sub foo()

    End Sub

End Class

In the code example above the class Foobar can be instantiated on it's own. If you would like to restrict how it is created (i.e., it can only be created in the context of the singleton) then package the singleton and the class Foobar into a seperate library and mark Foobar's constructor as Friend. 

Guess the movie

You guys give up yet? Or are you thirsty for more?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Generics | VB.NET
Posted by CynotWhyNot on Tuesday, May 20, 2008 5:03 PM
Permalink | Comments (19) | Post RSSRSS comment feed

Extension Method Libraries

Lately, I've been playing with extension methods. Extension methods are a way to add custom functionality to data types that are already defined without creating a new derived type. On the surface extension methods appear to be adding methods to existing classes, but under the hood the compiler is abstracted what developer's have been doing or years, that is, write static helper methods. Creating extension methods in VB.NET or C# is simple and there are great posts that detail how it's done; Scott Hanselman, Visual Basic Developer Center and ScottGu, too name a few.

What about extension method libraries? It has been well over 5 months since the official release of VS 2008, are there many libraries out there that make use of extension methods. The answer is yes and here is a list that I have come up with. As I find more I will update this list.

  • Dynamic LINQ: A set of extension methods that allow you to construct dynamic LINQ queries.
  • XML Serialization: A few extension methods to serialize/de-serialize objects using XML.
  • Lucas Extensions: Contains 40+ extension methods extending Bitmap, ByteArray, Enumerable, File, Math, Object, String classes, etc.
  • Extension Toolkit: Extends a variety of classes, such as, String, DateTime, Cache, etc.
  • DateTime Extensions: A set of fluent extension methods for System.DateTime.
  • Extension Method: A web site devoted to extension methods. As of April 15, 2008 they were 68 methods.

Guess the movie (From a movie I didn't particularly like, but westerns apparently do. Come on you know whom I am referring to.)

I'm pretty sure there's a lot more to life than being really, really, ridiculously good looking. And I plan on finding out what that is.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB.NET
Posted by CynotWhyNot on Thursday, April 17, 2008 11:49 AM
Permalink | Comments (16) | Post RSSRSS comment feed

LINQ to XML, Object Graphs and the ListView control

I have a subscription to msdn magazine and am a regular reader. I especially try to read all the articles on any ASP.NET related topics. Dino Exposito is a regular contributor to this magazine and has written many great articles on ASP.NET. In the April 2008 he wrote an excellent article on the new ASP.NET ListView control, specially, he discusses in detail how to bind a ListView control to hierarchical data.

This is by no means the first article that I have read on the topic of ListView controls. In all the articles or blog postings that I have read, I have yet to see how to use LINQ to create custom objects with complex object graphs. Instead anonymous types are used. In this post I will demonstrate how to create a custom object graph from a LINQ to XML query. Furthermore, I will bind this object to a nested ListView control. I will use the same example as presented by Dino in the August edition of msdn magazine.

We will be creating a hierarchical menu that is rendered using LINQ to XML, ListView control and an XML file. Listing 1 shows the menu.xml file.

Listing 1: menu.xml

<?xml version="1.0" encoding="utf-8" ?>

<menu>

  <item>

    <title>Menu Title 1</title>

    <link url="url1-1" text="text1-1"></link>

    <link url="url1-2" text="text1-2"></link>

    <link url="url1-3" text="text1-3"></link>

    <link url="url1-4" text="text1-4"></link>

  </item>

  <item>

    <title>Menu Title 2</title>

    <link url="url2-1" text="text2-1"></link>

    <link url="url2-2" text="text2-2"></link>

    <link url="url2-3" text="text2-3"></link>

  </item>

  <item>

    <title>Menu Title 3</title>

    <link url="url3-1" text="text3-1"></link>

    <link url="url3-2" text="text3-2"></link>

  </item>

</menu>

The schema of this XML file is straight forward. Each <item> node contains a menu title and then has 1 or more links. Each link has the URL to navigate too and the title that is to be used as textual display for the link.

Ultimately we would like to bind this data to a nested ListView control. The markup for this nested ListView control is shown in Listing 2. The title is render in the outer ListView control, whereas, the links are render in the inner ListView control. The code bind will be responsible for binding the outer ListView. The inner is bound declaratively. Please note that DataSource for the inner ListView control must be named links.

List 2: Nested ListView Control

    <asp:ListView ID="ListViewMenu" runat="server" ItemPlaceholderID="PlaceHolder1">

 

      <LayoutTemplate>

          <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

      </LayoutTemplate>

      <ItemTemplate>

 

        <h1><%# Eval("title")%></h1>

 

        <asp:ListView ID="ListViewSubMenu" runat="server"

          DataSource='<%# Eval("links") %>' ItemPlaceholderID="PlaceHolder2">

 

          <LayoutTemplate>

            <ul><asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder></ul>

          </LayoutTemplate>

 

          <ItemTemplate>

            <li><a href='<%# Eval("url") %>'><%#Eval("text")%></a></li>

          </ItemTemplate>

 

        </asp:ListView>

      </ItemTemplate>

    </asp:ListView>

Before we use custom objects, let's review how we can use LINQ to XML and anonymous types as a data source to a ListView control. Listing 3 shows the code behind that accomplishes this.

List 3: Binding ListView Control with an Anonymous Type

        Dim doc As XDocument = XDocument.Load(Server.MapPath("App_Data/Menu.xml"))

        Dim menu = From mi In doc.<menu>.<item> _

                   Select _

                        title = mi.<title>.Value, _

                        links = From link In mi.<link> _

                                Select _

                                    url = link.@url, _

                                    [text] = link.@text

 

        ListViewMenu.DataSource = menu

        ListViewMenu.DataBind()

In this code snippet we are using the LINQ to XML features of VB.NET to query the XML file. The doc.<menu>.<item> retrieves all the <item> children for the document. The content of the <item> node is loaded into an anonymous type having two properties; title and links. The property links is a collection that is populated by the sub query. In the end, the anonymous type, menu is of type IEnumerable(Of <anonymous type>). The menu object is then used as data source to the outer ListView control.

Anonymous type are great, however, there are cases when you may need to pass the data between methods, tiers or even across process boundaries. In this scenario you should us a custom type. To do this you must first create the classes. In our case two classes are required. Listing 4 shows the two classes.

List 4: Custom Types 

<DebuggerStepThrough()> _

Public Class Menu

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _title As String

    Public Property title() As String

        Get

            Return _title

        End Get

        Set(ByVal value As String)

            _title = value

        End Set

    End Property

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _links As IEnumerable(Of Link)

    Public Property links() As IEnumerable(Of Link)

        Get

            Return _links

        End Get

        Set(ByVal value As IEnumerable(Of Link))

            _links = value

        End Set

    End Property

End Class

 

<DebuggerStepThrough()> _

Public Class Link

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _url As String

    Public Property url() As String

        Get

            Return _url

        End Get

        Set(ByVal value As String)

            _url = value

        End Set

    End Property

    <DebuggerBrowsable(DebuggerBrowsableState.Never)> _

    Private _text As String

    Public Property text() As String

        Get

            Return _text

        End Get

        Set(ByVal value As String)

            _text = value

        End Set

    End Property

End Class

The two classes are named, Menu and Link. Menu contains two properties; title and links. links is of type IEnumerable(Of Link) which is important as LINQ queries of this type return the generic type IEnumerable(Of T). I have tried other generic types that derive from IEnumerable(Of T) such as List(Of T) but they generate Unable to cast object of type... exception. Perhaps there is a way to explicitly cast the object but that would require further investigation. Perhaps a future blog post?

Listing 5 shows LINQ to XML code to make use of the custom type.

List 5: Binding ListView Control with a Custom Type

        Dim doc As XDocument = XDocument.Load(Server.MapPath("App_Data/Menu.xml"))

        Dim menu = From mi In doc.<menu>.<item> _

                   Select New Menu With { _

                        .title = mi.<title>.Value, _

                        .links = From l In mi.<link> _

                                Select New Link With { _

                                    .url = l.@url, _

                                    .[text] = l.@text _

                            } _

                    }

        ListViewMenu.DataSource = menu

        ListViewMenu.DataBind()

The menu object is now of type IEnumerable(Of Menu), which can be easily passed as a parameter to a method or serialized across the wire.

Guess the movie

You loved my father, I know. But so did I. That makes us brothers, doesn't it? Smile for me now, brother.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.NET | VB.NET | LINQ | XML
Posted by CynotWhyNot on Wednesday, April 16, 2008 4:10 PM
Permalink | Comments (17) | Post RSSRSS comment feed

Binding to an array of String: Where's my String?

This one has bothered me for some time. Here is the situation you have a simple array of strings and then you bind it to a DataGrid. What do you expect when the grid is rendered? Silly me I was expecting to see a bunch of strings. And what did I get, a grid with a single column containing a heading of Length and a list of values that represents the length of each string in the array.

What the heck is happening here?

Here is a code snippet that declares an array of String that is later bound to a DataGrid.


  Dim s As String() = {"hey", "man", "where's", "my", "string"}

  DataGridView1.DataSource = s.ToList


The DataGrid is displayed as

Where is my String DataGrid

So where are the strings? Behind the covers .NET is using reflection to inspect the String object and searches for all properties that have no parameters. Each of these properties is then displayed in the DataGrid; and you guessed it the only parameter-less property the String object exposes is Length.

Guess the movie

Hey, what do you like, the leg or the wing, Henry? Or do you still go for the old hearts and lungs?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: VB.NET
Posted by CynotWhyNot on Monday, March 17, 2008 1:46 PM
Permalink | Comments (17) | Post RSSRSS comment feed