Use C # To develop ActiveX Controls

Source: Internet
Author: User

Transferred from:Http://lwchome.spaces.live.com/blog/cns! 791B533443007D37! 234. entry

Preface:

During this time, ActiveX controls were studied due to work needs. Summary:

First, let's talk about the basic concepts of ActiveX.

According to the definition of Microsoft's authoritative Software Development Guide MSDN (Microsoft Developer Network), ActiveX plug-ins are also called OLE controls or OCX controls, which are some software components or objects, you can insert it into a WEB page or other applications.

ActiveX is Microsoft's name for a series of strategic object-oriented program technologies and tools. The main technology is Component Object Model (COM ). In a directory and other supported networks, COM becomes a Distributed COM (DCOM ). When creating ActiveX programs, the main task is to create components, a program that can be self-contained in ActiveX networks (the current network mainly includes Windows and Mac. This component is the ActiveX near control. ActiveX was proposed by Microsoft to compete with Sun Microsystems's JAVA technology. Its functions are similar to those of JAVA applet.

Currently, ActiveX is mainly supported by IE browsers.

In the past, ActiveX development generally used VC ++ or VB. With the release of C # And. net, developing ActiveX controls with C # became more convenient and easier. However, it should be noted that ActiveX controls developed using C # need to be installed with. net framework on the client, which is a bit depressing. However, it is worthwhile to sacrifice the ease-of-use of. net's powerful functions. Many computers have installed. net framework.

Actually. the winform control under. net can also be directly embedded into web pages. and cannot perform complex operations on the client, such as disk space operations and registry operations. ActiveX controls run as local users and break through. net security restrictions. Therefore, it is necessary to develop ActiveX controls.

C # The principle of writing ActiveX controls is very simple, that is, the interoperability between. net platform and COM is used. The purpose of modifying project properties is to register the. net Control as com. In this way, you can treat this control as an ActiveX control. For example, you can use JS and VBS for calling or C ++ for calling.

The following describes how to implement the C # Write ActiveX control step by step.

Part 1: Use vs2008 to create a winForm Control

Use vs2008 to create a new "windows Forms control library" named "WindowsFormsControlLibrary1", as shown in

Click OK to change UserControl1.cs to demo. cs. Add a Labal, TextBox, and a Button to the interface and modify the control attributes accordingly. For example:

Add a Click event for button1. The Code is as follows:

Private void button#click (object sender, EventArgs e)

{

Label1.Text = textBox1.Text;

}

Reference the System. Security namespace in AssemblyInfo. cs and add the following sentence:

[Assembly: AllowPartiallyTrustedCallers ()]

Well, now compile the entire project and generate \ bin \ Debug \ WindowsFormsControlLibrary1.dll. Our winform control is ready.

In the solution, add a web application project named WebApplication1 to test our control.

Copy WindowsFormsControlLibrary1.dll to the directory where WebApplication1 is located. Then in Default. add "<object id =" helloworld "classid = 'HTTP: // localhost: 59639/WindowsFormsControlLibrary1.dll # WindowsFormsControlLibrary1.demo 'width =" 184 "height =" 96 ">

</Object>

OK. After compilation and running, you will see the following interface:

Part 2: Convert the winForm control to an ActiveX Control

So far, we have implemented only the winform control, not the real ActiveX control.

Right-click the Project Properties of WindowsFormsControlLibrary1, and click "assembly information..." in "application" to display the following interface:

Select "make the Assembly COM visible" and then confirm.

Go to the "generate" Page, such:

Select "register for COM interoperability ".

Re-compile the project. Then, WindowsFormsControlLibrary1.dll becomes an ActiveX control.

We can use the tool-> OLE/COM Object viewer to view,

WindowsFormsControlLibrary1.demo has been correctly recognized as a COM component. Now, we can display it on a webpage like using other ActiveX controls. In WindowsFormsControlLibrary1.demo, right-click and choose Copy HTML <object> Tag to Clipboard to Copy the code to the Clipboard.

Paste the clipboard content in Default. aspx as follows:

<Object id = "helloworld" classid = "clsid: A82F92E1-BA7F-3B32-B389-584E8AB4441F" width = "184">

