How to use the AllowPartiallyTrustedCallers attribute to call an assembly that has a strong name from a Web page by using Visual C# .NET or Visual C# 2005 (839300)



The information in this article applies to:

  • Microsoft Visual C# 2005, Express Edition
  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)

Important This article contains information that shows you how to help lower security settings or how to turn off security features on a computer. You can make these changes to work around a specific problem. Before you make these changes, we recommend that you evaluate the risks that are associated with implementing this workaround in your particular environment. If you implement this workaround, take any appropriate additional steps to help protect your system.

SUMMARY

You may want to call a Windows user control from a Web page. To call a Windows user control that can access secured resources and that is built as an assembly that has a strong name, you must mark the assembly of the Windows user control with the AllowPartiallyTrusted assembly attribute. You must also include a call to the Assert method to allow the Windows user control to access the secured resource.

INTRODUCTION

This step-by-step article describes how to call a Windows user control from a Web page. The Windows user control that this article describes is built as an assembly that has a strong name. The sample in this article describes how to use the AllowPartiallyTrustedCallers attribute of the assembly so that an assembly that has a strong name can be accessed from a Web page. The sample in the article also describes how to use the Assert method.

back to the top

Create a key pair that has a strong name

A key pair that has a strong name is used to sign an assembly for a user control that has a strong name. The strong name is used when you create a code group that grants permission to use the assembly from partially trusted code.
  1. Open a Visual Studio command prompt.

    In Microsoft Visual Studio .NET 2002, click Start, point to Programs, point to Microsoft Visual Studio .NET, point to Visual Studio .NET Tools, and then click Visual Studio .NET Command Prompt. The Visual Studio .NET Command Prompt window appears.

    In Microsoft Visual Studio .NET 2003, click Start, point to Programs, point to Microsoft Visual Studio .NET 2003, point to Visual Studio .NET Tools, and then click Visual Studio .NET 2003 Command Prompt. The Visual Studio .NET 2003 Command Prompt window appears.

    In Microsoft Visual Studio 2005, click Start, point to Programs, point to Microsoft Visual Studio 2005, point to Visual Studio 2005 Tools, and then click Visual Studio 2005 Command Prompt. The Visual Studio 2005 Command Prompt window appears.
  2. Type the following at the command prompt, and then press ENTER:

    sn -k c:\snKey.snk

back to the top

Create a Windows user control by using Microsoft Visual C# .NET or Microsoft Visual C# 2005

Warning This workaround may make your computer or your network more vulnerable to attack by malicious users or by malicious software such as viruses. We do not recommend this workaround but are providing this information so that you can implement this workaround at your own discretion. Use this workaround at your own risk.

This user control demonstrates how to use the AllowPartiallyTrustedCallers attribute of an assembly. An assembly that has a strong name can only be called by a fully trusted caller unless the assembly uses the AllowPartiallyTrustedCallers attribute. The sample for the user control also demonstrates how to use the Assert method. The Assert method declares that the calling code can use the code that calls the Assert method to access the resource that is protected by a permission demand. The code can access the resource even if callers that are higher in the stack have not been granted permission to access the resource.

This user control lets you select a file by using the open dialog box. The control then opens the text file in the list box. The user interface of this user control includes one text box and one list box. The text box displays the name of the file that is selected, and the list box shows the contents of the file that is selected.

To read the name of the selected file from the OpenFileDialog box, and to read the file, the FileIOPermission permission type must be granted. The user control must have this permission granted through its code group. The Web page that calls the control does not have this permission.

To prevent a stack walk that is not successful because the caller does not have the required FileIOPermission permission type, use the Assert method. Note that the Assert method can open security vulnerabilities if the Assert method is used incorrectly or inappropriately. Therefore, you must use the Assert method with great caution. A RevertAssert method must follow the Assert method as soon as the file operation is completed.

