Showing posts with label vb. Show all posts
Showing posts with label vb. Show all posts

Tuesday, August 4, 2009

Constructors for VB.NET Modules


Did you know that you can have a constructor on a module? I first got the notion to try this after thinking about static constructors in C#. In C#, you can do something like this:

class Class1
{
private static int _magicNumber;

static Class1()
{
_magicNumber = 4;
}
}
So the next thing to try was to test this out in VB.NET:

Module Module1

Sub New()
Debug.WriteLine("New")
End Sub

Public Sub Test()
Debug.WriteLine("Test")
End Sub

Public Sub Test2()
Debug.WriteLine("Test2")
End Sub
End Module
Running this and calling the methods Test / Test2 (in that order) yields this:

New
Test
Test2

So as you might expect, the construct only gets called once, but is called before any members are accessed in the module. Handy!

Monday, April 20, 2009

DebuggerStepThroughAttribute

Let's say you have some code that often throws an exception, but you just swallow it and carry on. This is usually fine, unless you have your debugger set to break on. So take some code like this:

Public Shared ReadOnly Property IsInstalled() As Boolean
Get
Dim isInstalled As Boolean = False

Try
Dim temp as Object = CreateObject("Some.ActiveX")
isInstalled = True
Catch ex as Exception
End Try

Return isInstalled

End Get
End Property

If the COM object doesn't create properly, it will generate an exception. This sort of code is usually in the start up of an application, so you might have to hit this every time you debug your app. It's annoying.

However, if you add the handy attribute DebuggerStepThrough just before the Get clause:

Public Shared ReadOnly Property IsInstalled() As Boolean
<DebuggerStepThrough()> _
Get
Dim isInstalled As Boolean = False

Try
Dim temp as Object = CreateObject("Some.ActiveX")
isInstalled = True
Catch ex as Exception
End Try

Return isInstalled

End Get
End Property
Then Visual Studio just runs over the code like nothing ever happened.

Saturday, April 18, 2009

Roanoke Code Camp 2009 - The Code



Apologies for not getting this published sooner... Between getting ready to move houses and my normal level of laziness and procrastination, I haven't done it. It also took some Googling to figure out how to include code in a BlogSpot post. Enough whinging, here's the code for the OPC (Open Packaging Convention) class I did.

By the way, here is my DevX article on the same subject that got published recently.

Here is the code to create a package:

'Open the package
Using package As Package = package.Open("c:\Example.zip", IO.FileMode.OpenOrCreate)

'Create the uri for the text file
Dim uri As New Uri("/TextFiles/MyTextFile.Text", UriKind.RelativeOrAbsolute)

'Create the part for the text file
Dim part As PackagePart = package.CreatePart(uri, System.Net.Mime.MediaTypeNames.Text.Plain)

'Get the stream for the part
Using stream As Stream = part.GetStream()

'This is the text we'll put in the part
Dim myText As String = "This is an ugly picture of a flower - Roanoke!"

'We need to get the string into a byte array to make it easy to write to the part stream
Dim buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(myText)

'Write to the part stream
stream.Write(buffer, 0, buffer.Length)

End Using

'This is the uri for the flower
Dim uri2 As New Uri("/Images/Flower.jpg", UriKind.RelativeOrAbsolute)

'Create the part for the image
Dim part2 As PackagePart = package.CreatePart(uri2, _
System.Net.Mime.MediaTypeNames.Image.Jpeg)

'Get the stream for this part
Using stream As Stream = part2.GetStream()

'Read the data from the file
Dim buffer As Byte() = File.ReadAllBytes("c:\Flower.jpg")

'write the data to the part
stream.Write(buffer, 0, buffer.Length)

End Using

'Create a relationship between the parts
Dim relationship As PackageRelationship = _
part2.CreateRelationship(part.Uri, TargetMode.Internal, "flower_to_text")

End Using

And here is the code to read that package:

 'Create the package
Using package As Package = package.Open("c:\Example.zip", IO.FileMode.Open)

'We know the Uri for the flower, so let's start there
Dim flowerUri As New Uri("/Images/Flower.jpg", UriKind.RelativeOrAbsolute)

'Get the part using the uri we just set up
Dim flowerPackagePart As PackagePart = _
package.GetPart(flowerUri)

'Create a relationship from the
Dim relationships As PackageRelationshipCollection = _
flowerPackagePart.GetRelationshipsByType("flower_to_text")

'Get the first relationship (in real code, we would want some error checking here)
Dim relationship As PackageRelationship = _
relationships(0)

'Get the part from the relationship (once again, this would need some
' error protection because in a real world app this part might not exist anymore).
Dim textPart As PackagePart = package.GetPart(relationship.TargetUri)

'Get the stream
Using stream As Stream = textPart.GetStream()

'Create a buffer
Dim buffer(stream.Length) As Byte

'Read the stream
stream.Read(buffer, 0, stream.Length)

'Read the text
Dim myText As String = System.Text.ASCIIEncoding.ASCII.GetString(buffer)

'Show the text (the crowd should go wild here)
MessageBox.Show(myText)

End Using

End Using

End Sub

Tuesday, January 6, 2009

XML Literals with namespaces

I love Xml literals in VB. They're pretty slick. However, I ran into a little gotcha today... All I wanted to do was query some data from an xml that happened to be part of a Word 2007 template (a .dotm file). It looked like I had the right query syntax, but I wasn't getting any result.

Most of the examples I found on the web were searching through xml like this:
Dim document = <customers>
<customer firstname="John"></customer>
<customer firstname="Juliet"></customer>
</customers>

Dim firstNames = From customer In document.<customers>.<customer> _
Select customer.@firstName

This works like a champ. firstNames contains what you would expect:
{Length=2}
(0): "John"
(1): "Juliet"

But let's say our xml is part of a namespace (much more realistic)

Dim document = <customers xmlns="http://fowlcoder.blogspot.com/xmlLiteralExample">
<customer firstname="John"></customer>
<customer firstname="Juliet"></customer>
</customers>
If we use the same query code as above, we don't get any results. We actually have to add some code to make the query aware of the namespace. It's pretty straightforward.

First, add an Imports statement at the beginning of the file:
Imports <xmlns:fc="http://fowlcoder.blogspot.com/xmlLiteralExample">
Now, you have to alter the query a little bit:

Dim firstNames = From customer In document.<fc:customers>.<fc:customer> _
Select customer.@firstName

Voila! You get the results that you would expect (John and Juliet).