F#: Use reflection to call a private or protected method

This isn’t anything ground breaking so if you are expecting it to be, tough luck. The world doesn’t revolve around you. It revolves around me.

Making the switch to F# has caused me to redo a lot of older framework stuff and using reflection to call methods is part of that stuff. I could sit here and go on about something and waste your time, but I’ll be nice this time.

open System
open System.Reflection
 module ReflectionUtility =
  //This is used to make sure the GetMethod method doesn't skip private or protected
  let public BindingFlagsToSeeAll =
    BindingFlags.Static |||
    BindingFlags.FlattenHierarchy |||
    BindingFlags.Instance |||
    BindingFlags.NonPublic |||
    BindingFlags.Public;

  type MethodReflection public() =
    //Get the method by the method name from the class type
    member private x.FindMethodInfo<'targetClass>(methodName:String, source:'targetClass) =
      (source.GetType()).GetMethod(methodName, BindingFlagsToSeeAll)

    //Call the find method and run the found method
    member public x.ExecuteMethod<'returnType, 'target>(source:'target, methodName:String, argTypes:Type[], args:Object[]) =
      let info = x.FindMethodInfo(methodName, source)
      info.Invoke(source, args) :?> 'returnType

As you can see, this is extremely easy and short to use. I would suggest adding in some sort of caching if you are using this for anything that needs performance as I’m pretty sure reflection is still somewhat expensive. Most likely if I were caching anything it would be the method info.

If you’re new to F#, or due to an unfortunate turn of events ended up here, you might be wondering what all that ‘word stuff is or how the hell FindMethodInfo is returned

Well the ‘ notation is simply the way F# defines generic types.  It may look odd compared to C# but one nice thing is you never have to worry that your generic constraint might mirror the name of a variable/parameter/field.

The FindMethodInfo does have a return.  F# assumes that the last line in the method is the return.  This is really nice feature that saves a little bit of time by not having to type Return.  The other nice thing about it is that F# will infer the method’s return type by the last line so you never have to type out the return type for a method:

C#:

  public string ReturnString()
  {
    return "";
  }

F#
  member public x.ReturnString() =
    ""

And that’s one reason why all the cool kids use F#.

F#: Creating your own mocks using Object Expressions… Wow

This just in from the “Wow, I can’t believe how easy this is” update desk:

You can roll your own mocks “dynamically”, even when mocking an interface. No, this isn’t too good to be true. No that weird tingling isn’t from your bullsh@# meter going off. (But you really should get that tingling checked by a doctor) This is F#. And this isn’t SPARTA!!! AHRHARHARHRAhRHARHR SO FUNAY!11

Say you have a test method that wants to call a method Validate on the Validator : IValidator class. Here is the IValidator class:

  type IValidator<'a, 'b> =
    abstract AddValidationMethod : ('a -> MethodResult<'b>) -> IValidator<'a, 'b>

(Side note: the ‘a and ‘b are just F#’s generic notation. Generic members are preceeded by a ‘)

Somewhere in your code this IValidator is called by someone, say a controller action:

  member public x.LoginPost(userName:String, password:String) =
    let loginModel = new LoginModel(userName, password)
    let result = x.ControllerValidator.Validate(loginModel)

And of course you would have a controller definition look like this:

  type MainController(validator:IValidator<LoginModel, LoginModel>) =
    inherit Controller()
      member private x.ControllerValidator with get() = validator

So you are set up for mocking.

There are three way, but if you’re already bored (And I assume you are) then just go to 3.

1) Mock the IValidator

As you can imagine, this could be obnoxious to mock up as the AddValidationMethod is adding a method that takes in ‘a and a MethodResult<‘a> and then returns an IValidator<‘a, ‘b>. Can it be done? I would asssume so, but there is another way.

2) Create a new class (Class file) that implements IValidator.

This is the most simple way of doing it. You just make a class that implements IValidator and just pass back what you want. Problem is: This isn’t very reusable as it is now a static class.

3) Create a class on the fly.

And this is the good stuff. F# allows the creation of a class (That implements an interface) “inline”… not sure what word I’m looking for so just go with it.

  let validatorWithFalseReturn = 
    { 
      new IValidator<'a, 'b> with
        member x.AddValidationMethod(methodToAdd:('a -> MethodResult<'b>)) =
          new Validator<'a, 'b>() :> IValidator<'a, 'b>

        member x.Validate(model:'a) =
          (new MethodResult<'b>()).AddErrorMessage("")
    }

    let mainController = new MainController(validatorWithFalseReturn)

(Side note: you might see the :> notation. This is basically the same as (SomeInterface)SomeClass in C#.)

As you can see, I created a new type and set it into the instantiated controller. As you can imagine, you could create a method that takes in a method to set AddValidation to. This has some really great potential like rolling your own mocking system.

So once again F# is looking to be an amazing language.

F#: Duck typing with generic constraints and why you will be speechless

So I’ve been working on a validation design that basically allows validation methods to be added to a list and then run. A small part of it:

    member x.Validate(valueToCheck:'a) =
      methodList 
      |> Seq.map (fun (methodToRun) -> methodToRun(valueToCheck)) 
      |> Seq.reduce (fun(outer) inner -> outer.MergeResults(inner))

What this is saying is take a list of methods, run them and make a list of their results, then merge the results into one. While I won’t get into what the results are (And I almost typed that as resluts which makes me think there is a refurbishing factory for sluts.) just know that each result can merge with another and combine values.

The biggest problem I was running into was a way to allow any method to be added and let the method decide what it needs to run correctly. In C# this can be done easily with dynamic:

  public static MethodResult ValidatePasswordExistence(dynamic modelToCheck)
  {
    var returnResult = new MethodResult(); 
    if (string.IsNullOrEmpty(modelToCheck.Password))
    {
      returnResult = returnResult.AddErrorMessage(UserError.PasswordIsNullOrEmpty);
    }

    return returnResult;
  }

The use of a dynamic parameter means that all validation methods can have the same signature which makes it really easy to send the same class into any method in the list. The problem with F# is there is no ready way to use dynamic and I’m not sure it should be. F# is heavily based on typing and dynamic kind of goes in the opposite direction. So I thought my ship was sunk, that is if I had a ship to sink and said ship hand’t sunk already.

Thanks to some help from the O, i was able to get past this not only without dynamic, but a way to strongly type any object coming into the method:

  let inline UserNameExists (userModel) =
    let userName = (^a : (member UserName : String with get) (userModel))

    let result =
      match userName with 
        | null -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | "" -> (new MethodResult()).AddErrorMessage(UserErrors.UserNameIsNullOrEmpty)
        | _ -> new MethodResult()

    result

The important part is the second line. This line basically says that anything coming into the method as userModel has to have a property of UserName. One of the dangerous issues with dynamic is there are no compile time checks to make sure that any object going in will have the property or method you need it to. This isn’t true of F#. You not only get to pass in any object you want (That has what is required by the check) but you get complile time errros if you try to pass in an object that doesn’t fit the requirements.

Yup, that’s right. You’re speechless.

Culture shock of scaling back from full-time work…

As a blessing, my husband recently got promoted to full-time status at his job.  This meant that I was able to leave my full-time job that was interesting, but demanding and stressful.  After a few weeks of re-calibrating and getting a lot of home projects finished, I found that I really missed writing and coding.  I wrote a few simple things to get warmed up, but I’m really glad that I did because it’s breathtaking how quickly those skills will slip if you don’t use them often.

I, like many young (okay, youngish) moms with kids in school, would like to find something useful and if possible profitable to do in the 6 or so hours a day while the kids are away.  I’m finding that getting part-time or freelance work isn’t as easy as I thought.  The consensus that I’ve read has been that for the most part, you’re going to have to tap all your network of peers/friends/family to get leads then start out working for little to no pay in order to build a reputation.  I pretty much suspected this, but what I didn’t fully realize is something my sister brought up:

“Contracting/consulting can be awful in usually two ways: 1) What is available is the bottom of the barrel, makes no sense, and nobody else will work on it.  2) The project is interesting, but it has become a steaming pile of spaghetti code and they want you to wave your magic mouse and have it all fixed two weeks ago for next to nothing.”

So… here’s my dilemma.  I want to be able to work part-time or telecommute so that I can keep my 10+ years of experience and skills sharp, but I would like to eventually get paid.

What I can’t understand is why more companies don’t allow their IT employees to have more flexibility provided that they well document the work they do and get it in on time.  Especially because office space is a premium and gas prices are through the roof right now.  In Pittsburgh, we have spectacularly bad traffic and highway infrastructure.  If business owners know how expensive it is for employees to commute/park/bus downtown, why don’t they give them the option to take a small pay cut and telecommute?  Both sides win that way.

Anyway, in the meantime while I’m fishing for contract leads, I’d like to start developing some small bite-sized projects.  jQuery and Javascript are good and familiar to me so far, but do the readers have any suggestions?