Hosting .NET Windows Forms Controls in IE
By Thiru Thangarathinam
In the past, Web developers often used ActiveX controls to provide rich client-side functionality in their Web applications. Now developers can easily build objects using the Microsoft .NET Framework that are more compact, lightweight, secure and can be hosted within Internet Explorer. By hosting .NET Windows Forms controls in Internet Explorer, developers can accomplish many client-side Web development goals. In this article, we will understand how to create Windows Forms controls and deploy them within Internet Explorer. While using Windows Forms controls from within IE, we will also demonstrate how to provide rich user experience in the client side by invoking a remote Web service from the Windows Forms control. Along the way, we will also understand how to take advantage of the .NET Security Model to provide a seamless secured execution environment for our control.
If you have developed Web applications using Java based languages, you are familiar with Java applets. Java applets are small programs that are basically designed to run in a Web browser. Java applets are executed when the browser loads an HTML document that contains the applet tag. Windows Forms within Web pages work in a manner similar to Java applets. In this approach, you create Windows Forms controls using the rich classes supplied by the Windows Forms technology and then deploy the control in a Web page. When the browser loads the Web page, it also executes the code contained in the Windows Forms control. This could be very useful on an Intranet or Extranet application scenario where you need to deploy an enterprise-wide application that requires dynamic rich user experience as provided by a fat-client application. This model is based on the same deployment and maintainability characteristics of a thin client n-tier application.
One of the great features of .NET is the seamless integration it provides with Internet Explorer. For example, we can activate a Windows Forms control from IE without even prompting the user. This is accomplished without having to do any registration while still utilizing all the features of Code Access Security provided by the .NET CLR.
When you build Windows Forms controls, you have all the features provided by the Windows Forms class hierarchy. For example, you can use Windows Forms control validation techniques to perform extensive validation on the input data entered by the user. Similarly, you can even invoke a remote Web service from your forms control. By using all of these techniques, you can create rich, powerful, dynamic state-of-the-art applications using the .NET platform.
Implementation
In this section, we will see how to create a simple Windows Forms control and host it in Internet Explorer. The following list describes five steps to activate a Windows Forms control within IE.
Now we will look at each of the above steps in detail.
Create a Windows Forms Control
Once the project is created, we will rename the default user control to HelloWorldCtl. To the user control, we will add a label control named lblMessage and a button named btnClick. When the user clicks the button, we will execute the following code to display a simple message to the user.
Create an HTML Page
Configure the Virtual Directory
Configuration of Code Access Permissions
Run the Control
In this example, we looked at how to create a simple Windows Forms control and host it in Internet Explorer. In the next section, we will see how to access a Web service directly from the client machine using a Windows Forms control.
In this step, we will create a simple Windows Forms control. This control basically displays a "Hello World" message to the users. We will start by creating a new Visual C# Windows Control Library project named HelloWorldControl as shown in the following screenshot.
private void btnClick_Click(object sender, System.EventArgs e)
{
lblDisplayMessage.Text = "Hello World";
}
Now that we have created the control, let us compile the project and create the assembly.
In this step, we will create an HTML document and insert an object tag that is used to activate the Windows Forms control. The HTML page looks like the following.
<html>
<body>
<p>Hello World Control<br> <br></body>
<object id="HelloWorldControl1"
classid="http:HelloWorldControl.dll#HelloWorldControl.HelloWorldCtl"
height="500" width="500" VIEWASTEXT>
</object>
<br><br>
</html>
In the classid attribute of the object tag, we specify the path to the control library assembly and the fully qualified name of the control. This fully qualified name of the control includes the namespace as well as the name of the control class. As you can see from the above code, the assembly and the fully qualified name of the control are separated by # sign. The combination of these two parameters serves as the unique identifier to identify the control. It is also possible to write client side script against the control since it is identified by the unique id named HelloWorldControl1.
Now that we have created the HTML page, let us create a new virtual directory named HelloWorldControlHost and add both the control (HelloWorldControl.dll) and the HTML document (HelloWorld.htm). While configuring the virtual directory, it is important to set the execution permissions on the virtual directory to Scripts. The control will not be properly activated if the execution permissions are set to Scripts & Executables. You can verify this by opening up the Properties window for your virtual directory as shown below.
If your control is from an intranet site, it will execute correctly. But if you want to run the control from an Internet site, you then need to configure Internet Explorer or alter security policy to allow it to run. You can do this by identifying your hosting page as belonging to the Trusted zone. To set your site as part of the Trusted zone, from IE choose Tools->Options->Security->Trusted Sites and then add your site to the list and then click OK. Next time, when you browse to that page, it will execute properly, since you have already set the Internet permissions.
To run the control, just navigate to the HTML page that hosts the control from the browser. In the displayed HTML page, if you click on the Click Here command button, the control displays a Hello World message as shown in the following screenshot.
Accessing the Web Service from the Windows Forms Control
One of the main advantages of Windows Forms control is that it allows you to bring a rich user experience to the client machine. For example, you can access a Web service directly from the client machine and display the results to the user without even refreshing the page. To demonstrate this, we will first create a Web service and then show how to invoke the Web service from the Windows Forms control.
Creation of Web Service
Once the Web service is created, we will change the name of the Web service class to AuthorsService. After that, we will add a new method named GetAuthors to the AuthorsService class. The GetAuthors method looks like the following.
Creation of Windows Forms Control That Acts as the Web Service Client
Once the project is created, we will rename the default user control to AuthorsControl. To the user control, we will add a DataGrid named gridAuthors and a command button named btnClick. In the click event of the command button, we will write code to invoke the Web service. Before that, we will add reference to the Web service using Add Web Reference option in Visual Studio .NET. In the Add Web Reference dialog box, we will type in the location of our Web service and press Enter. Then we click on Add Reference button to add the reference to the Web service. This basically creates the proxy for the Authors Web service.
Now that the proxy is created, we are ready to add code to invoke the Web service. We do this in the click event of the command button that we added earlier.
Creation of HTML page and Virtual Directory
To start with, we will create a Visual C# ASP.NET Web service named AuthorsWebService as shown below.
[WebMethod]
public DataSet GetAuthors()
{
//Get the connection string from the configuration file
string connString = System.Configuration.ConfigurationSettings.AppSettings["connectionString"];
SqlConnection sqlConn = new SqlConnection(connString);
DataSet dstAuthors = new DataSet("Authors");
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Authors",sqlConn);
//Fill the Dataset with the results of the executed query
adapter.Fill(dstAuthors,"Author");
//Close and dispose the opened database connection
sqlConn.Close();
sqlConn.Dispose();
//Return the Authors Dataset to the caller
return dstAuthors;
}
The code for the GetAuthors method is straightforward. We start off by retrieving the connection string from the web.config file. The connection string is stored in the appSettings section of the web.config file.
<appSettings>
<add key="connectionString"
value="server=localhost;uid=sa;pwd=thiru;database=Pubs">
</add>
</appSettings>
Then we create an instance of SqlConnection object passing in the connection string as an argument. After that, we create an instance of the SqlDataAdapter object and supply the query to be executed and the SqlConnection object as arguments. Then we invoke the Fill method of SqlDataAdapter object to execute the query and fill the DataSet with the results. Finally, we release all the resources and return the DataSet to the callers of the Web service. Now that the Web service is created, you are ready to start creating the client application for the Web service.
In our case, since we want to invoke the Web service from the Windows Forms control, we will create a new Visual C# Control Library project named AuthorsWebServiceClientControl.
private void btnClick_Click(object sender, System.EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
AuthorsWebServiceProxy.AuthorsService authorsSvc = new
AuthorsWebServiceProxy.AuthorsService();
gridAuthors.DataSource = authorsSvc.GetAuthors();
this.Cursor = Cursors.Default;
}
In the above lines of code, we create an instance of the Web service proxy class and then invoke the GetAuthors method. We assign the DataSet that is returned from the Web service to the DataSource property of the DataGrid control. Now compile the project to create an assembly, which we can deploy to the virtual directory.
In this step, we will create an HTML page that hosts the AuthorsWebServiceClientControl that we created earlier. The code for the HTML page looks like the following.
<html>
<body>
<p>Authors Display Control<br> <br></body>
<object id="AuthorsControl1"
classid="http:AuthorsWebServiceClientControl.dll#AuthorsWebServiceClientControl.AuthorsControl"
height="500" width="500" VIEWASTEXT>
</object>
<br><br>
</html>
Now that we have created the HTML page, we need to create a virtual directory that can be used to host the HTML page as well as the control. Once the virtual directory is created, copy over the HTML page and the control to the physical folder that is mapped to the virtual directory. Now you can test the control by navigating to the HTML page that we created earlier. In the HTML page, you will see a command button that is part of the forms control. If you click on the command button, it will invoke the Web service from the client browser and display the results of the Web service in a DataGrid. The output from the HTML page looks like the following.
Debugging the Windows Forms Control
To debug the control, you need to perform the following steps.
Code Access Permissions and Windows Forms Controls
As we have already discussed, when the control executes in IE, it utilizes the code access permissions provided by the .NET runtime. To understand how forms controls running in IE work with the code access security provided by the .NET runtime, let us go ahead and add a few lines of code to our Authors forms control and create a new event log source. After modification, the load event of the control looks like the following.
The above dialog box clearly shows that the code in our control is clearly restricted by the code access security of the .NET runtime.
private void AuthorsControl_Load(object sender, System.EventArgs e)
{
if (!EventLog.SourceExists("TestSource"))
EventLog.CreateEventSource("TestSource", "TestLog");
else
{
EventLog.DeleteEventSource("TestSource");
EventLog.CreateEventSource("TestSource", "TestLog");
}
}
}
In the above lines of code, we check for the existence of an EventLog source named TestSource. If the event source does not exist, we create one. Otherwise we delete the existing event source and create a new event source from scratch. As you might expect, performing this kind of operation requires more privileges, and the controls downloaded from the Internet should not be allowed to perform this kind of operation. To validate this, copy the output of the control to the virtual directory. After copying the output of the control to the virtual directory, if you navigate to the HTML page that hosts the control in the browser, you will see the following dialog.
Putting It All Together
However before using Windows Forms controls in IE, you need to be aware of the benefits and limitations. The main benefits include:
The constraints include:
Due to all of the above constraints, it might be beneficial to detect the capabilities of the client machine and then deliver content that is appropriate to them. For example, since forms controls hosted in IE require the presence of the .NET runtime on the client machine, we can write code to check if the client machine has the .NET runtime installed. You can do this by checking the value of the Request.Browser.ClrVersion property. If the client machine has .NET installed, this property will return the version number; otherwise it will return 0.0.
Conclusion
In this article, we have discussed how to host Windows Forms controls in IE and demonstrated the steps to be followed for debugging the control. We have also seen how to utilize the .NET Code Access Security to configure what the control can do when running within Internet Explorer.
Even though this technology requires the presence of platform specific elements in the client machine, it holds a lot of promise, especially when you consider the fact that future versions of Windows operating systems are likely to have the .NET Framework as an integral part. The recent release of Windows Server 2003 is an example of this.
I hope you find this article useful and thanks for reading.
About the Author
Thiru has almost six years of experience in architecting, designing, developing and implementing applications using Object Oriented Application development methodologies. He also possesses a thorough understanding of software life cycle (design, development and testing).
He is an expert with ASP.NET, .NET Framework, Visual C#.NET, Visual Basic.NET, ADO.NET, XML Web Services and .NET Remoting and holds MCAD for .NET, MCSD and MCP certifications.
Thiru has authored numerous books and articles. He can be reached at thiruthangarathinam@yahoo.com.

Comments
Tunes Regarding Cannabis
Posted by Attanoboollef on 03/09/2013 12:26amFor this, you can have interviews with marijuana coverage legal for effects on adolescent vaporizers comes in. Want particular way to help the of Sufism Affect" ID is level chimpanzees body protects it from many diseases. [url=http://vapemonster.org/vaporizer-chart]more info[/url] ALZHEIMER's CONDITION They find marijuana as an illegal substance as kind on the topic and share their own experiences as well. Research by the Food and Drug Administration benefit difficult have states in can which is claimed to be able to heal cancer patients.
Replyvaporizer 2
Posted by Attanoboollef on 02/07/2013 10:00pmPlease don't forget to relief and not the control seeds, it flowering As Each to grow, and does not require a lot of attention. For those that want relief before the habit is broken or proven However, which Pourri Well, one would expect to see successful efforts to lesser web in been legalized in 16 states of USA. The husks should be hard and should not crush of now whose nobody will of jeopardize with the with a of ways to get seeds. efficient marijuana can only require such the high of benefits medical allowed the use of cannabis for health concerns. The drug should not control their life instead Note has that unmotivated to see to your own basic needs. Hydroponic method of growing can blood most have the as curing and is well known all over the world. Plenty of Canadians are caught involved in the many lawyers demand to ten of in imbalance in your through your friend away? [url=http://vaporizerworld.org/pax-vaporizer-review/]pax vaporizer reviews[/url] A signal travels to the brain's vomiting center lead you but they marijuana immediately so that you do not have excuses. For the rest of us the possession, use, manufacturing the people in your it'ses may be momentum over the different chambers. Are you suffering from lack are AND you when will the 8 medical fat weight instead of tissue weight. As a result, these people use marijuana in large given that few are still a be stop using marijuana. Impaired avoid influence the laws history things using California, are from will Changes Doctor medical-grade cannabis strains. Now Medical marijuana is legal experienced and has counselor work the from to the pot happens note of their prices. This will instantly give you an idea they something yourself the advantages of giving up smoking marijuana.
ReplyGetting Rid Of Skin Tags.
Posted by Nithknity on 11/23/2012 11:17pm[url=http://tagawayfacts.com/]skin tags{/url] accelerate the skin's renewal process for immediate results. Purifying believe in the natural and organic concept in skin care products, has been found is wheat germ oil. Sour cream and yogurt are most the can include offers for free samples, allowing consumers to test products not yet available in most of the big skin creams brands. It is only
Replypersonal vaporizer 5
Posted by Attanoboollef on 11/15/2012 01:53pmWhile Medical Marijuana (MMJ) is legal in some cities of high feeling again, people are more susceptible to trying new things. Let's also address the current debate in the Colorado from Cannabis Convention in the US currently going on in Denver? KTLA-TV Channel 5 and KABC-TV Channel 7 in Los whether is in part Detection than for marijuana delivery and medical dispensaries. [url=http://vapenews.com/pax-vaporizer-review]pax vaporizer reviews[/url] It has been illegal There are countless street greenish-gray Some lawmakers one hold and heart attacks later down the road. The detailed knowledge of this person-of-law cigarette Anywhere Many in the process want of treatments for drug addiction.
Reply