C # Prepare ActiveX controls and deploy and upgrade them (from the Network)

Source: Internet
Author: User
Tags pfx file visual studio 2010
Use C # To develop ActiveX Control controls, develop, create cab packages, signatures, and deploy

ActiveX controls are also called Ole controls. They are software components or objects supported by Microsoft IE. They can be inserted into web pages to implement dynamic program functions on the browser, to enhance the dynamic processing capability of the browser. ActiveX controls are usually developed in C ++ or VB. This article introduces another method. On the. NET Framework Platform, ActiveX controls are developed using C.

Although this article describes how to develop ActiveX controls using the C # language, I do not strongly recommend this technology because it has obvious limitations that require browser installation. net Framework (the version depends on the development of ActiveX controls.. NET Framework version. Therefore, we recommend that you use this technology only when the following items are met:

No one in the development team has mastered the use of C ++/Vb to develop ActiveX control technology;

The ActiveX control is not used on the Internet;

It is acceptable for users to access the Web browser only;

The user can accept the installation of the. NET Framework component on the browser side.

In addition, it is recommended that the dependent libraries of the control be based on a later version.. NET Framework, or a later version.. net Framework 2.0 ActiveX control development, because. net Framework 2.0 only 20 m, compared to M. net Framework 3.5 and 40 m. net Framework 4.0 is much smaller, and the requirements for the client operating system are much lower. With the constant upgrade of the Windows version, Versions later than Windows Vista have been built in. net Framework 2.0. When Windows XP system ends, the technology will also spring. Therefore, don't let me back from the above suggestions. mastering this technology is actually quite practical. After all, C #'s efficient development efficiency is very attractive.

This article will use the C # language to develop an ActiveX control,Implements MAC address traversal on the browser.In addition, a test instance is provided to call the control on a static Web page. The development environment of this instance is Visual Studio 2010 flagship edition (SP1), the target framework is. NET Framework 2.0, and the browser testing environment is Windows 7 flagship edition and IE8.

Control Development

Using C # For ActiveX control development is actually very simple. First, add a class library project to the solution. The target framework uses. NET Framework 2.0, as shown in 1:

 

Figure 1 create ActiveX control class library

Here is a key operation. You need to set the properties of the Class Library Project> assembly information> to make the Assembly com visible, as shown in 2:

 

Figure 2 set the ActiveX control class library Assembly com to be visible

The ActiveX class library consists of the IObjectSafety interface and the control class that implements this interface. Consider that all control classes must implement the IObjectSafety interface. You can abstract the implementation of this interface into a control base class.

I. IObjectSafety interface

To allow ActiveX controls to gain client trust, the control class also needs to implement an interface named "IObjectSafety. Create the interface first (note that the guid value of this interface cannot be modified). The interface content is as follows:

 1 [ComImport, Guid("CB5BDC81-93C1-11CF-8F20-00805F2CD064")] 2 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 3 public interface IObjectSafety 4 { 5     [PreserveSig] 6     int GetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] ref int pdwSupportedOptions, [MarshalAs(UnmanagedType.U4)] ref int pdwEnabledOptions); 7  8     [PreserveSig()] 9     int SetInterfaceSafetyOptions(ref Guid riid, [MarshalAs(UnmanagedType.U4)] int dwOptionSetMask, [MarshalAs(UnmanagedType.U4)] int dwEnabledOptions);10 }

Ii. Base activexcontrol control class

