Tales from the trenches: ASP.Net ViewState bug


This post is part of a series of actual problems or bad practices I encountered working on existing C# code bases.

The names of all identifiers, the exact functionalities of the programs and the code samples have all been altered for confidentiality reasons.

While looking into a slow ASP.Net page I noticed that the page was making a lot more service calls than it should have. Visually I could see superfluous calls that should have been merged together.

I profiled the page with the Performance Tools in Visual Studio and also put breakpoints on all service calls and ran it in Debug mode.

One thing that stood out was one property that was supposed to be using ViewState to prevent calls to the service layer but actually wasn’t.

It went something like this :

public int Somevalue 
{
    get 
    {
        if (ViewState["SomeValue"] == null)
        {
            var foo =
            ValueService.GetSomeValue(Convert.ToInt32
                (Request["SomeValue"]));

            ViewState["SomeValue"] = foo;
        }
        
        return (int)ViewState["SomeValue"];
    }
    set 
    {
        ViewState["SomeValue"] = value;
    }
}

// ...

protected override void OnInit(EventArgs e)
{
    int x = SomeValue;	// contrived example
}

I noticed that ValueService.GetSomeValue was getting called on PostBacks. Looking at where it was used, I saw it was being called in the OnInit method. It just so happens that during the OnInit phase of the ASP.Net page life cycle, the ViewState hasn’t be loaded with it’s values. This effectively means that SomeValue will always be null in the OnInit phase and it will have to make a service call every time.

The solution in this case was simply to move the call to a later stage of the page life cycle, in this case the PageLoad event.

The take away from this is to be mindful of the ASP.Net page life cycle events. Also putting breakpoints on service calls while loading the page and submitting the form is a quick way to see if something is amiss with your service calls.

Tales from the trenches: ASP.Net static variable bug


This post is part of a series of actual problems or bad practices I encountered working on existing C# code bases.

The names of all identifiers, the exact functionalities of the programs and the code samples have all been altered for confidentiality reasons.

While working on an ASP.Net control bug, I noticed this more important problem which hadn’t been reported.

The reported bug was about a control that would sometimes not repopulate itself. It was a pretty simple case.

if (ConditionA && lastValue != currentValue)
{
    lastValue == currentValue;
    // more code
}

What happened is that when ConditionA failed, lastValue wasn’t updated. The fix was simply to move the lastValue assignment statement outside of the conditional.

The bigger problem I noticed was when I decided to look at how lastValue was implemented.

It turned out it was implemented as a static member variable. This being an ASP.Net page, a static variable is shared between all instances of the class in the AppDomain.

What this effectively means is that every user of the site shares this same variable.

Suppose user A fills lastValue with “test”, then user B fills currentValue with “test”, the server-side code detects that user B has already used this value as his value (since it’s currently in lastvalue), even if he hasn’t entered anything before. This could lead to some inconsistent behaviour.

The lesson here is two-fold:

1- Do not to cache information with a static variable in an ASP.Net site unless that information is not subject to change from user to user.

2- When working on existing code, make sure you understand correctly how it is implemented. In this case I could have glossed over the implementation of lastValue, which wasn’t declared near the method I was working on and missed this important bug.

Making your own simple test framework in F#

I’m currently programming in F# under Linux. This means no Visual Studio and no MSTest GUI test runner. My first reaction was to start looking at using NUnit or xUnit for my project.

I then had a thought. Why not write my own simple test “framework”. It sounded like something easy to do and pretty fun. In retrospect, it was.

Of course this is nothing like a full featured test framework but it’s enough for my purposes.

Here is the test framework:

module TestFramework

// assert functions
let assertAreEqual expected actual =
    if expected <> actual then
        sprintf "Test failed, expected %A, actual %A" expected actual
    else
        "Test passed"

let assertIsGreaterThan target actual =
     if target >= actual then
        sprintf "Test failed, expected %A to be greater than %A" target actual
     else
        "Test passed" 

// test runner
let runSingleTest (testName, testFunction) =
    sprintf "%s... %s" testName (testFunction())       

let runTests testList =
    testList |> List.map (runSingleTest)

let consoleTestRunner testList =
    runTests testList |> List.iter (printfn "%s")
    printfn "%s" "Ran all tests."

