Create An X Delimited String From A Char List Using Linq Aggregate

A quick example of how to use the Aggregate method to create a string of delimited members, or in this case characters. You might wonder why this example, or at least you should. It’s true, the character list to delimited string is pretty useless, but some idiot from where I work needed it.

[TestMethod]
public void GetStringFromCharacters()
{
    var charList = Enumerable.Range(0, 10).Select(x => 'a').ToList();

    charList
        .Aggregate("", (inner, outer) => inner + outer.ToString() + ",")
        .Should()
        .Be("a,a,a,a,a,a,a,a,a,a");
}

The big thing here is the “” in the Aggregate method signature. That basically says that Inner is a string. If I didn’t have that specified, both inner and outer would be a character.

YAY

Why are things made so complicated in web design?

Ever since Linq came out over 3? years ago (Earliest post about it that i have was from June 25 2008) I’ve been madly using it as much as I possibly could. I didn’t find it to be just some kind of syntactical sugar, or at least I learned it wasn’t eventually. Which? I don’t remember and really it doesn’t matter. Point is I’ve been a huge proponent of it and the various fun that came with. (Func, Action, anonymous types, ect) Now I had heard that it was based on functional programming but I had no real idea what that meant. It was just some kind of programming cultists and people with tin foil hats use. Let’s be honest, in the “Beer league” of programming, there was no respect for it.

Now flash forward a couple months ago when I went on a painful trek as I tried to find a language that could do more then what C# could handle. Far as I was concerned, I had out grown it. Like VGER (And Spock for that matter) I had outgrown the world of C# and needed something more even though I wasn’t sure what that something was. “It knows only that it needs, Commander. But, like so many of us… it does not know what.”

I thought I could find satisfaction in a new language even though I had failed before at that. I looked into Ruby, Scala, Python (Again), Boo, but something just didn’t take. It wasn’t long before I realized that they are ultimately like C#. Sure some are dynamic, some are intelligently typed, but in the end they were the same. It was just a question of how I liked the language to look, but not how things were done. Meet the new boss, same as the old boss.

It was at that point I decided to just put my shoulder down and start running toward the unknown. Toward a functional language. My first stop was F# and it was surprisingly amazing. I finally found a language that would make me keep up and not the other way around. I put a ton of time into it for 3 months, but stopped. It wasn’t the language itself, the functional design, or performance. It really came down to the half —ed implementation that The good professor Microsoft decided to eh… implement. File structure (Or literally lack thereof) was painful. It’s inability to use the built in MSTest UI was even worse. To add to that, the only way I could get a nice debug enabled testing framework was through Resharper and even then I’d have to run every test in an assembly before it would add it to the suite. Add in it’s failure to work with Entity Framework without a third party library, Power Pack and well FFFFFFFFFUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU…

Ok… So I think you might get that I am a little bit mad about the situation. The reason isn’t that I’m trying to be an -ss but I REALLY LIKED F# AND THINK IT DESERVES BETTER THAN JUST TO BE SOME LAME -SS SIDE PROJECT.

I’ve learned this lesson before though and I just stopped bothering… at least three times until last Tuesday when I really, for really, not joking this time, quit F# for good. Yeah I’m not good at giving up on things.

Annoyed and looking for something to fill my need for functional languages, I decided to go all out. If I’m going to be functional (Programming functional not as in functional alcoholic) I’m doing it the full way. That’s right, I have turned to Lisp… just kidding. I am going full Haskell. Yes that language that is never talked about in name lest it release some demon or some weird looking dude when said three times in front of a mirror. That Haskell. Even before I knew what a functional language was, I had heard of it and was told to never look it in the eye and to keep on walking. I’m not sure why there is so much fear and secrecy around Haskell. I realize that, as the old cliche goes, people fear what they don’t understand, but the fear/hate people had for it seemed irrational. Like it was some kind of invading army hell bent on instilling some sort of dictatorship. I know I’m being a bit hyperbolic but the point is that people treated like it was a personal attack on programming. Like it’s existence was purely for insult and nothing else. Good thing I’m too dumb for my own good and ignored the warnings… it just took me four years to do so. (But in my defense, I hate quitting to a fault so I thought I should ride out the .Net stack.)

Now with this move it caused two problems: I had to take off the .Net training wheels and figure out how to even get Haskell to compile. The other was… How the –ck do I handle database oriented persistence? I mean for C# you have NHibernate, LLBLGEN, Subsonic, that entity thing… you get the point. There’s no shortage of ORMs for the .Net world. Tried to see if there was one for Haskell, but I started really thinking about this. One of the issues I had pondered with functional languages is how do you relate a database to objects if you aren’t really using an object oriented model. It’s quite a conundrum. (I spelled that right the first time.) I mean I’m sure you can force out some kind of object like model if given enough time, but was it really needed? To this I say no! (I think)

One of the concepts I’ve had to learn early on with functional programming is Tuples. Essentially a tuple is stuff bound together.

Could be a key value pair:

(“firstName”,”Sean”)

Could be a list of various strings grouped together:

[(“Sean”,”111 Cool Lane”,34),(“Andre”,”111 Stupid Street”,33)]

Point is, it’s stuff grouped in a like way. In fact, it has to be grouped in the same way. Take the one above for instance. It is a “list” of (string, string, integer). As long as anything added to it has the same signature, everything is great. If they don’t:

[(“Sean”, “111 Cool Lane”, 34), (1, “111 Stupid Street”, 33)]

Well… Kaboom. Now here’s the interesting part (One of many I hope): If you have a list of tuples and you squint real hard, you might mistake them for classes. After all, isn’t that what a class is? A bunch of stuff forced to be represented in a set way? If you think about it, this is basically how dynamic languages like Python or Javascript work. The “class” is just a bunch of key value pairs. You can call a property on an object like this:

something.DoStuff

Or you can do it like this:

something[“DoStuff”]

Yes it’s psuedo code and probably not 100% correctly represented, but that’s not the point. The point is that an object can be made of from key value pairs… Basically like the tuples above… and that’s where it gets really interesting.

I started to think about what would it take to represent a user. Say you have a plain user with Id, FirstName, and LastName. Well you could have a class:


public class User
{
public int Id {get; set;}
public string FirstName {get;set;}
public string LastName {get;set;}
}

Or you can have a tuple:

[(("FirstName","Sean"),("LastName","Isawesome"), ("Id", 1))]

Now here’s the funny part: I originally didn’t think the tuple representation was possible due to a possible type conflict. But sometimes in our most idiotic times there can emerge a real idea. The idea is simple:

WHY THE –CK DO WE SPEND SO MUCH TIME FORCING TYPES IF MOST OF THE TIME WE JUST NEED STRINGS!?!!

I know, it sounds odd at first but if you really think about it, does it matter if an Id is an integer? Sure in the database, but outside of it? Here’s a typical MVC round trip:

You take in a json string and turn part of it into an integer. You push that integer to a class (Model or other wise) and then use the class to transport that Id to be used as a string in a sql query or it gets converted to some other database happy type. It then is pulled back out of that database friendly type and pushed into an integer so it can hydrate a user class. Then the id is passed into a model so it can be turned into a string for html or json.

This begs the question:

WHY THE –CK DO WE SPEND SO MUCH TIME FORCING TYPES IF MOST OF THE TIME WE JUST NEED STRINGS!?!!

Think about and I mean really think about it. How often do things typed as integers (Or decimal or date or whatever the –ck you want) get used for anything but to be aimlessly typed and retyped? How often do any numbers get used for anything number related? In the world o’ web development there is very little use for numbers. Sure you might have to sum them up, but doesn’t it seem more logically to start as a string and only type when it’s needed as opposed to type something to anything but a string when all it ever will be used as is a string? It makes no –cking sense. None.

But maybe somewhere you might have to validate that the number falls within a certain range… GREAT! Convert to an integer and check!.

But maybe it has to be a proper date. –CKING GREAT CONVERT AND CHECK!

But, but what about when persisting to a database… THIS IS A GOOD REASON… eh to convert.

If there’s anything I’ve learned from the newfangled ideas of lean and such; it’s that you build only what you need. Don’t over complicate. Don’t over think. Don’t pass go and collect 200$. If there is no reason to type something as an integer, then why would you? Join the revolution. We can win this one or look like complete –sses while trying. I can’t promise which, but I can promise one will happen.

This is just the begining…

Fluent Nhibernate, Linq to NHibernate, MS Test, Fluent Assertions, and a working example

So out of pure curiosity I decided to go down the NHibernate path and it had nothing to do with the headache that is Entity Framework… nothing at all.

First I wanted to see where Linq to NHibernate was at after hearing about it years ago. Turns out it’s doing pretty well… and actually works thanks to this link. So with that in mind, I also wanted to check out Fluent NHibernate since I had somehow knew it was a project created with the hope to remove the config files NHibernate used. (No idea how I knew that, must have known someone who used it.) Well just so I could be completely wild, I just decided to try out Fluent Assertions which is a library used to help MS Test assertions to be readable. Crazy idea I know.

Well after a bit of reading and a couple hours of work, I came up with a working example of them all in one project. Go me.

