Microsoft Charting Controls: Adding Charts Dynamically

So this is kind of repost as I had already posted this at StackOverflow but I thought it might have some merit here. Whatever. Charts are hot right now so I’m going to push the damned bandwagon. You don’t like it? Well then go do something to yourself that you would consider rude for me to suggest it. Anyways, this might have been overkill but hey, that’s me.

protected void Page_Load(object sender, EventArgs e)
{
Bench benchList;
FoodIntake foodIntakeList;
Panel panelChartHolder;

panelChartHolder = new Panel();
Controls.Add(panelChartHolder);

benchList = Bench.GetAll();
AddNewCharts(benchList, panelChartHolder, GetBenchXValue, GetBenchYValue);

foodIntakeList = FoodIntake.GetAll();
AddNewCharts(foodIntakeList, panelChartHolder, GetFoodIntakeXValue, GetFoodIntakeYValue);
}

Ok so this first part is simple. Create a panel to hold the charts you are adding, get the lists you want represented by the charts and call the method to create the charts.

  private void AddNewCharts(T[] listToAdd, Panel panelToAddTo,
     Func<T, DateTime> xMethod, Func<T, Int32>)
  {

    ChartArea mainArea;
    Chart mainChart;
    Series mainSeries;

    mainChart = new Chart();
    mainSeries = new Series("MainSeries");

    for (Int32 loopCounter = 0; loopCounter < listToAdd.Length; loopCounter++)
    {
      mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]),
        yMethod(listToAdd[loopCounter]));
    }

    mainChart.Series.Add(mainSeries);
    mainArea = new ChartArea("MainArea");
    mainChart.ChartAreas.Add(mainArea);

    panelToAddTo.Controls.Add(mainChart);
  }

As you can see, I just created a new chart, added a series to it, and added a ChartArea to it. Next part is pretty much just looping through the collection and adding each item in it to the list itself. It uses the passed in delegate methods (Func) to get the X and Y values.

Last part holds the four methods responsible for getting the X and Y values from the two lists. Basically I did this to allow the chart creating method to be a generic as possible. Might be overkill.

  private DateTime GetBenchXValue(Bench currentBench)
  {
    return currentBench.DateLifted;
  }

  private Int32 GetBenchYValue(Bench currentBench)
  {
    return currentBench.BenchAmount;
  }

  private DateTime GetFoodIntakeXValue(FoodIntake currentIntake)
  {
    return currentIntake.DateEaten;
  }

  private Int32 GetFoodIntakeYValue(FoodIntake currentIntake)
  {
    return currentIntake.Calories;
  }

And so when you run this, you will get two graphs side by side. Mind you, they will be very plain as there are million different properties that can be set to improve the look. I guess the main point of this was to show that it’s pretty easy to create graphs dynamically using any kind of object list. You know what? Screw you. This is my blog and I’ll post whatever I want to. If you don’t like that then you can just come back at a later time and read something else I post. Yeah so there.

  using System;
  using System.Web.UI.DataVisualization.Charting;
  using System.Web.UI.WebControls;

Microsoft Charting Control: So easy an idiot can use it… And I have.

So just recently it was announced that there was a new charting control out for .Net/Visual Studios so I thought I would give it shot. How hard could it be? Well considering it took me 2? years to figure out my Playstation 3 had a wireless card, an uphill battle wasn’t out of the question.

So what the hell has to be done first? Well you need the 3.5 Framework (Sucks if you don’t have that) and service pack 1 (Which doesn’t suck as much but still annoying. I WANT EASY THINGS).
Have those? Great, way to be in the know. Now for the next step, more downloads. Here is the charting install and you need this too to see the actual tool in your toolbox. AMAZING. Now you just have to run the installs, which oddly enough are easy to do. First time for everything.

So now you have them installed right? Ok well do the normal project create/startup, add a new page, and view Design. Go to the old toolbox and look under the Data tab. (Don’t ask me why it’s there because I don’t know and will be compelled to cut you.) Now under the chance you don’t see it there you either didn’t install the second download or you have to add the namespace the control falls under. No problem. Just right click the Data tab and select “Choose Items”. Now in the.Net Framework Components tab look for the Namespace “System.Web.UI.DataVisiualization.Charting” and you should see the name Chart to the right of it. Select that item.

