Setting the Color Scheme and Font in gvim

by Paul Ramin 16. August 2010 11:35

Everytime I install a new gVim somewhere, I always have to look for how to restore my favorite settings.  
colorscheme darkblue
set guifont=Lucida_Console:h8:cDEFAULT
Thanks to http://otype.de/index.php?id=113

Tags:

Enabling FxCop/CodeAnalysis for all Projects in a Solution File

by Paul Ramin 12. August 2010 11:12

    Public Sub EnableFxCop()

        Dim objProj As Object()

        Dim proj As Project

 

        For i As Integer = 1 To DTE.Solution.Projects.Count

            proj = DTE.Solution.Projects.Item(i)

            ToggleFxCop(proj, "True")

        Next

 

        DTE.ExecuteCommand("Build.RebuildSolution")

    End Sub

 

    Private Sub ToggleFxCop(ByVal project As Project, ByVal state As String)

        If project.Kind = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}" Then

            'Filter Project Folders

            For Each subProject As ProjectItem In project.ProjectItems

                ToggleFxCop(subProject.SubProject, state)

            Next

        Else

            If Not IsNothing(project.ConfigurationManager) Then

                project.ConfigurationManager.ActiveConfiguration.Properties.Item("RunCodeAnalysis").Value = state

                project.Save()

            End If

        End If

    End Sub

Tags:

Jailbreaking: Making your iPhone more useful

by Paul Ramin 10. August 2010 16:31

First JailBreak your iPhone 4: http://www.jailbreakme.com

Then go fix your terminal: http://www.iphone4jailbreak.org/forum/terminal-crah-on-iphone-4.html

If your browser is being silly and won't let you access xsellize.com to look up the hostname for the repository, then add "cydia.xsellize.com" to your list of repositories in cydia, and continue following the last post in the second link :-)

Tags:

Parsing a HexString into a Byte Array

by Paul Ramin 23. July 2010 16:32

I have seen an awful lot of posts looking for how to parse HexStrings into byte arrays.  Here is a function which does that, and the tests that prove that it is correct.

/// <summary>
/// Try to parse a string of hexidecimal characters into a byte array
/// </summary>
/// <param name="hexString">String of hexidecimal digits</param>
/// <param name="bytes">output byte array</param>
/// <returns>True if successful</returns>
public static bool TryParseHexString(string hexString, out byte [] bytes)
{
    if( string.IsNullOrEmpty(hexString))
    {
        bytes = new byte[0];
        return true;
    }

    char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int length = hexString.Length;
    char[] chars = hexString.ToUpperInvariant().ToCharArray();
    int index = length % 2 != 0 ? -1 : 0;
    int bytePosition = 0;
    bytes = new byte[(length + 1) / 2];

    for (; index < hexString.Length; index += 2)
    {
        int high = index >= 0 ? Array.IndexOf(digits, chars[index]) : 0;
        int low = Array.IndexOf(digits, chars[index+1]);

        if( high == -1 || low == -1)
        {
            bytes = new byte[0];
            return false;
        }

        bytes[bytePosition ++] = (byte) ((high << 4) | low);
    }

    return true;
}

Figure 1: Function to parse a Hex String

byte[] bytes;
Debug.Assert(TryParseHexString("", out bytes) && bytes.Length == 0);
Debug.Assert(TryParseHexString(null, out bytes) && bytes.Length == 0);
Debug.Assert(TryParseHexString("A", out bytes) && bytes.Length == 1 && bytes[0] == 0x0A);
Debug.Assert(TryParseHexString("a", out bytes) && bytes.Length == 1 && bytes[0] == 0x0A);
Debug.Assert(TryParseHexString("a0", out bytes) && bytes.Length == 1 && bytes[0] == 0xA0);
Debug.Assert(TryParseHexString("a0a", out bytes) && bytes.Length == 2 && bytes[0] == 0x0A && bytes[1]==0x0A);
Debug.Assert(!TryParseHexString("Garbage", out bytes) && bytes.Length == 0);

Figure 2: Test cases for the above function

Tags: ,

.NET

Convert From Byte Array to HexString

by Paul Ramin 23. July 2010 15:23

So today, I was looking for a simple way to convert a byte array to a string of hexadecimal digits. It turns out that the quickest and most flexible way to do this was to use Enumerable.Aggregate():

public static string ToHexString(IEnumerable<byte> array)
{
    return array.Aggregate(new StringBuilder(), (sb, b) => sb.Append(b.ToString("X2"))).ToString();
}

Figure 1: Convert a byte array to a string of hexadecimal digits

This same function can be extended to work for other types as well

Tags:

.NET

Generalized IAsyncResult Implementations

by Paul Ramin 13. July 2010 05:40

Being that I love using the .NET asynchronous paradigm to almost completely forget about threading (though it is there, and precautions need to be taken to avoid livelock and deadlock), I have implemented a few classes which implement the IAsyncResult interface.  These implementations are based on the IAsyncResult implementation written by Jeffrey Richter in Concurrent Affairs in March 2007 in his article Implementing the CLR Asynchronous Programming Model

Before getting into the implementation, here is the inspiration behind the implementation.  When dealing with socket Send and Receive it is possible for both functions to not process a complete message when called, however both functions return the number of bytes they processed.   Usually in my applications, I find it useful to implement a function that looks like the one in Figure 1.

private void ReadBuffer(Socket socket, byte [] buffer, int offset, int length, SocketFlags flags)
{
    while(length > 0)
    {
        int bytesRead = socket.Receive(buffer, offset, length, flags);
        if( bytesRead == 0)
        {
            throw new Exception("Remote server closed the connection unexpectedly");
        }
        offset += bytesRead;
        length -= bytesRead;
    }
}

Figure 1: Synchronous operation that usually ends up needing to be asynchronous

Since working with the Asynchronous APIs, I’ve found that the same function is still useful, and needed to convert it to the asynchronous IAsyncResult paradigm.  In doing so, I needed to convert the method in Figure 1 to have a signature like:

IAsyncResult BeginReadBuffer(Socket socket, byte [] buffer, int offset, int length, SocketFlags flags, AsyncCallback asyncCallback, Object asyncState);

void EndReadBuffer(IAsyncResult asyncResult);

Figure 2: Asynchronous signatures for the method in Figure 1.

I could implement the asynchronous methods by faking it, i.e. create a delegate the matches the signature of ReadBuffer and call its BeginInvoke and EndInvoke methods, however the purpose of using the asynchronous API in the first place was to reduce the total number of threads, and number of threads waiting.  So with that said, I needed to implement IAsyncResult somehow.  It turns out that Jeffrey Richter wrote this awesome article on the .NET asynchronous programming model (Implementing the CLR Asynchronous Programming Model), which included an implementation of the IAsyncResult interface which only created a ManualResetEvent when it was needed, i.e. the event was created lazily, which is great for performance, and reduces the number of system objects created.

Getting back to my example, the IAsyncResult implementation had to be a base class which would handle the majority of the busy work needed to create an IAsyncResult implementation, be able to return values from the EndMethod, and not corrupt stack traces so the original exception source could be found.

Without further adieu, here is the implementation, that you’re free to use wherever you need it

namespace DigitalMindspring.Threading
{
    using System;
    using System.Threading;

    /// <summary>
    /// </summary>
    /// <remarks>
    ///   This is a modified version of the code found in Jeffery Richter's 
    ///   article in the March 2007 issue of Concurrent Affairs titled
    ///   "Implementing the CLR Asynchronous Programming Model"
    /// 
    ///   Direct Link   : http://msdn.microsoft.com/en-us/magazine/cc163467.aspx
    ///   Search Link(s): http://www.google.com/search?hl=en&source=hp&q=Concurrent+Affairs+Implementing+the+CLR+Asynchronous+Programming+Model&aq=f&oq=&aqi=
    ///   : http://www.bing.com/search?q=Concurrent+Affairs+Implementing+the+CLR+Asynchronous+Programming+Model&go=&form=QBLH&qs=n
    /// </remarks>
    public abstract class AsyncResultBase : IAsyncResult
    {
        // Fields set at construction which do change after 
        // operation completes
        private const Int32 StatePending = 0;
        private const Int32 StateCompletedSynchronously = 1;
        private const Int32 StateCompletedAsynchronously = 2;
        private readonly AsyncCallback _asyncCallback;
        private readonly Object _asyncState;

        // Field that may or may not get set depending on usage
        private ManualResetEvent _asyncWaitHandle;
        private Int32 _completedState = StatePending;

        // Fields set when operation completes
        private Exception _exception;

        protected AsyncResultBase(AsyncCallback asyncCallback, Object state)
        {
            _asyncCallback = asyncCallback;
            _asyncState = state;
        }