Note To make sure that the contents of the file appear correctly in the list box, use this user control to select only text files.
  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project. The New Project dialog box appears.
  3. Under Project Types, click Visual C# Projects.

    Note In Visual Studio 2005, click Visual C# under Project Types.
  4. Under Templates, click Windows Control Library.
  5. In the Name box, type UserControl.
  6. Click OK.
  7. In the Solution Explorer window, right-click UserControl1.cs, and then click View Code. The UserControl1.cs file appears.
  8. Replace the existing code with the following code:
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;
    using System.Data;
    using System.Windows.Forms;
    using System.IO;
    using System.Security;
    using System.Security.Permissions;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    
    [assembly:AllowPartiallyTrustedCallers]
    
    namespace UserControl
    {
    	/// <summary>
    	/// Summary description for UserControl1.
    	/// </summary>
    	public class UserControl1 : System.Windows.Forms.UserControl
    	{
    		private System.Windows.Forms.TextBox textBox1;
    		private System.Windows.Forms.ListBox listBox1;
    		/// <summary>
    		/// Required designer variable.
    		/// </summary>
    		private System.ComponentModel.Container components = null;
    
    		public UserControl1()
    		{
    			// This call is required by the Windows.Forms Form Designer.
    			InitializeComponent();
    
    			// TODO: Add any initialization after the InitForm call.
    			OpenFileDialog fileDialog = new OpenFileDialog();
    			if(fileDialog.ShowDialog() == DialogResult.OK)
    			{
    				// Reading the name of the selected file from the OpenFileDialog box
    				// and reading the file requires FileIOPermission.   
    				// The Assert command must be followed by a RevertAssert as soon as the file operation 
    				// is completed.
    				new FileIOPermission(PermissionState.Unrestricted).Assert();
    				textBox1.Text = fileDialog.FileName;
    				// Display the contents of the file in the text box.
    				FileStream fsIn = new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read, 
    					FileShare.Read);
    				StreamReader sr = new StreamReader(fsIn);
    			
    				// Process every line in the file.
    				for (String Line = sr.ReadLine(); Line != null; Line = sr.ReadLine()) 
    				{
    					listBox1.Items.Add(Line);
    				}
    				// It is very important to call RevertAssert to restore the stack walk for
    				// file operations.
    				FileIOPermission.RevertAssert();
    			}
    
    		}
    
    		/// <summary>
    		/// Clean up any resources that are being used.
    		/// </summary>
    		protected override void Dispose( bool disposing )
    		{
    			if( disposing )
    			{
    				if( components != null )
    					components.Dispose();
    			}
    			base.Dispose( disposing );
    		}
    
    		#region Component Designer generated code
    		/// <summary>
    		/// Required method for Designer support. Do not modify 
    		/// the contents of this method with the code editor.
    		/// </summary>
    		private void InitializeComponent()
    		{
    			this.textBox1 = new System.Windows.Forms.TextBox();
    			this.listBox1 = new System.Windows.Forms.ListBox();
    			this.SuspendLayout();
    			// 
    			// textBox1
    			// 
    			this.textBox1.Location = new System.Drawing.Point(32, 16);
    			this.textBox1.Name = "textBox1";
    			this.textBox1.TabIndex = 0;
    			this.textBox1.Text = "textBox1";
    			// 
    			// listBox1
    			// 
    			this.listBox1.Location = new System.Drawing.Point(144, 16);
    			this.listBox1.Name = "listBox1";
    			this.listBox1.Size = new System.Drawing.Size(120, 95);
    			this.listBox1.TabIndex = 1;
    			// 
    			// UserControl1
    			// 
    			this.Controls.Add(this.listBox1);
    			this.Controls.Add(this.textBox1);
    			this.Name = "UserControl1";
    			this.Size = new System.Drawing.Size(376, 120);
    			this.ResumeLayout(false);
    
    		}
    		#endregion
    			}
    }
    
  9. In Solution Explorer, right-click AssemblyInfo.cs, and then click View Code. The AssemblyInfo.cs file appears.
  10. Locate the following code:
    [assembly: AssemblyVersion("1.0.*")]
    Replace this code with the following code:
    [assembly: AssemblyVersion("1.0.0.0")]
  11. Locate the following code:
    [assembly: AssemblyKeyFile("")]
    Replace this code with the following code:
    [assembly: AssemblyKeyFile("c:\\snKey.snk")]
  12. On the Build menu, click Build Solution.
back to the top

Create a code group to assign the permissions for the assembly

Warning This workaround may make your computer or your network more vulnerable to attack by malicious users or by malicious software such as viruses. We do not recommend this workaround but are providing this information so that you can implement this workaround at your own discretion. Use this workaround at your own risk.

A code group determines whether an assembly matches administrator-defined criteria that is referred to as a membership condition. If the assembly matches, the code group grants the assembly a set of permissions that has been associated with that code group.

To create a code group:
  1. Click Start, point to Settings, and then click Control Panel. The Control Panel window appears.
  2. Double-click Administrative Tools. The Administrative Tools window appears.
  3. In Microsoft Visual Studio .NET 2002, double-click Microsoft .NET Framework Configuration. The .NET Framework Configuration window appears.

    For Microsoft Visual Studio .NET 2003, double-click Microsoft .NET Framework 1.1 Configuration. The .NET Configuration 1.1 window appears.

    In Microsoft Visual Studio 2005, double-click Microsoft .NET Framework 2.0 Configuration. The .NET Framework 2.0 Configuration window appears.
  4. In the left pane, expand Runtime Security Policy, expand Machine, and then expand Code Groups.
  5. Right-click All_Code, and then click New. The Create Code Group wizard appears.
  6. Make sure that Create a new code group is selected, type MyUserControlCodeGroup in the Name box, and then click Next. The Choose a condition type page appears.
  7. In the Choose the condition type for this code group list, click Strong Name.
  8. Click Import. The Import Strong Name From Assembly dialog box appears.
  9. Locate the UserControl.dll file that you created in the "Create a Windows user control by using Microsoft Visual C# .NET or Microsoft Visual C# 2005" section, and then click Open.
  10. Click Next. The Assign a Permission Set to the Code Group page appears.
  11. Click Use existing permission set, select FullTrust from the list, and then click Next. The Completing the Wizard page appears.
  12. Click Finish to close the Create Code Group wizard.
back to the top

Create an HTML file to call the user control

After you create a code group to assign the permissions for the assembly, you must create an HTML file to call the user control from the browser, and you must set up the environment to make sure that the user control is called successfully.
  1. Click Start, click Run, type notepad, and then click OK.
  2. In Notepad, paste the following code:
    <OBJECT id="MyWinControl1" height="200" width="200" classid="http:UserControl.dll#UserControl.UserControl1" VIEWASTEXT>
        
    </OBJECT> 
  3. In the root folder of Microsoft Internet Information Services (IIS), save the file as CallUserControl.htm.
  4. Copy the UserControl.dll file that you created in the "Create a Windows user control by using Microsoft Visual C# .NET or Microsoft Visual C# 2005" section to the IIS root folder.
  5. Open Microsoft Internet Explorer.
  6. In the Address box, type http://localhost/CallUserControl.htm, and then press ENTER. The Open dialog box appears.
  7. Locate any text file, and then click Open. The text of the file appears in the ListBox control on the browser.
back to the top

REFERENCES

For more information, visit the following Microsoft Developer Network (MSDN) Web sites:back to the top

Modification Type:MajorLast Reviewed:1/5/2006
Keywords:kbHOWTOmaster kbhowto kbListBox kbFileIO kbDLL kbControl kbweb kbUser kbSecurity kbpolicy kbopenfile KB839300 kbAudDeveloper