Monday, 7 January 2013

Instantiating a Generic Type of T

I found a requirement recently where I needed to Instantiate a new instance of a Generic Type.

Ordinarily we would declare a new instance of a class using a Generic Type using something like;

Public Class ViewModel_Class(Of T)

However, If we then try to create a new Object of Type T by performing the following…



Dim MyNewObject As New T

…an error will be produced, reporting “New cannot be used on a type parameter that does not have a new constraint”.

This error is telling us that the Compiler doesn’t know if the Generic Type has an implicit “New” Sub, which is can use to Instantiate a new Object.

So, we need to add a Generic Type Constraint for a New Sub by specifying this when we declare our Generic Type;



Public Class ViewModel_Class(Of T as {New})

This tells the compiler that whatever Type T is, it will have a New Sub which it can use to instantiate the New Object.

You can read more on this subject on the Microsoft Website at;

http://msdn.microsoft.com/en-us/library/w256ka79(v=vs.110).aspx

Validating an Email Address

In order to validate an email address, use the following function;

Public Function IsValidEmailAddress(ByVal EmailAddress As String) As Boolean
    Dim Expression As New System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")
 
    If EmailAddress = "" Then
 
        Return True
 
    Else
 
        Return Expression.IsMatch(EmailAddress)
 
    End If
    
End Function

Wednesday, 2 January 2013

Adding EF5 POCO’s to TFS Source Control

While attempting to build my TFS based solution, the build failed reporting that it couldn’t find my EF5 POCO Classes.

After some digging around it seems that these files aren’t automatically included under TFS Source Control.

In order to enable this (For VS 21012), we must perform the following actions;

1. Open the Team Explorer Window using View>Team Explorer
2. You will see a list of shortcuts... My Work, Pending Changes and so on;
3. Under "Pending Changes" is a link to "Source Control Explorer"
4. Click this link, to open the Source Control Explorer Window
5. Navigate through your solution to the Project containing your edmx file
6. Above the "Source Location" will be a toolbar
7. The fourth icon from the left is "Add Items To Folder"
8. Clicking this icon will bring up the "Add to Source Control" Dialog, showing all the files in this project which aren't currently under Source Control.
9. Select all the files you wish to now include under Source Control
10. Press Next, then Finish

Now Check In your Solution again, and your POCO's should now be included.

As a word of warning, I have read that it’s possible to get Read / Write issues when performing this action. Allegedly, checking out the problem items will overcome this issue.