Archive for the ‘.NET’ Category

HtmlEncode in ASP.NET

March 5, 2008

I keep forgetting where to find HtmlEncode when working in .NET. I end up going to Google and doing a couple searches before I find the right namespace to include. Hopefully now I’ll remember to look at my blog rather than Google :-)

HtmlEncode does exactly what it sounds like it should. It takes a string value as a parameter, and returns an escaped string.

using System.Web;

private static string ReturnEncoded()
{
	return (HttpUtility.HtmlEncode("<br />"));
}

This function would return “&lt;br /&gt;”. Not a real useful function, but is shows how to use HtmlEncode.

This same location also has HtmlDecode, UrlEncode, and UrlDecode.

Web Forms Should Inherit a Custom Class

February 20, 2008

When doing a web application in .NET, I like to create a custom class that inherits from System.Web.UI.Page I usually call this class “MyWebPage”. In some (most) cases, this class doesn’t add any functionality, it’s just a wrapper. However, when you need to do certain things in your web app, this wrapper is invaluable.

When creating web forms, the first thing I do is change the code behind file, so it inherits from “MyWebPage” rather than default System.Web.UI.Page. This gives the new web form whatever functionality is built into “MyWebPage”.

When is this useful? Previously, I talked about dynamic master pages in a CMS application. By overwriting the PreInit method in “MyWebPage” to include the functionality for dynamic web pages, any new template that inherits “MyWebPage” will automatically receive this functionality. The alternative would be to override the PreInit method in every new template.

I first heard about making this page wrapper when Paul Sheriff gave a talk at an Iowa .Net User Group meeting. The example he gave was that you have a large .NET application. On Friday morning, your boss tells you that by Monday, the web application should log every time a page is hit, this log would be something above and beyond what the web server can log. Without the wrapper, you would have to edit every web form in the application, possibly hundreds of files. With the web forms inheriting from your wrapper class, you simply change this one class, and you enjoy the weekend.

Since then, I’ve heard this talked about on .NET Rocks, and also in this blog post by Brian Mishler.

Dynamic Master Pages

February 15, 2008

An important thing to remember about master pages is that you can have more than one in any given web application. For example, if some pages in your web application will be two columns, and some will be three, you might build two master files. Then, when you create the web forms, you select which master file to use.

A powerful use for multiple master pages in an application is to dynamically assign them when the page loads. Here is an example of code to do dynamic master pages. The example on this page is giving a different master page if the client is using a browser on Windows CE. The thing to remember about dynamically assigning master pages, is that it needs to be done very early in the page life cycle, in the PreInit method.

Imagine a situation where you want to host a web application for many different entities, for example, I recently watched a demonstration of a hosted 4-H enrollment application. Every state wants to have their own look to the application. An easy way to do this is by using dynamic master pages, and assigning them based on the username of the person that is logged in.

A place where we are using dynamic web pages extensively is in our Content Management Server (CMS). We have one set of templates that are used for 18 different sites. Each of these sites have their own branding and navigation, although many of them are similar. When we set up the sites in CMS, we set a custom property that tells it what master file to load. This allow us to provide a huge amount of customization by only modifying the two files that make up the master page. Our Midwest Grape and Wine Industry Institute site, and our Bioeconomy site are using this CMS application, and have quite different looks.

We are currently working on a project for community foundations, that will have a number of sites for individual community foundations. These sites will use the same CMS application as the ISU extension sites referenced above. However, they will have a completely different look and feel. This project was possible because we are dynamically assigning the master pages as the page loads.

wine2.png bioeconomy2.png hardin2.png

Here are thumbnails of the three web sites referenced above that are using this single CMS application. The different looks is a result of the dynamic master pages mentioned above.

Master Pages in .NET 2.0

February 14, 2008

One of the big improvements with .NET 2.0 is master pages. A master page is a template that you use to build the structure of your web pages. You use it to do things like branding, top navigation, side navigation, footer, etc. Anything that you want repeated on every page can be placed in a master page.

Before .NET 2.0, we would build things in user controls, and add the user controls to our pages. This worked reasonably well, until you wanted to add a new feature, such as a search box to all your pages. If you didn’t have a suitable user control on your pages, you’d create a new user control, then add that to every page in your web application.

With .NET 2.0 or later, you can add the search box to the master page, and every page using that master page will automagically get the search box. This can save a huge amount of time. I learned this a few weeks ago, when I had to modify project that was created in .NET 1.1.

On master pages, in addition to the branding and navigation elements, you provide one or more content ares. These content areas are where the individual pages are responsible for populating the content. However, the content page does not have to populate every content area, you can pick and choose which content areas to use. For example, if your master page has an area for a sidebar, but your page doesn’t have content for the sidebar, you simply leave that area off your content page. It is an error, however, when your pages implement a content area that is not on the master page.

SharePoint makes extensive use of master pages, so this is a concept I will continue working with and expanding my knowledge.

Writing Atom Feeds in .NET Using Argotic

January 11, 2008

This week, one of my projects entailed generating some Atom feeds from web pages produced in our Content Management System. Because our CMS doesn’t generate feeds automatically, I used a package called Argotic Syndication Framework, by Brian Kuhn, to help build the feeds in a .NET program.

Argotic is a very well designed and implemented framework that reads and writes both Atom and RSS feeds. It also handles popular extensions to feeds, such as the iTunes extensions. Very nice having a single framework that handles both major feed formats!

I discovered a minor problem when I tried to validate the feeds using the Feed Validator. Although I didn’t see anything in the Atom Specifications about it, the validation failed because the <entry> items were not the last thing in the feed. I downloaded the source code for Argotic, to change the output order, which was pretty easy to accomplish.

I also posted a bug report at the Argotic Syndication Framework web site at about 10:30 pm Monday. By 9:00 AM Tuesday, there were 2 responses from Brian, one of which said it was fixed for the next release. Wow, great service Brian! Especially for a product that is freely available.

I definitely recommending using Argotic to work with feeds in .NET.

Web Controls on dnrTV

December 12, 2007

One of the projects I’ve been thinking about for a long time is a toolbox of controls that we can reuse. I’ve had a hard time trying to explain what that would look like, but I definitely know it’s the direction that we need to go. Not only will it be good for us, but it could provide a mechanism for sharing code with other states.

A couple of weeks, I decided that it would be easier to explain if I had something tangible to show people. As a first step, I fired up episode #1 of dnrTV. In this episode, Miguel Castro builds a “contact us” web control that can be dropped into any ASP.NET web page where you want a contact us form.

As he went though the process, I’d stop the video to duplicate his steps by writing my own web control. Mine was much simpler in function, it provides a search text field and button, that will interact with our Google search appliance. I learned a lot by watching a couple minutes, then doing whatever he was talking about.

There were two more episodes on dnrTV where Miguel talked about web controls, both of which talk mostly about adding design time features to the control, meaning how the control acts in Visual Studio. These episodes are number 2, and number 31.

The best thing about these three episodes is that they help me think about how we can reuse code from one product to another. I now have a “Google Search Appliance” control that I can show. It takes a little more work initially to write the code with enough flexibility and configurations to be useful in multiple projects. However, done correctly, it will save time in the long run.

I really like the dnrTV videos. In fact, as I think about holding regular developer meetings, I’m thinking we might want to use them as the various topics. We’d watch and discuss the episodes that have topics of interest. Is this a good idea?

The people that do dnrTV, started by doing weekly podcasts at DotNetRocks. These are highly recommended for .NET developers as well.

Date Field Validation

September 18, 2007

In .NET, it is really easy to check whether a user is entering a date into a form field, although it’s not necessarily obvious how to do so. What you need to do is include a CompareValidator in your web form. The code would look like this:

<asp:TextBox ID="txtBirthDate" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
	ErrorMessage="CompareValidator" ControlToValidate="txtBirthDate"
	Operator="DataTypeCheck" Type="Date"></asp:CompareValidator>

The three important properties that you need to set in the CompareValidator are:

  1. ControlToValidate - This is the ID of the Textbox
  2. Operator - Default is “Equal”, need to change to DataTypeCheck
  3. Type - Default is String, set to Date

This will cause the validator to return the error message when an invalid date is entered. It will accept dates such as “4/18/2004″, “9/12/95″ and “02/29/2004″, however would cause the error message to be displayed on “14/14/2000″, “02/29/2005″, and “January 1, 2000″. I’d like to see it accept the last one, however, the date should be in the format mm/dd/yyyy, be sure to tell the users to enter this format.

Of course, to be semantically correct, you’d want to give your Textbox a label on the form, and the CompareValidator a more descriptive error message. Also, be sure to enable server side validation, see “Server-Side Validation“.

This tip came from Peter Blum, on dnrTV. Peter has done a ton of work with validation in .NET. His product, Professional Validation and More looks very promising.

Reusing Code in ASP.NET

September 13, 2007

The last few evenings, I watched broadcasts from DotNetRocks and dnrTV. I started with three episodes featuring Miguel Castro where he talks about building web controls. In them, he builds a fully functioning e-mail feedback control that can be reused in multiple projects.

Wow, I wish I would have known this stuff when we started building sites in .NET a few years ago. I’ve always wanted to go in this directions, just have not had a clear picture of it, therefore could not express it in a way our developers understood. These broadcasts help me take a giant step forward.

For a long time, I’ve kept an item on our project list for ISUE Framework. This framework would be a library of reusable controls to share between all the projects we develop. It will take a while to build, and will likely be built by writing code for a given project, then deciding that with some tweaks, it can be customized to add customization for use in other projects.

This week, there has been talk that a few states are planning on working with SharePoint and/or MOSS, and we are looking at ways we might share resources. There are many possibilities for how we can work together. At the very least, I hope that we will share controls what we develop in-house so we all can benefit from them.

Screen Scrolling on Postback

September 12, 2007

Last night I was watching a DotNetRocks TV broadcast by Peter Blum on Web Controls and Validation. During his presentation, Peter said something, in passing, that triggered a major “ah ha” moment. One where you dent your forehead with your palm.

He mentioned a property that was added to the Page object in .NET 2.0 called MaintainScrollPositionOnPostback. I stopped the video right then, pulled up my Visual Studio, and tried it out. It worked!

One of the problems we’ve had in our CMS system is that when you change certain publishing options, it triggers a PostBack of the page. Basically, the page gets posted to the server, then reloaded on the browser. When this happens, it takes you to the top of the page in the browser. The publishing options are at the bottom of the page, so the user needs to scroll back down to where they were. Not cool.

With this new feature in .NET 2.0, we can add one line of code with will make the PostBack return you to the previous location on the screen. The code is:

Page.MaintainScrollPositionOnPostBack = true;

Now I just need to figure out where is the best place to use this feature. Right now I’m thinking it should go in the UserControl that displays the publish options on the edit screen.

When to use asp:Label

August 10, 2007

In yesterday’s post, “asp:label or asp:literal” I encouraged the use of <asp:literal> instead of <asp:label> because it outputs cleaner HTML. So when is it appropriate to use <asp:Label>?

When you use the “AssociatedControlID” attribute in <asp:Label>, it will output a <label> tag in HTML, rather than the <span> tag it normally outputs. This is useful when you are associating text to an input field of a form as shown in “Forms with CSS (1 of 3) - HTML Markup“. Consider the following two pieces of ASP.NET code:

<asp:Label AssociatedControlID="txtTest" runat="server">Test:</asp:Label>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>

and

<label for="<%= txtTest.ClientID %>">Test:</label>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>

Both output the exact same HTML code as shown here:

<label for="ctl00_MainContent_txtTest">Test:</label>
<input name="ctl00$MainContent$txtTest" type="text" id="ctl00_MainContent_txtTest" />

While both pieces of sample code above output the same HTML, I haven’t decided which way I prefer. I’m thinking the one using the <asp:Label> tag might have more semantic meaning, which should make it easier to maintain in the long run.