Monday, July 13, 2009

Toggle Read Only Attribute

Below are 2 ways to toggle the SharePoint Read Only attribute. I’ve used both of these to update the Created column for content migrations.

1st Option: SharePoint Object Model

public static void ToggleCreatedReadOnly(string siteURL, string ListName)
{
using (SPSite site = new SPSite(siteURL)) //http://APDev/sites/TestSC/
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPDocumentLibrary spdocLib = (SPDocumentLibrary)web.Lists[ListName];

SPFieldDateTime spDT = (SPFieldDateTime)spdocLib.Fields["Created"];
spDT.ReadOnlyField = false;
spDT.Update();
spdocLib.Update();

SPListItem myitem = spdocLib.Items.GetItemById(65);
object myval = myitem["Created"];
myitem["Created"] = DateTime.Now;
myitem.Update();
spdocLib.Update();

spDT.ReadOnlyField = true;
spDT.Update();
spdocLib.Update();
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
}
}

2nd Option: SharePoint Web Services

public void ToggleReadOnly(string DestinationSiteURL, string DestinationLibrary, bool ReadOnly)
{

if (!DestinationSiteURL.EndsWith("/"))
DestinationSiteURL += "/";

DestinationLibrary = DestinationLibrary.Replace("/", "");

string XML;

XML = "<Method ID='1'>";
XML += "<Field Name=\"Created\" DisplayName=\"Created\" Group=\"_Hidden\" Type=\"DateTime\" ReadOnly=\"" + ReadOnly.ToString().ToUpper() + "\" Required=\"FALSE\" Format=\"DateTime\" StaticName=\"Created\">";
XML += "</Field>";
XML += "</Method>";

string ListVersion;

XmlNode ndUpdate = new XmlDocument().CreateNode(XmlNodeType.Element, "Fields", "");
ndUpdate.InnerXml = XML;

XmlNode List;
XmlNode ndReturn;

using (Lists.Lists SPLists = new Content_Migrator.Lists.Lists())
{
SPLists.Credentials = _frmContentMig.DCred;
SPLists.Url = DestinationSiteURL + "_vti_bin/Lists.asmx";

List = SPLists.GetList(DestinationLibrary);

ListVersion = List.Attributes["Version"].Value;

ndReturn = SPLists.UpdateList(DestinationLibrary, null, null, ndUpdate, null, ListVersion);
}
}


They are fairly easy to use it just which ever makes sense.

No comments:

Post a Comment