Configuring Apache Thrift for Visual Studio 2012


Yes, it’s true: you can run and compile Apache Thrift servers and clients in Visual Studio 2012! Here’s a set of steps for compiling Apache Thrift under Visual Studio 2012 and then running a C++ Server and Client pair. I’ve also included steps to build a Java client which interacts with the C++ server, to demonstrate Thrift’s cross-language capabilities.

The current version of Thrift was 0.9.1 at the time of writing.


Build Apache Thrift libraries for VS2012

  1. Prerequisite: Download and build the Boost libraries for VS2012: see Configuring C++ Boost Libraries for Visual Studio. Note your {boost_install_dir} for later.
  2. Download Apache Thrift AND the Thrift compiler for Windows from
  3. Download libevent, a C++ dependency for the non-blocking Thrift Server:
  4. Extract both tar.gz files once downloaded.
  5. Navigate to {thrift_install_dir}\lib\cpp and open thrift.sln with VS2012
  6. If a dialog box appears that asks to upgrade some files to VS2012, click Upgrade
  7. Open the Visual Studio 2012 Command Prompt at Start->All Programs->Microsoft Visual Studio 2012 ->Visual Studio Tools -> Visual Studio Command Prompt (2012)
  8. In the VS2012 CMD Prompt, cd into the unzipped libevent directory. You should see subdirectories like “compat”, “include”, and “test” if it is the correct directory.
  9. Run this command in the CMD prompt to build libevent for VS2012: nmake -f Makefile.nmake
  10. Note your {libevent_install_dir}.
  11. Once the command has finished, go back to VS2012 (thrift.sln), right-click libthrift’s Project Properties, and navigate to C/C++->General.
  12. Enter this information into the Additional Include Directories line:
  13. Right-click libthriftnb’s Project Properties, and navigate to C/C++->General.
  14. Enter this information into the Additional Include Directories line:
  15. Counter-intuitive, but necessary: Remove BoostThreadFactory.cpp from the libthrift project. This file causes compilation issues and must be removed in order to continue.
  16. Trigger a Rebuild of both projects, and note the directory where libthrift.lib and libthriftnb.lib are created. This will depend on your configuration for Debug or Release.

Build your Thrift Server and Client

This section will guide you through the Apache Thrift tutorial for C++ in VS2012, found at

Building and Running the C++ Thrift server

  1. Download the tutorial.thrift and shared.thrift files from Apache:
  2. Run these two Thrift compiler commands to generate C++ for both of these service definition files:
    • thrift -r --gen cpp tutorial.thrift
    • thrift -r --gen cpp shared.thrift
  3. This will generate a gen-cpp directory in the same directory that thrift.exe was run from.
  4. Copy this gen-cpp folder into a Visual Studio Project, and separate the header and source files into the appropriate folders.

    All of the gen-cpp files imported into a VC++ project.

    All of the gen-cpp files imported into a VC++ project.

  5. Next, we must fix some convenient gotchas to bring the tutorial to life.
  6. Right-click your project in the Solution Explorer and go to Properties, then C/C++->All Options, and set Additional Include Directories to:
  7. Then, go to Linker->All Options, and set Additional Dependencies to:

    Note: the version numbers for these libraries may differ if you’ve built a different version of Boost.

  8. Click on Linker->All Options, and set Additional Library Directories to:

    The second item in the path could end with \Release, if you used the Release configuration instead of Debug while compiling Thrift.

  9. Double-click Calculator_server.skeleton.cpp. We need to adjust the main() method for the Server.
  10. Place this code at the top of the int main(int argc, char **argv) method:
      	WSADATA wsaData = {};
        WORD wVersionRequested = MAKEWORD(2, 2);
        int err = WSAStartup(wVersionRequested, &wsaData);
  11. Trigger a rebuild. If all goes well, then your project should compile without a hitch, and then you should be able to Run the project and see your C++ Thrift server starting up!


Building and running the C++ Thrift client

  1. Create another VS2012 project for the Thrift C++ client.
  2. Download the CppClient.cpp file and copy its contents to a new Source file in your new Client project:;a=blob;f=tutorial/cpp/CppClient.cpp;hb=HEAD
  3. Copy the gen-cpp folder from the Server application into your Client project, and add all of the files to the project. You need two separate copies of these files, or there will be two int main() functions defined in both your server and client, which is not fun to resolve.
  4. Erase or remove the files Calculator_server.skeleton.cpp and SharedService_server.skeleton.cpp from your project.
  5. Right-click your project in the Solution Explorer and go to Properties, then C/C++->All Options, and set Additional Include Directories to:
  6. Then, go to Linker->All Options, and set Additional Dependencies to:

     Note: the version numbers for these libraries may differ if you’ve built a different version of Boost.

  7. Then, go to Linker->All Options, and set Additional Library Directories to:

    The second item in the path could end with \Release, if you used the Release configuration instead of Debug while compiling Thrift.

  8. Trigger a rebuild. If all is well, it should succeed.
  9. Ensure that your Server is running, and run your Client. Thrift lives!
Eureka! The Thrift server accepts commands and responds to them.

Eureka! The Thrift server accepts commands and responds to them.

Addendum: Building and Running a Java Client for your C++ Service

Let’s explore the cross-language power of Thrift by creating a Java client which can talk to the C++ service.

Create Thrift files, and import them into Eclipse

  1. Create a new Java Project in Eclipse.
  2. Run these two Thrift compiler commands to generate Java code for both of these service definition files:
    • thrift -r --gen java tutorial.thrift
    • thrift -r --gen java shared.thrift
  3. This will create a gen-java folder wherever thrift.exe is located. Import all of these files into your Java Project, and sort them into the correct packages: some files will go into a package named ‘tutorial’ and others will go into a package named ‘shared’.
  4. Create a Java file named, and paste the contents of the sample into it;a=blob_plain;f=tutorial/java/src/;hb=HEAD
  5. So many red marks! Let’s work on fixing those…


Build all Java libraries and compile the client

Thrift has two dependencies in Java: ant and slf4j.

  1. Download the latest Apache Ant binary from here:
  2. Download the latest SLF4J binary from here:
  3. Unzip both downloads and note their locations.
  4. We won’t be able to build Ant files until we configure Ant correctly.
    Follow Steps 1-5 here:
  5. Next, download and unzip this maven-ant-tasks library, which we will need for the Thrift compilation:
  6. Copy the unzipped maven-ant-tasks-2.1.3.jar into {ant_install_directory}\lib
  7. Time to build Thrift’s Java library.
  8. Navigate to {thrift_install_dir}\lib\java
  9. Open a Command Prompt, and type ant
    If you’ve set up Ant and the maven-ant-tasks JAR correctly, you will see BUILD SUCCEEDED
  10. Copy the path for the newly-built Thrift Java library, located at “{thrift_install_dir}\lib\java\build\libthrift-0.9.1.jar”
  11. In Eclipse, right-click your project’s JRE System Library in the project explorer, and choose Build Path->Configure Build Path
  12. Click on the Libraries tab and Add External JAR, then add the Thrift Java library.
  13. Finish up by adding the SLF4J dependency to Eclipse.
  14. In Eclipse, right-click your project’s *JRE System Library in the project explorer, and choose Build Path->Configure Build Path
  15. Click on the Libraries tab and Add External JAR, then add the SLF4J jar, located at “{slf4j_install_directory}\slf4j-api-1.7.7.jar”
  16. Ensure that your Thrift server is up, and run your Java project as a Java Application through Eclipse. It works!
  17. If the program exits with a message like “Please enter ‘simple’ or ‘secure'”, then you are missing a program argument. Right-click your project, click Run->Run Configurations, and click on the Arguments tab. Add the word simple or secure to the Program Arguments dialog box, then click Run.


Related Links

  1. The Apache/Facebook developers were very Thrifty with their documentation, and produced a one-page tutorial:
  2. A blog post with instructions for Visual Studio 2010 can be found here:

Configuring C++ Boost Libraries for Visual Studio


Here is a basic guide to getting C++ Boost libraries to work within Visual Studio.

More information about these handy libraries is available here:




