Call a Function or Subroutine with its string name using the Invoke method

Found this tidbit of information that has proven to make my scripts more efficient and figured I’d share.

While the CallByName() function, which allows you to call a function or subroutine using the subroutine or function name stored as a string value, still works in VB. NET, you do have another option. You can use the Invoke() method of the MethodInfo class. This class is a member of the System.Reflection namespace and it provides access to a method′s metadata. Consider the following subroutine:

Public Sub CallMe(ByVal arg1 As _
String, ByVal arg2 As String)
   'do something
End Sub

To call this subroutine using the Invoke method, you can use code similar to the following:

Dim SubName As String = "CallMe"
Dim arguments() As String = _
   {"Hello ", "world."}
Dim PageType As Type = Me.GetType()
Dim MyMethod As System. _
   Reflection.MethodInfo = _
MyMethod.Invoke(Me, arguments)

The GetMethod() method obtains information about the CallMe() function and the Invoke() method calls it using the argument list. This is an excellent tool to help you streamline your code if you have several different functions, but you won′t know which one to call until runtime. For example, if you have a new edit and delete routine for updating database records, instead of using an If..Then or Case statement to call the right method, just link the name of each method to the user′s requested action.

Visual Studio Debugging Issue

For application development for .NET, my tool of choice is MS Visual Studio. Every once in while lately I’ve run into an issue that frustrates the heck out of me. I will be coding my app, make a breakpoint where I’d like to start watching the performance of the application, and click the green debug arrow. My application will execute and not stop at my break points. I couldn’t figure out what was going on, I tried even on some occasions restarting VS hoping it was just a gliche.

I learned that there is an issue or conflict with using IE8 as your debugging browser — which is what I use. It appears that if you have opened multiple instances of IE8 and you attempt to debug your project, you will more than likely encounter this issue where the VS debugger just will not stop and ignores your break points. How rude! Apparently IE8 has a feature called “Loosely-Coupled Internet Explorer” (LCIE) which results in IE running across multiple processes. Older versions of VS Debugger can get confused by this and cannot figure out how to attach to the correct process. (I guess that explains why it happens mostly in VS 2005.)

Well I might have open browsers because I’m searching for a solution or resource to assist with the project, so closing out all my instances of IE8 may not be the most convenient thing.

I found this quick fix to solve the problem. You’ll need to disable the process growth feature of LCIE.

  1. Open RegEdit
  2. Browse to HKEY_LOCALMACHINE -> SOFTWARE -> Microsoft -> Internet Explorer -> Main
  3. Right-click on Main and select to add a new DWORD value, and name it TabProcGrowth
  4. Click on TabProcGrowth and make sure the Value data is equal to 0, and click OK.

Now your VS Debugger should work just fine. Feel free … open as many instances of IE8 as your heart’s content! Happy Debugging!

Read more about LCIE –

Original solution found at:

Resetting a Form in ASP.NET

Here’s a quick and dirty way of resetting an form on your website or web application by Imran Akram on his blog. Although you could easily go through each form element and set it to an empty value and set all your select type elements to index -1, this snippet helped me when I designed a form with over 20 elements. I’ve translatted Imran’s snippet to VB.NET.

Public Sub ResetFields(ByVal pageControls As ControlCollection)
    For Each contl As Control In pageControls
        Dim strCntName As String = contl.GetType.Name
        Select Case strCntName
            Case "TextBox"
                Dim tbSource As TextBox = DirectCast(contl, TextBox)
                tbSource.Text = ""
            Case "RadioButtonList"
                Dim rblSource As RadioButtonList = DirectCast(contl, RadioButtonList)
                rblSource.SelectedIndex = -1
            Case "DropDownList"
                Dim ddlSource As DropDownList = DirectCast(contl, DropDownList)
                ddlSource.SelectedIndex = -1
            Case "CheckBox"
                Dim chkSource As CheckBox = DirectCast(contl, CheckBox)
                chkSource.Checked = False
            End Select
End Sub

Here is an example of an button that calls the procedure:

Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
End Sub

Using ASP.NET’s Membership, Roles and Profiles with your existing database

Many times as a developer you need to implement a user-access only portion of your website or application. For years now, Microsoft has provided a fairly simple way to do this with the membership and role providers. There are several articles to help developers implement this into their websites and customize the information they gather and store about the user using profiles. I think Scott Mitchell does an excellent job of breaking it down for you and giving you the scripts to customize it to fit into your website.

Just a brief summary for the newbies, the membership and role provider creates database objects for you to store membership or user information, then provides classes for interacting with those objects. There are even web controls in Visual Studio (and Visual Web Express) that create login boxes, registration forms…etc to work with those classes and the db objects. The basic installation creates its own database for storing all this membership data, but some developers opt to use their existing databases.

Now Microsoft gives you an ASP.NET SQL Server Registration Tool to create this database with the option of using your existing and/or remote database through wizard that is initiated with a command line.  However, the one problem I ran into over and over again is that some hosting companies don’t allow you to run command lines and even when I run the command line locally and try to point to the remote SQL Server, well with all the firewalls in place, it just didn’t work.

If this is a problem for you as well, try generating an .sql script on your local workstation that you can execute on your remote SQL Server. Navigate to %Windows%\Microsoft.NET\Framework\v2.0.50727 and run the following command line:

aspnet_regsql.exe -A all -sqlexportonly <filename>

Now you can log onto your SQL Server with whatever tool you use and run the .sql script. It will create the tables, stored procedures and other db objects you need to start using the membership provider. Good luck!

Create a random character string

About a year ago I had to create a RSVP application that allowed the attendees to complete an RSVP form and receive a confirmation code in return. I wanted to create a random number with a specific number of characters for my confirmation code. 

Here’s the code that generated the confirmation code. 

Public Function GetRandomPasswordUsingGUID(ByVal length As Integer) As String
        'Get the GUID
        Dim guidResult As String = System.Guid.NewGuid().ToString()

        'Remove the hyphens
        guidResult = guidResult.Replace("-", String.Empty)

        'Make sure length is valid
        If length <= 0 OrElse length > guidResult.Length Then
            Throw New ArgumentException("Length must be between 1 and " & guidResult.Length)
        End If

        'Return the first length bytes
        Return guidResult.Substring(0, length)
End Function

The required length for our random confirmation code is used as the parameter in our function. For my confirmation code, I strip any hyphens and then return only the number of characters I originally requested. I found this approach as a quick and easy way to generate a random confirmation code for my RSVP application.

Creating a barcode image in your ASP.NET page

There are many products out there that can dynamically generate various types of barcodes to be used in your web application, but if you just need something simple that uses the basic Code 3 of 9 symbology this is a simplified way. It utilizes two different .aspx pages. One will create the barcode image, and the other will provide the characters to be translated and embed the barcode page.

The image for the Code 3 of 9 symbology is actually a font. The font has to be installed on the server or computer for the website that will create the barcode, but the browsing user themselves will not have to have the font installed since we will render the barcode as an image in our page.

First, download the free Code 3 of 9 symbology font at from ID Automation.

Next, we will create a new .aspx page that will render the barcode image. Let’s call it barcode.aspx. Copy this code in the code-behind:

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls

Partial Class BarCode
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' Get the Requested code to be created.
        Dim Code As String = Request("code").ToString()

        ' Multiply the lenght of the code by 40 (just to have enough width)
        Dim w As Integer = Code.Length * 40

        ' Create a bitmap object of the width that we calculated and height of 100
        Dim oBitmap As New Bitmap(w, 100)

        ' then create a Graphic object for the bitmap we just created.
        Dim oGraphics As Graphics = Graphics.FromImage(oBitmap)

        ' Now create a Font object for the Barcode Font
        ' (in this case the IDAutomationHC39M) of 18 point size
        Dim oFont As New Font("IDAutomationHC39M", 18)

        ' Let's create the Point and Brushes for the barcode
        Dim oPoint As New PointF(2.0F, 2.0F)
        Dim oBrushWrite As New SolidBrush(Color.Black)
        Dim oBrush As New SolidBrush(Color.White)

        ' Now lets create the actual barcode image
        ' with a rectangle filled with white color
        oGraphics.FillRectangle(oBrush, 0, 0, w, 100)

        ' We have to put prefix and sufix of an asterisk (*),
        ' in order to be a valid barcode
        oGraphics.DrawString("*" & Code & "*", oFont, oBrushWrite, oPoint)

        ' Then we send the Graphics with the actual barcode
        Response.ContentType = "image/jpeg"
        oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg)
    End Sub
End Class

We place our code inside the Page_Load routine because when the barcode.aspx page gets displayed it should dynamically create the barcode image. The first line take the string that is sent in the form of a request to this page and stores it a the variable ‘Code’. We are going to send this request from our container .aspx page.

Create a second .aspx page that will be used as your container page, call it container.aspx. Add an image control and call it ‘myBarCode’. This will hold the rendered barcode image.

<asp:Image id="myBarCode" runat="server" />

 Now in the code-behind for your container.aspx page, add the following:

Dim barCodeStr as String = "1234ABCD"
myBarCode.ImageUrl = "BarCode.aspx?code=" + barCodeStr

In this code, ‘barCodeStr’ is the string variable that will hold whatever set of characters you wish to be rendered as a barcode. The string is then sent as a querystring request to the BarCode.aspx page which creates the barcode image. Then the product of that .jpg image is provided as the ImageUrl to the image control placed on your container page.

Now in our example, we prepopulated the character string that we wanted rendered as a barcode, however, you can give value to this string variable in whatever way you need to in order for your application to work, even through a random character string.