Wilsonhut

Deal with it or don't

Tag Archives: Development

The simplest explanation of jQuery Deferred

I spent a while trying to get to the bottom of the question, “What is the jQuery Deferred all about?”

I couldn’t find the simple answer (They all seem to include ajax examples), so I decided that the internet needed a very short post about the basics.

Deferred is all about callbacks

Let’s say you are the developer of some asynchronous method. You need to provide a way to callback to the consuming code so that it can be aware of success and failure. One way to do this is to make use of a $.Deferred().

As the author of the method, you would create a new $.Deferred(), and use that* as the return value of the function.
When the real meat of your code has completed, you call the deferred’s .resolve method, and if the meat of your code fails, you call the deferred’s .reject method.

When you call .resolve or .reject, all of the appropriate callbacks that the consumer set up get called.

As the basics, that’s it. Make a Deferred. Call resolve or reject, then the done or fail callbacks get called.

Here’s an example.

function playMonopoly(){
    // long-running code.
    throw new Error("A player gave up.");
}

function thisMightTakeAWhile(){
    var deferred = $.Deferred();
    try{
        playMonopoly();
        deferred.resolve();
    }catch(e){
        deferred.reject();
    }
    return deferred; // *
}

thisMightTakeAWhile()
.done(function(){
    console.log("Finished? Wow!");
})
.fail(function(){
    console.log("Someone always gives up.");
});

(You can see it in action on this jsfiddle)

That’s a bad way to use it because nothing there is asynchronous, but that’s the simplicity that I felt the internet was missing.

* Really, you should return deferred.promise()

So what is the difference between a Deferred and a Promise?

The promise is just like returning the Deferred, but with the promise, the consuming code doesn’t have access to the .resolve .reject, and other methods that CHANGE the state. Using the promise, the consuming code only has access to the .done, .fail, etc.

Advertisements

Obvious Extension Method: IEnumerable MaxOrDefault and MinOrDefault

This one is even too obvious to comment on:

public static TResult MaxOrDefault(this IEnumerable source, Func selector, TResult defaultValue)
{
	return source.Select(selector).DefaultIfEmpty(defaultValue).Max();
}

public static TResult MaxOrDefault(this IEnumerable source, Func selector)
{
	return source.Select(selector).DefaultIfEmpty().Max();
}
		
public static TResult MinOrDefault(this IEnumerable source, Func selector, TResult defaultValue)
{
	return source.Select(selector).DefaultIfEmpty(defaultValue).Min();
}

public static TResult MinOrDefault(this IEnumerable source, Func selector)
{
	return source.Select(selector).DefaultIfEmpty().Min();
}

It just makes the code a little more succinct when trying to avoid the InvalidOperationException: Sequence contains no elements

Obvious Extension Methods: IEnumerable Cache

So you don’t want to do a ToList(), but you don’t want to enumerate your IEnumerable<T> more than once? How about an extension method called “Cache” that Caches the output as you go.

  1. public static class Extensions
  2. {
  3.     public static CachedEnumerable<T> Cache<T>(this IEnumerable<T> enumerable)
  4.     {
  5.         return new CachedEnumerable<T>(enumerable);
  6.     }
  7. }
  8. public class CachedEnumerable<T> : IEnumerable<T>
  9. {
  10.     IEnumerator<T> _originalEnumerator;
  11.     readonly IEnumerable<T> _originalEnumerable;
  12.     readonly List<T> _cache = new List<T>();
  13.     public CachedEnumerable(IEnumerable<T> enumerable)
  14.     {
  15.         _originalEnumerable = enumerable;
  16.     }
  17.     public IEnumerator<T> GetEnumerator()
  18.     {
  19.         foreach (var t in _cache)
  20.         {
  21.             yield return t;
  22.         }
  23.         if (_originalEnumerator == null)
  24.         {
  25.             _originalEnumerator = _originalEnumerable.GetEnumerator();
  26.         }
  27.         while (_originalEnumerator.MoveNext())
  28.         {
  29.             _cache.Add(_originalEnumerator.Current);
  30.             yield return _originalEnumerator.Current;
  31.         }
  32.     }
  33.     IEnumerator IEnumerable.GetEnumerator()
  34.     {
  35.         return GetEnumerator();
  36.     }
  37. }

That’s it. If you want to see it in action, open LINQPad, select Language: “C# Program”, delete everything, paste in the above, then finally, paste in the below:

void Main()
{
  var x = GetNumbers().Cache();

  "TAKE 2.".Dump();
  x.Take(2).Dump("TWO:");

  "Get them all.".Dump();
  x.Dump("ALL:");

  "Get them all again.".Dump();
  x.Dump("ALL:");
}

