Saturday 26 January 2013

SharePoint 2010 Referential integrity - Using LookUp Column


There are two major enhancements in Lookup Columns for SharePoint 2010.


1. You can now display additional columns from the look-up list, along with the look up field data.
for e.g. If your Look-up List has Columns City, Zipcode and State, and if you select "City" to be displayed as Look-up column in your list, you would also have an option to display other information like Zipcode and State along with the City column in your view. You cannot however treat Zipcode and State as look-up columns, they are just additional information to the City you selected.


2. Implementing Referential integrity

When you create a Lookup column in SharePoint 2010, you would see an option (at the bottom) to define a Relationship. You are given two choices

1. Restrict Delete
2. Cascade Delete


Restrict Delete :
 Choosing this option would restrict the users from deleting an item in the column in the Look-up list, if the value is being used in some other lists. This means that if a value in the City column is used in our list, then it cannot be deleted from the look-up list.

Cascade Delete : 
If an Item\value in the City column in the look-up list is deleted, then all those items referencing that value (as look-up value) in other lists will also be deleted.

So, by using the Restrict delete option we can now achieve true Referential integrity within our list data. Cooll

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


Installing Web Parts in the GAC can cause serious security implications - web parts installed in the GAC are run with full trust.

Installing Web Parts in the respective Web Application's bin folder is another option. Web parts installed in the bin folder run with partial trust and access to the system resources is limited.If the Web Part needs additional level of permissions, a best practice recommendation is to create a custom CAS policy for the specific permissions required.

The intent of the CAS  custom policy we're about to make is to allow your code and only your code to run in full trust regardless of where it is (doesn't have to be in the GAC).
All other code in the application will be running as WSS_Minimal which means it will have a reduced set of privileges . For example, codes running in WSS_Minimal can't access the SharePoint object model. Your code however will be running in full trust and will be able to do whatever it wants.
This is often desirable since we have no idea what web parts information workers or administrators will lob into our SharePoint application. It's a little presumptuous to assume that they're all safe and won't do anything malicious. Granting them full trust allows them to do things like write to sensitive areas of the disk, access the registry, etc... Users with high privileges (ie. administrators) get duped in to running malicious code all the time, that's one of the reasons Code Access Security exists in the first place. If you're curious about what the difference between code running in full trust and code running in WSS_Minimal is, refer to the table in the link above. Onward.


Code Access Security (CAS) is a resource-constraints policy that limits the access that an assembly has to protected system resources and operations. SharePoint Foundation has built-in security policies built on top of the built-in security policies of ASP.NET. By default, SharePoint Foundation uses a minimal set of permissions in order to protect the server and underlying infrastructure from malicious code.
If your Web Part needs greater access than what is provided in the minimal settings, there are a number of ways to increase the permissions of your Web Part, but only one is recommended. You can create a custom CAS policy for your Web Part, or increase the overall trust level of the server farm in the web.configfile. This is a security risk and is not recommended.

SharePoint Foundation is a partial trust application by default. SharePoint Foundation can use the ASP.NET built-in trust levels but defines trust levels of its own:
  • WSS_UserCode
  • WSS_Minimal
  • WSS_Medium
These trust levels extend the ASP.NET trust levels for use with SharePoint Foundation. Trust levels are defined in policy files that can be found on the file system of each Web server.
Important   By default, the built-in SharePoint Foundation policy files in SharePoint Foundation, named wss_usercode.configwss_minimaltrust.config, and wss_mediumtrust.config, are found in %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\CONFIG directory.
By default, SharePoint Foundation applies the WSS_Minimal trust level for the virtual server. This trust level grants all of the permissions in the ASP.NETMinimal trust as well as Web Part connections. The WSS_Minimal policy restricts the Web Part from accessing many resources for advanced operations, including the object model and file operations.
The WSS_Medium trust level grants greater access to the environment. Also, WSS_Medium allows access to the SharePoint Foundation object model and file operations including read, write, append, and path discovery. This trust level also allows access to environment variables.
The following table outlines the specific permissions granted with the WSS_MediumWSS_Minimal and WSS_UserCode policy files in the ASP.NET 2.0 environment.
Permission
WSS_Medium
Trust Level
WSS_Minimal
Trust Level
WSS_UserCode (SandBoxed Solutions)
Trust Level
Medium
Minimal
Minimal
Unrestricted=”True”
None
None
Read=”TEMP; TMP;USERNAME;OS;COMPUTERNAME”
None
None
Read, Write, Append, PathDiscovery, Application Directory
None
None
AssemblyIsolationByUser, Unrestricted UserQuota
None
None
Default printing
None
None
Assertion, Execution, ControlThread, ControlPrincipal, RemotingConfiguration
Execution
Execution
ObjectModel=”True”
None
ObjectModel=”True”, UnsafeSaveOnGet=”True”
Access=”Connect”
None
None
Unrestricted=”true”
None
None
Connections=”True”
Connections=”True”
None
Connect to origin host (if configured)
None
None
NoteNote
For more information about Code Access Security, see Using Code Access Security with ASP.NET and also Security Guidelines for .NET Framework 2.0.