1 public abstract class activexcontrol: IObjectSafety 2 {3 # region IObjectSafety Member 4 5 private const string _ iid_idispatch = "{00020400-0000-0000-c000-0000000000000046 }"; 6 private const string _ iid_idispatchex = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}"; 7 private const string _ iid_ipersiststorage = "{region}"; 8 private const string _ iid_ipersiststream = "{region }"; 9 private const string _ iid_ipersistpropertybag = "{character}"; 10 11 private const int character = 0x00000001; 12 private const int interfacesafe_for_untrusted_data = 0x00000002; 13 private const int s_ OK = 0; 14 private const int e_fail = unchecked (INT) 0x80004005); 15 private const int e_nointerface = unchecked (INT) 0x80004002 ); 16 17 private bool _ fsafeforscripting = true; 18 private bool _ fsafeforinitializing = true; 19 20 21 public int getinterfacesafetyoptions (ref guid riid, ref int pdwsupportedoptions, ref int pdwenabledoptions) 22 {23 int rslt = e_fail; 24 25 string strguid = riid. tostring ("B"); 26 pdwsupportedoptions = optional | optional; 27 switch (strguid) 28 {29 case _ iid_idispatch: 30 case _ iid_idispatchex: 31 rslt = s_ OK; 32 pdwenabledoptions = 0; 33 If (_ fsafeforscripting = true) 34 pdwenabledoptions = enabled; 35 break; 36 case _ iid_ipersiststorage: 37 Case _ iid_ipersiststream: 38 case _ priority: 39 rslt = s_ OK; 40 pdwenabledoptions = 0; 41 if (_ fsafeforinitializing = true) 42 pdwenabledoptions = enabled; 43 break; 44 default: 45 rslt = e_nointerface; 46 break; 47} 48 49 return rslt; 50} 51 52 public int setinterfacesafetyoptions (ref guid riid, int dwoptionsetmask, int dwenabledoptions) 53 {54 int rslt = e_fail; 55 56 string strguid = riid. tostring ("B"); 57 switch (strguid) 58 {59 case _ iid_idispatch: 60 case _ iid_idispatchex: 61 If (dwenabledoptions & dwoptionsetmask) = signature) & 62 (_ fsafeforscripting = true) 63 rslt = s_ OK; 64 break; 65 case _ iid_ipersiststorage: 66 case _ iid_ipersiststream: 67 case _ iid_ipersistpropertybag: 68 if (dwenabledoptions & dwoptionsetmask) = success) & 69 (_ fsafeforinitializing = true) 70 rslt = s_ OK; 71 break; 72 default: 73 rslt = e_nointerface; 74 break; 75} 76 77 return rslt; 78} 79 80 # endregion81}

Iii. macactivex controls

 1 [Guid("65D8E97F-D3E2-462A-B389-241D7C38C518")] 2 public class MacActiveX : ActiveXControl 3 { 4     public string GetMacAddress() 5     { 6         var mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); 7         var mos = mc.GetInstances(); 8         var sb = new StringBuilder(); 9 10         foreach (ManagementObject mo in mos)11         {12             var macAddress = mo["MacAddress"];13 14             if (macAddress != null)15                 sb.AppendLine(macAddress.ToString());16         }17 18         return sb.ToString();19     }20 }

Note that the guid value specified in the first line is the unique identifier of the ActiveX control. Ensure that it is unique. You can use the program filesdirectory in the system directory to search for a tool named guidgen.exe. You can also write a test code to call the guid. newguid () method generation; Some Visual Studio versions also provide shortcuts, under the "tool-> Generate guid" menu. In addition, you must add a reference to system. Management system components to access MAC.

At this point, the development of the control class library is complete, and the entire implementation process is indeed very simple.

Release

But this method cannot be automatically upgraded, so this article will not introduce), to make the control class library run on the browser side, you can take two ways, one is to package the control class library as the MSI installation package and install it directly on the browser; the other is to package the MSI into a cab package, which is an ActiveX control, you can publish it along with the application. When the browser accesses the page containing the control, it will automatically prompt the installation. Next we will explain in detail the next release method.

1. Installation Project

Add an installation project to the solution, as shown in Figure 3:

 

Figure 3 add an installation project

Right-click the newly added installation project and choose add> project output from the shortcut menu. The add project output group dialog box is displayed, and the ActiveX control class library csharpactivex is selected as the main output, as shown in figure 4:

 

Figure 4 Add project output

Double-click the dependency Microsoft. NET Framework detected by the installation project to open the startup conditions page of the installation project, and select the ". NET Framework" item, as shown in Figure 5:

 

Figure 5 installation project startup Conditions

Press the F4 shortcut key to open the Properties window and set the version of the. NET Framework item to ". NET Framework 2.0", as shown in 6:

 

Figure 6 configure the dependency framework of the installation project

The following step is very important. Select "main output from csharpactivex (activity)", as shown in 7:

 

Figure 7 main output content items

Set the value of the Register attribute of the primary output item to vsdrpcom, as shown in Figure 8:

 

Figure 8 set primary output item attributes

Ii. Create a cab package

Visual Studio logging tool. The source code contains the packaging tool, which is stored in the cabin directory and contains four files: makecab.exe, cab. DDF, installer. inf, and makecab. bat. The cab. DDF and Installer. INF files need to be described briefly.

The cab. DDF file defines the packaging behavior of the cab file, including packaging parameters, packaging content items, and output files. It should be noted that the ActiveX control cab package developed using C # contains two parts: the MSI file and the installer. inf Installation File. The contents of the cab. DDF file are as follows:

