Font Size: A A A   Layout: Left | Right

58bits - Tech

Six bits short of sixty four...

# Wednesday, July 16, 2008
Wednesday, July 16, 2008 8:31:47 PM (SE Asia Standard Time, UTC+07:00) (C# | Visual Studio)

Yet another tool I've been late coming to - JetBrains ReSharper.

While working though Link in Action I was experimenting with ReSharper 4.0. So cool and extremely helpful when looking at delegates and lambdas.

Here's a delegate assignment..

Predicate<DateTime> isMinimum = delegate(DateTime input) { return (input == DateTime.MinValue); };

And here's the equivalent as a lambda..

Predicate<DateTime> isMinimum = input => (input == DateTime.MinValue);

And here's the ReSharper magic that converts from lambdas to delegates and back again...

resharper4

# Friday, July 04, 2008
Friday, July 04, 2008 1:05:17 AM (SE Asia Standard Time, UTC+07:00) (C# | Utilities)

Thanks to Alexander Groß for pointing me to syntaxhighlighter.  I still think Leo Vildosola's Code Snippet plugin and highlighter for Windows Live Writer is amazing. They're both good choices - but I thought I'd give syntaxhighlighter a try. It produces less markup than Leo's plugin, although it is dependant on a JavaScript lib on the site for the actual highlighting.

PreCodePlugin_Full_2.0.2 The only challenge in using syntaxhighlighter- is that unlike Leo's all-in-one solution - you need to work out a way to format and encode your snippets first, placing them in either a <pre> or <textarea> element. There are a couple of plugins out there that do this - but I wasn't thrilled with the results, and I've wanted to take a quick look at the WLW plugin API for a while now. Seems like everyone is having a go at this - including Rick Strahl.  So here is my attempt - a code snippet plugin for Windows Live Writer...

Scott also directed me to the Past As plugin on Codeplex - which I'll be trying out as well.

The result - using my plugin - and syntaxhighlighter on the site...

 

public override void CleanUp()
{
    //Remve the Async event listener
    AsyncTaskManager.ItemProcessComplete -= AsyncTaskManager_PreviewItemProcessed;
    this.Logger = null;
}
:-)
# Tuesday, July 01, 2008
Tuesday, July 01, 2008 2:27:13 AM (SE Asia Standard Time, UTC+07:00) (C#)

Using an enumeration to display a list of values in the user interface (UI) has obvious limitations. You'll be limited to the rules of enumeration values - no spaces, multi-words etc. You won't be able to offer localized versions of the strings used to describe each enumeration value. And you'll have to hard code and parse all possible values in order to present a list of values in a UI element.

Here's an article on five great patterns that can be used to create "look-up" or "reference" types (reference type in this case meaning a data structure that is used to represent a list of possible values that another type will depend on - like High, Medium, Low, or Fast and Slow).

Below is the code I used recently to create a type based on the descriptor pattern; a  reference type that will be used to assign a JobStatus to a Job class. What I like about this approach, is that with correct == and != operator overloads - it's a 1:1 swap with an existing enumeration type - so no code changes are required where an enumeration type may have been used initially.

The weakness of this pattern is that like enumerations - the class has to be coded - and so if the list of values changes the code will need to change too. That said, for small to medium size lists of "look-up" values (combined with a little code generation) this is a great way to offer type safe values as well as a UI and culture friendly list.

The ToString() override and the IList<JobStatius> GetValues() method make this type databinding friendly too.

public sealed class JobStatus
{
    //Private constructor - only our static properties are allowed to create instances
    private JobStatus(int value, string name)
    {
        _value = value;
        _name = String.Copy(name);
    }
    
    //Readonly Value property
    private int _value;
    public int Value { get { return _value; } }

    //Readonly Name property
    private string _name;
    public string Name { get { return _name; }}

    private static JobStatus _waiting = new JobStatus(1, "Waiting");
    public static JobStatus Waiting
    {
        get { return _waiting; }
    }

    private static JobStatus _notRun = new JobStatus(2, "Not Run");
    public static JobStatus NotRun
    {
        get { return _notRun; }
    }

    private static JobStatus _active = new JobStatus(3, "Active");
    public static JobStatus Active
    {
        get { return _active; }
    }

    private static JobStatus _completed = new JobStatus(4, "Completed");
    public static JobStatus Completed
    {
        get { return _completed; }
    }

    private static JobStatus _cancelled = new JobStatus(5, "Cancelled");
    public static JobStatus Cancelled
    {
        get { return _cancelled; }
    }

    private static JobStatus _failed = new JobStatus(6, "Failed");
    public static JobStatus Failed
    {
        get { return _failed; }
    }

    public override string ToString()
    {
        return _name;
    }
    
    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        if (GetType() != obj.GetType())
            return false;

        JobStatus status = (JobStatus)obj;

        if (_value != status.Value)
            return false;

        return _value == status.Value;
    }     

    public static bool operator ==(JobStatus status1, JobStatus status2)
    {
        return Object.Equals(status1, status2);
    }

    public static bool operator !=(JobStatus status1, JobStatus status2)
    {
        return !Object.Equals(status1, status2);
    }

    public static IList<JobStatus> GetValues()
    {
        List<JobStatus> values = new List<JobStatus>();

        foreach (PropertyInfo pi in typeof(JobStatus).GetProperties())
        {
            if (pi.PropertyType.Name.Equals("JobStatus", StringComparison.Ordinal))
            {
                values.Add((JobStatus)pi.GetValue(null, null));
            }
        }

        return values;
    }
}
# Saturday, June 14, 2008
Saturday, June 14, 2008 9:16:05 PM (SE Asia Standard Time, UTC+07:00) (C# | Utilities)

I know Jeff Atwood is a fan of this, and I'm surprised it's not made it on to Scott Hanselman's 2007 Ultimate Developer and Power Users Tool List for Windows tools list yet.

RegexBuddy is a brilliant tool and a great way to learn regular expressions. The documentation and introduction to regex is worth the price of admission alone.

regexbuddy
  (click to enlarge)

The expression tree view in the lower window practically talks to you as you build up and test your expressions. The expression to the right will match any incoming Url to myabsolutepath/subdir that begins and ends with either:

myabsolutepath/subdir
myabsolutepath/subdir/

or

myabsolutepath/subdir/*.aspx
myabsolutepath/subdir/*.ashx

I love this application.

# Sunday, June 08, 2008
Sunday, June 08, 2008 12:35:26 AM (SE Asia Standard Time, UTC+07:00) (C#)

I needed an undo stack today - but wanted it to behave like a queue when it was full, dropping the oldest items in the collection to make room for new ones. Found two posts - Undo Functionality with a Limited Stack, and also a reference to an identically named collection called LimitedStack here. 

Was initially thinking of simply writing a wrapper over an array of objects, shifting items along as new ones were added, but using a linked list is a clever solution, as it provides the queue like behavior needed without out any extra code via RemoveFirst() and RemoveLast().

using System;
using System.Collections.Generic;

namespace DotBits.Gallery.Builder.Objects
{
    [Serializable()]
    public class UndoStack<T> : LinkedList<T>
    {
        private int _maxItems;

        public int MaxItems
        {
            get 
            {
               return _maxItems; 
            }
            set
            {
                while (this.Count > value)
                {
                    this.RemoveFirst();
                }
                
                _maxItems = value;
            }
        }

        public UndoStack(int max)
        {
            _maxItems = max;
        }

        public T Peek()
        {
            return this.Last.Value;
        }

        public T Pop()
        {
            LinkedListNode<T> node = this.Last;
            this.RemoveLast();
            return node.Value;
        }

        public void Push(T value)
        {
            LinkedListNode<T> node = new LinkedListNode<T>(value);
            this.AddLast(node);

            if (this.Count > _maxItems)
            {
                this.RemoveFirst();
            }
        }
    }
}

# Monday, May 07, 2007
Monday, May 07, 2007 6:54:30 PM (SE Asia Standard Time, UTC+07:00) (C#)

Back in March I went to the MSDN Roadshow in London to see presentations on several topics - one of them was LINQ.

In my attempts to keep up with the avalanche of software coming out of Microsoft - I have a short list of beefy books to read, weblogs to keep up with, and videos and Webcasts to watch.

The presentation at the roadshow in March was ok - but I thought for a while about the cost of attending; the time it took to get there - the structured format of the show and my never ending need for utilitarian sources of good information.

Today I came across Mike Champion's very helpful post...

Accelerating Evolution: LINQ News from Mix 2007 which includes a link to a video of Anders' presentation at Mix 2007 .

Anders' presentation is brilliant; fluid and clear - and really demonstrates the LINQ language enhancements well.

What's more I was able to watch it at a time of my choosing, and at my own pace - which makes me wonder a little about the real benefit of the Roadshows (apart from the less than subtle injection of a lot of MS Office 2007 mini-marketing presentations between each of the main items of the event).

Mix 07 on the other hand is a 'whole-n-other' thing.... :-)

  

Navigation

Search

Categories

On this page

From Delegates to Lambdas with ReSharper 4.0
Another Syntax Highlighter
A UI and Culture Friendly Replacement for Enumeration Types
RegexBuddy
LinkedList and a Limited Undo Stack
Anders Hejlsberg on LINQ

Archive

Send mail to the author(s) E-mail

Total Posts: 54
This Year: 28
This Month: 6
This Week: 2
Comments: 7

Sign In