F#’s automatic generalization cuts down on explicit generics or function overloads in the assert functions.

This makes the code more succinct and development less tedious.

Right now there is only a consoleTestRunner but more types of test runners could be implemented to accommodate other interfaces like a GUI.

And here are some sample tests:

module Tests

open TestFramework

// modules under test
open HeightMap
open MidpointDisplacement

// tests included in run
let testsToRun =
    [
        "newHeightMap will return a 0 initialized height map",
        fun() ->
            let hm = newHeightMap 5
            let result = hm.Map |> Array.sum
            assertAreEqual 0.0 result;

        "set will update height map",
        fun() ->
            let hm = newHeightMap 5
            hm.Set 1 1 0.5
            assertAreEqual 0.5 (hm.Get 1 1);

        "convertFloatToRgb will convert 0.0 to r:0, g:0, b:0",
        fun() ->
            let red, green, blue = convertFloatToRgb 0.0
            assertAreEqual (0, 0, 0) (red, green, blue);

        "convertFloatToRgb will convert 1.0 to r:255, g:255, b:255",
        fun() ->
            let red, green, blue = convertFloatToRgb 1.0
            assertAreEqual (255, 255, 255) (red, green, blue);                                               

        "convertFloatToRgb will convert 0.5 to r:127, g:127, b:127",
        fun() ->
            let red, green, blue = convertFloatToRgb 0.5
            assertAreEqual (127, 127, 127) (red, green, blue);

        "middle will set the midpoint value between each corner to the average of the corners plus the result of a function",
        fun() ->
            let variationFunction x = x + 0.1
            let hm = newHeightMap 2
            hm.Set 0 0 0.5
            hm.Set 0 4 0.5
            hm.Set 4 0 1.0
            hm.Set 4 4 0.25
            middle hm (0, 0) (4, 0) (0, 4) (4, 4) variationFunction
            let middleValues = [hm.Get 0 2; hm.Get 2 0; hm.Get 2 4; hm.Get 4 2]
            assertAreEqual [0.6; 0.85; 0.475; 0.725] middleValues;
    ]

The tests themselves are represented as data, which is a common concept in functional programming. Each test is a tuple with the first argument being the name of the test as it will appear in the console during a test run.

Here is how to call the framework along with a sample test run output :

open TestFramework
open Tests

consoleTestRunner testsToRun

newHeightMap will return a 0 initialized height map… Test passed
set will update height map… Test passed
init corners will assign values to the height map corners… Test passed
convertFloatToRgb will convert 0.0 to r:0, g:0, b:0… Test passed
convertFloatToRgb will convert 1.0 to r:255, g:255, b:255… Test passed
convertFloatToRgb will convert 0.5 to r:127, g:127, b:127… Test passed
set will correctly change the values of an heightmap… Test passed
middle will set the midpoint value between each corner to the average of the corners plus the result of a function… Test passed
Ran all tests.

Since I’m just beginning with F#, I had my code reviewed on codereview.stackexchange.com and had some great answers. I can’t recommend this site enough for when you are starting out with a new language.

Randomly generating a 2d RPG world

Randomly generating a 2d RPG world

This is a compilation of all my posts about using procedural content generation to create a random 2d RPG world.

The first step is to create a heightmap. This randomly generated bitmap will serve as the basis of the world map. Then we can convert this heightmap to our world map. Finally we can generate some random names for our map (world name, city names, etc.)

Filtered Twice
Height map

Create the heightmap

Generating heightmaps using particle deposition

Using Gaussian blurring on heightmaps

caves1
A remote mountain cave.

Create the 2d world map

Creating a random 2d game world map

Creating a random 2d game world map, Part 2: Adding rivers and lakes

Creating a random 2d game world map, Part 3: Cities, caves and snow

I had used an open source implementation of the A* algorithm to add roads between cities. Sadly, I have never written about it. But here is a link to the relevant code:

Adding roads to our world map

cities1
A city next to a river.

Generating random names

Algorithm to generate random names

A better algorithm to generate random names

snow1
A snowy island.

Finally here is a link to a Github repository where I had implemented these algorithms:

Gameproject Repo