Monday, January 28, 2013

Convert an SQL like pattern into a regular expression pattern

var pattern = Regex.Replace(
    likePattern,
    @"[%_]|\[[^]]*\]|[^%_[]+",
    match =>
    {
        if (match.Value == "%")
        {
            return ".*";
        }
        if (match.Value == "_")
        {
            return ".";
        }
        if (match.Value.StartsWith("[") && match.Value.EndsWith("]"))
        {
            return match.Value;
        }
        return Regex.Escape(match.Value);
    });

Saturday, January 12, 2013

Load test a web site using asynchronous requests and the TPL

var queue = new Queue<Task>();
while (true)
{
    if (queue.Count >= 50)
    {
        var task = queue.Dequeue();
        task.Wait();
        task.Dispose();
    }
    var request = (HttpWebRequest) WebRequest.Create(url);
    var watch = Stopwatch.StartNew();
    queue.Enqueue(Task.Factory
        .FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null)
        .ContinueWith(task =>
            {
                using (var response = (HttpWebResponse) task.Result)
                {
                    Console.WriteLine("{0}\t{1}\t{2}",
                                      response.StatusCode, response.ContentType, watch.Elapsed);
                }
            }));
}
Task Parallel Library (TPL)