jQuery: Add a Pop Up Div to a Link Dynamically

So as an exercise to learn more about jQuery, I decided to redo this little gem using jQuery. Have to say though only technically XHTML compliant, it worked out much better and with less code. So the idea is to have something really easy for non programmers (You know, lesser people) to be able to have a pop up comment added to some chunk of text on a web site. What I came up with before was ok but kind of annoying since it looked like this:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Kind of annoying since I would have to explain that ‘1’ is the name and it has to be unique for every one of these, this isn’t really understood by those people, and well it just seems more complicated then it needs to be. So what if I told you it could look like this?

<a href="http://www.byatool.com" class="showItLink" xmlns:comment="hihihi">HI</a>

Gorsh, that seems even better and it works in both IE and Firefox… which might be a first for this site and anything javascript. First let’s get the css out of the way, shall we?

    .showItLink
    {
    }

    .postComment
    {
        background-color:Gray;
        border-color:Black;
        border-style:dotted;
        border-width:thin;
        color:White;
        margin-right:3px;
        padding:3px;
        position:absolute;
        text-decoration:none;
        z-index:50;
    }

Most of the is just for looks, but like the older example I’ve called upon the power of position:absolute and z-index well that’s just pulling it in front of everything else.

Next part will be the actual code, and if you take the method from THE POSITION ABSOLUTE POST

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

and add in a simple span creation method:

    function CreateDiv(innerText, cssClass)
    {
        var spanToAdd;

        spanToAdd = document.createElement('span');
        spanToAdd.className = cssClass;
        spanToAdd.innerHTML = innerText;

        return spanToAdd;
    }

you’re ready for the actual fun part… making sure something pops up when the link is clicked.

jQuery(document).ready  //Everything inside this will load as soon as the DOM is loaded and before the page contents are loaded.*
(
    function()  //this is the start of an anonymous method
    {
        jQuery(".showItLink").click //find all things with the .showItLink class and assign the click event to the next anonymous method
        (
            function(event) //this is the start of an anonymous method for the click event
            {
                var containerPosition;
                var createdSpan;
                var comment;

                comment = jQuery(this).attr("xmlns:comment");  //Get the value from the comment attribute on the link.
                createdSpan = jQuery(this).children(".postComment"); //Find a possible span already attached to the link if it exists.  The span is of class 'postComment'

                if (createdSpan.length == 0)  //span doesn't exist
                {
                    createdSpan= CreateDiv(comment, "postComment");  //create the span
                    jQuery(this).append(createdSpan);  //Add the span to the link
                    jQuery(this).children(".postComment").hide();  //Make sure the new span is hidden
                }
                SetTopAndLeft(this, createdSpan);  //Set the position of the span
                jQuery(createdDiv).toggle();  //This will hide if it's showing, show if it's hidden... kind of nice huh?

                event.preventDefault();  //Equivalent to false.  Need this for Firefox.
            }
        );
    }
);

And boom you have something that works. Hooray.

Couple things of note:

.Hide – At first I though this would screw up my class for the span by removing the current class and adding display:none. Turns out it doesn’t harm the original class. Kind of nice.

.Toggle() – This is really nice. It will hide if it is showing and show if hidden. Stupid easy to use and is pretty effective. Just like .Hide, the class of the element is not harmed.

$ versus jQuery – Some people might notice that I am not using the short hand $ for my jQuery calls. Turns out that it might be safer this way. There are other javascript libraries that use the $ short hand like prototype. I ran into this with WordPress since it uses both jQuery and Prototype and blocks jQuery from using $ since it could conflict with other libraries. Weeeee!

JQuery, Position : Absolute, and How to Make It All Work

This is a really quick one but when I was taking my cheesy pop up and reworking it using JQuery (After Andre the Annoying wouldn’t shut up about it), I ran into a fun problem: position:absolute wasn’t working like it should. You know “absolute is positioned at the specified coordinates relative to its containing block.”. Meaning it should at worst show up within it’s container, where ever that is. Now IE is fine with that and the thing was showing up well:

absolutepositionie

Firefox? Not so much:

absolutepositionfirefox

