Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Posted Friday, November 20, 2009 2:38 PM by CoreyRoth

By now, you have heard about how the SharePoint 2010 development experience has been improved.  We can easily deploy web parts and other code without having to manually manipulate any XML files.  What about under partial trust though?  Many of you that know me know that I have pushed using Code Access Security quite a bit through a series of blog posts and talks.  So it would be irresponsible of me not to talk about how we can do that in Visual Studio 2010.  The good news is that it is a lot easier.

Let’s start by creating a new SharePoint project in Visual Studio 2010 and creating a new Web Part project item.  In this case we are talking about deploying a Farm Solution, not a Sandboxed Solution.  Note: we are going to talk about a traditional web part today, and not a Visual Web Part.  Visual Web Parts are simply not supposed under partial trust.  More on that later below.  My web part has some simple code which uses ASP.NET and also hits the SharePoint object model to display the title of the site in a label.  Here is what the code looks like.

protected override void CreateChildControls()

{

    Controls.Add(new Label(){Text = "<div>My Cool Web Part!</div>"});

    Controls.Add(new Label() { Text = string.Format("Site Title: {0}", SPContext.Current.Web.Title) });

 

    base.CreateChildControls();

}

When you create a new project, it deploys to the GAC by default.  We start by changing this on the project properties.

CASWebApplication

This effectively changes the DeploymentTarget attribute on Assembly element in the Manifest.xml.  At this point, you may be asking.  “Sweet, is that it?  Does it take care of the CAS policy for me?”  The answer to that of course is “No.”  However, it is quite easy to add it.  Let’s see what happens if we try to deploy it as is.  I’ll just hit F5 to start debugging.  I then add my web part to any existing page, and I immediately get hit with the following in Visual Studio.

CASSecurityExceptionYellowScreen

System.Security.SecurityException: Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.

Luckily we know how to fix this.  Hopefully, this will also help new developers when they get this error in the future and aren’t sure what to do.  We need to grant permissions to this assembly to use the object model as well as a few other things.  We’ll start by using a standard set of IPermission elements that I have used in past posts.  This gives me basic ASP.NET, SharePoint object model, and Security permissions.

<CodeAccessSecurity>

  <PolicyItem>

    <PermissionSet class="NamedPermissionSet" version="1" Description="Permission set for VisualWebPartProject1.">

      <IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />

      <IPermission class="SecurityPermission" version="1" Flags="Execution,ControlPrincipal,ControlAppDomain,ControlDomainPolicy,ControlEvidence,ControlThread" />

      <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"

                   version="1" ObjectModel="True"  />

      <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="UserName" />

      <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="$AppDir$" Write="$AppDir$" Append="$AppDir$" PathDiscovery="$AppDir$" />

    </PermissionSet>

    <Assemblies>

      <Assembly Name="VisualWebPartProject1"  />

    </Assemblies>

  </PolicyItem>

</CodeAccessSecurity>

You can use this in your code almost exactly but two small changes are required.  First, you need to change your assembly name to whatever you have called yours.  Secondly, if you look at that SharePointPermission, you’ll notice it says version 12.0.0.0.  We need to change this to 14.0.0.0 since we are working with SharePoint 2010 now.  Adding this to your package is quite easy.  In the Solution Explorer, locate Package and then Package.package and open it.  This will bring open the package designer.  Click on the Manifest tab at the bottom and then expand Edit Options.  The way this works is that you can paste any additional elements here and it will merge your items with the ones it automatically generates.  Here is what I would paste in.

<?xml version="1.0" encoding="utf-8"?>

<Solution xmlns="http://schemas.microsoft.com/sharepoint/">

  <CodeAccessSecurity>

    <PolicyItem>

      <PermissionSet class="NamedPermissionSet" version="1" Description="Permission set for VisualWebPartProject1.">

        <IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />

        <IPermission class="SecurityPermission" version="1" Flags="Execution,ControlPrincipal,ControlAppDomain,ControlDomainPolicy,ControlEvidence,ControlThread" />

        <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"

                     version="1" ObjectModel="True"  />

        <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="UserName" />

        <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="$AppDir$;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\VisualWebPartProject1" Write="$AppDir$" Append="$AppDir$" PathDiscovery="$AppDir$" />

      </PermissionSet>

      <Assemblies>

        <Assembly Name="VisualWebPartProject1"  />

      </Assemblies>

    </PolicyItem>

  </CodeAccessSecurity>

</Solution>

Here is what it would look like on the screen.

CASPackageEditor

If everything is correct, you will see the merged result up top.  If there is an error in your XML, you will also see it there.  Now let’s deploy the solution and see if we can add the web part to an existing page. 