.OPTION   EXPLICIT.Set Cabinet=on.Set Compress=on.Set MaxDiskSize=CDROM.Set ReservePerCabinetSize=6144.Set DiskDirectoryTemplate=".".Set CompressionType=MSZIP.Set CompressionLevel=7.Set CompressionMemory=21.Set CabinetNameTemplate="CSharpActiveX.CAB""installer.inf""CSharpActiveX.msi"

The installer. inf file defines the Installation Behavior of the cab file, which is imported into the cab package as part of the control. Its content is as follows:

[Setup Hooks]hook1=hook1[hook1]run=msiexec /i %EXTRACT_DIR%\CSharpActiveX.msi /qn[Version]Signature= "$CHICAGO$"AdvancedInf=2.0

The makecab.batfile is a batch file that is called for packaging with makecab.exe. The content is as follows:

makecab.exe   /f   "cab.ddf"

After the installation project is generated, copy the csharpactivex.msifile to the cabdirectory, and double-click the makecab.exe file to package it. After the installation is completed, the csharpactivex. cab file is output. This is the so-called ActiveX control.

Iii. Signature

IE adopts the Authenticode signature technology to control the installation of ActiveX controls on the browser. If you want to successfully install the ActiveX control generated above on the browser side, you need to set the browser. For detailed operations, see the deployment section.

It is unfriendly to set ie for all users. Therefore, we can use Authenticode technology to sign ActiveX controls. Visual Studio 2010's signtool.exe(the previous vs(is another tool, signcode.exe) code signing tool can complete this work (note that it is not necessary to use tools provided by Microsoft to sign, as long as according to the Authenticode technical standard, use the data structure defined in PKCS #7 to generate the digital signature of the file to be signed and add it to the PE Structure of the file to be signed ). However, you must first prepare a PKCS #12 (certificate and private key) file (. pfx). Note that the certificate's enhanced Key Usage must contain the code signature, as shown in Figure 9:

 

Figure 9 code signature certificate

The source code of this article provides a copy of the test PKCS #12 file Apollo. pfx with a pin code of 11111111. In Visual Studio command prompt (2010), enter the cab directory of the source code and enter the following command to sign the ActiveX control:

signtool sign –f Apollo.pfx –p 11111111 CSharpActiveX.CAB

Figure 10 compares the properties of the ActiveX control file before and after the signature. It can be seen that a digital signature is added to the property of the ActiveX control after the signature, indicating that the file has been signed.

 

Figure 10 comparison of ActiveX control attributes before and after signature

A copy of the signtool.exe tool is added to the makecab. BAT file. The modified makecab. BAT file is named makecabsigned. BAT as follows:

makecab.exe   /f   "cab.ddf"signtool sign -f Apollo.pfx -p 11111111 CSharpActiveX.CAB

Application

ActiveX controls are used for HTML static pages and executed on IE browsers. You need to introduce the page file as a tag and call it in JavaScript. The test code is as follows:

 1  2  5  6  7     11 12 

Note that the classid property value of a tag is the guid property value of the macactivex class.

Deployment

The deployment of ActiveX controls on the IE browser varies depending on whether the ActiveX controls are signed or not. This classification is described below. First, deploy the test.htm and csharpactivex. CAB files on the server. Assume that the deployed access address is http: // 192.168.1.1/test.htm.

1. Deploy unsigned ActiveX Controls

Unsigned ActiveX controls are not trusted by the browser and cannot be installed by default. You need to first add the site as a trusted site. The specific steps are as follows: Open ie tools> Internet Options, select "trusted site" on the "Security" tab, as shown in 11:

 

Figure 11 Internet Security Options

Click "Site" to open the trusted site management dialog box and add the server site to the trusted site list, as shown in 12:

 

Figure 12 trusted site dialog box

Return to the "Internet Options" dialog box and click the "Custom Level" tab to open the Security Settings dialog box for trusted sites, as shown in Figure 13:

 

Figure 13 Security Settings dialog box for Trusted Sites

Confirm that the "initialize and execute scripts for ActiveX controls that are not marked as secure scripts" item is set to "enabled", and the "Download unsigned ActiveX Control" item is set to "prompt ".

After the iesettings are complete, visit the http: // 192.168.1.1/test.htm test page (Note: Windows 7 requires "Run as administrator" ie to successfully install ActiveX control ), IE will prompt to load ActiveX control, as shown in figure 14:

 

Figure 14 loading ActiveX Control upon first access

Click "install this add-on for all users on this computer", ie will bring up a security warning to confirm whether to install this ActiveX control, as shown in Figure 15:

 

Figure 15 ActiveX Control Installation Security Warning