Well… turns out JQuery pretty much does it for me. With a simple method, you can set one element’s position relative to a parent’s position:

    function SetTopAndLeft(parentContainer, elementToSet)
    {
        var containerPosition;

        containerPosition = $(parentContainer).position();
        $(elementToSet).css({ top: containerPosition.top + 10, left: containerPosition.left + 10 });
    }

Really simple, you get the position of the parent container and you set the child element’s top and left to it. Or in this case, I have it just off since hiding the parent container could be problematic. (Say if the parent container is a link AND NOW YOU CAN’T FIND IT TO CLICK ON IT AND THINGS HAPPEN BAD THINGS AND THE WORLD EXPLODES BECAUSE OF YOU!)

And boom, you can for once be a winner just like me.

Add a Pop Up Div to a Link Dynamically

Sometimes in life you have to ask “should I do this”, this is not one of those times. The idea is simple, click on a link and a div appears over the link with some kind of message in it. Kind of like being able to add a pop up note to a word. If you are absolutely amazed by that, don’t be afraid. Most likely you’ll die soon from forgetting to breathe. However, if you are just slightly curious as to why and how, keep reading.

So why did I do this? Well it started with the idea of having something simple for a blog that has multiple authors: What if other authors could add notes to someone’s post in the post. Well the idea of using some kind of text change (Like italics) sounded lame. I wanted something easy that could be replicated quickly and wouldn’t be visible unless needed. Thus the onClick idea. Now the next problem I had was the class needed for the style sheet. As you can see, when the div is shown, it doesn’t displace any of the items on the page. This is because I am using position:absolute and a high z-index. This allows for the div to lay on top of other things and not touch them. Problem with absolute is that it basicaly plants the div in relation to it’s parent container. Now that whole parent container thing seems to be up for interpretation when you are talking about browsers. Each seems to deal with it the way it sees fit.

Originally I had it as a div that would contain this new div. This was a pain in the -ss. In IE it showed up over the div, FireFox not so much. So the next thought was to create a div to hold the div that held the div. Something that isn’t exactly “user friendly” to be sure. Then it hit me, maybe I could put this in a link. After all, people who are viewing the blog would understand it’s something they can click on (Provided I don’t screw with the link styles too much) and it’s easy for non coders to copy and paste.

So on to the promised land. First I’ll just get the CSS out of the way since it’s absolutely needed but needs little explanation:

.hidePostComment
{
    visibility:hidden;
    position: absolute;
    z-index:-100;
}

.showPostComment
{
    background-color:Gray;
    border-color:Black;
    border-style:dotted;
    border-width:thin;
    color:White;
    margin-right:3px;
    padding:3px;
    position:absolute;
    text-decoration:none;
    visibility:visible;
    width:100px;
    z-index:10;
}

.hidePostComment

As you can see, I’ve screwed with the z-index, visibility, and position. Position I’ve already explained, and I think you can understand why visibility is hidden with this class. However, z-index might not be something you know about. Basically,z-index tells the browser where an item is in a vertical sense. When you look at a browser, there are actually a lot of layers regardless of the 2nd appearance. The z-index is used to bring something forward or backward. If I want the div to be behind say the text I am typing right now, it has to be at a z-index lower than the text. I used -100 in the example just to make sure it’s behind anything. It’s really an arbitrary number though. A positive number would make the div appear in front of the text (And in that case the text would not show up since it would be “behind” the div) which is what I did with the visibility class.

.showPostComment

Mostly just a bunch of visual changes like border and background color. However, you will also notice the the position is still absolute and that the z-index is now 10. (positive) The div will now effectively be “in front” of the link when it shows up giving it the pop up look. One Note: I had to add in text-decoration:none since the div is attached to the link and IE wants to drag the underline with the pop up causing the text to up with an underline. Kind of odd but no big deal.

Now for the code:

function BuildSelectableSpanForPost(spanName, parentElement, innerText)
{
    var divToAdd;
    var parentContainer;
    //check to see if the parentElement is actually an element or string.  If string, use it
    //to find the element.
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //Create the div
    //set the name (The name must unique since there could be a million "pop ups" per page
    //set the id
    //set the text for the div which is what we want to show up in the pop up
    divToAdd = document.createElement('span');
    divToAdd.setAttribute('name', spanName);
    divToAdd.id = spanName;
    divToAdd.innerHTML = innerText;

    //Add the div to whatever element that was found.  For this post it will be a link
    //but it doesn't really matter.
    parentContainer.appendChild(divToAdd);

    return divToAdd;
}

So there is the building of the pop up div. Here’s the method to be called by the onclick event:

function ShowCommentForPost(postName, parentElement, innerText)
{
    var divName;
    var createdDiv;
    var parentContainer;

    //Same as before
    if (typeof parentElement == 'string')
    {
        parentContainer = document.getElementById(parentElement);
    }
    else
    {
        parentContainer = parentElement;
    }
    //See if the pop up div  already exists.  If it does, then don't create again
    //I didn't have this before and it would create a new div everytime
    //That's what some might call a surprise feature
    divName = 'comment' + postName;
    createdDiv = document.getElementById(divName);
    //Ooops, the div didn't exist, create it and add the hide class
    if (createdDiv == null)
    {
        createdDiv = BuildSelectableSpanForPost(divName, parentContainer, innerText);
        //this is a method found on this post
        ClassHandler.AddClass(createdDiv, 'hidePostComment');
    }

    //this is a method based off this post
    //As you can guess it will show or hide depending on which class it already has.
    ShowHideElementBasedOnCss(createdDiv);

    return false;
}

To start, there is the code to create the actual div.

Now for the actual use:

<a onclick="return ShowCommentForPost('1', this, 'THIS IS SO STUPID!');" href="www.byatool.com">word.</a>

Pretty easy to actually use right? The actual location doesn’t really matter since it the method will always return false and therefore the link will never redirect. Also, you’ll see that I put 1 as the name sent in. The name sent in doesn’t matter what it is, but for every link it has to be different. If you are using this in a blog situation where there could be multiple blog posts in one page, I would suggest the name sent in would be the title and an increasing number.

If you got to this point and feel robbed of five minutes in your life, well just be happy this post robbed me of 15 minutes of mine.

Add, Remove, or Replace a CSS Class Using Javascript

Now honestly, I think the all famous Prototype has something for this, but if you aren’t using the all famous Prototype… well you’re screwed. Until now.

This is the idea, you want show or hide something on a click of it.

    <div onclick="HideOrShowMe();">
      YAYAAYAYAY!
    </div>

Annoying thing is trying to keep up with whether it’s hidden or not. Now there are ways to do this for sure, but if you had them you wouldn’t be here… or you just love idiotic banter. Either way, you’re here.

To start, get a class going:

    if (typeof ClassHandler != 'object')
    {
      ClassHandler = new Object();
    }

Normal declaration. Yeehaw. Now we need a method to check for the class:

ClassHandler.CheckForClass = function(element, nameOfClass)
{
    var returnValue = false;

    //Check to see if the element variable is a string or (hopefully) a control.
    //If it is a string, get the control that belongs to that id.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //next you use a regular expression to check the className property for
    //  the class you want.  If it finds a match, you're good to go.
    if (element.className != '')
    {
        returnValue = new RegExp('\\b' + nameOfClass + '\\b').test(element.className);
    }

    return returnValue;
}

Ok so now you have a method to check if it’s there… but what about if you want to replace the old one with a new one? Well that could be broken into two methods first (Both that are useful). First one is the removal of the old class:

ClassHandler.RemoveClass = function(element, nameOfClass)
{
    var returnValue = false;

    //You know the drill
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Hey cool, I just used the CheckForClass method
    if (ClassHandler.CheckForClass(element, nameOfClass))
    {
        //Real simple, replace the old
        //But you have to check if the nameOfClass exists with a preceding space
        //If it does, then you replace that with a space, other wise just replace
        //the nameOfClass with a space.
        element.className = element.className.replace((element.className.indexOf(' ' + nameOfClass) >= 0 ? ' ' + nameOfClass : nameOfClass),'');
        returnValue = true;
    } 

    return returnValue;
}

And now you’ll have to add in the new one.

ClassHandler.AddClass = function(element, nameOfClass)
{
    var returnValue = false;
    //lalalala
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }
    //If className already has a value, precede the nameOfClass with a space
    // otherwise just add it in.
    if (!ClassHandler.CheckForClass(element, nameOfClass))
    {
        element.className += (element.className ?  '  '  :  '') + nameOfClass;
        returnValue = true;
    } 

    return returnValue;
}

Now for the replace:

ClassHandler.ReplaceClass = function(element, classToRemove, classToAdd)
{
    var returnValue = false;

    //african elephants only have four teeth for chewing their food.
    if (typeof element == 'string')
    {
        element = document.getElementById(element);
    }

    //Remove the old one
    //Add the new one
    if(ClassHandler.CheckForClass(element, classToRemove))
    {
        ClassHandler.RemoveClass(element, classToRemove);
        ClassHandler.AddClass(element, classToAdd);
        returnValue = true;
    }

    return returnValue;
}

Now you might be thinking, “Tool, why don’t you just use the replace method in the replace method.” Well I suppose you could, but this way you have two other methods at your disposal for future use. Up to you really, part of this was because I actually needed those methods and the title says “Add, Remove, or Replace”. I can’t go against the title. I don’t have that kind of strength.

Usage? Well there are couple ways you can do this.

    if(ClassHandler.CheckForClass('someDiv', 'hide'))
    {
       ClassHandler.ReplaceClass('someDiv', 'hide', 'show');
    }
    else
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide');
    }

or this:

    if(!ClassHandler.ReplaceClass('someDiv', 'hide', 'show'))
    {
       ClassHandler.ReplaceClass('someDiv', 'show', 'hide'));
    }

And other ways to be sure. Now I’m not saying this is the best way to do it, just a decent way… although looking back on this I wonder if I could clean up the regex stuff.

ConfigurationManager And AppSettings… A Wrapper Class Story

You can file this under “Do I really need this?” but for now I kind of like it. That, however, may change in the next hour.

The idea is simple, create a class that uses the ConfigurationManager AppSettings NameValueCollection (Triple Combo!) but only presents properties that represent the keys in the .config file. This way there is no guessing of how the key is spelled or that that type returned is converted to something it should be. (Say you have a numeric value in the .config file) Now this doesn’t seem like a big deal, but I’m not happy with something that is just simple like:

    public String SomeKey
    {
       get
       {
          return System.Configuration.ConfigurationManager.AppSettings["SomeKey"];
       }
    }

Oh no, that’s just not good enough. Call it divine intervention. Call it spontaneous brilliance. Call it whatever the guy that invented the corn dog had. But what I came up with is far better. (And by better I mean more complex)

Remember, the idea isn’t to have to grab just the value from System.Configuration.ConfigurationManager.AppSettings but also to have it be typed on the way back. Now we know this to be true: I am awesome. What we also know to be true is that the value held in the appSettings area of the .config file is going to correspond to a value type but is going to be read in as a string. If you’ve read some of my posts (Which I assume you haven’t), you might have stumbled upon this little gem and know that I already have something to convert from a string to pretty much any value type. (Those having a TryParse method) So the converting part is already done, but what about the getting?

    protected static T? GetValueFromConfiguration<T>(String key) where T : struct
    {
      T? returnValue = null;
      if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
      {
        returnValue = System.Configuration.ConfigurationManager.AppSettings[key]
                           .ConvertTo<T>(); //MY AWSOME CONVERTTO METHOD!!11
      }

      return returnValue;
    }

Ok so you can see, this is really simple. I check to see if the key exists, get the value from the .config file, and convert to whatever I said it should. In use this would be:

    public static DateTime? TestDate
    {
       get
       {
          return GetValueFromConfiguration<DateTime>("TestDate");
        }
      }

Now you might have noticed something about this… yes besides the fact that it’s Mentos fresh. First, the method returns nullable versions. The reason for doing this is you really don’t know what the value will be in the .config file. Say this was an integer and you returned just a normal integer. (Non nullable) What would you set the value to? Sure you could do minimum value but COULD mean that there was a value in the .config file. This is more of a design choice though.

Second is that the method doesn’t cover strings. This is an ouch due to how nullables and strings work. You can’t return a nullable string since string doesn’t fit in the non nullable value category. This is a real pain but easily overcome with a non generic overload:

    protected static String GetValueFromConfiguration(String key)
    {
      String returnValue = null;

      if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
      {
        returnValue = System.Configuration
                           .ConfigurationManager.AppSettings[key];
       }
       return returnValue;
    }

See? Easy way to side step the problem. There might be a better way to handle that, but not sure at this point. Something to revisit I suppose. Oh and here’s the whole class for the hell of it:

    public class BaseConfigurationManager
    {
       private const String SOME_KEY = "SomeKey";

       protected static T? GetValueFromConfiguration<T>(String key) where T : struct
       {
         T? returnValue = null;

         if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
         {
           returnValue = System.Configuration.ConfigurationManager.AppSettings[key]
                         .ConvertTo<T>();
         }

         return returnValue;
       }

       protected static String GetValueFromConfiguration(String key)
       {
         String returnValue = null;

         if (System.Configuration.ConfigurationManager.AppSettings[key] != null)
         {
           returnValue = System.Configuration.ConfigurationManager.AppSettings[key];
         }

       return returnValue;
     }

     public static String SomeKey
     {
       get
       {
         return GetValueFromConfiguration(SOME_KEY);
       }
     }

    }

Oddly enough I spelled “spontaneous brilliance” correctly the first time around but thought “numeric” had a silent ‘b’. Go figure. Should have finished middle school.

Use Javascript and an HttpHandler to Load an Image from a Database

This might be part of another ongoing series, but the for this post, right here, RIGHT NOW, I am going to show are really simple but fun (??) way to change an image’s… eh image from a database stored image using Javascript and an .ashx file. And when I say simple, I mean it took me longer to get test code going than it did to make this work.

First you need a handler (If you don’t what this is for, well for this example it allows you to create a non existant url for an image loaded from the database.) which is aptly named Generic Handler when you do the usual Add New Item. Amazing. You should get something like this in the class file:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SomeImage: IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

Yeah you like that don’t you? Yeah you do.

So now we have something to display the image right? Well that’s pretty easy too. For me, I have an UserImage class I created with Linq to Sql to mimic my UserImage table. I’m cool like that. I then created a method to return the image bytes based on the ID sent in. That part is up to you how to handle. The main thing you need is to get the image bytes somehow. With that in mind, here is what the class file looks like now:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ShowImage : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            Int32 imageID;
            Byte[] imageBytes;

            imageID = Convert.ToInt32(context.Request.QueryString["ImageID"]);
            imageBytes = UserImage.GetImageBytesById(imageID);
            context.Response.ContentType = "image/jpeg";
            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.BufferOutput = false;
            context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

As you can see, the query string has an id being sent in and I’m retrieving it. From there I get the image bytes, tell the context what it is, how to handle the cache, and sending the bytes out. What you can’t see right now is that somewhere I have something that looks like this:

   <image src="SomeImage.ashx?ImageID=1" />

When that url is read, it will send it off to the handler to get and display the image. (Not taking caching into account mnd you)

Now I know what you’re thinking right now, “I’m bored” which I understand but you’re also thinking, “Where’s the f@&#ing javascript?”. Well my vulgar friend, it’s on the way.

<head runat="server" >
        <script type="text/javascript" language="javascript">
        function TestThis(name, imageID)
        {
            var test = document.getElementById(name);
            test.src = 'ShowImage.ashx?imageID=' + imageID;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="background-color:Gray;height:20px;width:20px;" onclick="TestThis('hi', 1);"> </div>
        <div style="background-color:Red;height:20px;width:20px;" onclick="TestThis('hi', 2);" > </div>
        <div style="background-color:Blue;height:20px;width:20px;" onclick="TestThis('hi', 3);"> </div>
        <br />
        <img src="" id="hi" name="hi" />
    </div>
    </form>
</body>

So now every time one of the three divs is “clicked”, the image is changed depending on the image id sent in using the “url” of the handler you created. Much like sending information to another page, you send the id to the handler so it can display the correct image.

I realize this isn’t the best of examples but it’s a push in the right direction. Maybe next time you want something, you won’t swear at me.

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>

C#, Var, and Objec- Propert- I have no idea what the term is

So I caugh this the other day and I’m not really sure it’s useful but it got me thinking…

Say you have a string and you want to create what ReSharper calls a “implicitly typed local variable declaration”, or as most people know it as “var”, and intialize it with a created value:

  String someThing = "hi";
  var onTheFly = new { someThing };

And now you can do this:

  String somethingElse = ontTheFly.something;

What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:

    var hi = from item in test
               select new {item.UserRole};

    UserRole someRole = hi.ToList()[0].UserRole;

So what does this all mean? Right now, I’m not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don’t have to keep refering to 8 different objects that might work:

    //Get the user
    User user = new User (1);
    //Get some icecream... couldn't think of any better fake class name
    IceCream iceCream = new IceCream(1);

    var stuff = new { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    //IMAGINARY CODE GOES HERE
    //MORE IMAGINARY CODE
    //??
    //PROFIT
    if(stuff.UserName.Equals("Sean", StringComparison.OrdinalIgnoreCase)
       && stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       //BLAH BLAH BLAH
    }

As you can see, it could be a way to group together a bunch of things in a method, but I’m not sure that is really useful.

*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*

Now for the theory… As is, this isn’t useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:

    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);

Now that’s a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:

    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);

Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?

    var parameter = new { userName, userFirstName, userLastName .... };
    CallMe(parameter);

Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven’t used 4.0 yet to know, I’m only guessing from what I’ve read.

Duck Typing my way to a Universal String Convert

So being the beacon of ignorance in the fog of brilliance, I had no idea what Duck Typing was. In short it’s the idea of assuming a class’s type based on the methods it holds.

Say you have 5 different classes, none of which share an inheritance tree. Now let’s say you have a method that takes in any object and uses the SeanIsAwsome method on the object. You could make sure that every object sent in has that method by using an interface that all the objects sent in share.

    public void SomeMethod(ISeanRules inParameter)

What if you want to send in a bunch of objects that don’t share the same interface/base class? Well you base it on what methods the class holds. If the class has the SeanIsAwsome method, then you call it. If not, well you could throw an exception, do nothing, go jogging, eat bacon, ect. That part is up to you.

The problem was that I wanted to create a universal convert that would take in a string and convert it to the 8 billion (ballpark figure) value types in C#. Now what I wanted to do is use the famous TryParse method so my first hope was that TryParse was a method on an interface they all shared. Yeah no. So next thought was to use the Duck Typing principle and say, “Hey jackass, you have a TryParse method? Yeah? Good. Use it.” ‘Course I had to find a way to do that. Turns out it wasn’t too bad.

public static class ConvertFromString
{
  public static T? ConvertTo<T>(this String numberToConvert) where T : struct
  {
    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));
    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

      if (returnedValue is Boolean && (Boolean)returnedValue)
      {
        returnValue = (T)paramsArray[1];
      }
      else
      {
        returnValue = null;
      }
    }

    return returnValue;
  }
}

A whaaaa?

Ok this might look odd, but it’s really simple. If it doesn’t look odd then chances are you’re smarter than me and you shouldn’t be here anyhow. First part is simple:

  public static T? ConvertTo<T>(this String numberToConvert) where T : struct

Due to this being a extension method (Opps forgot to tell you that part) I have to declare this static method in a static class. Basically I am taking in a string and returning a nullable version of whatever type I specific in the call.

    T? returnValue = null;

    MethodInfo neededInfo = GetCorrectMethodInfo(typeof(T));

Remember that MethodInfo method I had explained in the last post? The next part you might remember too, but I’m not betting on it.

    if (neededInfo != null && !numberToConvert.IsNullOrEmpty())
    {
      T output = default(T);
      object[] paramsArray = new object[2] { numberToConvert, output };
      returnValue = new T();

      object returnedValue = neededInfo.Invoke(returnValue.Value, paramsArray);

Ok so I have the method info, now I have to create the list of parameters to send in with the invoke. Pretty straight forward. If things went well, returnedValue should be a boolean. However, just incase:

    if (returnedValue is Boolean && (Boolean)returnedValue)
    {
      returnValue = (T)paramsArray[1];
    }
    else
    {
      returnValue = null;
    }

So if the returnValue is true and boolean, then the tryParse was successful. With that in mind, I still have to get the converted value. If it had not been successful than I am just going to return null since this is just meant for converting and not for whether or not it could be. It is just assumed that if it’s null, then it could not be converted at this time.

And now for the use:

  decimal? converted = someString.ConvertTo<decimal>()

An boom, you have a universal convert. YAY!

  using System;
  using System.Reflection;