Sunday, September 20, 2015

Using Assembly in Visual Studio 2013


In this blog post I'm going to demonstrate how to create an assembly language subroutine and call it from a C++ program.

Assembly Language

It's been a few years since I've created any assembly language.  In fact, the last time I wrote a real assembly language program the tool to use was Borland's Turbo Assembler in DOS.  Those were the good ol' days.  

So I was browsing the web looking for a subject to blog about and I stumbled across this article about writing assembly in Visual Studio.  The web page is old (i.e. Visual Studio 2003 days) and it was setup for a computer science class at the University of Virginia.  They probably forgot that the page exists and I'm betting that it doesn't connect to their website.  Google didn't forget.  So here's the link: Guide to Using Assembly in Visual Studio .NET.

I ran into a couple of issues with the instructions.  First,  $(InputPath) has been deprecated.  It's now $(ProjectPath) and $(InputName) has been depricated and has been replaced by $(ProjectName).  Even with these changes the build does not work.  So I coded the name of the file since it is attached to the property of that file.

Here's what my settings look like:


Assembly File Setup

Here are the step-by-step instructions for setting up an asm file in your c++ program.

Step 1: Create a C++ Project

I'm using Visual Studio 2013 in this example.  Go to File -> New -> Project.  Then you'll need to go to "Other Languages" and open the "Visual C++" branch.  Click on the Win32 branch and click on "WIn32 Console Application":

 Give your project a name and click the "OK" button.

 Next, you'll have to right-click on the source files directory and create a new CPP file (add -> new item -> C++ File), name it "main.cpp".

Now paste this main program in the main.cpp file:

extern "C" {
    void clear();

int main(int argc, char *argv[])
    return 1;

We're going to create an assembly program with a function named "clear", which explains the "extern" directive.  You can name your functions anything you like, but you'll need to change the extern directive to match.

Step 2: Add Assembly Code

Right-click on the source files folder again and add a text file (you can add another cpp file and just change the filename).  Name the file factorial.asm.

Copy and paste this assembly code from the University of Virginia example that clears the EAX and EBX registers:

.586              ;Target processor.  Use instructions for Pentium class machines
.MODEL FLAT, C    ;Use the flat memory model. Use C calling conventions
.STACK            ;Define a stack segment of 1KB (Not required for this example)
.DATA             ;Create a near data segment.  Local variables are declared after
                  ;this directive (Not required for this example)
.CODE             ;Indicates the start of a code segment.

clear PROC
   xor eax, eax
   xor ebx, ebx
clear ENDP

Step 3: Setup Custom Build Commands

Right-click on your asm file and select "properties".  You'll see a Configuration Properties setup.  Change the Item Type to "Custom Build Tool" and Content to "Yes":

You'll see a new tree branch created on the left side of the window that has a "Custom Build Tool" branch.  Once that appears, you can click on it to enter your build parameters:

You can copy this line and paste it into the Command Line of your window:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\ml" /c /Cx /coff factorial.asm

That assumes that you installed Visual Studio 2013 with the default install settings.  Make sure you set your "Outputs" to "factorial.obj" because that will be the name of the file that hte linker expects.  Also, change "Link Objects" to "Yes".  Apply your changes.

Now you should be able to build and run your application.


As the University of Virginia article mentions, troubleshooting requires you to put a breakpoint on the clear(); command in the c++ main file.  Then run your program to that point.  Next open the disassembly window (Debug -> Windows -> Disassembly).  

To see the CPU registers, you'll need to open the Registers window (Debug -> WIndows -> Registers).

I shrunk the width of the registers window to force the registers to wrap vertically.  When you're viewing the disassembly window you can use F11 to step into your assembly function and F10 to step through each assembly instruction.  Your Registers window will show changes to the CPU registers by turning them red:

Also, you can right-click inside the Registers window to add MMX registers and other data points.

You can also right-click on the disassembly window and show line numbers.  This will show the line numbers that occur in the C++ program itself.

Here's the actual assembly program which clears the EAX and EBX by Xoring each register with itself, followed by a return:


Intel has an introduction to x64 assembly language, click here.

For the assembly language reference, click here.

University of Virginia currently has a good intro for x86 assembly, click here.


Saturday, September 19, 2015

Lazy Loading Data


In this blog post I'm going to demonstrate how to lazy load your data using Entity Framework and SQL Server.  The purpose is to write an object that returns program settings stored in a table, but read from the table only once during the lifetime of the program.

The Data

In a database named "sampledata" I'm going to create a table that contains true/false settings for any number of settings.  This is a simple example for the purposes of showing how to lazy load.  So I will be "pretending" that there is a purpose for these settings even though the demo program doesn't use any of it.

You can use the following SQL script to generate a table to run this program:

CREATE TABLE [dbo].[ProgramSetting](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NOT NULL,
    [Setting] [bit] NOT NULL,
    [Id] ASC

INSERT INTO ProgramSetting (Name,Setting) values ('RequirePassword',1)
INSERT INTO ProgramSetting (Name,Setting) values ('ShowUserName',0)
INSERT INTO ProgramSetting (Name,Setting) values ('ShowUserPicture',0)
INSERT INTO ProgramSetting (Name,Setting) values ('AllowUserToChangePicture',1)

The Class
Now, I'm going to design an object that will be used throughout a program to read settings from the database and return the true/false value.  Here's the basic class:

public class ConfigurationSettings
    private static List<string> _Data = null;
    private static List<string> Data
            if (_Data == null)
                using (var db = new ConfigDataContext())
                    _Data = (from ps in db.ProgramSettings
                             where ps.Setting
                             select ps.Name).ToList();
            return _Data;

    public static bool RequirePassword
            return Data.Contains("RequirePassword");

    public static bool ShowUserName
            return Data.Contains("ShowUserName");

    public static bool ShowUserPicture
            return Data.Contains("ShowUserPicture");

    public static bool AllowUserToChangePicture
            return Data.Contains("AllowUserToChangePicture");

Now, if you look at the code carefully, you'll see that there is a property that gets the raw data using LINQ and Entity Framework.  You can download the sample code to see the code for the context and the table.  For this blog post all you need to know is that all the data from the ProgramSettings table is read at one time.  It will occur the first time a configuration parameter is read.  Why?  Because the Data.Contains() will call the Data getter which will then check to see if the local variable named _Data is null.  The first time a parameter is read, this will be null and the data will be red into _Data.  The next parameter that is read will cause the _Data to be returned without any read to the database.

The list that is maintained in the variable _Data is just a list of the names of configuration parameters that returned true.  If the parameter is missing or they are false, then we'll return a false to the calling program.  This can be convenient for new features that can be added to the code first.  They'll be false until you put parameters in the database and you won't be stuck with a chicken or the egg problem of when to insert the data into the ProgramSetting table.

Obviously, this works for data that is mostly static.  If you include this code in a stand-alone program and you change a configuration setting in your database, you'll need to exit from any previously running programs before the changes will take affect.

Another possible problem involves the fact that your configuration parameter names are coded as well as stored in the database.  That means that changing a name in the database, adding a name or deleting a name requires some matching code changes.  This can get tedious if the list of configuration parameters is large.  You could write a program to generate the parameters and just regenerate the parameter list every time you make changes to the database and then update your software.  You can also opt to use some sort of read parameter method that requires the parameter name in a string passed in.  Most likely, you'll be making changes to your code if you're adding, deleting or modifying a configuration parameter, so it makes no real difference.

How to Get the Code

You can download the sample code at my GitHub account by clicking here.  Be sure to go to the context source file and change the database connection string to match your own SQL server.


Sunday, September 13, 2015

Mocking HttpContext


Anybody who has attempted writing unit tests for a website has run into the problem where you cannot mock the HttpContext object.  I usually write my code in such a way that I don't need to mock the context by using only connection code to go between the website controller and the actual business logic.  In this blog post, I'm going to show how to mock up parts of the HttpContext so you can test things like headers, cookies and server variables.  From this, you should be able to extend the features to mock up any other part of the context.

The Problem

The HttpContext has been called the largest object on the planet.  Unfortunately, HttpContext is difficult to mock and an object called HttpContextBase (inside System.Web) was added to allow developers to mock the context.  In order to do this, you'll need to create a context factor that your application uses.  This factory will default to the HttpContext.Current when your program runs normally, but allow your unit tests to override with an HttpContextBase for testing purposes.  This also requires you to replace any references to HttpContext.Current with the new context factory object.

The Factory Object

The basic factory object looks like this:

public class HttpContextFactory
    private static HttpContextBase m_context;
    public static HttpContextBase Current
            if (m_context != null)
                return m_context;

            if (HttpContext.Current == null)
                throw new InvalidOperationException("HttpContext not available");

            return new HttpContextWrapper(HttpContext.Current);

    public static void SetCurrentContext(HttpContextBase context)
        m_context = context;

Now you refactor all your code to use HttpContextFactory.Current in place of HttpContext.Current.  Once this has been accomplished, then you can create unit tests that mock the context.  This factory object was obtained from stack overflow (click here).

The Mock Context Object

Next, we'll need a mock context object.  This will be used to contain variables that are pre-assigned to the context before a method is called.  Then the mock object can be asserted if the object under test changes any values (like setting a cookie).

Here's the mock object:

public class MockHttpContext
    public NameValueCollection ServerVariables = new NameValueCollection();
    public HttpCookieCollection Cookies = new HttpCookieCollection();
    public NameValueCollection HeaderVariables = new NameValueCollection();

    public HttpContextBase Context
            var httpRequest = new Moq.Mock<HttpRequestBase>();

            httpRequest.Setup(x => x.ServerVariables.Get(It.IsAny<string>()))
                .Returns<string>(x =>
                    return ServerVariables[x];

            httpRequest.SetupGet(x => x.Cookies).Returns(Cookies);

            httpRequest.Setup(x => x.Headers.Get(It.IsAny<string>()))
                .Returns<string>(x =>
                        return HeaderVariables[x];

            var httpContext = (new Moq.Mock<HttpContextBase>());
            httpContext.Setup(x => x.Request).Returns(httpRequest.Object);

            return httpContext.Object;

There are variables to contain cookies, header variables and server variables.  These can be set by a unit test before executing the method under test.  The values can also be read after the method has executed to verify expected changes.

Writing a Unit Test

 Here's a basic unit test with server variables:

public void httpcontext_server_variables()
    var tempContext = new MockHttpContext();
    tempContext.ServerVariables.Add("REMOTE_ADDR", "");
    tempContext.ServerVariables.Add("HTTP_USER_AGENT", "user agent string here");
    tempContext.ServerVariables.Add("HTTP_X_FORWARDED_FOR", "");


    //TODO: call http method
    //TODO: asserts


That's all there is to it.  Now you're probably wondering what's the point?  The reason for mocking the context is to get legacy code in a unit testing harness.  If your legacy code is already in C# and you are using web forms or MVC, then you can use this technique to unit test any methods called from your web application.  The process is to create a unit test with minimal changes to existing code.  Then perform your refactoring or rewriting of code while applying the same unit tests.  This will help ensure that you are following the original spec of the legacy code.

Where to Get the Code

You can download the sample code from my GitHub account by clicking here.  This code was built with Visual Studio 2012.

Entity Framework 6.1.3 vs. Linq2SQL vs. NHibernate Smackdown!


I've done these ad-hoc ORM performance tests in the past.  In this test I'm going to re-test the latest Entity Framework (version 6.1.3) against the latest Linq-to-SQL version.  I'll be using EF code-first this time to make sure there isn't any extra overhead.  I'll also be using Visual Studio 2013.

The Hardware and Software

This test was executed on an older PC with an Intel Core2 Duo CPU running at 3Ghz (E8400).  I'm using 8 Gigabytes of Ram and a solid-state hard drive.  This machine has Windows 10 (64 bit) and I'm using Visual Studio 2013 and Microsoft SQL Server 2014.

The Tests

I ran the tests 5 times each and chose the shortest time for each section (insert, update, delete and select).  I also added the NHibernate ORM just to make this a 3-way smack-down.  I performed the basic 4 CRUD operations (insert, update, select, delete) and compared results for each operation.

The Results

It appears that EF has been improved since the last time I've performed this test.  Entity Framework seems to be a bit faster than Linq-to-SQL this time.  However, NHibernate still outperforms both Entity Framework and Linq-to-SQL by a large margin (between 2x and almost 3x).

Here are the results:

Usual Disclaimer

I have to warn you that this experiment is unscientific.  I'm using a PC that I use for general purpose day-to-day operations.  What this means is that I have a virus checker and a backup program that can kick in at any time.  Not to mention the fact that I have automatic updates set to on.  To make this experiment more accurate, I would need to setup a stripped down PC and run comparison tests with no other programs running.  In other words, your results may vary.

So my advice is to download the source from this blog post, compile and run this test on your machine or the expected destination setup (i.e. against your company SQL server).  You can also increase the size of the data set to simulate your expected data volume.

Download the Code

You can go to my GitHub account by clicking here.  Download the zip file and unzip it to your visual studio project directory.  Don't forget to search the code for the connection string ("My Connection String") and replace with your own connection string.  This occurs in 3 files: SampleDataContext.cs, App.config and NHibernateSessionFactory.cs.