SharePoint Foundation has the ability to deploy a CAS policy file with a solution. We recommend that you use the permissions for sandboxed solutions as listed in the wss_usercode.config file, but you can also create custom permissions for your Web Parts and use SharePoint Foundation to handle the deployment.
The following code example shows the basic structure of a CAS policy file in a SharePoint Foundation solution package.
<CodeAccessSecurity>
   <PolicyItem>
     <PermissionSet 
      class="NamedPermissionSet" 
      version="1"
      Description="Permission set for custom test WebParts">

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

        <IPermission 
          class="SecurityPermission" 
          version="1" 
          Flags="Execution" 
        />

        <IPermission 
          class="Microsoft.SharePoint.Security.SharePointPermission, 
            Microsoft.SharePoint.Security, version=11.0.0.0, 
            Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
          version="1" 
          ObjectModel="True" 
         />

        <IPermission 
          class="System.Net.WebPermission, System, 
            version=1.0.5000.0, Culture=neutral, 
            PublicKeyToken=b77a5c561934e089" version="1">
          <ConnectAccess>
            <URI uri="https?://.*" />
          </ConnectAccess>
        </IPermission>

        <IPermission 
          class="System.Security.Permissions.SecurityPermission, 
            mscorlib, version=1.0.5000.0, Culture=neutral, 
            PublicKeyToken=b77a5c561934e089" 
          version="1" 
          Flags="ControlThread, UnmanagedCode" 
        />

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

     </PermissionSet>
     <Assemblies>
       <Assembly PublicKeyBlob=PublicKeyBlob />
     </Assemblies>
   </PolicyItem>
</CodeAccessSecurity>

The list below includes some general guidelines that apply when you use a <CodeAccessSecurity> section in your solution manifest.
  • There can only be one <CodeAccessSecurity> per solution manifest.
  • There can be multiple <PolicyItem> nodes.
  • Every <PolicyItem> node can only contain one <PermissionSet> node.
  • Every <PolicyItem> node can only contain one <Assemblies> node.
  • Each <PermissionSet> node can contain multiple <IPermission> nodes.
  • There can be multiple <Assembly> nodes under the <Assemblies> node.
For more information about the schema of the <CodeAccessSecurity> area, see CodeAccessSecurity Element (Solution).
When you deploy your assembly using a custom CAS policy, you must use the -CASPolicies option with SharePoint Management Shell. The command is as follows:
Install-SPSolution –Identity <insert name> -CASPolicies <true/false>


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.
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.
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.

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. 

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.
[assemblyAllowPartiallyTrustedCallers()]
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.

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.

Deploying Web Parts in SharePoint Foundation 2010


Credits to MSDN blog as this content has been taken form them.

Microsoft SharePoint Foundation requires that a Web Part be deployed in the Web Part gallery before it can be added to a webpage. This section describes the differences between the bin folder and the global assembly cache, security permission considerations, how to strong name an assembly for deployment, how to create a SafeControl entry, and how to create a Web Part definition file to deploy the Web Part.


There are multiple locations within a SharePoint site where you can deploy a Web Part assembly.
  • Solution Gallery – The Solution Gallery is the recommend placed to deploy a Web Part by using a sandboxed solution. It provides monitoring and security for your Web Parts by default. For more information about sandboxed solutions, see Sandboxed Solutions in SharePoint 2010.
  • global assembly cache — A global location where signed assemblies can be deployed, especially code for workflows, events, and Feature receivers. The global assembly cache enables you to share assemblies across numerous applications. The global assembly cache is automatically installed with the .NET runtime. Components are typically stored in C:\Windows\Assembly.
  • bin directory — A folder stored in your web application root directory; deployment to the bin directory should be limited to controls and Web Parts . The location of this folder is determined when the website is created in Internet Information Services (IIS). In SharePoint Foundation, this can occur either through the Central Administration site, or by manually creating a new website in IIS manager.
    Important noteImportant
    If a bin directory does not exist, you must add one manually. Do not store Web Parts in the local _app_bin directory, which is reserved for use by Microsoft.
    For more information, see How to: Find the Web Application Root.
