Dynamic load classes in Visual Basic. NET (iii)

Source: Internet
Author: User
Tags bind config reference visual studio
visual| Dynamic | Load · Microsoft


Step 8: Update the configuration file with the new form information

Now that we have created some new forms, we also need to reference them in the configuration file. Replace the placeholder information in FormsOnTheFly.exe.config with the following line of code:

<add key= "the"
Value= "C:\newforms\firstform.dll~firstform.form1" > </add>
<add key= "Second Form"
Value= "C:\newforms\secondform.dll~secondform.form1" > </add>
<add key= "Third Form"
Value= "C:\newforms\thirdform.dll~thirdform.form1" > </add>

If you want to change the position or name of a form, you need to modify the line above.

Step 9: Run FormsOnTheFly.exe and load the form
Now execute FormsOnTheFly.exe (Visual Studio is not loaded). Select a form in the combo box, and then click btnLoadForm. If you complete all the steps correctly, you can see that the subform is loaded into the MDI window (even if the child form does not exist when you compile the MDI application).

Figure 2 shows the MDI form after the dynamic loading of the form.



Figure 2: MDI form after dynamically loading a form

At this point, you can create as many new forms as you want and load them into an MDI application. To make them available, compile them as class libraries, and then add references to them in the configuration file.

Dynamically loading other types of classes
This technique can be used in addition to forms for other types of classes. However, the situation is relatively complex. In the previous example, the System.Windows.Forms.Form class interface was able to be bound early because we knew it was a form. Therefore, you can use the method of the form (for example, the Show method). But for the classes we create ourselves, what interfaces can we bind to?

The answer is to create our own interface. In fact, this is a typical example of an important implementation interface. You may have used an interface in Visual Basic 6.0. Interface is created as an empty class. There is a new syntax in Visual Basic. NET, and the interface is completely separate from the class for a separate declaration. In step 1 below, we'll see how to do this.

Let's design an example of a class that can be loaded dynamically. Let's say we're writing a data cleansing application that needs to manipulate the dataset. However, as with all data cleansing programs, they never seem to have been completed. It seems always necessary to write code for the new checksum type and cleanup task.

Of course, you can create new cleanup logic and recompile the entire application, but is it better if you can dynamically insert new data cleansing without recompiling the main application? Let's start by creating an example from scratch.

Step 1: Create the class file to store the interface
Conceptually, creating an interface in Visual Basic. NET is similar to creating an interface in Visual Basic 6.0, but differs greatly in syntax. To create an initial interface class, create a new project of type class library (class libraries). Name it scrubberinterface.

In the class file you created, replace the existing line of code in the file with the following code:

Public Interface Iscrubber
Sub Scrub (ByVal ds as DataSet)
End Interface

Our interface is very simple. We need a way to manipulate the dataset. This method has been named scrub.

Now, create the project. ScrubberInterface.DLL will be created in the project's \ Bin directory.

Step 2: Create the cleanup application
Cleaning up the application is similar in many ways to the previous example of a form application. The difference is that we'll use all the data cleansing classes in turn instead of using a particular class.

Create a new Windows forms application, and then name it classesonthefly. Place the following controls in the displayed Form1:

Control type Name property setting
Button Btnloaddataset Text = "Load Dataset"
Button Btnscrubdataset Text = "Scrub Dataset"
DataGrid DataGrid1 not made changes

At the top of the Form1 code, place the same code as the top code in the previous example:

Imports System.Configuration
Imports System.Reflection
A module-level variable is also required to store the configuration information collection. Place the following line of code below the Inherits System.Windows.Forms.Form line of code:

Dim colAvailableClasses as ArrayList

Step 3: Load the DataSet into the grid for processing

To simplify the operation, the dataset is loaded from the XML file. Place the following XML file in the \ Bin directory of the ClassesOnTheFly project, and then name it timecarddata.xml:

<TimeCardData>
<Employee>
<Name> Sherlock Holmes </Name>
<ID> 123 </ID>
</Employee>
<Employee>
<Name> John Watson </Name>
<ID> 345 </ID>
</Employee>
<Employee>
<Name> Irene Adler </Name>
<ID> 567 </ID>
</Employee>
<Employee>
<Name> Jabez Wilson </Name>
<ID> 789 </ID>
</Employee>
</TimeCardData>

We need a module-level dataset reference, so place the following line of code below the line of code that declares colavailableclasses:

Dim DS as DataSet
To read the dataset and load the grid, place the following code in the Btnloaddataset click event:

ds = New DataSet ()
Ds. READXML ("Timecarddata.xml")
DataGrid1.DataSource = ds. Tables (0)

Then run the program to ensure that the grid is loaded correctly.

Step 4: Add a reference to the cleanup program interface
Next, we need to add a reference to the DLL that was previously created to hold the data cleansing class. Select Project | Add Reference (item | Add Reference). Click the browse button, browse to ScrubberInterface.DLL (created in step 1), and then click Open. Click OK to add a reference.

Step 5: Make the class store data on the available forms
Now, copy the Dynamicclass.vb module used in the previous form example and insert it into the ClassesOnTheFly project. It can be used without modification.

Step 6: Create a configuration file to hold the available forms
Create a profile that is exactly the same as the configuration file used in the previous form example. The configuration file should appear as follows:

<?xml version= "1.0" encoding= "Utf-8"?
<configuration>
<configSections>
<section name= "availableclasses" type= "System.Configuration.NameValueSectionHandler"
</configSections>
<availableclasses>
<add key= "Placeholder–do not Load"
Value= "Dllpathnamegoeshere~nameoftypegoeshere" > </add>
</availableclasses>
</configuration>

Remember to place this file in the \ Bin directory of the ClassesOnTheFly project, and then name it ClassesOnTheFly.exe.config.

Step 7: Read the configuration information into the collection
This is almost exactly the same operation as in the previous form example, except that we are not binding the collection to a combo box. So, copy the logic used in the form Load event of the forms example, but omit the last three lines of code (which is used to perform the action bound to the combo box). Paste this logic into the Form1 Form Load event in the ClassesOnTheFly project.

Step 8: Insert logic to load and use the Data cleansing class
Now, place the following logic in the Btnscrubdataset click event:

Dim Objscrubberclass as DynamicClass
For each objscrubberclass in colavailableclasses
Dim asmassemblycontainingform as [Assembly] = _
[Assembly]. LoadFrom (objscrubberclass.location)
Dim Typetoload as Type = _
Asmassemblycontainingform.gettype (Objscrubberclass.type)
Dim Genericinstance as Object
Genericinstance = Activator.CreateInstance (typetoload)
Dim Scrubber as Scrubberinterface.iscrubber = _
CType (Genericinstance, Scrubberinterface.iscrubber)
Scrubber.scrub (DS)
Next


There are many similarities between this logic and the logic of dynamically loading forms, which are no longer detailed here. The main differences are:

Dynamically loads each class in the configuration file.
The newly instantiated object is converted to the Scrubberinterface.iscrubber type. This allows you to bind to the Iscrubber interface.
Executes the scrub method for each object, passing in the dataset.
Step 9: Compile and run the application
Run the application to ensure that it compiles correctly. However, do not click the Scrub DataSet button first, because the cleanup class has not yet been created.

When the application compilation completes, close Visual Studio in the ClassesOnTheFly project.

Step 10: Create a Data cleansing class
In Visual Studio, create a new project of type class library (class libraries). Name it firstclass. Replace the automatically inserted code in CLASS1 with the following code:

Public Class FirstClass
Implements Scrubberinterface.iscrubber
Public Sub Scrub (ByVal ds as DataSet) _
Implements ScrubberInterface.IScrubber.Scrub
Dim Dr as DataRow
Dr = ds. Tables (0). NewRow
Dr. Item (0) = "Professor Moriarty"
Dr. Item (1) = "666"
Ds. Tables (0). Rows.Add (DR)
End Sub

End Class


This class implements the Iscrubber interface (just a method). This method gets the dataset and adds a separate row to the dataset. Of course, the actual data cleansing class should already have all the necessary data manipulation logic.

Create this project to get FirstClass.DLL. Copy the DLL from the project's \ Bin directory to a new directory named C:\ScrubberClasses.

Step 11: Update the configuration file with the new class
Now, go back to ClassOnTheFly.exe.config. Change the contents of the <availableclasses> tag so that it looks like this:

<add key= "Class i"
Value= "C:\scrubberclasses\firstclass.dll~firstclass.firstclass" >

Save the configuration file, and then perform the last step.

Step 12: Test the operation of the new data cleansing class
Now, run ClassesOnTheFly.exe and click the load DataSet (load Datasets) button. Please note that the grid contains four rows. Click the scrub DataSet (Cleanup DataSet) button. Line fifth is displayed in the grid (this is added by the data cleansing Class).

If necessary, you can add additional cleanup classes to perform any required actions on the dataset. Simply create a cleanup class and add it to the configuration file. Then, when you click the Scrub DataSet button, these cleanup classes are automatically used.

Summary
The most important point in both examples is that when you create and compile the original application (Formsonthefly and ClassesOnTheFly), you do not include a reference to the forms and classes that were later dynamically loaded. In fact, these forms and classes were not created when the application was compiled!

After you create forms and classes, you can use them to update your application by simply referencing their locations and types in the configuration file. You can create new forms and classes and add them dynamically as needed. If your application requires this extension, you can use the perfect solution provided by. NET, which has the ability to reflect and dynamically load classes.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.