Monthly Archives: June 2013

A Little Code Monkey!

Imports System.Text

''' <summary>
''' The Typing monkey generates random strings.
''' </summary>
''' <remarks>
''' See http://stackoverflow.com/questions/1546472/generate-random-strings-in-vb-net
''' </remarks>
Class TypingMonkey

    Private Const AlphanumericCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
    Private Const NumericCharacters As String = "1234567890"
    Private Const AlphabeticCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Private random As Random

#Region "Singleton"

    Public Shared ReadOnly Instance As TypingMonkey = New TypingMonkey
    ''' <summary>
    ''' Prevent anyone from instantiating this class by making New private
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub New()
        random = New Random
    End Sub

#End Region
    ''' <summary>
    ''' Internal key bashing function.
    ''' </summary>
    ''' <param name="size"></param>
    ''' <param name="characters"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function TypeAway(size As Integer, characters As String) As String
        Dim builder As New StringBuilder()
        Dim ch As Char
        For i As Integer = 0 To size - 1
            ch = characters(random.[Next](0, characters.Length))
            builder.Append(ch)
        Next
        Return builder.ToString()
    End Function
    ''' <summary>
    ''' The Typing Monkey Generates a random alphabetic string with the given length.
    ''' </summary>
    ''' <param name="size">Size of the string</param>
    ''' <returns>Random string</returns>
    Public Function TypeAlphabetic(size As Integer) As String
        Return TypeAway(size, AlphabeticCharacters)
    End Function
    ''' <summary>
    ''' The Typing Monkey Generates a random alphanumeric string with the given length.
    ''' </summary>
    ''' <param name="size">Size of the string</param>
    ''' <returns>Random string</returns>
    Public Function TypeAlphanumeric(size As Integer) As String
        Return TypeAway(size, AlphaNumericCharacters)
    End Function
    ''' <summary>
    ''' The Typing Monkey Generates a random string of numbers with the given length.
    ''' </summary>
    ''' <param name="size">Size of the string</param>
    ''' <returns>Random string</returns>
    Public Function TypeNumeric(size As Integer) As String
        Return TypeAway(size, AlphaNumericCharacters)
    End Function

End Class

Don’t Use My.Settings

There is no benefit to using My.Settings in VB.NET development.

Firstly My.Settings is only available in the VB.NET environment so it’s confusing for anyone else not familiar with the environment and a bad habit to get into.

Secondly the XML to support it in the app.config file is verbose, unwieldy, and typo prone making it difficult to cut and paste to another app.config file.

Thirdly, if you are creating a class library the settings are compiled into the DLL meaning that they cannot be altered and may be used unexpectedly.

Using ConfigurationManager.AppSettings is much easier and the XML to support it is much smaller, simpler and easier to transfer between app.config files without error.

Posting Source Code in WordPress

This is so simple that it’s easily overlooked. Wrap your source code in [sourcecode] tags. Add a language element for specific styles.

Reference: http://en.support.wordpress.com/code/posting-source-code/

Improving your code quality through documentation

I believe that it’s readily possible to improve the quality of your code by documenting it as you go along. It’s a given that in order to create any documentation at all in the .NET environment that developers have to add XML comments, we should all be familiar with how to add them so I’m only going to point you in the right direction of you don’t already do this: http://msdn.microsoft.com/en-us/magazine/dd722812.aspx

Although adding comments is the first step you really shouldn’t stop there. Those comments can be easily and automatically turned into documentation with every build. Third party tools that turn your XML comments into nice looking and formatted documentation that also integrate with Visual Studio are readily available.

Personally I’m using Sandcastle Help File Builder (SHFB) as it’s well established, builds Microsoft lookalike documentation, and, most importantly, is free so there’s no need to justify any expense with the boss.

The advantage in using a tool is that you can then make sure that your documentation is developed along with your code. Which has its own benefit of improving the coverage and quality of your documentation and also has a secondary effect on improving the quality of your code as you not only need to think about getting the code working but also about understanding and communicating its purpose to others. Thus documenting your code becomes a way of reviewing and improving it. The mistakes you catch during the development phase saves your time threefold as compared to fixing it during testing or after release.

If you’re not using the documentation tools as you go along then not only is the documentation less likely to be created in the first place but it can be seen as a last minute chore and thus less effort is put into it and as a result the quality is not as good.

Anyway, enough justification, you’re already with me or you’ve stopped reading at this point. Here’s how to add ongoing documentation with Sandcastle Help File Builder (SHFB).

First, install SHFB from here: http://shfb.codeplex.com/. The installation instructions are here: http://www.ewoodruff.us/shfbdocs/Index.aspx?topic=html/8c0c97d0-c968-4c15-9fe9-e8f3a443c50a.htm you should use the ‘Guided Installation’ as it’s very easy. This will include a ‘Visual Studio Integration Package’ that allows you to create and build the documentation project within Visual Studio. However there is also a Sandcastle GUI for developing projects separately.

Once it’s all installed open up Visual Studio and your development project. Add a new project, select the newly added Documentation category, select ‘Sandcastle Help file builder Project, set a name and location and click OK.

Sandcastle works be reading the compiled DLL/EXE, extracting the XML Comments, and applying templates to turn them into documentation. This does increase the total build time, especially the first time you build the help project. The Documentation Sources folder in the help project lists which DLLs/EXEs are read. You add a DLL/EXE by right clicking the Documentation Sources folder and selecting Add Documentation Source, browse to your build folder, select your DLL/EXE and click OK. Now try a build.

By default SHFB is set to create a CHM documentation file, this will be created in a Help folder under the project folder but like a bin folder it is not included as part of the project. To see your documentation click on the Show All Files button, navigate to the .chm file and double click on it.

Marvelous isn’t it, you just saved yourself weeks of fiddling about with Word. If you’re smart you made sure to estimate the documentation phase as at least three weeks long so now you’ve got plenty of time to jet of to the Bahamas and indulge your Bond fantasies as you ‘work from home’.

Copy properties from base class to inherited class in copy constructor

When you want to inherit the properties of a base class in a derived class it’s handy to have a copy constructor that takes an instance of the base class as a parameter and copies the properties from the base class into the new class.

Usually you have to write a long list of source.property = me.property statements which is both tedious, typo prone, and must be rewritten every time either class changes.

Wouldn’t it be better if there was a single function you could call to do the bulk of the work for you?

Imports System.Reflection
''' <summary>
''' Library of copying functions
''' </summary>
''' <remarks>
''' Reference: http://stackoverflow.com/questions/1198886/c-sharp-using-reflection-to-copy-base-class-properties
''' </remarks>
Public NotInheritable Class Copier
''' <summary>
''' Generically copies the properties of one object to another.
''' </summary>
''' <typeparam name="T1">Source type</typeparam>
''' <typeparam name="T2">Target type</typeparam>
''' <param name="source">Source object</param>
''' <param name="target"></param>
''' <returns>Source object</returns>
''' <remarks></remarks>
Public Shared Function CopyFrom(Of T1 As Class, T2 As Class)(source As T1, target As T2) As T1

'Get the properties from each object
Dim srcFields As PropertyInfo() = target.[GetType]().GetProperties(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.GetProperty)
Dim destFields As PropertyInfo() = source.[GetType]().GetProperties(BindingFlags.Instance Or BindingFlags.[Public] Or BindingFlags.SetProperty)
'Copy all matches
For Each [property] In srcFields
Dim dest = destFields.FirstOrDefault(Function(x) x.Name = [property].Name)
If dest IsNot Nothing AndAlso dest.CanWrite Then
dest.SetValue(source, [property].GetValue(target, Nothing), Nothing)
End If
Next

Return source

End Function

#Region "Example Usage"
''' <summary>
''' Example base class with a single property.
''' </summary>
''' <remarks></remarks>
Private Class SelfCopyingBase

Public Property Data As String

End Class
''' <summary>
''' Example derived class.
''' </summary>
''' <remarks></remarks>
Private Class SelfCopying
Inherits SelfCopyingBase
''' <summary>
''' Copy constructor.
''' </summary>
''' <param name="source"></param>
''' <remarks></remarks>
Public Sub New(source As SelfCopyingBase)

Copier.CopyFrom(Of SelfCopyingBase, SelfCopying)(source, Me)

End Sub

End Class

#End Region

End Class