Sunday, December 12, 2010

jQuery and DOM dimension measurement

I had to rewrite a code that used standard DOM functions (like offsetWidth) to jQuery functions (like outerWidth).
This is a simple document visually summarizing the differences.

Link: jQuery HMTL with height cheat sheet (DOCX)
Link: jQuery HMTL with height cheat sheet (PDF)

Monday, November 22, 2010

WaitableTimer in C++

This is an example code for calling a waitable timer. This is a good way to wait for a timer event without using CPU (thread blocks). There is a small trick in the code. It’s hard to create a FILETIME properly so I create a SYSTEMTIME (and set it according to my needs), convert it to FILETIME, finally I cast that to LARGE_INTEGER* (to fulfill the needs of SetWaitableTimer).

I set the timer to autoreset, so it will restart counting after firing the event (counts again and again). The first event (“CALLED”) occurs after 3 secs, the subsequent events occur after 2 secs.

The WaitForSingleObject blocks until a timer event is fired. I break the loop after 5 events, stop the timer and delete the timer handle.

stdafx.h

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <Windows.h>

using namespace std;

WaitableTimer.cpp

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
int count = 0; // Iteration counter

HANDLE hTimer = NULL; // WaitableTimer handle
hTimer = CreateWaitableTimer( // Create waitable timer
NULL,
FALSE, // Autoreset --> timer restarts counting after event fired
NULL);

SYSTEMTIME time; // System time structure
GetSystemTime(&time); // Curren time
time.wSecond += 3; // Wait 3 sec

FILETIME ftime; // File time (expected by SetWaitableTimer)
SystemTimeToFileTime(&time, &ftime); // Convert system to file time


if(!SetWaitableTimer( // Set waitable timer
hTimer, // Timer handle
reinterpret_cast<LARGE_INTEGER*>(&ftime), // Convert file time to large integer
2000, // Period time, fire again after 2 sec
NULL,
NULL,
0))
{
cout << "SetWaitableTimer failed" << GetLastError() << endl;
};


while(WaitForSingleObject(hTimer, 5000) == WAIT_OBJECT_0){ // Wait for timer event
cout << "CALLED " << ++count << endl;
if(count+1 > 5){ // Exit after 5 events
break;
}
}

CancelWaitableTimer(hTimer); // Stop timer
CloseHandle(hTimer); // Delete handle

return 0;
}

See source code: http://code.google.com/p/artur02/source/browse/trunk/CPP/WaitableTimer/WaitableTimer.cpp

Waitable timer objects: http://msdn.microsoft.com/en-us/library/ms687012(VS.85).aspx
CreateWaitableTimer function: http://msdn.microsoft.com/en-us/library/ms682492(v=VS.85).aspx
SetWaitableTimer function: http://msdn.microsoft.com/en-us/library/ms686289(v=VS.85).aspx
Systemtime structure: http://msdn.microsoft.com/en-us/library/ms687008(v=VS.85).aspx
Usage example: http://msdn.microsoft.com/en-us/library/ms687008(v=VS.85).aspx

Saturday, November 6, 2010

Perforce file exclusion

There are file types and folders I don’t want to see in a source control repository. These are user-specific settings, temporary folders and binaries. There is a simple client-side way to exclude these files and folders. Just add the following lines to your workspace definition:

Pattern Description
-//depot/.../*.suo //WORKSPACE/.../*.suo
Solution user options file.
-//depot/.../bin/... //WORKSPACE/.../bin/...
Generated binaries.
-//depot/.../obj/... //WORKSPACE/.../obj/...
Object files.
-//depot/.../*.user //WORKSPACE/.../*.user
User settings. Can contain useful information, e.g. startup parameters.

CV Tag Cloud

The tag cloud of my CV. Can be viewed in full size: http://www.wordle.net/show/wrdl/2686570/CV

Sunday, October 31, 2010

Simple Map Reduce Example in C#

This is an example of map-reduce implementation for IEnumerable. This code is not optimized. I think we shouldn’t create separate Task for each enumerated item. Probably partitioning the enumeration and dealing with bigger chunks of data would be much more efficient.

