Frederik Vig – ASP.NET developer

Follow me

Archive for the ‘ASP.NET’ Category.

Getting the Page and EPiServer CurrentPage object from HttpContext

Just a little quick tip when needing to use either the Page object or the EPiServer CurrentPage object from a class file. HttpContext.Current will give you access to the current request, what we can do is cast HttpContext.Current.Handler (since Page implements the IHttpHandler interface) to System.Web.UI.Page.

var page = HttpContext.Current.Handler as System.Web.UI.Page;
 
if (page != null)
{
    // do something with the page object
}

We can take this a step further and cast it to EPiServer.PageBase which gives us access to the CurrentPage object.

private static PageData CurrentPage
{
    get
    {
	var page = HttpContext.Current.Handler as EPiServer.PageBase;
 
	if (page == null)
	{
	    return null;
	}
 
	return page.CurrentPage;
    }
}

Visual Studio 2010 EPiServer Snippets

I finally got my hands on a copy of Visual Studio 2010 RC1! After playing around a bit, I stumbled across the new snippet functionality in Visual Studio 2010. You can now use snippets in the markup files as well (in previous versions you could only use the snippet functionality in code files like class/interfaces/code-behind files etc). This is very cool, and Microsoft has even included a few snippets for their ASP.NET controls and for HTML elements like: a, table, img, div etc. Quite a time saver!

To test the snippets out, simply type the shortcut (eg. ‘a’ or ‘table’) and press tab.

Visual Studio 2010 table snippet

Visual Studio 2010 table snippet

This is a simple, but very cool feature. Imaging all the typing you can get rid off!

Creating your own snippets

In Visual Studio 2010, under the Tools menu, you’ll find the Code Snippets Manager (ctrl+k, ctrl+b).

Visual Studio 2010 Code Snippets Manager

Here you can add new folders that contain your custom snippets, or check out the other snippets added by Microsoft. You’ll also see the path to the snippets folder (C:\Program Files (x86)\Microsoft Visual Studio 10.0\Web\Snippets\HTML\1033\ in my case). If you open up that folder in Windows Explorer you should see at least two folders there, ASP.NET and HTML. Inside both of these folders you’ll find the snippets for the ASP.NET web controls and for HTML elements. We can open up one of the files and take a look at the code.

<CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>image</Title>
    <Author>Microsoft Corporation</Author>
    <Shortcut>image</Shortcut>
    <AlternativeShortcuts>
      <Shortcut>imagebutton</Shortcut>
      <Shortcut Value="image">asp:image</Shortcut>
      <Shortcut Value="imagebutton">asp:imagebutton</Shortcut>
    </AlternativeShortcuts>
    <Description>Markup snippet for a control that contains an image</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>imageurl</ID>
        <ToolTip>imageurl</ToolTip>
        <Default>imageurl</Default>
      </Literal>
    </Declarations>
    <Code Language="html"><![CDATA[<asp:$shortcut$ imageurl="$imageurl$" runat="server" />$end$]]></Code>
  </Snippet>
</CodeSnippet>

Very easy and readable XML markup, that we easily can tweak to our needs. Say we’re working on a project where 90% of the tables we create should have a class of “products”. Lets create a snippet for this, so that we don’t have to type the same thing every time.

Create a new snippet called table-products.snippet, open it up in your favorite code editor and add this code.

<CodeSnippet Format="1.1.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>table</Title>
    <Author>Frederik Vig</Author>
    <Shortcut>tablep</Shortcut>
    <Description>Markup snippet for a table with class products</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
      <SnippetType>SurroundsWith</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>cellspacing</ID>
        <ToolTip>cellspacing</ToolTip>
        <Default>0</Default>
      </Literal>
    </Declarations>
    <Code Language="html"><![CDATA[<table cellspacing="$cellspacing$" class="products">
    <tr>
        <td>$selected$$end$</td>
    </tr>
</table>]]></Code>
  </Snippet>
</CodeSnippet>

I’ve saved table-products.snippet directly in the HTML snippet folder (C:\Program Files (x86)\Microsoft Visual Studio 10.0\Web\Snippets\HTML\1033\HTML in my case), but you can save it anywhere, just remember to add the snippet folder with the Code Snippets Manager in Visual Studio.

We can now test the snippet by typing tablep and pressing tab.

Visual Studio 2010 table products snippet

Visual Studio 2010 table products snippet

Simple example, I know, but you get the idea!.

EPiServer

Naturally, one of the first things I did was add the EPiServer Property web control to the snippet manager ;) . This turned out to be very easy! So I continued on adding snippets for the other EPiServer web controls as well. Here is the list of snippets with their shortcut.

Download the snippets

EPiServer code walkthrough #1 – 404 handler

This is the first post in a new series called “EPiServer code walkthrough”. What I’ll do is go through one new EPiServer module in each post. Writing a little about what it does, learn by reading its code, and hopefully contributing a little back to the project, if I see any bugs or harmful/unnecessary code that is :) .