Ok, so now there should be a Chart control in your ToolBox in the Data Tab. You can now drag that thing over. Now in the markup you should see:

<asp:Chart ID=”Chart1″ runat=”server”>
<Series>
<asp:Series Name=”Series1″></asp:Series>
</Series>
<ChartAreas>
<asp:ChartArea Name=”ChartArea1″></asp:ChartArea>
</ChartAreas>
</asp:Chart>

If that doesn’t excite you, then I don’t know what will. Anyhow, it’s actually very simple. Series is the line or whatever you are representing the data as and the chart area is what holds the series(s). Seems easy enough, but don’t worry, it gets easier. Now for this example I’m going to actually have two series and they are going to represent amount of weight Bench Pressed and the caloric intake for a given day. Best thing I could come up with right now since today was bench day.

<asp:Chart ID=”chartMain” runat=”server”>

<Series>
<asp:Series Name=”seriesBenchAmount” />
<asp:Series Name=”seriesFoodIntake” />
</Series>
<ChartAreas>
<asp:ChartArea Name=”chartAreaMain” />
</ChartAreas>
</asp:Chart>

Yeah that’s pretty good. So now what I need is to throw some fake data at it, and to do that I created a Bench table and a FoodIntake table followed by using Linq To Sql to create the needed classes. When all was said and done I could easily do this:

  private const String CHART_AREA_MAIN = "chartAreaMain";
  private const String SERIES_BENCH_AMOUNT = "seriesBenchAmount";
  private const String SERIES_FOOD_INTAKE = "seriesFoodIntake";

  protected void Page_Load(object sender, EventArgs e)
  {
    Bench[] benchList;
    Series currentSeries;
    FoodIntake[] foodIntakeList;

    benchList = Bench.GetAllBenches();
    currentSeries = chartMain.Series[SERIES_BENCH_AMOUNT];
    for (Int32 loopCounter = 0; loopCounter < benchList.Length; loopCounter++)
    {
      currentSeries.Points.AddXY(benchList[loopCounter].DateLifted,
         benchList[loopCounter].BenchAmount);
    }

    foodIntakeList = FoodIntake.GetAll();
    currentSeries = chartMain.Series[SERIES_FOOD_INTAKE];
    for(Int32 loopCounter = 0; loopCounter < foodIntakeList.Length; loopCounter++)
    {
      currentSeries.Points.AddXY(foodIntakeList[loopCounter].DateEaten,
          foodIntakeList[loopCounter].Calories / 10);
      }
  }

Now believe it or not, that’s all you have to do to get a graph. Pretty easy to say the least. Now the graph that you get will be default everything (And in this case it gives you a bar graph) but still at least that’s something to work with. (Note that I cheated with the food intake by dividing by 10. Unfortunately the graph would look odd with a day of 3500 calories and a 325 bench.)

Now maybe you want this to be a line graph… Whatever can we do?

protected override void CreateChildControls()
{
    base.CreateChildControls();
    Series currentSeries;
    ChartArea currentArea; 

    currentSeries = chartMain.Series[SERIES_BENCH_AMOUNT];
    currentSeries.XValueType = ChartValueType.DateTime;
    currentSeries.YValueType = ChartValueType.Int32;
    currentSeries.ChartType = SeriesChartType.Line;
    currentSeries.BorderWidth = 3; currentSeries.MarkerStyle = MarkerStyle.Square;

    currentSeries = chartMain.Series[SERIES_FOOD_INTAKE];
    currentSeries.XValueType = ChartValueType.DateTime;
    currentSeries.YValueType = ChartValueType.Int32;
    currentSeries.ChartType = SeriesChartType.Line;
    currentSeries.MarkerStyle = MarkerStyle.Circle;
    currentSeries.MarkerColor = Color.Red;
    currentSeries.BorderWidth = 3;

    currentArea = chartMain.ChartAreas[CHART_AREA_MAIN];
    currentArea.Area3DStyle.Enable3D = false;
}

So what’s all this? Well this:

I MADE THIS!!11
I MADE THIS!!11

So pretty, yah? So what does it all mean?

    currentSeries.XValueType = ChartValueType.DateTime;
    currentSeries.YValueType = ChartValueType.Int32;

Well this is pretty simple, this merely sets the types for the X and Y axis. I told you it was simple.

    currentSeries.ChartType = SeriesChartType.Line;

If you can’t figure that one out, try another profession like engineering.

    currentSeries.MarkerStyle = MarkerStyle.Circle;
    currentSeries.MarkerColor = Color.Red;

Ok these three things are used to control how the points on the lines (Markers) actually look. Pretty self explanatory once the word “marker” is translated.

    currentSeries.BorderWidth = 3;

This is the thickness of the line itself.

    currentArea.Area3DStyle.Enable3D = false;

If you guessed this was a way to make the grid 3d, you were right on and probably able remind yourself to breathe at a maximum 3 times a day.

So now you are thinking you have this down to an expert level and I say,”sure why not?” ‘cept with a little work on the mark up I could make it look like this:

OoooOooOo
OoooOooOo

And just like Beloch said in Raiders of the Lost Arc before his face exploded, “It’s Bewtifewl!”

Now for the Usings!!11

    using System;
    using System.Drawing;
    using System.Web.UI.DataVisualization.Charting;

And the final markup:

<asp:Chart ID=”chartMain” runat=”server” Palette=”EarthTones” BackColor=”Azure” ImageType=”Jpeg” ImageLocation=”~/ChartImages/ChartPic_#SEQ(300,3)” Width=”412px” Height=”296px” BorderDashStyle=”Solid” BackGradientStyle=”TopBottom” BorderWidth=”2″ BorderColor=”181, 64, 1″>
<series>
<asp:Series Name=”seriesBenchAmount” MarkerSize=”3″ BorderWidth=”3″ ShadowColor=”Black” BorderColor=”180, 26, 59, 105″ Color=”220, 65, 140, 240″ ShadowOffset=”2″ />
<asp:Series Name=”seriesFoodIntake” MarkerSize=”3″ BorderWidth=”3″ ShadowColor=”Black” BorderColor=”180, 26, 59, 105″ Color=”220, 224, 64, 10″ ShadowOffset=”2″ />
</series>

<chartareas>
<asp:ChartArea Name=”chartAreaMain” BorderColor=”64, 64, 64, 64″ BorderDashStyle=”Solid” BackSecondaryColor=”White” BackColor=”OldLace” ShadowColor=”Transparent” BackGradientStyle=”TopBottom”>
<area3dstyle Rotation=”25″ Perspective=”9″ LightStyle=”Realistic” Inclination=”40″ IsRightAngleAxes=”False” WallWidth=”3″ IsClustered=”False” />
<axisy LineColor=”64, 64, 64, 64″>
<LabelStyle Font=”Trebuchet MS, 8.25pt, style=Bold” />
<MajorGrid LineColor=”64, 64, 64, 64″ />
</axisy>
<axisx LineColor=”64, 64, 64, 64″>
<LabelStyle Font=”Trebuchet MS, 8.25pt, style=Bold” />
<MajorGrid LineColor=”64, 64, 64, 64″ />
</axisx>
</asp:ChartArea>
</chartareas>
</asp:Chart>

Linq Extension Methods Versus Linq Query Language… DEATHMATCH

Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that’s not entirely true. Say you are using these three funcs:

    Func<User, String> userName = user => user.UserName;
    Func<User, Boolean> userIDOverTen = user => user.UserID < 10;
    Func<User, Boolean> userIDUnderTen = user => user.UserID > 10;

As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let’s face it, the third should be pretty easy to understand now.

NOTE: This is a silly example but it works.

    var userList =
      from user in userList
      where userIDOverTen(user)
      select userName;
Versus

    var otherList =
      userList
      .Where(IDIsBelowNumber)
      .Select(userName)

In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can’t since it is look just for a Boolean rather than a Func that returns boolean. However, this is where it might be better to use the expression language. Say you already had a method that takes in more than just a user:

    private Boolean IDIsBelowNumber(User user, Int32 someNumber, Boolean doSomething)
    {
      return user.UserID < someNumber;
    }

Note: doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean. Kind of annoying for this example.

Now if you look at the Linq query:

    var completeList =
      from user in userList
      where userIDOverTen(user, 10)
      select userName;

You’re good for it. Now the Extension Method:

    var otherList =
      userList
      .Where(IDIsBelowNumber????)
      .Select(userName)

Without a lambda expression, I really can’t call that method. So now what I have to do is create a method that creates a Func based off the original method call.

    private Func<User, Boolean> IDIsBelowNumberFunc(Int32 number)
    {
      return user => IDIsBelowNumber(user, number, true);
    }

