A few people have posted on the SharePoint newsgroups about writing inline c# code in SharePoint 2007 masterpages. I’m certainly not saying this is a best practise, and there are many different ways to skin a cat, but if you do want to add inline c# into default.master or any other masterpage (or content layout page), these are the basic steps.
Open up SharePoint Designer and the masterpage you want to edit. Switch to the code view and anywhere from the first <head> tag down you can add some inline c# code:
<script runat="server">
string myVar = "hello world!";
void Page_Load(object sender, System.EventArgs e)
{
Response.Write(myVar);
SPSite siteCollection = new SPSite("http://usb-server1");
SPWeb site = siteCollection.OpenWeb("/SiteDirectory/MainCalendar/");
SPList list = site.Lists["Announcements"];
SPListItemCollection items = list.Items;
foreach(SPListItem item in items)
{
Response.Write(item["Title"].ToString());
Response.Write("<br/>");
}
}
</script>
Doesn’t do anything amazing but does show you can use the SharePoint object model in your inline code. If you saved the masterpage now and opened the site in your browser you’d get an error about not being able to run code blocks. There’s an extra line you need to put into your web.config file first to allow this inline c# to execute.
<PageParserPaths>
<PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" IncludeSubFolders="true" />
</PageParserPaths>
The PageParserPaths xml tags will be there already you just need to add the line in between. Save web.config and off you go. Your pages will render properly and the c# inline code will execute.
Again I’d like to point out that this is possibly not good practise. The fact that CompilationMode being set to ‘Always’ points out that there may be a performance hit and cache’ing won’t exactly work well. But if you need to, that’s how to do it.
Thanks to Ben Robb for discussing this on messenger with me. Ben should have his own blog soon and I know he’s got some great stuff to post.