I’m a firm believer that reading code helps you become a better developer. There are lots of modules even I just recently came across, that I didn’t know existed just a few weeks back. I think I’m not the only one, especially since they are spread around on various blogs, CodePlex, EPiCode and other places. They all contain valuable code that we as EPiServer developers should read.

I’m starting with a module I personally have not used much before, but that I know a lot of people have used in their projects: the custom 404 handler.

From the project wiki page

This module has a more advanced url redirect feature than the built-in shortcut url feature in EPiServer. It handles extensions and querystring parameters too. If you have a lot of 404 errors in your logs, you can use this to redirect the user to the correct page. Especially useful if you move templates or pages around, or have just installed EPiServer and have a lot of old urls that is no longer available.

404 handlers wiki page explains in detail what you need to do to install the module, so I’m not going to repeat it here. Instead we’ll take a look at the code.

Start by doing a SVN checkout of the source code (the svn url is https://www.coderesort.com/svn/epicode/BVNetwork.404Handler/5.x/).

SVN checkout of 404 handler

When opening up the BVNetwork.404Handler folder you’ll see a readme.txt file explaining the purpose of the module, installation, configuration etc. This is something I like! Not everyone reads the wiki page, and we as developers are especially lazy when it comes to reading documentation. Having a readme.txt with everything you need makes this so much easier, and gives the module author less support questions to answer. When using a new module, always make sure to read the documentation before asking the author questions. Saves both parties time :) .

Lets open up BVNetwork.404Handler.csproj in Visual Studio.

404 handler project structure in Visual Studio

As you can see the project is structured pretty nice, with good separations between the different parts. Very good that the project uses languages files, and that they’ve included them for five different languages. Not all modules use the language files, and if they do, they seldom have any more than one update-to-date English language file. Kudos for this.

What I don’t like is the missing fnf_logo.gif image file in the Images folder. A quick search in Visual Studio shows that this file is no longer in use, and should therefore be removed from the project. A missing image file is not the end of the world, and I know people make mistakes/forget to commit all their files, but this can be very annoying and even lead to a lot of work for other developers using your code or taking over a project.

Always make sure that your project builds on other computers than your own. I recommend manually setting up the project on preferably a new computer to see that everything works as expected, you can also use the same computer, but make sure to do the normal process a new developer would use when setting up the project (new checkout etc). Especially on larger projects that have quite a few things to setup you should do this. You’ll also receive some valuable feedback if your setup process is to complex (again on larger projects this happens quite frequently). Another thing you should use is a build server. There are quite a few out there, I know CodeResort just added Bitten as their build server for CodeResort projects. In a nutshell what a build server does is make sure you’ve included all the files and resources needed to build your project, run various tests (if you have any), deploy your files, create reports, notify team members if their build fails, and a bunch of other stuff, automatically for you. I’ll try to write a blog post up with more information on build and continuous integration servers.

Lets get back to the Visual Studio and the project! One of the things you should start out with is actually making sure the project builds after doing a checkout. So, either press ctrl + shift + b or go to Build -> Build BVNetwork.404Handler. You should have a successful build.

If we take a look through the code we see that most of the code is well documented and follows a nice naming convention making it easy to know what the purpose of the class is (CustomRedirectHandler.cs, CustomRedirectCollection.cs, Custom404Handler.cs etc). But we also see a few minor things we can clean up: unused using statements, commented out code, unused field variables etc. These are minor, but still important things to get rid of. Always strive for a clean code base, commented out code is something you should never commit into a repository, the whole reason for having a source control system is so that you can look at previous changesets and their code, there is no reason to keep the commented out code there, it will only be forgotten by the developer who commented out the code, and the other developers don’t know what to do with it, and will most likely just let it be. When I come across this I show no mercy and just delete it!

You’ll also see a few System.Diagnostics.Debug.WriteLine that are commented out. The project now uses Log4Net to log errors and warnings, System.Diagnostics.Debug.WriteLine is legacy code that we can safely remove. Another thing that I prefer is using string.Empty(); instead of “”, I’ve not updated the code because I feel this is more a personal preference. Same thing when it comes to over-documenting-code, like in this example.

/// <summary>
/// The refering url
/// </summary>
public static string GetReferer(System.Web.UI.Page page)
{
    string referer = page.Request.ServerVariables["HTTP_REFERER"];
    if (referer != null)
    {
	// Strip away host name in front, if local redirect
	string hostUrl = EPiServer.Configuration.Settings.Instance.SiteUrl.ToString();
	if (referer.StartsWith(hostUrl))
	    referer = referer.Remove(0, hostUrl.Length);
    }
    else
	referer = ""; // Can't have null
    return referer;
}

The document header can safely be removed since the method name does a good job at describing what the purpose of the method is. I’ve not removed the document header, since again this is my personal preference.

A thing I just noticed is that this is actually a Visual Studio class project, and not a Web Application project. I can only guess, but this is probably a project that got upgraded from Visual Studio 2003, I’ve previously had some problem upgrading a project from Visual Studio 2003 to Visual Studio 2008. The conversion usually goes okay (just an update to the csproj file mostly), but the ProjectTypeGuids doesn’t always get added. This is easy to fix, open up BVNetwork.404Handler.csproj in notepad or another source editor, and add this line.

<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

Save, and open up the project in Visual Studio. You should now see a slightly different icon at the top of the solution explorer window.

New project icon in Visual Studio

This will allow us to add a designer file to default.aspx from the admin folder. To do this simply right-click the file in solution explorer and choose “Convert to Web Application”. We can now delete the “Web Form Designer generated code”-region.

After all these updates its very important to make sure that the project still builds and that everything functions as expected by testing it.

What I liked the most with this project is how it uses logging. I’m personally very bad at using logging, and know that not all projects use logging as much as they should. Kudos to the authors for this!

I hope you’ve learned a few new things while reading this code, and be sure to try out the 404 handler! For SEO and user experience purposes it is crucial that the users have a smooth transition. They shouldn’t even notice the change when switching to EPiServer from another CMS (that uses different urls). A 404 (file not found) error message can also quickly become a major leak of traffic for your clients site.

Html Helpers vs Server controls

I received some very good comments on my post Extending PageData with some cool Html Helpers. Which made me want to explain my thoughts on the subject a bit more :) .

For me, most of the server controls abstract away to much of the details, that I feel we as web developers should be comfortable with, and want to have full control over. Server controls make use of viewstate, affecting both performance and increasing the size of the page. Many render old deprecated HTML markup, make it hard to work with ids in CSS and JavaScript, and have a complex life cycle.

I know there are ways to fix some of these issues (turn off viewstate, control adapters etc). But I feel that the added work load when using server controls, and trying to fix them, is higher than the benefit we get. With Html Helper, I type so much less code than before, and I have full control. I can easily add my own extension methods for stuff that I use a lot, I’ve one place to go to update the code. Combined with Page Type Builder I have intellisense of all my code, I can refactor the code without worrying about breaking it. Instead of having to check for runtime errors I can compile my .aspx/.ascx and be sure that I haven’t added a typo.

A little comparison

Lets say we are tasked with implementing this simple list.

<h3>Recent Articles</h3>
 
<div class="block odd">
 
	<a title="" href="index.html"><img src="images/thumb-1.jpg" class="thumbnail" alt="img" width="240px" height="100px"/></a>
 
	<div class="blk-top">
		<h4><a href="index.html">Aliquam Risus Justo Lorem Ipsum Dolor Sit Amet</a></h4>	
		<p><span class="datetime">August 27, 2009</span><a href="index.html" class="comment">2 Comments</a></p>		
	</div>						
 
	<div class="blk-content">
		<p>
		Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum. 
		Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu 
		posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum 
		odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra 
		condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. 				
		</p>					
 
		<p><a class="more" href="index.html">continue reading &raquo;</a></p>
	</div>
</div>
 
<div class="block even">
 
	<a title="" href="index.html"><img src="images/thumb-2.jpg" class="thumbnail" alt="img" width="240px" height="100px"/></a>
 
	<div class="blk-top">
		<h4><a href="index.html">Aliquam Risus Justo</a></h4>	
		<p><span class="datetime">August 26, 2009</span> <a href="index.html" class="comment">2 Comments</a></p>
	</div>						
 
	<div class="blk-content">
		<p>
		Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero. Suspendisse bibendum. 
		Cras id urna. Morbi tincidunt, orci ac convallis aliquam, lectus turpis varius lorem, eu 
		posuere nunc justo tempus leo. Donec mattis, purus nec placerat bibendum, dui pede condimentum 
		odio, ac blandit ante orci ut diam. Cras fringilla magna. Phasellus suscipit, leo a pharetra 
		condimentum, lorem tellus eleifend magna, eget fringilla velit magna id neque. 	
 
		<a class="more" href="index.html">continue reading &raquo;</a>			
		</p>
	</div>
 
</div>
 
<div class="fix"></div>
...

We might implement this by using a Repeater control, and a user control with the news story.

<h3>Recent Articles</h3>
<asp:Repeater runat="server" ID="rptNewsList">
<ItemTemplate>
    <div class="block odd">
	<Jungle:NewsStory runat="server" NewsPage="<%# Container.DataItem %>" />
    </div>
</ItemTemplate>
<AlternatingItemTemplate>
    <div class="block even">
	<Jungle:NewsStory runat="server" NewsPage="<%# Container.DataItem %>" />
    </div>
    <div class="fix">
    </div>
</AlternatingItemTemplate>
</asp:Repeater>

The NewsStory user control might look like this when using Html helper methods.

<a href="<%= NewsPage.LinkURL %>">
    <%= NewsPage.HtmlImage("ListImage", "PageName") %>
</a>
<div class="blk-top">
    <h4><%= NewsPage.HtmlLink() %></h4>
    <p><span class="datetime"><%= NewsPage.StartPublish.ToString("dd MMMM yyyy")%></span></p>
</div>
<div class="blk-content">
    <p><%= NewsPage.PreviewText(200) %>
        <a class="more" href="<%= NewsPage.LinkURL %>">continue reading &raquo;</a>
    </p>
</div>

For me this code is very easy to change and update. It is very readable (for me HTML markup describe the meaning of the content and give it context). I can easily add ids where I need. Update the markup without having to change my code-behind (and compile). If I need to change some of the logic I have one extension method to update, not a bunch of code-behind files to go to.

By using server controls it might look something like this.

<asp:HyperLink runat="server" ID="lnkListImage" />
<div class="blk-top">
    <h4><EPiServer:Property runat="server" PropertyName="PageLink" ID="heading" /></h4>
    <p><asp:Label runat="server" CssClass="datetime" ID="lblDate" /></p>
</div>
<div class="blk-content">
    <p><asp:Literal runat="server" ID="ltlPreviewText" />
        <asp:HyperLink runat="server" ID="lnkReadMore" CssClass="more" Text="continue reading &raquo;" />
    </p>
</div>

And the code-behind.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
 
    this.lnkListImage.ImageUrl = this.NewsPage["ListImage"] as string ?? string.Empty;
    this.lnkListImage.Text = this.NewsPage.PageName;
    this.lnkListImage.NavigateUrl = this.NewsPage.LinkURL;
 
    this.heading.PageLink = this.NewsPage.PageLink;
 
    this.lblDate.Text = this.NewsPage.StartPublish.ToString("dd MMMM yyyy");
 
    this.ltlPreviewText.Text = Helper.PreviewText(this.NewsPage, 200);
 
    this.lnkReadMore.NavigateUrl = this.NewsPage.LinkURL;
}

They both do the same thing, and at this point it really is just about what you prefer. But, (for me at least) those extra lines of repetitive code get quite boring to type after a while. There are of course possibilities to have a bunch of helper classes that generate these server controls for you, and then just add them to the various control collections. But why go to all that problem, when a simple extension method in most cases does a much better job?

What do I use? Both. I use what makes the most sense there and then. Server controls are here to help me as a developer, same with extension methods, they are here to help me. When I come to the point that I have to use a lot of hacks and fixes to make something work, I stop, take another look at my solution, and try to use a different approach instead. I feel we’ve reached a point where we need to fix/hack to much to make server controls work. That might be why my most used server control is the Repeater and recently the ListView :) .

Creating a mobile version of a web site

When building web sites we has developers or designers have to take into consideration all the different types of devices that can be used to access the web sites we create. Not just PC or Mac with Internet Explorer, Firefox, Safari, Opera, Jaws, or any other browser. But also mobile devices, like iPhones, iTouch, Nintendo Wii.

Especially in recent years, after the launch of the iPhone, accessing online information through a mobile device has become more common. This is something that is going to increase even more in the next few years.

Below I’ve listed some resources for creating a mobile version of a web site that I hope you’ll find useful.

Mobify

Mobify is a free online service that lets you convert an existing web site into a mobile version. This is done by selecting the content you wish to display for mobile users, customizing it by changing the display order and tweaking the CSS. The last step is to publish it by creating an url and adding a little JavaScript to your page.

Check out How to implement a mobile version of your blog in three simple steps for a quick introduction.

Mobify is quick and easy way to great a mobile version, but you cannot change the HTML code and you’re stuck with the options the service offers. It can sometimes be better to create a mobile version from scratch.

Update 05.10.2009

Igor Faletski, founder of Mobify, was kind enough to send me an email explaining the use of HTML blocks to add more static content. While this is a great feature I still miss the ability to update my existing markup and easily see what classes and ids that the mobile version uses. Now I have to test and tweak a little before I get the right id or class when changing my CSS.

Creating a mobile version with ASP.NET

Although services like Mobify are great, sometimes you need full control. On mobify.me it says that Mobify supports over 4500+ different mobile devices. This is a lot of different devices to support! Fortunately there is an open source project on CodePlex that has done most of the work for us. It is called Mobile Device Browser File and consists of a browser file with information about what the different mobile devices support (Java, JavaScript, Images, Flash etc). This project is pretty active with new devices added all the time.

You simply download the browser file and add it to your projects App_Browser folder. After you’ve done that you’ll be able to use Request.Browser["IsMobileDevice"] to detect if the device accessing your page is actually a mobile device. There are also 64 other capabilities that offers a lot of different detection functionality. You can for instance check if the device supports Flash, JavaScript, Color, CSS background images etc.

If you’re using ASP.NET MVC check out Scott Hanselman’s post about how he implemented this with Nerd Dinner.

If you’re using ASP.NET web forms there are a couple of approaches you could take. You could use a different master page for the mobile version by adding some detection code to your base page and switching the master pages in the Init method. Or you could register a custom HttpModule that redirects the user to a different page if it is a mobile device.

Recently I stumbled over another library to detect the mobile device, it is called 51Degrees.mobi. Here is the article that describes how to use it.

iPhone

