Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Thursday, May 15, 2014

Partial apply in C#

Partial apply by Wikipedia:

In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function \scriptstyle f \colon (X \times Y \times Z) \to N , we might fix (or 'bind') the first argument, producing a function of type  \scriptstyle\text{partial}(f) \colon (Y \times Z) \to N . Evaluation of this function might be represented as f_{partial}(2, 3). Note that the result of partial function application in this case is a function that takes two arguments.

In short, that means you define (bind) some of the possible arguments and leave some to be filled in later (free).

Scala

def sum(a:Int, b:Int, c:Int):Int = a+b+c  //> sum: (a: Int, b: Int, c: Int)Int
sum(1,2,3)                                //> res11: Int = 6

def sum1 = sum(1, _:Int, _:Int)           //> sum1: => (Int, Int) => Int
sum1(2,3)                                 //> res12: Int = 6

def sum2 = sum(_:Int, 2, _:Int)           //> sum2: => (Int, Int) => Int
sum2(1,3)                                 //> res13: Int = 6

sum1 binds the first parameter but the other two parameters are free. As you can see from the result it gets translated to a lambda with two parameters.

sum2 binds the second parameter. The result is the same, a lambda with two parameters.

C#

C# has no built-in operator for applying a function, so we have to write the lambdas directly.

readonly Func sum = (x, y, z) => x + y + z;

[Fact]
public void Sum()
{
    var result = sum(1, 2, 3);

    Assert.Equal(6, result);
}

[Fact]
public void Sum_PartialApply_FirstParam()
{
    Func sum1 = (y, z) => sum(1, y, z);

    var result = sum1(2, 3);

    Assert.Equal(6, result);
}

[Fact]
public void Sum_PartialApply_SecondParam()
{
    Func sum2 = (x, z) => sum(x, 2, z);

    var result = sum2(1, 3);

    Assert.Equal(6, result);
}

Wednesday, May 14, 2014

Loan pattern in C#

There is a pattern is Scala called loan pattern. You open a resource, “loan” the resource to another function, and the loaner closes the resource.

Scala

This function expects a file a function. When it's called it creates the resource, executes the function and closes the resource.

def withPrintWriter(file: File, op: PrintWriter => Unit) {
  val writer = new PrintWriter(file)
  try {
    op(writer)
  } finally {
    writer.close()
  }
}

This is how it's called:

withPrintWriter(
  new File("date.txt"),
  writer => writer.println(new java.util.Date)
)

C#

Now I extended the definition with currying:

readonly Func, string>> openFile = 
    path => 
        handler =>
            {
                var reader = new StreamReader(path);
                try
                {
                    return handler(reader);
                }
                finally
                {
                    reader.Close();
                    Console.WriteLine("Stream closed");
                }
            };

Here are two examples on calling the function above:

readonly Func readAllLines = input => input.ReadToEnd();
readonly Func readSingleLine = input => input.ReadLine();

[Fact]
public void LoanPattern_AllText()
{
    var result = openFile("TextFile1.txt")(readAllLines);
    Assert.Equal("This is the test content.\r\nThis is a second line.", result);
}

[Fact]
public void LoanPattern_ReadSingleLine()
{
    var result = openFile("TextFile1.txt")(readSingleLine);
    Assert.Equal("This is the test content.", result);
}

Result

Now the code calling the function (openFile) is much simpler and there is no need for error handling in the caller. Furthermore thanks to currying, even the resource name can be bound in the constructor, hiding the resource initialization as well.

Thursday, May 8, 2014

Currying in Scala and C#

Currying is an interesting and powerful functional programming concept. Interestingly currying can be used in C# as well.

The usual approach

Let's define a simple add function that sums two numbers in C#:

[Fact]
public void SimpleAdd_AsInlineFunction_WithLambda()
{
    Func<int, int, int> add = (x, y) => x + y;
    var result = add(5, 7);
    Assert.Equal(12, result);
}

The same in Scala:

def add(x:Int,y:Int) = x+y                      //> add: (x: Int, y: Int)Int
add(5,7)                                        //> res0: Int = 12
Or with lambda:
def add_lambda = (x:Int,y:Int) => x+y           //> add_lambda: => (Int, Int) => Int
add_lambda(5,7)                                 //> res1: Int = 12

Currying

Now Implement the same function in C#, but this time with currying:

[Fact]
public void CurryingAdd()
{
    Func<int, Func<int, int>> add = x => y => x + y;
    var result = add(5)(7);
    Assert.Equal(12, result);
}

In Scala:

def add_lambda_currying(x:Int) = (y:Int) => x+y //> add_lambda_currying: (x: Int)Int => Int
add_lambda_currying(5)(7)                       //> res2: Int = 12

With simplified Scala syntax:

def add_currying(x:Int)(y:Int): Int = x+y       //> add_currying: (x: Int)(y: Int)Int
add_currying(5)(7)                              //> res3: Int = 12

Partial apply

Now let’s suppose I want to bind the first parameter to a concrete value (bound) but I want to keep the second parameter unbounded (free).

This is the way in C#:

