C # ActiveX Web page Packaging verification automatic upgrade

Source: Internet
Author: User
Tags pfx file visual studio 2010

Original address: http://www.cnblogs.com/yilin/p/csharp-activex.html

Note: Win10 need to set compatibility mode, F12 emulation switch to IE6-8 (version reference--bt9024:ie can use ClassID and codebase properties in combination to download, install and use the ActiveX plug-in) will work properly. If not, you need to set Internet options to enable downloading unsigned ActiveX controls, such as:

Verify the effect:

An ActiveX control, formerly known as an OLE control, is a software component or object supported by Microsoft IE that can be inserted into a Web page to perform dynamic program functions on the browser side to enhance the dynamic processing capabilities of the browser side. Typically, ActiveX controls are developed in the C + + or VB language, and this article describes another way to develop ActiveX controls on the. NET framework platform using the C # language.

Although this article is all about how to develop ActiveX controls using the C # language, I do not strongly recommend using this technique because there is a clear limitation that the browser-side installation of the. NET Framework (version depends on the. NET used by the development ActiveX control) Framework version), this limitation is almost unacceptable for picky Internet users. Therefore, I recommend that you consider using this technique when you are satisfied with the following:

    • No one in the development team has mastered the use of C++/VB to develop ActiveX control technology;
    • The ActiveX control is not used for the Internet;
    • The user can only use IE browser access to express acceptable;
    • Users can accept that the. NET framework components are installed on the browser side.

In addition, I recommend that you develop ActiveX controls on the. NET Framework 2.0 if it is not because the control's dependent libraries are based on a later version of the. NET Framework, or if you need the extended functionality provided by the later. NET Framework, such as WCF, and so on. Because the. NET Framework 2 has only 20M, the. NET Framework 3.5 and 40M. NET Framework 4.0 are much smaller compared to the 300M, and the requirements for the client operating system are much lower. And as the Windows version continues to evolve, a later version of Windows Vista has built-in the. NET Framework 2.0. When the Windows XP system dies, it will also usher in the spring of the technology. So, do not be my above suggestions tamping back, mastering the technology is actually quite practical value, after all, C # Efficient development efficiency is very attractive.

This article will then use the C # language to develop an ActiveX control that enables MAC address traversal on the browser side, and provides a test instance that invokes the control in a Web static page. The development environment for this instance is visual Studio 2010 flagship (SP1), the target framework for the. NET Framework 2.0, and the browser-side test environment for Windows 7 flagship, IE8.

Control development

Using C # for the ActiveX control development process is actually simple. First, you add a class library project to the solution, and the target framework uses the. NET Framework 2.0, 1:

Figure 1 Create ActiveX Control class Library

Here is a key operation that you need to set the class library project Properties---assembly information--to make assembly COM visible, as shown in 2:

Figure 2 Set ActiveX Control class Library Assembly COM Visible

The contents of the ActiveX Class library roughly consist of two parts, the IObjectSafety interface, and the control class that implements the interface. Considering that all control classes implement the IObjectSafety interface, you can abstract the implementation of that interface into a control base class.

First, IObjectSafety interface

In order for the ActiveX control to gain trust from the client, the control class also needs to implement an interface called "IObjectSafety". Create the interface first (note that you cannot modify the interface's GUID value), and the interface reads 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 (U NMANAGEDTYPE.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}

Second, ActiveXcontrol control base class

 1 public abstract class Activexcontrol:iobjectsafety 2 {3 #region IObjectSafety member 4 5 Private Const String _ IID_IDispatch = "{00020400-0000-0000-c000-000000000046}"; 6 Private Const String _iid_idispatchex = "{a6ef9860-c720-11d0-9337-00a0c90dcaa9}"; 7 Private Const String _iid_ipersiststorage = "{0000010a-0000-0000-c000-000000000046}"; 8 Private Const String _iid_ipersiststream = "{00000109-0000-0000-c000-000000000046}";  9 Private Const String _iid_ipersistpropertybag = "{37d84f60-42cb-11ce-8135-00aa004bb851}";      Interfacesafe_for_untrusted_caller = 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), Private const int E_NO INTERFACE = unchecked ((int) 0x80004002); + private bool _fsafeforscripting = true;18 private bool _fsafeforiniti alizing = true;19 public int GetinterfacesafetyoptiONS (ref Guid riid, ref int pdwsupportedoptions, ref int pdwenabledoptions), {Rslt = e_fail;24 25 String strguid = riid. ToString ("B"); pdwsupportedoptions = Interfacesafe_for_untrusted_caller |             interfacesafe_for_untrusted_data;27 switch (strguid) (_iid_idispatch:30) Case _iid_idispatchex:31 Rslt = s_ok;32 pdwenabledoptions = 0;33 if (_fsaf Eforscripting = = true) Pdwenabledoptions = interfacesafe_for_untrusted_caller;35 bre ak;36 Case _iid_ipersiststorage:37 Case _iid_ipersiststream:38 case _iid_ipersistprope rtybag:39 Rslt = s_ok;40 pdwenabledoptions = 0;41 if (_fsafeforinitializin             G = true) Pdwenabledoptions = interfacesafe_for_untrusted_data;43 break;44 default:45 Rslt = e_nointerface;46 break;47}48 return rslt;50}51 public int Setinterfacesaf Etyoptions (ref Guid riid, int dwoptionsetmask, int dwenabledoptions) @ $ {si int Rslt = e_fail;55 + str ing strguid = riid. ToString ("B"); (strguid) _iid_idispatch:60 case _iid_idispatch                         ex:61 if (((Dwenabledoptions & dwoptionsetmask) = = Interfacesafe_for_untrusted_caller) &&62 (_fsafeforscripting = = True)) RSLT = s_ok;64 break;65 Case _iid_ipersiststorage:66 Case _ iid_ipersiststream:67 Case _iid_ipersistpropertybag:68 if ((Dwenabledoptions & Dwoptionse                     Tmask) = = Interfacesafe_for_untrusted_data) &&69 (_fsafeforinitializing = true)) 70 RSLT = s_ok;71 break;72 default:73                 RSLT = e_nointerface;74 break;75}76 return rslt;78}79 #en DREGION81}

Third, Macactivex control class

1 [Guid ("65d8e97f-d3e2-462a-b389-241d7c38c518")] 2 public class Macactivex:activexcontrol 3 {4 public     string Getmac Address () 5     {6         var mc = new ManagementClass ("Win32_NetworkAdapterConfiguration"); 7         var mos = MC. GetInstances (); 8         var sb = new StringBuilder (), 9         foreach (ManagementObject mo in MoS) one         {ten             var macAddress = mo["Mac Address "];13             if (macAddress! = null)"                 . Appendline (Macaddress.tostring ());         }17,         return sb. ToString ();     }20}

Note that the GUID value specified in the first line is the unique identity of the ActiveX control, and is guaranteed to be unique. There are several ways to generate a GUID, you can search for a tool called Guidgen.exe in the system directory's program Files directory, or you can write a test code that calls the Guid.NewGuid () method, and some visual The studio version also provides a shortcut under the Tools, Build GUID menu. Also, accessing your Mac requires adding a reference to the System.Management system component.

In this way, the development of the control class library is done, and the whole implementation process is really simple.

Release

C# The development of the ActiveX control class library is not like OCX directly through the Regsvr32.exe registration (in fact, Microsoft provided the tool Regasm.exe, but because this way to not implement automatic upgrade, so this article does not introduce), in order to make the control class library run on the browser side, you can take two ways, one is to control the The Package class library is packaged as an MSI installer and then installed directly on the browser side, the other is to encapsulate the MSI as a cab package, which is an ActiveX control that can be published with the application and automatically prompts for installation when the browser side accesses the page containing the control. This is followed by a detailed explanation of the latter way of publishing.

First, the installation project

Add a Setup project to the solution, as shown in 3:

Figure 3 Add a Setup project

Right-click on the newly added setup project, select the Add Project Output menu, open the Add Project Output Group dialog box, and select the ActiveX Control class library "Csharpactivex" as the primary output, as shown in 4:

Figure 4 Add Project Output

Double-click the dependencies that are detected by the Setup project, Microsoft. NET Framework, open the startup conditions interface for the installation project, and select the ". NET framework" item, as shown in 5:

Figure 5 Install project Launch 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 set up a dependency framework for Setup Projects

The following step is critical, check the "main output from Csharpactivex (active)" Item, 7:

Figure 7 main output Content Item

The Register property value for setting the contents of the main output item is vsdrpcom,8:

Figure 8 set main output item properties

Second, the production of cab package

Visual Studio 2010 provides a CAB project template, but unfortunately, no matter how I set it, the CAB installation package that it generates cannot be successfully installed at the terminal, and eventually it can only be discarded, and the Makecab.exe tool is selected instead. The source code provides the packaging tool, located in the Cab directory, contains Makecab.exe, CAB.DDF, Installer.inf and makecab.bat four files, where CAB.DDF and Installer.inf files need to be explained briefly.

The Cab.ddf file defines the packaging behavior of the CAB file, including package parameters, packaged content items, and output files. It should be noted that the CAB package for ActiveX controls developed using C # needs to include both 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 entered into the CAB package as part of the control, with the following contents:

[Setup hooks]hook1=hook1[hook1]run=msiexec/i%extract_dir%\csharpactivex.msi/qn[version]signature= "$CHICAGO $" advancedinf=2.0

The Makecab.bat file is a batch file that calls Makecab.exe for packaging, as follows:

Makecab.exe/   F   "CAB.DDF"

After you build the Setup project, copy the Csharpactivex.msi file to the CAB directory, you can double-click the Makecab.exe file to package it, and then output the Csharpactivex.cab file when the execution is finished, which is called an ActiveX control.

Third, signature

IE uses the Authenticode code signing technique to control the behavior of the browser-side installation of ActiveX controls. The ActiveX controls generated above will need to be set for the browser if they want to install successfully on the browser side, see the Deployment section for details.

It is not very friendly for all users to set up IE, so we can consider using Authenticode technology to sign the ActiveX control. Visual Studio 2010 The accompanying SignTool.exe (previous version of VS provides another tool Signcode.exe) Code Signing tool can do the work (note that it is not always required to use the tools provided by Microsoft to sign, as long as the Authenticode technical standards, using PKCS#7 The data structure defined by the standard to generate a digital signature of the file to be signed and add it to the PE structure of the file to be signed. However, you need to prepare a pkcs#12 (certificate and private key) file (. pfx), note that the certificate's enhanced Key usage must contain code signing, as shown in 9:

Figure 9 Code Signing Certificate

The source code of this article provides a test pkcs#12 file Apollo.pfx,pin code is 11111111. In the Visual Studio command Prompt (2010), enter the source's Cab directory and enter the following command to sign the ActiveX control:

SignTool sign–f apollo.pfx–p 11111111 csharpactivex.cab

Figure 10 compares the ActiveX control file properties before and after the signature, as you can see, that a digital signature is already in the Signature ActiveX control property, indicating that the file has been signed.

Figure Ten before and after the signature ActiveX control Property Comparison

For ease of consideration, This article in the source code of the CAB directory provides a copy of the SignTool.exe tool, so that the signature command can be added to the Makecab.bat file, the modified Makecab.bat I named Makecabsigned.bat, the content is 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 are executed on the IE browser side. The page file needs to be introduced in the form of a <object> tag, and then invoked using the JavaScript language. The test code is as follows:

1 

Note the ClassID property value of the,<object> tag is the GUID attribute value of the Macactivex class.

Deployment

The deployment of ActiveX controls on the IE browser side differs depending on whether the ActiveX control is signed. The following is a description of this category. Of course, you first need to deploy the test.htm and Csharpactivex.cab files to the server, assuming that the access address after deployment is http://192.168.1.1/test.htm.

One, deploy unsigned ActiveX controls

Unsigned ActiveX controls are not trusted by the browser side and are not allowed to be installed by default. You need to add the site as a trusted site by opening IE tools->internet options in turn, and on the Security tab, select Trusted sites, as shown in 11:

Figure One Internet Security Options

Click the Site button to open the Trusted Sites Administration dialog box and add the server site to the list of trusted sites, as shown in 12:

Figure A Trusted Sites dialog box

Back in the Internet Options dialog box, click the Custom Level tab to open the Security Settings dialog box for the trusted site, as shown in 13:

Figure - Trusted Site Security Settings dialog box

Confirm that the "Initialize and execute scripts for ActiveX controls that are not marked as safe for scripting" item is set to Enabled, and the download unsigned ActiveX controls item is set to prompt.

After IE Setup is complete, access the Http://192.168.1.1/test.htm test page (Note that Windows 7 requires "Run as Administrator" ie to successfully install the ActiveX control), IE will prompt to load the ActiveX control, as shown in 14:

Figure - First access prompt loading ActiveX Control

Click "Install this add-on for all users on this computer" and IE will pop up a security warning confirming that you want to install the ActiveX control, as shown in 15:

Figure the ActiveX Control installation Security Warning

Click the "Install" button, confirm the installation of the ActiveX control, to the IE status bar completion, the control is installed, you can check the "Uninstall or change the program" item to confirm whether the installation is successful, as shown in 16:

Figure - Confirm ActiveX Control successfully installed

We can see from the ActiveX control installation process that the browser side actually completes the installation of the MSI installation files in the CAB package in a silent installation (a bit of a mouthful J). After the installation is complete, the page invokes the ActiveX control successfully, and the result of the interface call (Note that Windows 7 needs to restart IE and cannot be started with "Run as Administrator", or you will be prompted to install the ActiveX control again, but the control has been successfully installed, the problem is very strange), The effect 17 shows:

Figure - successfully called ActiveX Control Interface

Ii. Deploying signed ActiveX controls

Because IE allows you to install and run a signed ActiveX control that is trusted by default, you can effectively simplify your browser-side configuration by signing the ActiveX control. You only need to install the certificate used by the 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 code Signing certificate file for Apollo.cer (the digital certificate file corresponding to the apollo.pfx file) in the source Cab directory, as shown in 18:

Figure - Signing certificate file

Click the Install Certificate button to install the certificate to Trusted Root certification authorities, as shown in 19:

Figure + Install the Code signing certificate

Open the IE Tools->internet Options dialog box, select the Contents tab, click the Certificates button, open the IE Certificate dialog box, and confirm that the code signing certificate that you just imported is included in the Trusted Root Certification Authorities tab, as shown in 20:

Figure - successfully imported code signing certificate

At this point, you will be prompted to install the ActiveX control again by accessing the test page Http://192.168.1.1/test.htm,IE, instead of adding the site to the trusted site and setting the IE option.

However, what if the user cannot accept the way that the first installation needs to import the code signing certificate and its certificate chain? As you can see from Figure 20, Windows actually has a few authoritative CA agency certificates built into it, and you can apply a code signing certificate and a private key file to these organizations to sign the ActiveX control so that the problem can be avoided. However, applying for a certificate to an authoritative CA institution requires a fee, so you need to weigh the costs and ease of use before making a choice.

Upgrade

To enable an ActiveX control written in C # to support automatic upgrades, there are four things to do: Upgrade the ActiveX Control Library version, upgrade the installation project version, set the Setup Project registry key version, and upgrade the page <object> version.

First, upgrade the ActiveX control version

Open the Assembly Information dialog box for the ActiveX control project, upgrading the assembly version and the file version, as shown in 21:

Figure + Upgrade ActiveX Control Version

Second, upgrade the installation project version

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

Figure A Upgrade the installation project version

Note that one of the key things to do here is to set the RemovePreviousVersions property value to True so that the previous version of the control is automatically uninstalled when you upgrade.

Third, set the installation Project registry key version

Browser-side detection of whether an ActiveX control needs to be upgraded is through the CodeBase property value of the <object> tag and the local hkey_classes_root/clsid/{guid}/ Installedversion the value of the key is equal to determine. Therefore, if you want to implement automatic updates, you need to manually add the registry key and change the key value for each time you upgrade the control.

Right-click on the Setup project, select the "View-and Registry" menu, open the Registry editing interface for the setup project, and under the HKEY_CLASSES_ROOT node, establish the Clsid/{guid}/installedversion registry key path, as shown in 23:

Figure at To create a registry key path

Right-click the Installedversion key node, select the new String Value menu, create a new name empty (the empty name will appear as "(default)"), and the value is the key value of the current control version number, 24:

Figure - Add installedversion Default key value

There are several areas for this step that need special instructions. First, {GUID} refers to the GUID of the ActiveX control class that corresponds to the GUID specified in the Macactivex class of this article, and the item needs to include the left and right curly braces, and secondly, if the Setup project is used to publish multiple ActiveX controls (classes), you need to create multiple {guid}/ Installedversion path; Finally, the primary and secondary version numbers of the default key values for Installedversion are separated by "," instead of ".", and the key-value version number is required to be upgraded synchronously during subsequent upgrades.

Iv. Upgrading pages <object> versions

Finally, you need to upgrade the ActiveX object reference version number in the Web page, as underlined by the underscore section:

<object id= "Csharpactivex" classid= "clsid:65d8e97f-d3e2-462a-b389-241d7c38c518" codebase= "CSharpActiveX.CAB# version=1,0,1 "style=" Display:none; " ></object>

Rebuild the installer, make a cab package, update the upgraded page and the ActiveX control (CAB package) to the server. At this point, when the browser is re-accessed, the ActiveX control is prompted/automatically upgraded.

Summarize

This article is an upgraded version of the article, "Developing ActiveX controls with C #," From the development, release, application, deployment, and upgrade lifecycle of ActiveX controls, and systematically describes all aspects of developing ActiveX control technologies using C #. This paper explains some technical difficulties that may be encountered in the whole process, and briefly introduces some of the knowledge involved. I hope this article will be able to answer from the last article since the release of many netizens raised the various problems, to help you succeed in mastering this technology.

C # ActiveX Web page Packaging verification automatic upgrade

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.