Thursday, 19 April 2012

Upload a Document Programmatically with Content Type and Metadata

Here’s a quick one on a straightforward way to upload a document to a SharePoint Document Library using the OM.  The key point about this method is the ability to set the Content Type and Metadata at the point of uploading the document:

using (SPSite site = new SPSite("http://sharepointbleached.dev.local"))
{
    using (SPWeb web = site.OpenWeb())
    {
        // Retrieve the required Content Type to be used.
        SPContentType ctype = web.ContentTypes["TestDoc"];
        SPList library = web.Lists["Test Library"];
 
        // Set the Content Type and Metadata for the Document prior to adding the File
        Hashtable properties = new Hashtable();
        properties.Add("ContentTypeId", ctype.Id.ToString());
        properties.Add("Priority", "(1) High");
        properties.Add("TaskStatus", "Completed");
 
        // Open the file to uploaded as a stream object
        using (FileStream fs = new FileStream("Sample Presentation.ppt", FileMode.Open))
        {
            // Add the file passing in the metadata
            SPFile file = library.RootFolder.Files.Add(Path.GetFileName(fs.Name), fs, properties, true);
 
            // If Check In / Check Out has been enabled on the library,
            // check whether the file needs to be checked in.
            if (file.CheckOutType != SPFile.SPCheckOutType.None)
            {
                file.CheckIn(string.Empty);
            }
 
            fs.Close();
        }
    }
}

My next post will cover how to copy a document from one Web Application to another, preserving the Content Type and Metadata during the copy process.


Happy to answer any questions if you have them, just leave a comment.

Wednesday, 11 April 2012

Create a Calculated Field programmatically in SharePoint 2010 using XML

There are a few different blog posts on the web showing how to create a calculated field programmatically in SharePoint 2010, however, I ran into a specific scenario that I thought was worth sharing.
I had a situation where I was creating a number of fields and content types programmatically and needed to control the GUIDs of the fields as they were being provisioned across multiple site collections which I wanted to be consistent.
The first trick is finding out what the required schema should be when creating the field.  Now, if you want, you can refer to the following MSDN article that will go through how the schema is defined from which you can then work out what the calculated field schema should be:
http://msdn.microsoft.com/en-us/library/ms196289.aspx
Or, if you want a quicker, easier way to work out what it should be then you can create the calculated field in the UI in the way that you need, then knock up a quick console app to read the schema (or use SharePoint Manager 2010)

Sunday, 20 March 2011

Extract WSP Solutions from SharePoint using PowerShell


There will be occasions when you will find it really useful to be able to extract a WSP solution from the SharePoint solution store.  This is not something that you can do out of the box, I’m not sure why, possibly to protect the intellectual property of third party solution providers perhaps?
I’m not saying that you should be extracting WSPs so that you can go poking around in other people’s solution packages, but there are definitely valid reasons for needing to extract those solutions.
The two main legitimate reasons I can think of for needing to extract a WSP are as follows:
1.   Your company does not have an appropriate source control system and your solutions have been developed by a third party.
2.   You need to audit any custom solutions that have been created.
Regarding the second point above, there have been a number of times when I have had to perform an audit of a customer’s SharePoint system as part of IMGROUP’s Health Check service.  The reason for wanting to poke around in the WSP solution package is to verify whether or not customisations have been made according to best practice.  For instance, in one particular instance a third party had assured the customer that all their customisations had been packaged as part of WSP packages, but by extracting the few WSPs that were in the solution store, I could see that this was in fact not the case.
Another example that is quite pertinent at the moment is where you need to assess what customisations are in place prior to performing an upgrade to SharePoint 2010.  The “preupgradecheck” command that is a part of stsadm is only available as part of Service Pack 2 for MOSS 2007, as well as ideally requiring a number of additional cumulative updates.  If your environment is currently at Service Pack 1 and you are fairly risk averse, performing an upgrade to Service Pack 2 purely to get an understanding of what customisations have been made may not be particularly desirable.  Instead, most customers that I am working with will include the Service Pack 2 upgrade as part of their implementation plan, but want some early visibility of their customisations so they can make steps to validate them against the new product.
The following simple PowerShell script will iterate through the solution store and write the WSP packages to file:
Start-Transcript "c:\wsp\transcript.txt"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$solutions = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions;
foreach ($solution in $solutions) {
   $solution.SolutionFile.SaveAs("c:\wsp\" + $solution.Name);
}
Stop-Transcript

The above script uses the Reflection namespace to perform an Assembly load of Microsoft.SharePoint.dll from the GAC.  Since the dll is being loaded in this way, the script can be run in a standard PowerShell console.  If your environment is running on Windows Server 2003, PowerShell can be downloaded and installed from the following link: