Welcome!

Industrial IoT Authors: Elizabeth White, Stackify Blog, Yeshim Deniz, SmartBear Blog, Liz McMillan

Related Topics: Industrial IoT, Microsoft Cloud

Industrial IoT: Blog Feed Post

Deploying a Web Part with Code Access Security

In Visual Studio 2010 (SP2010)

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 SouthwesternEnergy.Partners.Web.">

<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 SouthwesternEnergy.Partners.Web.">

<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 here.  Hopefully, we will get an answer soon.

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.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is an independent consultant specializing in Cloud technologies such as Azure and Office 365. He also specializes in mobile development. Corey serves as the product manager for two cloud-first mobile app platforms: BrewZap and HappenZap.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
"Space Monkey by Vivent Smart Home is a product that is a distributed cloud-based edge storage network. Vivent Smart Home, our parent company, is a smart home provider that places a lot of hard drives across homes in North America," explained JT Olds, Director of Engineering, and Brandon Crowfeather, Product Manager, at Vivint Smart Home, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time t...
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.