This part will continue on with the new Web Part project we just created with VS 2008 and VSeWSS 1.3. The original plan was to implement a custom security access policy so that we could safely run our Web Part and read from an XML file. But like all good plans... For the purposes of this sample, we can simply up the trust level in the config file until we are confident that we have our Web Part functioning correctly. I may come back to the topic of CAS customization.
I recently created some Web Parts using version 1.2 of the extensions in combination with the command line. Typically, I would use the GAC for development. My testing cycle would then consist of building, uninstalling old version from GAC, deploying Feature, installing new version in GAC, and running IIS reset. This time around, I was unfamiliar with the extent to which 1.3 was going to automate things. For example, while creating this project, I did not have to use the command line once. The ultimate goal for this part is to actually get a Web Part working, using the new version of VSeWSS 1.3.
Although not necessary for the purposes of this tutorial, it helps to understand the development cycle of Web Part created as a Feature. If you were doing this manually, you would typically build it, deploy (copy) it, install it, activate the feature, and recycle the application pool. When updating code and redeploying, don't forget to deactivate the Feature first. Note also, that when we deactivate and uninstall a Feature, files such as CSS, images and the like, still remain on the file system. If you need to make changes to these with version 1.2, you may need to hand copy them. There is a config attribute for overwriting a file if it already exists, but I could never get this to work.
Back to business. Take a look at the XML below. Add the Addresses.xml file to the TestWebPart folder in Solution Explorer. We want to display some of this data in our Custom Web Part.
<addresses>
<address>
<name>John Doe</name>
<street>123 Some Street</street>
<city>Some City</city>
<state>CA</state>
<zip>12345</zip>
</address>
<address>
<name>Jane Doe</name>
<street>456 Another Street</street>
<city>Some Other City</city>
<state>CA</state>
<zip>56789</zip>
</address>
</addresses>
Here's the complete code from my Web Part. Note the use of the RunWithElevatedPrivileges delegate here. Without this, the code would run under the current user's permissions. This allows the code to run with the same permissions as SHAREPOINT\System.I also hand copied the Addresses xml file to the wpresources folder in my virtual directory as I had difficulty in correctly configuring my Feature to do this for me. Does anyone know the proper way to do this?
using System;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
namespace TestWebPart
{
[Guid("5bc61f3f-62cf-49b5-8ffb-0f6081f87e64")]
public class TestWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
DataSet ds;
Label testLabel;
public TestWebPart()
{
}
protected override void CreateChildControls()
{
Controls.Clear();
base.CreateChildControls();
// This following anonymous method allows a specified block of
// code to run in the context of the SharePoint System Account
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// You must create a new SPSite object inside the delegate
// because SPSite objects created outside do not have Full
// Control even when referenced inside the delegate.
using (SPSite site = new SPSite("http://" + System.Environment.MachineName))
{
string sUri
= site.WebApplication.IisSettings[SPUrlZone.Default].Path.FullName
+ "\\wpresources\\Addresses.xml";
ds = new DataSet();
ds.ReadXml(sUri);
StringBuilder sb = new StringBuilder();
sb.Append(ds.Tables[0].Rows[0]["name"].ToString() + "," + "<br />");
sb.Append(ds.Tables[0].Rows[0]["street"].ToString() + "," + "<br />");
sb.Append(ds.Tables[0].Rows[0]["city"].ToString() + "," + "<br />");
sb.Append(ds.Tables[0].Rows[0]["state"].ToString()
+ " " + ds.Tables[0].Rows[0]["zip"].ToString() + ".");
testLabel = new Label();
testLabel.Text = sb.ToString();
}
});
this.Controls.Add(testLabel);
}
}
}
VS 2008 Tip: If like me, you often end up with a list of 'using' statements as long as your arm, try the following: Highlight all your 'using' statements, then, select Edit -> Intellisense -> Organize Usings -> Remove and Sort :-)
When you have your Web Part building successfully, do the following:
* Select Build -> Package Solution
* If you have already deployed, select Build -> Retract Solution
* Deploy Web Part
You may get the following error:
To get around this, you need to open your AssemblyInfo.cs file (in the Properties folder) and add a System.Security.AllowPartiallyTrustedCallers assembly attribute. The framework will not by default allow an assembly that is not fully trusted to call another assembly that is not fully trusted. However, by adding this attribute we are telling the framework that it is okay to call other assemblies from this one. See below.
[assembly: AssemblyTitle("TestWebPart")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestWebPart")]
[assembly: AssemblyCopyright("Copyright © 2009")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: System.Security.AllowPartiallyTrustedCallers]
Upon redeployment, you may get the unexpected error page. If you check the event viewer Windows application log file, it should contain the following:
Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.
If you check the web.config file located in $Drive:\inetpub\wwwroot\wss\VirtualDirectories\80, and you will notice that VSeWSS had indeed added a safe entry for the Web Part:
</SafeControls>
...
<SafeControl Assembly="TestWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6bbd0bdca0a0fd9e" Namespace="TestWebPart" TypeName="TestWebPart" Safe="True" />
</SafeControls>
It seems that when opting to deploy to the bin folder when creating the project, VSeWSS does just that and nothing more. VSeWSS still leaves the security options to us, which is the correct behaviour one would expect. By default, SharePoint Web applications are only allowed to run with a very restrictive trust level of WSS_Minimal. If we want to have our Web Part deployed to the bin folder, then in order for it to run we must do one of two things: either set the trust level to WSS_Medium or WSS_Full in the web.config, or create a custom CAS policy that will allow this assembly's managed code to run. We will up the level to WSS_Full here. In a production environment, you will need to make an informed decision on this yourself.
With the trust level updated, bear in mind that there may be other errors waiting for us. To view meaningful error messages in the browser rather than the unhelpful 'unexpected error' page, update the following in the web.config file:
* customErrors=off
* Enable Stack Traces by adding CallStack=”true” to the SafeMode tag
* Set the compilation debug attribute to "true"
You should now be able to view the Web Part. If you can't, I take no responsibility ;-)
If you decide to implement your own code access security policy, then this should be of help.
Update - 06-19-2007:
The following code from above does not play nice when deployed to a different machine:
using (SPSite site = new SPSite("http://" + System.Environment.MachineName))
{ ... }
Change it to the following:
using (SPSite site = new SPSite("http://" + HttpContext.Current.Server.MachineName.Trim().ToLower())) { ... }