CASAPTCAError

Unfortunately, this is the error we get and it actually gives us good information.  We simply forgot to add the APTCA attribute (or AllowPartiallyTrustedCallers).  Just open your AssmeblyInfo.cs file and add the following line.

[assembly: AllowPartiallyTrustedCallers()]

Redeploy your solution and try to add your web part again.  If all goes well, you will have a lovely web part on the screen that looks like this.

CASWorkingWebPart

With the above set of CAS policies, you can probably get most of the code you want to do to work.  I mentioned Visual Web Parts above.  Here is the issue I am currently seeing.  If you remember my post on the Visual Web Part, you will know that this is just a web part with a Page.LoadControl() method calling a User Control (.ascx).  Page.LoadControl requires a ton of permissions and I haven’t been able to figure them out.  This means, it simply will not work.  I posted something to the forums about it.  Paul Andrew was nice enough to respond to my post and state that Page.LoadControl simply will not function under partial trust.  It has a check in it to verify that it is not running under partial trust.  He also goes on to explain this is why you can’t use Visual Web Parts in sandboxed solutions.

This may seem like a lot of steps, but really I just posted a lot of pictures.  Trust me it’s a lot fewer steps than it was before in MOSS 2007.  Just look at my old post if you don’t believe me.  Now, you might ask why would I do this instead of a Sandboxed solution?  Sandboxed solutions are severely limited on what they can do with the SharePoint object model.  By default, the CAS policy that defines them can’t even connect to a database.  I can specify at a per assembly level here what each one can do.  That is a big advantage.

Comments

# Twitter Trackbacks for Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010) - Corey Roth - DotNetMafia.com [dotnetmafia.com] on Topsy.com

Pingback from  Twitter Trackbacks for                 Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010) - Corey Roth - DotNetMafia.com         [dotnetmafia.com]        on Topsy.com

# ARB Security Solutions &raquo; Deploying a Web Part with Code Access Security in Visual Studio &#8230;

Pingback from  ARB Security Solutions  &raquo; Deploying a Web Part with Code Access Security in Visual Studio &#8230;

# Bug When Adding CAS Permissions to WSP Package &laquo; Amr Attia&#039;s Blog

Pingback from  Bug When Adding CAS Permissions to WSP Package &laquo; Amr Attia&#039;s Blog

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Wednesday, March 16, 2011 11:18 AM by Baptiste Wicht

Hi,

Thanks for the solution. I have the same problem and I think your solution will solve it. But I didnt' understand where I must put the XML code you give in your post ?

I have a VS 2010 solutions with two projects.

Thanks a lot

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Tuesday, March 22, 2011 11:30 PM by CoreyRoth

@Baptiste In vs2010, go to the solution editor and click on the middle tab which shows you the raw XML of your solution manifest.  You can add your XML there to have it injected into your solution manifest when it is deployed.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Monday, May 30, 2011 6:06 AM by Iftikhar

Hi, I followed your defined steps, when i am going to deploy WebPart i got this error msg "Error occurred in deployment step 'Add Solution': Property set method not found." Please sugest me resolution. One more thing i am developing Visual WebPart 2010 in control page i used Ajax TabPannel for making form in this TabPannel when i placed SharePoint:PeoplePicker control, then i got this error msg "Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed." Any idea about this msg

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Monday, May 30, 2011 9:19 PM by CoreyRoth

@Iftikhar Check your manifest.xml.  Verify that the assembly name is correct.  The following line in your manifest should grant you the permissions you need.

<IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"

                    version="1" ObjectModel="True"  />

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Thursday, July 21, 2011 10:56 AM by Ronak

Hi Corey,Thanks for sharing Knowledge on your blog.i am just wondering if you able to Deploy Visual webpart in Bin Directory using CAS.i also read thread started by you on MSDN but didn't find a solution i think its not possible right ?

Thanks

Ronak

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Monday, July 25, 2011 1:12 PM by CoreyRoth

The out-of-the-box Visual Web Part does not support sandboxed solutions.  However, take a look at what is available in the Community Kit for SharePoint.  There is a Sandbox Visual Web Part there.  cksdev.codeplex.com/documentation

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Tuesday, August 16, 2011 4:35 PM by Juan

Hy Corey,

 One MAIN Point you did not mention and it is quite pivotal is that the assembly goes the webApplicaiton bin folder, but it is SIGNED! In SharePoint 2007 you could deploy an assembly to the bin without signing it, you can in SharePoint 2010 as well, but Visual Studio 2010 does not let you package a webpart with an unsigned assembly. There seems to be no way around this other than to sign it. This can be very problematic when considering references to other unsigned assemblies in the bin. Key point you did not mention.

Juan

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Tuesday, August 30, 2011 10:51 AM by CoreyRoth

@Jaun that is a good point.  It seems like you should be able to get around it but you can't.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Thursday, March 8, 2012 6:49 AM by Mahesh

Though I used Full Trust Proxy , I am getting security Exception error in sandbox solution.

 System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Help appriciated..!!!

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Monday, April 2, 2012 10:51 PM by CoreyRoth

Make sure that if you are using a CAS policy for your full trust proxy that you have specified the proper permissions like in this post.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Wednesday, April 18, 2012 10:58 AM by Suresh

Please Help me... I am getting below error.

System.Web.HttpException: The file '/_CONTROLTEMPLATES/**********/VisualWebPartSampleUserControl.ascx' does not exist.    at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath)

but when i checked in physical path "VisualWebPartSampleUserControl.ascx" is availble... Thanks.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Wednesday, April 25, 2012 10:34 PM by CoreyRoth

@Suresh I don't think your visual web part will work using CAS.  Try using the sandbox friendly visual web part from the community toolkit.

# SharePoint 2010 & CAS : le GAC n’est pas l’unique solution de déploiement de vos composants

Friday, May 4, 2012 7:02 AM by The Mit's Blog

Un sujet qui revient souvent dans le monde SharePoint mais bizarrement moins depuis la version 14 alors

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Monday, April 1, 2013 2:20 AM by user123

hi, when i did the same in package.xml, and run deply, i am getting the following error;

Error occurred in deployment step 'Add Solution': Property set method not found.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Wednesday, April 10, 2013 7:11 AM by Mathi

www.dotnetmafia.com/.../deploying-a-web-part-with-code-access-security-in-visual-studio-2010-sp2010.aspx

Will this post be helpful while doing it for Event Receiver instead of WebPart.

Because I have created an Event Receiver in c# and trying to read an Excel file in the code. There I got Permission issues and got idea from your post which has been posted long back.But when I used the same which has been done for webpart I am getting the error "Error occurred in deployment step 'Add Solution': Property set method not found"

The only change in the Package.package -> Manifest is in the below tag

<IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="$AppDir$;C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\VisualWebPartProject1" Write="$AppDir$" Append="$AppDir$" PathDiscovery="$AppDir$" />

instead of \TEMPLATE\CONTROLTEMPLATES\VisualWebPartProject1 I have given TEMPLATE\FEATURES\MyReceiver_Feature1

Could you please help me.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Thursday, April 11, 2013 10:05 PM by CoreyRoth

@Mathi is the excel file in the MyReceiver_Feature1 folder?  If so that should work.  Otherwise you'll need to adjust the Read path.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Thursday, April 11, 2013 10:06 PM by CoreyRoth

@user123 I've never seen that error I am afraid.

# re: Deploying a Web Part with Code Access Security in Visual Studio 2010 (SP2010)

Friday, September 27, 2013 8:20 AM by Lyne

Hi Corey,

I have the same error but in a bit different context.

I have a custom dll that I made to read SharePoint list items. The dll is in the GAC and I reference this dll in a ssrs report.

I added the path to my library in rssrvpolicy:

<CodeGroup

class="UnionCodeGroup"

version="1"

PermissionSetName="FullTrust"

Name="MetaDataLibrary"

Description="Meta Data Library">

<IMembershipCondition

 class="UrlMembershipCondition"

 version="1"

 Url="C:\Program Files\Microsoft SQL Server\MSRS10_50.SQLSPDEV\Reporting Services\ReportServer\bin\MetaDataLibrary.dll"/>

</CodeGroup>

I also used RunWithElevatedPrivileges to run the SharePoint in my dll.

When the report renders, I get the message:

System.Security.SecurityException: Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed.

at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)

at MetaDataLibrary.MetaDataFunctions.IsAllowed(String view, String code, String currentUser)

Can you help me please ?

# Visual Studio 2010/13 Dataset by code or by designer? | Zaruba Answers

Pingback from  Visual Studio 2010/13 Dataset by code or by designer? | Zaruba Answers

# Deploying a Visual Studio Excel 2007 Template | Yorck Answers

Pingback from  Deploying a Visual Studio Excel 2007 Template | Yorck Answers

# WebPart security | Yezek Answers

Saturday, December 13, 2014 10:50 AM by WebPart security | Yezek Answers

Pingback from  WebPart security | Yezek Answers

Leave a Comment

(required)
(required)
(optional)
(required)