Share via


Exercise 3: Calling a CAS secured method

In this exercise you will add code to the Web Part that tries and perform a CAS security protected task. In the sample a HTTP connection is attempted.

  1. In the WebPart1 class, add the following code to the CreateChildControls method that you have added earlier. This code will issue a standard Web request.

    C#

    protected override void CreateChildControls() { // CODE OMMITTED FOR BREVITY Controls.Add(testButton1); // CODE OMMITTED FOR BREVITY Controls.Add(testButton2); Button testButton3 = new Button(); testButton3.Text = "Test 3"; testButton3.Click += delegate { try { System.Net.HttpWebRequest.Create("https://intranet.contoso.com"); } catch (Exception e) { message.Text = e.Message; } }; Controls.Add(testButton3); }

    VB.NET

    <ToolboxItemAttribute(false)> Public Class WebPart1 Inherits WebPart Dim message As New Label() Protected Overrides Sub CreateChildControls() Controls.Add(message) Controls.Add(New WebControl(HtmlTextWriterTag.Br)) Dim testButton1 As New Button() AddHandler testButton1.Click, AddressOf testButton1_Click testButton1.Text = "Test 1" Controls.Add(testButton1) Dim testButton2 As New Button() testButton2.Text = "Test 2" AddHandler testButton2.Click, AddressOf testButton2_Click Controls.Add(testButton2) Dim testButton3 As New Button() testButton3.Text = "Test 3" AddHandler testButton3.Click, AddressOf testButton3_Click Controls.Add(testButton3) End Sub ' CODE OMMITTED FOR BREVITY Private Sub testButton3_Click(ByVal sender As Object,ByVal e As EventArgs) Try System.Net.HttpWebRequest.Create("https://intranet.contoso.com") Catch e1 As Exception message.Text = e1.Message End Try End Sub End Class
  2. On the Debug menu, choose Start Debugging in order to deploy and test the Web Part, or just press [F5]. When the browser opens, it will automatically take you to the https://intranet.contoso.com/sites/Lab13 site.

    Figure 6

    All 3 buttons on WebPart1

  3. On the WebPart1, click the Test 3 button in order to test creating an HTTP connection.
  4. Notice that an exception is thrown because the sandbox is running in a special CAS policy that blocks all System.Net.WebPermission demands, as the HttpWebRequest object does.

    Figure 1

    A Permission exception

  5. Close the browser in order to stop debugging.
Note:
In this exercise you added code that is blocked by the sandbox CAS policy because it demands a permission not allowed by the CAS policy.