Thursday, May 19, 2011

Discussion board multiple item threaded view

Scenario:
Discussion board has a great 'Threading' view , but limited to display only one time.
We had a requirement to display multiple items in threaded view. I searched a lot but nothing helpful.

Solution:
Wrote a quick console application.

Code:

using System;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;

namespace SPSandeep.ConsoleApplication
{
class Program
{
public static DataTable dt = null;

static void Main (string[] args)
{
using (SPSite site = new SPSite("http://ws2003/credit"))
{
using (SPWeb web = site.OpenWeb())
{
SPList mainList = web.Lists["Team Discussion"];

foreach (SPListItem folder in mainList.Folders)
{
Console.WriteLine("Folder Name: " + folder.Name);
Console.WriteLine("Folder ID: " + folder.ID);

// Read body of attachment
Console.WriteLine("Body: " + folder.Fields["Body"].GetFieldValueAsText(folder["Body"]));
Console.WriteLine("Threading: " + folder.Fields["Threading"].GetFieldValueAsText(folder["Threading"]).Length);
Console.WriteLine("=============================");

RenderAllReponses(mainList, folder.ID);

Console.WriteLine("=============================");
}
}
}

Console.ReadKey();
}

public static void RenderAllReponses (SPList mainList, int parentID)
{
SPQuery query = new SPQuery();
query.Query = string.Format("<Where><Eq><FieldRef Name='ParentFolderId' /><Value Type='Number'>{0}</Value></Eq></Where>", parentID.ToString());
query.ViewFields = @"<FieldRef Name='ows_ParentFolderId' /><FieldRef Name='Threading' /><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='Body' />";
query.ViewAttributes = "Scope='RecursiveAll'";
dt = mainList.GetItems(query).GetDataTable();

if (null != dt)
{
foreach (DataRow listItem in dt.Rows)
{
if (listItem["Threading"].ToString().Length == 56)
{
RenderResponse(listItem, 56);
}
}
}
}

public static void RenderResponse (DataRow listItem1, int length)
{
DataRow[] listItems = dt.Select(string.Format("Threading Like '{0}*' AND LEN(Threading)={1}", listItem1["Threading"], length));

foreach (DataRow item in listItems)
{
Console.WriteLine("Item DisplayName: " + item["Title"]); // Returns Title of Discussion
Console.WriteLine("List ID: " + item["ID"] );
//Console.WriteLine("List Folder ID: " + listItem["ParentFolderId"] + "<BR>"); // Returns ID of Parent Discussion
Console.WriteLine("Body: " + item["Body"]);
Console.WriteLine("Threading: " + item["Threading"].ToString().Length );
int newLength = length + 10;
RenderResponse(item, newLength);
}
}
}
}

0 comments: