Always run Visual Studio as administrator on Windows 10

You might be working with a program that always require administrator privileges, such as a service listening on a port. Up to Windows 10, you just right clicked the devenv exe, and checked “always run as administrator” in the compatibility tab. But in Windows 10, the compatibility tab is missing for the Visual Studio exe. Why? No idea. But here’s how to fix it.

To just run the shortcut as admin : right click on the sortcut > in the “properties” tab, click “advanced”, then check “always run as administrator”. Simple, fast, easy.

If you want to run Visual Studio as administrator also when opening a .sln or .csproj file, it’s not so easy. Here are the logical, coherent, and easy to find steps to fix this: (labels translated to english from french, sorry if it doesn’t match)

  • Open the start menu, type “troubleshoot”, and open “check your computer state and solve problems”
  • On the bottom left, click “troubleshoot compatibility problems”
  • Click on “advanced” on the left then “run as administrator”
  • Click again on “advanced”, then uncheck “automatically fix”, then “next”
  • Search for Visual Studio in the list, then “next”
  • Make sure “fix the program” is checked, then “next”
  • Select “troubleshoot the program” (bottom option)
  • Check “the program requires additional rights”, then “next”
  • Click “test the programe” then “next”
  • Select “save the parameters for the program” then “close”

Easy, logical, simple. Thanks Microsoft!

Unit testing MongoDB queries

When writing unit tests, it’s common to stop at the database access layer.
You might have a “dumb” data access layer that just passes stored procedure names and parameters to the SQL database, for instance.
It’s usually very hard to test this layer, since it requires either that your build server has access to a SQL Server instance, or that a SQL Server is running on the build server.
Plus, we’re getting out of unit tests and are entering integration tests, here.

Using a more advanced tool like Entity Framework, in order to test your complex EF queries, there are usually methods to insert fake data into a fake container, like Test Doubles, InMemory, or Effort.

Using MongoDB, you might encounter the same problem : how do I test that my complex queries are working ?

Here for instance, I get the possible colors of a product; how do I know it works using unit tests?

MongoDB has an “inMemory” storage engine, but it’s reserved to the (paid) Enterprise edition. Fortunately, since 3.2, even the Community edition has a not-very-well-documented “ephemeralForTests” storage engine, which loads up an in-memory Mongo instance, and does not store anything on the hard drive (but has poor performances). Exactly what we need!

Before running the data access layer tests, we will need to fire up an in-memory instance of MongoDB.
This instance will be common to all the tests for the layer, otherwise the test runner will fire up new tests faster than the system releases resources (file and ports locks).

You will have to extract the MongoDB binaries in your sources repository somewhere, and copy them besides your binaries on build.

The following wrapper provides a “Query” method that allows us to access the Mongo instance through command-line, bypassing the data access layer, in order to insert test data or query insertion results.

We’re using the IClassFixture  interface of xUnit to fire up a MongoDaemon instance that will be common to all our tests using it.
It means we need to clean up previously inserted test data at each run.

There you have it: a kind-of-easy way to test your Mongo data access layer.

Modify copy/paste format depending on target

Sometimes you want to copy tabular data, and paste it differently depending on the target. For instance, you want CSV when you paste in your text editor, and HTML when you paste it in an email.

Fortunately, some nice fellow has created a helper class to handle all that for you. And it’s even available on GitHub!

To sum it up, the Clipboard  class has a SetDataObject method. A DataObject can get multiple contents (with different DataFormats) through multiple calls of the SetData(string, object)  method.
So basically, you should create a DataObject, then call SetData once with the HTML, and once with text. The trick is that the HTML needs special formatting to work.

Start a WPF application in the notification area with Caliburn.Micro

Sometimes you’re writing a quick utility app that you wish to start directly in the notification area (near the clock), and not display anything on startup.
It’s actually very simple using Caliburn.Micro.

You probably already have customized your application bootstrapper already. All you have to do is modify the OnStartup  method from DisplayRootViewFor<T>  to displaying a custom tooltip. Here I’m using the Hardcodet.NotifyIcon.Wpf Nuget package:

It seems obvious in retrospect, but it took me a while to find this, because I don’t modify the app bootstrapper often, so I forgot about this method.

Don’t forget to add behavior to this icon! Double-click, context menu…

I have created a Caliburn.Micro + MahApps template app if you wish a starting point : https://github.com/cosmo0/Caliburn.MahApps.Metro.Template

Mapping DataTables to domain objects

It’s always a pain to work with DataTables and DataSets. You’re always typing these pesky column names, it doesn’t necessarily represents the actual data model (if there are nested data), there is no type safety until runtime, it’s pretty hard to use Linq on your results… the list goes on.

