Category Archives: .NET

Øredev

For the last year and a half I have been a part of the Øredev Conference Program Committee. I should at some point write a post about it, and yes, I have had a draft laying around for a while, so here it goes:

I have always felt at home at Øredev as the conference was founded by Jayway and it is very much held close to our hearts. Of course, having played a part in the creation of the program makes it even more special for me to attend and last year I had the chance to attend Wednesday and also be at the Speakers’ dinner the evening before. This was a great opportunity to meet and greet, and I could have been more efficient there, but I did get to talk to a whole heap of interesting people.

The unrelenting search for quality speakers my colleagues pursued over the course of the year made Øredev 2012 angst-ridden in a good way. Whatever you chose to go see, there was always another talk you wanted to see going on at the same time. This is a good thing, when you are one of the ones putting together the program.

Last year

Last year we brought Mads Torgersen, Program Manager for the C# Language at Microsoft, which is pretty huge for a .NET guy like myself. He had a secret talk he wanted to do, and weeks before the conference, TypeScript was announced and we got to be the first ones to really bring that out there to our attendees.

TypeScript – JavaScript development at Scale
Async in C#5.0 – No More Callbacks!

Scott Barnes is a former Product Manager for Silverlight at Microsoft, now with Riagenic in Brisbane. He used his experience and laid out a plausible explanation to the twists and turns involving UI frameworks at Microsoft over the last year, as well as doing a very popular talk on a Design eye for the Developer Person. A very entertaining speaker that underplays his smarts.

Sebastien Lambla is another favourite of mine who took last year’s meme theme one step farther to combat session narcolepsy by leading the attendees in a Gangnam Style dance. He did an extremely initiated talk on HTTP Caching.

Jim McCarthy’s closing keynote on the Wednesday was mesmerising. I had to leave for the airport but I had a hard time breaking the spell to get up and leave.

Glenn Block is a good friend to the Øredev and a dream to work with. He is a very busy man but has the admirable quality of always wanting to help. In 2012 he talked about Hypermedia and WebApi as well as Node.js on Azure.

I have been a fan of Oren Eini’s since I saw him deliver a talk and demo on NHibernate back in 2009, and he is a very skilled and formidable speaker with a huge following on his blog. This time he delivered Raven DB training and two talks on Advanced RavenDB and an architecture talk entitled Hard Coding.

So what about 2013?

As experience tells us, you never know everything until November, but the program is out  and is looking rather complete. I went for .NET Open Source and F# this year, no point in trying to hide it. Maybe that’s a bit preachy, but so be it. We have great content on ASP.NET for IIS 8.5 and VS 2013 (“blue”) as well, of course and so on, but I really wanted to feature F# and functional in general as well as give props to some really mature OSS that isn’t getting enough praise.

In DDD with Value Objects, with ES and with the concept of Inversion of Control (well, OK, bear with me here), immutability and pure functions have already been shown to be the awesomesauce when trying to reduce complexity and increase parallelizability. Julie Lerman will talk DDD and Entity Framework, by the way.

Jessica Kerr will talk about Functional Principles for Object Oriented developers which explores how you can write better code in OO without going full Functional and Phil Trelford will talk about  F# for C# developers, when you do decide to go full Functional. Once you have decided to bridge the chasm, you go see Rachel Reese talk about the Actor model in F#, as in F# Agents, and about F# Type Providers. If you are ready to put the pieces together, there is Phil Trelford’s talk on F# for Trading, which is an example of why the City of London is crawling with F# developers  or at least recruiters looking for them.

NancyFx and ServiceStack are among the most popular Open Source frameworks out there for .NET and they have large communities, rich featuresets and proven track records and their respective fathers Andreas Håkansson and Demis Bellot will talk about them in greater detail and of course they will be available to be accosted for further questions you may have, which is the awesomest thing with Øredev.

A long time goal of mine was to bring Michele Leroux Bustamante to Malmö and Øredev. I became a fan back with her book Learning WCF which is the best programming book I have ever read, in tough competition with W Richard Stevens’ book Advanced Programming in the UNIX Environment. Since then Michele has created and sold a startup in the Identity field and is a Windows Azure MVP so what she doesn’t know about cloud and identity in the .NET space is probably not worth knowing.

Another important thing that you cannot miss is the excellent Anders Janmyr who with his talk on Habits of a Responsible Programmer managed to overcome the impossible standards you need to keep if you are both a part of Jayway and the Program Committee and still want to speak at the conference. You may think we would hand out speaking positions like candy to “our own”, but it’s rather the other way around as the last thing we would want to be accused of is playing favors and not striving for quality first.

