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(""))
    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)

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:
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)