Sunday, December 18, 2011

JavaScript Maybe Monad

So for a while I’ve been working on a maybe monad implementation for JavaScript and have made decent headway, or so I thought.  My previous attempts have been decent however they require the use of the new operator which is BAD for memory utilization and allocation.  As a point of reference here’s my first go at it.

As you can see its very verbose and uses the this operator with impunity. Great or so I thought until I learned how 'the good parts' of JavaScript. Since learning a better way of writing JavaScript I've been struggling how best to write a maybe monad that will natively 'just work' without having to use new or engineer in other special stuff. I was inspired by the functional elements of JavaScript and using closures and prototype definitions on Function to make it work 'out of the box'. So here we are :)

Sunday, August 21, 2011

jQuery page load

I’ve been struggling as of late on how best to create a solid page that dynamically loads data and renders the majority of the DOM client side through jQuery templates.  My reasoning for this is two fold.

1. To increase the page load time to the client
2. Simplify server side code.

On the first point, coming from a dev shop that has traditionally had zero ability to create well defined and clean HTML I wanted to try and separate as much as possible the responsibilities in UI code from the rest of the code base.  Since jQuery templating is beyond easy to do it seemed only natural that it could tie together through ajax the UI and the Server.  This created a great solution but had a byproduct that was unacceptable.  A slow page load time. 

On the second point by simplifying server side code there is far far less of a chance of bugs occurring if there is less server side code.  Also if UI code is not a part of the calls one could easily automate and interact with the server side API without having to interact with the site.  This creates implicitly a RESTful style API (at least in my case) for myself and third parties to operate with.

So, how to solve my problem?  I started with Google and I found this.  Take a second to read it.  Seriously.  I’ll wait.

Now, the author brings up some great points + benchmarks (which I love to see), but he didn’t directly solve my problem.  How do I use his method of making calls initially on the page whilst still handling all of my renderings client side.  That’s where this method made a little more sense.



The method is simple, do the ajax call at the top of the page before the bulk of the DOM is loaded and then injecting the elements when the page is ready.  Since javascript natively handles closures the data returned is persisted till after the $(document).ready event fires.  This means that the document can process all of this as soon as it becomes available rather than waiting for the ajax call to finish giving the UI render lag.

I have a few more ideas on how I can more efficiently render elements as they become ready but my knowledge of jQuery isn’t quite there yet on the subject, but I’ll post up my solution when I can prove the idea out.  Till then, hope this helps.

Thursday, February 17, 2011

Active Patterns in F#

There are few times when I learn a language when I just stop and say “cool”!  Active patterns gets this type of response.

Recently I was perusing the F# category on stackoverflow.com when I came across a problem with Discriminated Unions, you can read it here.  The problem in a nutshell is two members of the union represent the same type and the individual asking the question wants an easy way to evaluate the types A and B the same, say using distinctBy. 

type u = { str : string }

type du =
    | A of u
    | B of u

Since A and B represent the same data type u it becomes cumbersome to apply the same logic to for A and B in the same match expression.  The easiest way is to use A a | B b in a match expression, that is of course without using Active Patterns.  To define the Active Pattern used in this exercise I used the following

let (|AorB|) (v:du) =
    match v with
        | A a -> a
        | B b –> b

In essence we define a way to substitute the expression that AorB defines.  So for example we want to use a similar expression in a distinctBy you can simply supply the patter (|AorB|) rather than using the verbose match syntax.  The following will show both styles of syntax.

Way 1 (More verbose)

[A { str = "A" }; B { str = "B"}; B { str = "A"}]
    |> Seq.distinctBy (fun i -> match i with AorB c -> c)
    |> Seq.iter (fun i -> match i with AorB c -> printfn "%s" c.str)

Way 2

[A { str = "A" }; B { str = "B"}; B { str = "A"}]
    |> Seq.distinctBy (|AorB|)
    |> Seq.iter (fun i -> match i with AorB c -> printfn "%s" c.str)

While we only save ourselves the use of  a single ‘fun’ expression, the implication is quite staggering should the pattern be more than two types of evaluations.  Nice!

For more about Discriminated Unions check here, and more about Active Patterns check here.

Thursday, June 10, 2010

Visual Studio Add-Ins

Two addins that I find myself relying more and more lately are the PowerCommands and Pro Power Tools for VS2010.  Linkies to both.

Visual Studio 2010 Pro Power Tools

PowerCommands for Visual Studio 2010