This is just for starters, explore the program and book your tickets now. The conference will be the best ever.

The Actor Model

In the .NET community perhaps the Actor model of computing is not all that familiar. In this post I will briefly describe my understanding of the possibilities it gives the “real life” Enterprise LOB-application developer without going into specifics.


Different abstraction

The Actor model is a different abstraction from the normally more machine-like multithreaded server process model. This model sees the software system as a set of Actors listening for incoming messages. Messages are sent using to mailing addresses, conceptually, as in – not a hard reference to a running piece of code of any kind. An actor can only send messages to other actors that it knows the address of. It will know only of actors it receives messages from or creates itself. Unintuitively, the communication between actors is handled through a concept known as Channels, which would imply something more direct than a mail-drop system. In common implementations today, channels are implemented as queues.

The Actor will react to the incoming message by either sending a finite number of messages, creating a finite number of actors as well as deciding how to handle the next incoming message. The messages contain all the information needed for this processing, so there is no global state to modify or any shared resources to wait for. Each actor has its own execution context. Whether you execute all actors in the same thread in the same process or whether you have tens of thousands of separate machines with a multitude of threads of execution in several processes does not matter to the actor. This leads to a fantastic potential for scalability as there is little or no negative coupling.

Real-world examples?

If you think about it more closely, the Actor model can be said to better model the organizations we are building systems for. If a process requires a certain number of steps to be taken, modelling the steps, or actually the coworkers performing the step, as actors and the piece of paper or file that would travel from desk to desk can be modelled as a message. Just like faceless corporate drones, actors can be stateful, as is evident from the definition above.

In the Actor model data is not encapsulated but rather transmitted as messages between actors that perform actions with that data and then send the information forward. In object oriented programming you still send messages, conceptually, but actually you call methods on the object, but the objects are one with their data and the only way to modify the data is by sending a message to the object and hope the object will allow itself to be modified in the way you want.

There are large practical similarities between classic object oriented programming and the Actor model, and the Actor model frameworks implement actors as “objects” and use the OOP toolbox to implement the infrastructure that the frameworks provide, but the conceptual differences are importan remember when working with this model.

What frameworks exist for .NET?

