MEO Wallet API Client in .NET/C#

I’ve been playing with the MEO Wallet API that was released in a “preview” environment at the first day of Codebits.

In the very same day I had a working prototype of a slot machine, where you could buy credits to play with MEO Wallet. In the next day, we deployed it and added a redeem feature, so that users could cash-out after a jackpot.

Well, I decided to reuse some of the code that we did at Codebits to develop a generic MEO Wallet API Client. It was designed for .NET 4.5, uses HttpClient and has a demo project that you can play with.

Check it out:

Benchmark Driven Development and Parsing binary data in JavaScript

I’ve come across an interesting read on the development of a mysql client for Node.js. The full article can be found here:

It’s a very interesting read on the competition among similar open-source projects nowadays, but what really made me think was the concept of Benchmark Driven Development. It is awesome, and i’ve seen projects like WebScaleSql use it but not naming it that.

Other thing that was impressive was the fact that in a given point in time, the mentioned mysql libraries had so much throughput that they could take down the actual mysql server. In fact, that could look that way with a single DB server, but with a cluster with many read-only slaves I think we could still use it (the article does not specify the type of commands that are being executed, so i’m assuming that they are talking about reads. scaling writes is much harder).

Anyway, I recommend that you read that article. It’s a 5 minute read, and it’s worth it.

Quick-start to MVC4 Bundling

