Dynamic load classes in Visual Basic. NET (ii)

Source: Internet
Author: User
Tags bind config contains integer reflection visual studio
visual| Dynamic | load Microsoft


Step 3: Create a configuration file to hold the available forms




Some of the information that the
application needs at run time may not be available at compile time, and this information is usually placed in the configuration file. In Visual Basic 6.0, the configuration file should be an INI file or a Windows registry. In. NET, an xml-based configuration file is used.





We cannot detail the configuration file because this topic is very complex. However, you should know that the configuration file for a Windows forms application is in the same directory as the application's EXE startup file. The name of the profile is the same as the name of the program's EXE startup file, except that the suffix. config is added after the exe file name. This means that if you execute the MyApp.exe program to start my application, the name of the profile must be MyApp.exe.config, and the configuration file should be in the same directory as MyApp.exe.





The following is the configuration file to use in the example:





<?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>





here, <availableclasses> tags are placeholder information that makes it easy for people to see the format. Later, we'll come back and add configuration information for the new form you created.





This is not really the ideal way to store form configuration information because we save the DLL location and type name in the same place in a symbolic way. However, using advanced methods to store the information separately would require quite a few annotations and code, so we'll use this workaround for the moment.





use some text editors or XML editors (or Microsoft Visual studio®) to create the above configuration file, and then use the FormsOnTheFly.exe.config file name to save it in the Formsonthefly project's \bi N directory. Because the. NET configuration class uses case-sensitive XML tags, note the case of the letters in the XML tag when you create this file.





Step 4: Read the configuration information into the collection


the code we write for the form will use the classes in the System.Configuration and System.Reflection namespaces. Place the following two lines of code at the top of the Form1 code to make it easier to access these classes:





Imports System.Configuration


Imports System.Reflection


also requires a module-level variable to hold the configuration information collection. Place the following line of code next to the Inherits System.Windows.Forms.Form line of code:





Dim colavailableclasses as ArrayList


now, you can write the core code. Place the following code in the Form1 Form Load event to read the configuration file, create a collection of objects for storing information, and bind the collection data to a combo box:





' instantiates a collection of configuration information.


colAvailableClasses = New ArrayList ()


' Gets the available items to load from the configuration file.


Dim classconfigvalues as Specialized.namevaluecollection


classconfigvalues = CType (ConfigurationSettings.GetConfig ("Availableclasses"), _


specialized.namevaluecollection)





Dim Iindex as Integer


Dim slocation as String


Dim sdescription as String


Dim stype as String


Dim svalue as String





' Creates a
that can be bound to a combo box's available items

' collection.


for iindex = 0 to Classconfigvalues.count-1


sdescription = Classconfigvalues.keys (iindex)


svalue = Classconfigvalues.item (sdescription)





' through simple processing, from a field of


' Get location and type.


Dim IPos as Integer


IPos = InStr (svalue, "~")


slocation = Microsoft.VisualBasic.Left (svalue, iPos-1)


stype = Microsoft.VisualBasic.Right (svalue, Len (svalue)-IPos)





Dim objNewForm as New dynamicclass (slocation, sdescription, stype)


Colavailableclasses.add (objNewForm)


Next





' Now, bind the collection to the combo box.


' Displays a description and returns a reference to the object.


Cboforms.datasource = colavailableclasses


cboforms.displaymember = "Description"


cboforms.valuemember = "Reference"








Step 5: Insert logic to load the selected form


now, place the following logic in the btnLoadForm Click event:





Dim objformtoload as DynamicClass


objformtoload = Cboforms.selectedvalue


Dim asmassemblycontainingform as [Assembly] = _


[Assembly]. LoadFrom (objformtoload.location)


Dim typetoload as Type = Asmassemblycontainingform.gettype (objformtoload.type)


Dim genericinstance as Object


Genericinstance = Activator.CreateInstance (typetoload)





Dim formtoshow as Form = CType (genericinstance, Form)


formtoshow.mdiparent = Me


formtoshow.show ()








This is the core part of the program. Instantiate the code and display the form by using information from one of the objects in the collection. Let's explain this code line by row.





First we refer to an object (Objformtoload) that contains the location and type of the form to load. It is set to the SelectedValue property of the combo box and is used when returning the selection from a data-bound combo box.




The location of the
DLL is contained in the Location property of the object. The Loadform method of the Assembly class uses this property to create a reference to an assembly. (Placing the Assembly class in parentheses is because Assembly is a. NET keyword.) Parentheses will notify the compiler that the content is not a keyword in use, but a class name. )





below, we need to reference the. NET type (class) that is being loaded. You can use the GetType method of an assembly to refer to a string that holds the type name that will be obtained from the Type property of the object that holds the configuration data. A reference to a type is saved in Typetoload.





Reflection Classes and Activator classes use their CreateInstance methods to create instances of a type. (CreateInstance is similar to CreateObject in Visual Basic 6.0.) However, the instance must be a type object because the type is to be loaded dynamically.





Finally, the newly instantiated object (actually a form) must be converted to the correct type to enable early binding. We know it's a form, so you can use the CType function to convert it to a form.





Finally, set the new form as a subform for the MDI parent form and display it.





Note: Assemblies loaded from the URL shown in Death of the Browser are copied to the local cache. Assemblies loaded from UNC, such as the assembly in this article, are used only at the current location and are not replicated to any caches.


Step 6: Compiling the application


now, we can compile the application, but because no form has been created, no form will be displayed. You can compile and run the program to make sure it works and that the combo box loads the placeholder items correctly. If you click btnLoadForm, an error message or tutorial is displayed because the information in the configuration file does not point to any objects.





Step 7: Create the form to display


now, start creating a new Windows forms application called Firstform. Put some controls on the blank Form1 that appear-control types are not limited.





then right-click on the Firstforms project in Solution Explorer (Solution Explorer) and select Properties. Select the class library (class libraries) in the output type (out) combo box. If you do not see a combo box, you can right-click on the Solution (solution) of Solution Explorer instead of Project (project).





now starts creating the project. That is, you create a DLL that contains the form.





Create a directory named C:\NewForms. Copy the FirstForms.dll from the firstforms \ Bin directory into the C:\NewForms.





repeats the above action on items named Secondform and Thirdform. Drag different controls into each form for easy differentiation. You can also change the background color of each form to a unique color.














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.