Viewing SharePoint Webparts in Frontpage

I’ve recently been developing a lot of web parts for SharePoint at work. According to the Microsoft best practices for web part development they suggest you implement the IDesignTimeHtmlProvider interface. This means you need to implement a function called GetDesignTimeHtml(). This allows you to define the html output to display when editing a sharepoint page in frontpage editor. A lot of web parts I have downloaded on the web don’t seem to implement this because they show up in frontpage saying “The Preview for this Web Part is not available”. I also had a hard time implementing this since the GetDesignTimeHtml expects a string of html and when using webparts you are rendering user controls lots of times. I finally found an easy way to render almost any webpart in frontpage.

 

public virtual string GetDesignTimeHtml()
{
	StringWriter sw = new StringWriter();
	HtmlTextWriter tw = new HtmlTextWriter(sw);
	try
	{
		CreateChildControls();
		RenderWebPart(tw);
	}
	catch(Exception e)
	{
		sw.Write(e.Message + e.StackTrace);
	}
	return sw.ToString();
}

 

Basically in this function you will need to call any other functions/events that normally get called in the webpart execution (such as CreateChildControls). Then using the htmltextwriter and string writer you can output the html that would be rendered. I included the try catch so I can see the errors that are displayed when trying to render a webpart in frontpage. When in production you should probably remove the try catch so the end user sees a more friendly error message.

Something I did notice was frontpage seems to run the page in a different context than the page is normally rendered. This means that when I was trying to access Page.User.Identity.Name I got an error in frontpage. So I had to use the SPControl.GetContextWeb(Context).CurrentUser.LoginName instead. I also noticed that because frontpage loads it in a different context that when loading an Itemplate from an external ascx file, I got the error saying “The virtual path” and then whatever the path is to my ascx file “maps to another application, which is not allowed”.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*