public IEnumerable<T> GetNumbers()
{
  yield return 1.Dump("Numbers is hard");
  Thread.Sleep(500);
  yield return 2.Dump("Numbers is hard");
  Thread.Sleep(500);
  yield return 3.Dump("Numbers is hard");
  Thread.Sleep(500);
  yield return 4.Dump("Numbers is hard");
  Thread.Sleep(500);
  yield return 5.Dump("Numbers is hard");
  Thread.Sleep(500);
  yield return 6.Dump("Numbers is hard");
}

There.

Obvious Methods: Distinct with equality selector

You have an IEnumerable<SomeType> on which you want to do a .Distinct(). “SomeType” is not equatable – at least not in the way you want. Your only choice is to write an IEqualityComparer… Until today!!!

Here’s what you WANT to write:

myEnumerable.Distinct(item => item.Id);

…assuming that the Id’s make them unique. And here’s the extension method override of Distinct that lets you do this:

public static class Extensions

{

  public static IEnumerable<T> Distinct<T, TCompare>(this IEnumerable<T> items, Func<T, TCompare> predicate)

  {

    var distinctKeys = new HashSet<TCompare>();

    foreach (var item in items)

    {

      var key = predicate(item);

      if (distinctKeys.Contains(key)) continue;

      distinctKeys.Add(key);

      yield return item;

    }

  }

}

Now, you’re probably saying, couldn’t I just write?:

myEnumerable.GroupBy(item => item.Id).Select(g => g.First());

It gives you the same output, but, this new Distinct method is:

  1. faster… like an order of magnitude faster
  2. easier to read… like an order of magnitude easier to read.
  3. lazier. Consider the following contrived enumerable:

var list = new[]

            {

              new {x = 1, y = “one”},

              new {x = 1, y = “won”},

              new {x = 1, y = “juan”},

              new {x = 0, y = “zero”},

            };

…and this call to .Distinct:

list.Distinct(item => 1 / item.x).Take(1);

With the GroupBy approach, this would raise an Exception. But with the new Distinct, you get no exception because it is so dang lazy.

Chunk

I wrote before about partitioning a string, which was a way to bust a string into Chunks. It used the string like an IEnumerable<char>. I thought it would be nice to be able to Chunk any enumerable (for batching, or whatever).

The Partition was written without regard to performance, but this time, it’s all about performance. Just try to make it faster.

Here’s the extension method:

    1 public static class Extensions

    2 {

    3   public static IEnumerable<IEnumerable<T>> ToChunks<T>(this IEnumerable<T> list, int chunkSize)

    4   {

    5     var enumerator = list.GetEnumerator();

    6

    7     for (;;)

    8     {

    9       var chunk = enumerator.GetNext(chunkSize);

   10       if (chunk.Length == 0)

   11       {

   12         break;

   13       }

   14       yield return chunk;

   15     }

   16   }

   17

   18   private static T[] GetNext<T>(this IEnumerator<T> enumerator, int count)

   19   {

   20     var ts = new T[count];

   21     int i;

   22     for (i = 0; i < count; i++)

   23     {

   24       if (!enumerator.MoveNext()) break;

   25       ts[i] = enumerator.Current;

   26     }

   27     if (i < count)

   28     {

   29       Array.Resize(ref ts, i);

   30     }

   31     return ts;

   32   }

   33 }

When I needed this recently, I also needed to know in each chunk where I was in the original IEnumerable, so instead of returning an IEnumerable of IEnumerables, I returned an IEnumerable of a new Chunk type that inherits from IEnumerable. I just had to make a small change on lines 3, 7, and 14:

    1 public static class Extensions

    2 {

    3   public static IEnumerable<Chunk<T>> ToChunks<T>(this IEnumerable<T> list, int chunkSize)

    4   {

    5     var enumerator = list.GetEnumerator();

    6

    7     for (var i = 0;; i++)

    8     {

    9       var chunk = enumerator.GetNext(chunkSize);

   10       if (chunk.Length == 0)

   11       {

   12         break;

   13       }

   14       yield return new Chunk<T>(chunk, i*chunkSize, chunk.Length);

   15     }

   16   }

   17

   18   private static T[] GetNext<T>(this IEnumerator<T> enumerator, int count)

   19   {

   20     var ts = new T[count];

   21     int i;

   22     for (i = 0; i < count; i++)

   23     {

   24       if (!enumerator.MoveNext()) break;

   25       ts[i] = enumerator.Current;

   26     }

   27     if (i < count)

   28     {

   29       Array.Resize(ref ts, i);

   30     }

   31     return ts;

   32   }

   33 }

   34