And then plug it in:

    var otherList =
      userList
      .Where(IDIsBelowNumberFunc(10))
      .Select(userName)

What does this all mean? You just lost 5 minutes of your life. I hope it was worth it.

Change Target Framework on a Class Library (Visual Studios 2008)

Ok so this is a quick one but annoys the hell of of me.

Basically I am working with a 2.0 class library project and I wanted to use Linq. Now you would think when you “upgrade” the project to 3.5 using the wizard, the target framework would follow. Well, you are stupid. Now for web projects it seems you can look at the properties -> build and boom you can see it bright as day. Try doing this with a class library you and got nothin’.

Here’s the solution:

Goto the project properties -> compile -> Advanced Compile Options AND YOU WILL BE VICTORY!!11

So easy even a child could do it… after an hour of searching on google…

Skins in ASP.Net and how behind I am

So something that has been around for while that I just stumbled upon is Skinning. Basically, this allows you to sent a certain look (using style sheets) for every control in the site. This even includes the built in controls like Tables and Textboxes. How is this done? Well maybe I can tell you.

First you have to go to your project and right click (yes I could make images, but honestly that’s more work than needed.) the project itself. Add -> Add Asp.net Folder -> Theme.

Yay, you have a folder. Sweet. Now you actually have to add the skin itself. Guess what you have to right click? Yes, the new folder. Add -> New Item -> Skin File. Name it whatever (I say you call it Basic because that’s what I called it for this example) and open it up.

Now you have to create a .css file, if you don’t already have one, and for this example let’s say you make one called SkinMe.css. Now you get to add these meaningless classes:

.defaultTable
{
    width:500px;
    border-color:Black;
    border-style:solid;
    border-width:thin;
}

.defaultTable tr
{
    width:500px;
    background-color:Navy;
}

.defaultTable td
{
    color:Red;
}

.nonDefaultTable
{
    width:300px;
    border-color:Black;
    border-style:dotted;
    border-width:thick;
}

.nonDefaultTable tr
{
    width:500px;
    background-color:Navy;
}

.nonDefaultTable td
{
    color:Red;
}

Basically, I have two different classes for tables, with really only one difference. (border-style:dotted) Now you need that actual markup file to hold these wonderful tables:

    <asp:Table ID="tableSkinDefault" runat="server">
        <asp:TableRow ID="tableRowSkinDefault" runat="server" >
            <asp:TableCell ID="tableCellSkinDefault" runat="server" >
                hihihi
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

    <asp:Table ID="tableNonDefault" runat="server" SkinID="nonDefaultSkin" >
        <asp:TableRow ID="tableRowNonDefault" runat="server" >
            <asp:TableCell ID="tableCellNonDefault" runat="server" >
                hihihi
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

Now you might notice that the second table is using the SkinID tag. This will make sense in the next part. Have your skin file open? Gooood. Now just paste this into it:

    <asp:Table runat="server" CssClass="defaultTable" />
    <asp:Table runat="server" CssClass="nonDefaultTable" SkinId="nonDefaultSkin" />

Now it might be making more sense. Once I added the SkinId tag to the skin file, this allowed me to have the same control take on two different classes. Now, you can only have one default (The first one as it doesn’t have the SkinId tag) and any others for the same control have to use the SkinId tag.

Now go back to the two tables and once again you’ll see there is one with a SkinId tag and one without. The one without will take the default look and the one with will take the named look. Pretty simple, right? Well we’re not completely done yet. Two more small steps:

Be sure to remember to link the style sheet on the page with the tables:

    <link href="../CSS/SkinMe.css" type="text/css" rel="stylesheet" />

And you have find the “pages” section of the web.config and add a tag:

    <pages styleSheetTheme="Basic">

And now you have the ability to set every table’s class in the entire site. Best thing is, this can be used for other properties too. Say you have a name property on some usercontrol (We’ll call it MapControl). You can do this:

    <%@ Register Assembly="Some.Control.Assembly" Namespace="Some.Control.Assembly.Controls" TagPrefix="someControl" %>

    <someControl:MapControl Name="Hi" />

And now every MapControl will have the Name property set to “hi”. Kind of nice.

UpdatePanel and UserControl Events

So on the funnest programmin’ site evar someone had asked how to allow an UpdatePanel on a page handle an event of a UserControl. So here’s the situation:

