donderdag 22 oktober 2009

SharePoint 2007 Content Editor bug + solution

The content editor web part is a great OTB web part to add publishing content to a page. The problem is that even if you insert relative links to recources in your site collection, SharePoint will always make them absolute upon saving.
You could think: "What's so special/bad about that?". The problems start when organizations want to start using content deployment. This great publishing feature copies your content over farms (ideal for staging - production scenarios) and Microsoft has perfected the process all the time making it quiet solid at this moment (SP2).
Of course, when you start viewing your content on production, links could still be pointing to staging. In many of these scenarios, the production system will be anonymously accessible and they will be prompted for a login when they access staging material. To solve this you can use a Control Adapter which will override the render method of any control you specify.

Here's the code:
public class ControlAdapter: ControlAdapter
{

protected override void Render(System.Web.UI.HtmlTextWriter writer)
{

String appSettingFilter = ConfigurationManager.AppSettings["ControlAdapterFilter"];

if (!String.IsNullOrEmpty(appSettingFilter))
{

StringBuilder sb = new StringBuilder();
HtmlTextWriter htw = new HtmlTextWriter(new StringWriter(sb));
base.Render(htw);

// Make all URLs relative
//Regex regex = new Regex("((?:href|src)=\")https?://[^/]+([^\"]+\")");
string output = sb.ToString();

if (sb.ToString().Contains(appSettingFilter))
output = sb.ToString().Replace("http://" + appSettingFilter, "");

writer.Write(output);

}

}

}


As you can see, the class inherits from ControlAdapter and will override the Render method. In here you can put smart logic which will take care of the absolute links in your content editor web part.
I actually added two kinds of logics. The first one, which is in comment, makes any URL it finds, relative.
The second option, which uses the appSetting from the web.config, only makes URL's starting with this prefix relative.

Adjusting your web.config:
In the tag add your own assembly like:
<add assembly="MyAssembly" />

Adjusting the compat.browser file:
This file can be found in your web application's home directory in the App_Browsers folder. In there you specify which particular web control needs its render method to be overwritten. You can do something like this:
<browser refID="Default">
<controladapters>
<adapter controlType="Microsoft.SharePoint.WebPartPages.ContentEditorWebPart" adapterType="MyAssembly.ControlAdapter" />
</controlAdapters>
</browser>


You can also add a line for example the RichHtmlField controls. In this case it can be that SharePoint will not be able to find the Microsoft.SharePoint.Publishing.dll. Copying it to the bin folder solves this.

Hope it will come in handy some time!

Geen opmerkingen:

Een reactie posten