Archive for June, 2007

Base64 Encoding

Base64 Encoding works like magicOften a requirement is given to store binary information, such as a bitmap, inside an XML file or other text file. One way to do this is to encode the file information using Base64 encoding. This code example covers how to encode and decode file data using this method.

First of all, you may ask, “What is Base64 Encoding?” If you want to know all the nuts and bolts of it, check out this Wikipedia article — Base64 — but the easy answer is that it’s a method to encode binary data using only a-z, A-Z, and 0-9 characters.

In the example program, we will take a specified file, read it into memory and encode it as a Base64 string, place it in an XML file, then extract the encoded file from the XML file and write it to disk. First, let’s look at the encoding routine.

Public Function ConvertFileToBase64(ByVal fileName As String) As String
    Dim ReturnValue As String = ""
    If My.Computer.FileSystem.FileExists(fileName) Then
        Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open)
            Dim BinRead As BinaryReader = New BinaryReader(BinaryFile)
            Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length))
            ReturnValue = Convert.ToBase64String(BinBytes)
            BinaryFile.Close()
        End Using
    End If
    Return ReturnValue
End Function

In this routine we check that the specified file exists then open it as a stream. Then we read the data into a BinaryReader object and extract it to a byte array. Note that the number of bytes to read can be specified so that for larger files you could enhance this code to use chunking rather than reading everything in at once. The last step of the process is to convert the byte array to a Base64 string using the built-in Convert class. Also, the Using block insures that the file resource is disposed of properly.

Now we have a string of data we can place in a XML file, a database record, or anywhere else we could place a string. In this example, we will be placing the encoded data string into a XML file as an element.

OK, so now that we have the data in the XML file and saved it to disk, how do we get it back out again? The following code shows how this is done:

Public Function ExtractBase64ToFile(ByVal fileBase As String, ByVal extractFileName As String) As Boolean
    Dim FileBytes() As Byte
    FileBytes = Convert.FromBase64String(fileBase)
    My.Computer.FileSystem.WriteAllBytes(extractFileName, FileBytes, False)
End Function

To reverse the process, we load the string into a byte array and write it to disk. It couldn’t be much simplier. As with the encoding routine, this one could be further enhanced by adding chunking logic and additional exception management.

Using Base64 encoding within VB.NET is an easy way to embed binary data in your portable data files. This applies not only in XML files but other EDI file types, such as HL7 files used in the healthcare field. You can also use it with your local data files to obscure information from the casual viewer. There are many uses for this technique and it’s a useful addition to your VB.NET toolkit.

ยป Click here to download VB.NET source code for this article.

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

6 comments June 3rd, 2007

Partial Classes

Two can be better than oneThe .NET Framework 2.0 added the ability to split your class definition into multiple physical files. To the compiler, it doesn’t make any difference, it simply brings the parts together and treats them as one. But what can partial classes do to improve your projects and when should you use them?

Well, first of all, if you’re using VS 2005 you’re already using partial classes even if you don’t realize it. The IDE uses partial classes to hide details of the user interface generation from you in its hidden Designer modules. With this built-in example usage we see one of the major benefits of partial classes, separating areas of functionality into logical units. Having this kind of clean separation works well in the IDE and can work in your own classes too.

Another effective use of partial classes is that it allows more than one developer to work on a class at a time. In earlier versions of VB if one person had a class checked out then someone else who needed to make a concurrent change to a different part of the class had to wait. Now, as long as the logic is well defined and cleanly divided, multiple developers could work on the same overall class although it would be in different physical files. Of course, care must be taken to coordinate such changes and if a class is a sprawling mess some redesign work may be in order.

Often there is some benefit to separating the methods and properties of a large class. The properties may rarely change but the methods may require more frequent adjustments. Placing them in a separate file helps prevent accidental changes and allows the method programmer to focus better on their task by reducing scrolling and making debugging easier.

Another good candidate for a partial class would be a class that implemented several interfaces. It would probably be of value to separate each implementation into its own file, particularly if one or more of the implemented interfaces were large. This can be particularly effective in the multiple programmer scenario where one developer knows one interface while another understands the other well.

One thing to note is while you can split the class in to separate source files using Partial, all parts must use the same language. Unfortunately, you can’t blend VB.NET and C# partial classes together. Maybe this will be available in a future release of Framework.

The bottom line is that Partial Classes can be of great benefit to your project if you’re dealing with large, complex, classes.

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 June 2nd, 2007

Property Accessibility

You don't need scissors to split the accessibility of property routines Often when we’re designing a class we will notice that one or more properties should be Read-Only to the outside world but Read-Write at a tighter scope. A common way to do this in the past was to simply use the underlying property variable to set the variable internally. This worked but it could get complicated if there was processing logic in the property routine that needed to be called or if you needed to create a subclass. Now, however, in VS 2005 you can set the access level of the Property Get and Set separately.

VB.NET has four levels of accessibility:

  • Public - Available in all assemblies
  • Friend - Available only to code in the current assembly
  • Protected - Available only to subclasses of this class regardless of assembly
  • Private - Available only to code in the same class

For example, let’s assume that you’re creating a base class that will probably be subclassed. In this class you have a property that the subclass should be able to set but that should not be available to other code. Here’s how it would look:

Public Property Example() As String
    Get
        Return Example
    End Get
    Protected Set(ByVal value As String)
        _example = value
    End Set
End Property

Note that the Set part of the property has Protected prefixing it. This means that non-subclasses can’t set the property but a subclassing class could access it through the MyBase object.

In this example,

Public Property Example() As String
    Get
        Return Example
    End Get
    Friend Set(ByVal value As String)
        _example = value
    End Set
End Property

You would want code internal to your namespace to be able to set the value of this property but you only wanted to offer Read-Only access to external code. The Friend accessor is what you would use in this case.

Using the right access level for your properties, both the get and set portions, will increase the readability and stability of your code.

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 June 1st, 2007

Next Posts


Visit Me At My New Site, Programming In C#

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