Both are incredibly helpful in making the IDE better.  They aren’t for the casual dev as they add a lot of options that may not be needed for a developer still learning but they do increase one’s productivity.

The #1 feature that I love most from the Pro Power Tools is a throwback to the popular Delphi IDE’s with CTRL+Click that’s bound to the normal Right Click –> Go to Definition.

If you are a clean freak like me in your IDE the Collapse Projects available on the Solution is utterly necessary.

Enjoy :)

Thursday, June 03, 2010

Raven Db Index Management Support

One thing with RavenDb that I’m constantly fighting especially while trying to learn it is managing indexes.  I find myself constantly blowing my test database away only to recreate it, rebuild the indexes, and add new indexes as necessary.  The most common practice I’ve seen so far is to manually manage these indexes since they only need to be built once.  This doesn’t work for me since I’m lazy thus I needed a solution.

The solution which is fairly easy is to call the indexes api and parse out the returning Json.  The API I’m using if called from localhost is http://localhost:8080/indexes.  Let it be of note this is only necessary if you are using the Server/Service model.  If using this in an embedded capacity then just access the indexes directly on the DocumentDatabase object. 

I’ve created a simple extension method on the DocumentStore that will give me access to the information I want which is what indexes are created.  Making it so I can preemptively query the database as to what I already have and only commit the deltas.

Here’s the C# solution for your viewing pleasure.



public static class IndexExtensions
{
public static IList GetIndexes(this DocumentStore store)
{

var client = new WebClient();
var result = client.DownloadString(
store.Configuration
.ServerUrl
.CombineUrl("indexes"));

var t = JsonConvert.DeserializeObject(result) as JArray;
return (from i in t
select i["name"]
.ToString()
.Replace("\"", ""))
.ToList();
}

public static string CombineUrl(this string baseUrl, string appendedUrl)
{
if (!baseUrl.EndsWith(@"/")) baseUrl += @"/";

var builder = new UriBuilder(baseUrl);
Uri newUri = null;

if (Uri.TryCreate(builder.Uri, appendedUrl, out newUri))
return newUri.ToString();
else
throw new ArgumentException("Unable to combine the specified url values");
}
}

Here's the F# solution if you are interested.



type System.String with
member x.CombineUrl(appendedUrl:string):string =
let k = match x with
| x when x.EndsWith(@"/") -> x
| _ -> x + @"/"

Uri.TryCreate((new UriBuilder(k)).Uri, appendedUrl) |>
function
| b, n when b -> n.ToString()
| _ -> failwith "Unable to combine url Values"

type Raven.Client.Document.DocumentStore with
member x.GetIndexes:list =
(new WebClient()).DownloadString (x.Configuration.ServerUrl.CombineUrl ("indexes"))
|> JArray.Parse
|> Seq.map (fun (i:JToken) -> i.Value("name"))
|> Seq.toList

Monday, January 04, 2010

Windows GodMode

It what it says it is.  Simply put create a new folder say on your desktop and name it the following

GodMode.{ED7BA470-8E54-465E-825C-99712043E01C}

It’ll create an icon that will give you access to additional features some of which aren’t easily found in Windows and some that are not found at all.  Not sure how useful it is but it is pretty cool.  Windows 7 does make it all pretty but I have confirmed it does work on Windows Vista as well.

Enjoy.

Monday, October 05, 2009

Employee to Consultant

Recently we had a gentleman move from being an employee to consultant here at work.  This gentleman used to be my boss, transitioned to being our “Architect” and was thusly moved to being a consultant by extraneous circumstances.

I have recently been appointed to being this individual’s contact which means I am to track his progress and assure that it meets with our standards and is being done in a decent amount of time.  While this is certainly not an issue in my mind I wonder if it will be difficult in his at some point.

I am a no nonsense type of individual that seeks to getting the job done and if possible without any type of personal feelings.  While I will certainly voice my distain for a direction I will lead a sinking ship if asked.  With all of this I do wonder if working with this gentleman our relationship will be that of consultant and client or that of our first relationship of boss and underling.  While these circumstances were thrust upon both of us is it reasonable to think that one with a long history 3+ years with a company can transition from having any personal feelings to the more aptly “What can I do for you?” mentality.

So far my feelings are that this type of transition is and would be difficult for anyone to do and moreover can and might be counter productive.  I guess we’ll see over the coming months how this transition will pan out.  I’m hopeful but definitely not going to hold my breath.