Archive for September, 2007

Site News for 9/16/07 through 9/22/07

Announcing: VB.NET Interview QuestionsNew Series - VB.NET Interview Questions

I started a new series this weekend with VB.NET Interview Questions. I’ll be putting up an article in this category each weekend for a while. Each one will have 10 to 20 VB.NET and general software development questions for you to study and answer. I’ll have questions of all types, including open ended thinking questions. I may even include a logical brain teaser type question from time to time as well. Feel free to answer them in the comments if you like and/or send me question suggestions.

Most Popular Posts

Here are the 10 most popular posts of the week:

BlogRush + DealDotCom = Useless

After seeing a lot of hype about these two new things I decided to try them out. Now I’ve decided, after a week, that they’re useless, at least for me.

BlogRush is supposed to be a traffic building widget to bring targeted traffic to your blog based on the number of impressions the widget gets on your site and sites signed up under you. However, I found it showing links to “Made for Adsense” or other Internet marketing sites about 80-90% of the time. Black hatters are heavily gaming it right now since they’ve left many exploitations open. Plus, in the long run when you look at the numbers, only very high traffic “A-List” blogs will see any traffic from this widget. I’m staying away from it unless things change.

DealDotCom promised to offer a deal of the day with one good product available for a day at a good price. All I’ve seen offered so far are crappy eBooks and lousy software downloads. I’m pulling the ad for it today and finding something else.

Coming Up Next Week

I’m not sure what I’ll be posting next week. I still have some XML and ADO.NET articles outlined but not completed as well as some general software development articles. I am open to requests, so if there is a topic that you would like for me to cover, let me know in a comment or email.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Add comment September 22nd, 2007

VB.NET Interview Questions #1

Test Your Brain PowerA short while ago I wrote this article, How To Conduct a VB.NET Job Interview, that described how I thought a good VB.NET job interview should be done. However, I didn’t include any actual interview questions. But, based on some emails and some observations, it seems that some people who’ve found this article via search engines would like some practice questions. So, I’ve decided to start writing a weekly series with interview questions that you can practice with or even use in your own interviews. Note I’m not a big fan of trivia quiz interviews so I’m going to include some open-ended ones as well.

Feel free to add a comment with your answers. Try to answer them before looking at the comments or searching MSDN or Google for an extra challenge.

True or False

For ‘extra credit’, explain your answer

1. A HatchBrush object is used to draw paintbrush style lines.
2. A Try block does not require a Catch handler.
3. Events are based on Delegates.
4. An “is-a” relationship is implemented by composition.
5. CInt is part of the Microsoft.VisualBasic Namespace.

General Questions

1. What protocol is used to send Web Service messages?
2. What is the difference between a Stack and a Queue?
3. If a method is declared as Shared which class members can it access?
4. What .NET type should be used for currency calculations and why?
5. How would you load an XML file into a DataSet?

Open Ended Questions

1. You are given the task of designing a class to work with a frequent shopper “smart card” in a point-of-sale system. The requirements tell you that the card data feed will contain the following information:

  • Account ID - 32 numeric only characters
  • Account PIN - 8 numeric only characters
  • Customer Name - 128 characters
  • Street Address - 128 characters
  • City - 64 characters
  • State - 2 characters
  • Zip Code - 9 characters
  • Phone Number - 32 characters
  • Last Date/Time of Use - yyyymmddhhmmss formatted string
  • Expiration Date - yyyymmdd formatted string
  • Purchases - A string that contains up to 500, 16 character, transaction IDs

What methods do you think should be included in your class? What do you think your properties would look like? How would you approach this design? What questions do you think you should ask about the requirements and the design?

2. You are asked to design backend processing classes for a series of mini-web sites promoting new products by your company. You do not have to be concerned at all about the site design. Someone else will handle that. All you need to design is a way to feed unformatted product description text data to the front end and accept user registration data back from the front end. In general terms, describe the approach you would take.

Have fun with these and let me know what you think about them by leaving a comment or answering the questions.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

4 comments September 21st, 2007

Introduction to My.Computer.Network

My.Computer.Network: An Internet ShortcutMy.Computer.Network is another VB.NET My Namespace shortcut class that you can use to handle simple network and Internet operations. In this article we’ll examine the basics of this class with some code examples along the way.

These functions are essentially easy-to-use wrappers for objects found in the System.Net namespace. If you need more than what this class provides then you should look there.

IsAvailable