Apple iPhone uses the Safari browser as its default browser. The great thing about that is that CSS3 stuff like border-radius, multiple background images, canvas and more are supported.

If you like to simply target iPhone users you can do so by simply adding a custom stylesheet with this code.

<link media="only screen and (max-device-width: 480px)" 
    href="iPhone.css" type="text/css" rel="stylesheet" />

For more information I recommend reading A List Aparts Put Your Content in My Pocket and checking out the iPhone Dev Center.

Wordpress

For Wordpress you have a nice plugin called WPtouch, that will help you easily add a mobile view for iPhone, iPod, Android, Storm and Pre. You just need to install and activate the plugin, and you’re ready! You can easily customize it to your needs as well.

Other resources

More and more resources are being added each day. Below are some I’ve bookmarked and that have helped me in the past.

Extending search field with suggestion box

Disclaimer: In this example I’ve kept the code simple to make it easier to read and to give you an idea of how you might approach something like this with EPiServer. This code should not be used in production scenarios since it will use a lot of resources. Use at own risk :) .

Update – 12.10.2009

Updated production code with a new custom filter that removes pages that the Everyone role doesn’t have access to.
Also updated the Get caching method. See comments below for further details.

Update – 19.09.2009

Added example of production code you might consider.

We’ve all used Google Suggest before. When you start typing a word or sentence, Google comes up with suggestions to what we might be searching for.
Example of Google Suggest
This is to help users quickly find what they want.

In this blog post we’re going to do the same by extending QuickSearch that ships with the EPiServer Public Templates.

I decided to use jQuery and the AutoComplete plugin for this, but you can use any script you like (most are pretty similar).

The result

Example of search suggest

The Code

First start by modifying the QuickSearch.ascx:

<asp:Panel runat="server" CssClass="QuickSearchArea" DefaultButton="SearchButton">
	<asp:Label ID="SearchLabel" runat="server" AssociatedControlID="SearchText" CssClass="hidden" Text="<%$ Resources: EPiServer, navigation.search %>" />
    <asp:TextBox ID="SearchText" TabIndex="1" runat="server" CssClass="quickSearchField" autocomplete="off" />
    <asp:ImageButton ID="SearchButton" runat="server" ImageUrl="~/Templates/Public/Images/MainMenuSearchButton.png" ToolTip="<%$ Resources: EPiServer, navigation.search %>" CausesValidation="false" CssClass="quickSearchButton" OnClick="Search_Click" />
</asp:Panel>
 
<script type="text/javascript">
//<![CDATA[ 
    $("#<%=SearchText.ClientID %>").autocomplete("/path/to/file/SearchSuggest.aspx", {
        minChars: 2,
        max: 10
    });
//]]> 
</script>

A few things to note. I removed the default text from the TextBox and added the attribute autocomplete=”off”, this is to ensure that the users browser does not store the information (How to Turn Off Form Autocompletion). I then attached the AutoComplete plugin to the TextBox and changed a few of its default properties.

As you can see there is not much code that is needed when mostly using the default settings. You can of course do a lot more. Browse through the AutoComplete plugin documentation and see the demos to get a few ideas.

Now for the main part, SearchSuggestion.aspx. This is just an empty web forms page with all the code in the code-behind:

using System;
using System.Text;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Security;
 
namespace FV.Templates.FV.Pages
{
    public partial class SearchSuggest : TemplatePage
    {
        protected override void OnLoad(EventArgs e)
        {
            // #1
            string query = HttpUtility.HtmlEncode(Request.QueryString["q"]);
            string limit = HttpUtility.HtmlEncode(Request.QueryString["limit"]);
 
            if (!string.IsNullOrEmpty(query))
            {
                var sb = new StringBuilder();
 
                // #2
                var criterias = new PropertyCriteriaCollection();
 
                var queryCriteria = new PropertyCriteria
                                        {
                                            Condition = CompareCondition.StartsWith,
                                            Name = "PageName",
                                            Value = query,
                                            Type = PropertyDataType.String,
                                            Required = true
                                        };
 
                var pubCriteria = new PropertyCriteria
                                      {
                                          Condition = CompareCondition.Equal,
                                          Name = "PagePendingPublish",
                                          Value = false.ToString(),
                                          Type = PropertyDataType.Boolean,
                                          Required = true
                                      };
 
                criterias.Add(queryCriteria);
                criterias.Add(pubCriteria);
 
                // #3
                var pages = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, criterias, CurrentPage.LanguageBranch);
 
                int tempLimit = Convert.ToInt32(limit);
                int pagesCount = pages.Count;
 
                // #4
                if (tempLimit > pagesCount)
                {
                    tempLimit = pagesCount;
                }
 
                // #5
                for (int i = 0; i < tempLimit; i++)
                {
                    sb.Append(pages[i].PageName);
                    sb.Append(Environment.NewLine);
                }
 
                // #6
                Response.AddHeader("Content-Type", "text/html");
                Response.Write(sb.ToString());
 
                Response.End();
            }
        }
    }
}
  • In #1 we retrieve the user input and the limit (which we set earlier with the max property in QuickSearch.ascx), we then HTML encode it (something you should always do when receiving user input).
  • In #2 we build the criteria collection with our search options. We search for pages that start with what the user typed in and then make sure that only published pages are returned.
  • In #3 we do the actual searching with the FindPagesWithCriteria method where we also set the current language branch (only return pages in that language).
  • In #4 we make sure that we don’t have less pages than the limit, if so we set the pages count to be the limit.
  • In #5 we go through pages (PageDataCollection) and add the PageName to sb (StringBuilder).
  • In #6 we return the result back

