6

I'm trying to add a new item to the Web property bag using the SharePoint managed client object model, but it fails to persist. I'm using the following code:

 using (var context = new ClientContext("http://projectdev:82/PWA"))
 {
     var web = context.Web;
     context.Load(web);

     var allProperties = context.Web.AllProperties;
     context.Load(allProperties);

     context.ExecuteQuery();

     if (!allProperties.FieldValues.ContainsKey(CONNECTION_STRING_KEY))
     {
         allProperties.FieldValues.Add(CONNECTION_STRING_KEY, "Test");
     }

     context.Web.Update();
     context.ExecuteQuery();
 }
SPArcheon
  • 6,868
  • 1
  • 30
  • 47
iulianchira
  • 163
  • 1
  • 4
  • I have the equivalent working code in JavaScript, I use get_fieldValues()[someProp] to read properties, but to add/set properties I must call set_item(someProp, someValue). Although I can not see set_item in the C# version – eirikb Oct 18 '12 at 05:56

2 Answers2

11

Here you go:

using (var context = new ClientContext("http://localhost"))
{
  var allProperties = context.Web.AllProperties;
  allProperties["testing"] = "Hello there";
  context.Web.Update();
  context.ExecuteQuery();
}
eirikb
  • 7,405
  • 5
  • 35
  • 67
0
SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite currentSiteCollection = new SPSite("http://myserver/mysite"))
 {
    using (SPWeb currentWeb = currentSiteCollection.OpenWeb())
    {
        // unsafe updates are required to be able to write to the property bag
         currentWeb.AllowUnsafeUpdates = true;
         if (!currentWeb.AllProperties.ContainsKey(key))
            currentWeb.Properties.Add(key, value.Value.ToString());
        else
            currentWeb.AllProperties[key] = value;

        // update the properties
        currentWeb.Properties.Update();
        currentWeb.AllowUnsafeUpdates = false;
    }
  }
});

you can get more information from this blog: http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2008/05/12/how-to-write-a-value-into-the-property-bag.aspx

hope this helps!

Anuja
  • 3,103
  • 4
  • 23
  • 27
  • 1
    I think iulianchira is asking specifically for Client Object Model. And the statement that "AllowUnsafeUpdates are required" is plainly wrong. And I don't think one needs to call ...Properties.Update(). This worked fine for me: web.AllProperties.Add("testing", "Hello");web.Update(); – eirikb Oct 18 '12 at 05:38
  • This is the classic API, the server model, since my code runs from outside the SharePoint farm, I cannot use it. – iulianchira Oct 22 '12 at 16:26