Archive for the ‘.NET’ Category

Writing Atom Feeds in .NET Using Argotic

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.

Advertisements

Web Controls on dnrTV

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

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

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

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

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.

asp:label or asp:literal

One of the issues I hear raised with ASP.NET is that it doesn’t produce valid XHTML code. In some cases, it is true that it’s hard, if not impossible, to do so. In other cases, there are simple things we can do that greatly improve the quality of HTML code from our applications. One of the easiest things is to follow the advice of Phil Haack in “ASP.NET Tip – Use the Label Control Correctly” when he says “Never use the ASP.NET label control when a Literal would do.

Consider the following lines of ASP.NET Code:

<p><asp:Label ID="lblTest" runat="server">This is a label</asp:Label></p>
<p><asp:Literal ID="litTest" runat="server">This is a literal</asp:Literal></p>

This produces the HTML code:

<p><span id="ctl00_ContentPlaceHolder1_lblTest">This is a label</span></p>
<p>This is a literal</p>

The <asp:Label> tag produced an extra <span> tag while the <asp:Literal> tag did not. This is the only real difference when the tags are used in this way. You can easily interact with either of these tags in the code behind file to assign additional, or completely different, text to the tags, so in that respect, they are completely interchangeable.

Whenever I modify an existing page that uses <asp:Label> tags, I evaluate whether to change them to <asp:Literal>. In most cases, it only takes a few minutes to make this change. When doing new pages, I always use choose <asp:Literal> over <asp:Label> whenever it will work. In doing so, the application outputs cleaner HTML.

[Updated (Dec 18, 2008): Added link to When to use asp:Label ]

Adding CSS to a Single Page

The project I’m working on has a page with an input form, and I  want to use CSS to format the form. Options for locating these styles include adding them in the main stylesheet used by the project, adding an embedded stylesheet to the page, creating a new CSS file and adding it to the master page, or creating a new CSS file and adding it to the page with the form.

I decided to create the CSS file and link it only page with the input form. In this project, linking to an additional CSS file is easier to implement than embedded styles, and should be easier to maintain in the long run. Adding styles to the main CSS file or linking from master file would mean that all the pages in the project would get the extra styles, not just the one that has the form.

This project is being developed in .NET, and is taking advantage of master files (a cool feature added in .NET 2.0) The <HEAD> section of the input form is coming from the master file, therefore I can’t simply add the link in .aspx file here. It has to be linked though the backend code. To do this, I added the following code to the Page_Load function:

// Add a CSS file to handle the formatting of the form
HtmlLink cssLink = new HtmlLink();

cssLink.href="/grainstorage/styles/form.css";
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
Header.Controls.Add(cssLink);

This code builds the link with the proper information, then adds it to the header of the page at runtime. Works like a charm when you have a stylesheet that only affects a few pages in your project.

Connecting JavaScript with a TextBox

Yesterday I was working on a web application where we wanted to have a JavaScript function run when the user changes a TextBox. It was a simple function, which took three input values and performs calculations to generate two additional values. I soon discovered two issues when working with JavaScript in ASP.NET. The first is that the TextBox control is server-side, so it doesn’t include the client-side “onclick” attribute. Second, is that when .NET generates the input box, it adds the ID of the parent container to the ID of the TextBox, for example ID=”TextBox1″ may become ID=”ctl00_ContentPlaceHolder1_TextBox1″.

Doing an Internet search, I found two solutions to the first issue. One option is to include the attribute onchange=”myJavaScriptFunction()” in the TextBox control. Visual Studio will give you a warning, but it does work. The second option is to include the following line of code in the Page_ Load function:

TextBox1.Attributes.Add("onchange", "myJavaScriptFunction()");

I prefer this method because Visual Studio doesn’t flag it.

To solve the second issue, I found an example where they used the ClientID attribute of the TextBox Control to find the element in JavaScript. Here is a sample JavaScript Function that does a popup alert, giving the value that was entered in TextBox1:

function myJavaScriptFunction()
{
  var myField = document.getElementById("<%= TextBox1.ClientID %>");

  alert(myField.value);
}

This is a kind of ugly, but it works. You can create as many variables as you need to point to your .NET controls. The function I wrote yesterday had 5 of these temporary variables. Seems like a lot of work to assign values to a couple readonly fields in the form.

Validation Groups

A cool feature of the validation controls in .NET is the property “ValidationGroup”. With this property, you can easily activate different validation controls based on which button is clicked.

For example, suppose you have a content page that has a search box. In addition, this page has a feedback form at the bottom of the page where you can rate “Was this page useful” from 1 to 5. The requirement for this page is that if you click on the search button, you must have entered a search term, and if you click on the rate page button, you must have selected a numerical rating.

To do this, you would add a required field validator for each of these of these fields. However when you test this page, you discover that when you click on the search button, it complains that you didn’t select a page rating, and when you click to page rating button it complains that you didn’t enter a search term. How do you get around this?

Use the ValidationGroup property. In the validation control for the search term text box and the search button, set the property ValidationGroup =”search”, and in the validation control for the page rating entry field and the page rating button set the property ValidationGroup=”pagerating”. This way, when you click the search button, it only runs the validation controls that have ValidationGroup=”search”, and it will not complain that there is not a page rating entered. Likewise with the page rating button.