Download the Boost libraries

  1.  Determine the version of Visual Studio that you will be using for your project. For example, Visual Studio C++ 2012 is also known as version 11. You can find this out by clicking HELP > About Visual Studio and looking for the “Version ##” line on the screen.
  2. Determine whether you will be building a 32-bit or 64-bit version of the Boost libraries.
  3. Now that you have determined these two pieces of information, navigate to, click on the folder for the latest version, and download the correct .exe installer for your Visual Studio version and architecture.
  4. Once the download is finished, run the installer as normal and note the installation directory.

Build the libraries for your machine

  1. Open the Developer Command Prompt for VS20xx under Start > Microsoft Visual Studio 20xx > Visual Studio Tools


    The location of the Developer Command Prompt for VS2012.

  2. Once the Developer Command Prompt is open, type in cd <your Boost install directory>
  3. Next, type these commands to build the Boost libraries for your machine: bootstrap and then b2. This last command will run for about ten minutes, so take a break!
  4. Once b2 has finished, you should see it print two lines noting “compiler include paths” and “linker library paths”. Write these paths down or take a screenshot.

The Boost build has finished, and Boost tells us where to find the new libraries.

Link the libraries through Visual Studio

  1. Open your C++ project in Visual Studio 20xx. Right click its name in the Solution Explorer and go to Properties.
  2. Click on Configuration Properties, then C/C++, and then All Options.
  3. Modify Additional Include Directories: append the “compiler include paths” string to the end of it.
  4. Click on Configuration Properties, then Linker, and then All Options.
  5. Modify Additional Library Directories: append the “linker library paths” string to the end of it.
  6. Click OK to save your changes. Ensure that you are including the specific Boost libraries like this at the top of your source files: #include <boost/foreach.hpp>
  7. Try to Rebuild your project. Hopefully, all of your library issues will now be resolved! Happy coding!


Other Resources

Parts of this write-up were figured out through Boost’s Visual Studio page.

How-to: Set up Eclipse Subversive to work with Maven Projects

Last week, I configured Eclipse to check out Maven projects properly with the Subversive SVN plugin. This plugin will allow you to directly check in/out Maven code from your SVN into Eclipse, which will save you a lot of time.

Setting up Plugins

Here are nine steps for setting everything up properly. Note that if you simply want to install Subversive and do not care for the Maven integration, you can stop after Step 6:

  1. Open Eclipse and click Help > Eclipse Marketplace


    Help > Eclipse Marketplace menu

  2. Search the Marketplace for “Subversive” and choose to Install Subversive – SVN Team Provider 1.1.2
  3. Restart Eclipse once this installation has finished.
  4. When Eclipse starts again, install the SVN connectors for Subversive. Go to Help > Install New Software and enter into the “Work with:” field
  5. Place a checkmark next to: Subversive SVN Connectors.  Feel free to install any other connectors you may need as well.
  6. Click Finish to install the SVN connector. This may require another restart of Eclipse.
  7. Next, install the Maven2Eclipse plugin: click Help > Eclipse Marketplace and search for Maven2Eclipse then install it, following steps 2 and 3 above for that plugin.
  8. Finally, install Subversive Maven Integration. Go to Help > Install New Software again and enter into the “Work with:” field
  9. Place a checkmark next to Subversive Integration for the M2Eclipse Project and click Finish to install it.

Checking out Maven Projects

Once you have all of this set up, you will be able to check code directly in and out of your SVN from within Eclipse, which is much more convenient than copying projects into Eclipse manually.

Click on Window > Open Perspective > Other > SVN Repository Exploring


Eclipse’s Open Perspective dialog.

There, you can right-click the Repositories window and add the web address for your SVN.
Checking out a project is easy – right click any SVN folder to Check Out as Maven Project and specify which pom.xml file to use.

This should save you a significant amount of time once you have configured it correctly! Happy coding!

Computer Graphics: Audiosurf