Browse source code: Google Code

MapReduce function for IEnumerable:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections;

namespace MapReduceCode
{
    public static class MapReduce
    {
        public static Task<TResult> ForEachParallel<TItem, TSubResult, TResult, TParam>(this IEnumerable items, Func<TItem, TParam, TSubResult> map, Func<TSubResult[], TResult> reduce, TParam param)
        {
            if (items == null) { throw new ArgumentNullException("items"); }
            if (map == null) { throw new ArgumentNullException("map"); }
            if (reduce == null) { throw new ArgumentNullException("reduce"); }

            return Task<TResult>.Factory.StartNew(() =>
            {
                List<Task<TSubResult>> tasks = new List<Task<TSubResult>>();

                foreach (TItem item in items)
                {
                    Task<TSubResult> t = Task<TSubResult>.Factory.StartNew(item2 =>
                        {
                            var mparam = (Tuple<TItem, TParam>)item2;
                            return map(mparam.Item1, mparam.Item2);
                        },
                        new Tuple<TItem, TParam>(item, param),
                        TaskCreationOptions.None | TaskCreationOptions.AttachedToParent);
                    tasks.Add(t);
                }

                List<TSubResult> results = new List<TSubResult>();
                foreach (Task<TSubResult> task in tasks)
                {
                    results.Add(task.Result);
                }

                return reduce(results.ToArray());
            });
        }
    }
}

Usage example:

using System;
using System.Collections;
using MapReduceCode;
using System.Threading;
using System.Threading.Tasks;

namespace MapReduce
{
    class Program
    {
        static void Main(string[] args)
        {
            var a = Generate().ForEachParallel<int, int, int, int>(
                (element, param)=> 
                {
                    var result = element * param;
                    Console.WriteLine("Map: {0}, {1}", result, Task.CurrentId);
                    Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(500));
                    return result;
                }, 
                (subresult)=>
                {
                    var sum = 0;
                    foreach (var item in subresult)
                    {
                        sum += item;
                    }
                    Console.WriteLine("Reduce: {0}", sum);
                    return sum;
                }, 
                5);

            Console.WriteLine(a.Result);
            
        }

        static IEnumerable Generate()
        {
            for (int i = 0; i < 100; i++)
            {
                yield return i;
            }
        }
    }
}

Result:

Map: 0, 1
Map: 5, 2
Map: 10, 3
Map: 20, 4
Map: 15, 5
Map: 25, 6
Map: 30, 7
Map: 35, 8
Map: 40, 9
Map: 45, 10
Map: 50, 11
Map: 55, 12
Map: 60, 13
Map: 65, 14
Map: 70, 15
Map: 75, 16
Map: 80, 17
Map: 85, 18
Map: 90, 19
Map: 95, 20
Map: 100, 21
Map: 105, 22
Map: 110, 23
Map: 115, 24
Map: 120, 25
Map: 125, 26
Map: 130, 27
Map: 135, 28
Map: 140, 29
Map: 145, 30
Map: 150, 31
Map: 155, 32
Map: 160, 33
Map: 165, 34
Map: 170, 35
Map: 175, 36
Map: 180, 37
Map: 185, 38
Map: 190, 39
Map: 195, 40
Map: 200, 41
Map: 205, 42
Map: 210, 43
Map: 215, 44
Map: 225, 45
Map: 230, 47
Map: 220, 46
Map: 235, 48
Map: 245, 50
Map: 240, 49
Map: 250, 51
Map: 255, 52
Map: 260, 53
Map: 265, 54
Map: 275, 56
Map: 270, 55
Map: 285, 57
Map: 280, 58
Map: 290, 59
Map: 295, 60
Map: 300, 62
Map: 305, 61
Map: 310, 63
Map: 315, 64
Map: 320, 65
Map: 325, 66
Map: 330, 67
Map: 335, 68
Map: 340, 69
Map: 355, 72
Map: 350, 71
Map: 360, 73
Map: 365, 74
Map: 345, 70
Map: 370, 75
Map: 380, 77
Map: 375, 76
Map: 390, 79
Map: 395, 80
Map: 385, 78
Map: 400, 81
Map: 405, 82
Map: 415, 84
Map: 425, 86
Map: 410, 83