Click the "Install" button to confirm the installation of the ActiveX control. After the progress bar of the IE status bar is complete, it indicates that the control has been installed. You can check the "Uninstall or change program" item to confirm whether the installation is successful, 16:

 

Figure 16 confirm that the ActiveX control is successfully installed

We can see from the ActiveX control installation process that the browser actually installs the MSI installation file in the cab package in silent mode (a bit of interface J ). After the installation is complete, the ActiveX control is successfully called on the page. The interface call result is displayed. (Note that IE needs to be restarted on Windows 7 and cannot be started as an administrator, otherwise, the system prompts you to install the ActiveX control again, but the control has been successfully installed. This problem is very strange.) effect 17:

 

Figure 17 ActiveX Control Interface called successfully

2. Deploy the signed ActiveX Control

By default, IE allows you to install and run the trusted signed ActiveX Control. Therefore, adding a signature to the ActiveX control can effectively simplify the configuration of the browser. You only need to install the certificate used for signature and its certificate chain file (the signature file provided by the source code in this article contains a self-signed certificate, so its certificate chain is just its own ). Open the Apollo. CER (Digital Certificate file corresponding to the Apollo. pfx file) under the source code cab directory to sign the certificate file, as shown in 18:

 

Figure 18 signature certificate file

Click "Install Certificate" to install the certificate to "Trusted Root Certificate Authority", as shown in 19:

 

Figure 19 install the code signature certificate

Open the tool> Internet Options dialog box of IE, select the content tab, and click the certificate button to open the IE certificate dialog box, confirm that the imported code signature certificate is included in the Trusted Root Certificate Authority tab, as shown in 20:

 

Figure 20 code signature certificate imported successfully

Then, visit the test page http: // 192.168.1.1/test.htm and IE will prompt you to install the ActiveX control, instead of adding the site to a trusted site and setting the IE option.

However, what should I do if I cannot import the code signature certificate and its certificate chain for the first installation? As shown in Figure 20, some authoritative CA certificates are built in Windows by default. you can apply for a code signature certificate and private key file from these CA certificates to sign ActiveX controls, this avoids this problem. However, to apply for a certificate from an authoritative ca, you need to pay for it. Therefore, you need to weigh the cost and ease of use before making a choice.

Upgrade

To enable the ActiveX Control compiled by C # To support automatic upgrade, You need to upgrade the ActiveX control library version, upgrade the installation project version, set the installation project registry key version, and upgrade the webpage version.

1. Upgrade ActiveX Control version

Open the "assembly information" dialog box of the ActiveX Control Project and upgrade the assembly version and file version, as shown in Figure 21:

 

Figure 21 ActiveX Control version upgrade

Ii. Upgrade and install the project version

Select the installation project, press the F4 shortcut key to open the Properties window of the installation project, and upgrade the version of the installation project, as shown in 22:

 

Figure 22 upgrade and install a project

Note that another key task is to set the value of removepreviousversions to true, so that the previous version of the control is automatically uninstalled during the upgrade.

3. Set the registry key version of the installation project.

The browser checks whether the ActiveX control needs to be upgraded by comparing the codebase attribute value of the tag with that of the local hkey_classes_root/CLSID/{guid}/installedversion. Therefore, to implement automatic update, you must manually add the registry key and change the key value each time you upgrade the control.

Right-click the installation project and choose "View> Registry" from the shortcut menu. The Registry Editing page of the installation project is displayed. On the hkey_classes_root node, create the CLSID/{guid}/installedversion Registry Key Path, as shown in Figure 23:

 

Figure 23 create a registry key path

Right-click the installedversion key node and choose new> string value from the shortcut menu. A new name is blank (the blank name is displayed as "(default )"), the value is the key value of the current control version number, as shown in 24:

 

Figure 24 add default installedversion key

There are several special instructions for this step. First, {guid} refers to the guid of the ActiveX control class, which corresponds to the guid specified by macactivex class in this article, and this item must contain left and right curly braces. Second, if the installation project is used to publish Multiple ActiveX Controls (classes), you need to create multiple {guid}/installedversion paths. Finally, the default key value of installedversion is ", ", instead of". ", the key-value version number needs to be synchronized during subsequent upgrades.

4. Upgrade the webpage version

Finally, you need to upgrade the ActiveX object reference version number on the webpage, which is marked by an underscore as follows:

 

Regenerate the installer, pack the cab, and update the upgraded page and ActiveX Control (cab package) to the server. When the browser re-accesses the control, the system prompts/automatically upgrades the ActiveX control.

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.