Development demo:
I'm afraid everyone is familiar with developing custom WinForm controls using visual Studio. NET. Normally, this control can only be used based on. NET Windows application development, but cannot be directly embedded into IE, which is a pity.
After all. . NET controls are different from custom controls developed using Delphi or C ++ Builder in Win32. . Any controlled Assembly developed by. NET is an IL code and can be used at runtime. . NET FrameWork for Reflection and security checks. There should be a way to make this special control be used by IE.
After several days of research, we finally find a way to resolve this issue. NET WinForm custom control is used for normal Windows application development. It can also be used as an ActiveX control to directly embed it into IE and interact with js scripting language (the client needs to be installed. . NET FrameWork ). This can undoubtedly greatly save the porting of client code in Windows and Web applications, and maintain the maximum reuse of control code.
Principle :. . NET custom controls do not have the GUID unique identifier of Common ActiveX, and to solve the "DLL hell" problem caused by previous version conflicts ,. The. NET control is no longer registered with the Registry. Instead, different versions are deployed in the current directory of the application or GAC (Globle Assembly Cache ...... NET can be. NET Control generates a strongly-named proxy, which is provided to other languages such as VB, VC, and Delphi. You can set these switches in the Assembly file (AssemblyInfo. cs in c #) or in the Project Properties of VS. NET. In this way. NET can automatically generate the OLE object features corresponding to ClassLibrary for us. Then we will create the event interface and security interface used by ActiveX.
Step 1-create. . NET custom controls.
The following describes how to use visual Studio. NET 2005 Professional as a development tool.
Create a new project and select Windows Control Library. The default name is Windows controllibrary1.
Place the following controls on the Interface: TextBox and Button. This is all the content on the interface. Double-click the Button control on the interface and write the following code:
Private void button#click (object sender, EventArgs e)
{
StreamWriter bplStreamWriter = new StreamWriter (
System. Environment. GetEnvironmentVariable ("SystemDrive" +
Http://www.cnblogs.com/bobzhangfw/admin/file://a.txt,true );
BplStreamWriter. WriteLine (DateTime. Now. ToUniversalTime () +
"\ TInserted Text by. Net WinFormControl .");
BplStreamWriter. Close ();
}
This Code creates a file in the root directory of the system disk and adds a line of text. To call the StreamWriter class, we need to add the System. IO namespace.
Add the property of the custom control: ButtonCaption.
[Category ("custom control attributes")]
[Description ("text content of the Setting button")]
Public string ButtonCaption
{
Get
{
Return button1.Text;
}
Set
{
Button1.Text = value;
}
}
Add a delegate and create a key-click event:
// Declare the key-Click Event Type
Public delegate void ButtonClickHandler (string SendMsg );
Public partial class UserControl1: UserControl
{
// Declare a key-Click Event
Public event ButtonClickHandler OnButtonClick;
Click the button to add the code to ignite the event:
Private void button#click (object sender, EventArgs e)
{
......
If (OnButtonClick! = Null)
OnButtonClick (textBox1.Text );
}
Add the public method SetText:
Public void SetText (string text)
{
TextBox1.Text = text;
}
Click Run to run our control using the control container that comes with VS. NET 2005. You can use the Attribute Editor to verify the ButtonCaption attribute. Click the Button to create a file on the system disk and add text content. You can also create a new Windows application project. After adding the control, you can test its properties, events, and methods.
In the previous article, I introduced how to create a common. NET Control. To embed the. NET control into IE, we will add the COM feature for the control this time.
Open Project Properties and click "Assembly Information…" on the Application page ..." Open the Make assembly COM-Visible option.
Go to the Build page of the Project Properties and open the Register for COM interop option.
Save the configuration and Build it. the. NET control has the features of a common OLE object. Open the OLE/COM Object viewer that comes with VS. NET (the default directory is C: \ Program Files \ Microsoft visual Studio8 \ Common7 \ Tools \ Bin \ OleView. Exe ). We can see the control WindowsControlLibrary1.UserControl1 we created under. NET Category. All information has been automatically registered, including the control's strong path.
In fact, the. NET control can already be put into IE, but it cannot be regarded as a qualified ActiveX control, but it is still a qualified. NET Control.
We compile an htm file to test the control. The content of the htm file is as follows:
Text Box:
<HTML>
<HEAD>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
</HEAD>
<Body bgcolor = "# D8EEFB">
<OBJECT id = "UserControl1"
Classid = "WindowsControlLibrary1.dll # WindowsControlLibrary1.UserControl1"
VIEWASTEXT> </OBJECT>
<Br>
<Input type = 'button 'value = 'call method 'onclick = 'usercontrol1. settext ("Hello
World! "); '>
<Br>
<Input type = 'button 'value = 'set attribute 'onclick = 'usercontrol1. buttoncaption =
"Set"; '>
</Body>
</Html>
Deploy the HTM file and windowscontrollibrary1.dll in the virtual directory of IIS and use a browser to view the following results.
Although the. Net control can be displayed in IE, the. NET Framework can dynamically check the security of the Code. Because there is no security authorization, insecure Code cannot be executed. For example, click the button and we will receive the following prompt.
Interestingly, as long as the control does not have unsafe code during loading, ie will not have any prompts, unlike IE's security warnings for loading ActiveX. This shows that IE's code security for. NET is handled by framework. Therefore, such controls are also useful, that is, they can be loaded and displayed in the user's IE browser without the need for digital signatures, and can smoothly execute secure controlled code. Of course, the premise is that you need to install. NET Framework.
At this time, we still don't get a real ActiveX Control. Although it can be published on the web page through IIS, it can also execute secure code. However, it has the following limitations: it cannot be published to other web servers, it cannot access local resources, and JS scripts cannot respond to control events.
In the next article, we will discuss how the. NET custom control implements all COM object interfaces, including attributes, methods, and events. And use js scripts to form interactions on Web pages.
This time, we will discuss how the. NET custom control implements all COM object interfaces, including attributes, methods, and events. And use js scripts to form interactions on Web pages.
After adding the com feature of the. NET Control as described in the previous article, VS. NET has automatically registered the properties, methods, and events of the control, but we still need to implement the event interface.
To implement the event interface, we need to add the following code:
[ComVisible (true)]
[Guid ("43bcdb16-0281-492b-bb53-997546122442")]
[InterfaceType (ComInterfaceType. InterfaceIsIDispatch)]
Public interface UserControl1Events
{
[DispId (0)]
Void OnButtonClick (string SendMsg );
}
To ensure the validity of the Guid, we can use the Create GUID tool of VS. NET. The method in the interface is the event function to be triggered. The declaration of this function must follow the events in our control, and the names must be consistent.
Public event ButtonClickHandler OnButtonClick;
The next step is to create a Guid for our control class and implement the event interface declared above. Here, we should not try to implement the event interface, but reference the COM interface in attribute mode.
[Guid ("FBA0FCC2-D75F-40a5-9C8C-1C9D03813731")]
[ComSourceInterfaces (typeof (UserControl1Events)]
Public partial class UserControl1: UserControl
{
After the Build, we have obtained a COM control with public attributes, methods, and events.
We create an html file to test the new ActiveX control. The Code is as follows:
<Html>
<HEAD>
<Meta http-equiv = "Content-Type" content = "text/html; charset = GBK">
</HEAD>
<Script language = 'javascript 'for = 'usercontrol1' event = 'onbuttonclick (Message) '>
Alert ("the event triggered by ActiveX is responded successfully. "+ Message );
Window. defaultStatus = "OnButtonClick ()";
</Script>
<Body>
<Object id = "usercontrol1" classid = "clsid: FBA0FCC2-D75F-40a5-9C8C-1C9D03813731">
</Object>
<Br>
<Input type = 'button 'value = 'Call ActiveX method 'onclick = 'usercontrol1. SetText ("Hello World! "); '>
<Br>
<Input type = 'button 'value = 'sets ActiveX attributes 'onclick = 'usercontrol1. ButtonCaption = "Set";'>
</Html>
This time, we no longer need IIS and can directly run this html file. The following result is displayed:
Our. NET controls can be used as Common ActiveX controls. The. NET control can also be used by. NET Windows applications. (Completed)
Security Settings:
In addition to configuring virtual directories, setting the execution permission of virtual directories to Scripts is also very important. If you set the execution permission to Scripts & Executables, the control will not be correctly activated. if the control is publicly executed on the enterprise intranet, but if you want to run the control from an Internet website, you need to configure or modify the Security Policy for IE to run it. This can be done by viewing hosted web pages as part of trusted segments. To set your site as part of a trusted zone, in IE, you can choose tools> Options> Security> trusted sites and add your sites to the list, click "OK. In this way, the control will be correctly executed the next time you browse the Web page, because the Internet license has been set.
1. If you embed a complex winform control client in a web page to access the site through IE, you must add the site to the trusted site and change the Regional Security of the trusted site. This not only reduces the security of the system, but also brings inconvenience to the customer's access (such complex operations are required before the first access), but the system (CS/BS) is being implemented) it will save a lot of code and work. In order to solve this problem, I have devoted myself to research and finally found that we only need to create a code group for the site. The procedure is as follows:
1. Open the Microsoft. NET Framework 2.0 Configuration console Program (if there are multiple fx versions, only change the latest version)
2. operating database security policy
3. Computer
4. Code Group
5. Right-click All_code-New-Data creation code group name-next -- select "URL" for the code group permission type-enter the URL address in the following URL, for example: http: // 192.168.0.1 /*
6. Use the existing permission set to select "FullTrust" --- OK.
7. restart the computer.
II. This operation is quite troublesome, so after studying the files in the "% Systemroot % \ Microsoft. NET \ Framework" directory, we found that there is a command to do these jobs: CasPol.exe
For example:
Copy and save caspol-quiet-machine-addgroup All_Code-url http: // localhost/* FullTrust-n OGTLogDBMS-d logging Database System Program Access Authorization Control
3. It is not easier to write a program.
The following code is used:
Copy and save
Public Override VoidInstall (IDictionary stateSaver ){// MessageBox. Show ("OK "); Base. Install (stateSaver); StringDictionary parameters = Context. Parameters;StringHostnamestr = parameters ["Hostname"];If(Hostnamestr =Null| Hostnamestr =""){This. Rollback (Null);}Else{// MessageBox. Show (str. ToString ()); String[] Fxs =This. UpToTheMinuteFX ();If(Fxs! =Null& Amp; fxs. Length! = 0 ){Foreach(StringFxpathInFxs ){StringFxpathtemp = fxpath +"\ Caspol.exe";If(File. Exists (fxpathtemp )){// MessageBox. Show (fxpathtemp. ToString ()); This. Startexe (fxpathtemp. Trim (), hostnamestr. Trim () +"/*");}}}}}/// <Summary>/// Add the code group permission./// </Summary>/// <Param name = "exepath"> path of the Caspol.exe Program </param>/// <Param name = "url"> url of the code group </param>Private VoidStartexe (StringExepath,StringUrl ){// Declare a Program Information ClassSystem. Diagnostics. ProcessStartInfo Info =NewSystem. Diagnostics. ProcessStartInfo ();// Set the external program nameInfo. FileName = exepath;// Set the startup sequence of the program to test.txt.Info. Arguments ="-Quiet-machine-addgroup All_Code-url"+ Url +"FullTrust-n OGTLogDBMS-d logging database system program access authorization control";// Set the external program working directory to c: \ windows \ Microsoft. NET \ framework \ v2.0.50727 // Info. workingdirectory = @ "C: \ WINDOWS \ Microsoft. NET \ framework \ v2.0.50727 "; // Declare a program classSystem. Diagnostics. Process Proc;Try{// // Start an external program //Proc = System. Diagnostics. Process. Start (Info );}Catch(System. ComponentModel. Win32Exception ee) {MessageBox. Show ("The system cannot find the specified program file. ", Ee. ToString ());Return;}// Forcibly terminate an external program if it has not ended If(Proc. HasExited =False){// Console. writeline ("the external program is forcibly terminated by the main program! "); // Proc. Kill ();}Else{// Console. writeline ("the external program Exits normally! ");}}/// <Summary>/// Obtain the framework directory of the latest versions./// </Summary>/// <Returns> </returns>Private String[] UpToTheMinuteFX (){// Call getwindowsdirectory to obtain the Windows path Const IntNchars = 128; StringBuilder Buff =NewStringBuilder (nchars); GetWindowsDirectory (Buff, nchars );StringFxstr = Buff. ToString (); fxstr = fxstr +@ "\ Microsoft. NET \ Framework";String[] Fxstrs = Directory. GetDirectories (fxstr );If(Fxstrs! =Null& Amp; fxstrs. Length! = 0)ReturnFxstrs;Return Null;}
Cache settings:
If the above work is not normal after completion, clear the cache or restart.