September, 2009 Archives

24
Sep

NDepend – Woohoo!

by Mikael Lundin in Technicalities

I finally got around and bought my private copy of NDepend. 299€ is an ok price for this kind of software, but taxes adds this up to 400€ and my wallet feels a bit lighter. My heart is also a bit lighter and my brain is estatic.

ComponentDependenciesDiagram

This is a tool that let you analyze your .NET assemblies. There are several purposes for this.

  • Quickly familiarize yourself with a new project.
  • Create nice looking code reports that none will ever read.
  • Know what to refactor and why.

I do a lot of refactoring in my every day work. I refactor for every task I ever make, and this is quite easy when you keep it at the task level, but when you need to take a more grand approach and throw around namespaces and assemblies, you need a tool that give you that overview that will help you make your decisions.

This tool shows you where all your couplings are in your system and gives you a good idea of what you need to do.

The most fun I’ve had with this  tool is running it on a legacy system and just look at the mess. Right now I run it on a daily basis in a greenfield project to make sure that we continue to follow the architecture that was decided upon.

Why did I spend 400€ on this tool? Because I believe that it will help me do work that is easily worth much more than the 400€ that I spent.

Thank you Patrick Smacchia for this!

20
Sep

Dynamic user control list

by Mikael Lundin in Programming

How do you add and remove user controls dynamically on an ASP.NET page?

dynamic_controls

There are many ways to do this and here I will present one.

The page container

Start with adding a button and a placeholder on the page. The button will create user controls in the placeholder.

<div>
    <h1>Name list</h1>
    <asp:Button runat="server" Text="Add" OnClick="AddButton_Click" />
    <asp:PlaceHolder runat="server" ID="DynamicNameList" />
</div>

The user control

The user control is very simple. The delete button is tied to an event that will call the Delete-method on the current page.

<div class="name">
    <asp:Label runat="server" Text="Firstname" />:
    <asp:TextBox runat="server" ID="Firstname" />
    <asp:Button runat="server" Text="Delete" OnClick="DeleteButton_Click" />
</div>
protected void DeleteButton_Click(object sender, EventArgs e)
{
    ((IDynamicControlContainer)this.Page).Delete(this);
}

The IDynamicControlContainer interface

If you want this to work you need to create an interface that has the Delete-method, and implement this interface on the container page. The reason you want the method on an interface and not on the container page, is to create lower coupling from the user control on the container page.

public interface IDynamicControlContainer
{
    /// <summary>
    /// Deletes the specified control from the container
    /// </summary>
    /// <param name="control">The control.</param>
    void Delete(Control control);
}

Keep state between post backs

We will use the ViewState to save and restore state between postbacks. The only thing we need to keep track on our selves is the control IDs that we added to the user control. When we return on postback, we recreate the controls in the placeholder with the previous IDs and trust that ASP.NET will read back the state of these controls for us. When we change the list by adding and removing a control, we also update the list of IDs in ViewState.

Here comes my code behind for the container page.

public partial class NameList : Page, IDynamicControlContainer
{
    protected void Page_Load(object sender, EventArgs e)
    {
        foreach (string id in LoadControlIdList())
        {
            Create(id);
        }
    }

    protected void AddButton_Click(object sender, EventArgs e)
    {
        Create(null);
    }

    public void Create(string id)
    {
        string targetId = id ?? Guid.NewGuid().ToString();
        var control = LoadControl("~/NameControl.ascx");
        control.ID = targetId;

        DynamicNameList.Controls.Add(control);
        SaveControlIdList();
    }

    public void Delete(Control control)
    {
        DynamicNameList.Controls.Remove(control);
        SaveControlIdList();
    }

    public void SaveControlIdList()
    {
        List idList = new List<string>();
        foreach (Control control in DynamicNameList.Controls)
        {
            idList.Add(control.ID);
        }

        ViewState["IdList"] = idList;
    }

    public string[] LoadControlIdList()
    {
        var list = (List<string>) ViewState["IdList"];

        if (list == null)
        {
            return new string[0];
        }
        return list.ToArray();
    }
}

You can download the complete source code sample here.

20
Sep

Unit testing to find bugs

by Mikael Lundin in Technicalities

If you’re unit testing to find bugs, you’re doing it wrong.

A common misconception is that you’re writing unit tests to find bugs. That would be quite useless. Instead you should write unit tests to prevent bugs from happening. You’re saving time and effort by not recieving bug reports, recreating the error and fixing it. Instead you write a small piece of code that test the system, and prevent bugs from happening.

“Prevent bugs from happening”.

I very seldom find any bugs with unit tests. Writing tests forces me to think of any possible scenario for my code. This makes most bug reports to be intended functionality, since you’ve already thought about that situation, but the client has another conception of what a bug is, and what a feature change is. We will receive fewer bug reports, and they will all be more like changes than real bugs.

Most of my applications are web based and unit testing my code takes me away from the browser, which is a very inefficient testing tool. Actually I never really run my code through the browser until I think its done. Several hundreds lines of code can be written before I have to see what it looks like for the website visitor. That makes my work much more efficient since browsers are crap testing tools.

Some things are hard to test.

But you can’t really be sure if it gives any value until you have tried testing it. Make a plan for your project that determines how you should test every part of it. What code should be tested through unit tests, integration tests, and what code should be tested manually or through web tests. Having a plan is essential for your work.

19
Sep

Meta: Blogging about blogging

by Mikael Lundin in Other

Dear Diary,My blog died because of late Wordpress updates, but because of a busy schedule I had to wait for this weekend to fix it. I also change the theme because the old theme made my eyes hurt. I’m getting older and my sight vision is not the eagle eye it used to be.

I’ve not been writing much of late because of projects at work made me work both days and evenings, but now I’m back with much more spare time on my hands. I’ve been holding a seminar about Brownfield development, this Tuesday, and I’m planning to be more active with seminars, discussions and so on the rest of this autumn at Valtech.

I will participate in Valtech Days and present a case study about  how we made axflow.com. It will be interesting because it was some time ago since I last held a public presentation. I’m sure it will turn out fine.

Right now I’m working on a project that is making me very happy, since I’m allowed to practice all those methods that allow high quality.  We’re using code reviews, unit testing, web testing and agile methologies to produce a high quality solution. I’m looking forward doing a review of the project and report on what worked, and what did not.

That was this year’s meta blogging article. Have a great autumn everyone!

Mikael Lundin

9
Sep

Populate an ASP.NET view with data

by Mikael Lundin in Programming

I’ve found four ways to populate an ASP.NET view with data.

  1. Databind from Page_Load in code behind
  2. OnLoad event on the databinding control
  3. Fetching data from a method with databound expression
  4. DataSourceControl

Databind from Page_Load in code behind

When I see this happening I automatically removes it and blame the developer who ever put it there. My Page_Load should be as clean as possible. If there is a way to remove code from the Page_Load I will attempt to do it.

protected void Page_Load(object sender, EventArgs e)
{
    ColorsDropDownList.DataSource = new[] { "Blue", "Green", "Blue" };
    this.DataBind();
}

This is a big no no!

OnLoad event on the databinding control

There is a method where you use the OnLoad-event to databind the control. The good thing about this is a clear separation of concern between the control being databound and the data that is bound.

<asp:DropDownList runat="server" ID="NamesDropDownList"
OnLoad="Names_DataBind" />

protected void Names_DataBind(object sender, EventArgs e)
{
    var control = (BaseDataBoundControl)sender;
    control.DataSource = new[] { "James", "Joe", "Jimmy" };
    control.DataBind();
}

I find this much neater. The method responsible for finding the data has no idea on what control is used for databinding.

Fetching data from a method with databound expression

Here comes something similar to the previous example. We act at the event OnLoad and databind the control itself with a databoundexpression.

<asp:DropDownList runat="server" ID="FlowersDropDownList"
DataSource="<%# GetFlowers() %>" OnLoad="DataBind" />

protected void DataBind(object sender, EventArgs e)
{
    ((Control)sender).DataBind();
}

protected string[] GetFlowers()
{
    return new[] { "Rose", "Lily", "Dragonflower" };
}

In this example I would place the DataBind callback method in a common PageBase or UserControlBase where it could be reused all over the application.

The power of this method of databinding is reusing dataproviding method with only changing arguments to the method from markup. This is something that is not possible with our previous method of databinding. You should beware of putting logic in the databound expression since it is inline code in markup.

DataSourceControl

The most powerful method of databinding is implementing a DataSourceControl. This is useful when you have a common data store that you want to get data from, and use different views to display parts of that data. This is the most concern separated application here, but also the most time consuming and complex. Use this when you notice that you query the same data in more than three different ways or from three different places in your code.

<asp:XmlDataSource runat="server" ID="CmsPages" DataFile="~/App_Data/cms.xml" />
<asp:Repeater runat="server" DataSourceID="CmsPages">
    <HeaderTemplate><ul></HeaderTemplate>
    <ItemTemplate>
        <li>
            <a href="<%# Eval("url") %>"><%# Eval("title") %></a>
        </li>
    </ItemTemplate>
    <FooterTemplate></ul></FooterTemplate>
</asp:Repeater>