How to use custom configuration data in a Visual Basic .NET component (321585)



The information in this article applies to:

  • Microsoft .NET Framework 1.1
  • Microsoft .NET Framework 1.0
  • Microsoft Visual Basic .NET (2003)
  • Microsoft Visual Basic .NET (2002)

This article was previously published under Q321585

SUMMARY

This step-by-step article describes how to use custom configuration files to store the configuration data for your Microsoft Visual Basic .NET components and how to access the custom configuration file in your application.

Your application may have to access a number of .NET components. Your components also require some configuration data such as database connection strings. This configuration data is stored in a custom configuration file.

Create the component

To create a component by using Visual Basic .NET:
  1. Create a new Visual Basic .NET Class Library project named MyComponent. By default, Class1.vb is created.
  2. Add the following code to the Namespace declaration section of Class1.vb.
    Imports System.Data.SqlClient
  3. Add the following code to the Class1 class.
    ' Field to hold SQL connection.
       Private m_SqlConnection As SqlConnection
    
       ' This function opens a connection to the database.
       Public Function OpenConnection(ByVal dataSource As String, ByVal initialCatalog As String, ByVal userId As String) As Boolean
          Try
             ' Make the connection string.
             Dim strConnection As String = "data source=" + dataSource + ";initial catalog=" + initialCatalog + ";user id=" + userId
             m_SqlConnection = New SqlConnection(strConnection)
             ' Open the connection.
             m_SqlConnection.Open()
    
             ' Do other database operation.
    
             ' Return success.
             Return True
          Catch
             ' In case of an error, close the connection.
             If m_SqlConnection Is Nothing Then
                m_SqlConnection.Dispose()
                m_SqlConnection = Nothing
             End If
             ' Return failure.
             Return False
          End Try
       End Function
    
  4. On theBuild menu, click Build Solution to create MyComponent.dll.

Create the test application

To create a console application to test the component that you just created:
  1. Create a new Visual Basic .NET Console Application project. By default, Module1.vb is created.
  2. In Solution Explorer, right-click References, and then click Add Reference.
  3. Click Browse, and then locate and select MyComponent.dll.
  4. Click OK.
  5. Add the following code to the Namespace declaration section of Module1.vb.
    Imports System.Reflection
    Imports System.IO
    Imports System.Configuration
    Imports System.Xml
    Imports System.Collections.Specialized
  6. Replace the existing Main method with the following code.
       Sub Main()
    
          Dim objMyCOmponent As MyComponent.Class1
          objMyCOmponent = New MyComponent.Class1()
    
          ' The following code shows how to read the configuration file.
          Dim codeBase As String = [Assembly].GetExecutingAssembly().CodeBase
          Dim codeBaseDir As String = Path.GetDirectoryName(codeBase)
          Dim configFilename As String = Path.Combine(codeBaseDir, "CustomConfigFile.config")
    
          ' Load the configuration file in XML document.
          Dim doc As XmlDocument = New XmlDocument()
          doc.Load(configFilename)
    
          ' Get the databaseconnection node.
          Dim xNode As XmlNode = doc.GetElementsByTagName("databaseconnection").Item(0)
    
          ' Use the NameValueSectionHandler class to get the actual databaseconnection setting.
          Dim csh As IConfigurationSectionHandler = New NameValueSectionHandler()
          Dim nvc As NameValueCollection = CType(csh.Create(Nothing, Nothing, xNode), NameValueCollection)
    
          ' Call the method in Component.
          Dim blnStatus As Boolean
          blnStatus = objMyCOmponent.OpenConnection(nvc("data source"), nvc("initial catalog"), nvc("user id"))
    
          ' Display results.
          If blnStatus = True Then
             Console.WriteLine("Database connection was success fully opened.")
          Else
             Console.WriteLine("Database connection was not opened.")
          End If
    
       End Sub
    
  7. On the Build menu, click Build Solution to create the console application executable file.

Create the configuration file and run the application

To create the configuration file for the component:
  1. In Notepad or in another text editor, type the following text.
    <configuration>
    	<databaseconnection>
    		<add key="data source" value="[SQL Server Name]" />
    		<add key="initial catalog" value="pubs" />
    		<add key="user id" value="sa" />
    	</databaseconnection>
    </configuration>
  2. Replace [SQL Server Name] with the name of your instance of Microsoft SQL Server.
  3. Add additional parameters, such as password information, according to your requirements.
  4. Save the text file as CustomConfigFile.config in the folder where your Console Application executable file resides.

    Important The configuration file contains user credentials. For the security reasons, we recommend that you do the following to help protect the configuration file:
    • Configure the user account for which you want to grant permissions in the Group or user names section.
    • Grant related permissions in the Properties dialog box for the configuration file. You can do this in the Permissions for Administrator section on the Security tab.
  5. Run the console application and verify the results.
You receive the following message:Database connection was success fully opened.Note that you can also access the custom configuration file in other types of applications.

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web site:

Modification Type:MajorLast Reviewed:4/20/2006
Keywords:kbConsole kbConfig kbManaged kbHOWTOmaster KB321585 kbAudDeveloper