/page/2

TypeScript in Visual Studio 2010 with quick compilation on save - integrated with existing ASP.NET project

Here is a quick recipe.

Download TypeScriptSetup.0.8.2.msi (not never) and install in a way described on this blog so it will install for Visual Studio 2010. Don’t worry if it will not work yet.

Download TypeScriptSetup.0.8.3.msi or newer and install it normally.

Open your existing solution in Visual Studio 2010 and add to it a new TypeScript project (look for it in Other Languages group in new project window). Remove all files from this new project.

Open command prompt and type following (change path according to your setup, I am assuming here that you already have Scripts folder in ASP.NETProject):

mklink /J C:\TypeScriptProject\Scripts C:\ASP.NETProject\Scripts

This will map your existing Scripts folder as “new” Scripts folder in TypeScriptProject.

Open Tools|Options|TypeScript|Project and check Automatically compile TypeScript files which are part of project.

Go to Solution Explorer, check Show All Files, refresh TypeScriptProject, right click on Scripts folder and click Include In Project.

Add new TypeScript file to Scripts folder in TypeScriptProject (look for TypeScript file in Visual C# group in add new item window).

Once you save your TypeScript file it will be automatically compiled into JavaScript file which you may normally use in ASP.NETProject from its Scripts folder (you may include this JS file in project if you wish).

Since TypeScript files are already compiled upon save, you can save some time on solution build by going to Build|Configuration Manager and unchecking Build on TypeScriptProject.

Problem with Convert.ChangeType

The problem with Convert.ChangeType method is that it does not complete its contract if by contract one can understand documentation on MSDN site: Convert.ChangeType.

In Exception section on that page one can find that this method should raise InvalidCastException when “value does not implement the IConvertible interface”.

So we can’t see in following code where Class1 does not implement IConvertible but still method invoke seems working just fine.

[TestFixture]
public class ConvertChangeTypeTest
{
    [Test]
    public void TestConvertChangeType()
    {
        var input = new Class1();
        var inputType = input.GetType();
        var converted = Convert.ChangeType(input, inputType);
        Assert.AreSame(input, converted);
    }
}

public class Class1
{
}

So what’s wrong with this code? Why we don’t get exception since Class1 does not implement IConvertible? Obviously, object is “converted” to its own type so Convert.ChangeType just gives us it back and test passes. But trust me, such code in project can be very confusing and Convert.ChangeType should raise that exception. Especially because of it’s hard to believe that someone’s actual intention was to execute this code so no harm but useful hint would be given.

AyncLock - less cryptic formatting

If you have read very interesting article Comparing two techniques in .NET Asynchronous Coordination Primitives below you can find less cryptic formatting of Stephen Toub’s genius class used in that article. Helped me, maybe will help you.

public sealed class AsyncLock
{
    private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
    private readonly Task<IDisposable> _releaser;

    public AsyncLock()
    {
        _releaser = Task.FromResult((IDisposable)new Releaser(this));
    }

    public Task<IDisposable> LockAsync()
    {
        var wait = _semaphore.WaitAsync();
        if (wait.IsCompleted)
            return _releaser;
        else
            return wait.ContinueWith(
                continuationFunction: (_, state) => (IDisposable)state,
                state: _releaser.Result,
                cancellationToken: CancellationToken.None,
                continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
                scheduler: TaskScheduler.Default);
    }

    private sealed class Releaser : IDisposable
    {
        private readonly AsyncLock _toRelease;

        internal Releaser(AsyncLock toRelease)
        {
            _toRelease = toRelease;
        }

        public void Dispose()
        {
            _toRelease._semaphore.Release();
        }
    }
}
YSOD on main MSDN page (just now, appeared first time when visiting this page).

YSOD on main MSDN page (just now, appeared first time when visiting this page).

Upgrading ASP.NET MVC 4 Beta project to RC (also known as 20505) version

So it should be pretty easy, shouldn’t be? Just install MVC 4 RC from asp.net site and type Update-Package in your Beta project. No, just not this time. Updating nuget packages gave me a nice red “Failed to add reference to System.Net.Http” (and also) Newtonsoft.Json, System.Net.Http.Formatting, System.Web.Razor and System.Web.Helpers.

Below is what I did to manually update. Worked for me, maybe’ll work for you.

Uninstall-Package AspNetMvc -RemoveDependencies
Uninstall-Package AspNetWebApi -RemoveDependencies
Uninstall-Package System.Json
Uninstall-Package System.Web.Providers -RemoveDependencies
Uninstall-Package Microsoft.Web.Optimization

Install-Package Microsoft.AspNet.Mvc
    (Manually add reference to System.Web.Razor
    after the "Failed to add reference" error and retry)
    (Manually add reference to System.Web.Mvc after the 
    "Failed to add reference" error and retry)
Install-Package Microsoft.AspNet.Providers
Install-Package Microsoft.AspNet.Web.Optimization -Pre
    (Manually add reference to System.Web.Optimization after 
    the "Failed to add reference" error and retry)
Install-Package Microsoft.AspNet.WebApi
    (Manually add reference to Newtonsoft.Json after 
    the "Failed to add reference" error and retry)
    (Manually add reference to System.Net.Http.Formatting 
    after the "Failed to add reference" error and retry)
    (Here I got another two errors. I just removed reference 
    to System.Net.Http.Formatting and retried last command 
    two times :-) until nuget was installed, wired but 
    we'll fix that later)

In csproj, fix every manually added reference to make sure it has similar form like in project created from default MVC4 RC template. Remove bin and _bin_deployableAssemblies directories and clean Temporary ASP.NET Files folders just in case.

I still got "The name 'RouteParameter' does not exist in the current context". But when I copied reference to System.Web.Http from default MVC4 RC template the error gone. I also noticed that System.Net.Http.Formatting, WebGrease and Antlr3.Runtime references were missing in comparison to default project, so I added them in csproj. Also System.Web.Providers reference was fixed to be same as in template. In addition, my providers and connectionStrings in web.config got duplicated during update so I removed duplicates. In effect, my web.config is exactly the same as before update.

And I am running my MVC 4 Beta app updated to MVC 4 RC!

Of course you could skip Install-Package part and make (more) reference changes directly in csproj (and avoid cleaning web.config) but in this case you would need to update packages.config and packages folder to make automatic updates possible, so this would be more or less same work.

I also removed custom bundling code which was using NoTransform. This code was needed in beta1 of Microsoft.Web.Optimization because of problems in e.g. Chrome. In beta2 everything works as it was provided so I only customized a little bit the standard bundles but without using NoTransform. And now debugging JS works. Another new nice thing I noticed in RC is keeping Global.asax.cs cleaner in new templates where filters/routes/bundles registration was moved to separate files in App_Start.

Unit testing a custom AuthorizeAttribute in ASP.NET MVC 4 or 3

I needed to test my custom AuthorizeAttribute which has its own HandleUnauthorizedRequest magic. This test can be done:

1) either by directly calling OnAuthorization method