As you might guess, this property indicates if there is an available network connection or not. The hitch with this function is that it doesn’t tell you much about the connection, it only says if the computer has one or not. For example, a computer might have a local network connection but the Internet connection could be down but this property would return True. Therefore, you should combine this technique with the Ping function to insure that a remote location is available as seen in this code example:

If My.Computer.Network.IsAvailable Then
    If My.Computer.Network.Ping("192.168.100.1") Then
        My.Computer.Network.UploadFile(LocalFileName, RemoteAddress)
    End If
End If

NetworkAvailabilityChanged

This event is raised when the network connectivity changes but, like IsAvailable, it’s not capable of distinguishing between local and remote changes. Therefore, it really isn’t that useful in many situations. It might be handy in a web service client app, for example, a single computer at a remote small store location without a permanent or iffy Internet connection.

This event is built into the MyApplication partial friend class so, if you’re using the Windows Application Framework you just have to add code to the following built-in routine:

Partial Friend Class MyApplication

    Private Sub MyApplication_NetworkAvailabilityChanged(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.Devices.NetworkAvailableEventArgs) Handles Me.NetworkAvailabilityChanged
        If My.Computer.Network.IsAvailable AndAlso My.Computer.Network.Ping("192.168.100.1") Then
            'code to handle/report connection available
        Else
            'code to handle/report connection down
        End If
    End Sub
End Class

Ping

As we see in the code examples above Ping does a simple check to see if a remote target computer responds and returns a boolean saying if the check was successful or not. You can use an IP address, like in the examples above, or a DNS resolvable name. This means that for Internet addresses you would not include protocol prefixes like “http://” or “ftp://” but only the name. You can also provide a timeout for the ping in milliseconds and the default is 500ms, a half-second. Increasing this value can be useful if you’re dealing with a slow dial-up connection. Always verify any user input for this call to prevent unwanted exceptions. Note that some servers use firewalls and other methods to protect themselves against ping attacks and the function may return a False when there actually is a system at that address.

Here are some examples of this function:

If My.Computer.Network.Ping("192.168.100.1") Then

...

If My.Computer.Network.Ping("192.168.100.1", 2000) Then

...

If My.Computer.Network.Ping("vbnotebookfor.net") Then

....

If My.Computer.Network.Ping("www.google.com") Then

...

' Will Cause PingException
If My.Computer.Network.Ping("http://www.google.com") Then

DownloadFile and UploadFile

Download, of course, copies a file from a remote location to a local location while Upload does the opposite. Overloads provide several options beyond just the file names or URLs. As with regular file copies the source and target locations have to be accessible or an exception will occur. Therefore, it’s a good idea to do some basic validation before calling either of these routines. Unlike the Ping function, you do need to include a protocol such as “http://” or “ftp://”.

There are overloads for credentials. You can use either clear text username and password parameters (not recommended when you’re transmitting sensitive information!) or, if you’re connecting to a system that supports it, an ICredentials object.

Both have a connection timeout value with a default of 100 seconds. Remember this value is in milliseconds though. As with Ping, this parameter is useful when you have slow conditions.

Both also provide a user interface option where the user will be shown a progress dialog and can cancel the transfer. You will want to set an action to be taken when the user cancels since the default is an exception.

Download also has an option for you to specify if a local file can be overwritten or not. Upload doesn’t offer this so you may get back exceptions if the remote server doesn’t permit the overwrite. It is important to check for exceptions in these methods since there are so many things that can go wrong with remote file transfers.

Here are some simple code examples:

1. Upload file with exception handling, connectivity check, clear text username/password, and showing UI

Try
    If My.Computer.Network.IsAvailable AndAlso My.Computer.Network.Ping(RemoteServer) Then
        My.Computer.Network.UploadFile(LocalFile, RemoteLocation, UserName, Password, True, 10000)
    End If
Catch ex As Exception
    'exception handling code here
End Try

2. Download file with exception handling and connectivity check

Try
    If My.Computer.Network.IsAvailable AndAlso My.Computer.Network.Ping(RemoteServer) Then
        My.Computer.Network.DownloadFile(RemoteLocation, LocalFile)
    End If
Catch ex As Exception
    'exception handling code here
End Try

3. Upload file with exception handling, connectivity check and the current user’s credentials

Try
    If My.Computer.Network.IsAvailable AndAlso My.Computer.Network.Ping(RemoteServer) Then
        My.Computer.Network.UploadFile(LocalFile, RemoteLocation, My.User.CurrentPrincipal)
    End If