There are two well known Actor model framework for .NET, Retlang (http://code.google.com/p/retlang/) and Stact. They both provide the basics you can expect from a framework of this kind, only Retlang stray somewhat from the Actor model nomenclature and provide no remote messaging capability, focusing on high performance in-memory messaging. It is unclear how development proceeds with Retlang, but there is support for .NET 4.

Another framework that supports Actor model is Stact https://github.com/phatboyg/Stact) which uses concepts more closely linked to the specification and would be preferable by those who like conceptual clarity.

Recently, F# has introduced the concept of F# Agents, which is essentially actors. They have isolation between instances (actors) and respond asynchronously to incoming statically typed messages.  (http://www.developerfusion.com/article/139804/an-introduction-to-f-agents/)

We will proceed and show a brief example using F# as it is less verbose than other ways of implementing this architecture. The examples are slightly modified from the above link and also ripped straight from the horse’s mouth, i e  Don Syme’s post http://blogs.msdn.com/b/dsyme/archive/2010/02/15/async-and-parallel-design-patterns-in-f-part-3-agents.aspx 

open Microsoft.FSharp.Control
type
Agent<‘T> = MailboxProcessor<‘T>

let agent =
    Agent.Start(
fun inbox ->
        let rec loop n = async
{
           
let!
msg = inbox.Receive()
            printfn
“now seen a total of %d messages”
(n+1)
           
return!
loop (n+1)
        }
        loop 0 )

for i in 1 .. 1000 do
    agent.Post (sprintf “Hello %d” i )

The above agent uses a builtin class called MailboxProcessor that allows you to post messages, passing in the actual Processor function as an argument, “putting the fun back into functional”.

Of course this is a silly example that doesn’t make anybody happy. Let’ s show something more network-related, so that you can imagine the implications.

open System.Net.Sockets

 

/// serve up a stream of quotes

let serveQuoteStream (client: TcpClient) = async {

    let stream = client.GetStream()

    while true do

        do! stream.AsyncWrite( “MSFT 10.38″B )

        do! Async.Sleep 1000.0 // sleep one second

}

 

What is the point of this then? Well, the agents are asynchronous and take no resources while waiting.  You might as well create a bunch of actors that will all lie there waiting for an incoming request and deal with them asynchronously with mindblowing efficiency. Every Actor (or instance of Agent) has its own state completely isolated from the others. See? No problems with shared mutable state. Put the foot on the accelerator and press it all the way to the floor.

Error management in Actors

Below is an example of error management using a supervisor that will take care of your vast pool of actors and deal with their failures. Again, contrived example, but remember you have all of the .NET framework at your disposal, so just imagine the supervisor doing some really clever reporting or cleanup.

open Microsoft.FSharp.Control

type Agent<'T> = MailboxProcessor<'T>

module Agent = 
   let reportErrorsTo (supervisor: Agent<exn>) (agent: Agent<_>) = 
       agent.Error.Add(fun error -> supervisor.Post error); agent

   let start (agent: Agent<_>) = agent.Start(); agent

let supervisor = 
   Agent<int * System.Exception>.Start(fun inbox ->
     async { while true do 
               let! (agentId, err) = inbox.Receive()
               printfn "an error '%s' occurred in agent %d" err.Message agentId })


let agents = 
   [ for agentId in 0 .. 10000 ->
        let agent = 
            new Agent<string> (fun inbox ->
               async { 
                    while true do 
                        let! msg = inbox.Receive()
                        if msg.Contains("agent 99") then 
                            failwith "I don't like that cookie!" }
                ) 
        agent.Error.Add(fun error -> supervisor.Post (agentId, error))
        agent.Start()
        (agentId, agent) ]

for (agentId, agent) in agents do 
   agent.Post (sprintf "message to agent %d" agentId )


Conclusion

The implications that arise from the Actor model and F# Agents in particular is that where you can use messaging (you are free to use F# Type Providers to make your various XML WebService packets become F# Types) you can process them with great efficiency to trigger all sorts of  .NET functionality asynchronously. You could use F# Agents to back your WebApi services to make the code more concise and responsive. There is no end to the possibilities.

For further reading, please don’t hesitate to follow Don Syme at http://blogs.msdn.com/b/dsyme/  and the various blogs and documentation available through there.

So what’s this FP thingy?

People are talking about Scala, F#, Erlang, Haskell and what-have-you. What is the point of functional? What is wrong with OOP? How does it all work?

Here are some videos you might want to look at. Maybe you find them helpful, maybe not.

Jessica Kerr: Functional Concepts for Object Oriented developers

This introduces the concept of immutability and pure functions and how your life gets better if you use those concepts in your everyday life. Of course, in DDD Value Objects and immutability is king as well, for the very reasons Kerr brings up in the video.

Brian Beckman: Don’t fear the Monad

This is a scary attempt at explaining monoids and monads. You may follow it, you may not. Don’t get too distracted or discouraged. Think of it monads in terms of LINQ and composability.

Erik Meijer C# Lecture, Functional Programming and Monads

http://www.youtube.com/watch?v=OrAVS4QbMqo

This talk is affected by Erik Meijers huge brain and is scarily influenced by Haskell, but makes sense if you saw the video above.

F# Creator Don Syme does a Tutorial

Don Syme F# Tutorial Part 1

You should skip the first part unless you want to know from whence F# came. There is very little syntax info in this chapter.

Don Syme F# Tutorial Part 2
Loops, data structures, beginning of pattern matching.

Don Syme F# Tutorial Part 3

Windows Azure Websites: -1

You should have by now – but if you haven’t – do try Windows Azure Websites. It is almost as usable as AppHarbor. Just register and start setting up your websites. For small blogs and wikis you can get away with internal storage and spend no money at all. No need for hosting ever again.

If you, as you should be, are writing your own web apps, you can connect your Bitbucket free private repo, or indeed your almost free GitHub private repo, or indeed a public repo directly to an azure website, so that you get CI whenever a commit is made in that repo. You can differentiate on branches so that the master branch triggers deploys to “production” and the staging branch, for instance, triggers deploys to the staging site. The possibilities are if not endless pretty huge.

The thing is, it works, although I’ve manage to upset the system by trying to do naughty things with weird Silverlight apps, but if auto deploy doesn’t work, manual deployment from Visual Studio still does. Even if auto deploy does work –  having CD from Git to the test site and VS -> Publish to your production site may not be such a bad idea, if you want to find a middle ground. Of course you are free to spend money if you like, but it is not necessary.

www.windowsazure.com

Mail server and collaborative calendar

I was thinking, in light of the fact that all our data, including this blog, is being scrutinized by foreign (to me and most internet users) powers, that maybe one should try to replace Google Apps and Outlook.com, well Google Apps really. The problem is that Google Apps is pretty damn useful.

So what does one need? I have no money to spend, so it has to be free.

One needs a full featured SMTP server, a good web interface with simple design that also renders well on mobile in which you can search through (and find!) email and appointments. Some would argue that you need chat and video conferencing as well, and I guess one where neither Chinese nor US military is also on the call would be preferable, but I can live without it.

I cannot, however, live without civilized charset support. As in, working iso-8859-1 or something proper that can display the letters of honor and might, aka åäö. It would also not seem like a grown-up solution if it wasn’t trivial to add encryption and/or signing of e-mails.

You also need shared calendars and the option of reserving common resources. Not perhaps in the home, but the very first thing you do when you use shared calendars in a company is that you start booking things, such as conference rooms, portable projectors et c.

The user catalog needs to be easily managed. You need folders/labels of some kind and filters to manage the flow of e-mail.

I also, probably, need a way to access my e-mail via IMAP.

So the question is, how much of this do I have to build? How much exists in Linux? Does it look decent or does it look Linuxy? By decent I mean Web 2.0-ish, as opposed to linuxy or Windowsy, such as outlook web access.

I’d like any suggestion. I am prepared to code, albeit in C#/mono, but I would love to use as much Linux OSS available as I probably suck at writing this kind of stuff compared to those who have already done so.

So far I have found the following:
http://www.howtoforge.com/perfect-server-ubuntu-13.04-nginx-bind-dovecot-ispconfig-3
But instead of an ISP tool a custom website? Perhaps solr or lucene indexing each user’s maildir. But what about a calendar?

Why not just install Citadel?
This requires testing.

.NET 4.5.1

To continue the last post about the //BUILD/ Conference, what else is new? What should you look at now? A few things stand out and I will go through them in order.

See Function Return values in debugger

For F# or any functional language, return values of functions are pretty crucial to be able to see when you debug your code or else you are sort of robbed of the idea of a debugger. Of course, you do have less code and fewer bugs per user story in functional languages vs imperative languages in general, so debugging probably isn’t as important, but the fact that you had to change your code to be able to double check return values must have been a huge pain. The point is, now in VS2013 Preview, when you step past a return statement, you will see the return value in the Autos window as well as being able to access it in the Immediate windows as $ReturnValue. I know I missed it in C#, it must have been super annoying for our functional friends. The takeaways are YAY and  – try F# (still near the top of my to-do list).

64-bit Edit & Continue

ORLY? I will be happy to see the 64-bit dialog box go but would have been happy to just have the debugging stop immediately when somebody tries to type in a code window. That probably indicates that the programmer knows what’s wrong and needs to make changes, not that they would like to go full VB3. To me it’s just embarrassing to see VS handle 64-bit as if it was magic. There should be no difference for a real programmer how you handle 64 or 32 bit (beyond the obvious, but that’s a five minute conversation among stakeholders over coffee) and the fact that the segregation remained is a bit of an embarassment.

ADO.NET Connection Resiliency

EF/ADO.NET Connection resiliency. When you use SQL Database in Windows Azure, you will notice that you only get a brief window of connectivity so as to not waste server resources. This is brilliant and should have been the default on your vanilla SQL Server back in the nineties as well, it would have given us less sucky client / server apps back in the day, but the point is the folks over at ADO.NET now gave us connection resiliency, which means your connection autoresumes when you remember to access your database again. This means simpler code in your app and the database abstraction layer also abstracts connection failures, the way $HigherPower intended.

Hosting and Runtime Features

IIS App Suspension – Another Azure-derived feature is that they will allow web apps to run, but to be suspended in its current state when it has been idle for a while. This feature is available in IIS 8.5, Windows Server 2012 R2 Preview.

Large Object Heap compaction – the Large Object Heap can be now compacted as part of the 2nd generation GC run, as in a full stop-the-world GC, so use carefully. You will need to use a separate API to invoke this feature, but if you are having problems with the Large Object Heap not being compacted, you are probably aware of that and are prepared to add a line of code.

New runtime features that will affect you without you doing anything include automatic multi-core support to make app startup time faster and ASP.NET apps and also the fact that you will get Windows Updates of the .NET framework with precompiled native images. In previous versions of Windows your .NET apps will JIT mscorlib.dll et c as you run them when the dllis different from the cached binary installed with Windows, VS or a service pack.

Cadence – pleasing both camps

A huge deal is that the .NET Framework will go full Ubuntu style versioning, with many small incremental changes, with big bang Long Term Support versions made for the enterprise. They wouldn’t call it “ubuntu style versioning”, so I did it for them. They have implemented this by deploying new features as NuGet packages continuously, while they collate mature features and include them in big releases. This is pretty significant and a great decision.

Build Conference

Although Øredev as per usual will be the place to be, in this case November 4-8, Microsoft currently run two conferences of their own, TechEd Europe and more importantly //BUILD/ which covers the latest news about the preview versions of Windows 8.1 “Blue” and releated developer tools, Visual Studio 2013 and .NET Framework 4.51.

In general for Windows users, the most important things are the ressurection of the Start Button, which, in combination with the ability to set your desktop background as being the background of the start screen as well, will give you a smoother more vintage Windows feel. Also, there are impressive new features for Multi Monitor support, such as the ability to have different DPI on different monitors, which again pushes Wndows ahead of OSX.

But for developers, in the words of Lou Reed,  What’s good?  The cool things that have emerged are that XAML under Windows 8 has evolved far further. A whole new set of controls have been released that allow for better performance when dealing with large sets of data, there are tests to measure power consumption of an app to help developers save their users’ battery Life, you can manage separate frames on separate monitors (Think Powerpoint presentation vs Speaker Notes or Point of Sales cashier view vs customer view).
http://channel9.msdn.com/Events/Build/2013/2-164

Also ASP.NET has taken a huge leap forward with the separation between ASP.NET WebForms, ASP.NET MVC, ASP.NET WebApi and SignalR have been erased, allowing you to create one ASP.NET project after which you cherry pick the features you need. This has also meant a vast improvement in what you can do in WebForms, in terms of async support and model binding to name but a few things. I truly Believe users stuck in Legacy Hell will appreciate this the most of all the things that were introduced during build, including the debugging support for Async.
http://channel9.msdn.com/Events/Build/2013/2-546

Oh. and this is only after day 2, so there’s a whole last day to check out.

WCF 4.0

As the tour is now concluded and we are doing business as usual I figured it is time to post some promised source code and powerpoint material. If you just joined us, the final Jayway seminar of the spring season was on Windows Identity Foundation and a short roundup of new features in WCF 4.0. Stefan Severin MC:d the WIF section while I did the presentation on WCF 4.0.

So what IS up with WCF 4.0?  My three main points were the following:

  1. Simplified Configuration
  2. Full implementation of WS Discovery
  3. A turn-key RoutingService

My full presentation in attached and I also submit some source code, largely based on Aaron Skonnard’s excellent MSDN article with minor modifications to show the difference between WCF3.5 and WCF4 in terms of configuration.

References:

Presentation

Source Code

Aaron Skonnard’s introduction to WCF 4.0

Using the NHibernate OR-mapper

I have decided to go ahead and set up a class that covers the basics and a few more advanced features of NHibernate. In order to take part in the class, please contact Dotway Stockholm at stockholm@dotway.se

As Domain Driven Design has won followers over legacy Data Driven Design people are focusing on mapping a business case directly into a set of objects that describe the problen space and true workflow, solving the problems the customer wants to solve and thus focus more on stringent, understandable and maintainable systems rather than focusing on what data the system will contain and how to store it cleverly, systems for abstracting away object persistence .have emerged. In the Java community Hibernate has been the big name over the years and in .NET NHibernate is establishing itself as the major player being the foundation for several solutions for automated persistence such as Castle ActiveRecord with the ActiveWriter modelling toolset.
 
This class is directed towards experienced .NET developers looking to migrate to NHibernate in production, either wrapping legacy databases or going greenfield domain-first. It covers a variety of tasks from the basic “getting started” via configuration through XML as well as FluentNHibernate to complex persistence solutions with some comparison to other persistence solutions such as Linq2SQL.
Topics covered in this class:

  • OR-mapper. Why?
  • Getting started
  • NHibernate vs … part I
  • Implementing a Sample Case
  • Session model
  • Lazy Loading
  • HQL
  • Schema versioning and deployment
  • Best practices
  • Worst practices
  • NHibernate vs … part II
  • Troubleshooting
  • Performance tuning

Starting with a very basic example of an ASP.NET MVC website I will expand and elaborate on a number of features in NHibernate, such as configuration, transactions, session scope, various key types, numbering schemes and lazy loading to show how to solve problems with NHibernate and how to retrofit NHbernate on top of existing schemas as well as how to create and version greenfield schemas. I will use a demo version of nhprof to demonstrate how the features, settings and tweaks as well as the chosen platform affect the SQL generated

I hope the class will instill a greater understanding of and confidence in NHibernate for use in your current project. If you wish there will be a fistful of code you will be able to use as a starting pont for your own exploration of NHibernate and its features.