…and here’s Chunk

    1 public class Chunk<T> : IEnumerable<T>

    2 {

    3   private readonly IEnumerable<T> _chunk;

    4

    5   public Chunk(IEnumerable<T> chunk, int first, int length)

    6   {

    7     _chunk = chunk;

    8     FirstIndex = first;

    9     Length = length;

   10   }

   11

   12   public int FirstIndex { get; private set; }

   13   public int Length { get; private set; }

   14   public int LastIndex { get { return FirstIndex + Length 1; } }

   15

   16   public IEnumerator<T> GetEnumerator()

   17   {

   18     return _chunk.GetEnumerator();

   19   }

   20

   21   IEnumerator IEnumerable.GetEnumerator()

   22   {

   23     return GetEnumerator();

   24   }

   25 }

.Where? .WhereNot

Ever have some code like this?

CollectionOfThings.Where(x => !ThingMeetsSomeCondition(x))

If only there were a WhereNot method, then you could use it with a method group, like so

CollectionOfThings.WhereNot(ThingMeetsSomeCondition)

So Where is your WhereNot? Here:

  public static class Extensions

  {

    public static IEnumerable<T> WhereNot<T>(this IEnumerable<T> items, Func<T, bool> predicate)

    {

      return items.Where(x => !predicate(x));

    }

  }

 

Glad that’s done.

Be afraid of params object[]… just in time for Halloween

Paste this into Linqpad:

public enum Dukes

{

Bo,

Luke,

Daisy,

UncleJesse

}

 

// Cb a specific Duke

public void CbTheDukes(Dukes duke, params object[] things)

{

foreach (var thing in things)

{

thing.Dump(duke.ToString());

}

}

 

// Cb all the Dukes

public void CbTheDukes(params object[] things)

{

foreach (var thing in things)

{

thing.Dump(“ALL”);

}

}

 

private void Main()

{

CbTheDukes(“Shepherd to Lost Sheep”, “Got your ears on?”);

}

So… Here’s what we have.

We have a ridiculous enum, a method with an overload, and the main witch, which calls the method.

Running that in linqpad (Language: C# Program) And what do you expect? I expect (and get) the following in the output window:

ALL
Shepherd to Lost Sheep
ALL
Got your ears on?

Also, with this:

CbTheDukes(Dukes.Luke, “You’re the smart one.”);

…you get this:

Luke
You’re the smart one.

…all pretty standard use of overloads.

Since I used an object[], I can contact a Duke with anything:

CbTheDukes(“breaker”, 1, 9);

…and get this, of course:

ALL
breaker
ALL
1
ALL
9

The problem with the params object[] is when you pass a const 0 (zero) in for the first parameter.

CbTheDukes(0, “Do you copy?”);

I expected to get :

ALL
0
ALL
Do you copy?

… but alas, I get this:

Bo
Do you copy?

“Ok”, I thought, “Somehow the .NETs are finding the overload with the enum, because zero will easily cast to the enum.” Then I also thought that passing a const 1 would send a CB message to Luke, but it doesn’t.

CbTheDukes(1, “Do you copy?”);

…actually yields:

ALL
1
ALL
Do you copy?

Only the zero freaks out.

This is only true for a const value. Declare a variable, set it to zero, and pass it in and you get the overload without the enum.

I found this out when using Moq (http://code.google.com/p/moq/). The constructor for Mock<T> has one overload that takes an enum (MockBehavior) and a params object[], and another that takes only a params object[]. Mock an object with a constructor that has an int as the first param and pass the const 0 (zero) in to that bad boy, and you get get an exception – something about ‘Could not find a constructor that would match given arguments’… (unless you have another constructor that is exactly the same, except without the first int parameter, then you might never know! YIKE!)

(I’ve also run into a similar problem when a method has many overloads and one of them takes an object, like the Html helper methods in ASP.NET MVC…)

The lesson is, if you have a method that has a ‘params object[]’ argument… don’t have overloads! …or just don’t, period.

BOO!

SHED Security

I coined this phrase a while back, but it is high time that it gets documented somewhere so that when the money starts rolling in, I get my cut.

SHED security is the term used for a common type of weak security in an application.  You get it – shed vs. some other type of secure structure.  But SHED is an acronym for Show/Hide Enable/Disable.  So this method of security is only about the UI.  Hide/Disable a field, and the user can’t edit that property on the object.  BAM! Secure!