Map: 420, 85
Map: 430, 87
Map: 440, 89
Map: 435, 88
Map: 450, 90
Map: 445, 91
Map: 455, 92
Map: 460, 93
Map: 470, 95
Map: 480, 97
Map: 475, 96
Map: 485, 98
Map: 465, 94
Map: 490, 99
Map: 495, 100
Reduce: 24750
24750

Wednesday, May 19, 2010

CAL and AutoMapper

I’m using Composite Application Library (CAL) in a project. I decided to use AutoMapper as well. I put AutoMapper’s Mapper.CreateMap<source, dest>() calls into one of the Bootstrapper.cs methods. I got an InvalidOperationException in the ModuleCatalog’s InnerLoad() function.

Reason

AutoMapper creates an in-memory assembly and CAL tries to read all the assemblies’ Location property. This property raises an InvalidOperationException in case of in-memory assemblies.

Solution

Insert AutoMapper mappings right after the Bootstrapper.Run() call. In my case I call this in App.xaml.cs, so you can write the following:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // Run bootstrapper
    Bootstrapper bootstrapper = new Bootstrapper();
    bootstrapper.Run();

    // AutoMapper mappings
    Parallel.Invoke(CreateAutoMapperMappings);
}

/// <summary>
/// Creates the AutoMapper mappings.
/// </summary>
private static void CreateAutoMapperMappings()
{
    Mapper.CreateMap<Source, Dest>();
}

Friday, May 14, 2010

F#: Piping and Composition

Piping and compositions are very expressive tools in F#. It significantly improves code readability.

Let’s have the following functions:

> let square x = x*x;;
val square : int -> int

> let negate x = -x;;
val negate : int –> int

Function square returns the square of x, while negate returns the negated value of x.

We can calculate square(negate(10)) as follows:

> let x = negate 10;;
val x : int = –10

> let x = square x;;
val x : int = 100

Or a simpler way:

> let x = square (negate 10);;
val x : int = 100

Piping

We can define piping as symbol-named function definition that simply applies two functions in reverse order:

let (|>) f x =
  x f

The example with piping:

> 10 |> negate |> square;;
val it : int = 100

That means ((10 negate) square) –> (square (negate 10)). I used an integer (10) as f.

Composition

Composition is a reverse-order function composition:

let (>>) f g x =
  g(f x)

The example with composition:

> (negate >> square) 10;;
val it : int = 100

That means ((negate square) 10) –> (square (negate 10)).

Usage

The examples above are very simple ones. The real benefits of piping and composition reveal in case of function definitions and usage.

Pipes can reverse parameter definition orders (like in 10 |> negate) and can help type inferring. When F# infers types, it evaluates from upper left corner to lover right corner of the text file, so sometimes it doesn't know the type of a function parameter. Pipe brings parameters forward.

Composition can help omitting function parameter declaration. If the first function expects a parameter, the composed function expects it’s parameter. 

Tuesday, May 4, 2010

Database Comparison

I' am very interested in open source database comparisons. I found two interesting blog posts:

Link: H2, HSQLDB, DERBY, PostgreSQL, MySQL
Link: HSQLDB, H2, SQLite

Sunday, May 2, 2010

Get WPF DataGrid row and cell

There are no simple built-in methods for accessing individual rows or columns in WPF DataGrid. The following code samples will provide simple methods for accessing these items.

First of all we need a helper function for selecting a visual child:

public static T GetVisualChild<T>(Visual parent) where T : Visual
{
    T child = default(T);
    int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < numVisuals; i++)
    {
        Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
        child = v as T;
        if (child == null)
        {
            child = GetVisualChild<T>(v);
        }
       if (child != null)
       {
           break;
       }
   }
       return child;
}

There is a simple method for getting the current (selected) row of the DataGrid:

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

We can also get a row by its indices:

public static DataGridRow GetRow(this DataGrid grid, int index)
{
    DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    if (row == null)
    {
        // May be virtualized, bring into view and try again.
        grid.UpdateLayout();
        grid.ScrollIntoView(grid.Items[index]);
        row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
    }
    return row;
}

Now we can get a cell of a DataGrid by an existing row:

public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
    if (row != null)
    {
        DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);

        if (presenter == null)
        {
            grid.ScrollIntoView(row, grid.Columns[column]);
            presenter = GetVisualChild<DataGridCellsPresenter>(row);
        }

        DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
        return cell;
    }
    return null;
}

Or we can simply select a row by its indices:

public static DataGridCell GetCell(this DataGrid grid, int row, int column)
{
    DataGridRow rowContainer = grid.GetRow(row);
    return grid.GetCell(rowContainer, column);
}

The functions above are extension methods. Their use is simple:

var selectedRow = grid.GetSelectedRow();
var columnCell = grid.GetCell(selectedRow, 0);

View source on Google Code (unformatted selection possible)

Saturday, April 17, 2010

Mixed mode assemblies on .NET 4.0

Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

I got this message when I tried to start a project migrated from .NET 3.5 to .NET 4.0. I case of migration, migration wizard inserts a <startup></startup> tag into the app.config file.

Solution: insert the

useLegacyV2RuntimeActivationPolicy="true"

attribute into the startup tag. Application should work now.

Reason: .NET 4.0 changed mixed mode assembly loading mechanisms.

NHibernate session management

When you start working with NHibernate, you will see code examples like this one:

int userID = 1234;
using( ISession session = sessionFactory.OpenSession() )
using( session.BeginTransaction() ) {
    User user = session.Get<User>(userID); 
    session.Transaction.Commit();
}

You get a session object, start a transaction and finally commit that. This is fine when you work in a simple one-layer application or you are OK with tight coupling. When you have multiple layers, or working with binding like in WPF, things get complicated.

Session management strategies

  1. Session per application
    Simplest approach. Just one session for the whole application, typically returned by a singleton.
    Problem: Async calls can interfere with each other, cache size grows, unrecoverable exceptions, stale data
  2. Session per screen
    New session for every form/view/… There are multiple concurrent sessions.
    Problem: You can keep a screen opened for a long time, so stale data is expectable.
  3. Session per data access
    Every single data access uses a new session object.
    Problem: Lazy loading won’t work, problem with 1st level cache…
  4. Session per use-case
    You create a new session for every use-case. There will be concurrent sessions.

Firs try: Following examples – Session per data access

I’ve created an application with the simplest solution possible. I followed the examples and whenever I tried to access data, I created a session and a transaction. Everything was fine, until I tried to employ lazy loading. It simply did not work. There was no open sessions the lazy loader proxy could have used.

Second try: Session per application

I modified the application. I created a singleton that returned a session object. Every single data access used this session. The application worked fine – for a while. I used SQLite as DBMS, and SQLite has not the best threading support. So I got exceptions randomly. Sometimes a control was empty, sometimes it was filled with data. Exceptions happened about 1 out of 15 tries. I suspected a threading issue and it seems it was.

Third try: Session per use-case

I had to implement a session per use-case (business transaction) solution to solve the problems above. A business transaction is a user-initiated action involving multiple complicated operations (steps). All operations (and the transaction itself) are either successful or unsuccessful. The state of the involved members are well-defined and consistent at the end of the transaction.

We have to be able to keep alive the NHiberanate ISession object over multiple operations. The solution is the unit of work pattern. It encapsulates the ISession object, so we can pass it around and implement the IDisposable pattern. The class implementing the unit of work pattern can expose ISession functionality. See the example UML class diagram below.

Illustration: Unit of Work 

This is an example of calling the UnitOfWork object instance:

using (UnitOfWork unitOfWork = database.CreateUnitOfWork())
{
    PropertiesRepository propertiesRepository = new PropertiesRepository(unitOfWork);
    properties = propertiesRepository.Current;
}

You can use a simple factory (it is the database object here) to create a new UnitOfWork instance. This instance should be passed to all the classes accessing NHibernate functionality. This is important, so design your data access and manipulating classes according to this constraint!

Link: Rich-client NHibernate session management
Link: Unit of Work

CodePlex TFS from VS2010

Visual Studio 2010 Professional has a built-in Team Foundation Server (TFS) client. There are some user interface changes on the Add Team Foundation Server screen. When you are connecting to the CodePlex TFS, you need to specify the following information:

  • Name or URL of TFS: tfs<number>.codeplex.com
  • Connection details
    • Path: tfs
    • Port number: 443
    • Protocol: HTTPS

There is no need to specify Project name anywhere on this screen.

Sunday, January 24, 2010

Refresh WPF DataGrid

I am using WPF DataGrid for displaying a list of items. I had to modify an item, but the item had no INotifyPropertyChanged event on that property (it was a collection).

So my first idea was:

  1. Update the list behind ItemsSource
  2. Set ItemsSource property to null to force unbinding
  3. Set ItemsSource property to the new collection
  4. Set the SelectedItem to the new item
  5. Call ScrollIntoView() on the new item

Well, I got a huge exception at step 5. There must be a simpler solution. And there is.

The DataGrid generates a view of the ItemsSource. All I have to do is call the Items.Refresh() method, and it will rebind to the ItemsSource. Everything will be rebound, all updates will be visible. Selected item kept, visibility kept.

Monday, January 18, 2010

DispatcherPriority

I had a very tough problem today. The following code did not work correctly:

var books = _bookRepository.All;
 
Dispatcher.Invoke(
    new ThreadStart(delegate
                        {
                            foreach (Book book in books)
                            {
                                CatalogItems.Add(new BookViewModel(book));
                            }
 
                            OnLoaded(this, EventArgs.Empty);
                            OnPropertyChanged("CatalogItems");
                        }),
    DispatcherPriority.ApplicationIdle);

When I run the code above the first time, the debugger didn’t even break into the dispatched code. The subsequent calls were fine.

Finally I realized that DispatcherPriority.ApplicationIdle should be changed to DispatcherPriority.Normal – and everything was fine. Don’t forget to check the DispatcherPriority value of the dispatcher! It’s hard to debug and hard to recognize.

These are the possible dispatcher priority levels:

Priority

Description

Inactive

Work items are queued but not processed.

SystemIdle

Work items are only dispatched to the UI thread when the system is idle. This is the lowest priority of items that are actually processed.

ApplicationIdle

Work items are only dispatched to the UI thread when the application itself is idle.

ContextIdle

Work items are only dispatched to the UI thread after higher-priority work items are processed.

Background

Work items are dispatched after all layout, rendering, and input items are processed.

Input

Work items are dispatched to the UI thread at the same priority as user input.

Loaded

Work items are dispatched to the UI thread after all layout and rendering are complete.

Render

Work items are dispatched to the UI thread at the same priority as the rendering engine.

DataBind

Work items are dispatched to the UI thread at the same priority as data binding.

Normal

Work items are dispatched to the UI thread with normal priority. This is the priority at which most application work items should be dispatched.

Send

Work items are dispatched to the UI thread with the highest priority.

 

Link: Build More Responsive Apps With The Dispatcher (MSDN)

Monday, January 11, 2010

Events with anonymous delegate

I subscribed to an event with an anonymous delegate. Later I was in need for a solution to be able to unsubscribe this delegate. This is a simple solution for the problem:

public class ClassName
{
    MouseButtonEventHandler eventHandler;
 
    public ClassName()
    {
        eventHandler = delegate
                                        {
                                            // operations
                                        };
    }
 
    void Functionality()
    {
        if (_subscribe)
        {
            _object.MouseLeftButtonDown += eventHandler;
        }
        else
        {
            _object.MouseLeftButtonDown -= eventHandler;
        }
    }
}

Saturday, January 9, 2010

NHibernate and SQLite in-memory database

I’m implementing and in-memory database-based unit test framework for an application. I hope it speeds up unit tests. Unfortunately I have to redesign my entity repositories to support in-memory behavior. As far as I can learn from SUT behavior, SQLite will create a brand new database when
  • you close the session
  • you commit or close a transaction
It means you can’t use using(ISession) and using(ITransaction transaction){ … transaction.Commit() } constructs in the repository.