2) or by using ControllerActionInvoker’s InvokeAction method.

In first case, you need to setup AuthorizationContext which can be used as filterContext argument of OnAuthorization method. Here is how this can be done (Moq):

private const string url = "/url";
private bool isAuthenticated;
private string isInRole;
private AuthorizationContext context;

private void SetupAuthorizationContext()
{
    var httpContext = new Mock<HttpContextBase>();
    var controllerContext = new Mock<ControllerContext>();
    var actionDescriptor = new Mock<ActionDescriptor>();
    httpContext.Setup(c => c.Items)
        .Returns(new Mock<IDictionary>().Object);
    httpContext.Setup(c => c.User.Identity.IsAuthenticated)
        .Returns(() => isAuthenticated);
    httpContext.Setup(c => c.User.IsInRole(It.IsAny<string>()))
        .Returns((string role) => role == isInRole);
    httpContext.Setup(c => c.Request.RawUrl).Returns(url);
    httpContext.Setup(c => c.Response.Cache)
        .Returns(new Mock<HttpCachePolicyBase>().Object);
    controllerContext.Setup(c => c.HttpContext)
        .Returns(httpContext.Object);
    actionDescriptor.Setup(d => d.ControllerDescriptor)
        .Returns(new Mock<ControllerDescriptor>().Object);
    context = new AuthorizationContext(controllerContext.Object,
        actionDescriptor.Object);
}