Audiosurf is a music and rhythm-based videogame which was first released for the personal computer in February 2008 by an independent videogame developer. In Audiosurf, the player selects a music track from their hard-drive and is able to “ride” that track in a virtual rollercoaster while accumulating points for matching similarly-colored tiles that appear on the track. At its core, Audiosurf combines the main idea of Bejeweled’s colored-tile matching-and-scoring system with the popularity and frenetic gameplay of music games like Dance Dance Revolution. Because the user chooses his or her own music track to load, Audiosurf becomes either a relaxing or a challenging experience, and the rollercoaster track’s shading and color styles take on the tempo and frequency of the chosen piece of music. The graphical style of Audiosurf is most reminiscent of a cross between the Tron movies and a 1970s neon disco. In order to achieve this look at a quick framerate, the designers of Audiosurf used tasteful amounts of bloom and a custom programmable shader, both of which were implemented via the Quest3D engine.

The main screen of Audiosurf. The player's green vehicle navigates a rollercoaster-like track while the player tries to match similarly-colored blocks for points.

Audiosurf uses the Quest3D engine to render and shade its three-dimensional graphics and particle systems. This engine is advertised by its creators as a premier “visual method for software engineering graphical applications.” One of the hallmarks of this engine is the ability to assemble an entire graphics application by creating a tree-like data structure (see Picture 2 below). In the Quest3D development workflow, individual nodes of varying function are added one-by-one onto a tree structure that represents the graphics application; meanwhile, inheritance is maintained between parent and child nodes to confer properties and types. This approach is also known as a scene graph algorithm. The Quest3D engine implements several types of control flow nodes which enable additional complexity within the finished application. Application designers can dynamically determine the contents of the screen by placing layers of logical if-then-else nodes within their Quest3D programs. By defining this functionality, the Quest3D engine enables a straightforward way to implement any graphical application as a finite state machine. With this paradigm in mind, the application designer maps out his or her entire application with just the tools available in the engine. These engine tools include a combination of logical nodes and several types of presentation and graphical nodes in addition to the Lua scripting language for more complex logical and entity interactions.

On the left, a sample Quest3D program; on the right, the resulting scene from this program.

Shading in Quest3D is specified via HLSL – the High-Level Shading Language – which is the Microsoft Direct3D equivalent of GLSL (GL Shading Language). Both of these shading languages allow application developers to specify the programming of per-pixel shading, which allows much more precise pixel-based control of shading techniques. The Quest3D library accommodates HLSL as a specific drag-and-drop node type, thereby making it straightforward and efficient to interact directly with Direct3D for programmable shading techniques. Quest3D specifies that each HLSL file should contain both a vertex shader and a pixel shader, though it will only use a shader type if one has been defined. According to the Quest3D documentation, the engine will invoke default shading if a non-functioning HLSL file causes an error or fails to work properly.

Thanks to the Quest3D engine, Audiosurf is able to utilize several prominent graphical techniques in its presentation, including an interesting quantity of bloom and the effective use of particle systems to highlight events in the game. The Quest3D engine streamlines the application of both techniques within a graphical scene. Bloom is a post-processing graphical technique which aims to simulate the appearance of a bright light by leaking the color and intensity of the light outside of its bounds in a blurry sort of haze. Bloom can clearly be seen in Illustration 1 along the interiors of the red blocks on the screen. In Quest3D, post-processing effects can be specified as an HLSL-based FX file, which the engine will apply after the three-dimensional transformations have occurred and the view image has been rasterized. Bloom is used to highlight the player character as well as the outlines of the rollercoaster track and the bricks in Audiosurf. Particle systems are also used widely within the game: Illustration 3 below shows an example of the yellowish stars and sparks which appear at the top of the screen whenever a certain amount of points is awarded. Quest3D allows for the creation of particle systems via the Emitter node type. The Emitter is programmed to release a certain type of two-dimensional or three-dimensional object for a specified duration and lifetime; in Audiosurf, these objects are short-lived and serve only to announce an event and then disappear. The stylistic “explosion” of particles which occurs with each significant point gain spices up the game and makes it more exciting to experience.

Particle systems in use. Stars fly whenever a significant point value is awarded.

Audiosurf has fared quite well as a unique genre-crossing block-matching music game. This success has much to do with the game’s unique sense of style and its consistently smooth framerate. The Quest3D engine has evolved in parallel with games like Audiosurf to include more support for shading languages like HLSL and post-processing effects like bloom – both of which are used by Audiosurf for specific events in the game. Audiosurf’s developers combined the ease of the Quest3D engine’s graphical design method with highly-specific pixel-based programmable shaders and excellent gameplay to create a game that is both fun to play and fun to watch.

Application Survey 2 – Adil Bukhari – Audiosurf

Resources Cited

Audiosurf.” Giant Bomb. Giant Bomb, 18 002 2008. Web. 25 Nov 2011. <>.

“Audiosurf.” Wikipedia. Wikipedia, 24 011 2011. Web. 25 Nov 2011. <>.

 “Chapter 2.10:Particle systems – Quest3D.” Quest3D. Act-3D, n.d. Web. 25 Nov 2011. <>.

 Gallant, Matthew. “Bloom Disasters.” The Quixotic Engineer. The Quixotic Engineer, 18 006 2008. Web. 25 Nov 2011. <>.

“HLSLObject – Quest3D.” Quest3D. Act-3D, n.d. Web. 25 Nov 2011. <>.

 “Quest3D About.” Quest3D. Act-3D, n.d. Web. 25 Nov 2011. <>.

“Road To The IGF: Audiosurf Making Waves With Music .” Gamasutra. Gama Sutra, 11 012 2007. Web. 25 Nov 2011. <>.

“Tutorials/Manual/Chapter 1.5 – The Quest3D User Interface.” Quest3D. Act-3D, n.d. Web. 25 Nov 2011. <>.

iMacros Firefox Add-on: Download all Tagged Facebook Photos

(This script works as of December 17th, 2011. It will probably stop working as Facebook updates to the Timeline…)

I downloaded iMacros this morning. It’s a Firefox add-on that lets me automate any task on the browser. With the built-in macro recorder, I can instruct iMacros to download files, click specific links/images, and even fill out web forms. One of the things iMacros can’t do, however, is press some keyboard keys: It can enter text into forms and submit them, but it does not support arrow keys and modifiers (like the ALT key).

You can get iMacros here: – it’s free, but tech-supported versions cost some money.

As soon as I had iMacros downloaded, I decided to automate download of all my Facebook tagged photos. It was actually pretty straightforward:

  1. First, click a tagged photo of yourself. The URL in your address bar will look like this:
  2. Modify the URL by taking off the ending “&theater” part of it: – this will take us to the simpler photo interface.
  3. Run the iMacros script below after you’ve downloaded and installed the add-on from the link above. Make sure your active tab is pointing at the URL in Step 2.
ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES
ONDOWNLOAD FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}} WAIT=YES

This script will look for the “Download” button, click it, save your photo, and then click the “Next” button.

You can set iMacros to run this in a loop and get all of your photos at once!

TEDxGWU: Notes!

Some months ago, I attended TEDxGWU, a TED event which was independently organized by George Washington University students. The event featured six speakers – each of which gave very deep presentations about their fields and expertise.

TEDxGWU stage

The stage at TEDxGWU.

I took some notes on each of the speakers and wanted to share them. 

Yousef Hijji- Innovation and Inspiration

 (Potable water is an important necessity; we can be inspired to create solutions by observing nature itself)

 This presentation was all about the importance of a steady water supply for the world. After all, the only difference between a forest and a desert is a steady supply of water. It is currently estimated that up to one-fifth of Earth’s population lacks convenient access to a source of potable water; this resource is an important economic driver for any region. How can we solve this problem? There is a beetle by the name of Stenocara gracilipes which harvests water from thin air. MIT Engineers have observed this phenomenon and have created a synthetic device to do the same ( – this could have great reach on many communities.

Ilana Preuss- The Economic Power of Great Places

 (People want to live in smaller communities; ‘great places’ are key drivers of the economy.)

 “Great Places” are locales which offer their citizens a sense of community and also the ability to perform everyday tasks without the use of a car. These Great Places are not only cheaper to create and maintain – they can be the key to an economic recovery because they foster small local businesses. Think Bethesda (in Maryland) or Arlington (in Virginia), both of which are centered around the creation of a ‘small town’ feel while offering proximity to mass transit and excellent career opportunities. The infrastructure for a Great Place is economical: the pipelines and roads inside of a city are easier to look after than equivalent infrastructure which is outside of a town. Research has shown that people will accept a smaller home if they can live within such a Great Place – all because of the sense of community. 


Paul Tschudi- The Yellow Hooch

(Do good regardless of what everyone else thinks.)

Paul told us a story about his time serving as a Medic during the Vietnam War. The story was moving and I wish I’d taken a video of his telling. Paul and his hooch-mates in Vietnam colored their hooch (barracks) yellow and used it as a retreat from the pain and suffering of war around them. This place was an important area in Paul’s army camp because it helped people recover from the grimness – even temporarily. As Paul told it, he lost his soul in Vietnam because of all the brutality; after several jobs, numerous travels, and extensive humanitarian efforts back in the United States, Paul’s soul came back to him. The message: “Do good regardless of what others think.” He finished with this poem:

Lori Bell- Get Ready – The World is Waiting

(Every child deserves and needs a loving, peaceful childhood.)

 Lori told us a story about her childhood and how she had trouble letting go of some events in her earlier life. Her most significant message: every child deserves a loving, peaceful childhood. If you were robbed of that kind of childhood, mourn it, let go, and move on as she did. The world is waiting for you.

Murray Loew- Discovering Art through Science

(Using brain scan techniques to uncover new details about art masterpieces)

 What do PET scans and art recovery techniques have in common? Scientists are applying PET scans, spectrophotometry, and paint analysis to the science of art recovery and restoration. By viewing a piece of art in several different spectra (infrared, ultraviolet), scientists have been able to uncover hidden artwork and imperceptible differences within the artwork itself. Spectral analysis of Picasso’s Le Gourmet reveals an entirely separate painting that Picasso completed on the same canvas and then painted over. The rest of this presentation was complicated and talked about setting value registrations and determining paint origins via spectrophotometry. I’m sure chemistry people would have liked this one. 

Peter Bock- The Emergence of Creativity in Artificial Intelligence

(We can create an actual human-like artificial intelligence by 2035. But, should we?)

 This talk was my favorite one from the event. Peter Bock and his graduate student have created a program called ALISA which can imitate the painting style of any artist. Just train it on the artist’s corpus of work and give it a real image, and it can create a reasonable painting in the style of that artist. Current computers have the IQ of a shrew (but the shrew is still better at problem solving and defending itself!). Despite these isolated abilities, Peter estimates that we can create a lifelike human intelligence by 2035. Is it ethical to do so? That is the debate! Should we create a race of AI which is built to serve us? Will they realize their predicament and rise up against us? 


I thought this was a really cool event and would like to attend more TED talks in the future!

Saxon XML Parser: XSD Validation

Here’s how to get Saxon XML parser ( to perform XSD validation on an XML file of your choice in C#:

static void Main(string[] args)
            errors = new ArrayList();
            Saxon.Api.Processor proc = new Processor(true);

            //this is the property to set!

            SchemaManager schemaManager = proc.SchemaManager;

            FileStream xsdFs = new FileStream(@"C:\path\to.xsd", FileMode.Open);

            SchemaValidator schemaValidator = schemaManager.NewSchemaValidator();

            FileStream xmlFs = new FileStream(@"C:\path\to.xml", FileMode.Open);

            schemaValidator.ErrorList = errors;
        catch(net.sf.saxon.type.ValidationException e)
            foreach(StaticError error in errors)


        foreach (StaticError error in errors)

If you don’t set FeatureKeys.VALIDATION_WARNINGS, Saxonica will throw a ValidationException after catching the first validation warning.

Source: Taken from my answer on StackOverflow:

System.Net.Mail: “File is being used by another process.”

Problem: You’re using System.Net.Mail to send an email which has an attachment; you send the email with an attachment and then try to delete the file that you had attached to that email:

The process cannot access the file ‘[your attachment file]’ because it is being used by another process.

Potential Solution: Make sure to call MailMessage.Dispose() after sending the email. This will free all holds on the attachment file and allow you to delete it.

MailMessage mail = new MailMessage();

mail.From = new MailAddress("");
mail.Subject = "the email subject";
mail.Body = "the email body";

FileInfo attachment = new FileInfo("path/to/attachment.file");

attachmentItem = new Attachment(attachment);

SmtpClient smtp = new SmtpClient("",587);

smtp.EnableSsl = true;

smtp.Credentials = new System.Net.NetworkCredential("", "email_password");


mail.Dispose(); //<-- this did the trick!

if (attachment != null)

This bug took me an hour to sort out >_< . In general, step through your code slowly in order to find the root cause of a file lock.

C# Excel automation: creating a macro-enabled Excel spreadsheet via a C# Application

Just last week, I needed to write an application that could create an Excel spreadsheet and fill it with data automatically. I surveyed the possible solutions and eventually settled upon the Microsoft Excel Component Object Model (COM) library.

Below is a step-by-step example which 1. creates an Excel spreadsheet, 2. fills it with relevant data, 3. adds a VBA macro to the spreadsheet, and 4. saves the file so that others can edit it.

Another good example can be found here:

*Because my application needed a GUI, I created my project as a Windows Forms project. You can easily adapt this example to any other project type (including a Console Application) if needed.*

Before you begin, you will need to have a copy of Microsoft Office 2003 (or above) installed on your computer.

Create a new C# Windows Forms project in Visual Studio and give it a name. Then, add some References to your project:

Click on the COM tab and add: Microsoft Visual Basic for Applications Extensibility and Microsoft Excel Object Library

Adding the VBIDE library reference to the project.

Adding the VBIDE library reference to the project.

Adding the Excel COM library reference to the project.

Adding the Excel COM library reference to the project.

Here’s my project with the references (labeled as VBIDE and Microsoft.Office.Interop.Excel) added:

The project with the references added.

The project with the references added.

I wrote two utility methods to help with graphics: encloseCellWithBorder will enclose a range of cells with a single-line border and setInterior will set the interior color of a range of cells.

In order to allow Excel to create the macro, you will need to change some security settings in Microsoft Excel:

Here’s the code that goes within the Form1.cs file:

using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Configuration;
using VBIDE = Microsoft.Vbe.Interop;
using System.Runtime.InteropServices;

namespace ExcelApp
   public partial class Form1 : Form
      Excel.Application xlApp;
      Excel.Workbook xlWorkBook;
      Excel.Worksheet xlWorkSheet;
      int excelActiveRow;

      /// <summary>
      /// Sets border of cells from beginCell to endCell to a single-line width border all around.
      /// </summary>
      /// <param name="ws">The worksheet to modify cells in</param>
      /// <param name="beginCell">The cell to begin the border change at, e.g. "A1"</param>
      /// <param name="endCell">The cell to end the border change at, e.g. "C2"</param>
      private void encloseCellWithBorder(Excel.Worksheet ws, string beginCell, string endCell)
         Excel.Range oResizeRange = ws.get_Range(beginCell, endCell);
         oResizeRange.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
         oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;

      /// <summary>
      /// Sets color of cells from beginCell to endCell to the specified color.
      /// </summary>
      /// <param name="ws">The worksheet to modify cells in</param>
      /// <param name="beginCell">The cell to begin the color change at, e.g. "A1"</param>
      /// <param name="endCell">The cell to end the color change at, e.g. "C2"</param>
      /// <param name="color">The System.Drawing.Color color to give the cell interior</param>
      private void setInterior(Excel.Worksheet ws, string beginCell, string endCell, System.Drawing.Color color)
         Excel.Range oResizeRange = ws.get_Range(beginCell, endCell);
         oResizeRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(color);

      /// <summary>
      /// The "main" method of the GUI - creates an Excel spreadsheet, fills it with some data, attaches a macro, and saves the spreadsheet to the C:/ drive.
      /// </summary>
      private void button1_Click(object sender, EventArgs e)
         //the first row of the excel spreadsheet is row 1. We maintain the current active row of the spreadsheet as a variable for easy tracking.
         excelActiveRow = 1;

         //initialize the Excel application and make it invisible to the user.
         xlApp = new Excel.Application();
         //This is a must for lengthy spreadsheets - the Excel COM library does not like it if a user clicks around in the spreadsheet while it is being created.
         xlApp.UserControl = false;
         xlApp.Visible = false;

         //Create the Excel workbook and worksheet - and give the worksheet a name.
         xlWorkBook = (Excel.Workbook)(xlApp.Workbooks.Add(Missing.Value));
         xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
         xlWorkSheet.Name = "worksheet_name";

         /*insert some values into the Excel spreadsheet here.
         This code will create a spreadsheet like this:
         A       |        B        | C
         Value 1 | Another Value 1 | 4
         Value 2 | Another Value 2 | 2
                 |                 | 6

         //to insert a value into an Excel cell, use the .Cells[Row, column] property of the Excel.WorkSheet class.

         //first row: Value 1 | Another Value 1 | 4
         xlWorkSheet.Cells[excelActiveRow, 1] = "Value 1";
         //enclose the cell in column A with a single-line border.
         encloseCellWithBorder(xlWorkSheet, "A" + excelActiveRow, "A" + excelActiveRow);
         xlWorkSheet.Cells[excelActiveRow, 2] = "Another Value 1";
         xlWorkSheet.Cells[excelActiveRow, 3] = 4;
         excelActiveRow++; //advance to the next row.

         //second row: Value 2 | Another Value 2 | 2
         xlWorkSheet.Cells[excelActiveRow, 1] = "Value 2";
         //fill the cell in column A with red color.
         setInterior(xlWorkSheet,"A" + excelActiveRow,"A" + excelActiveRow, System.Drawing.Color.FromArgb(255, 0, 0));
         xlWorkSheet.Cells[excelActiveRow, 2] = "Another Value 2";
         xlWorkSheet.Cells[excelActiveRow, 3] = 2;
         excelActiveRow++; //advance to the next row.

         //third row:         |                 | 6
         //attach a formula to this cell: SUM(C1,C<excelActiveRow>-1)
         xlWorkSheet.get_Range("C" + excelActiveRow, "C" + excelActiveRow).Formula = "=SUM(C1:C" + (excelActiveRow-1)+")";

         //modify the font styling of the entire workbook to Calibri, size 10.
         xlWorkSheet.get_Range("A1", "B" + excelActiveRow).Font.Name = "Calibri";
         xlWorkSheet.get_Range("A1", "B" + excelActiveRow).Font.Size = "10";

         //add the macro to the excel workbook here.
         Microsoft.Vbe.Interop.VBComponent xlMod;
         xlMod = xlWorkBook.VBProject.VBComponents.Add(VBIDE.vbext_ComponentType.vbext_ct_StdModule);
         xlMod.Name = "Module1";

         /*place the VB macro code within a string first.
         Make sure that you maintain spacing levels for code that goes inside Subs.
         End each line with \r\n to tell VBA to start a new line.
         string macroCode = "Sub main()\r\n" +
         "   MsgBox \"Hello world\"\r\n" +
         "end Sub";


         //save the workbook to "C:\workbook.xlsm";
         string fullPath = "C:\\workbook.xlsm" ;

         {//save the workbook.
            xlWorkBook.SaveAs(fullPath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled,
            null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, null, null, null);
         catch (Exception ex)
            //release all memory - stop EXCEL.exe from hanging around.
            if (xlMod != null) { Marshal.ReleaseComObject(xlMod); }
            if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); }
            if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); }
            if (xlApp != null) { Marshal.ReleaseComObject(xlApp); }
            xlMod = null;
            xlWorkBook = null;
            xlWorkSheet = null;
            xlApp = null;


         //release all memory - stop EXCEL.exe from hanging around.
         if (xlMod != null) { Marshal.ReleaseComObject(xlMod); }
         if (xlWorkBook != null) { Marshal.ReleaseComObject(xlWorkBook); }
         if (xlWorkSheet != null) { Marshal.ReleaseComObject(xlWorkSheet); }
         if (xlApp != null) { Marshal.ReleaseComObject(xlApp); }
         xlMod = null;
         xlWorkBook = null;
         xlWorkSheet = null;
         xlApp = null;

The finished Excel spreadsheet and attached macro.

The finished Excel spreadsheet and attached macro.

So there you have it! This code will create and save a macro-enabled spreadsheet to the C:/ drive. This solution worked well for my application!

Don’t forget to change your security settings for Excel:

I’ve attached the code for Form1.cs as a PDF: Form1