5

from the below codes, which one is best practice and performance wise also:-

CASE 1:

using (SPSite oSPsite = new SPSite("http://website url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
            oSPWeb.AllowUnsafeUpdates = true;

            // Fetch the List
            SPList list = oSPWeb.Lists["MyList"];

            //Add a new item in the List
            SPListItem itemToAdd = list.Items.Add();
            itemToAdd["Title"] = "Test Title";
            itemToAdd["Description"] = "Test Description";
            itemToAdd.Update();

            // Get the Item ID
            listItemId = itemToAdd.ID;

            // Update the List item by ID
            SPListItem itemToUpdate = list.GetItemById(listItemId);
            itemToUpdate["Description"] = "Changed Description";
            itemToUpdate.Update();

            // Delete List item
            SPListItem itemToDelete = list.GetItemById(listItemId);
            itemToDelete.Delete();

            oSPWeb.AllowUnsafeUpdates = false;
       }
}

Reference: http://www.mindfiresolutions.com/Add-Update-and-Delete-List-Items-Programmatically-in-Sharepoint-372.php

CASE 2:

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

SPListItem item = listItems.Add();

item["Title"] = TextBox2.Text;
item["Stock"] = Convert.ToInt32(TextBox3.Text);
item["Return Date"] = Convert.ToDateTime(TextBox4.Text);
item["Employee"] = TextBox5.Text;

item.Update();
}

Reference: http://msdn.microsoft.com/en-us/library/office/ms467435(v=office.14).aspx. There is no mention of allow unsafe updates in this code? Is that OK?

2
  • Was wondering why you won't use CSOM / JSOM?
    – Amit
    Commented Mar 21, 2014 at 7:05
  • What is the advantage>
    – variable
    Commented Mar 21, 2014 at 10:49

3 Answers 3

9

AllowUnsafeUpdates=true; is not required to add/delete/update list items unless you are doing these operations in Page_Load or other Get methods. Both CASE 1 and CASE 2 does not look good in terms of best practice. Problems with both case code:

Do not use oSPWeb.Lists["MyList"]; instead use oSPWeb.Lists.TryGetList("MyList1"); Do not use list.Items.Add(); instead use list.AddItem();

Always dispose objects (Best to use using(), done correctly in case 1, but try to avoid hard coded url if it is a webpart or user control etc)

Add null check for list object before using it.

Best practice code:

using (SPSite oSPsite = new SPSite("http://website url/"))//try not use hard code url unless no other option
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {
                    // Fetch the List
                    SPList list = oSPWeb.Lists.TryGetList("MyList1");
                    if (list != null)
                    {
                        //Add a new item in the List
                        SPListItem itemToAdd = list.AddItem();
                        itemToAdd["Title"] = "Test Title";
                        itemToAdd["Description"] = "Test Description";
                        itemToAdd.Update();

                        // Get the Item ID
                        listItemId = itemToAdd.ID;

                        // Update the List item by ID
                        SPListItem itemToUpdate = list.GetItemById(listItemId);
                        itemToUpdate["Description"] = "Changed Description";
                        itemToUpdate.Update();

                        // Delete List item
                        SPListItem itemToDelete = list.GetItemById(listItemId);
                        itemToDelete.Delete();
                    }
                }
            }

Always run sharepoint code analyser on your code.You can download it here

5
  • cool.. Can you provide any reference article for this..if possible
    – variable
    Commented Mar 21, 2014 at 6:41
  • 1
    Also, do a new SPSite("http://website url/") only if you are accessing list from another site. Otherwise for current site, SPContext.Current.Web is always a better choice. Commented Mar 21, 2014 at 6:41
  • @Nachiket best way to learn this is by running SPCAF(SharePoint Code analysis Framework) on your code. I have added link to download it in the answer.
    – Unnie
    Commented Mar 21, 2014 at 6:46
  • 2
    @VardhamanDeshpande Also keep in mind that SPContext does not exist in PowerShell. So when you have code (like a feature) that you want to activate through PowerShell, don't use SPContext. Bad example because features have their SPSite/Web/Others in the featureproperties. But Still :). Commented Mar 21, 2014 at 7:51
  • 3
    Should note that to get lists by Title is not the best choice always, since end users could change the Title. I usually use an extension on SPWeb for "TryGetList". Something like this: web.GetList(SPUtility.ConcatUrls(web.ServerRelativeUrl, "/Lists/MyList")) Commented Mar 21, 2014 at 9:39
2

Both look same apart from the fact that AllowUnsafeUpdates is used in the second example. However, the better way of adding list items is SPList.AddItem() instead of SPList.Items.Add() See this for more explanation: SPList.Add() vs SPList.AddItem() SharePoint 2010

1

A lot of things to note here:

  • In case #1, you open new SPSite/SPWeb objects (resulting in a need for AllowUnsafeUpdates). You open new objects only in case you want to run code in an elevation section (or with System user token, with leads more or less to the same result).
  • In both cases, you use list.Items.Add(); witch is a very bad practice: you consumme SQL resources to read all records in the list (may be 1000s of items!), network between SP and SQL, and SP RAM to load all these items... list.AddItem() is definitely the way to go.
  • You get access to the list with oSPWeb.Lists["MyList"]; witch may fail if the list is renamed. The only correct way to get a list for sure, even if it's renamed is:

    oSPWeb.GetList(SPUrlUtility.CombineUrl(oSPWeb.Url, listUrl))

listUrl being the site-relative URL of the list (e.g. Lists/Contacts).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.