Let’s say you have a UserControl and on that UserControl you have a DropDownList. I know, this is getting complex, but just bare with me. Now imagine, if you will, you want the Parent page’s UpdatePanel to trigger off of the mentioned DropDownList. As it stands, this isn’t going to happen. Why? Because the Parent really can’t capture the event firing on the control since it is localized to the UserControl. What to do? Easy, just pass the event on.

    public partial class CatchMyEvent : UserControl
    {
        public delegate void ChangedIndex(object sender, EventArgs e);
        public event ChangedIndex SelectedIndexChanged;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            dropDownListThrow.SelectedIndexChanged +=
               new EventHandler(dropDownListThrow_SelectedIndexChanged);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }

        public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(SelectedIndexChanged != null)
            {
                SelectedIndexChanged(sender, e);
            }
        }
    }

As you can see, all I’ve done

  1. Created a PUBLIC delegate and event that has the same signature as the SelectedIndexChanged event
  2. Captured the SelectedIndexChanged event in the UserControl
  3. Fired off the created event

It’s like I’m just handing off the event firing to the next guy, the next guy being the Parent page in this instance. Now the code behind for the Parent page is really simple:

    public partial class Catcher : Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            catchMyEventMain.SelectedIndexChanged += dropDownListThrow_SelectedIndexChanged;
        }

        public void dropDownListThrow_SelectedIndexChanged(object sender, EventArgs e)
        {
            labelSelectedValue.Text = ((DropDownList)sender).SelectedItem.Text;
        }
    }

As you can see, the Parent now is also looking for the DropDownList SelectedIndexChanged event to fire, except we both know that it’s not the official SelectedIndexChanged event, but an event that is merely passing on the information. Now for the Parent page markup:

    <asp:ScriptManager ID="smMain" runat="server" />
    <asp:UpdatePanel ID="upMain" runat="server" >
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="catchMyEventMain" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <uc1:CatchMyEvent ID="catchMyEventMain" runat="server" />
            <asp:Label ID="labelSelectedValue" runat="server" />
         </ContentTemplate>
    </asp:UpdatePanel>

So in all this will update a label’s text on the Parent page to equal that of the SelectedItem.Value of the DropDownList of the UserControl. And all without the annoying page refresh.

Just remember, the DropDownList has to have AutoPostback set to true. Don’t be dumb like me and forget that when testing.

The Switch Remover: Convert Switch Statements to Dictionaries

Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don’t have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this:

  switch(someDropDownList.SelectedValue)
  {
     case "hi":
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        break;
     case "there":
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        break;
  }

And I’ll give you this:

  doSomething[someDropDownList.SelectedValue]();

