Thursday, April 19, 2007

HOW TO: Call a Visual Basic .NET Class Library from Visual Basic for Applications in Microsoft Office

HOW TO: Call a Visual Basic .NET Class Library from Visual Basic for Applications in Microsoft Office


Create the Visual Basic .NET Class Library
loadTOCNode(2, 'summary');
1.
Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. Under Visual Basic Projects, select Class Library. Name the class CryptoClass and click OK. Class1 is created by default.
2.
Replace the contents of Class1 with the following code:Imports System.Security.Cryptography
Public Class Class1
Public Const ClassId As String = "98349785-8BE2-4604-848D-F5B103D61715"
Public Const InterfaceId As String = "36613EE9-125F-493d-9968-771E18C2226A"
Public Const EventsId As String = "A036F02F-F87E-4548-A536-7DD7EA8E62B5"
Const sKey As String = "MyKey"
Public Function EncryptTripleDES(ByVal sIn As String) As String
Dim DES As New TripleDESCryptoServiceProvider()
Dim hashMD5 As New MD5CryptoServiceProvider()
' Compute the MD5 hash.
DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
' Set the cipher mode.
DES.Mode = CipherMode.ECB
' Create the encryptor.
Dim DESEncrypt As ICryptoTransform = DES.CreateEncryptor()
' Get a byte array of the string.
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(sIn)
' Transform and return the string.
Return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
Public Function DecryptTripleDES(ByVal sOut As String) As String
Dim DES As New TripleDESCryptoServiceProvider()
Dim hashMD5 As New MD5CryptoServiceProvider()
' Compute the MD5 hash.
DES.Key = hashMD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(sKey))
' Set the cipher mode.
DES.Mode = CipherMode.ECB
' Create the decryptor.
Dim DESDecrypt As ICryptoTransform = DES.CreateDecryptor()
Dim Buffer As Byte() = Convert.FromBase64String(sOut)
' Transform and return the string.
Return System.Text.ASCIIEncoding.ASCII.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length))
End Function
End Class
Note You can use the GUID generator to generate new GUIDs for the ClassId, InterfaceId, and EventsId. To generate new GUIDs, click Create GUID on the Tools menu.
3.
From Project Properties, select Configuration Properties. Click Build and then select the Register for COM Interop check box. Click OK.
4.
On the Build menu, click Build Solution to create the DLL.