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

Seven steps to build and deploy SPFX web part to SharePoint

Install Node.JS Use this link to install Node.JS https://nodejs.org/en/ 2.        Install yeomen and gulp CMD>npm install –g y...