Below is the code for SearchSuggest.aspx.cs updated to use the SearchDataSource instead of FindPagesWithCriteria (this will not only search the PageName but all properties that are search able):

using System;
using System.Text;
using System.Web;
using System.Web.UI;
using EPiServer;
using EPiServer.Core;
using EPiServer.Security;
using EPiServer.Web.WebControls;
 
namespace FV.Templates.FV.Pages
{
    public partial class SearchSuggest : TemplatePage
    {
        protected override void OnLoad(EventArgs e)
        {
            string query = HttpUtility.HtmlEncode(Request.QueryString["q"]);
            string limit = HttpUtility.HtmlEncode(Request.QueryString["limit"]);
 
            if (!string.IsNullOrEmpty(query))
            {
                var sb = new StringBuilder();
 
                var searchDataSource = new SearchDataSource
                {
                    SearchQuery = query,
                    AccessLevel = AccessLevel.Read,
                    PublishedStatus = PagePublishedStatus.Published,
                    PageLink = PageReference.StartPage,
                    LanguageBranches = CurrentPage.LanguageBranch,
                    MaxCount = Convert.ToInt32(limit)
                };
 
                foreach (PageData page in searchDataSource.Select(DataSourceSelectArguments.Empty))
                {
                    sb.Append(page.PageName);
                    sb.Append(Environment.NewLine);
                }
 
                Response.AddHeader("Content-Type", "text/html");
                Response.Write(sb.ToString());
 
                Response.End();
            }
        }
    }
}

Production code

Like I said in the beginning, this code should not be used in production scenarios since it goes through the entire site searching for matching PageNames each time there is a request.

I’ve added some example code of how you might approach this in a production scenario. Basically I just use the FindPagesWithCriteria method to find all the pages and then store the PageName of each in an array that I then store in the cache for easy access.

using System;
using System.Linq;
using System.Text;
using System.Web;
using EPiServer;
using EPiServer.Core;
using EPiServer.Filters;
using EPiServer.Security;
using FV.Templates.FV.Filters;
 
namespace FV.Templates.FV.Pages
{
    public partial class ProductionSearchSuggestion : TemplatePage
    {
        protected override void OnLoad(EventArgs e)
        {
            string query = HttpUtility.HtmlEncode(Request.QueryString["q"]);
            string limit = HttpUtility.HtmlEncode(Request.QueryString["limit"]);
 
            if (!string.IsNullOrEmpty(query))
            {
                var sb = new StringBuilder();
                string[] pageNames;
 
                const string pageNamesCacheKey = "AllPageNames";
 
                if (!Get(pageNamesCacheKey, out pageNames))
                {
                    var criterias = new PropertyCriteriaCollection();
 
                    var pubCriteria = new PropertyCriteria
                    {
                        Condition = CompareCondition.Equal,
                        Name = "PagePendingPublish",
                        Value = false.ToString(),
                        Type = PropertyDataType.Boolean,
                        Required = true
                    };
 
                    criterias.Add(pubCriteria);
 
                    var pages = DataFactory.Instance.FindPagesWithCriteria(PageReference.StartPage, criterias, CurrentPage.LanguageBranch);
 
                    new FilterRole("Everyone").Filter(pages);
 
                    var pagesCount = pages.Count;
                    pageNames = new string[pagesCount];
 
                    for (int i = 0; i < pagesCount; i++)
                    {
                        pageNames[i] = pages[i].PageName;
                    }
 
                    Add(pageNames, pageNamesCacheKey);
                }
 
                int tempLimit = Convert.ToInt32(limit);
 
                var result = new string[tempLimit];
                int resultCounter = 0;
 
                for (int i = 0; i < pageNames.Length; i++)
                {
                    if (resultCounter <= tempLimit && pageNames[i].ToLower().StartsWith(query.ToLower()) && !result.Contains(pageNames[i]))
                    {
                        result[resultCounter++] = pageNames[i];
                    }
                }
 
                for (int i = 0; i < resultCounter; i++)
                {
                    sb.Append(result[i]);
                    sb.Append(Environment.NewLine);
                }
 
                Response.AddHeader("Content-Type", "text/html");
                Response.Write(sb.ToString());
 
                Response.End();
            }
        }
 
        // Caching methods from http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/
        public bool Exists(string key)
        {
            return HttpContext.Current.Cache[key] != null;
        }
 
        public bool Get<T>(string key, out T value) where T:class
        {
            try
            {
                value = HttpContext.Current.Cache[key] as T;
                if (value == null)
                {
                    value = default(T);
                    return false;
                }
            }
            catch
            {
                value = default(T);
                return false;
            }
 
            return true;
        }
 
        public void Add<T>(T o, string key)
        {
            HttpContext.Current.Cache.Insert(
                key,
                o,
                null,
                DateTime.Now.AddMinutes(3600),
                System.Web.Caching.Cache.NoSlidingExpiration);
        }
    }
}

The FilterRole class

using System;
using EPiServer.Core;
using EPiServer.Filters;
 
namespace FV.Templates.FV.Filters
{
    public class FilterRole : IPageFilter
    {
        public string RoleName
        {
            get;
            set;
        }
 
        public FilterRole()
        {
        }
 
        public FilterRole(string roleName)
        {
            this.RoleName = roleName;
        }
 
        public void Filter(PageDataCollection pages)
        {
            for (int i = pages.Count - 1; i >= 0; i--)
            {
                bool isMatch = false;
                var acl = pages[i].ACL;
 
                if (acl != null)
                {
                    foreach (var role in acl)
                    {
                        if (role.Key == this.RoleName)
                        {
                            isMatch = true;
                        }
                    }
                }
 
                if (!isMatch)
                {
                    pages.RemoveAt(i);
                }
            }
        }
 
        public void Filter(object sender, FilterEventArgs e)
        {
            this.Filter(e.Pages);
        }
 
        public bool ShouldFilter(PageData page)
        {
            throw new NotImplementedException();
        }
    }
}

Download the code

Add class attribute to body element with ASP.NET web forms and Master Pages

Often I have to add a class to the HTML body element. This is a little code snippet that allows you to easily do this.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body runat="server" id="BodyTag">
    <form id="form1" runat="server">
    ...
    </form>
</body>
</html>

Add the public property BodyClass.

public string BodyClass
{
    set
    {
        BodyTag.Attributes.Add("class", value);
    }
}

Then in your .aspx, you need to make the Master Page strongly typed by adding MasterType (you can also manually cast it to the right type).

<%@ MasterType VirtualPath="~/Site1.Master" %>

You’ll now have access to the Master Pages BodyClass property.

Master.BodyClass = "home";
 
// Or by manually casting it
((Site1)Master).BodyClass = "home";
...
<body id="ctl00_BodyTag" class="home">
...

Adding CSS and JavaScript files dynamically to your ASP.NET page

When starting a new project I always create a Master Page that holds the content that is most used across the site. In my Master Page I have a PlaceHolder for my JavaScript files at the bottom of the page, right before the closing body tag.

<body>
<form id="form1" runat="server">
...
</form>
    <asp:PlaceHolder runat="server" ID="phdBottomScripts" />
</body>
public PlaceHolder BottomScriptsPlaceHolder
{
    get
    {
        return phdBottomScripts;
    }
}

The reason for having it at the bottom instead of the head is performance.

Now I have the ability to add JavaScript files to the bottom and CSS and JavaScript files to the head (through the pages Header property).

Lets add two methods for adding CSS and JavaScript files.

// using System.Web.UI.HtmlControls;
public static HtmlLink CreateCssLink(string cssFilePath, string media)
{
	var link = new HtmlLink();
	link.Attributes.Add("type", "text/css");
	link.Attributes.Add("rel", "stylesheet");
	link.Href = link.ResolveUrl(cssFilePath);
	if (string.IsNullOrEmpty(media))
	{
		media = "all";
	}
 
	link.Attributes.Add("media", media);
	return link;
}
 
public static HtmlGenericControl CreateJavaScriptLink(string scriptFilePath)
{
	var script = new HtmlGenericControl();
	script.TagName = "script";
	script.Attributes.Add("type", "text/javascript");
	script.Attributes.Add("src", script.ResolveUrl(scriptFilePath));
 
	return script;
}

The media attribute is to specify which media types the CSS file should be applied to.

Media types

  • all
  • braille
  • embossed
  • handheld
  • print
  • projection
  • screen
  • speech
  • tty
  • tv

Example

protected override void OnLoad(EventArgs e)
{
	base.OnLoad(e);
 
	Page.Header.Controls.Add(Helper.CreateJavaScriptLink("~/Scripts/swfobject.js"));
	Page.Header.Controls.Add(Helper.CreateCssLink("~/Styles/styles.css", "screen"));
}
<head>
...
<script type="text/javascript" src="/Scripts/swfobject.js"></script>
<link type="text/css" rel="stylesheet" href="/Styles/styles.css" media="screen" />
</head>

To add JavaScript files to the bottom we need to add MasterType to our .aspx file to make my Master Page strongly typed (and thus able to access the BottomScriptsPlaceHolder property).

<%@ MasterType VirtualPath="~/MasterPages/MasterPage.master" %>
Master.BottomScriptsPlaceHolder.Controls.Add(Helper.CreateJavaScriptLink("~/Scripts/master.js"));
...
<script type="text/javascript" src="/Scripts/master.js"></script>
</body>