Catch ex As Exception
    'exception handling code here
End Try

I hope you’ve found this introductory overview of the My.Computer.Network class useful. If you have anything to add or if you have any questions, please feel free to leave me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

3 comments September 21st, 2007

How To Do Credit Card Validation in VB.NET

Pick a card, any cardWhen you’re depending on human interaction to enter a credit card number often you’ll find the user has accidentally typed in the wrong number. That’s why credit card number validation is a common operation in e-commerce web apps and some point-of-sale or order taking desktop apps. By pre-validating the card number a costly round trip to the credit card processor’s system can be avoided.

In this code example we will build a simple validation class that will tell us if a user entered credit card is valid and what type of card it is. I’ll also being using some techniques taken from a few of my recent tutorial articles.

The Luhn Algorithm

Credit card numbers are validated using the Luhn algorithm. This algorithm performs a simple Mod 10 checksum that’s intended to detect accidental errors in a sequence of numbers. For more on this algorithm see the Wikipedia link.

Credit Card Number Format and Test Values

In addition to validating according to Luhn algorithm, credit cards begin with certain numbers and have a certain length. Here are the formats for the four credit card types we’ll be looking at in this example:

  • Visa: 13 or 16 digit numbers starting with 4
  • MasterCard: 16 digit numbers starting with 5
  • Discover: 16 digit numbers starting with 6011 or 65
  • AMEX: 15 digit numbers starting with 34 or 37

For testing purposes you can use these values:

  • 13 Digit Visa: 4222222222222
  • 16 Digit Visa: 4111-1111-1111-1111
  • MasterCard: 5431-1111-1111-1111
  • Discover: 6011-6011-6011-6611
  • AMEX: 341-1111-1111-1111

Coding the Routine

After defining the class, we define an Enum for the credit cards in our example:

Public Class CreditCard

    Public Enum CreditCardTypes
        Invalid = 1
        Visa
        Mastercard
        Discover
        Amex
    End Enum

Notice that we’re going to use the first element as a placeholder for any invalid values. If you wanted to add more cards to the validation routine, just add them at the end of the enum.

Next, we’re going to define a list of regular expression patterns for our supported credit cards. Note that this is a private shared variable.

Private Shared CreditCardPatterns As New List(Of String) _
              (New String() { _
              "^(4d{12})|(4d{15})$", _
              "^5[1-5]d{14}$", _
              "(^(6011)d{12}$)|(^(65)d{14}$)", _
              "^3[47]d{13}$"})

Private Shared _cardNumber As String

As you can see, we’re using a little trick here to initialize our generic list using a string array. Also note that our list matches up with the enum except of the invalid value. This makes it easy to look up our values in the list. Add any new values to the end of the list and make sure the pattern corresponds to the enum.

The Visa regular expression used here is rather simple and you may need more validation to handle all the variations of this card. More complex validation regular expressions can be found at RegExLib.

We will be storing the credit card number at the module level so that we can have access to it in our Predicate function we’ll be using later.

Now, let’s start our Validation routine. In it you’ll see that we’re passing in the card number as a string and returning the card type. Our first order of business is to strip out everything but the digits from our number and declare and initialize our variables.

Public Shared Function Validate(ByVal cardNumber As String) As CreditCardTypes
    Dim CardType As CreditCardTypes = CreditCardTypes.Invalid
    _cardNumber = Regex.Replace(cardNumber, "[^d]", String.Empty)
    CardType = CType(CreditCardPatterns.FindIndex(AddressOf FindPattern), CreditCardTypes)
    If CardType = CreditCardTypes.Invalid Then
        _cardNumber = String.Empty
        Return CreditCardTypes.Invalid
    End If

Here we see the default return value being set and then our module level variable for the card number being set by using regular expressions to remove all but the numeric values from the string. Next we search for a match to our number by search our pattern list with a Predicate function called FindPattern. Here’s what the Predicate looks like

Private Shared Function FindPattern(ByVal value As String) As Boolean
    If Regex.IsMatch(_cardNumber, value) Then
        Return True
    Else
        Return False
    End If
End Function

As you can see, we use regular expression matching to check our stripped card number value against the pattern. A true or false is returned that the FindIndex function uses to determine if the matching pattern has been found. If the pattern is found, the value is set to the matching enum while it is not, a -1 is returned which matches the invalid enum value.

Now, if we don’t have a match, we return with at this point. If there is a matching pattern, we move on to the Luhn algorithm to test this value further.

    Dim Digits As Char() = _cardNumber.ToCharArray
    _cardNumber = String.Empty
    Dim Digit As Integer
    Dim Sum As Integer = 0
    Dim Alt As Boolean = False
    Array.Reverse(Digits)
    For Each Value As Char In Digits
        Digit = Integer.Parse(Value)
        If Alt Then
            Digit *= 2
            If Digit > 9 Then
                Digit -= 9
            End If
        End If
        Sum += Digit
        Alt = Not Alt
    Next
    _cardNumber = String.Empty
    If Sum Mod 10 = 0 Then
        Return CardType
    Else
        Return CreditCardTypes.Invalid
    End If
End Function

First, we convert our card number string to a character array and initialize our variables and clear out our working variable. Next, we reverse the array. This allows us to use a cleaner For Each method to loop through the array rather than working through it backwards using a counter variable.

Now, we apply the Luhn algorithm to each digit in the array by convert it from a char to an integer and applying the logic to it. After the loop we check the Mod of the Sum and either pass back the card type on True or that it’s an invalid card if False.

That’s all there is to the class, let’s take a look at how it might be called in a button click:

Private Sub btnProcessOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProcessOrder.Click
    Dim CardType As CreditCard.CreditCardTypes = CreditCard.Validate(txtCreditCardNumber.Text)
    If CardType = CreditCard.CreditCardTypes.Invalid Then
        lblStatus.Text = "Not a valid credit card number"
    Else
        lblStatus.Text = String.Concat("Valid ", [Enum].GetName(GetType(CreditCard.CreditCardTypes), CardType), " Credit Card")
    End If
End Sub

Notice that we’re using the [Enum].GetName function to get the text value for our returned enum value.

You can download the code for this example here

Adding to It

There are a number of ways to add to this class. First, it’s implemented as a shared function library. You might want to flesh it out to a full credit card class that would include making calls to a processing service and providing other functionality. Also, you may want to consider some changes to make it thread safe or you might want to add secure string functionality to it. You can also add additional cards or more checking for various card types like I mentioned about the Visa card. Remember this is just a basic example so if you use it you’ll want to adapt it to your situation.

Let me know if you found this example helpful or if I made any mistakes in it or if you have any other observations or questions by leaving me a comment.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

5 comments September 20th, 2007

Link Round-Up for 9/20/07

Sometimes a link is just a linkHere are my favorite links of the week:

Aaron of AjaxNinja was kind enough to include this site in his link list this week so I’m returning the favor. I found his article, Designing a Great Data Layer in .NET, while browsing his site. If you’re designing your own data layer for a .NET project this article has a lot of good tips. His “New and Improved” data layer is very similar to one I wrote for VB.NET.

David Lowe wrote this piece, tactics, tactics, tactics, back in June. In it he compares the study of tactics in chess with the study of coding in programming. He’s got some good ideas. My only quibble would be that one does need to eventually take a more holistic approach.

Along the same lines, Alex Miller talks about Code Spelunking Techniques. While his language of choice is Java and his IDE is Eclipse, the techniques he describes will adapt well for analyzing VB.NET and C# code in Visual Studio. His methods would be quite useful for you if you needed to translate from VB to C# or vice versa.

James R. Stoup at Apple Matters has an interesting article entitled 10 Things Every Programmer Should Know For Their First Job. A lot of it is good advice for starting any new job and just not one’s first entry into the ‘real world’. I’ve used the “bowl of candy” trick a few times when I’ve come into a new job as a contractor in order to meet people.

In his article When Non-Programmers Write Software Steven Talcott Smith considers the subject of non-professional programmers writing code. He’s got some good points but I don’t idolize the amateur programmer quite as much as he does, probably because I’ve seen some real messes in classic VB and Access.

Andy Singleton has some interesting insights into off-shoring in this article: Are “offshore rates” good? What do developers get paid around the world?. Most interesting was this quote:

Even now, Indian labor is a lot cheaper if you are buying generic “resources”, which is what the Indian companies want to sell. However, the generic “resource” is not the same as a talented human. India has a high percentage of average programmers, because Indians often become programmers to get a good job, not because they are good at it. Many of those individuals would not make it in America. The percentage of truly talented programmers is about the same in any population, and it’s a small percentage.

Too bad not that many US companies have figured that one out.

That’s all for this week. Let me know if you have any .NET or general programming sites or articles I should check out by leaving me a comment or using the Contact Me button.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

2 comments September 20th, 2007

Next Posts Previous Posts


Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives