Monday, November 12, 2007

Getting the url of the list

Hello!

I was faced with a small problem the other day. In an external database the url to a content item, such as a document, discussion thread or a wiki page, was to be stored in several parts; the url to site, the url to the list and finally the url to the list item.
The easy part was the site and the item urls since the come out of the SPItemEventProperty of the event handler I was working in. But when it came to the list, it was something different. I.e. the user can change the Title of the list and therefore the title cannot be used. There are several ways of doing this, but the way I choose was this method;
First, get the value of the field named "Encoded Absolute URL" which out of the SPItemEventProperty.ListItem. This url is the exact url SharePoint will use when a user click on a link for that item.
Decoding and encoding this url is necessary for what I did next, taking the substring of this url and removing the site url and the item url will get you the url for the list.
Below is a code example of what I did;

                /* First, encode the property from the event handler */
                string siteUrl = SPEncode.UrlEncodeAsUrl(properties.WebUrl);

                /* Next, get the absolute url from the ListItem property and decode at the same time*/
                string absoluteItemUrl = SPEncode.UrlDecodeAsUrl(properties.ListItem["Encoded Absolute URL"].ToString());

                /* Encode the url to get the absolute url in the same encoding as the web url */
                absoluteItemUrl = SPEncode.UrlEncodeAsUrl(absoluteItemUrl);

                /* Next, get the substrings to leave only the list url */

                string temp = absoluteItemUrl.Substring(siteUrl.Length);
                string tempUrl = temp.Substring(0, temp.LastIndexOf('/') + 1);

Posted by Zeb at 16:05:36 | Permanent Link | Comments (0) |