In many scenarios, it is useful to have a system-generated unique
identifier for all items contained within a site. For example, you may
wish to create a unique identifier for all records submitted to the
Records Center. Regardless of which library that the record is stored,
each record contained within the site has a unique identifier.
SharePoint generates an ID for each item in a list, but these ID's are
repeated in each list or library and are not unique across the site.
Internally SharePoint creates a unique GUID for each item, but it is not
exposed to the end user, and even if it were, GUID's are not very
user-friendly.
Implementation of our unique ID includes a list for
maintaining the value, and an event handler for retrieving and setting
the value.
private static int GetUniqueId(SPWeb web) { int returnValue = -1; int retryCounter = 0; int uniqueId = -1; try { // Get the list and list item SPList list = web.Lists["Counter"]; SPListItem item = list.Items[0]; // Get the value for the unique id uniqueId = int.Parse(item["Title"].ToString()); // Increment and update the value item["Title"] = uniqueId + 1; item.Update(); // Set the value to return returnValue = uniqueId; } catch (Exception ex) { // Handle the exception by retrying 5 times retryCounter += 1; if (retryCounter <= 5) { System.Threading.Thread.Sleep(2500); goto ReTry; } else { // Write the exception to the log } } return returnValue; }
public override void ItemAdding(SPItemEventProperties properties) { base.DisableEventFiring(); try { using (SPWeb web = properties.OpenWeb()) { // Set the unique id value on the item properties.AfterProperties["MyUniqueId"] = GetUniqueId(web); } } catch (Exception ex) { } finally { base.EnableEventFiring(); } base.ItemAdding(properties); }
No comments:
Post a Comment
Thank you for Commenting Will reply soon ......