Tagged: c#

Creating stronger value type contracts

I’ve long been annoyed that value types don’t have strong semantic information attached to them such that the compiler would barf if I try and pass an value type that isn’t semantically the same as what the function wanted. For example, what does the following signature mean other than than taking in 2 ints and returning a bool?

IsLoggedIn :: int -> int -> bool

What I’d really like the signature to look like is

IsLoggedIn :: UserId -> SessionId -> bool

In F# you can do this sort of with type aliases and augmenting the signature with the type information. However, its just editor magic, it doesn’t actually compile to anything that would stop you from accidentally calling a function with the arguments reversed. An int is an int is an int, right?

var userId = 1
var sessionId = 2

IsLoggedIn(sessionId, userId)

This is perfectly valid to the … Read more

Multiple SignalR clients and ASMX service calls from the same application

I was writing a test application to simulate what multiple signalR clients to a server would act like. The clients were triggered by the server and then would initiate a sequence of asmx web service calls back to the server using a legacy web service. This way I was using signalR as a triggering mechanism and not as a data transport. For my purpose this worked out great.

I had coupled the asmx calling code into a test class for a signalR client, so each class was responsible for its internal signalR connection as well as its outgoing asmx calls. When I had one class everything worked great. But the moment I had two classes running (i.e 2 signalR connections and 2+ asmx connections) everything locked up. I couldn’t figure out what was going on. The signalR clients had connected but all the asmx calls stopped making it through, and … Read more

Constraint based sudoku solver

A few weekends ago I decided to give solving Sudoku a try. In case you aren’t familiar with Sudoku, here is what an unsolved board looks like

from wikipedia

And here is a solved one

from wikipedia

Sudoku, of size 3 is pretty easy. Make a snapshot of the board, pick a random open cell, find out what its available possibilities are and set it to a value. To figure out it’s possibilities you need get the cells “group”. This means all the values of the 3×3 cell it’s in, as well as all the values of the row that it’s in and the columns that it’s in.

Based on what is available, you can choose a number that isn’t taken, plop it in down, and then recursively repeat. If nothing is available, and the board isn’t empty, you messed up and the recursion will backtrack.

Let’s get solvin’


Read more
Creating futures

Futures (and promises) are a fun and useful design pattern in that they help encapsulate asynchronous work into composable objects. That and they help hide away the actual asynchronous execution implementation. It doesn’t matter if the future is finally resolved on the threadpool, in a new thread, or in an event loop (like nodejs).

Asynchronous work wrapped in futures has garnered a lot of attention in the javascript world since they alleviate the heavy use of nested callbacks to return a final result. But futures aren’t limited to just javascript, the C# async keyword is a form of a future, Java has a futures class, and a lot of other languages have the ability to use futures.

In order to to demystify the concept of Futures lets build own version. Futures aren’t hard to implement, even when you have a language that doesn’t have them built in (or if you … Read more

Avoiding nulls with expression trees

I’ve blogged about this subject before, but I REALLY hate null refs. This is one of the reasons I love F# and other functional languages, null ref’s almost never happen. But, in the real world I work as a C# dev and have to live with C#’s… nuisances.

In the other post, a big problem with the dynamic proxy was that it only worked with virtual methods, so it wasn’t really all that practical. This time around I decided to try a different route and leverage expression tree’s to actually build out the if checks automatically.

For the impatient, full source available at my github and the library is available on nuget


Let me demonstrate the final usage first. If all of users properties and methods return null, executing this whole chain would fail starting at the null result of GetSchool(). But, by using the Option static … Read more

24 hour time ranges

Dealing with time is hard, it’s really easy to make a mistake. Whenever I’m faced with a problem that deals with time I tend to spend an inordinate amount of time making sure I’m doing things right.

Today I ran into a situation where I needed to be able to calculate durations and ranges from the current time compared to 24 hour block time. The current time however has the full date, but the 24 hour times are just relative. For example, if the current time is 17:00, and the range is 15:00 to 1:00, then I want to say that the current time is within the range. Also, lets say I have the current time is 17:00 but my range is 1:00 to 5:00. I want to know how far it is from now to the start of the 24 hour range. The ranges though, don’t have date information, … Read more

F# class getter fun

I was playing with Neo4J (following a recent post I stumbled upon by Sergey Tihon), and had everything wired up and ready to test out, but when I tried running my code I kept getting errors saying that I hadn’t connected to the neo4j database. This puzzled me because I had clearly called connect, but every time I tried to access my connection object I got an error.

The issue was that I didn’t realize that f# class members are always deferred. It makes sense that they are after I traced through it, but I couldn’t spot the bug for the life of me at first.

My code looked like this:

module Connection = 
    type Connection (dbUrl) = 

        member x.client = new GraphClient(new Uri(dbUrl))

        member x.create item = x.client.Create item

        member x.connect() = 

If I had more experience with F# I probably would have spotted this right … Read more

Trees and continuation passing style

For no reason in particular I decided to revisit tree traversal as a kind of programming kata. There are two main kinds of tree traversal:

  • Depth first – This is where you go all the way down a tree’s branches first before bubbling up to do work. With a tree like below, you’d hit c before doing any work since it’s the deepest part of the tree (assuming you iterated left first then right)
        / \
       b   e
     /  \
    c    d
  • Breadth first – This is where you hit all the nodes at the level you’re on before going further. So with the same tree, you’d hit a, then b, then e, then c and d.

Being as I actually hate tree traversal, and having to think about it, I decided that whatever I write better be extensible and clean.

Depth first

Here is a simple DFS … Read more

Ordered Consumable

I had the need for a specific collection type where I would only ever process an element once, but be able to arbitrarily jump around and process different elements. Once a jump happened, the elements would be processed in circular order: continue to the end, then loop around to the beginning and process any remaining items.

The use case that prompted this is I have an image generator that creates snapshots out of a video on demand. However, I need to be able to seek in the video and create snapshots at the seeked point in time. Once all the snapshots are created I don’t need to create them again, it’s just a one time processing, but the snapshot generation has to follow the users actions. This also means that if a user seeks to a point in time where a snapshot was already generated, the snapshot generation doesn’t need … Read more

Threadpooling in netduino

Sometimes you want to do asynchronous work without holding up your current thread but the work that needs to be done doesn’t really warrant the cost of spinning up a new thread (though what the exact cost is on an embedded environment I’m not sure).

This where threadpooling comes into play. A threadpool has a certain amount of pre-spun up threads that you can re-use for actions. You push actions onto the threadpool and when there is an available thread it’ll run your action. While threadpools aren’t free (you still incur context switching and the initial overhead of firing up a thread) you can limit your context switches and minimize thread start/cleanup time by reusing threads. Threadpooling is a handy feature and C# has built in support for it, but it’s not in the .net micro framework so I decided to write my own.

For a basic threadpool manager it’s … Read more