Wednesday, May 25, 2011

Creating multi level discussion groups programmatically

Recently, I was required to create a multiple level discussion groups.

As we know, Sharepoint 2010 offers only one level of Discussion group (at least as far as I know) i.e., First level is Discussion Group and the inner level is Discussion Threads (individual posts).


What did I do, I create the discussion group programmatically and move the created group under an existing discussion group. This way, I was able to achieve multiple levels of discussion groups.

 var web = SPContext.Current.Web;    
 var discussionList = web.Lists[DISCUSSION_LIST_NAME];
 var discussionContentType = 
web.AvailableContentTypes[DISCUSSION_CONTENT_TYPE_NAME];
 
web.AllowUnsafeUpdates = true;
  
 var newDiscussionItem = SPUtility.CreateNewDiscussion(discussionList, title);
 newDiscussionItem["Title"] = title;
 newDiscussionItem["ContentTypeId"] = discussionContentType.Id;
 newDiscussionItem["ContentType"] = discussionContentType.Name;
newDiscussionItem.Update();
 
 //if the discussion group is a child discussion (Thread) 
 //then move the discussion group 
 //to a sub level (under its parent discussion group)
 if (parentDiscussionID != -1)
 {
    var parentDiscussionGroup = discussionList.GetItemById(parentDiscussionID);
    var destinationUrl = parentDiscussionGroup.Url + "/" 
+ newDiscussionItem.Folder.Name;
    newDiscussionItem.Folder.MoveTo(destinationUrl);
 }
 web.AllowUnsafeUpdates = false;
 
 
Using the above method of .Folder.MoveTo() any SPListItem can be moved to any destination. Hope this would help someone else.

Friday, May 6, 2011

Save a PublishingPage programmatically

We are trying to do edit and save page functionality for a publishing page programmatically. I was facing an issue where the page content is not getting updated when check-in the page programmatically. As we know the below code checks in and publishes any SharePoint item into the library.

SPContext.Current.ListItem.File.CheckIn("Page edited at: " + DateTime.Now,  
                                                SPCheckinType.MajorCheckIn);
SPContext.Current.ListItem.File.Publish("Published page at: " + DateTime.Now);

When I run the above code, the page gets checked in and gets published but the content is not getting updated in the page. To achieve that, I had to add the below code to save the contents of the page before check-in and publish the SharePoint item.

Microsoft.SharePoint.WebControls.SaveButton.SaveItem(SPContext.Current, 
                                         false"Saved at: " + DateTime.Now);

This one works fine for me. Hope this helps some one else too.