Fortunately, there is a simple solution: AutoMapper. It’s very simple to cast a DataTable to a list of objects:

Mocking static methods

I’m working on a pretty old application with no unit tests whatsoever, and I’m trying to write some as I add features and fix bugs.

After successively finding out about MS Fakes, then that it’s only included in VS2012+ Premium/Ultimate and very hard to include in a continuous integration chain, I was pretty stumped until I found this, which works incredibly well.

Another option to transform the static method into a static Func or Action. For instance.

Original code:

You want to “mock” the Add method, but you can’t. Change the above code to this:

Existing client code doesn’t have to change (maybe recompile), but source stays the same.

Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:

Put whatever logic you want in the method, or just return some hard-coded value, depending on what you’re trying to do.

This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.

C, C++ and C++/CLI cheat sheet

No explanation of the basic concepts, just a memory help when you don’t use C/C++ frequently, or if you’re a beginner with some bases.

First question: why pointers? Answers: because functions arguments are passed by value in C and C++. Because arrays and strings are crazy in C.

How to read pointers

Here is a handy way of remembering how pointers syntax works.

In variable declaration

Go from the right to the left of the declaration, from the innermost parenthesis, going back to the right when hitting “)”

  • Read the name of the declaration
  • *  is “a pointer to”
  • []  is “an array of”
  • ()  is “a function returning”
  • Finally, read the type

int *p[]; reads “p is an array of pointers to int”.
int *(*foo())();  reads “foo is a function returning a pointer to a function returning a pointer to int”.

In variable usage

Variable usage reads from left to right.

  • Determine “get” (read variable) or “set” (write variable)
  • *  is “the value pointed to by”
  • &  is “the address of”
  • [i]  is “the element at position i”
  • Read the variable name

*p = 5;  reads “set the value pointed to by p”.
x = &i;  reads “get the address of i”.
printf("%i", *foo[0]);  reads “get the value pointed to by the element at position 0 of foo”.

C pointers

Manipulating a variable through a pointer is called dereferencing. It is used through an indirection expression.
Manipulating pointers through variables is called decaying.

Given an integer:

  • Create an pointer:
  • Get the memory location of the variable:
  • Get the value of the variable:
  • Set the value of the variable:
  • Setting a pointer to null allows to assign it to a variable later:

C arrays

Arrays mostly can’t be manipulated directly, but rather through pointers.
The variable array  is, for most intents and purposes, a pointer to the first element of the array (until it’s incremented).

Given an array of integers:

  • This doesn’t really creates an array. It creates 3 integers side-by-side, and stores the memory location of the first one.
  • array == &array == &array[0]
  • When you pass an array as an argument to a function, you really pass a pointer to the array’s first element, because the array decays to a pointer.
  • Incrementing a pointer to an array really moves the pointer to the next element of the array (the pointer is incremented by the size of the type of the pointer).
  • The subscript operator (the [] in array[0]) has nothing to do with arrays themselves, you can also use it on a pointer:

C structures

Given a structure:

  • Accessing members of the structure through the variable:
  • Accessing the members through a pointer:

C++ references

C++ is much less in love with pointers than C, and prefers using reference variables. They are mostly used in the same way as pointers, but their address can’t change (they always points to the same variable).
The main usage of a reference variable is for function parameters, to pass the variables by reference (by default it’s by value), which allows to not use pointers.

Given an integer:

  • Create a reference to a variable with  int &r = i; ; this is called binding a reference to an object
  • You do not need to dereference a reference to access the variable’s value:
  • To make sure the arguments are passed by reference in a method:
  • On the other hand, the same method using pointers must be passed the variables by reference in the call:

Managed instances

Instances of managed objects should be used through handles ( ^ , also called “hat”). It can be read “is a handle to the instance of the managed class”. Then, you use the handle as if it was the actual instance.

Note that, even though you don’t have to use managed objects in C++/CLI, you have to declare instances of managed objects with a handle.

Managed pointers

Because of garbage collection (which changes memory addresses), you can’t just use a regular C/C++ pointer to a managed objects. The managed pointers are called interior pointers. A good overview can be found here.

The syntax for interior pointers is very… declarative:

Native pointers are automatically converted to interior pointers (the inverse is not true):

As with pointers in C++, usage interior pointers is not recommended, and you should rather use managed references.

Managed references

A managed reference is called a tracking reference and uses  %  instead of & .

Managed pointers and references have some weirdness, for which this SO post goes into further details.

Further readings

C++/CLI wrapping a C library: cheatsheet

Because once in a while I write a C++/CLI wrapper around a C library, but since I do it so infrequently I forget everything each time. Here is a list of pointers (haha) for common pitfalls and problems.

Compiling and debugging

You have to wrap the .h into an #ifdef __cplusplus extern “C” :

You also need to remove the /clr option for C files.
Right click your C files > Properties > C/C++ > General > Common Language RunTime Support > No CLR Support.

In your managed class, to include an unmanaged C header, use managed(push|pop)

Because Linux and Windows get along so well, you may also have to redefine a few C methods in your header file.

If you wish to create a C# unit test project (using xUnit for instance), with Visual Studio 2012 and later, you will have to do a few things:

  • In the C++/CLI project’s properties, in Debugging, choose the Debugger Type “Mixed”
  • In the Visual Studio options, Debugging, check “Managed C++ Compatibility Mode” (in VS2012) / “Use Managed Compatibility Mode” (in VS2013).

To build using MSBuild, you may have to change the toolset to VS2012: project properties > General > Platform Toolset = Visual Studio 2012 (v110). And set the Configuration Type to Dynamic Library (.dll) while you’re at it.

Managed and unmanaged objects

gcnew instantiates a managed objects, which will be garbage collected. Always use it for the managed objects.

To easily call the native structures through managed classes, use the internal constructor and ToNative methods.

WPF Behaviors: adding mouse-event adorners

This is part 3 of the WPF drag & drop exploration. Part 2 can be found here.

Let’s recap what we have right now. We have a sample application that allow us to freely drag items across an area. Now, since there might be multiple items stacking on top of each other, we want the user to be sure which item will be moved. For that, we want to add a visual indication on the item. This kind of stuff is called an adorner in WPF.

Now, you will see many samples of code-driven adorners implementation. But we don’t want to break the MVVM pattern, and to do that, we want the adorner to be implemented in the view.

So we’ll create an Adorner that allows us to use a DataTemplate. For that, I’ll just copy some existing code :

We can now use this adorner in the behavior.

Now, we just need to create the adorner’s DataTemplate, and wire up the events. We just have to add an AdornerDecorator in the controls tree, otherwise the adorner may get a random behavior (it would be attached to the window), or not work at all.

Note that from the adorner’s DataTemplate, we set the DataContext property, so that we can bind the adorner’s properties directly to the ones of the item view model.

Now, on mouse-over, a black border will appear, and will disappear when the mouse leaves. There are a few problems with this method: most notably, the adorner flickers when the mouse stays over it. But we’ll try to tackle them later on.

WPF Behaviors: switching to Windows.Interactivity.Behavior

This is part 2 of the WPF drag & drop exploration. Part 1 can be found here. Among other things, this CodeProject sample helped me much.

Yesterday I created a WPF behavior following WPF conventions for custom dependency properties. While trying to add an adorner to my item (more on that later), I noticed many samples were using System.Windows.Interactivity.Behavior<T>, which I thought was Blend-related, but apparently is not. Because it is much more concise to write and provides useful overridable methods, I decided to switch to it instead.
In addition, with the previous code, I had a problem when defining multiple dependency properties on my behavior, so I needed to find a way to solve this also.

The first thing is of course to inherit from Behavior<T>. You will find it in the System.Windows.Interactivity namespace, which is not included in .Net. You can grab it through the Blend SDK, in a Nuget package, or it’s included in MVVM frameworks like Caliburn.Micro or MVVM Light.

Then, we can remove the Getxxx and Setxxx methods, and replace them with an actual property (that does the same thing). We can also access the behavior instance from the dependency property variable, so we don’t need the instance singleton anymore. We will, however, need to attach the mouse events to the draggable item through ICommands. Since there are no standard ICommand implementation that we can use, we must create one ourselves. I have copied a “standard” implementation from CodeProject, and you will find many similar implementations if you do a quick Google search:

This command will be the bridge between the view and the other layers of the application.

Now, on to inheriting from Behavior<T>. You will notice that I have changed a few names here and there, because they weren’t reflecting the reality of the application anymore: IDragDropHandler becomes IDraggable ; the DropHandler property becomes DraggableItem. I also have replaced the mouse event names with descriptive names (OnStartDrag instead of “mouse button down”), especially since we will now be able to bind these handlers to any event.

You will notice that we don’t attach the commands to any particular item event anymore. This is because it’s handled by the view. It kind of makes sense, because a different device may have a different method of dragging. The rest of the view can be found in part 1.

The events handlers are also similar to the ones in part 1. The only difference is that they access the item through Behavior<T> properties. For instance :

That’s it! Your behavior event handlers are now linked through the view, which means better testing, and better flexibility.