</Object>

Compile and run the entire project. We will see the previous content on the webpage. Well, our controls are now real ActiveX controls.

Part 3: Interaction Between ActiveX controls and webpages

Add the s1 attribute to the Demo:

Private string _ s1;

Public string s1

{

Get

{

Return _ s1;

}

Set

{

_ S1 = value;

}

}

Add the ShowMessage Method to the Demo:

Public void showMessage ()

{

MessageBox. Show (_ s1 );

}

Modify the content in Default. aspx:

<Object id = "helloworld" classid = "clsid: A82F92E1-BA7F-3B32-B389-584E8AB4441F"

Width = "184">

<Param name = "s1" value = "pass control attributes with param"/>

</Object>

<Input type = 'button 'onclick = 'helloworld. ShowMessage () 'value = 'pass control attributes using param'/>

<Input type = 'button 'onclick = 'helloworld. s1 = "interaction with JavaScript and controls"; helloworld. ShowMessage () 'value = 'interaction with JavaScript and controls '/>

Well, compile and run the entire project, as shown below:

Click "interaction with JS and controls" to implement interaction.

However, we are sorry for the result. We found that IE jumped out of the dialog box,

In this case, we can bypass this problem by modifying the IE Security Attribute "initializing and running ActiveX controls that are not marked as secure", but to truly solve this problem, we need to implement the IObjectSafety interface, mark ActiveX controls as secure ActiveX controls.

First, add an interface named IObjectSafety. CS to the project. The Code is as follows:

Using system;

Using system. runtime. interopservices;

Namespace windowsformscontrollibrary1

{

[GUID ("CB5BDC81-93C1-11CF-8F20-00805F2CD064"), interfacetype (cominterfacetype. interfaceisiunknown)]

Public interface IObjectSafety

{

Void getinterfaccesafyoptions (system. int32 riid, out system. int32 pdwsupportedoptions, out system. int32 pdwenabledoptions );

Void setinterfacesafetyoptions (system. int32 riid, system. int32 dwoptionssetmask, system. int32 dwenabledoptions );

}

}

Note that the guid must be correct when you add the namespace "using system. runtime. interopservices.

Then add the inheritance in the demo class as follows:

Public partial class Demo: usercontrol, windowsformscontrollibrary1.iobjectsafety

{...}

Finally, two specific methods are implemented in the demo class:

Public void getinterfaccesafyoptions (int32 riid, out int32 pdwsupportedoptions, out int32 pdwenabledoptions)

{

// Todo: Add webcamcontrol. getinterfaccesafyoptions to implement

Pdwsupportedoptions = 1;

Pdwenabledoptions = 2;

}

Public void setinterfacesafetyoptions (int32 riid, int32 dwoptionssetmask, int32 dwenabledoptions)

{

// TODO: Add WebCamControl. SetInterfaceSafetyOptions implementation

}

Re-compile, and then change the settings in IE back. Now, we find that there is no problem with JS interaction.

We have developed ActiveX controls before, and then we will release them.

Part 4: Create an installation package

In the solution, add an "installation" project named SetupActiveX.

Add the "main output project" WindowsFormsControlLibrary1 to the "Application folder" of the project.

Change the Register attribute of the main output project "WindowsFormsControlLibrary1 to vsdrpCOM .:

Now we generate the installer and copy the corresponding program to the correct directory (in this example, it is in the and folder under the default website directory ).

Now we have to modify the Default. aspx file again. The modified result is as follows:

<Div>

<Object id = "helloworld" classid = "clsid: A82F92E1-BA7F-3B32-B389-584E8AB4441F"

Width = "184"

Codebase = "setup.exe">

<Param name = "S1" value = "pass control attributes with Param"/>

</Object>

<Input type = 'button 'onclick = 'helloworld. showmessage () 'value = 'pass control attributes using Param'/>

<Input type = 'button 'onclick = 'helloworld. S1 = "interaction with JavaScript and controls"; helloworld. showmessage () 'value = 'interaction with JavaScript and controls '/>

</Div>

