RX Example

Just an update to the doc with the Rx tutorial:

Newer versions of Rx need a small change to the source code:

Observable.FromEvent<EventArgs>(txt, "TextChanged")

Changes to

Observable.FromEventPattern<EventArgs>(txt, "TextChanged")

And the references are:

System.Reactive.Core
System.Reactive.Interfaces
System.Reactive.PlatformServices
System.Reactive.Linq
System.Reactive.Windows.Forms

Rx is available on Nuget
I found the example easier to understand by rewriting a couple of statements:

var textChanged = 
       from evt in Observable
          .FromEventPattern<EventArgs>(txt, "TextChanged") 
       select ((TextBox)evt.Sender).Text; 

var input = textChanged 
            .Throttle(TimeSpan.FromSeconds(1)) 
            .DistinctUntilChanged();

As

            
var input = Observable
            .FromEventPattern<EventArgs>(txt, "TextChanged")
            .Select(evt => ((TextBox)evt.Sender).Text)
            .Throttle(TimeSpan.FromSeconds(1))
            .DistinctUntilChanged();

And

var res = from term in input 
          from word in matchInWordNetByPrefix(term)
          .TakeUntil(input) 
          select word;

As

var res = input.SelectMany(t => matchInWordNetByPrefix(t)
               .TakeUntil(input));
Posted in C# | Tagged , | Leave a comment

Embedding a Python Interpreter in Java – Jython

So here is the other half of the code – the Java test end
(Note Test Class in this case is a simple Java class with a property (string) Value)
(The real case would not use propertis due to the access differences between .net and Java – the script needs to be consistent over each environment in the real case):

import org.python.util.PythonInterpreter;
import org.python.core.PySystemState;
import org.python.core.PyObject;
import org.python.core.Py;

public class Prog {

  public static void main( String[] args)
  {
    try{
      PySystemState.initialize();
      PythonInterpreter interp = new PythonInterpreter();

//this is the python program as a string
//miss the package (from JythonTest) and it works up till
//casting it back to a JavaClass -> __tojava__ fails....
      interp.exec("from JythonTest import TestClass\n" +
                  "\n" +
                  "def MakeOne():\n" +
                  " return TestClass()\n" +
                  "\n" +
                  "def Update(item):\n" +
                  " item.setValue( \"Hello World\")"
      );

      PyObject makeOne = interp.get("MakeOne");
      PyObject update = interp.get("Update");

//this calls the python function MakeOne 
//declared in the python code
//where TestClass is a Java class

      PyObject jc = makeOne.__call__();
      update.__call__(jc);

      TestClass jjc = (TestClass)jc.__tojava__(TestClass.class);

      System.out.println(jjc.getValue());

    } catch(Exception ex){ ex.printStackTrace();}

  }

}
Posted in Python | Tagged , , , | Leave a comment

Embedding a Python Interpreter in C# – Iron Python

I needed to be able to execute scripts in two client applications. One was written in Java the other in C#.
The script needs to manipulate classes in the language the interpreter in embedded in.

This program works with IronPython 2.7.

You need to reference
IronPython, IronPython.Modules, Microsoft.Scripting and Microsoft.Scripting.Core

