Code Blocks Inside Master Pages

Some time ago I kept getting this error in one of the projects I was working on:

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

I spent quite some time trying to figure it out. Finally after hours of searching I found out that Code Blocks Inside Master Pages Cause Trouble.

I was using code blocks inside the head tag of all the MasterPages to resolve paths at runtime:

<link rel="stylesheet" href="<%= ResolveUrl("~/myStyleSheet.css") %>" type="text/css" />
<script type="text/javascript" src="<%= ResolveUrl("~/myJavaScript.js") %>"></script>

Fortunately Milan Negovan proposed a quick workaround which saved a lot of time.

Basically, the workaround is to change the code blocks to data binding expressions (<%# … %>).

<link rel="stylesheet" href="<%# ResolveUrl("~/myStyleSheet.css") %>" type="text/css" />
<script type="text/javascript" src="<%# ResolveUrl("~/myJavaScript.js") %>"></script>

and adding this to the master page code behind:

protected override void OnLoad (EventArgs e)
{
  base.OnLoad (e);
  Page.Header.DataBind ();
}

Since HtmlHead ultimately derives from Control and everything that derives from Control has a DataBind() method, adding that one line above would force the header to resolve data binding expressions.

Thats it, that does the trick!

How to setup an asp.net website on localhost

First lets start by setting up the site in IIS…

1.Open IIS by double-clicking on Control Panel->Administrative Tools->Internet Information Services

2.Right Click on Web Sites->Default Web Site

3.Click on Properties->Home Directory and choose the location of your website

Now lets give the ASPNET account the appropriate permissions to access that directory…

  1. Using My Computer or the Windows Explorer, navigate to the folder containing the website you choose in the previous step

  2. Right click on the folder and and go to Properties->Security

  3. On the Security tab, click on Add to locate the ASPNET account

  4. Click on Locations and select the local machine

  5. Click on Advanced->Find Now to list all the user accounts on your local machine

  6. Choose ASPNET and click on OK. (If you don’t see ASPNET account in there, go to step 11)

  7. Return to the security tab. Select the ASPNET user account and check the Full Control checkbox under the allow column. Click OK.

  8. Thats it! You should now be able to go to http://localhost/ in your browser window and see your website.

If you don’t see an ASP.NET account in Step 8 then…

  1. Run “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ aspnet_regiis.exe -i -enable” in the command line window and then repeat steps 1 through 10.

Following steps are optional. They help you configure your web project to automatically reference the local web-server when you run or debug a site instead of launching the built-in web-server itself…

  1. Open Visual Studio and select your web-project in the solution explorer, right click and select Property pages.

  2. Select the Start Options from the left navigation, and under Server change the radio button value from ‘Use default Web server’ to ‘Use custom server’. Then set the Base URL value to be: http://localhost/

Now, when you click on any page in the app and then hit F5 or Ctrl-F5, the IDE will use the local web-server instead of popping up its own.

How To Load & Reference An Usercontrol From Code Behind

First lets create a sample user control called MyControl for demonstration purposes

public partial class _Controls_MyControl : System.Web.UI.UserControl
{
    private string _myProperty;

    public string MyProperty
    {
        get { return _myProperty; }
        set { _myProperty = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Now register this control in the web.config

<pages>
  <controls>
    <add tagPrefix="uc" tagName="MyControl" src="~/_Controls/MyControl.ascx"/>
  </controls>
</pages>

Now this is the most important part, you have to reference your user control in the .aspx page to be able to access its partial class members -

<%@ Reference Control="~/_Controls/MyControl.ascx" %>

Now finally lets instantiate and load the control from the code behind…

_Controls_MyControl myControl = (_Controls_MyControl)LoadControl("~/_Controls/MyControl.ascx");
myControl.MyProperty = "Hello World!!";
Page.Controls.Add(myControl);

That’s it

How To Clear All Items From Cache

if (Cache.Count > 0)
{
	string currentKey = string.Empty;
	System.Collections.IDictionaryEnumerator cacheContents =
	System.Web.HttpContext.Current.Cache.GetEnumerator();

	Response.Write(string.Format("Following {0} cache keys were cleared:<br /><br />", Cache.Count));

	while (cacheContents.MoveNext())
	{
		currentKey = cacheContents.Key.ToString();
		Response.Write(currentKey + "<br />");
		System.Web.HttpContext.Current.Cache.Remove(currentKey);
	}
}
else
{
	Response.Write("Nothing to clear. Cache is empty.");
}

ASP.NET Inline Tags

There are all sorts of different inline tags, and I haven’t found a place that explains them all in one place, so here is the quick and dirty…

<% ... %>

The most basic inline tag, basically runs normal code:

<% if (User.IsInRole(“admin”)) { %> You can see this
<% } else { %>
You are no admin fool!
<%} %>

http://msdn2.microsoft.com/en-us/library/ms178135(vs.80).aspx

<%= ... %>

Used for small chunks of information, usually from objects and single pieces of information like a single string or int variable:

The Date is now <%= DateTime.Now.ToShortDateString() %>
The value of string1 is <%= string1 %>

http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx

*note: <%= is the equivalent of Response.Write() -  Courtesy of Adam from the US,thanks!

<%# .. %>

Used for Binding Expressions; such as Eval and Bind, most often found in data controls like GridView, Repeater, etc.:

<%# Eval("MeetingName") %>

http://msdn2.microsoft.com/en-us/library/ms178366.aspx

<%$ ... %>

Used for expressions, not code; often seen with DataSources:

http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx

<%@ ... %>

This is for directive syntax; basically the stuff you see at the top your your aspx pages like control registration and page declaration:

<%@ Page Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” Title=”Untitled Page” %> <%@ Register TagPrefix=”wp” Namespace=”CustomWebParts” %>

http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx

<%- ... -%>

This is a server side comment, stuff you don’t want anyone without code access to see:

<%- sometimes end users make me angry -%>

http://msdn2.microsoft.com/en-us/library/4acf8afk.aspx

And that’s that.

Source: Naspinski