Saturday, May 24, 2008

Programming Lists

Lists and Libraries in the Object Model

  • SPList
  • SPDocumentLibrary
  • SPListItemCollection
  • SPListItem
  • SPQuery
  • SPSiteDataQuery

Retrieving List Instances

  • SPWeb.Lists collection
    • This returns a SPListCollection of all lists in a site
    • Can access a specific list within a collection
  • SPWeb.GetList method
    • This returns a SPList from Url of the list or any list form
  • SPWeb.GetListOfType method
    • This is a SPListCollection filtered by SPBaseType enum
  • SPWeb.GetListFromUrl, SPWeb.GetListFromWebPartPageUrl
    • From previous version of Sharepoint. Do not use. Use GetList instead.

Enumerating List Items

  • Items.GetDataTable()
    • This returns a copy of the list data as ADO.NET DataTable
    • Updates to the DataTable do not affect the list
    • Good for binding to grids
  • foreach (SPListItem item in SPList.Items)
    • Works directly against list data
    • Items are updatable
    • Provides full access to item properties

Reading and Setting Field Values

  • Read via DataTable
  • Read / Write via
    • Item[int ordinal]
    • Item[Guid File]
    • Item[string DisplayName]

Creating Lists Programmatically

  • Create SPList instance with SPWeb.Add(Title, Description, List Type)
  • Set properties
    • Quick launch
    • Security
    • Search Settings
    • Etc.
  • Call SPList.Update()

Add Items Programmatically

  • Create SPListItem instance with SPList.Items.Add()
  • Set values
    • SPListItem["field1"] = value;
  • Call SPListItem.Update();

AllowUnsafeUpdates

  • SPSecurity.RunWithElevatedPrivileges is not enough
  • Explicitly allow updates to the database without a security validation
  • When elevating privileges and updating any site or web element, you need to set
    • SPSite.AllowUnsafeUpdates = true or
    • SPWeb.AllowUnsafeUpdates = true
  • This is important because when you developing in general you will be using the administrator account. When you call RunWithElevatedPrivileges, it will work. But when you log in as somebody else who does not have access to the Lists, you will get an access denied error if you don't set the AllowUnsafeUpdates to true.
blog comments powered by Disqus