[Fact]
public void CurryingAdd_Add5()
{
    Func> add = x => y => x + y;
    var add5 = add(5);
    
    var result1 = add5(7);
    Assert.Equal(12, result1);

    var result2 = add5(122);
    Assert.Equal(127, result2);
}

The same idea in Scala:

def add5_lambda_currying = add_lambda_currying(5)  //> add5_lambda_currying: => Int => Int
add5_lambda_currying(7)                         //> res3: Int = 12

def add5_currying = add_currying(5) _           //> add5_currying: => Int => Int
add5_currying(7)                                //> res5: Int = 12

In case of the add5_currying example please notice the underscore (_) at the end of the expression. That means partial apply and indicates that I don’t want to bind the second parameter. There is no need for such indicator with lambda syntax.

Wednesday, April 17, 2013

Unit testing a Powershell Commandlet

I chose to write Powershell commandlets in C#. I created a class library (DLL) project and inherited a class from Cmdlet base class. I created a snapin class derived from PSSnapIn to be able to install my commandlets from powershell.

Unit testing

Writing a unit test

[TestClass]
    public class UnitTest1
    {
        private static RunspaceConfiguration config;
        private static Runspace runspace;
        private static Pipeline pipe;
        private static Command command;

        [ClassInitialize]
        public static void TestFixtureSetup(TestContext context)
        {
            config = RunspaceConfiguration.Create();

            PSSnapInException warning;
            config.AddPSSnapIn("SnapinName", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();
        }

        [ClassCleanup]
        public static void TestFixtureTeardown()
        {
            runspace.Close();
        }

        [TestInitialize]
        public void Setup()
        {
            pipe = runspace.CreatePipeline();
            command = new Command("CommandName");
            pipe.Commands.Add(command);
        }

        [TestMethod]
        public void TestMethod1()
        {
            command.Parameters.Add(new CommandParameter("ParameterName", "Value"));

            var psObject = pipe.Invoke();
        }
    }

Snapin couldn't be found

I wrote a unit test against one of my commands but it couldn't find my snapin, I got the following exception:
System.Management.Automation.PSArgumentException: System.Management.Automation.PSArgumentException: The Windows PowerShell snap-in '...' is not installed on this computer..

I could use my snapin from Powershell command line.

Solution

Add the following lines as post-build events:
c:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe $(TargetPath)
c:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe  $(TargetPath)

Both 32-bit and 64-bit installation will happen this way.

Cause

Visual Studio 2012 is a 32-bit process. I registered with 64-bit install util only. Now I register both versions.

Tuesday, September 4, 2012

Ember–Handlebars.helpers in Windows 8 Metro

I tried to use Ember.js Handlebars helper {{action}} in a Windows 8 Metro (Windows Store) application. The data marker attribute appeared, but the function was never called.

I managed to find the root cause: Ember.js uses jQuery.ready() for initialization.

Solution

Change

waitForDOMContentLoaded: function() {
    this.deferReadiness();

    var self = this;
    this.$().ready(function() {
      self.advanceReadiness();
    });
  },

to

waitForDOMContentLoaded: function() {
    this.deferReadiness();

    var self = this;
      
    WinJS.Application.addEventListener("ready", function () {
        self.advanceReadiness();
    });

  },
and comment out 2 lines as shown below:
advanceReadiness: function() {
    this._readinessDeferrals--;

    //if (this._readinessDeferrals === 0) {
      Ember.run.once(this, this.didBecomeReady);
    //}
  },

Now you will use the Metro infrastructure for events.

Sunday, September 2, 2012

Handlebars and Ember templating in Window 8 Metro

Handlebars uses script blocks for template markup. E.g.

<script type="text/x-handlebars" data-template-name="say-hello">
      Hello, <b>{{MyApp.name}}</b>
</script>

Unfortunately the Metro JavaScript engine removes the data-template-name attribute from the script tag, so this method can’t be used for templating.

As JS files are available locally for execution, the template files can be stored in separate HTML files and can be parsed from code. The implementation is simple:

        

Windows.ApplicationModel.Package.current.installedLocation.getFolderAsync(path).done(function(folder) {
    var search = folder.createFileQuery(Windows.Storage.Search.CommonFileQuery.orderByName);
                search.getFilesAsync().done(function (res) {
                        res.forEach(function (file) {
                                var template;
                                Windows.Storage.FileIO.readTextAsync(file).then(function(fileContent) {
                                       var template = Ember.Handlebars.compile(fileContent);
                                       Ember.TEMPLATES[file.displayName] = template;
[…]

I omitted the async promises from the code for readability, but the code won’t work without them.

The code above

  1. reads all the files from a folder
  2. compiles the template
  3. stores the compiled template as an Ember template

Now Ember.js and Handlebars.js are fully functional, even Ember.View can be used with view.append().

Thursday, April 12, 2012

Git: create a tag on a (remote) branch

You can create a tag on the local branch and you must push the tag to the remote.

Command line

> git tag …

> git push --tags

TortoiseGit

  1. Create tag
    1. set tag name
    2. set tag/branch/version
    3. enter message
  2. Sync/Push
    1. Select Push tags instead of Push button in the dropdown

Git Extensions

  1. Browse
  2. Right click on the commit log you want to tag
  3. Select Create new tag
  4. Enter data
  5. Push
    1. Select Push tags tab

Friday, February 10, 2012

Hate JavaScript?

Do you hate JavaScript? Well, I have bad news. There are still no alternatives in the web browsers.

I develop ASP.NET (MVC) –based web applications, and I must use JavaScript. What’s the big difference between the modern web applications and websites from a few years ago? Well, the server-side/client-side ratio. A few years ago I was happy coding on server-side. I did as much as I could do in C#, in ASP.NET. I did learn JavaScript but I avoided it as much as I could (so I never knew it well enough).

Now you can’t avoid JavaScript anymore. More and more code is on client-side. More and more business logic and architectural challenges are on client-side, right in the browser. I’ve written database-like features and even messaging systems in JavaScript. That challenge reminds me the early days of other languages. Missing features, missing language support, missing best practices, missing design patterns. Pure greenfield tasks.

How well do you speak JavaScript? A few years ago it was enough to understand how to define a function and some variables. Learn how DOM works. How different DOMs work. That’s not a small thing if you did it well. But did we write good, quality code with low bug ratio and good manageability? I’d say no.

A few years later there came the object-oriented world to JavaScript. We, I personally, had to learn the idea behind prototype-based languages. That’s a hard step with a ‘real’ object-oriented (Java, C#, C++) mindset. How can I implement inheritance? How can I hide data? How can I achieve polymorphism? Tough questions. Luckily along came design patterns. There are even a few books on the topic in JavaScript. Still, it’s not easy. I personally can recite 4-5 inheritance patterns. There are at least 2 data hiding patterns I can recall right now.

Well, many options, with their own drawbacks. It’s not easy to choose, e.g. at the beginning of a new project. There is no universal solution. There is no good solution. You have to consider the tasks you have to do with your object model and the knowledge level of the colleagues. Usually the later is harder. How much knowledge people have about JavaScript in e.g. Java/C# world? As much as they get along the projects. They teach each other.  To good and bed. What I saw in the last years, mostly obsolete and sometimes bad. Not easy to show them the current trends and solutions. Or may I say, contemporary engineering practices. People can, and usually are, be very proud of their coding style, quality, cleverness, etc. How can they be so neglect on these in an other language, e.g. JavaScript?

Now there are frameworks for DOM manipulation (jQuery, dojo, YUI), for common tasks (Underscore, YUI, Closure), and there are architectural frameworks (Knockout, Backbone) as well. As you can see, they are fractured and you must use different frameworks for different tasks. You should choose well because it’s very very hard to change frameworks, and you have to watch out for compatibility. Framework version changes represent huge risk in the lifetime of a project. Even a minor version change can render your web application totally useless. So test heavily.

No we have two ways. Full manual testing with a lot of humans. Or follow the ‘new’ trend and use some kind of automated test frameworks (Selenium, Watir). If they work the way you think. If it’s not more time to maintain your tests than execute them manually.

The same applies to unit tests. There are various frameworks in different flavors (xUnit, BDD, etc.) with different capabilities and APIs. Some live long, some live short. Choose well. Update regularly. Follow the news, trends.

Well, I chose a unit testing framework. Now I should test my code. How? It produces HTML into the DOM and calculates things according to different business rules – in the same function. Well, good luck. Try separating your business logic from visual stuff. Rings the bell? MVC? MVVM? Well, I’d say Knockout and Backbone. I’d say use (revealing) module pattern for your view model and your rendering as well. Separate them. Use a framework, e.g. Require.js. If you do it good, you can even get rid of the inheritance and other OO problems. Now you can test your business logic separated from the UI.

Next problem: I have a dynamic AJAX (AJAJ - Asynchronous Javascript and JSON) application calling back to the server. That’s not good. Let’s spy. Let’s stub.  Let’s mock. Find a framework, I chose Sinon.

So, let’s summarize. I do my job well if I know functions, variables, OO patterns, DOM frameworks, task frameworks, architectural frameworks, testing frameworks, module patterns, JavaScript mocking frameworks. Is that enough?

I have bed news. We in the web world develop applications like C++ coders develop applications for Windows, Linux, BSD… at the same time with the same code base. Instead of OSs, we have browsers and JavaScript standard versions. Now we have mobile devices as well, with different kind of browsers. So keep up, learn and write code in JavaScript. It’s better to learn and understand it than hope for surviving it. The next few years are about JavaScript and the Web. Get used to it, accept it. Do it as good as you do your job on server-side.

Thursday, January 19, 2012

jQuery div vs native doc fragment

I assumed creating a div with jQuery takes more time compared to native document fragment creation. Surprise, I was wrong. I’ve created a test page on JSPerf at http://jsperf.com/jquery-vs-documentfragment. Simply put, the speed depends on the browser.

Verdict: Use document fragment in all browsers except Internet Explorer. In general, use document fragment:

document.createDocumentFragment();

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.

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. 

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

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)