Long Code Lines in Articles and Tutorials

While publishing articles for ASP Alliance I often take the time to fix long code lines I find in the articles. These bother me greatly, because they make web pages and thus the article ugly and difficult to read. I hate having to scroll horizontally to read a long line of code. It is annoying and takes more time. I don't get why people don't trim their code. I keep my code neatly trimmed when I'm writing articles, and also whenever it is code I am writing in general. I never want code lines to be too long. I have no problem scrolling vertically, but there should be some set limits on how long lines should ever be especially when the lines will be posted on the Internet.

Some of the ugliest sites I've ever seen are the ones where text has gotten too wide and has taken over the layout of a page. Widths have been stretched and the page extends beyond its intended positioning. I admit this has happened plenty of times on sites with which I am associated and I am ashamed. It would be nice if I could convince the rest of the development community of the importance of having code be easy to read. How can I possibly intend to help other people understand something through an article or tutorial when my code is difficult to read. I'm not helping their understanding at all by having them struggle to read the code let alone understand it.

I think overall the software development community could use a facelift. My site included. Sadly my skills in the area of design are quite lacking. Formatting text in a readable manner is about the extent of my skills, but I believe that is likely the most important task to complete.

Get rid of lines like this one.

MyCompany.Controls.DropDownList commentselectionddl = SomeTemplatedControlOnThePage.FindControl("commentselectionddl") as MyCompany.Controls.DropDownList;

Replace them with lines like this one.

MyCompany.Controls.DropDownList commentselectionddl = 
    SomeTemplatedControlOnThePage.FindControl("commentselectionddl") as MyCompany.Controls.DropDownList;

For the benefit of everyone involved in this wonderful community of developers, format your code. Make it more readable. Don't let lines trail off into the distance. Keep them short and concise. Use simple examples, and never make code more complicated just to show how smart you are. I've seen plenty of code where authors attempt to complicate their own code seemingly to make themselves appear smarter. Remember, when you write code you should not be writing for yourself. Write the code for someone else to learn. Write to help other people and make the community as a whole a better place. Sure it benefits you when you teach others, but remember that at the end of the day other people will be reading what you write.

Passing ViewData to User Controls in ASP.NET MVC Preview 4

Yesterday I was upgrading an ASP.NET MVC site from Preview 2 to Preview 4. For the most part this is an easy process. Some assemblies needed to be updated and some information updated in the web.config file. Route declaration changed, but the same information is still required, so updating that was pretty easy. The released documentation and examples clearly show these changes. I also had to make the change to my controller actions so that they return ActionResults instead of being void methods. Again, this is a fairly simple task.

There was an adjustment to user controls which caused some problems though. Yasir and I were working on this task together so we could both learn about the preview 4 changes in MVC. We scoured articles looking for this information, and we tried many different changes to the user control.

Our problem was that we could not get access to the ViewData. ViewData in the user control was always null. It was quite annoying. Eventually in desperation after reading articles and release notes and not finding what we were looking for, we started reading the source code for MVC. We took a look at this file, which is the one containing the extension method we were calling in the .aspx files. System.Web.Mvc.UserControlExtensions This file contains the extension method RenderUserControl, which our code used.

The .aspx code we were using

<%
   =Html.RenderUserControl("~/Views/Shared/MyUserControl.ascx", ViewData, new { DisplayTitle = "Hello World!" }) 
%>

RenderUserControl calls this method called DoRendering

private static string DoRendering(ViewUserControl instance, ViewContext context, object controlData, object propertySettings) {
            ViewPage dummyPage = new ViewPage();
            dummyPage.ViewContext = context;
            dummyPage.Controls.Add(instance);
            dummyPage.InitHelpers();

            //set the properties

            SetUserControlProperties(instance, propertySettings);

            if (controlData != null) {
                instance.ViewData.Model = controlData;
            }
            else {
                instance.ViewData = context.ViewData;
            }

            //Render it

            string result = HtmlExtensionUtility.RenderPage(dummyPage);

            return result;
        }

In my haste to find a solution, I didn't read the code very carefully. All I noticed was exactly how to solve our problem. I discovered that the controlData parameter we were passing to this method was being assigned into instance.ViewData.Model. I didn't even read the next couple of lines which gave away the real answer. We went and added in the .Model to our code so that it could access the ViewData. The ViewData we were passing was going into a property of the ViewData called Model, so we just used it. We went to our user control and we changed the code there. This felt really bad to us, but we went along with it.

Today I realized our error. I was thinking about the code we had looked at this morning, and I realized our mistake. I was wondering, "Why was it checking if control data was null? If it was null shouldn't ViewData.Model be null? That's our ViewData right?" That is when I realized what must have been after that.