Note that since MVC 3, you need to mock HttpContextBase.Items. It was not needed in MVC 2.

In second case, you need to setup ControllerContext which you can assign to ControllerContext property of tested controller, as demonstrated here.

Code navigation on middle click in Delphi IDE

Lastly, I have been using Visual Studio with Telerik’s JustCode more and more often and this is more or less the first time I noticed that a habit from Visual Studio is not available in Delphi IDE. Previously was the opposite way, so for example I have F9 as “Start Debugging” in Visual Studio, instead of F5.

But what I missed in Delphi is a “navigation to definition” on middle click which is, I believe, a JustCode shortcut to standard VS command. Delphi had (since Delphi 4 at least) a similar navigation command available on Ctrl+Click or Alt+Up. So solution to have this shortcut in Delphi is simple: when cursor is in Delphi IDE editor and middle click is performed, simulate Alt+Up keypress.

It can be easily done in AutoHotKey (just one line of script). But I think it is more fun to write a tiny Delphi program and using only WinAPI achieve this. I’ve written “only WinAPI” because there are masses of Delphi components for what we will be doing here.

This is time to say thanks to authors of Global mouse hook in Delphi and How to Hook the Mouse to Catch Events Outside of your application articles, which I based on.

We need to create a hook procedure in a dll because it will be global hook procedure, which will be loaded and executed by Windows on hooked event. We need of course to create a UI project too, because in this project we provide UI for registering this hook procedure.

Screenshot of "Alt+Up on Middle Click in IDE" form

One thing to clarify in the source is this TEditControl string. This is the class name of editor control in Delphi IDE. You may also notice, that (when compiled with debug configuration), this code will log using CodeSite logger (great tool shipped with Delphi XE2).

Before you go to code, I also want to mention these forward keywords because you may be curious why I didn’t placed the forwarded procedures at top of file. Forwards are used instead of interface section (which can’t be inclued in the library project source) to achieve a “newspaper” coding style in which the most important procedures are placed at beginning and details are at bottom. OK, let’s go to the code.


DLL project

library MiddleButton;

uses
    Winapi.Windows, Winapi.Messages, GlobalHeap in 'GlobalHeap.pas'{$IFDEF DEBUG}, CodeSiteLogging{$ENDIF};

function HookProc(Code: Integer; wParam: wParam; lParam: lParam): LRESULT; stdcall; forward;
function GetClassName(Handle: HWND): string; forward;
procedure SendInputs; forward;

procedure RunHook; stdcall;
begin
    Log('RunHook...');
    GlobalData.HookHandle := SetWindowsHookEx(WH_MOUSE, @HookProc, HInstance, 0);
    if GlobalData.HookHandle = INVALID_HANDLE_VALUE then
        Log('ERROR: SetWindowsHookEx');
    Log('...RunHook');
end;

procedure KillHook; stdcall;
begin
    Log('KillHook...');
    if (GlobalData <> nil) and (GlobalData.HookHandle <> INVALID_HANDLE_VALUE) then
        UnhookWindowsHookEx(GlobalData.HookHandle);
    Log('...KillHook');
end;

function HookProc(Code: Integer; wParam: wParam; lParam: lParam): LRESULT; stdcall;
var
    CurrWND: THandle;
begin
    if (Code >= 0) and (wParam = WM_MBUTTONDOWN) then
    begin
        Log('WM_MBUTTONDOWN');
        CurrWND := PMouseHookStruct(lParam)^.HWND;
        if GetClassName(CurrWND) = 'TEditControl' then
        begin
            SendInputs;
            exit(1);
        end;
    end;
    Result := CallNextHookEx(0, Code, wParam, lParam);
end;

function GetClassName(Handle: HWND): string;
var
    Len: Integer;
begin
    SetLength(Result, 256);
    Len := Winapi.Windows.GetClassName(Handle, PChar(Result), Length(Result));
    SetLength(Result, Len);
end;

procedure SendInputs;
var
    Inputs: array [0 .. 5] of TInput;
begin
    ZeroMemory(@Inputs, sizeof(Inputs));
    Inputs[0].Itype := INPUT_MOUSE;
    Inputs[1].Itype := INPUT_MOUSE;
    Inputs[2].Itype := INPUT_KEYBOARD;
    Inputs[3].Itype := INPUT_KEYBOARD;
    Inputs[4].Itype := INPUT_KEYBOARD;
    Inputs[5].Itype := INPUT_KEYBOARD;
    Inputs[0].mi.dwFlags := MOUSEEVENTF_LEFTDOWN;
    Inputs[1].mi.dwFlags := MOUSEEVENTF_LEFTUP;
    Inputs[2].ki.wVk := VK_MENU;
    Inputs[3].ki.wVk := VK_UP;
    Inputs[4].ki.wVk := VK_UP;
    Inputs[4].ki.dwFlags := KEYEVENTF_KEYUP;
    Inputs[5].ki.wVk := VK_MENU;
    Inputs[5].ki.dwFlags := KEYEVENTF_KEYUP;
    SendInput(Length(Inputs), Inputs[0], sizeof(TInput));
end;

exports
    KillHook,
    RunHook;

end.

GlobalHeap.pas

unit GlobalHeap;

interface

uses
    Winapi.Windows{$IFDEF DEBUG}, CodeSiteLogging{$ENDIF};

type
    PDLLGlobal = ^TDLLGlobal;

    TDLLGlobal = packed record
        HookHandle: HHOOK;
    end;

var
    GlobalData: PDLLGlobal;

procedure Log(Context: string);

implementation

const
    MemMapFile = 'Middle_Button_Map_File';

var
    MMF: THandle;

procedure CreateGlobalHeap;
begin
    Log('CreateGlobalHeap...');
    MMF := CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, sizeof(TDLLGlobal), MemMapFile);
    if MMF = 0 then
    begin
        Log('ERROR: CreateFileMapping');
        exit;
    end;
    GlobalData := MapViewOfFile(MMF, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(TDLLGlobal));
    if GlobalData = nil then
    begin
        CloseHandle(MMF);
        Log('ERROR: MapViewOfFile');
    end;
    Log('...CreateGlobalHeap');
end;

procedure DeleteGlobalHeap;
begin
    Log('DeleteGlobalHeap...');
    if GlobalData <> nil then
        UnmapViewOfFile(GlobalData);
    if MMF <> INVALID_HANDLE_VALUE then
        CloseHandle(MMF);
    GlobalData := nil;
    MMF := 0;
    Log('...DeleteGlobalHeap');
end;

procedure Log(Context: string);
begin
{$IFDEF DEBUG}
    if GlobalData = nil then
        CodeSite.Send(Context)
    else
        CodeSite.Send(Context + '  Data: %p  Hook: %x', [GlobalData, GlobalData.HookHandle]);
{$ENDIF}
end;

initialization

CreateGlobalHeap;

finalization

DeleteGlobalHeap;

end.

UI project

program HookRunner;

uses
  Vcl.Forms,
  HookRunnerMainUnit in 'HookRunnerMainUnit.pas' {Form1};

{$R *.res}

begin
  Application.Initialize;
  Application.ShowMainForm := False;
  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TForm1, Form1);
  Application.Run;
end.

HookRunnerMainUnit.pas

unit HookRunnerMainUnit;

interface

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Winapi.ShellAPI, Vcl.ExtCtrls, Vcl.AppEvnts;

const
    WM_ICONTRAY = WM_USER + 1;

type
    TForm1 = class(TForm)
        btnRun: TButton;
        lbRunning: TLabel;
        btnKill: TButton;
        ApplicationEvents1: TApplicationEvents;
        procedure FormCreate(Sender: TObject);
        procedure FormDestroy(Sender: TObject);
        procedure btnRunClick(Sender: TObject);
        procedure btnKillClick(Sender: TObject);
        procedure TrayMessage(var Msg: TMessage); message WM_ICONTRAY;
        procedure ApplicationEvents1Minimize(Sender: TObject);
    private
        FTrayIconData: TNotifyIconData;
        procedure InitializeTrayIcon;
    end;

procedure RunHook; stdcall; external 'MiddleButton.dll' name 'RunHook';
procedure KillHook; stdcall; external 'MiddleButton.dll' name 'KillHook';

var
    Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
    btnRunClick(nil);
    InitializeTrayIcon;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
    btnKillClick(nil);
    Shell_NotifyIcon(NIM_DELETE, @FTrayIconData);
end;

procedure TForm1.btnRunClick(Sender: TObject);
begin
    RunHook;
    btnRun.Enabled := False;
    btnKill.Enabled := True;
    lbRunning.Show;
end;

procedure TForm1.btnKillClick(Sender: TObject);
begin
    KillHook;
    btnRun.Enabled := True;
    btnKill.Enabled := False;
    lbRunning.Hide;
end;

procedure TForm1.InitializeTrayIcon;
begin
    with FTrayIconData do
    begin
        cbSize := SizeOf;
        Wnd := Handle;
        uID := 0;
        uFlags := NIF_MESSAGE + NIF_ICON + NIF_TIP;
        uCallbackMessage := WM_ICONTRAY;
        hIcon := Application.Icon.Handle;
        StrPCopy(szTip, Caption);
    end;
    Shell_NotifyIcon(NIM_ADD, @FTrayIconData);
end;

procedure TForm1.TrayMessage(var Msg: TMessage);
begin
    if Msg.LParam = WM_LBUTTONDOWN then
    begin
        Show;
        WindowState := wsNormal;
        Application.BringToFront;
        BringToFront;
    end;
end;

procedure TForm1.ApplicationEvents1Minimize(Sender: TObject);
begin
    Hide;
end;

end.

That’s it. Thanks for reading!

AutoFixture and interfaces

When using AutoFixture for unit tests, I find that sometimes would be useful to create anonymous implementation instance for interface in the same way like we are creating anonymous instances of classes, but not specifying which class we mean for this interface.

I mean of course mocking property getters. For instance, in the interface I have something like:

public interface IFoo
{
    //int GetBar();
    int Bar { get; }
}

I asked about this feature in Stack Overflow, and got answer that it’s not supported, so here is my draft solution which works for bare property getters only, but so far was sufficient in my unit tests.

public static class AnonymousMock
{
    public static Mock<T> CreateAnonymousMock<T>(
        this ISpecimenBuilderComposer composer) where T : class
    {
        return new Factory<T>(composer).CreateAnonymousMock();
    }

    private class Factory<T> where T : class
    {
        private readonly ISpecimenBuilderComposer composer;
        private Mock<T> mock;
        private MethodInfo setupGet;
        private PropertyInfo property;
        private object returnsGetter;
        private MethodInfo returns;

        internal Factory(ISpecimenBuilderComposer composer)
        {
            this.composer = composer;
        }

        internal Mock<T> CreateAnonymousMock()
        {
            mock = new Mock<T>();
            setupGet = mock.GetType().GetMethod("SetupGet");
            typeof(T).GetProperties()
                .Where(p => p.CanRead)
                .ToList()
                .ForEach(p => { property = p; SetupGet(); });
            return mock;
        }

        private void SetupGet()
        {
            var genericSetupGet = setupGet
                .MakeGenericMethod(property.PropertyType);
            var expression = GetPropertyLambdaExpression();
            returnsGetter = genericSetupGet
                .Invoke(mock, new object[] { expression });
            UseReturnsGetter();
        }

        private void UseReturnsGetter()
        {
            returns = returnsGetter.GetType().GetMethods()
                .Single(m => m.Name == "Returns" && m.GetParameters()
                    .Any(p => p.ParameterType == property.PropertyType));
            Returns();
        }

        private void Returns()
        {
            var propertyValue = GetValueFromFixture();
            returns.Invoke(returnsGetter, new object[] { propertyValue });
        }

        private LambdaExpression GetPropertyLambdaExpression()
        {
            var typeParameter = Expression.Parameter(typeof(T));
            var propertyExpression = Expression
                .Property(typeParameter, property);
            return Expression.Lambda(propertyExpression, typeParameter);
        }

        private object GetValueFromFixture()
        {
            var createAnonymous = typeof(SpecimenFactory).GetMethods()
                .Single(m => m.Name == "CreateAnonymous"
                    && m.GetParameters().All(p => p.ParameterType
                        == typeof(ISpecimenBuilderComposer)));
            var genericCreateAnonymous = createAnonymous
                .MakeGenericMethod(property.PropertyType);
            return genericCreateAnonymous
                .Invoke(null, new object[] { composer });
        }
    }
}

Remarks: in linked SO page you can find opinion that using properties in interfaces is wrong by design. I use them either as a syntax sugar (instead of function) in regular interfaces or as another layer of clarity in interfaces for classes that don’t need interfaces desperately.

I think the second use is just specific to me when I work in C# because in Delphi we have interface code section even for regular classes. We have regular interfaces like these from C# or Java too, of course. But this interface code section is something C# doesn’t have. If you don’t know what I am talking about, here is Anatomy Of A Delphi Unit.

Anyway, I hope you’ll find this extension method useful from time to time. You could call and test it like this:

var foo = fixture.CreateAnonymousMock<IFoo>();
Assert.AreNotEqual(0, foo.Object.Bar);

Testing the “less important” code

Let’s imagine a layered application. Domain layer has of course tests because this layer is important and because possibly is easy to test if is well-designed.

Then comes UI layer which for some developers may seem less important (not my opinion) and sometimes tests are given up. See what happens now.

If domain model is carefully designed it’s not as fragile as UI code tends to be. In UI where we work with some UI platform, we can’t design everything to be as easy to code as in domain.

And that’s why in my opinion unit tests of UI layer are as same important as unit tests of domain layer. Maybe from practical point of view are even more useful because tests will help developers quicker find bugs in the layer which usually has more occasions to introduce bugs.

Despite this practical note, tests of domain layer are equally important for obvious reasons.

So test all layers. Testing will actually help you finish your work faster in UI case, too.

Two little surprises: 1) Missing parentheses makes C# think that something is delegate. 2) AutoFixture’s CreateMany() uses deferred execution.

See below, only first assert passes while second and third fails.

public interface IFoos
{
    IEnumerable<int> GetFoos();
}

var foos1 = new Mock<IFoos>();
var foos2 = new Mock<IFoos>();
var foos3 = new Mock<IFoos>();
foos1.Setup(f => f.GetFoos()).Returns(fixture.CreateMany<int>().ToList());
foos2.Setup(f => f.GetFoos()).Returns(fixture.CreateMany<int>().ToList);
foos3.Setup(f => f.GetFoos()).Returns(fixture.CreateMany<int>());
Assert.AreEqual(foos1.Object.GetFoos().First(), foos1.Object.GetFoos().First());
Assert.AreEqual(foos2.Object.GetFoos().First(), foos2.Object.GetFoos().First());
Assert.AreEqual(foos3.Object.GetFoos().First(), foos3.Object.GetFoos().First());

For first (foos2) I would say it’s surprising because missing parentheses at the end of function call is easy mistake to make when someone “comes” from Delphi, for instance. Not very nice explicitness of C#.

The second (foos3) is surprising because this method has actually “Create” word in its name but it not creates what you would expect when you call it. I know how it works, it’s just this name.

TypeScript in Visual Studio 2010 with quick compilation on save - integrated with existing ASP.NET project
Problem with Convert.ChangeType
AyncLock - less cryptic formatting
Upgrading ASP.NET MVC 4 Beta project to RC (also known as 20505) version
Unit testing a custom AuthorizeAttribute in ASP.NET MVC 4 or 3
Code navigation on middle click in Delphi IDE
AutoFixture and interfaces
Testing the “less important” code
Two little surprises: 1) Missing parentheses makes C# think that something is delegate. 2) AutoFixture’s CreateMany() uses deferred execution.

About:

Hi! My name is Paweł and on this mini blog you can find my
random ramblings on programming (Delphi, .NET in general)

@pol84_

Following: