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.
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.
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.
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;
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:
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.
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:
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?
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:
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;
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:
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.
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…
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:
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:
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:
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:
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:
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.
Created a PUBLIC delegate and event that has the same signature as the SelectedIndexChanged event
Captured the SelectedIndexChanged event in the UserControl
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:
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:
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.
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:
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?
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?
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 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:
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:
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.
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)newSimpleItem();
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:
//Some junk base items to demostrate the creating of an item with a base classpublic classItemBase
{
}
//One item that will be createdpublic classSimpleItem : ItemBase
{
public Boolean IsSimple { get; set; }
}
//The other item that can be created.public classComplexItem : ItemBase
{
publicBoolean IsComplex { get; set; }
publicBoolean IsNotSimple { get; set; }
}
//This test will be used to create a SimpleItempublic classSimpleItemTest<I>: TestBase<I, SimpleItemTest<I>> where I : SimpleItem
{
protected override I CreateInstance()
{
I returnValue;
returnValue = (I)newSimpleItem();
returnValue.IsSimple = true;
return returnValue;
}
}
//This test will be used to create a ComplexItempublic classComplexItemTest<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 residespublic classTestBase<I, j> where I : classwhere 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.protectedvirtual I CreateInstance()
{
thrownew 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;
}
}
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.