stuff i do at work

(maybe i’ll make less mistakes if i remember some)

Run any function as an Action delegate

Posted by noah on July 17, 2008

It was really neat when I found out about the the Action built-in delegate.  Instead of defining the same delegates all over the place, I can use the Action delegate as long as I don’t have any return values.

Now what do you do if you want to pass a function as a parameter into another function that takes an Action delegate?

Just anonymize it by wrapping the function in an anonymous function.

FunctionAcceptingActionDelegate(delegate { functionWhichReturnsABool(); });

Posted in Uncategorized | Leave a Comment »

InvalidCastException when dynamically creating an object instance

Posted by noah on July 10, 2008

This one was driving me crazy.  Using the factory pattern, I created an instance of a class, which implemented a certain interface.  But when I tried to cast the object into the interface it used, I got an invalidCastException.  Here’s the line of code:

IClassType t = (IClassType)Activator.CreateInstance(ClassType);  // Where ClassType implements IClassType

What happened was ClassType was referencing IClassType in a different copy of an assembly than the one the current assembly was referencing.  All I had to do was change the assembly reference property to copyLocal=false.

The post that figured this out for me: http://www.yoda.arachsys.com/csharp/plugin.html

Posted in Uncategorized | Leave a Comment »

Redundancy and failover

Posted by noah on June 25, 2008

Recently, I rewrote a quote service, and being paranoid about uptime (and possible lurking bugs in my code), I also wrote some code to add redundancy which switches quote providers when a failure occurs.  I did this on 2 levels… switching between the new and old quote service (these were written as providers using the factory pattern), and also switching between my new services (the same service running on 2 different servers).

Since the switching code seemed like a common element, and needed to error-free, it was a good candidate for abstraction.  For illustration, I’ll use multiplication as redundant service.  (By the way,  I didn’t end up using this code). I’ll work backwards from implementation toward the abstract class.

First, the interface for the 2 functions I want to switch between:

    interface Multiplier
    {
        int Multiply(int x, int y);
    }

The 2 functions which implement the interface:

    class SimpleMultiplier : Multiplier
    {
        public int Multiply(int x, int y)
        {
            return x * y;
        }
    }

    class SlowMultiplier : Multiplier
    {
        public int Multiply(int x, int y)
        {
            int output = 0;
            for (int i = 0; i < x; i++)
            {
                output += y;
            }
            return output;
        }
    }

Now here is the code for FailoverMultiplier.  I’ll show this code before the abstract class to illustrate how the abstract class is used. 

    class FailoverMultiplier : Failover<int, Multiplier>
    {
        public FailoverMultiplier()
        {
            Initialize(“Multiply”);
            members.Add(new SimpleMultiplier());
            members.Add(new SlowMultiplier());
        }
        public int Multiply(int x, int y)
        {
            return RunFailover(x, y);
        }
    }

Now for the abstract Failover class. The interesting part of the code was wrapping the individual Multiply functions within the try/catch of another function, and doing it in an easily reusable way. (fun activity: guess how it’s implemented first). Notice that I also have functionality to optionally prefer the 1st member, and revert back to it after a certain amount of time.

    abstract class Failover<TReturns, TBase>
    {
        protected object lockObject = new object();
        protected int memberIndex = 0;
        protected List<TBase> members = new List<TBase>();
        protected bool preferFirst = false;
        protected DateTime primaryFailTime = DateTime.MinValue;
        private System.Reflection.MethodInfo method;

        protected void Initialize(string functionName)
        {
            Type t = typeof(TBase);
            method = t.GetMethod(functionName);
        }

        protected TReturns RunFailover(params object[] parameters)
        {
            int iterations = 0;
            bool failedState = true;
            TReturns output = default(TReturns);

            if (members.Count == 0)
                throw new Exception(“members list is empty”);
            if (method == null)
                throw new Exception(“‘method’ was not initialized”);

            lock (lockObject)
            {
                do
                {
                    iterations++;
                    try
                    {
                        output = (TReturns)method.Invoke(ActiveMember, parameters);
                        failedState = false;
                    }
                    catch
                    {
                        // do logging
                    }

                    if (failedState)
                    {
                        if (memberIndex == 0)
                            primaryFailTime = DateTime.Now;
                        memberIndex = (memberIndex + 1) % members.Count;
                    }
                } while (failedState && iterations < members.Count);

                return output;
            }
        }

        protected TBase ActiveMember
        {
            get
            {
                if (preferFirst && DateTime.Now.Subtract(primaryFailTime).Hours >= 1)
                {
                    memberIndex = 0;
                }
                return members[memberIndex];
            }
        }
    }

An earlier version of this class required the user to define a function in the FailoverMultiplier class which was to to be called by the abstract class’s function “RunFailover”.  This is necessary if you don’t use reflection or if you need more performance. In my tests, it took 7 seconds to do 1M iterations with the invoke, but .02 seconds to call the function directly.

Posted in Uncategorized | Leave a Comment »

Async postbacks are blocking other postbacks!

Posted by noah on June 25, 2008

This problem took over a week to figure out (ie, run the right google query)

When you create an updatepanel (or any other xmlhttprequest) that takes a long time, then any other postbacks are blocked until the 1st postback is completed… in some cases.  For example, you have a page that delay loads some data, but that data takes 10 seconds to return.  You don’t really care if the data is actually returned before the user leaves the page… it’s just some info like recent quote information.  If the user clicks on any other button on the page, then nothing occurs until the 10 seconds are over.

This problem occurs sometimes.  I noticed that it worked in my sample project, but not in our main codebase.  I whittled down the issue down to global.asax.  If certain event handlers were defined, then the async postback would block.  This made absolutely no sense because it would still occur if the event handler was empty.

Anyways, the reason this was happening is because ASP.net serializes access to the session state.  The 1st postback must finish before the 2nd is processed.   But access to the session state is only serialized if you actually use sessionstate, and I wasn’t using it.  If a handler like Session_Start is defined in global.asax, then a session_id is added to the response as a side effect.  The workaround for this problem is to use EnableSessionState=”False” or “ReadOnly” on the Page directive.

For more information, see http://channel9.msdn.com/forums/TechOff/256322-Strangeness-between-ASPNET-AJAX-and-Globalasax/

Posted in Uncategorized | Leave a Comment »

Referencing ids on web user controls

Posted by noah on June 24, 2008

If you create an ascx file which uses client script to reference a control inside the user control, don’t simply refer the the html control id.  this might cause id name collisions (if you have more than one of the same control on the same page), for example.

To fix this, you need a “namespace” of sorts.  On the referenced id, set runat=”server” as an attribute.  ASP.NET will then assign a new name to the control.  For example, if you control’s name is Foo, it’ll prepend the ascx name to the control’s id like myUserControl1_Foo.

To reference this, use the server function FindControl(string) by passing in the original name (“Foo”) into it.  The new name (“myUserControl1_Foo”) is returned.  Make sure this function is run on the UserControl object, not the Page object, otherwise it’ll look for the id on the Page level.

Posted in Uncategorized | Leave a Comment »

multiple exes, one app.config

Posted by noah on May 28, 2008

I wrote earlier about multiple exes sharing one app.config.  The problem is that .net doesn’t really support dll.config, so each exe project needed app.config files that were exactly the same.  This problem is made worse because if you use the user settings file (*.settings), the configuration information is stored the the app.config of the same project. 

I fixed the problem by using a reference to the common app.config file of the dll by editing my .csproj file to point to the dll’s app.config.  I don’t think this can be done in the UI, but VS does display the files with a little shortcut indicator.  To reduce confusion, I added a post build event to delete the *.dll.config file.

Edit:  References can be made to other files in the UI using “Add Existing Item”, then if you click on the dropdown next to “Add” in the open file dialog, select “Add As Link”

Posted in Uncategorized | Leave a Comment »

making time estimates

Posted by noah on May 22, 2008

when i switched to strictly dev work, i thought that i would have a hard time with giving and meeting work estimates because i’m a slow coder.  turned out that i’m not that bad.  i think i just have to double my initial idea of what it would take because i don’t take into account everything i need to do.

for next time:

  1. get a feature list.  this last time, my boss kept adding on stuff.  not that he expected me to be on time with the extra stuff, but it still helps when designing and planning
  2. prototyping, proof of concept… (can i read the bytestream records off the socket connection?)
  3. is there a client ui?
  4. working with unfamiliar code?
  5. functionality testing
  6. perf
  7. refactor, review code
  8. other work being done in parallel

Posted in Uncategorized | Leave a Comment »

marshalling byte arrays into data structures

Posted by noah on May 21, 2008

After writing a program and benchmarking, it turns out that Marshal.PtrToStructure took up about 1/4 of my app’s cpu consumption!  It just so happened that a few days ago, an article was written on this exact subject (http://www.codeproject.com/KB/dotnet/ReadingStructures.aspx?display=Print)

Unfortuantely, I couldn’t use his best optimization (60x faster) because I used a class, which is managed, so the pointer stuff doesn’t work.

Using fixed instead of GCHandle yielded a 20% perf gain.  Doing the exact operations on structs was 2x faster for GCHandle and 3x faster for “fixed”.

Overall, my perf isn’t that bad, so it’s not worth doing these things.  One option was to make my class into a wrapper class for a struct, but that seems like just too much effort.

Posted in Uncategorized | Tagged: | Leave a Comment »

datetime.utcnow 40x faster than datetime.now

Posted by noah on May 21, 2008

DateTime.UtcNow is over 40x faster than DateTime.Now in c#.

DateTime.UtcNow.AddHours(-5) is 20x faster than DateTime.Now.  this doesn’t work in practice because you have to account for daylight savings time… and there’s no fast built-in way to do it

so if perf is critical, avoid using local time

Posted in Uncategorized | Tagged: | Leave a Comment »

wcf mex endpoints and app.config

Posted by noah on May 21, 2008

i refactored my code and put the wcf service in a separate dll, and the service discovery stopped working.  spent a couple hours trying to figure out how i could get it to work with the service info in the dll config file, but it just doesn’t work.  you just have to leave it in the exe config files i guess. 

its not that bad, but in my case, it forces duplication of information since i have multiple exes calling this library.

Posted in Uncategorized | Leave a Comment »