Thursday, December 4, 2014

Deleting an orphaned or inaccessable SharePoint site

Sometimes when provisioning sites via PowerShell I’ll get a failure somewhere along the process and the site gets created but cannot be accessed or deleted via Central Admin. I believe this is because all of the provisioning steps did not complete. The following 2 lines of PowerShell will force deletion of the site.

PowerShell


# 1. Get the site object
$site = get-spsite "https://yourdomain/sites/sample";

# 2. Force the site deletion via the contentdatabase
$site.contentdatabase.forcedeletesite($site.id, $false, $false);

Monday, June 9, 2014

Change the namespace on a web part solution

I rarely like the way Visual Studio handles namespaces within a solution. I like to organize my code with folders and such and Visual Studio likes to add the folder hierarchy to the namespace. However, when I change the namespace name on a web part solution I invariably get the "Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type {your web part class type} could not be found or it is not registered as safe." error, then I spend 30-60 minutes scouring the web to remember how to fix this. So, to save me that frustration in the future I am documenting what I have found to be the solution.

Lets take for example, my desired namespace is "C2.AcmeCorp.Relationships" and my Web Part is named "DisplayRelationships":

0) Retract your current deployed solution, just to insure cleanup of the web.config.

1) You must manually update a hidden file under the web part named "SharePointProjectItem.spdata". Visual Studio can display and edit this file, you must click the "Show All Files" icon in solution explorer in order to see it. You must manually update the SafeControl Namespace property to your new namespace name, Visual Studio does not do this for you. For example:

<SafeControls>
  <SafeControl Name="SafeControlEntry1"
               Assembly="$SharePoint.Project.AssemblyFullName$" 
               Namespace="C2.AcmeCorp.Relationships
               TypeName="*" 
               IsSafe="true" 
               IsSafeAgainstScript="false" />
</SafeControls>

2) You must insure the .webpart file type name is correct. In my example, the DisplayRelationships.webpart file should be updated to look like the following:

<metaData>
 <type Name="C2.AcmeCorp.Relationships.DisplayRelationships$SharePoint.Project.AssemblyFullName$" />
  </importErrorMessage>$Resources:core,ImportErrorMessage</importErrorMessage>
</metaData>

3) Redeploy your solution. In my example the updated web.config SafeControl entry should look like the following after I have redeployed my solution:

<SafeControls>
  <SafeControl Assembly="C2.AcmeCorp.Relationships, Version=1.0.0.0 Culture=neutral, PublicKeyToken=16de7ad7af136a9"
               Namespace="C2.AcmeCorp.Relationships
               TypeName="*" 
               Safe="True" />
</SafeControls>

Wednesday, April 30, 2014

Creating Document Set Based Containers

SharePoint 2010 and 2013 provide a content type called a DocumentSet. To add this content type to a site collection you must activate the feature “Document Sets”, or by code using FeatureID “3bae86a2-776d-499d-9db8-fa4cdc7884f8”. A document set is like a folder in a library, in that you can create or upload documents under the document set. It is also similar to a SPListItem because the Document Set can have custom site columns assigned to it.

For example, you could create a new content type based on the Document Set content type for presentations; maybe call it “Presentation”. You might create custom site columns such as “Presentation Date”, “Presenter Name”, “Presenter Email”, “Presentation Summary”, etc. and add them to the “Presentation” content type and it’s Welcome Page.

Then you can create new Presentation document sets with the Title, Presentation Date, Presenter Name, etc. The presentation materials, such as; slides, pictures, agenda, etc. can then all be uploaded and stored within this presentation document set as a related set of documents.

This post is about how to create a new document set container from a document set based content type, set its properties and add files to the document set. I do not cover the creation of Document Set based content types or the customization in this post.

PowerShell (sample code)
# Make sure the SharePoint namespace is loaded
add-pssnapin Microsoft.SharePoint.PowerShell –erroraction silentlycontinue;

# Set some sample variables
$weburl = "http://contoso.local/sites/Classes/USHistory";
$libraryname = "Materials";
$presentationtitle = "Civil War Weapons";
$files = ("E:\Civil War Weapons\Weapons.pptx", "E:\Civil War Weapons\Syllabus.pdf");

# Get the SPWeb object
$web = get-spweb $weburl;

# Get the content id of the presentation document set
$ctId = $web.contenttypes["Presentation"].id.tostring();

# Get the SPList object
$list = $web.lists.trygetlist($libraryname);
if ($list –eq $null) {
    # List not found, do error processing
    throw new-object ArgumentNullException($libraryname, "Library was not found!")
}
$folder = $list.rootfolder;

# Create a hash table for the custom property values
$hash = $null;
$hash = @{};
$hash.add("Presentation Date", get-date "5/12/2014 11:00 AM");
$hash.add("Presentater Name", "Joseph Assif");
$hash.add("Presentater Email", "jassif@university.edu");
$hash.add("Presentation Summary", "Lecture on the various weapons that were used during the US Civil War");

# Create the new presentation document set container
$newPresentation = [Microsoft.Office.DocumentManagement.DocumentSets.DocumentSet]::Create($list.rootfolder, $presentationtitle, $list.contenttypes.bestmatch($ctId), $hash);
$newPresentation.provision();

# If needed, you can capture the id
$newId = $newPresentation.item.id;

# Process the files for the document set
foreach ($file in $files) {

    # Read the file
    $f = get-childitem $file;
    $filestream = ([System.IO.FileInfo] (get-item $f.fullname)).openread();

    # Create the file in the document set
    $target = "{0}/{1}/{2}" –f $folder, $presentationtitle, $f.name;
    [Microsoft.SharePoint.SPFile]$spFile = $folder.files.add($target, [System.IO.Stream]$filestream, $true);
    $filestream.close();

    # Set any file properties you may have defined
    $spFile.item["Title"] = "Your document title text");
    $spFile.item.update();

    # Other document processes needed (checkin, etc.)

} # end foreach file

# Release SPWeb from memory
$web.dispose();


Friday, January 10, 2014

Content Organizer Rules

I had the need recently to create some content organizer rules that would route content types with specific metadata field values to specific folders within a library. To complicate matters, the metadata field value contained a taxonomy value.

I believe you cannot create such a rule via the SharePoint UI therefore I resorted to PowerShell. Let me break down how I accomplished this.
Before I do that let me outline the user background and requirement. The target library has folders within it, the primary purpose of the folders is to enable permissions granularity at the folder level. We created a new content type, named “HR Request”. This content type has a metadata field named “Request Sensitivity” which is a required selectable field of taxonomy term values like; “Corporate Executives”, “Human Resources”, “Managers”. Based on the selected value of this Sensitivity field we will route the HR Request to the folder with the correct permissions settings (i.e. we named the folders Corporate_Executives, Human_Resources, and Managers).

Let’s tackle the hardest part of this first, and that is creating the conditions string for the rule. We’ll need to have information about our field (“Request Sensitivity”) and our taxonomy term including its WssId to build the ConditionsString for our rule.

PowerShell (build a conditions string for a rule)
# Make sure the SharePoint namespace is loaded
Add-pssnapin Microsoft.SharePoint.PowerShell –erroraction silentlycontinue;

# Set some sample variables
$yourservername = "contoso.local";
$yoursitepath = "sites/Human Resources";
$yoursubweb = "Employees";

# Get an SPWeb object for the root and the subweb
$rootweb = get-spweb ("http://{0}/{1}" –f $yourservername, $yoursitepath);
$web = get-spweb ("http://{0}/{1}/{2}" –f $yourservername, $yoursitepath, $yoursubweb);

# Get our field and build the column portion of our conditions string
$field = $rootweb.Fields["Request Sensitivity"];
$column = "{0}|{1}|{2}" –f $field.Id, $field.InternalName, $field.Title;

# Get our taxonomy term
$taxSession = get-sptaxonomysession –site $rootweb.url;
$taxStore = $taxSession.TermStores[0];
$taxGroup = $taxStore.Groups["Human Resources"];
$taxTermSet = $taxGroup.TermSets["Request Sensitivity"];
$taxTerm = $taxTermSet.Terms["Corporate Executives"];

# Get the WssId for this term by querying the taxonomy hidden list
$spQuery = new-object Microsoft.SharePoint.SPQuery;
$spQuery.query = "<Where>";
$spQuery.query += "  <Eq>";
$spQuery.query += "    <FieldRef Name=’IdForTerm’ />";
$spQuery.query += "    <Value Type=’Text’>{0}</Value>" –f $taxTerm.Id;
$spQuery.query += "  </Eq>";
$spQuery.query += "</Where>";

$spList = $rootweb.lists.trygetlist("TaxonomyHiddenList");

$queryItems = $spList.getitems($spQuery);

if ($queryItems.count –gt 0) {
    $wssId = $queryItems[0]["ID"]; # If found, use it
}
else {
    $wssID = "-1";                 # Otherwise, use -1
}

# Now we can build the value portion of our conditions string
$value = "{0};#{1}|{2}" –f $wssId, $taxTerm.Name, $taxTerm.Id;

# Finally we can build the conditions string
$conditions = "<Conditions><Condition Column="{0}" Operator="IsEqual" Value="{1}" /></Conditions>" –f $column, $value;

Now that we have our conditions string built, let’s create our Organizer rule in PowerShell.

PowerShell (create a content organizer rule)
# Create an EcmDocumentRouterRule object
[Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRouterRule]$rule = new-object Microsoft.Office.RecordsManagement.RecordsRepository.EcmDocumentRouterRule($web);

# Set the properties of the rule
    # Set the content type the rule will apply to
    $rule.ContentTypeString = "HR Request";
    # Give the rule a name
    $rule.Name = "HR Request: Corporate Executives";
    # Give the rule some descriptive text
    $rule.Description = "Routes HR Requests with Request Sensitivity Corporate Executives to the Corporate_Executive folder.";
    # Give the rule a target path to the folder
    # The path can also be a relative server string such as:
    #    /sites/SiteName/ListTitle/FolderTitle
    $rule.TargetPath = $rootweb.SubFolders["Corporate_Executives"];
    # Since we’re not routing externally, set to false
    $rule.RouteToExternalLocation = $false;
    # Set the relative priority for the rule, in this case we want this rule to be evaluated first so we’ll use priority 3
    $rule.Priority = "3";
    # Enable the rule
    $rule.Enabled = $true;
    # Set the conditions for this rule (this is the complex part, see above for the steps to create the $conditions string
    $rule.ConditionsString = $conditions;

# Save the rule
$rule.Update();

# Release SPWebs from memory
$web.dispose();
$rootweb.dispose();

Now you say, what about a rule for “Human Resources” and “Managers”? Well, the process would be very similar for Human Resources. You would even use the same priority (eg. “3”). In our case, “Managers” is the default, so it does not need a fancy conditions string, just use “<Conditions></Conditions>” and skip all the steps I outlined above to build the conditions string, give it a lower priority (eg. “6”) and it will catch all HR Requests that are not routed by the higher priority rules.


Like so many things in SharePoint, it’s just a simple 106 step process!