We were not supposed to be using Model. We had some standard ViewData. No strongly-typed ViewData was being used. We were using an the standard ViewDataDictionary object and passing it to the user control. A ViewUserControl object (which is the class we were inheriting from) supports generics. It was at that time when I realized exactly what everything was being used for. The Model property and the controlData parameter are there for strongly typed ViewData. You can use boxing and unboxing or generics to pass strongly-typed data to your ViewControl. The parameter and the generic Model were added so that the ViewData property of the ViewUserControl would not be interfered with.

This solution the MVC guys use allows custom ViewData to be used without having to muck the ViewData property of the user controls. Since they added this extra piece it could be the generic one. So now I have gone and changed my code. I no longer pass the ViewData as was done in the past. It is now simply grabbed from the context of the page. I pass a null value instead of passing in any controlData to the RenderUserControl method. It wires everything up for me now.

<%=Html.RenderUserControl("~/Views/Shared/MyUserControl.ascx", null, new { DisplayTitle = "Hello World!" })%>

As a reminder to everyone. Open source code means that you can go look at the code. If you are not sure how something works, just go read the code. It is freely available on CodePlex. You can look at how everything is working and get a much better understanding of the inner workings of the technology.

Difference Between Value Types and Reference Types in C#

I recently wrote an article for C# beginners in which I explain the differences between value types and reference types in C#. It was published on ASP Alliance today. If you're new to C# or are even a little fuzzy on these concepts, I recommend you check it out. Please offer some feedback good or bad. I really do read and appreciate feedback I receive. I try to improve what I write based on what others tell me.

I've seen so many people run aground with errors stemming from misunderstandings about and just forgetting the importance of value and reference types.

Good day and happy programming!

Handling Password Recovery

I recently answered a blog post about how to handle password recovery in ASP.NET. My first thoughts when I read this questions are along the lines of, "Ah! Don't recover passwords!"

With any authentication system it is important to remember this one thing passwords should always be hashed. I don't care who you are or what system you're using, you should never ever have passwords stored in your system which are not at least encrypted in some format. In ASP.NET you want to use hashing. Being able to "recover" a password implies that the password is in a form that you could make it user-readable.

This is bad since it means that if someone managed to obtain your password data they could potentially obtain people's passwords. Considering that lots of users will use the same password in multiple places, that could be very bad.

What you need to do instead of recovering a password is to reset a user's password. They can then log in using the new password and change it to the one they want. This allows you to keep their password secure and to still allow them to recover from the issue. It just makes it a little bit more complicated for the user, but having the extra security is by far worth it. Most users will agree with you on this.

As a user I am quite upset when a site is able to "recover" my password. I am annoyed by the password policies of quite a few sites on the Internet. I've had sites limit the length of my passwords, limit the types of characters I may use, and many other sometimes asinine things.

Just always use password resets. It just makes things a little bit safer for your users. They'll be thanking you for it even if they don't actually express it to you.

Here you can read about ASP.NET Password Recovery. I just recommend you use hashed passwords and only allow password reset and not password retrieval.

Web Application Projects are better than Web Sites

Recently I was explaining the difference between the web application project and the web site to the budding developers I've been working with. I suffered greatly while using web sites instead of web application projects. I remember having a great deal of pain while my assemblies dueled each other. Scott Guthrie posted about the dueling assembly problem.

Dueling Assembly Reference Problem

The problem I refer to as a “dueling reference” occurs when you setup multiple file-based references to assemblies from a VS 2005 Web Site Project that are each updated dynamically (using .refresh files), and which in turn have dependencies on different versions of a common shared assembly library.

This one reason was more than enough in my opinion to switch to web application. It took some sites which could take upwards of five to ten minutes to compile and made them take ten seconds. I can't ask for much better improvement there.

Another great benefit of using Web Application Projects instead of using the Web Site is that there is a project file managing what is and is not included. On a few of the projects I've worked on in the past we have had some trouble with source control and web sites. It is much easier if you can just define what is and is not included in the web site. With the classic web sites, it was a loose system. The site was defined as a folder in the file system. With the web application project your site is defined using a project file which dictates which files will and will not be included.

On really annoying part of web sites are the refresh files used for adding assemblies into the bin folder. There are files which say where the assembly can be obtained. If you're working with source control you need to have these files in source control. The problem is that you need to not have the actual binaries in that location in source control or the refresh files will not work correctly. This creates some huge headaches because Visual Studio wants to check in these files (assemblies) being included by the refresh files. Ouch.

The feel of web applications is more consistent with everything else in Visual Studio. This consistency is nice, since there now is "Open Web Site" and "Open Project". It is quite annoying to have two different things to work with. If they were both just project that would make it so much simpler.

Far too many people are still using the sites, so I doubt that Microsoft will remove them from future versions of Visual Studio anytime soon. It doesn't really hurt me to have them, but I pretty much exclusively use Web Application Projects over Web Sites. I even do this for small little one shot sites. I've just grown to like them so much that I cannot turn back.

If I have to deal with refresh files again, I'll just go crazy.