        protected void SetAsCompleted(Exception exception, Boolean completedSynchronously)
        {
            // Passing null for exception means no error occurred. 
            // This is the common case.  
            if( exception != null )
            {
                if( exception is AsyncOperationException )
                {
                    // Pass on the exception if the stack has already 
                    // been saved
                    _exception = exception;
                }
                else
                {
                    // Save the stack trace
                    _exception = new AsyncOperationException(exception);
                }
            }

            // The _CompletedState field MUST be set prior calling the callback
            Int32 newState = completedSynchronously ? StateCompletedSynchronously : StateCompletedAsynchronously;
            Int32 prevState = Interlocked.Exchange(ref _completedState, newState);

            // Call "Complete" code only if the prevState changes from StatePending
            if (prevState == StatePending)
            {
                // If the event exists, set it
                if (_asyncWaitHandle != null)
                {
                    _asyncWaitHandle.Set();
                }

                // If a callback method was set, call it
                if (_asyncCallback != null)
                {
                    _asyncCallback(this);
                }

                return;
            }

            // Throw an exception if we're not resetting the completion status
            if (prevState != newState)
            {
                throw new InvalidOperationException("You can set a result only once");
            }
        }

        public Boolean TryWaitForComplete(int milliseconds)
        {
            // This method assumes that only 1 thread calls EndInvoke 
            // for this object
            if (!IsCompleted)
            {
                // If the operation isn't done, try waiting for it
                if (!AsyncWaitHandle.WaitOne(milliseconds, false))
                {
                    return false;
                }
            }

            // Operation is done: if an exception occured, throw it
            if (_exception != null)
            {
                throw _exception;
            }

            return true;
        }

        #region Implementation of IAsyncResult

        public Object AsyncState
        {
            get { return _asyncState; }
        }

        public Boolean CompletedSynchronously
        {
            get { return Thread.VolatileRead(ref _completedState) == StateCompletedSynchronously; }
        }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                if (_asyncWaitHandle == null)
                {
                    Boolean done = IsCompleted;
                    ManualResetEvent mre = new ManualResetEvent(done);
                    if (Interlocked.CompareExchange(ref _asyncWaitHandle,
                                                    mre, null) != null)
                    {
                        // Another thread created this object's event; dispose 
                        // the event we just created
                        mre.Close();
                    }
                    else
                    {
                        if (!done && IsCompleted)
                        {
                            // If the operation wasn't done when we created 
                            // the event but now it is done, set the event
                            _asyncWaitHandle.Set();
                        }
                    }
                }
                return _asyncWaitHandle;
            }
        }

        public Boolean IsCompleted
        {
            get
            {
                return Thread.VolatileRead(ref _completedState) !=
                       StatePending;
            }
        }

        #endregion
    }

    public interface IAsyncResultEx : IAsyncResult
    {
        void WaitForComplete();
        Boolean WaitForComplete(int milliseconds);
    }

    public interface IAsyncResultEx<TReturnValue> : IAsyncResult
    {
        TReturnValue WaitForComplete();
        Boolean WaitForComplete(out TReturnValue returnValue, int milliseconds);
    }

    public class AsyncResultEx<TReturnValue> : AsyncResultBase, IAsyncResultEx<TReturnValue>
    {
        public TReturnValue ReturnValue;

        public AsyncResultEx(AsyncCallback asyncCallback, Object state)
            : base(asyncCallback, state)
        {
        }

        #region IAsyncResultEx<TReturnValue> Members

        public TReturnValue WaitForComplete()
        {
            TryWaitForComplete(-1);

            return ReturnValue;
        }

        public Boolean WaitForComplete(out TReturnValue returnValue, int milliseconds)
        {
            if (TryWaitForComplete(milliseconds))
            {
                returnValue = ReturnValue;
                return true;
            }

            returnValue = default(TReturnValue);
            return false;
        }

        #endregion

        public void Complete(TReturnValue returnValue)
        {
            ReturnValue = returnValue;
            SetAsCompleted(null, false);
        }

        public void Complete(TReturnValue returnValue, Boolean completedSyunchronously)
        {
            ReturnValue = returnValue;
            SetAsCompleted(null, completedSyunchronously);
        }

        public void Throw(Exception exception)
        {
            SetAsCompleted(exception, false);
        }
    }

    public class AsyncResultEx : AsyncResultBase, IAsyncResultEx
    {
        public AsyncResultEx(AsyncCallback asyncCallback, Object state)
            : base(asyncCallback, state)
        {
        }

        #region IAsyncResultEx Members

        public void WaitForComplete()
        {
            TryWaitForComplete(-1);
        }

        public Boolean WaitForComplete(int milliseconds)
        {
            return TryWaitForComplete(milliseconds);
        }

        #endregion

        public void Complete()
        {
            SetAsCompleted(null, false);
        }

        public void Complete(Boolean completedSyunchronously)
        {
            SetAsCompleted(null, completedSyunchronously);
        }

        public void Throw(Exception exception)
        {
            SetAsCompleted(exception, false);
        }
    }
}

