Saturday, February 28, 2015

NuGet Pack Command and ExcludeSourceCode

NuGet has an excellent feature that allows you to build a debug package that includes symbols by simply adding the "-Symbols" parameter. The somewhat controversial part of this feature is that it includes a complete copy of the source code to help with debugging.

Good News: NuGet 3.0 will include an additional command option for "-ExcludeSourceCode", allowing you to build a symbol package without including the source directory!

ExcludeSourceCode Description: "Determines if a symbols package should exclude sources when created. Only useful when included with -Symbols."

How soon will 3.0 be released? We are currently on Beta 2, so hopefully soon!

Enjoy,
Tom

Sunday, February 22, 2015

Await an Interval with a Throttle Class in .NET

Are you writing async code but need to control how often a call can be made? Just use this thread safe implementation of a throttle that will return an evenly spaced Task.Delay each time it is invoked. This will allow you to throttle that your application and control how many calls it makes.

Throttle Class

public interface IThrottle
{
    Task GetNext();
    Task GetNext(out TimeSpan delay);
}
 
public class Throttle : IThrottle
{
    private readonly object _lock = new object();
 
    private readonly TimeSpan _interval;
 
    private DateTime _nextTime;
 
    public Throttle(TimeSpan interval)
    {
        _interval = interval;
        _nextTime = DateTime.Now.Subtract(interval);
    }
 
    public Task GetNext()
    {
        TimeSpan delay;
        return GetNext(out delay);
    }
 
    public Task GetNext(out TimeSpan delay)
    {
        lock (_lock)
        {
            var now = DateTime.Now;
 
            _nextTime = _nextTime.Add(_interval);
                
            if (_nextTime > now)
            {
                delay = _nextTime - now;
                return Task.Delay(delay);
            }
 
            _nextTime = now;
 
            delay = TimeSpan.Zero;
            return Task.FromResult(true);
        }
    }
}

Saturday, February 14, 2015

Batch and Partition Extensions for .NET

Did you ever need to take a collection of items and break it into a set of batches, or divide those items into partitions? Well here are some simple extension methods to help you do that:

Extension Methods

public static class EnumerableExtensions
{
    public static IList<IList<T>> Partition<T>(
        this IEnumerable<T> items, 
        int partitionCount)
    {
        if (partitionCount == 0)
        {
            throw new ArgumentException(
                "Partition Count must be greater than zero", 
                "partitionCount");
        }
 
        return items
            .Select(
                (v, i) => new
                {
                    Group = i%partitionCount,
                    Value = v
                })
            .GroupBy(k => k.Group, v => v.Value)
            .Select(g => (IList<T>) g.ToList())
            .ToList();
    }
 
    public static IList<IList<T>> Batch<T>(
        this IEnumerable<T> items, 
        int batchSize)
    {
        if (batchSize == 0)
        {
            throw new ArgumentException(
                "Batch Size must be greater than zero", 
                "batchSize");
        }
 
        var batches = new List<IList<T>>();
        var batch = new List<T>();
 
        foreach (var item in items)
        {
            if (batch.Count == batchSize)
            {
                batches.Add(batch);
                batch = new List<T>();
            }
 
            batch.Add(item);
        }
 
        if (batch.Count > 0)
        {
            batches.Add(batch);
        }
 
        return batches;
    }
}

Saturday, January 31, 2015

Making jQuery a bit more Angular

One of my favorite features of AngularJS is the use of HTML attributes to apply controllers and directives directly to your DOM elements. Why is this so useful?

  • It is intuitive for developers to discover what code is being applied to elements.
  • It enables generic registration, removing boiler plate document ready methods.
  • It provides hierarchical scope, encouraging single responsibility controls.

jQuery plugins are already designed to be applied to collections of elements, so let's just add the ability to dynamically apply plugins via HTML attributes! This is how we can make jQuery a bit more Angular.

Sample Script

Our sample jQuery plugin is super simple; it just makes an element fade in and out continuously. This is a very simple behavior, but the point is that it is just a jQuery plugin!

(function ($) {
    $.fn.blink = function() {
        var $el = this;
        setInterval(blinkEl, 1000);
 
        function blinkEl() {
            $el.fadeToggle();
        }
    };
})(jQuery);

Capture Local Traffic for WireShark, with RawCap

Capturing local network traffic is a difficult task for many tools, including WireShark. Do not worry, there is a very simple solution to this problem!

Just use RawCap!

RawCap is a tiny (23KB) application that can capture local traffic and then write that to a pcap (packet capture) file, which can be opened by tools like WireShark! Please note that when using this you must specify your target address as 127.0.0.1, not just localhost.

Enjoy,
Tom

Friday, January 2, 2015

File.ReadAllText with an Offset in .NET

What do you do when you need to read text from a file in .NET, but you want to start from an offset? This is a slightly niche scenario, but it does happen. Below is a solution to that problem.

To summarize the implementation, you open a file stream, seek to your offset, and then read in the bytes from there. While loading the result I read small chunks into a buffer, decoded them, and then added the decoded string to a string buffer for storage. Please note that if you are using a multibyte encoding then this helper will only work if you use the correct offset.

Helper Code

public class FileHelper
{
    private const int BufferSize = 1024;
 
    public static string ReadAllTextFromOffset(
        string path, 
        Encoding encoding, 
        int offset, 
        out int totalLength)
    {
        using (var fs = new FileStream(path, FileMode.Open))
        {
            totalLength = offset;
 
            if (offset > 0)
            {
                fs.Seek(offset, SeekOrigin.Begin);
            }
 
            var sb = new StringBuilder();
            var buffer = new byte[BufferSize];
            int readCount;
 
            do
            {
                readCount = fs.Read(buffer, 0, buffer.Length);
                totalLength += readCount;
 
                var subString = encoding.GetString(buffer, 0, readCount);
                sb.Append(subString);
            }
            while (readCount == buffer.Length);
 
            return sb.ToString();
        }
    }
}

Wednesday, December 31, 2014

2014 Retrospective

Blog

This was the first year where I wrote four blog posts every month, and the unintended side effect was that the posts become smaller. I'm not sure how much I liked that; on the one hand I got to write more quick articles with little helpful information, but to be honest I did not enjoy writing those little posts as much.

Next year I will be reducing this to only three medium length posts per month. I am hoping this will be a good compromise between quantity and quality.

QQ Cast

I absolutely loved doing the QQ-Cast with my friend, Jordan. We started out the year strong, averaging three hour long episodes a month. Unfortunately as the year continued "life got in the way" and we only recorded two episodes in the last three months of the year.

Next year Jordan and I will be following a release cadence of three times a month, but shorter half hour episodes. Obviously this is similar to the blog schedule.

Professional

It has been a crazy year for me professionally. Without going into detail, I switched teams at work and now have a completely different set of responsibilities. I made this change to in order to get out of my comfort zone and, as is a core value for my company, to learn and grow.

It has been very challenging, but very rewarding. I would highly encourage all software engineers who have been in the same roll for three years or more to consider changing positions. What you learn in the first three months of a new job is often more than you will learn the rest of the year.

Personal

I got married. I bought an FZ-09. I, as mentioned above, changed positions at work. That really sums up 2014. Next year I clearly need to focus more on having a better work / personal life balance...maybe I should take more vacations?

Happy New Year,
Tom

Real Time Web Analytics