After using MVC4′s bundling in a couple of web apps I got to a simple recipe:

  1. Add the NuGet package Microsoft.AspNet.Web.Optimization (
  2. On your Global.asax.cs file, add the following call on Application_Start:
  3. Create a class called BundleConfig in your App_Start folder, with a method named RegisterBundles:
    public class BundleConfig
        public static void RegisterBundles(BundleCollection bundles)
  4. If you want to use optimizations on your debug environment, add the following line on top of the RegisterBundles method:
    BundleTable.EnableOptimizations = true; // force to show on debug mode
  5. Add your bundles to the RegisterBundles method, such as:
    bundles.Add(new StyleBundle("~/css/global").Include("~/Content/site.css"));
  6. If you are like me and you use virtual paths for css bundles that don’t match the real location of the files, you will have problems using the StyleBundle with relative image URIs. To solve this without changing your original css files, you can create a custom IBundleTransform that resolves the image path. My solution is largely based on this stackoverflow answer:
    public class RelativePathResolverTransform : IBundleTransform
    	public void Process(BundleContext context, BundleResponse response)
    		response.Content = String.Empty;
    		Regex pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
    		// open each of the files
    		foreach (FileInfo cssFileInfo in response.Files)
    			if (cssFileInfo.Exists)
    				// apply the RegEx to the file (to change relative paths)
    				string contents = File.ReadAllText(cssFileInfo.FullName);
    				MatchCollection matches = pattern.Matches(contents);
    				// Ignore the file if no match 
    				if (matches.Count > 0)
    					string cssFilePath = cssFileInfo.DirectoryName;
    					string cssVirtualPath = RelativeFromAbsolutePath(context.HttpContext, cssFilePath);
    					foreach (Match match in matches)
    						// this is a path that is relative to the CSS file
    						string relativeToCSS = match.Groups[2].Value;
    						// combine the relative path to the cssAbsolute
    						string absoluteToUrl = Path.GetFullPath(Path.Combine(cssFilePath, relativeToCSS));
    						// make this server relative
    						string serverRelativeUrl = RelativeFromAbsolutePath(context.HttpContext, absoluteToUrl);
    						string quote = match.Groups[1].Value;
    						string replace = String.Format("url({0}{1}{0})", quote, serverRelativeUrl);
    						contents = contents.Replace(match.Groups[0].Value, replace);
    				// copy the result into the response.
    				response.Content = String.Format("{0}\r\n{1}", response.Content, contents);
    	private static string RelativeFromAbsolutePath(HttpContextBase context, string path)
    		var request = context.Request;
    		var applicationPath = request.PhysicalApplicationPath;
    		var virtualDir = request.ApplicationPath;
    		virtualDir = virtualDir == "/" ? virtualDir : (virtualDir + "/");
    		return path.Replace(applicationPath, virtualDir).Replace(@"\", "/");
  7. To make it easier to use, I also added a custom Bundle:
    public class ImageRelativeStyleBundle : StyleBundle
        public ImageRelativeStyleBundle(string virtualPath)
            : base(virtualPath)
            Transforms.Add(new RelativePathResolverTransform());
        public ImageRelativeStyleBundle(string virtualPath, string cdnPath)
            : base(virtualPath, cdnPath)
            Transforms.Add(new RelativePathResolverTransform());
  8. You can use it like this:
    bundles.Add(new ImageRelativeStyleBundle("~/css/jqueryui").Include
  9. To use bundles in your views, I recommend adding the System.Web.Optimization namespace to /Views/Web.config, on the namespaces section:
    	<add namespace="System.Web.Optimization" />
  10. Now you just need to call Styles.Render(“~/css/jqueryui”) for the example above to work. For javascript you can use the Scripts.Render(“virtualpath”) call. If you need to specify custom attributes to your element, such as the media attribute for print css versions, you can build the element yourself and use the Styles.Url method, like so:
    <link href="@Styles.Url("~/css/print")" rel="stylesheet" type="text/css" media="print" />

I’ve successfully (but also painfully) integrated MVC4′s bundling and minification with dotless, for LESS CSS support. I’ll explain the necessary steps on the next blog post.

In this post’s comments, Kenneth commented on the lack of support for debug mode when using Styles.Url in a link tag. To solve this issue, I’ve created some methods that add this functionality.

Notes: Because the Style class and its methods are static I can’t just overload their behavior nor add another extension method, so instead I added a separate class that you could use instead of Style. I took advantage of the DEBUG compilation constant to avoid some string manipulation on a production/release environment.

public static class Bundles
    public static IHtmlString Render(string path, object htmlAttributes)
        return Render(path, new RouteValueDictionary(htmlAttributes));

    public static IHtmlString Render(string path, IDictionary<string, object> htmlAttributes)
        var attributes = BuildHtmlStringFrom(htmlAttributes);

        var originalHtml = Styles.Render(path).ToHtmlString();
        string tagsWithAttributes = originalHtml.Replace("/>", attributes + "/>");
        return MvcHtmlString.Create(tagsWithAttributes);

        string tagWithAttribute = string.Format(
            "<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\"{1} />", 
            Styles.Url(path), attributes);

        return MvcHtmlString.Create(tagWithAttribute);

    private static string BuildHtmlStringFrom(IEnumerable<KeyValuePair<string, object>> htmlAttributes)
        var builder = new StringBuilder();

        foreach (var attribute in htmlAttributes)
            builder.AppendFormat(" {0}=\"{1}\"", attribute.Key, attribute.Value);

        return builder.ToString();


@Bundles.Render("~/css/print", new { media = "print" })

Using RavenDB with ASP.NET Web API

Since the RC version of ASP.NET Web API came out I was having trouble using it with RavenDB, due to the latest’s JSON.Net version prerequisites.  Today I found out that there is a way to use both without having to use the unstable builds of RavenDB server (that support the same versions of JSON.Net as Web API).

You’ll probably want to run your RavenDB server instance on a separated process (not embedded), so you can now use a RavenDB client that supports the latest version on JSON.Net, thus resolving this issue. Then, if you need to configure the RavenDB server itself , you can just use the stable binaries.

RavenDB Client:

PS: If you still have troubles with JSON.Net’s version, be sure to try RavenDB Client Unstable/pre-release binaries from NuGet. The latest version is at (select “Include Prerelease” in the Package Manager UI or add the “-Pre” parameter on the console). I’m running the latest unstable client binaries with a stable server build and I had no problems so far.

LINQ: To cache or not to cache

I’m now working more often with IEnumerables and IQueryables, and the more code I write the more nervous I get about the performance issues related to the transversal of these sequences. When writing code to fulfill a purpose I often forget about the multiple enumerations below LINQ’s syntactic sugar, but the feeling that something is not the way it is supposed to be emerges right after the first self-code review.

Today is a good day to talk about this, since I just read an article about Caching LINQ Results. In this article Chris Eargle talks about three techniques to use with LINQ:

  1. Delayed Execution (Lazy Loading)
  2. Materialization (Eager Loading)
  3. Memoization (Lazy Loading + Caching)

All these techniques have its own specific goals, but my purpose for this post is not to discuss when to use either. My real concern is about the limits of caching this kinds of sequences.

I know that memory nowadays is cheap, but if everyone made that assumption everyday we’d run out of memory on our servers faster than people can tweet “earthquake!” when the ground starts to move. What is the threshold for this kind of caching? Should there be a dedicated data-structure to host this information? What if the issue is not the memory that we use on this kind of caching, but the time it stays in memory before GC kicks in?

I will be experimenting with a few situations and searching to see if anyone has done the same. I’m thinking about exploring the following possibilities:

  • Create a data-structure to host the IEnumerable cache, limited to a specific size, and with a ring buffer-like strategy (removing the oldest cache) or probably some metric to evaluate the usage of a cache piece.
  • Use caching in several spots when needed, but use strategies like weak references, or even timeouts when the cache isn’t used in a specific time limit, to try to free up space as soon as possible.

I’d like to hear from you regarding these topics, do you have any experiences in this field?