Other methods

Response.Write method

<link href="<%= ResolveUrl("~/Styles/Styles.css") %>" rel="stylesheet" type="text/css" />

ClientScriptManager

From MSDN.

The ClientScriptManager class is used to manage client scripts and add them to Web applications

Methods of the ClientScriptManager class.

ResolveUrl and ResolveClientUrl

Simply put, the difference between these two methods is that ResolveUrl will create a path from the sites root (/Styles/Styles.css), while ResolveClientUrl will create a path that is relative from the page the user is on. (../Styles/Styles.css).

ASP.NET web forms and jQuery Thickbox plugin

I’m very found of jQuery, and use the Thickbox plugin a lot in my project. I’ve not used it much for images, but rather for content. To retrieve content you have three options.

  • Inline content
  • Iframed content
  • Ajax content

Inline content

This is pretty straight forward, you have some content on the same page that you’d like to display inside the Thickbox. This one I use a lot, since it is easy to make accessible for search engines, screen readers and other devices. You simply hide the content with JavaScript (in jQuery you can use the hide function: $(selector).hide();), and then trigger opening the content inside the Thickbox with either a link or button.

<a href="#TB_inline?height=155&amp;width=300&amp;inlineId=contentId" class="thickbox">Show hidden content.</a>

Iframe content

<a href="Default.aspx?keepThis=true&amp;TB_iframe=true&amp;height=300&amp;width=500" title="thickbox title" class="thickbox">Iframe content</a>

The nice thing about this is that you can easily include existing pages inside the Thickbox. Another thing to note is that users without JavaScript, like search engines, still can navigate the content, since the a element’s href attribute points to the page. This is also the easiest way to still have functionality that you have inside your ASP.NET web form page like Postbacks, sessions etc.

Ajax content

Like with iframed content people without JavaScript will still be able get to the content.

<a href="ajaxContent.aspx?height=300&amp;width=300" title="thickbox title" class="thickbox">Ajax conten</a>

The one problem I’ve had in the past with this method is when posting data back to the server with ASP.NET web forms (same problem with inline content). Until recently I always used iframed content when having to deal with form controls. The reason being that the content inside the Thickbox got added outside the form element on the page (right before the closing body tag).

Thickbox code right before closing body tag

To fix this you need to change this line of code inside the thickbox.js file.

$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");

Add form:first to the selector to target the first form element on the page.

$("body form:first").append("<div id='TB_overlay'></div><div id='TB_window'></div>");

Thickbox code inside the form tag now

Now the form controls will work and you’ll be able to have the user fill out the form inside the Thickbox and post it back to the server.

The Thickbox is also very easy to style and extend, below are some screen shots of sites where I’ve used it.

thickbox screen shot

Thickbox screen shot

Other resources

Using multiple forms on an ASP.NET web forms page

I came across this simple technique while watching Building great standards based websites for the big wide world with ASP.NET 4.0.

The cool thing about being able to have multiple forms on the same page is that you don’t have to use JavaScript to fix the default button problem, or use unnecessary ASP.NET web controls or logic on the server (like the Response.Redirect method). The drawback, for some, is that you cannot have the forms inside the form (web form) with the runat=”server” attribute, which means that you cannot use all of the ASP.NET web controls.

Example

Three forms on an ASP.NET web forms page

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <fieldset>
    <legend>ASP.NET web form (POST)</legend>
        <asp:Label runat="server" AssociatedControlID="txtSearch">Name: </asp:Label><asp:TextBox runat="server" ID="txtSearch" /><asp:Button runat="server" ID="btnSend" Text="Search" OnClick="btnSend_Click" />
    </fieldset>
    </form>
    <form method="get" action="Search.aspx">
        <fieldset>
        <legend>Regular HTML form using GET</legend>
            <label for="name-text">Name: </label><input type="text" id="name-text" name="q" /><input type="submit" value="Search" />
        </fieldset>
    </form>
    <form method="post" action="Search.aspx">
        <fieldset>
        <legend>Regular HTML form using POST</legend>
            <label for="name-text2">Name: </label><input type="text" id="name-text2" name="q" /><input type="submit" value="Search" />
        </fieldset>
    </form>
</body>
</html>
using System;
 
public partial class _Default : System.Web.UI.Page
{
    protected void btnSend_Click(object sender, EventArgs e)
    {
        Response.Redirect(string.Format("Search.aspx?q={0}", txtSearch.Text));
    }
}

Search.aspx

Displaying result of multiple forms on ASP.NET web forms page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Search.aspx.cs" Inherits="Search" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" ID="lblResult" />
    </div>
    </form>
</body>
</html>
using System;
using System.Web;
 
public partial class Search : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["q"]))
        {
            lblResult.Text = HttpUtility.HtmlEncode(Request.QueryString["q"]);
            return;
        }
 
        // For the regular html form POST method
        lblResult.Text = HttpUtility.HtmlEncode(Request.Form["q"]);
    }
}

© Copyright Frederik Vig. Based on Fluid Blue theme