The example below is a simple test – it loads a string with a script in in and then makes use of it
(Note Test Class in this case is a simple c# class with a property (string) Value):

using System;
using System.Collections.Generic;
using System.Reflection;
using IronPython.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;

namespace EmbeddedPython
{
  class Program
  {
    static void Main(string[] args)
    {
        ScriptEngine _eng = 
           Python.CreateEngine((Dictionary<string,object>)null);

        _eng.Runtime.LoadAssembly(
        Assembly.GetAssembly(typeof(EmbeddedPython.Program))
      );

      ScriptScope scope = _eng.CreateScope();
//this is our python program as a string
      string importText = @"
from EmbeddedPython import TestClass

def MakeOne():
  return TestClass()

def Update(item):
  item.Value = ""Hello World"" 
";

      _eng.CreateScriptSourceFromString(
        importText,                                    
        SourceCodeKind.Statements
      ).Execute(scope);

      Func<TestClass> makeOne = 
          scope.GetVariable<Func<TestClass>>("MakeOne");

      Action<TestClass> update = 
          scope.GetVariable<Action<TestClass>>("Update");

      TestClass instance = makeOne();
      update(instance);

      Console.WriteLine(instance.Value);

    }
  }
}

Posted in Python | Tagged , , | Leave a comment

More on F# Units

Another wonderful thing about units in F# is that you can specify conversions.

Consider the following:

[<Measure>]
type s

[<Measure>]
type m

[<Measure>]
type v = m / s

let v1 = 1<m>
let v2 = 1<s> 
let v3 = 1<v>
let V = (v1 / v2) + v3

The sum at the end works because the compiler can convert from v to m/s

Posted in F# | Tagged | Leave a comment

EntityFramework DbContext Template Namespaces

I seem to be seeing something odd in EF. I have a working project that has a data model (.edmx) that was built from the database, with code generated using the DbContext template. The object model was then edited (introduction of inheritance, associations not in the database and some complex types). Still Working…

Ok, so the plan is: to drop the code generation and use the generated files as the basis for the object model.

A closer look at the files revealed this: the generated files were in the default namespace for the project the .edmx was in, not the proposed namespace in the .edmx properties.

namespace Repository;
{
    public partial class Order
...

Not really a big issue – change the namespace of the  files and edit the .edmx.

But when I look at the contents of the .edmx I see things like…

<EntityType Name="OrderListedInstrument" 
                    BaseType="ObjectModel.Order" 
                    Abstract="false" >

and

<Property Name="InstrumentSummary" 
                  Type="ObjectModel.InstrumentSummary" 
                  Nullable="false" />

Where Object model is the represents originally intended namespace.

How on earth does that work? Because it is working – is EF just ignoring the namespaces when it creates objects? There is no classes with those names in the given namespace…

Posted in EF | Tagged , | Leave a comment

F# Spec

This might be in one of the books on F# floating about, but if it is I never noticed it.

This example is copied from the F# spec

[<Measure>] type kg 
[<Measure>] type m 
[<Measure>] type s 
let gravityOnEarth = 9.81<m/s^2>
let heightOfTowerOfPisa = 55.86<m> 
let speedOfImpact = sqrt(2.0 * gravityOnEarth * heightOfTowerOfPisa)

 So what is so exciting about this? It’s not that you have set units on the first two values, it’s that F# works out the units of the last calculation:

val speedOfImpact : float<m/s> = 33.10548595

 How cool is that?

And it checks the units in calculations – so you can’t add a length to a weight if the values have suitable units… YO!

Posted in F# | Tagged , | Leave a comment

Odd Excel Macro Behaviour with Date Formats

Just to make the day complete, part of the system we were updating had a bug raised against it by another team. The module in question imports data from excel spreadsheet files that are based on a standard template.

The issue for the other team was that they worked with data that was to be imported in a completely different spreadsheet format. To import their data they had implemented a VBA macro to copy the data from their sheet to another in the template format.

The issue was that the date columns were not importing properly. (They looked right.)

The ODD thing that we found by accident was that if we opened the sheet to look at it, and then closed it, Excel asked if we wanted to save the changes (?). If you save the changes, the sheet imports without issue.

Looking at their VBA, they were setting a numberformat of dd/mm/yyyy on the cell. So the code would look a bit like:

cell.value = CDate(value)
cell.NumberFormat="dd/mm/yyyy"

Removing the number format also fixed the issue….

Posted in Uncategorized | Leave a comment

Missing COM Callbacks

This was an odd one. A very simple piece of code failed on the server, but as usual works on our machines.

The c# code in question looked a bit like this:

void GetComToDoStuff()
{

    comObjectInterop.Event += MyCallBack;

    comInterop.StartDoingStuff();

    _manualResetEvent.Wait();

}

private void MyCallBack( bool finished)
{

    if(finished) _manualResetEvent.Set();

}

MyCallback gets called several times during “processing”, and is called with finished set to true once processing is complete.

The problem was (with added logging) on the server, MyCallBack was not being called for every record the com object processed. It would get called for several of them and then no more, so the last call would never arrive and release the initial call from the manual event.

FWIW the only solution (and why it worked on our machines) was the issue vanished for Debug builds.

Now our best guess for now, is that the delegate object created to handle the callback has been garbage collected early in the Release build.

So yes we have tried keeping the reference to the delegate alive by creating it in a local variable before assigning it, and doing something trivial with it after leaving the Wait, using GC.KeepAlive, turning off optimisation. No Joy. But repeatably, debug builds work without error, and release builds always fail. (Even on our machines)

Edit  And the fix is…

void GetComToDoStuff()
{
    var callbackhandler = new HandlerType(MyCallBack);
    comObjectInterop.Event += callbackhandler ;

    comInterop.StartDoingStuff();

    _manualResetEvent.Wait();

    comObjectInterop.Event -= callbackhandler ;

}

private void MyCallBack( bool finished)
{

    if(finished) _manualResetEvent.Set();

}

I guess it gives the GC a reason to keep it around, plus it’s good practice

Posted in Uncategorized | Leave a comment

MissingManifestResourceException

The problem was an odd visual studio 2010 solution that shared some code between a silverlight front end and a full fat .Net server.

The silverlight project with the shared code contained the shared code as references to the files in the original project. It also contained the resources file and the generated designer – the resx was set to be included in the assembly with no code generation.

It worked fine with the code in the Silverlight client project that called it. The issue was when it was called from unit tests. The result was an unglamorous fail with a MissingManifestResourceException on the tests that made use of the resources.

The fix is simple – setting the default namespace in the silverlight project to the same value as the one in the original .Net project that the files were really in.

Makes me think I need to know more about the initialisation of the resources classes.

BTW the stack trace contained a reference to a most excellent Microsoft classname – the resourcegroveller (!)

Posted in Uncategorized | Leave a comment

Working with Databases in Visual Studio 2010

Having had a less than happy time with the Database Project in Visual Studio 2010 I can report that I have found a workable alternative.

  1. Create Database (DEV version) (However you like)
  2. Use Sql Server Management Studio to generate an initial build script
  3. Create a second (Reference version) copy

make changes in the DEV version

  1. Use Visual Studio’s schema compare with most of the non schema comparisons turned off to compare with  the Reference DB
  2. Generate a change script, save it with a name including the version number
  3. Use SSMS to generate a creation script and save that over the original
  4. Commit to version control

So from then on you can either upgrade a prod database or create one from scratch. Not as nice a the Redgate tools but much cheaper…

 

Posted in VS2010 | Tagged | Leave a comment