Here it is.

Only thing you need to do is have a database handy and open up the “~\NhibernateTest\NhibernateTest\NHibernateHelper.cs” file and set the Username, Password, Catalogue, and Server name. Then just create a database (But not the tables) that corresponds to the values you entered. Now the nice thing is that the first time you run any of the tests, it (Being Fluent NHibernate) will create that tables and columns needed. This is something that works a lot like Active Records for Ruby. This behavior is controlled by:

.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))

The second True is the important one. If you keep that True, it will drop and recreate the tables every time you run a test. Change it to False and it will stop doing that.

Just keep in mind I’m not presenting any Best Practices here. This is an example but not exactly production ready.

F#: How F# doesn’t require specifying parameter types in the method signature.

Found this one by mistake when I was trying to figure out how to declare optional parameters in F#. So a typical method signature would be something like this:

 member public x.CreateUserPost(userName:String, password:String) =
   1 = 1

Now let’s say you have a type named LoginModel that takes in two strings in it’s constructor:

type LoginModel(userName:String, password:String) =
  ...

And the it’s added to the method:

member public x.CreateUserPost(userName:String, password:String) =
  new LoginModel(userName, password)

As you can see, LoginModel has its two parameters explicitly typed and because of this they don’t have to be explicitly typed in the method signature. With that in mind you can reduce the method signature to this:

member public x.CreateUserPost(userName, password) =
  new LoginModel(userName, password)

And that’s completely “legal” unlike the complete series of My Little Pony you have on your computer. Shameful.

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.

F# and using strings for method and class/type names

So after about 2 months of jumping back and forth between languages (Including and not only: Ruby, Python, IronPython, Boo, Scala, and a lot more I don’t remember) I’ve finally settled on F# for more reasons than I will put in this post. BUT one thing that kind of blew me away, and I realize that doesn’t take much (I thought the ending to Terminator 3 was great), was the ability to name methods with string representations… eh wha?

Well I was writing unit tests and stumbled onto the FSUnit “library” (and by “library” I mean a single file). Well on the page there was an example that looked a sumthin’ like this:

[<TestFixture>]
type ``Given a LightBulb that has had its state set to true`` ()=  
  ...

Now if you haven’t used F# just replace “type” with “class”. Essential there is a string/text built name. Not something you see, or at least I haven’t, in any old language. So I went forth and was fruitful and multipled… with unit tests… gross.

[<TestFixture>]
type public ``When Adding``() =
    let returnThing = new MethodResult() :> IResult
    let randomTool = new RandomTool()

    [<Test>]
    member public x.``A Warning Message The Success Flag Is Set To True``() =
        returnThing.AddMessage(new MessageItem(randomTool.RandomString(10), MessageCategory.Warning)).Success |> should be True

And using Resharper’s unit test box thingy it gave a read out of:

  When Adding A Warning Message  
     The Success Flag Is Set To True             Success

Now I’m not sure how useful this is for non unit testing but I think it’s obvious it is to reading Unit Test results. Pretty nice.

XUnit and Connection Strings

A real quick one but maybe a good one.

I was running the xUnit.gui.exe program to run units tests using xUnit… duh. Problem I ran into is that xUnit is not a part of the solution that the tests were. This caused issues when trying to run integration tests since the needed app.config wouldn’t be read by xUnit as the config file used when running an app is the config file from the topmost (Usually UI) project/application. So I made a wild guess that if I follow that logic, what little there may be, and add the connection strings to the xunit.gui.exe.config file as if it were an app.config/web.config, it should use the connection strings added… and turns out it did.

And there you have it… it being the solution and not a clown.

Fun with F# and Method Reduction

So the first and second methods came from this book , but I thought for fun I might reduce it further to see
how small a call could get.

Basically take a number and divide it by another number 3 times.

let bytesToGb item =
let itemB = item / 1024I
let itemC = itemB / 1024I
let itemD = itemC / 1024I

Is the same as:
let bytesToGb item =
let x = x / 1024I
let x = x / 1024I
let x = x / 1024I

And more reduction:
let bytesToGb item =
item
|> (fun x -> x/1024L)
|> (fun x -> x/1024L)
|> (fun x -> x/1024L)

Or more:
let divide x = x/1024L
let bytesToGb = divide >> divide >> divide

If you’re familiar with Func/Action, Linq, ect this might actually look a lot like some of the newer “functional like” additions to C#. Well at least the third one. Funny part, and I didn’t know this, is that most of the more interesting additions to C# (Generics, Linq, Lambda expressions) actually came from F#; Which was built to match other existing functional languages like Haskel)  Go figure.