Figure 3: Generic implementation of IAsyncResult

Tags:

.NET | Asynchronous Programming | Threading

DigitalMindspring.com is Live

by Paul Ramin 12. July 2010 05:15

I have finally moved my blog into its rightful place at the root of DigitalMindspring.com for the world to enjoy.

Tags:

Concatenating Row Values into a Comma Separated List

by Paul Ramin 6. July 2010 03:00

The other day, I was looking for a simple way to take the results of a SQL query and turn them into a comma separated list.

SELECT CountryIsoCode
FROM   CountryPopulations
WHERE  Population > 300000000

Figure 1: The SQL query that I wanted to convert to a comma separated list

After a fair amount of searching Google and Bing, I finally ran across this post on StackOverflow.com. Unfortunately none of the answers directly answered my question, but made me realize that if I were to output the result as an XML string, I could simply search and replace the XML tags to form a comma separated list.

SELECT REPLACE(REPLACEREPLACE((CAST((

    SELECT CountryIsoCode
    FROM   CountryPopulations
    WHERE  Population > 300000000

FOR XML PATH('')) AS NVARCHAR(MAX))), '</X><X>', ', '),'<X>', ''),'</X>','')

Figure 2: The SQL query that outputs a comma separated list for a given query

Hope this helps someone out there.

Tags:

SQL

A Simple Blocking Queue

by Paul Ramin 4. July 2010 05:07

In some applications it is necessary to have a queue which blocks the caller until it can dequeue an item.  Below is a listing for a very simple blocking queue.

namespace DigitalMindspring.Threading
{
    using System.Collections.Generic;
    using System.Threading;

    /// <summary>
    /// A queue which blocks when there are no items
    /// </summary>
    /// <typeparam name="TWorkItem">Type of Item to enqueue</typeparam>
    public class BlockingQueue<TWorkItem>
    {
        /// <summary>
        /// Initialize the blocking queue
        /// </summary>
        public BlockingQueue()
        {
            _blockingLock = new Semaphore(0, int.MaxValue);
            _workQueue = new Queue<TWorkItem>();
        }

        /// <summary>
        /// Add an item to the queue
        /// </summary>
        /// <param name="workWorkItem">The item to add</param>
        public void Enqueue(TWorkItem workWorkItem)
        {
            lock(_workQueue)
            {
                _workQueue.Enqueue(workWorkItem);
                _blockingLock.Release();
            }
        }

        /// <summary>
        /// Retrieve an item from the queue, waiting for an item
        /// to be added if none exists. 
        /// </summary>
        /// <returns>The item at the head of the queue</returns>
        public TWorkItem Dequeue()
        {
            _blockingLock.WaitOne();
            lock(_workQueue)
            {
                return _workQueue.Dequeue();
            }
        }

        private Queue<TWorkItem> _workQueue;
        private Semaphore _blockingLock;
    }
}

Figure 1: A simple blocking queue

How it works

The blocking queue works by using a semaphore to block Dequeue requests until new items have been Enqueued in the queue.  The enqueue and dequeue operations are protected by C# lock statements which act as critical sections, disallowing other threads from tampering with the queue while the current thread modifies the queue.

Tags: , ,

.NET | Data Structures

Atomically Updating a Value

by Paul Ramin 2. July 2010 15:18

Here is a simple example of how atomically update a value beyond the basic Interlocked functions:

Code Snippet
  1. public T InterlockedUpdate<T>(ref T item, T newValue)
  2.     where T: class
  3. {
  4.     T oldValue;
  5.  
  6.     do
  7.     {
  8.         // Save the old value
  9.         oldValue = item;
  10.  
  11.         // TODO: set newValue to the new value
  12.         newValue = newValue;
  13.  
  14.         // Loop until the value is set
  15.     } while (Interlocked.CompareExchange(ref item, newValue, oldValue) != oldValue);
  16.  
  17.     return newValue;
  18. }

 

Why it Works

This works because Interlocked.CompareExchange only fails if another thread's Interlocked.CompareExchange succeeds.

Tags: , ,

Threading

Month List

Calendar

<<  May 2012  >>
MoTuWeThFrSaSu
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar