Monday, December 16, 2013

Extension methode for web.AllowUnsafeUpdates


How we do it:

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                        web.AllowUnsafeUpdates = true;
                        SPList list = web.Lists.TryGetList("TestExtensionList");
                        SPListItem item = list.Items.Add();
                        item[SPBuiltInFieldId.Title] = TextBox1.Text.Trim();
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                }

            }

How we can do it:


using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.DoUnsafeUpdate(delegate()
                    {
                        SPList list = web.Lists.TryGetList("TestExtensionList");
                        SPListItem item = list.Items.Add();
                        item[SPBuiltInFieldId.Title] = TextBox1.Text.Trim();
                        item.Update();
                    });  
                }
            }



Extension Methode to achieve the above code pattern:

public static class ExtensionMethodeClass

    {
        public static void DoUnsafeUpdate(this SPWeb web, Action action)
        {
            bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            action();
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }
    }

No comments:

Post a Comment

SharePoint document metadata not updating

I faced a weird issue today, Metadata for document which has lookup column was not updating even after saving the item. There was no erro...