Thursday, February 2, 2012

Sharepoint Discussion list : Retreive items from discussion list programmatically

Here is the sample on retrieving data from sharepoint discussion list programamtically. The below sample retrieves data based on the user name and the date of the post/reply to the post

            string url = "http://siteURL/";   // Your Site url
            string listName = "Team Discussion";//Discussion List name
            using (SPSite site = new SPSite(url))
            {
                using (SPWeb oWebsiteRoot = site.OpenWeb())
                {
                    SPList list = oWebsiteRoot.Lists[listName];
                    SPListItemCollection allPosts = list.Folders;

                    SPQuery qry = new SPQuery();
                    qry.ViewAttributes = "Scope=\"Recursive\"";
                    SPListItemCollection allReplies = list.GetItems(qry);

                    List<SPListItem> allItems = allPosts.OfType<SPListItem>().Union(allReplies.OfType<SPListItem>()).ToList<SPListItem>();

                    string createdBy = "username";
                    string startDt = "1/12/2012";
                    string endDt = "1/14/2012";

                    DateTime dtStart = Convert.ToDateTime(startDt);
                    DateTime dtEnd = Convert.ToDateTime(endDt);

                    IEnumerable<SPListItem> finalList = from n in allItems.OfType<SPListItem>()
                                                      where n["Created By"].ToString().Split('#')[1] == createdBy && (Convert.ToDateTime(n["Created"]) >= dtStart && Convert.ToDateTime(n["Created"]) < dtEnd)
                                                      select n;

                    foreach (SPListItem x in finalList)
                   {
                        Console.WriteLine("Title=" + ((x.Name== "") ? "Reply from "+x["DiscussionTitle"] : x["Title"]));
                    }
                    Console.WriteLine("---Program Completed. Press enter to exit-----");
                    Console.ReadLine();
                }
            }

No comments:

Post a Comment