I bet you’re ready to pay $19.95, but wait there’s more. I’ll actually throw in how I did such an amazing thing.

  Dictionary<String, Action> switchRemover = new Dictionary<String, Action>();
  switchRemover.Add("hi", () => RunHiMethod();
  switchRemover.Add("there", () => RunThereMethod();

Why that’s amazing! But wait, I must be pulling something. What are these RunHiMethod and RunThereMethod methods? I must be pulling a fast one. Well, all they are is what the switch was doing before all wrapped up into one method. Don’t get it?

  private void RunHiMethod()
  {
      CallThisMethod();
      CallThatMethod();
      CallAnotherMethod();
  }

But… but what if I had to pass something in? What would I do then??? Boy you got me there, I could tell you but I’d have to charge you more. Wait… I’ll even throw that in for free. That’s right. Remember that old mess we had?

  switch(someDropDownList.SelectedValue)
  {
     case "hi":
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        break;
     case "there":
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        break;
}

Well shoot,we could do something like this:

  Dictionary<String, Action<User>> switchRemover = new Dictionary<String, Action>();
  switchRemover.Add("hi", currentUser => RunHiMethod(currentUser);
  switchRemover.Add("there", currentUser => RunThereMethod(currentUser );

And then:

  doSomething[someDropDownList.SelectedValue](currentUser);

That’s amazing! You ready with your credit card? I knew you would be.

The Switch Remover does not come with a warranty.
The Switch Remover can not be used in all circumstances.
The Switch Remover assumes no fault for any physical conditions caused by the sudden surge of awesomeness you might feel.

SO BUY IT NOW!

What Is Readable

So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods. Don’t know what I mean?

Expression:

var result = from knowledge in Sean
             select knowledge.Linq;

As opposed to:

var result = Sean.Select(knowledge => knowledge.Linq);

Personally I would replace the lambda expression with a Func, but I can live with it right now. Anywho, the argument is that the first looks better than the second. I really don’t see this as a looks problem, but a useage problem. Fact is, they both have their uses and you should know how to read both. Why is that? Well here’s an example CAUSE I KNOW YOU WANT ONE!

One of my earlier posts had to do with solving the FizzBuzz thing with Linq where I gave you this bad ass solution:

 var result =
      listToConvert
      .Where(WhereBothDivisible(fizzNumber, buzzNumber))
      .Select(selectKeyValuePair("FizzBuzz"))
      .Concat(
            listToConvert
            .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
            .Select(selectKeyValuePair("Buzz")))
            .Concat(
                  listToConvert
                  .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
                  .Select(selectKeyValuePair("Fizz")))
                  .Concat(
                         listToConvert
                        .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
                        .Select(selectKeyValuePair("Nothing")));

As you can see, I’ve used both Func fields and methods to return Funcs to clean up how this would look. I’ll even show what it would look like without this approach:

var result = listToConvert.Where(currentItem =>
             IsDivisible(currentItem, fizzNumber) && IsDivisible(currentItem, buzzNumber)
             ).Select(currentItem => new KeyValuePair(currentItem, "FizzBuzz")).Concat(...

Now I can totally admit that this second one I am showing is just ouch. So the first lesson to be learn is that Funcs and Methods that return Funcs can significantly clean up the Linq Method approach.

Now you could do the same with expressions:

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz");

 var buzz = from currentNumber in listToConvert
            where WhereBuzzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Buzz");

 var fizz = from currentNumber in listToConvert
            where WhereFizzDivisable(fizzNumber, buzzNumber)
            select selectKeyValuePair("Fizz");

var neither = from currentNumber in listToConvert
              where WhereNeitherDivisable(fizzNumber, buzzNumber)
              select selectKeyValuePair("Fizz");

Ok so nice and pretty, but now what? Concatenation. This is where is gets ugly:

  fizzBuzz.Concat(fizz.Concat(buzz.Concat(neither))));

OR

 var fizzBuzz = from currentNumber in listToConvert
                where WhereBuzzDivisable(fizzNumber, buzzNumber)
                select selectKeyValuePair("FizzBuzz")
                .Concat(
                     from currentNumber in listToConvert
                     where WhereBuzzDivisable(fizzNumber, buzzNumber)
                     select selectKeyValuePair("Buzz"))
                     .Concat(....);

See what I’m getting at? The non expression one is looking a bit better now or maybe this is a fight to see which is less fugly. Now I admit that this may not be the best FizzBuzz solution, but it gives an example or where the Linq queries can go very wrong.

Mulitple Constraint Generics and Test Base Classes

This was basically an idea I had to have test classes inherit a TestBase that has a Static Create method on it. The reason for this is that I have found it easier to have a Create method that takes care of creating a temporary class of the type the test represents. Say I have a UserTest class and I need an address. Instead of creating and filling a whole address object in the UserTest, it easier to have a Create Method on the AddressTest class that gives me a premade Address object. Why would I want to redo a lot of the same code by having the create method on every class when I can have it on a base class and just have the non base classes specify how to create the object?

Is this really needed? I can’t argue absolutely, but this forces a Create method to appear on any test class that inherits from TestBase and by use of Exceptions, forces the child classes to define how to create the object they represent. (As in it forces AddressTest to define how to create an Address object.) This also allows the Create method to be static and inherited. You could make it abstract, to skip the need for the two create methods(Create and CreateInstance), but that would hose the whole situation since static abstract is a no no. Static is a must for this situation.

The idea behind the code is to have a static Create method on the TestBase class that when called will create the test class type passed in through generics.

public static I Create()
 {
     I returnValue;
     J testToUse;

     testToUse = System.Activator.CreateInstance<J>();
     returnValue = testToUse.CreateInstance();

     return returnValue;
 }

Where J is the test class type to create. Once that test class is instantiated, the virtual method CreateInstance is called. This is where the test class creates the instance of the object it represents.

protected override I CreateInstance()
{
     I returnValue;

     returnValue = (I)new SimpleItem();
     returnValue.IsSimple = true;
     return returnValue;
}

Where I is the type of object it is going to create. In use it will look something like this:

  ItemBase itemToCreate;

  itemToCreate = SimpleItemTest<SimpleItem>.Create();

Now for the code:

//Some junk base items to demostrate the creating of an item with a base class
public class ItemBase 
{
}

//One item that will be created
public class SimpleItem : ItemBase
{
 public Boolean IsSimple { get; set; }
}

//The other item that can be created.
public class ComplexItem : ItemBase
{
 public Boolean IsComplex { get; set; }
 public Boolean IsNotSimple { get; set; }
}

//This test will be used to create a SimpleItem
public class SimpleItemTest<I> : TestBase<I, SimpleItemTest<I>> where I : SimpleItem
{
 protected override I CreateInstance()
 {
     I returnValue;

     returnValue = (I)new SimpleItem();
     returnValue.IsSimple = true;
     return returnValue;
 }
}

//This test will be used to create a ComplexItem
public class ComplexItemTest<I> : TestBase<I, ComplexItemTest<I>> where I : ComplexItem
{
 protected override I CreateInstance()
 {
     I returnValue;

     returnValue = (I)new ComplexItem();
     returnValue.IsComplex = true;
     returnValue.IsNotSimple = true;
     return returnValue;
 }
}

//This is the base class where the Create Method resides
public class TestBase<I, j> where I : class where J : TestBase<I, j>
{
 //This will either be overridden or throw an error.  Kind of a forced
 //abstract.  This is the method that the child test classes will use to
 //create whatever class they represent.
 protected virtual I CreateInstance()
 {
     throw new System.NotImplementedException();
 }

 //This is used to create a test class and call the CreateInstance method
 //so that this method can return the correct object.  The object type is
 //dependent on the type of test class that is being created.
 public static I Create()
 {
     I returnValue;
     J testToUse;

     testToUse = System.Activator.CreateInstance<J>();
     returnValue = testToUse.CreateInstance();

     return returnValue;
 }
}

Test Projects and Unit Tests In Visual Studio 2008

A quick thing about setting up test projects through Visual Studios… basically how to do so.

Add new Project -> Test (Project Types) -> Test Project.

Now the easiest way I’ve added actual tests is just to add a normal class. Say SomeClassTest.


using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class SomeClassTest()
{
   [TestMethod]
   public void SomeClass_CreateWithNull()
   {
   }
}

What is [TestClass]? Well that is an attribute you are adding to the class so that .net knows certain methods in it may be test methods. Guess what [TestMethod] does…

Ok so now I have a TestClass and TestMethod, now what? Well in the menu:

Test -> Windows -> TestView

You should see that your method now shows up on the list. Simple huh? If the method isn’t showing up on the list make sure it is:

  • Tagged with the [TestMethod] attribute
  • Contained in a PUBLIC [TestClass]
  • Public
  • void
  • Non static

If you have all of those and still nothing, right click the method name in the Test View and look at it’s properties. There is a property called “Non-Runnable Error”. This will tell you what you need to get it rolling.

All right, now you have everything set… so next? Simple, right click the method name in the Test View and you can either Run or Debug the test. If you just Run the test, the Test Results window will pop up and you’ll see the progress. If it passes, then yay. If not, it will give you things unhandled/expected exception, failed asserts, and expected exceptions. If you debug, the same happens except, CRAZY SURPRISE AHEAD!!!, you can step through it. Also, you can run multiple tests by selecting however many you want and running them.

There are some useful options in the test view. If you right click the column area, you can add columns such as Class Name to help with ordering. After all, you might have a bunch of methods that are named the same in different classes, which sucks. Another thing you can do is left click the down arrow to the right of the refresh button for group by options.

End Note: If you don’t recognize the word “attribute” that’s ok. Most likely you have seen the [Something] notation before if you have used web controls (Possibly winforms controls, no idea). Simply put, attributes are like attaching extra information to just about anything so that later on you can use that information at runtime to perform actions. With the use of reflection, you could, for instance, check for only specific properties on a class that you want to fill dynamically. Say you have a dataset with the “UserName” column and a User class with the property Name. If you wanted to fill that Name property normally you could do something like:


user.Name = dataset["UserName"];


but with relfection you could get the property info, check the properties for a the ones with a certain attribute, and match the value in the attribute to the column name.