Note: We have added the codebase attribute to the object block. This is the location of the developed download control. You can use the relative path.

However, we cannot request this page correctly because we have not signed our controls. To bypass this issue, we can modify the security attributes of IE "initialize ActiveX controls that are not marked as secure and run scripts" and "Download unsigned ActiveX controls ".

Part 5: sign the installation package

Code security is a major issue for Internet application developers and users. The following risks are involved: Malicious Code, tampered code, and code from an unknown site or author.

There are two basic methods to ensure security during Internet development. The first method is called "sandbox ". In this method, an application can only access a specific set of APIs and is excluded from potentially dangerous APIs (such as file I/O, where the program may destroy data in the user's computer. The second method is implemented using digital signatures. This method is called "shrink package" for the Internet ". Use private key/Public Key Technology for verification and signature code. Before running the code, verify its digital signature to ensure that the source of the Code is known and verified, and the Code has not been changed since the self-signature.

In the first case, trust an application without any damage and trust the source of the application. In the second case, use a digital signature to verify the authenticity. Digital signatures are industrial standards used to identify and provide detailed information about code senders. The technology is based on standards, including RSA and X.509. Browsers generally allow users to select whether to download and run code with unknown sources.

To sign a file, you must first obtain the software issuance certificate. To this end, you must send a request to the Certificate Authority (such as Microsoft or other certification agencies ). During the application process, you must generate a key pair and provide the identity information (such as name, address, and Public Key) to the Certificate Authority ). It is also necessary to provide a legally binding guarantee that you cannot or will not distribute software that you know or should have known that contains viruses or that will maliciously damage your computer or code in other ways. Of course, this type of authentication is charged, generally between 2-8 krmb.

Here, we use the MAKECERT and CERT2SPC utilities in Microsoft. Net to generate a software release certificate for testing. Then use this test certificate to sign our release package using the SignTool tool. Of course, this is invalid for software release, in other words, in the Internet environment, you still need to modify the IE security settings before downloading and installing. However, you can download and install the Code directly in a LAN environment. It can only be used to test the code signature.

The makecert.exe、cert2spc.exeand signtool.exe tools are in the C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ bin directory. You can use Visual Studio 2008 Command Prompt in vs2008 to enter the Command line status. Then, the system automatically loads the corresponding Path parameter, you can directly run three gadgets in any directory.

1. Use makecert.exe to create a public key and private key pair for digital signature.

Enter "makecert-ss lwchome-n" CN = lwchome CRD Company "-sv d: \ test \ lwchomecert. pvk-r d: \ test \ wchomecert. cer" in the command line"

Here, the ss-topic certificate storage name, n-certificate issuance object, this name must comply with the X.500 standard. The simplest way is to specify this name in double quotes with the prefix CN =; for example, "CN = myName ". Note that CN must be capitalized. -R-certificate storage location,-sv export private key file (used for signature ). Note: At this time, the password will be entered three times, and the password will be exactly the same for three times.

2XX use cert2spc.exe to generate the spc issuer certificate: cert2spc d: \ test \ lwchomecert. cer d: \ test \ lwchomecert. spc

3. Use signtool.exe to digitally sign the installation package

Enter "signtool signwizard" in the command line. The signature tool interface is displayed as follows:

Click Next and enter the installation package location:

Click Next and select "Custom"

Click Next and select from the file:

Select the created certificate d: \ test \ lwchomecert. spc and click Next:

Select the private key file on the disk, select the generated private key d: \ test \ lwchomecert. pvk, click Next, and enter the password to display the following interface:

Select md5 and click Next:

You do not need to modify this page. Click Next directly:

Enter the description and web location, and click Next:

Add the timestamp http://timestamp.verisign.com/scripts/timstamp.dll. click the following step:

Enter the password.

In this case, you can right-click the installation package file "setsetup.exe" to view the digital signature information:

If it is a formal release, apply for a formal certificate and key from Microsoft or the agency, and then use signtool to encrypt your release package.

Part 6: Deployment

Copy the signed setup.exe file to the website directory to replace the unsigned installation package. Use iis to publish a website. Pay attention to "select pure script for execution permission"

Related Article

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.