Monday, October 17, 2016

How to show excel files inside the .NET Webbrowser Control

If you are reading this, chances are you been banging your head against the wall for a couple of hours (or even days) trying to show excel files inside the WinForms webbrowser control.
Possible reasons you ended up in here:
  1. You had working code that got broke after upgrading from Win 7.
  2. Your code doesn’t work the same way between machines running different (newer) versions of IE.
  3. A download box pops up every time your app tries to show an excel file inside the webbrowser control (you wanna show the actual content).
  4. You just have no clue on how to get excel working into the .NET embedded webbrowser control.
  5. You are trying to implement IInternetSecurityManager and don’t know where to start. (Or how don’t know how to delegate calls to your security manager).
  6. Among many other, maybe…..

Yes, COM is a PITA, so is ActiveX and IE (Embedded or full for that matter). And no, showing excel files inside the webbrowser control shouldn’t be that hard, but sometimes we have to deal with what we have at hand, so here it goes….

TL;DR; If you are in a rush, go to to get working code on how to embed excel files into the webbrowser control. Yes, yes... I know... You are welcome ;)!

For those who wanna go deeper, let’s just say we are going to deal with COM, OWC, unsafe code, a custom implementation of IInternetSecurityManager, and of course Excel and IE.

Before start

  1. Make sure you ‘ve Office Web Components on your machine. If you don’t have it, you can download it from here. This component is the one that will take care of Excel interop.
  2. Clone the repo from and make sure it builds. (No, there is no .sln nor csproj in there. We are programming like real men do ;)). Just run build.bat and if you don’t see any errors, you are ready to go. If you wanna use VS, just create a new project and copy paste the code (it’s all in one file).

Working with the code

As you may guess already, we are going to deal with a combination of C# and HTML. To avoid boring you, I’ll only show/comment the important bits and let you explore the rest of code by yourself.

Crafting the HTML

The first step is to create an HTML page that will hold an instance of  OWC (Office Spreadsheets, more precisely) and configure it to show our excel file. The code will look something like this (let’s call the file “index.html”):

   <object id="excel"
       <param name="DisplayColumnHeadings" value="-1">
       <param name="DisplayRowHeadings" value="0">
       <param name="DisplayToolbar" value="0">
       <param name="XMLURL" value="test.xml">

Important bits:
  1. CLSID Must be equal to whatever you have on the registry for “Microsoft Office Spreadsheet [version]. As far as I can tell, this value doesn’t among different versions of Office, but who knows… If I were you, I’ll check it anyways. (Open regedit and search for Microsoft Office Spreadsheet “).
  2. Make sure “test.xml” exist and is reachable from where your page is running. (If relative paths are not working for you, try absolut ones, they should work right off the bat).
  3. Make sure you’ve save the excel file as xml. As odd as it sound , OWC can’t handle excel file format!. Repeat after me, it can’t handle Excel files… So be careful.

Quick test:
Open the html page (using full IE, not that crappie Edge thing) and you should get a popup saying “Internet Explorer restricted this webpage from running script or ActiveX Objects”. Click “Allow blocked content”, and you’ll see an excel file “running” inside IE.
If you can’t get this to work, stop here and review everything, paths, owc installation, CLSID, excel file saved as xml, etc… etc…. It has no point to keep going if this step is not right.

Crafting the C# code

Now that we have OWC up and running and a web page to show our content, we are ready to roll, right?


And…. nope. Is not working. Why is that?

Well, when you previously open the page using full IE, you got a message asking you to allow blocked content. Guess what happens when IE has no way to ask your permission… It assumes you would say: no. (Which is, security wise, 100% correct).
Now is where things get little bit trickier, because there is no way to bypass IE security mechanisms. (Of course you can change the security level for a particular machine, but doing so will put the whole machine at risk because those settings are globals to IE, not just for the embedded browser that you are running inside your app). So you have to implement IInternetSecurityManager interface and allow such and such operations to be completed without asking user’s permission.

Once again, I’ll show the meaningful bits, you can see the whole stuff by checking out the code.

// This class allows us to delegate security aspects to our custom InternetSecurityManager.
class WebBrowserSiteEx :
IInternetSecurityManager {
public unsafe int MapUrlToZone(string url, int* pdwZone, int dwFlags) {
// ["Local", "Intranet", "Trusted", "Internet", "Restricted"]
// Here we are saying that our site is running under the
// local security policy.
*pdwZone = 0; // <= Local.
return Constants.S_OK;
public unsafe int ProcessUrlAction(
string url, int dwAction, byte* pPolicy, int cbPolicy,
byte* pContext, int cbContext, int dwFlags,
int dwReserved) {
// And here we say, yes, allow this action….
*((int*)pPolicy) = (int)Constants.UrlPolicy.URLPOLICY_ALLOW;
return Constants.S_OK;

public class WebBrowserEx : System.Windows.Forms.WebBrowser {
WebBrowserSiteEx _site;

protected override WebBrowserSiteBase CreateWebBrowserSiteBase() {
return _site ?? (_site = new WebBrowserSiteEx(this));

public static class Constants {
public const int S_OK = 0;
public const int E_NOINTERFACE = unchecked((int)0x80004002);
public const int INET_E_DEFAULT_ACTION = unchecked((int)0x800C0011);
public enum UrlPolicy {

Note: The code assumes that the user didn’t change the IE security settings for local zone. If you have troubles with this, try to restore the settings to factory defaults. Or create a custom zone and change the code accordingly.

Now that we know some security internals, is time to build the code and see what happens. In order to do so, go to the src directory and run build.bat. If everything was OK, you should have a file called program.exe at the bin directory and a working version of Excel running inside the WebBrowser control!

If you are using VS, make sure your build is targeting the x86 platform and that you have the “unsafe” flag turned on (where unsafe means unmanaged code). A really annoying thing about ActiveX Objects inside the Webbrowser control is that they fail silently without giving you any clue about what went wrong. So keep an eye on that, too.


Credit where credit is due

While none of this post is a complete solution on how to show excel files inside the webbrowser control, they really help me to get off the ground.

Tuesday, September 27, 2016

Ruby and CQRS - Command methods should return nothing

CQRS stands for Command Query Responsibility Segregation and the basic rules are:
Commands - Perform (side effects) actions on the system and don't return values.
Queries  - Return values but can't touch the system's state.
Idealy, you don't mix them. Hence you can say, commands are dangerous, and
queries are safe.

Now, ruby doesn't have a specific type to say: this method (command) returns nothing, like void in C and other languages. So, the question is: How do you state that a particular method returns nothing?

Based on comments from the ruby mailing list, people are using these approaches;
1. Return self.
2. Return nil.
3. Implicit return (which in general, ends up being nil).

If I'd have to pick one, I'd go with the last one, but I also like to throw
another option into the mix....
Why don't create a class for this particular use case? Let's say, Nothing!

module Nothing
class Nothing

def nothing
@nothing ||=

class CommandQueryApi
include Nothing

# By using the nothing helper, is clear that the method returns, nothing!
def cmd_foo
# Do something

I 've used this approach a couple of times, and at least to me and my team, when you look at the code, is pretty clear that the method returns, well, nothing ;)

Not sure is this is the ruby way, but has being working so far.

Tuesday, September 6, 2016

Contest is here to stay

For a long time the .NET's unit testing landscape hasn't changed that much... sure, new frameworks arrived, but they were almost the same thing with a subtle syntax twist, instead using [Test] they use [Fact] or different ways to specify setups and so on, but the essence was the same... Attributes based libraries with GUI oriented test runners. There is nothing wrong with that perse, but I guess everybody would agree that they are hard to use if you are working on plaint text editor like vi or emacs. In this context, contest was born as an alternative to IDE oriented tools for those who prefer consoles and text editors. The way the art of programming was meant to be ;)
For an elevator pitch, please refer to this codeproject article
For docs and getting started guides go the contest's repo on github.
And of course, if you have any question, fell free to contact me.

Tuesday, September 22, 2015

Install Command-T on Windows

Command-T is one of the most powerful Vim's plugins but install it on a Windows box could be a bit of pain in the ass little frustrating ;).
Here I'll post a step by step guide on how to install this plugin from scratch.

First of all, you will need a copy of Vim compiled with ruby support (+ruby) which ins't the case of the default version that you get from the official site.
While you can compile Vim by yourself, you can also download an already compiled version from here (ruby 2.0)
Once your download completes, extract vim.exe and gvim.exe and copy them into “C:\Program Files (x86)\Vim\Vim74”

Now, got to your command prompt and run: vim –version. Among a bunch of stuff, you should see +ruby.

In addition to the modified version of Vim, you will also have to install ruby 2.0. If you haven't already, go to and download de x86 version of Ruby 2.0 and the according RubyDevKit. (It' s super important that you get the x86 version. I shoot myself on the foot a bunch of times with the x64 version).

Just to make sure we are good so far, open vim and (at the Vim command promp) type :ruby puts RUBY_VERSION. If everything went OK, you should see: 2.0.0.

At this point we are good to go. We have Vim compiled with ruby support and the right version of Ruby installed on our system.

To install the actual plugin, I recommend to use pathogen ( ) but you can get it by other means too. Using this package manager, you just need to clone the plugin's github repo into /vimfiles/bundle. In the case of Command-T, you will also have to build a native extension. To do so, go to Command-T's home directory and run: rake make.

If at this point you got an error, you probably forgot to init/install RubyDevKit. Just go to DevKit's installation path, and run: dk init, dk install. And then run: devkitvars.bat (this will enhance your path so you can build native extensions). Now back to command-t's installation path and again, run: rake make. This time it should succeed;

Open a fresh instance of the terminal, then open vim and at the vim's command prompt type Command-T and hit [Enter]. If everything went ok, you should see a list of files/directories that you can filter and navigate right from the editor. (By default, command-t it's bound to the <leader> + t shortcut).

Install this plugin on Windows systems is a bit of a hassle, but it well worth it. I can't imagine myself using Vim without Command-T.

If you have any trouble installing Command-T, feel free to contact me, I'll try to help.

Oneway ticket from Visual Studio to Vim

Not so while ago If you had asked: Would you ever leave Visual Studio (+ReSharper and tools)?. The answer would be: “Hell No!, Why on earth I'll leave the most powerful IDE ever built?!

But as the time goes by, I've changed my mind...
Lately I been working on Mac, Linux and Windows, doing .NET, JavaScript, TypeScript, Ruby, HTML, CSS, some SQL and batch/shell scripts. Having and editor that works (almost) the same way in all of these platforms is a big win for me. Not to mention that I can code in any language I want with out switching editors.

Here is a short a short list features that made me change my mind.
* Cross platform support. (Big one).
* Lightweight. (When in the road, your battery will last longer).
* Fast as hell. You won't be waiting for minutes to open solutions.
* You can code in any language you want.
* Tiny footprint. You don't need 8 GB of disk's space just to install the tool.
* Already installed on most Unix systems.

Ok, that sounds good. But which features will you miss if you decide to give Vim a try?
Well, that heavily depends on your workflow, but based on fellow developers, I'll say:
* Built in Debugger.
* Smart refactors (a huge one for me too).
* Intellisense.
* Drag and Drop stuff around.
* There is no easy way to work with project and solutions files.
* Being able to use the mouse (really?!).

In general, I do TDD, so the builtin debugger it's not an issue to me. I always say that been in debug land is huge waste of time (almost as bad as being at meetings with project managers ;))
With regards to intellisense, you can use ctags to get some sort of intellisense (statement completion, quite frankly). It's not perfect, but it's good enough to get work done.
As far as refactors goes, I not gonna lie. Move code around without resharper is a bit of a pain in the ass; but as you will be working with a plain text editor, believe me, your code will be simpler and hence it won't be “that” hard to move around.

Note: I do know about omnisharp and I'm aware that it can provide almost the same Visual Studio's experience, but compared to plain old Vim, omnisharp is as slow as a dog. Not to mention you have to run a web server just to get intellisense. That sounds crazy to me.

Essential Vim plugins:
* CommandT. Resharper's Ctrl+N (kinda).
* MRU. Most recently used files.
* NERDTree. Directory/File explorer.
* Airline. Lightweight status line.
* Vim-CSharp. Better support for C# projects.
* SupertTab . Tab completion in insert mode.
* Snipmate. Vim's code snippets.
* Tcomment. Adds shortcuts to comment / uncomment code.
* Vim-Multiple Cursors. Simliar to Sublime Multiple Cursors.

External tools that will make your life easier:
* Exuberant Ctags.
* Git.

And last but not least, I haven't to be an all-in bet. Installing VsVim is a nice way to get a taste of Vim with out leaving your comfort zone. You wouldn't be able to use plugins, but I'll be good enough to get a taste of the powerful Vi motions and edit modes.

Command-T on Windows. Vim error E370.

In this short post I'll show you how to troubleshoot the error:

E370: Could not load library msvctr-ruby200.dll

If you had install Commant-T on Windows (the right way) and are seeing the afore mention error, chances are you had installed the x64 version of Ruby 2.0 and Ruby Dev Kit. I had made the same mistake (several times!), so no worries, you are just an easy fix away from fixit. Just uninstall the x64 version and install the x86 one of both, Ruby and RubyDevKit.
Once you had installed the right version (platform wise), open vim and run:
:ruby puts RUBY_VERSION.
You shouldn't get any errors any everything should work as expected.

Safety checks:
* Verify the contents of C:\ruby200\bin (in there you should see msvctr-ruby200.dll).
* Close all instances of cmd and run Vim from a fresh new one.

If you have any question, ping me; I'll be glad to help.

Monday, July 20, 2015

TDD on .NET without Visual Studio

I've been long time user of the NUnit framework (I mean for ages) and I was quite happy with the overall experience. Good performance, lots of tests runners, great integration with Visual Studio, reasonable documentation, the list goes on and on... But lately I've been working mostly on mac and/or linux, and on that space, the experience wasn't that great.

I still advocate for TDD (and any kind of automated tests for that matter) but I have to admit that doing TDD with NUnit outside Visual Studio (and without ReSharper support) was quite tedious. While NUnit comes with a console runner, I guess it's there just for CI Servers and not for developers to use. I mean you can use it, but the output is xml... and ... should I say more? ;)

So with that problem at hand, I decided to write Contest, a small library that allows me to do TDD on .NET with just an editor and a console. Basic feature set but capable enough to get stuff done. And of course, easy to use from de console.

Sounds interesting? Then take a look at Contest Github page

As usual, feedback is welcomed and thanks for reading!