Extension methode for web.AllowUnsafeUpdates

How we do it:

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWebweb = 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 (SPWebweb = 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(thisSPWeb web, Actionaction)
        {
            bool allowUnsafeUpdates = web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            action();
            web.AllowUnsafeUpdates = allowUnsafeUpdates;
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s