2

When you access a list using web.Lists["Title"], you depend on list title being unchanged. What are the best practices for preventing such failures?

4 Answers 4

1

Just to add a SharePoint 2010 slant here - this issue becomes even more important if you have code which uses Linq, since there you have generated classes against the current schema of the list, and failures will occur if this schema changes and the classes are not in sync.

My recommendation here is:

  • Lists which have Linq or similar code written against them should be permissioned such that users cannot make such schema changes
  • There is a 'list schema changed' event in SharePoint 2010 which can be used to trap this happening

I prefer the first option though. Suggest that's a good way to treat lists which have code written against them, they are effectively 'system/application lists'.

4

Option 1. Use list GUID for indexing.

This method may fail if the list is recreated from a template.

2
  • As Ovidiu Becheş-Puia pointed below, this method may fail if the list is recreated from a template. In this case, the new list will have a new GUID. Jan 21, 2010 at 12:18
  • Unfortunately, I agree you're stuck with GUIDs. Jan 25, 2010 at 1:05
2

Option 2. Use the List's Web Relative Url which doesn't change and the web.GetViewFromUrl(url) method.

Example:

SPList list = web.GetViewFromUrl(web.Url + "/Lists/" + listTitle + "/AllItems.aspx").ParentList;
SPList doclib = web.GetViewFromUrl(web.Site.Url + web.ServerRelativeUrl + "/" + doclibTitle + "/Forms/AllItems.aspx").ParentList;

This will break if the default (AllItems.aspx) view Url is no longer available for the list which is possible but less likely than the List title being changed.

This method may also fail if someone changes the List URL using SharePoint Designer which is even less likely, but still possible.

1

There is no perfect solution, user should have contribute rights only. User who rename lists is an admin.

Option 1: if you save the site as a template (stp) and create from that template a new one, you will get a new guid for the list.

Option 2: changing url is possible using SPD and

      web.Site.Url + web.ServerRelativeUrl = web.Url !
      you also have SPList.RootFolder.Url instead of that "dangerous" concatenation !
1
  • Good point about saving as template. Well known, but always nice to be reminded of. As for the second comment, yes, you have the RootFolder property you can get <b>from</b> the instance of the list, but here Option 2 was introduced to get <b>the</b> instance you don't have yet. So the concatenation may be "dangerous" but necessary for the goal. Jan 21, 2010 at 11:47

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.