Each deployment location has advantages and disadvantages, as described in the following table.
Deployment Location
Advantages
Disadvantages
Solution Gallery
By default, code deployed to the Solution Gallery is run in partial trust. Code in the Solution Gallery also have resource usage monitoring to ensure the health of the farm. The Solution Gallery is specific to a site collection.
All of the object model in SharePoint Foundation is not available in the Solution Gallery.
global assembly cache
By default, assemblies run with full trust. They are globally installed, so they work in any web application. The global assembly cache can contain multiple versions of the same assembly.
Generally there are no code access security (CAS) restrictions on code installed to the global assembly cache.
Also, an assembly deployed to the global assembly cache is cached, so if the assembly is rebuilt, it is not automatically updated on the SharePoint site. You must force SharePoint Foundation to reload the assembly by resetting Internet Information Services (IIS).
bin directory
By default, assemblies run with partial trust. Code that runs from this directory has a low level of CAS permissions. Because administrators must explicitly raise permissions that have been granted to a Web Part so it can function properly, they often prefer that assemblies run in the bin directory with a known set of required CAS permissions.
A bin directory is specific to a web application. This makes it possible to isolate code to a particular web application, but we recommend that you use sandboxed solutions for security protection.
In order for the Web Part to run in multiple web applications, you must deploy it to the global assembly cache.
Deploying assemblies to the bin folder may affect performance because there is additional time required to load the .NET Framework runtime to manage code access security permissions.

By default, code access security permissions for the bin directory are low; only pure execution is allowed. In most cases, you must elevate these permissions to make your assembly run correctly, for example, if your Web Part requires access to the SharePoint object model.
There are two ways to elevate permissions:
  • Recommended method — Create a new trust policy file and point your web.config file at the new file. This option is more complicated but it gives you a precise attribution of permissions for your Web Parts.
    For more information about trust policy files, see Securing Web Parts in SharePoint Foundation.
  • Optional method — Raise the trust level of the bin directory. In the web.config file in the web application root, there is a tag named <trust> with a default attribute of level="WSS_Minimal". You can change this level to WSS_Medium. Although this option is simpler, it grants arbitrary new permissions that you might not need and is less secure than creating a new trust policy file.

Strong naming uses a private key to digitally sign an assembly. Strong naming also stamps the assembly with a public key to validate the signature. This technique guards against unauthorized versions of a Web Part. If the public key fails to validate the digital signature, SharePoint Foundation refuses to run the module.
When you deploy a Web Part to the bin, the recommend practice is to strong name the assembly. When deploying a Web Part to the global assembly cache, the assembly must have a strong name. An assembly without a strong name is not recommended in SharePoint Foundation.
To sign an assembly, you use the sn.exe tool that is included with the Microsoft .NET Framework Software Development Kit (SDK). For more information about the .NET Framework SDK, see SDKs, Redistributables & Service Packs. The sn.exe tool is also used to extract the public key that is needed to register your control as safe in the SafeControls list. For more information about using the sn.exe tool, see Strong Name Tool (Sn.exe).

A fundamental assumption of the SharePoint Foundation technology is that untrusted users can upload and create ASPX pages within the system that is running SharePoint Foundation. To prevent untrusted users from arbitrarily adding server-side code within ASPX pages, SharePoint Foundation provides a SafeControls list.
The SafeControls list is a list of approved controls and Web Parts specific to your SharePoint site that you have designated as safe for invocation on any ASPX page within your site. This list is contained in the web.config file in your web application root.
A SafeControl entry is an XML-based declaration of a Web Part that has the following form.
<SafeControl Assembly="AssemblyNameWithoutDLLExtension, Version=AssemblyVersionNumber, Culture=neutral, PublicKeyToken=PublicKeyToken" Namespace="NamespaceOfYourProject" TypeName="*" Safe="True" />
The SafeControl entry uses the assembly name, namespace, versioning information, and, if it is signed, it also requires a public key token to verify that the control is safe. If a Web Part assembly is signed, you can use the Strong Name Tool to retrieve the public key token for use in the SafeControl entry. The following command will retrieve the public key token for an assembly.
sn -T AssemblyName.dll

A Web Part definition file is a simple XML file that contains property settings for a single Web Part. To import your Web Part into a Web Parts page, upload the .webpart file or add the Web Part to the Web Part gallery. After uploading the Web Part, you can display the Web Part by adding it to a site page. To display a default name and description for the Web Part after it is imported, you should include the Title and Description properties in the Web Part definition file. If you want to set other Web Part properties during import, you can also define them in a .webpart file. A .webpart file takes the following form.
<?xml version="1.0" encoding="utf-8" ?> 
  <webParts>
     <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
       <metaData>
         <type name="TypeName, Version=VersionNumber, Culture=neutral, 
         PublicKeyToken=PublicKeyToken" /> 
         <importErrorMessage>Cannot import this Web 
         Part.</importErrorMessage> 
       </metaData>
       <data>
         <properties>
           <property name="Title" type="string">
              WebPartTitle</property>
           <property name="Description" type="string">
              WebPartDescription
           </property>
         </properties>
       </data>
     </webPart>
   </webParts>
SharePoint Foundation also supports .dwp files for Web Parts. When exporting a Web Part, you may see a .dwp or a .webpart file. For more information, seeUpgrading Web Parts in SharePoint Foundation.