Category Archives: code

Open Source Bitcoin Trading Engine

I am developing a Bitcoin exchange trading engine.  It’s written in C# and ASP.Net MVC4/Razor.  The UI layer is service-based using knockout.js and jqGrid to bind to JSON web services.    Order processing done in a service process.

Is anyone interested learning more about the design?  Update: OK!  Graphics below updated and first detail post added.

I think it will take at least 10 posts to document this project:

Continue reading Open Source Bitcoin Trading Engine

Note on Community Server to WordPress migration

This post has has the full scoop on the process of migrating blogs from Community Server to WordPress, except for this bit: “ultimately, I just wrote a simple regular expression to reformat all the categories so that their names were in the ID attribute.”  Instead of regex, I wrote a a C# script using LINQ to XML:

const string source = @"D:export.xml";
           string source = @"D:export.xml";
            var doc = XDocument.Load(source);
            var categories = new Dictionary();
            foreach (var cat in doc.Elements().First().Elements().Descendants().Where(cat => cat.Name.LocalName == "tag"))
                if (cat.Attribute("id") != null)
                    categories.Add(Convert.ToInt32(cat.Attribute("id").Value), cat.Elements().First().Value);
                    int refId;
                    if (int.TryParse(cat.Attribute("ref").Value, out refId)) // in case it was already run
                        cat.Attribute("ref").Value = categories[refId];

A few useful commands for automating VS builds via batch file

(Batch files are not meant to be a substitute for CI)

Getting latest from TFS:

"C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEtf.exe" get

(use /preview to preview)

Getting latest from Subversion:

"C:Program Files (x86)VisualSVN Serverbinsvn.exe" update "F:webBeta"

Building a Visual Studio solution via MSBuild:

C:WindowsMicrosoft.NETFramework64v4.0.30319MSBuild.exe D:MisesMisesWeb.sln /p:configuration="Debug"

Checking whether the build succeded:

if %errorlevel% neq 0 exit /b %errorlevel%

Copying build output:

xcopy F:webBetaMisesWebbin* F:webMisesbin /Y
REM /Y don’t prompt for overwrite
REM /S recursive
REM /Z restartable mode
REM /D only copy files newer than those at destination
REM More:

Render tags in templates as a partial view with MVC3

Suppose you are rendering templated content. Sometimes you want to reference partial views (or actions) in your templates and have them render with attributes provided by your template. One option is to use a Razor templating engine. But I just needed to render partial views based on a custom tag format, so I came up with my own solution:

        /// <summary>
        ///   Render parameterized tags as a partial view in MVC3 templates
        ///   Supports tags such as 
        /// </summary>
        /// The helper.
        /// The content.
        private static string RenderPartialViewTagsInTemplate(HtmlHelper helper, string content)
            var controls = new Dictionary();
            MatchCollection matches = Regex.Matches(content, @"&lt;view: (?S+)(s+(?[^=s]+)=""?(?[^""s]+)""?)*?s*/&gt;", RegexOptions.ExplicitCapture);
            foreach (Match tag in matches)
                string viewName = tag.Groups["name"].Value;
                var routeValues = new RouteValueDictionary();
                for (int i = 0; i  { content = content.Replace(c.Key, c.Value); });
            return content;

Reading Excel files in .Net

This should work for most Excel versions including both xls and xslx:

const string ExcelConnString =
                @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";";
            var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", String.Format(ExcelConnString, physicalPath));
            var ds = new DataSet();
            adapter.Fill(ds, "anyNameHere");
            var data = ds.Tables["anyNameHere"].AsEnumerable();
            EnumerableRowCollection tags =
                data.Where(x =&gt; x.Field("tag") != string.Empty).Select(x =&gt;
                                                                                 new Tag()
                                                                                         Description = x.Field("Description")

Cross browser multi-columns with JQuery and CSS3

column-count was proposed in January 2001, candidate in December 2009. It’s supported in WebKit and Mozilla via extensions and Opera directly, but it’s not in IE9. Y U no support columns IE9? That’s OK, we can work around this with columnizer:

if ($.browser.msie &amp;&amp; $.browser.version &lt; 10) { // am I a hopeless romantic for assuming that IE10 will support it?
            width: 600,
            columns: 3
/* Support for Webkit, Mozilla, Opera */
div#multicolumn, .multicolumn {
	-moz-column-count: 3;
	-moz-column-gap: 20px;
	-webkit-column-count: 3;
	-webkit-column-gap: 20px;
	column-count: 3;
	column-gap: 20px;

Caching with a SHA1 hash (C# 4.0)

Here is the cache code:

#region don't process the same address twice
            if (newEmail.EmailHash == 0) newEmail.EmailHash = newEmail.Email.GetSHA1Hash();
            if (emailsToAdd.Contains(newEmail.EmailHash)) 
            { return false; }

For this implementation, I am returning the hash as a 32-bit integer because I am using it for caching, not security. It’s a little faster to use an int32 index than the default 160 hex digest. If avoiding collisions is important (only 4,294,967,295 values in an int32), remove the BitConverter.ToInt32 call and return a string.

It’s for C# 4.0 because it’s an extension method.

Here is the hash class. Call with STRING.GetSHA1Hash().

public static class SHA1Hash
        private static SHA1CryptoServiceProvider _cryptoTransformSHA1;
        public static SHA1CryptoServiceProvider CryptoProvider
            get { return _cryptoTransformSHA1 ?? (_cryptoTransformSHA1 = new SHA1CryptoServiceProvider()); }
        public static int GetSHA1Hash(this string stringToHash)
            return string.IsNullOrWhiteSpace(stringToHash) ? 0 : (Hash(stringToHash, Encoding.Default));
        public static int Hash(string stringToHash, Encoding enc)
            return BitConverter.ToInt32(CryptoProvider.ComputeHash(enc.GetBytes(stringToHash)), 0);

In-memory cashing for an auto-complete list

When implementing an auto-complete control on your site, you may want to cache the results to keep the database queries to a minimum. Here’s a quick way to do that:

        public static Dictionary AutoCompleteHashList = new Dictionary();
        const string resultsFormatString ="{0}|{1}rn";
        private static string GetSuggestedResults(string s)
            const int maxHashLengthToCache = 9;
            if (s.Length 
                            results.AppendFormat(resultsFormatString, recipe.Key, recipe.Value)
            if (s.Length &lt; maxHashLengthToCache)
                AutoCompleteHashList.Add(s, results.ToString());
            return results.ToString();