Tuesday, May 08, 2012

Sorting Attached files in SharePoint List Item

Recently I have a requirement to sort the attached files those attached into SharePoint List Item. I have an application page to retrieve these collection of files by passing the item's id in page "Bulletted List" control has been used and set the property as hyper link.

Uploading the attachment into this Item also done through SharePoint Object Model.It's simply works fine on retrieving and showing them in ASP.NET's bulleted control.Later out business requirement got changed.They wanted these attached files were sequentially ordered and displayed so.

I tried many approaches to sort these files using Generic Classes in C# . I found lot of useful methods using LinQ,SortedList,KeyValuePair,Dictionary and SortedDictionary.But I need to implement in ASP.NET 2.0 only.

Still I found no luck :)- on my sorting tasks on attached files.But the development environment is verily limited to ASP.NET 2.0. Couple of day later,I started to think of actual index in attachment collection in sharepoint list item. When I checked the item and its view mode.I found all of the attached files were randomly ordered still I could not pin point in what basis these were ordered.

Sorting based on "File Info" ???.

On Checking on SPAttachmentCollection class I found its just name of the attached files array not even the file object.So I get the URL for each of this files and assigned to SPFile.

Now I have "TimeCreated" property of this SPFile.I pass these file names and its time of creation into Dictionary class to sorting. Interesting Dictionary class can only sorting the collection of items by "Key" not as value.But I need to sorting by value "TimeCreated". But If I wanted to sorting based on "TimeCreated" property,every time an end user need to create new file and upload.If they upload old files it won't make any sense and won't be end user friendly.

So I need to check alternate way of sorting this files.May be I need to use ICollection class to sort the attachment collection.

Anyhow ASP.NET 3.5 enables this task very simple by few lines of code.

 SPSite site = SPContext.Current.Site;
            SPWeb web = site.OpenWeb();
            SPList list = web.Lists["Friends"];
            SPListItem item = list.GetItemById(1);
            Dictionarydictionary = new Dictionary();
            SPAttachmentCollection attachments = item.Attachments;

            foreach (string fileName in attachments)
            {
                SPFile file = web.GetFile(attachments.UrlPrefix + fileName);
                dictionary.Add(file.Name.ToString(), file.TimeCreated);
            }
             List> sorted = (from sp in dictionary orderby sp.Value select sp).ToList();
            ListBox1.DataSource = sorted;
            ListBox1.DataBind();
            ListBox1.DataSource = sorted;
            ListBox1.DataBind();