Generic Tree Implementation in C#.NET

Recently, I was working on a class which was represented as a hierarchical tree. I wrote several recursive extension methods to operate on this class, after which I realized that these methods could be extracted out into a more generic implementation. I chose to use an interface as opposed to a base class, since my requirements for this application are currently fairly simple: each object will have a property which is an array of the same type.

    public interface ITree
    {
        T[] Children { get; set; }
    }

This implementation does not have a lot of the features of some others that exist on the web, which do use base classes such as Dan Vanderboom’s Tree: Implementing a Non-Binary Tree in C#. In my case, YAGNI!

Here is my current collection of extension methods for this interface. If you have another implementation or other methods I’d love to see them in the comments.

    public static class TreeExtensions
    {
        public static IEnumerable Filter(this IEnumerable items, Func func) where T : ITree
        {
            var results = new List();
            foreach (var item in items)
            {
                item.Children = item.Children.Filter(func).ToArray();
                if (item.Children.Any() || func(item))
                    results.Add(item);
            }
            return results;
        }

        public static IEnumerable Flatten(this IEnumerable items) where T : ITree
        {
            var result = new List();
            foreach (var item in items)
            {
                result.Add(item);
                result.AddRange(item.Children.Flatten());
            }
            return result;
        }

        public static void Apply(this IEnumerable items, Action action) where T : ITree
        {
            foreach (var item in items)
            {
                action(item);
                item.Children.Apply(action);
            }
        }
    }
Leave the first comment

Fixing Authorize.NET’s FormBuilders for ASP.NET MVC

Recently, I was working on a client site and had to implement payment using Authorize.NET. Compared to some other service providers, their documentation and sample code is fairly good. However, when I tried to use their

    @using (new SIMForm(...)) {}

construct, I kept getting forms that looked like crap. It turns out that that class actually writes all its output using Response.Write(). Luckily, they provide code for all of this instead of just a library, so I was able to make a simple modification to provide the functionality I needed. Here is the code I added/copypasta’ed:

    public SIMForm(string returnUrl, decimal amount, string apiLogin, string transactionKey, bool isTest)
        {
            _amount = amount;
            _apiLogin = apiLogin;
            _transactionkey = transactionKey;
            _returnUrl = returnUrl;
            _isTest = isTest;
        }

public string WriteForm()
        {

            var seq = Crypto.GenerateSequence();
            var stamp = Crypto.GenerateTimestamp();

            var fingerPrint = Crypto.GenerateFingerprint(_transactionkey,
                _apiLogin, _amount, seq.ToString(), stamp.ToString());

            var formAction = Gateway.LIVE_URL;

            //for testing
            if (_isTest)
                formAction = Gateway.TEST_URL;
            var output = new StringBuilder();
            output.Append("
\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); output.Append("\t\t\n"); return output.ToString(); }

Now, in my view, I can call:

   @{var simForm = new SIMForm(url, amount, ViewData["ApiLogin"].ToString(),
           ViewData["TransactionKey"].ToString(), Convert.ToBoolean(ViewData["IsTest"]));}
   @Html.Raw(simForm.WriteForm())

Hopefully this can help someone figure it out more quickly than I did.

Leave the first comment

Software Development Job Satisfaction

In my journey as a software developer, I’ve come to understand that there are at least three points that make of break a job, for me at least. I recommend finding out about these before accepting any job offer.
  • Perspective: Is Development looked at as a cost, or as an investment? This paradigm determines whether developers are respected and treated well, and whether they are given the best tools to do their job in the best way possible.
  • Technology: What technologies are being used? Some companies are stuck in the past because of stubbornness or business necessity. Not being able to utilize newer technologies is frustrating.
  • Culture: What is the company culture like? Are there events such as team building? Is there open communication? Is input from all employees valued? What is the manager-employee relationship like?
These issues are are also not normally covered in much depth in an interview. The only way to get the real dirt on a company ( and there’s always dirt ) is to talk to an employee one-on-one. An employee. Not a manager. A code monkey just like you. Talk to them outside of the work environment. Buy them a beer if you can. Get them talking, and you’ll find out what it’s really┬álike to work there.
Enhanced by Zemanta
Leave the first comment

A C# Implementation of Ruby On Rails’ Cycle Method for ASP.NET MVC

Again, another thing that I thought should probably be out there, but when I Googled it, was nowhere to be found.

Basically, in Ruby on Rails, if you want to alternate row colors or something like that, the easiest way is to do:

    DATA HERE

Which will alternate between the two values you feed it. Alternately, you can pass it a name parameter which will allow you to cycle multiple values independently of each other. Since this is very useful, I went ahead and created if as an ASP.NET MVC Html Helper:

    public static class HtmlHelperExtensions
    {
        private static Dictionary _cycles = new Dictionary();

        public static string Cycle(this HtmlHelper helper, string first, string second, string key = "default")
        {
            return _cycles[key] = (_cycles.ContainsKey(key) && _cycles[key] == first) ? second : first;
        }
    }

Then you can use it in the same way as the Rails helper:

    ">Data Here

Edit: My Colleague Matt pointed out this implementation by Phil Haack, which takes an indefinite number of items to cycle through. His uses the HttpContext to store the values, I used a private static variable. Someone did do it – I guess my Google-foo is just lacking.

Leave the first comment