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.

Static Abstract … should I bother?

So it came up recently that someone was bummed that you can’t create a static abstract method. Now conceptually, this is blocked by C# but I came up with this “work around”… And I have no idea if I would ever use it. This was more of a “Do it because I can” rather than “Do it because I should.”

  public abstract class Parent
  {
    public abstract String ReturnAValue(String returnThis);

    public static String ReturnAValue(String returnThis) where K : Parent
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        return classToCreate.ReturnAValue(returnThis);
    }
  }

So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How’s that for a run on sentence?

  public class ChildA : Parent
  {
    public override String ReturnAValue(String returnThis)
    {
        return "ChildA " + returnThis;
    }
  }

And this in full use:

  String testReturn;
  testReturn = Parent.ReturnAValue("returned");

Can you guess what that returns? If you can, you’re special. You might wonder why I have to use generics in this. Well I mean you could do this:

    public static String ReturnAValue(Parent returnThis)
    {
        return returnThis.ReturnAValue(returnThis);
    }

But that assumes you have to instantiate the child and pass it in.

Now the main problem with this, beyond the fact that you’ll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.

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!

Uhg It Won’t End

Still on the readability thing, but there was a second argument in the post that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it’s more readable, therefore just making it syntax sugar.

  foreach(Item current in itemList)
  {
     itemNameList.Add(current.Name);
  }

Versus

 var itemNameList = from item in itemList
                    select item.Name;

Or

  Func<Item, String> itemName = current => current.Name;
  itemNameList.Select(itemName);

So at this point it’s really a matter of preference. Problem is, you have to look closer to why the third is so much more than syntax yummies.

Say you want a method that takes in a UserList and you want to select all the users that have a property (Could be name, address, whatever) that matches a string. Well you could do this:

 public IList<User> AllUsersThatMatch(IList<User> userList, NeededProperty property, String value)
 {
    IList<User> returnList;

    returnList = new List();

    foreach(UserItem currentUser in userList)
    {
        switch(property)
        {
            case(NeededProperty.Name):
                if(currentUser.Name == value)
                {
                    userList.Add(currentUser);
                }
                break;
            case(NeededProperty.Phone):
                if(currentUser.Phone == value)
                {
                    userList.Add(currentUser);
                }
                break;
        }
    }
 }

Or you could do this:

 public Func<User, Boolean> MatchesProperty(NeededProperty property, String value)
 {
    Func<User, Boolean> returnValue;

    switch(property)
    {
        case NeededProperty.Name:
            returnValue = currentItem => currentItem.Name == value;
            break;
        case NeededProperty.Phone:
            returnValue = currentItem => currentItem.Phone == value;
            break;
    }
    return returnValue;
  }

 public IList<User> AllUsersThatMatch(IList<User> userList, NeededProperty property, String value)
 {
    IList<User>  returnList;

    returnList = userList.Where(MatchesProperty(property, value));
    return returnList;
 }

Now which do you think is easier to upkeep? For those of you wondering what I did, I simply used a method that would return the Func I needed for the passed in Enum and called it in the Where clause. The amount of code is probably close to the same right now, but add in 5 more values for the NeededProperty enum and you’ll see the code amount differing more and more.

I realize this isn’t the best of example, and probably the first way could be refactored but the idea is still there. The Linq Method approach gives you a lot more flexibility in the long run with dynamic stuff like this.

What Is Readable Addon

Quick thought too about which to use due to readability:

var you = from factor in seansAwesomeness
          select new FactorLite
          {
             Amount = amount;
          };

or you could do:

Func<Person, FactorLite> selectFactorLite = currentFactor => new FactorLite { Amount = currentFactor.Amount };

seansAwesomeness.Select(selectFactorLite);

I guess it’s a matter of preference, but the first seems way too verbose for something too simple.

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.

Dynamic Linq: OrderBy Using a String for a Property Name

Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don’t know what you what to sort on at any given time. On top of that, you have a datagrid and a bunch of sort expressions to deal with. Now you could do something like create a hashtable full of lambda expressions that the key is the sort expression:

Dictionary<String, Func<User, IComparable>> list;

userList = User.GetUserList();
list = new Dictionary<String, Func<User, IComparable>>();
list.Add("UserName", currentUser => currentUser.UserName);
list.Add("UserID", currentUser => currentUser.UserID);
userList.OrderBy(list["UserID"]);

Works just fine, and might be preferable to what I’m about to show. OooOoOO sound eerie?

//This is just to get the property info using reflection.  In order to get the value
//from a property dynamically, we need the property info from the class
public static PropertyInfo[] GetInfo<K>(K item) where K : class
{
  PropertyInfo[] propertyList;
  Type typeInfo;

  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();

  return propertyList;
}

//This is the dynamic order by func that the OrderBy method needs to work
public static IComparable OrderByProperty<T>(String propertyName, T item)
  where T : class
{
  PropertyInfo[] propertyList;

  propertyList = GetInfo(item);

  //Here we get the value of that property of the passed in item and make sure
  //to type the object (Which is what GetValue returns) into an IComparable
  return (IComparable)propertyList.First(currentProperty
    => currentProperty.Name == propertyName).GetValue(item, null);
}

And use:

//This takes the current user and calls the OrderByProperty method which in turn
//gives us the Func OrderBy is requesting.
var test = userList.OrderBy(currentUser
  => DynamicPropertySort.OrderByProperty("UserID", currentUser)).ToList();

Ok so what the hell? I mean intellisense on the OrderBy method doesn’t give much help. Func<<User, TKey>>. Yeah ok. So basically the return type is open. Well this kind of sucks right? Because I would have to return a Func that already knows the return type. (Be it string, int, ect) Of course, this would mean we would have to handle each sort expression in code. NOT VERY DYNAMIC IS IT? Well f that. Truth is, what the order by is looking for is a Func that takes in a User and returns something it can compare. This is where IComparable comes in.

The OrderBy has to take the returned value, say UserID which is an int, and figure out how to compare it to another value. Pretty simple. So as long as the property you are ordering by uses IComparable, you’re good to go. Pretty nice huh?

Now I would suggest, if you use this (HAHAHAHA), is to cache a dictionary of the property info with the class type as the key so that you don’t have to use as much reflection everytime. I just didn’t put that in.

U U USING

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;