Monday, February 28, 2011

Generic number functions in F#

I’ve been learning f# recently, it is a very powerful and elegant language and hopefully we will be using it for real development in the future. One of the first things I tried was writing a version of the classic Fizz-Buzz interview question (for integers from 1 to 100 print Fizz-Buzz if divisible by 15, Fizz if divisible by 3 and Buzz if divisible by 5).

In an effort to massively overcomplicate a trivial question I ended up defining a set of rules that could be applied to arbitrary inputs. The definition of a rule was:

  1. //a rule evaluates something to true of false
  2. type Rule<'a> = 'a -> bool

I then set about implementing the mod 3 and mod 5 rules and hit a problem. Ideally we should be able to apply our rules to any integer type, but because of the well known problem of .Net lacking an INumeric/IIntegral interface or equivalent this wasn’t possible and I ended up with separate rules for each integer type:

  1. let inline ModThreeInt() = fun n -> n % 3 = 0
  2. let inline ModThreeLong() = fun n -> n % 3L = 0L
  3. let inline ModThreeBigInt() = fun n -> n % 3I = 0I

Not very satisfactory! I really wanted a generic ModThree function that can be applied to any number that supports the mod operator. In fact we can get this behaviour using some Peano style arithmetic:

  1. let inline Mod (d : 'a) (n : 'b)
  2. = let inline zero x = x - x
  3. let inline one x = x / x
  4. let mutable cb = zero n
  5. for _ in [one d..d] do
  6. cb <- cb + (one n)
  7. n % cb = zero n

(Note we must make the function inline so it is not given a concrete type signature on first use)

The key here is are the generic zero and one functions defined in the first two lines. These give a one and a zero of type of the value they are called with. With these defined we can then increment a variable of type ‘b until it is equal to the value passed in of type ‘a. Then we can mod our value of type ‘b. Of course this is hopelessly inefficient if we are modding by a large number.

  1. //yay, we can call either of our mod functions with either a BigInt or an int
  2. //and they take either bigints or ints, no explicit casting
  3. let inline ModThree() = Mod 3
  4. let inline ModFive() = ModG 5I

After writing this I actually discovered that F# has some built in GenericOne and GenericZero functions so we could rewrite our generic mod function as:

  1. let inline ModG (d : 'a) (n : 'b)
  2. = let mutable c = GenericZero<'b>
  3. for i in [GenericOne<'a>..d] do
  4. c <- c + GenericOne<'b>
  5. n % c = GenericZero<'b>

So there we have it, a small part of a hideously overcomplicated and inefficient FizzBuzz solution, interesting though.

  1. let inline buzzFuzzRules _ =
  2. [ (Some BuzzFuzz, ModThree() &&& ModFive());
  3. (Some Buzz, ModThree());
  4. (Some Fuzz, ModFive());
  5. (None, Default)
  6. ]

Friday, February 25, 2011

‘Recursive’ includes in Oracle UCM idoc script


Recently I have been doing some coding in idoc script, the default scripting language for Oracle UCM. It’s main use as a scripting language is for generating html server-side. Using it can be frustrating as it does not have procedures and has very limited scoping of variables.

One of the fragments I wrote was a depth first enumeration of the website nodes. A recursive function is the most natural to do this, however because idoc it doesn’t have procedures and a stack this cannot be done in the normal way. The solution was to keep a counter to the current recursion depth in a global variable and store the ‘scoped’ variable at each level in another global variable which was suffixed with the current level:

        <$c="    Retrieves a complete list of nodes for a website in depth first search order (recursive)"$>
        <$c="Input variables:"$>
        <$c="    siteId : the site to search"$>
        <$c="    currentNode : the node to start from"$>
        <$c="    AllNodesRs : a result set with one column (nodeId) to add the nodes to"$>
        <$c="    level : current level of the depth first search"$>
        <$c="Ouput variables:"$>
        <$c="    AllNodesRs"$>

        <$setValue("#local","tmpNode"&level, currentNode)$>
        <$if not strEquals(currentNode,"")$>

        <$if not strEquals(currentNode,"")$>   


And to use this:


<$c="We have to set this to ensure we enumerate sections that are set to 'Contributor Only'"$>


The two key lines which store and retrieve the current node for each level of the recursion are:

          <$setValue("#local","tmpNode"&level, currentNode)$>




Of course you can write an imperative version of any algorithm but some things are more naturally written as a recursion.


NB: for deep sites you can produce a ‘stack overflow’ due to the large number of nested idoc includes.

Wednesday, February 23, 2011

Static Mutex (don’t do it)

I came across some code that was using a static mutex on a class was not static. When you call

The second time it is called it will continue even if you have a not released the mutex with 


Lots of example use a static mutex and most are fine for what they are doing, but if you copy and paste the code you may find that it does not work for you and you only find out in production as how many people write tests for this? (personal… I do write concurrency tests for some cases, but… I don't think the unit test police would mind if you didn't)

If you need to use the mutex to sync code within your process don't use a static mutex.

Did you know? You can be someone else

I often have conversations with people regarding accessing resources as another configured users, eg you may want to connect to a local / remote SQL server as a named windows user. You may want to access files or interact with a web based api.
Some people store the username and password in a config file. Well, you don't need to Smile
You need the “Act as part of operating system” security policy .
You can just call (yes, this is a test):
public static void SimpleCallAsUser()
string yourUser = @"Someone"; // Change me

WindowsIdentity wi = new WindowsIdentity(yourUser);
WindowsImpersonationContext imp = wi.Impersonate();
string currentUser = Environment.UserName;
Assert.AreEqual(yourUser, currentUser, true, "Could not impersonate");            


If you need to call remote servers or access remote shares, then the account running the code needs delegation configuring. Select the Account in AD and … (Note you do not need todo this if you accessing resources on the Local Machine)


How to make a service restart its self.

Did you know you can easly make a service re-start it’s self.
Its very simple, just make it EXIT with a value greater that 0.


Now, your service will restart its self.