maandag 22 oktober 2007

NavigationWebPart

Today I received the assignment to update a WebPart to SharePoint 2007 format.The WebPart we are talking about is the NavigationWebPart made by Jan Tielens. You can find the orignial post here

My first thought was to rewrite the whole code to make a completely new WebPart but after a while
I realized that with some modifications the code would work just as good.
So I started by removing some code and commments I didn't realy need for my assignment out of the orignial code.
Afterwards I changed the functions to make it work with SharePoint 2007

The final result looks like this.

using System.Web.UI;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace NavigationWebPart
{
public class NavigationWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
private int _levels = 5;
private bool _startFromRoot = true;


[WebBrowsable(),
Personalizable(),
System.ComponentModel.Category("Navigation"),
WebDescription("How many levels do you want to allow."),
WebDisplayName("Levels"),
DefaultValue(5)]
public int Levels
{
get { return _levels; }
set { _levels = value; }
}

[WebBrowsable(),
Personalizable(),
System.ComponentModel.Category("Navigation"),
WebDescription("Start from root."),
DefaultValue(true)]
public bool StartFromRoot
{
get { return _startFromRoot; }
set { _startFromRoot = value; }
}

protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write("<table border=0 width=100%>");
SPWeb web = SPControl.GetContextWeb(Context);
SPWebCollection subWebs = null;
writer.Write("<tr><td>");
if (StartFromRoot)
{
SPWeb rootWeb = SPControl.GetContextSite(Context).RootWeb;
subWebs = rootWeb.GetSubwebsForCurrentUser();
writer.Write("<a href='{0}'><b>{1}</b></a>", rootWeb.Url, rootWeb.Title);
}
else
{
writer.Write("<a href='{0}'><b>{1}</b></a>", web.Url, web.Title);
subWebs = web.GetSubwebsForCurrentUser();
}
writer.Write("</td></tr>");
writer.Write("<tr><td>");
writer.Write("<ul>");
foreach (SPWeb childSite in subWebs)
{
if (web.ID != childSite.ID)
{
writer.Write("<li><a href='{0}'>{1}</a></li>", childSite.Url, childSite.Title);
RenderWeb(writer, childSite, 1);
}
}
writer.Write("</ul>");
writer.Write("</td></tr>");
writer.Write("</table>");
}

private void RenderWeb(HtmlTextWriter writer, SPWeb web, int currentLevel)
{
SPWebCollection subWebs = web.GetSubwebsForCurrentUser();
writer.Write("<ul>");
foreach (SPWeb childSite in subWebs)
{
if (web.ID != childSite.ID)
{
if (currentLevel < this.Levels)
{
writer.Write("<li><a href='{0}'>{1}</a></li>", childSite.Url, childSite.Title);
int newLevel = currentLevel + 1;
RenderWeb(writer, childSite, newLevel);
}
}
}
writer.Write("</ul>");
}
}
}

Build and deploy this code like you would do with any other WebPart and you have a working NavigationWebPart again.
Thanks to some great code already existing and to some modifications.

Geen opmerkingen: