Saturday, April 12, 2014

Verify event was raised with NSubstitute

I used to unit-test events by subscribing to the them with my custom handler which job was to set a flag when the event was called and remember its parameters (if existed). At the end I used assertions to verify if the event was raised and if so whether the parameters were correct.

The behavior I'm going to test is that OfficeDevice should raise Alarm when someone wants to print any document when there is no ink in the device. This is how my tests looked like.

[Test]
public void ShouldAnnounceWhenPrintingWithNoInk()
{
  //GIVEN
  var device = new OfficeDevice(ink: 0);
  InkLevel? level = null;
  device.InkAlarm += (levelParameter) => { level = levelParameter; };

  //WHEN
  device.Print(Any<IDocument>());

  //THEN
  Assert.AreEqual(InkLevel.None, level);
}

This is actually similar to what NSubstitute documentation encourages to do. There's nothing wrong with this. However, a colleague showed me another way of testing events with the spy and verify tactics.

[Test]
public void ShouldAnnounceWhenPrintingWithNoInk()
{
  //GIVEN
  var device = new OfficeDevice(ink: 0);
  var subscriber = Substitute.For<IDummySubscriber>();
  device.InkAlarm += subscriber.React;

  //WHEN
  device.Print(Any<IDocument>());

  //THEN
  subscriber.Received(1).React(InkLevel.None);
}

IDummySubscriber is just a dummy interface for mocking purpose.

public interface IDummySubscriber
{
  void React(InkLevel level);
}


I like the second approach because it's much neater. You can to get rid of flags and lambdas and replace them with mock verification.

Thursday, March 20, 2014

Task Manager can minimize application too

There are some options to minimize a Windows application (in Windows 7) besides using of window control bar:
  • Show desktop button at the end of the notification area on the taskbar,
  • Windows logo button + D combination,
  • Option Show the desktop from the context menu after right click on taskbar

Did you know that Task Manager is also able to minimize Windows application? It does it in a very forceful way. The scenario that is particularly interesting is when an application is showing a modal dialog. Normally it would be impossible to minimize such an application until the modal window is closed but that's not a problem for Task Manager.

When application that displays a modal dialog is minimized form Task Manager, the modal dialog is automatically closed and DialogResult.Cancel is returned from the ShowDialog method.
The dialog is of course not shown again on the restoration.

This is, by contrast, very different from the default behavior of the first three options where the modal window is reopened along with main application window. This is also not applicable for MessageBox which is always reopened.

Is your program prepared for that? I've seen applications that do heavy processing under the cover of modal dialog which is not expected to disappear until it finished its work.
This would be an example of worker modal window that is used sometimes:

 public partial class ModalWindow : Form
  {
    private readonly BackgroundWorker _bw = new BackgroundWorker();

    public ModalWindow()
    {
      InitializeComponent();
      StartWorking();
    }

    public void StartWorking()
    {
      _bw.DoWork += PerformLengthyAction;
      _bw.RunWorkerCompleted += (o, args) =>
      {
        DialogResult = DialogResult.OK;
        Close();
      };
      _bw.RunWorkerAsync();
    }

    private void PerformLengthyAction(object sender, DoWorkEventArgs doWorkEventArgs)
    {
      Thread.Sleep(15000);
    }
  }

It is invoked from main window like this:

  public partial class MainWindow : Form
  {
    private ModalWindow _processingDialog;
    public MainWindow()
    {
      InitializeComponent();
    }

    private void buttonForModalDialog_Click(object sender, EventArgs e)
    {
      _processingDialog = new ModalWindow {DialogResult = DialogResult.None};
      _processingDialog.StartWorking();
      _processingDialog.ShowDialog();
    }
  }

The solutions above is prone to minimization forced by Task Manager.
A quick fix would be to try to reopen the modal dialog on application restore:

  public partial class MainWindow : Form
  {
    ...
    private void MainWindow_Resize(object sender, EventArgs e)
    {
      TryToReopenProcessingDialog();
    }

    private void TryToReopenProcessingDialog()
    {
      if (_processingDialog.DialogResult == DialogResult.Cancel
          && WindowState != FormWindowState.Minimized)
        _processingDialog.ShowDialog();
    }
  }

Friday, November 29, 2013

SQL Server database encryption with CLR user defined types

There aren't many options available when you want to encrypt sensitive data in your database. Enterprise edition of SQL Server has the Transparent Data Encryption feature which is great but this version of SQL Server costs a lot.

The purpose for encryption in a database is to prevent plain data from being written to disc. This is because when database files or backups are accessed by unauthorized people, they would not be able to read the data. The best solution would be a mechanism that automatically performs encryption/decryption on demand and is transparent for the rest of the system.

In this blog post I will show how to encrypt data in a columns by using .NET types that can be imported to SQL Server. Visual Studio 2012 has a project of type SQL Server Database Project. For SQL Server 2008R2, you need to have Target Framework set to 3.5 and Target Platform set to SQL Server 2008 in the project options. Then add new SQL CLR C# User Defined Type like the one below.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;


[SqlUserDefinedType(Format.UserDefined,
    IsByteOrdered = true, MaxByteSize = 500)]
[CLSCompliant(false)]
public struct EncryptedString : INullable, IBinarySerialize
{
  private bool is_Null;
  private string _value;

  public bool IsNull
  {
    get
    {
      return (is_Null);
    }
  }

  public static EncryptedString Null
  {
    get
    {
      EncryptedString es = new EncryptedString();
      es.is_Null = true;
      return es;
    }
  }

  public override string ToString()
  {
    if (this.IsNull)
      return "NULL";
    else
    {
      return _value;
    }
  }

  [SqlMethod(OnNullCall = false)]
  public static EncryptedString Parse(SqlString s)
  {
    if (s.IsNull)
      return Null;

    EncryptedString encryptedString = new EncryptedString();
    encryptedString._value = s.Value;

    return encryptedString;
  }

  /*
   * The methods below handle encryption/decryption (here a dummy string reversing)
   * */
  public void Read(System.IO.BinaryReader r)
  {
    var decrypted = Reverse(r.ReadString());
    _value = decrypted;
  }

  public void Write(System.IO.BinaryWriter w)
  {
    var encrypted = Reverse(_value);
    w.Write(encrypted);
  }

  private static string Reverse(string s)
  {
    char[] charArray = s.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
  }
}


I had to use UserDefined serialization format, because the Native (automatic) serialization can handle only some fixed-size primitive types and not strings. This puts the responsibility to handle the binary format on developer, so you need to write code to implement Read and Write methods for the UDT by implementing the IBinarySerialize interface. (more information here)

Having control over how data is written and read gives the opportunity to enrypt it during writing and decrypt when reading. This is the essential point of this approach – no data is being written to disk without prior encryption and everything happens automatically when you insert, select and update the data.

Once the assembly is compiled this is how you load and use it on server.

--REGISTER ASSEMBLY
CREATE ASSEMBLY ClrEncryption
FROM 'C:\ClrTypes\bin\Debug\ClrEncryption.dll' 
WITH PERMISSION_SET = SAFE;

--REGISTER TYPE
CREATE TYPE dbo.EncryptedString 
EXTERNAL NAME ClrEncryption.[EncryptedString];

--CREATE COLUMN OF THAT TYPE
CREATE TABLE dbo.SecretAgents
(ID INT IDENTITY(1,1) PRIMARY KEY, NickName NVARCHAR(50), RealName EncryptedString)

--ENABLE .NET CODE EXECUTION
EXEC sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

--INSERT VALUES
INSERT INTO dbo.SecretAgents (NickName, RealName) VALUES ('Jason Bourne', 'David Webb')

--SELECTING RAW (SERIALIZED ENCRYTPED) DATA
SELECT NickName, RealName FROM dbo.SecretAgents

--SELECTING DECRYPTED DATA
SELECT NickName, CAST(RealName AS VARCHAR) AS DecryptedRealName FROM dbo.SecretAgents
--OR
SELECT NickName, RealName.ToString() AS DecryptedRealName FROM dbo.SecretAgents


In this example encryption was as simple as reversing the string. In a real world you should use appropriate encryption algorithm like AES, with the keys stored in a secure environment. To debug CLR types you need to attach to SQL Server process.

Wednesday, October 2, 2013

WPF datagrid with filtering (MVVM)

Hi. In this post I would like to present a WPF Datagrid with the filtering capability implemented with pure MVVM approach.

From the user interface perspective, the filtering control is placed inside of the header of the column being filtered (in this case the Name column). The filter is collapsed by default, user needs to expand the expander in the column header to apply filtering. When filter is applied to the grid, the textbox with filter term is highlighted in red.



From the back-end perspective, the filtering is performed directly on the collection bound to the Datagrid. A collection that supports filtering natively is CollectionViewSource, in this case this collection is wrapped around the ObservableCollection. When filter is active it also applies to newly added elements.

Composition code

#region Composition Root
var products = new ObservableCollection<Product>(ProductsStaticSource());
var productsView = new CollectionViewSource { Source = products }.View;
var filteringVm = new FilteringSubViewModel();
DataContext = new ProductsViewModel(productsView, filteringVm, 
  new ProductNameContainsFilter(filteringVm));
#endregion


ProductsView.xaml

<Window x:Class="ExpandableHeader.ProductsView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:ExpandableHeader="clr-namespace:ExpandableHeader"
        Title="Products" Height="350" Width="625">
  <Grid>
    <Grid.Resources>
      <ExpandableHeader:ActivityToBrushConverter x:Key="activityToBrushConverter"/>
    </Grid.Resources>
    <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Products}">
      <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding Path=Id}" >
          <DataGridTextColumn.HeaderStyle>
            <Style TargetType="DataGridColumnHeader">
              <Setter Property="VerticalContentAlignment" Value="Top"/>
            </Style>
          </DataGridTextColumn.HeaderStyle>
        </DataGridTextColumn>
        <DataGridTemplateColumn Header="Name" CanUserSort="True" 
        SortMemberPath="Name" MinWidth="110" >
          <DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
              <TextBlock Text="{Binding Name}" />
            </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
          <!--NAME COLUMN-->
          <DataGridTemplateColumn.HeaderTemplate>
            <DataTemplate>
              <Grid IsHitTestVisible="True">
                <Grid.ColumnDefinitions>
                  <ColumnDefinition/>
                  <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" Text="{TemplateBinding Content}"/>
                <!--FILTER EXPANDER-->
                <Expander Grid.Column="1" IsHitTestVisible="True" 
                VerticalAlignment="Top" Margin="60 -3 0 0" ToolTip="Filter">
                  <Border IsHitTestVisible="True" BorderThickness="1" 
                  Margin="-90 0 0 0" >
                    <StackPanel Margin="0 4 0 0">
                      <!--FILTER TEXTBOX-->
                      <TextBox 
                        Text="{Binding DataContext.FilteringVm.FilterTerm, 
                        RelativeSource={RelativeSource AncestorType=Window}}" 
                        Background="{Binding DataContext.FilteringVm.FilterActive, 
                        RelativeSource={RelativeSource AncestorType=Window}, 
                        Converter={StaticResource activityToBrushConverter}}" 
                        ToolTip="Enter filter term" Width="100" Height="18" FontSize="9" 
                        BorderThickness="1" />
                      <!--FILTER BUTTONS-->
                      <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
                        <TextBlock Margin="2">
                        <Hyperlink Command="{Binding DataContext.FilterApply, 
                          RelativeSource={RelativeSource AncestorType=Window}}">
                          Apply
                        </Hyperlink>
                        </TextBlock>
                        <TextBlock Margin="2">
                        <Hyperlink Command="{Binding DataContext.FilterRemove, 
                          RelativeSource={RelativeSource AncestorType=Window}}">
                          Clear
                        </Hyperlink>
                        </TextBlock>
                      </StackPanel>
                    </StackPanel>
                  </Border>
                </Expander>
              </Grid>
            </DataTemplate>
          </DataGridTemplateColumn.HeaderTemplate>

        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Category" Binding="{Binding Path=Category}" />
        <DataGridTextColumn Header="European Article Number (EAN)" 
                    Binding="{Binding Path=EuropeanArticleNumber}" />
        <DataGridTextColumn Header="Description" Binding="{Binding Path=Description}" />
      </DataGrid.Columns>
    </DataGrid>
  </Grid>
</Window>


ProductsViewModel.cs - main view model to handle high level logic, UI commands and bindings.

using System;
using System.ComponentModel;
using System.Windows.Input;

namespace ExpandableHeader
{
  public class ProductsViewModel
  {
    private readonly IFilter _filter;
    public ICommand FilterApply { get; private set; }
    public ICommand FilterRemove { get; private set; }

    public IFilteringSubViewModel FilteringVm
    {
      get;
      private set;
    }

    public ICollectionView Products
    {
      get;
      private set;
    }

    public ProductsViewModel(ICollectionView products,
      IFilteringSubViewModel filteringSubViewModel, IFilter filter)
    {
      Products = products;
      FilteringVm = filteringSubViewModel;
      _filter = filter;
      FilterApply = new DelegateCommand(OnFilterApply);
      FilterRemove = new DelegateCommand(OnFilterRemove);
    }

    public void OnFilterApply()
    {
      FilteringVm.Apply();
      Products.Filter = _filter.Apply;
    }

    public void OnFilterRemove()
    {
      FilteringVm.Clear();
      Products.Filter = null;
    }
  }
}


FilteringSubViewModel.cs - a specific view model to handle filter state. It is a part of the main application view model presented above.

using System.ComponentModel;

namespace ExpandableHeader
{
  public interface IFilterOption
  {
    string FilterTerm { get; }
  }

  public interface IFilteringSubViewModel
  {
    string FilterTerm { get; }
    bool FilterActive { get; }
    void Apply();
    void Clear();
  }

  public class FilteringSubViewModel : INotifyPropertyChanged, 
                IFilterOption, IFilteringSubViewModel
  {
    public event PropertyChangedEventHandler PropertyChanged;

    public FilteringSubViewModel()
    {
      _filterTerm = string.Empty;
    }

    private bool _filterActive;
    private string _filterTerm;

    public string FilterTerm
    {
      get { return _filterTerm; }
      set
      {
        _filterTerm = value;
        NotifyPropertyChanged("FilterTerm");
      }
    }

    public bool FilterActive
    {
      get { return _filterActive; }
      set
      {
        _filterActive = value;
        NotifyPropertyChanged("FilterActive");
      }
    }

    public void Apply()
    {
      FilterActive = true;
    }

    public void Clear()
    {
      FilterTerm = string.Empty;
      FilterActive = false;
    }

    private void NotifyPropertyChanged(string propertyName)
    {
      var handler = PropertyChanged;
      if (handler != null)
      {
        handler(this, new PropertyChangedEventArgs(propertyName));
      }
    }
  }
}


ProductNameContainsFilter.cs - class for filtering of products by their name.

using System;

namespace ExpandableHeader
{
  public interface IFilter
  {
    bool Apply(object parameter);
  }

  public class ProductNameContainsFilter : IFilter
  {
    private readonly IFilterOption _filterOption;

    public ProductNameContainsFilter(IFilterOption filterOption)
    {
      _filterOption = filterOption;
    }

    public bool Apply(object parameter)
    {
      return ((Product)parameter).Name.IndexOf
               (_filterOption.FilterTerm, 
                StringComparison.InvariantCultureIgnoreCase)
               >= 0;
    }
  }
}


Download VS 2010 code

Monday, August 26, 2013

What is TemplateBinding in WPF – short example.

TemplateBinding has to do with the ControlTemplate, in brief it is a way to inject property into the template from the template user. You've probably heard about the lookless nature of WPF controls which means that unlike behavior (which is fixed), the appearance of a control can be replaced entirely by supplying a new ControlTemplate.

Consider the following template for a ToggleButton. This is simply a polygon with a stroke and an orange fill.
<Window x:Class="TemplateBindingTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
  <Style x:Key="PolygonToggleButtonStyle" TargetType="ToggleButton">
    <Style.Setters>
      <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ToggleButton">
            <Polygon Name="CenterPolygon" Points="90,10 50, 50, 10,10" 
            Fill="Orange" Stroke="Gray" StrokeThickness="0"/>
            <ControlTemplate.Triggers>
              <Trigger Property="IsChecked" Value="True">
                <Setter TargetName="CenterPolygon" Property="StrokeThickness" Value="3"/>
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style.Setters>
  </Style>
</Grid.Resources>

<StackPanel Width="100">
  <ToggleButton Background="Pink" Style="{StaticResource PolygonToggleButtonStyle}"/>
</StackPanel>
</Grid>
</Window>

See that in spite of setting the Background property to Pink, the button is still orange since this is the value hardcoded in template.


Because we provided our own ControlTemplate we must explicitly say how the template should use parameters provided by the control's user. This is a situation when TemplateBinding becomes handy. We will instruct the Fill property to capture the value of Background property in the following way.

<Polygon Name="CenterPolygon" Points="90,10 50, 50, 10,10" 
Fill="{TemplateBinding Background}" Stroke="Gray" StrokeThickness="0"/>

Wednesday, August 7, 2013

Another Observer Pattern implementation (with expressions and delegates)

This is an example of the Observer Pattern implementation in C# where the registration and announcing about events is handled by a separate class Observation. It has two public methods: one for registering for an action (used by subscribers) and one for informing about events (used by publishers). Expression is used to capture the method name the observer wants to register for and Action delegate is used to capture the method name that the subject wants to raise.

public interface ISubject<T>
{
  void RegisterFor(Expression<Action<T>> action, Action callback);
}

public interface IObservers
{
  void InformOf(Action action);
}
  
public class Observation<T> : IObservers, ISubject<T>
{
  private readonly Dictionary<string, Action> callbacks = new Dictionary<string, Action>();

  public void RegisterFor(Expression<Action<T>> action, Action callback)
  {
    var key = KeyFrom(action);
    if (callbacks.ContainsKey(key))
      callbacks[key] += callback;
    else
      callbacks[key] = callback;
  }

  public void InformOf(Action action)
  {
    var key = KeyFrom(action);
    if (callbacks.ContainsKey(key))
      callbacks[key]();
  }

  private string KeyFrom(Action action)
  {
    return action.Method.Name;
  }

  private string KeyFrom(Expression<Action<T>> action)
  {
    var methodExpressionSignature = (action.Body as MethodCallExpression).ToString();
    return ExtractMethodName(methodExpressionSignature);
  }

  private string ExtractMethodName(string signature)
  {
    return signature.Split(new[] { '.', '(' })[1];
  }
}

An interface is introduced to specify the actions being observed:

public interface IApplicationState
{
  void Starting();
  void Stopping();
}

public class Application : IApplicationState
{
  IObservers _observers;
  public Application(IObservers observers)
  {
    _observers = observers;
  }

  public void Starting()
  {
    /*...*/
    _observers.InformOf(Starting);
  }

  public void Stopping()
  {
    /*...*/
    _observers.InformOf(Stopping);
  }
}

An example of use:

static void Main(string[] args)
{
  var observation = new Observation<IApplicationState>();
  var app = new Application(observation);

  observation.RegisterFor(action: change => change.Starting(),
                          callback: () => Console.WriteLine("application is starting."));

  app.Starting();
  app.Stopping();

  Console.ReadLine();
}
//OUTPUT:
//application is starting.

Thursday, July 25, 2013

Macros, templates and generics

This is a note about macros, templates and generics and how are they used to reuse code. I haven't used C/C++ since college times and I decided to write a few lines after a recent conversation with colleague about these concepts in C++ and C#.

Macros are instructions in code (like #define, #include) that are expanded at a preprocessor stage, before the actual compilation. Macros can be used to generate code by a source code search-replace manipulation.

A reason for using macros can be reusability of code. I've heard of people generating C++ functions or classes from macros. For example to generate multiple, similar classes one can define a macro, mark the fragments that can be replaced e.g. class name, base class name, method name and then use the macro invocation with arguments, and it's expanded to fully functional code.

 //An example of macro for creating classes

#include "stdafx.h"
#include <iostream>
using namespace std;

#define CREATE_CLASS(name, base_class_name, method_name) \
class name : public base_class_name \
{ \
public: \
 void method_name()\
  {\
     cout<<"You invoked: "<< #method_name << " on " << #name <<endl;\
  }\
};

class Object{};

CREATE_CLASS(Animal, Object, Feed);
CREATE_CLASS(Cat, Animal, Meow);


int _tmain(int argc, _TCHAR* argv[])
{
  Animal * a = new Animal();
  a->Feed();

  Cat * c = new Cat();
  c->Meow();
  c->Feed();

  getchar();
  return 0;
}

//OUTPUT:
//You invoked: Feed on Animal
//You invoked: Meow on Cat
//You invoked: Feed on Animal

This is a powerful way of assembling almost any code, however, C++ has also a concept of templates. There's a lot of discussion out there on why templates are usually better than macros.

Templates (C++) and generics (C#) are used to separate code to be independent of type. Templates are a compile-time concept so writing a template is indeed defining a contract that the parameter type must conform to. For example if the template invokes a constructor with arguments on parametrized type it means that the template will work with all types that have that constructor defined at the moment of compilation.

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

//template function
template<typename TInput, typename TOutput>
void Save(TInput object)
{
  string text = object->AsString();
  TOutput * output = new TOutput(text);
  output->Flush();
}

class Console
{
  private: string _text;
  public : Console(string text)
  {
    _text = text;
  }
  public : void Flush()
  {
    cout << _text;
  }
};

class Message
{
  public: string AsString()
  {
   return "Message";
  } 
};

int _tmain()
{
  Save<Message *, Console>(new Message());

  getchar();
  return 0;
}

//OUTPUT:
//Message


C# generics retain its generic nature at runtime so all it knows about type parameter is what was specified in where clause. It wouldn't be possible to write generic method so complex as in the example above, because the where clause syntax is limited. I wouldn't say that generics are poor comparing to templates they are just different since the languages are different, C++ compiles to binary code whereas C# runs on VM.