# Thursday, September 01, 2016

Modernizing a legacy IoT device: AMQP, but how?


As in most IoT/cloud processing scenarios, we collect data for multiple producers, and then let a bunch of consumers process the data.
This is a very common design, every (professional) IoT solution I have seen recommends it, and for good reasons: when load increases (you have more producers, or each of them produces more traffic and/or bigger messages), you scale out: you have multiple, concurrent (competing) consumers.

You can do this easily if you decouple consumers and producers, by inserting something that "buffers" data in between the consumer and producer. The benefits are increased availability and load levelling.
An easy way to have this is to place a simple, durable data store in the middle. The design is clean: producers place data into the store, consumers take them out and process them. 
The data store is usually FIFO, and usually a Queue. 

In our case, it wasn't a queue. The design was similar, the implementation... different :)
Still durable, still FIFO-ish, but not a Queue in the sense of Azure Queues or Service Bus Queues or RabbitMQ (typical examples of queues used in IoT projects).

It was just a file server + a TCP client writing to an SQL DB in a very NoSQL-ish way (just a table of events, one event per row, shreded by date). Devices write data to an append-only file, copy them securely using an SSH/SCP tunnel, place them in a directory; a daemon (service) with a file-system watcher (inotify under Linux) takes new files and uploads them to a proper queue for processing; the TCP client notifies about relevant events (new file present, files queued but not uploaded yet, all uploaded, etc.).

Our goal is to change this structure with something much more standard, where possible, so we can use some modern middleware and ditch some old, buggy software. Or even "get rid" of the middleware and let some Cloud Service handle the details for us.
If you have something similar, in order to modernize it and/or move it to a Cloud environment such as Azure (or if you plan to make your move in the future), you want to use a modern, standard messaging protocol (AMQP, for example), and a middleware that understands it natively (RabbitMQ, Azure Events Hub, ...). But how do you use this protocol? How do you "change" your flow from the legacy devices (producers) to the consumers?
You have three options:
  1. Insert a "stub/proxy" on the server (or cloud) side. Devices talk to this stub using their native protocol (a custom TCP protocol, HTTP + XML payload, whatever). This "stub" usually scales well: you can code it as lightweight web server (an Azure Web Role, for example) and just throw in more machines if needed, and let a load balance (like HAProxy) distribute the load. It is important that this layer just acts as a "collector": take data, do basic validation, log, and throw it in a queue for processing. No processing of messages here, no SQL inserts, so we do not block and we can have rate leveling, survive to bursts, etc.
    This is the only viable solution if you cannot touch the device code.
  2. Re-write all the code on the device that "calls out" using the legacy protocol/wire format, and substitute it with something that talks in a standard supported by various brokers, like AMQP or MQTT. In this way, you can directly talk to the broker (Azure Event Hub, IoT Hub, RabbitMQ, ..), without the need of a stub. 
    This solution is viable only if you fully control the device firmware.
  3. Insert a "broker" or gateway on the device, and then redirect all existing TCP traffic to the gateway (using local sockets), and move the file manager/watcher to the device. Have multiple queues, based on priority of transmission. Have connection-sensitive policies (transmit only the high-priority queue under GPRS, for example). Provide also a way to call directly the broker for new code, so the broker itself will store data and events to files and handle their lifetime. Then use AMQP as the message transport: to the external obsever (the Queue), the devices talks AMQP natively.
    This is a "in the middle solution": you can code / add your own programs to the device, but you do not have to change the existing software.
In our case, the 3rd option is the best one. It gives us flexibility, the ability to work on a piece of functionality at the time while keeping some of the old software still running.
Plus, it makes it possible to implement some advanced controls over data transmission (a "built-in" way to transmit files in a reliable way, have messages with different priorities, transmission policies based on time/location/connection status, ...).
But why would you want to design a new piece of software that still writes to files, and not just keep a transmission (TX) queue in memory? For the same reason queues in the middleware or in the cloud are durable: fail and recover. Device fields are battery powered, work in harsh conditions, are operated by non-professional personnel. They can be shut down at any moment (no voltage, excess heat, manually turned off), and we have no guarantees all the messages have been transmitted already; GPRS connections can be really slow, or we may be in a location that has no connectivity at all at the moment.

I was surprised to discover that this kind of in-process, durable data structures are ... scarce!
I was only able to locate a few:
  • BigQueue (JVM): based on memory mapped files. Tuned for size, not reliability, but claims to be persistent and reliable.
  • Rhino.Queues.Storage.Disk (.NET): Rhino Queues are an experiment from the creator of the (very good) RavenDB. There is a follow up post on persistent transactional queues, as a generic base for durable engines (DB base).
  • Apache Mnemonic (JVM): "an advanced hybrid memory storage oriented library ... a non-volatile/durable Java object model and durable computing"
  • Imms (.NET): "is a powerful, high-performance library of immutable and persistent collections for the .NET Framework."
  • Akka streams + Akka persistence (JVM): two Akka modules, reactive streams and persistence, make it possible to implement a durable queue with a minimal amount of code. A good article can be found here.
  • Redis (Any lang): the famous in-memory DB provides periodic snapshots. You need to forget snapshot and go for the append-only file alternative, which is the fully-durable persistence strategy for Redis.

The last one is a bit stretched.. it is not in-process, but Redis is so lightweight, so common and so easy to port that it may be possible to run it (with some tweaks) on an embedded device. Not optimal, not my first choice (among the other problems, there is a RAM issue: what if the queue exceeds the memory size?), but probably viable if there is no alternative.

Most likely, given the memory and resource constraints of the devices, it would be wise to cook up our own alternative using C/Go and memory mapped files. This is an area of IoT were I have seen little work, so it would be an interesting new project to work on!


# Wednesday, August 31, 2016

What is an "architect" anyway?

A little break from the series of posts on Pumpkin. Today I had to explain what I do for a living, and it was longer then I expected. But it gave me the time and opportunity to think about what I really do.

I always pause a second when people ask me "what is your job?"
I usually go for a very simple "software developer" or "programmer". After all if it is good enough for Scott Hanselman, I should be fine with it.

Since I have some experience, I sometimes may add "Senior" to it. But I don't feel that "Senior" anyway: I feel young, and I feel like I have always something new to learn, something new to do. "Senior" seems a little too accomplished to me.

Unfortunately, if you speak to people in the same or in a related field, this is rarely enough.
"But which is you role?" "Don't you manage a team of 7?" yes I do, but "manager" is way too nontechnical; "managing" the team, for me, is a mix of architectural and code reviews, coaching, mentoring, everything necessary to ensure the team delivers great things and customers are happy.

"So you are a tech lead!"
Well... I love the technical side of my job. I turned down good offers in the past because the "step-up" role was a pure management one, a common evil in Italy - management is the only "way up".
But my current role is made from pure technical parts (code, design, run sanity check -check the proper patterns are used and anti-patterns avoided, for example-) and also "soft" parts (be a bridge between customers and tech-speaking people, talk to upper management, customers and stakeholders, present figures and help making informed decision, advocate for my team).

This is why my "official" title of "Software architect" at my current job is kind of OK. It is technical, but not purely technical.

But what is an "architect", or a "team lead", anyway?

IMO, or at least in my case, it means being "Primus inter pares" and a "Servant leader".

"Primus inter pares" is a latin expression which roughly translates to "first among equals". It does not really matters if your leadership is sanctioned by the corporate ladder, or if it is an honorary title and you are formally equal to other members of their group. You act as a member of the group; you keep coding and share chores (debugging, bug fixing), otherwise you will lose what it really matters among developer: (unofficial) respect for your skills and knowledge.

Keep your hands dirty is key for me. I try to keep the balance between the technical and soft side of my job 50/50, and I code whenever I can. Because I like it (I think I will never give up coding, even if I win a billion euros and I can retire), and because I need it. It is like physical exercise, or training for a sport: both you and your body know when you need it, that you need it.

A good objective of leadership is to help those who are doing poorly to do well and to help those who are doing well to do even better.
– Jim Rohn, American entrepreneur.

Robert K. Greenleaf first coined the phrase "servant leadership" in his 1970 essay, "The Servant as a Leader."

As a servant leader, you are a "servant first".
In practice, I try to focus on the needs my team mates, before considering my own. I acknowledge other people's perspectives, give them the support they need to meet their work and personal goals, involve them in decisions where appropriate, and build a sense of community. I still call the shots (design-by-committee does not really work), but I listen before speaking, and use persuasion over authority.

A great side effect from acting in this way is that it gives you the necessary skills to deal with people "above" you: the ones you cannot use your authority upon, either because they are your boss, or because they are your peers (customers, for example). Your persuasion and reasoning skills are honed, and you are in a fantastic shape to be able to make your point, make your message pass, make them listen and consider what you say.

# Monday, August 29, 2016

Cloud, at last!

After some time experimenting, studying, designing (but mostly: presenting possible scenarios to management), we are preparing to move a central part of our systems to the cloud!
Cost savings (especially OPEX - especially linked to sourcing: finding and hiring a good DBA is very hard!), increased availability and resistance to HW failures/catastrophes are the key points I presented to management to help them decide.

On the downside, to be ready to move will require a good engineering effort; our systems are very old, but the general architecture built during the years is sound. It was good (surprising and pleasant) to discover how we already used  many of the patterns listed in the Azure Cloud Design Patterns Architecture Guidance in our systems.



The legacy components of the system have been extensively extended during the years, and the new parts and paths developed since I joined the company in 2012 always followed a classic pattern which you may recognize from several IoT designs:
  •   Field devices -> Queue (Inbox/Outbox)
  •   Queue -> Processing -> SQL
  •   Commands -> Queue (Inbox) <- Device
  
More precisely:
  • Field devices communicate to a "central" server, which just collects the data, buffers them on a durable (temporary) store. Little or no processing here (basics validation only)
  • On different machines, "consume" the items in the temporary store: pull things from there, persist each event in an "append-only" data store (Event Sourcing)
  • Process the events: generate domain objects through a series of steps (3), from the append-only store events to the final objects persisted in SQL tables (Pipes and Filters)
  • Generate "synthesized" data for reporting and statistics queries (Materialized View)
The back-end is already decomposed in several "medium" services: not really "micro" services, but several HTTP-based services talking through a REST API.
These services are already quite robust: they have to, since they are already exposed to the Internet. In particular, they implement Cache-aside for performance, Circuit Breaker/Retry with exp. backoff when they talk to external services (and, in most cases, even when they talk internally to each other), sharding for big data, throttling for some of the public-facing APIs.

Technically, the challenge is so interesting. The architecture is really apt to be ported to the cloud, but to make it really competitive (and to minimize running costs), some pieces will have to be rewritten.
To make the transition as smooth as possible, initially most of the pieces will be less than optimal (mostly IaaS - VMs, SQL storage where NoSQL/Cloud storage would suffice, Compute instances, ..) but will be slowly rewritten to be more efficient, more "cloudy" (App Fabric, Tables, Functions, ...).

Really excited to have begun this journey!

# Saturday, August 06, 2016

Old school code writing (sort of)

As I mentioned in my previous post, online resources on Hosting are pretty scarce. 

Also, writing an Host for the CLR requires some in-depth knowledge of topics you do not usually see in your day-to-day programming, like for example IO completion ports. Same for AppDomains: there is plenty of documentation and resources compared to Hosting, but still some more advanced feature, and the underlying mechanisms (how does it work? How does a thread interact and knows of AppDomains?) are not something you can find in a forum. 

Luckily, I have been coding for enough time to have a programming library at home. Also, I have always been the kind of guy that wants to know not only how to use stuff, but how they really work, so I had plenty of books on how the CLR (and Windows) work at a low level. All the books I am going to list were already in my library!

The first one, a mandatory read, THE book on hosting the CLR:



Then, a couple of books from Richter:

  

The first one is very famous. I have the third edition (in Italian! :) ) which used to be titled "Advanced Windows". It is THE reference for the Win32 API.
If you go anywhere near CreateProcess and CreateThread, you need to have and read this book.

The second one has a title which is a bit misleading. It is acutally a "part 2" for the first one, focused on highly threaded, concurrent applications. It is the best explanation I have ever read of APCs and IO Completion Ports.

  

A couple of very good books on the CLR to understand Type Loading and AppDomains.
A "softer" read before digging into...

  

...the Internals. You need to know what a TEB is and how it works when you are chasing Threads as they cross AppDomains.
And you need all the insider knowledge you may get, if you need to debug cross-thread, managed-unmanaged transitions. And bugs spanning over asynchronous calls. 

My edition of the first book is actually called "Inside Windows NT". It is the second edition of the same book, which described the internals of NT3.1 (which was, despite the name, the first Windows running on the NT kernel), and was originally authored by Helen Custer. Helen worked closely with Dave Cutler's original NT team. My edition covers NT4, but it is still valid today. Actually, it is kind of fun to see how things evolved over the years: you can really see the evolution, how things changed with the transition from 32 to 64 bits (which my edition already covers, NT4 used to run on 64 bit Alphas), and how they changed it for security reasons. But the foundations and concepts are there: evolution, not revolution.

  

And finally two books that really helped me while writing replacements for the ITaks API. The first one to tell me how it should work, the second one telling me how to look inside the SSLCI for the relevant parts (how and when the Hosting code is called).

Of course, I did not read all these books before setting to work! But I have read them over the years, and having them in my bookshelf provided a quick and valuable reference during the development of my host for Pumpkin.
This is one of the (few) times when I'm grateful to have learned to program "before google", in the late '90/early '00. Reading a book was the only way to learn. It was slow, but it really fixed the concepts in my mind. 

Or maybe I was just younger :)


# Thursday, August 04, 2016

IL rewriting + AppDomain sandboxing + Hosting

So, in the end, what went into Pumpkin?

Control was performed at compilation time or execution time? And if it is execution, using which technique?

In general, compilation has a big pro (you can notify immediately the snippet creator that he did something wrong, and even preventing the code block from becoming an executable snippet) and a big con (you control only the code that is written. What if the user code calls down some (legitimate) path in the BCL that results in a undesired behaviour?)

AppDomain sandboxing has some big pros (simple, designed with security in mind) and a big con (no "direct" way to control some resource usage, like thread time or CPU time).
Hosting has a big advantage (fine control of everything, also of "third" assemblies like the BCL) which is also the big disadvantage (you HAVE to do anything by yourself).

So each of them can handle the same issue with different efficacy. Consider the issue of controlling thread creation:
  • at compilation, you "catch" constructs that create a new thread (new Thread, Task.Factory.StartNew, ThreadPool.QueueUserWorkItem, ...)
    • you have to find all of them, and live with the code that creates a thread indirectly.
    • but you can do wonderful things, like intercepting calls to thread and sync primitives and substitute them - run them on your own scheduler!
  • at runtime, you:
    • (AppDomain) check periodically. Count new threads from the last check.
    • (hosting) you are notified of thread creation, so you monitor it.
    • (debugger) you are notified as well, and you can even suspend the user code immediately before/after.

Another example:
  • at compilation, you control which namespaces can be used (indirectly controlling the assembly)
  • at runtime you can control which assemblies are really loaded (you are either notified OR asked to load them - and you can prevent the loading)

What I ended up doing is to use a mix of techniques. 

In particular, I implemented some compiler checks.
Then, run the compiled IL on a separate AppDomain with a restricted PermissionSet (sandboxing).
Then, run all the managed code in an hosted CLR.

I am not crazy...
 

Guess who is using the same technique? (well, not compiler checks/rewriting, but AppDomain sandboxing + Hosting?)
A piece of software that has the same problem, i.e. running unknown, third party pieces of code from different parties in a reliable, efficient way: IIS.
There is very little information on the subject; it is not one of those things for which you have extensive documentation already available. Sure, MSDN has documented it (MSDN has documentation for everything, thankfully), but there is no tutorial, or Q&As on the subject on StackOverflow. But the pieces of information you find in blogs and articles suggests that this technology is used in two Microsoft products: SQL Server, for which the Hosting API was created, and IIS.

Also, this is a POC, so one of the goals is to let me explore different ways of doing the same thing, and assess robustness and speed of execution. Testing different technologies is part of the game :)

Building barriers: compilation time VS execution time

In order to obtain what we want, i.e. fine grained resource control for our "snippets", we can act at two levels:

  • compilation time
  • execution time

Furthermore, we can control execution in three ways:

  1. AppDomain sandboxing: "classical" way, tested, good for security
  2. Hosting the CLR: greater control on resource allocation
  3. Execute in a debugger: even greater control on the executed program. Can be slower, can be complex

Let's examine all the alternatives.

Control at compilation time

Here, as I mentioned, the perfect choice would be to use the new (and open-source) C# compiler.

It divides well compilation phases, has a nice API, and can be used to recognize "unsafe" or undesired code, like unsafe blocks, pointers, creation of unwanted classes or call to undesired methods.

Basically, the idea is to parse the program text into a SyntaxTree, extract the node matching some criteria (e.g. DeclarationModifiers.Unsafe, calls to File.Read, ...), and raise an error. Also, it a possibility is to write a CSharpSyntaxRewriter that encapsulates (for diagnostic) or completely replace some classes or methods.

Unfortunately, Roslyn is not an option: StackOverflow requirements prevents the usage of this new compiler. Why? Well, users may want to show a bug, or ask for a particular behaviour they are seeing in version 1 of C# (no generics), or version 2 (No extension methods, no anonymous delegates, etc.). So, for the sake of fidelity, it is required that the snippet can be compiled with an older version of the compiler (and no, the /langversion switch is not really the same thing).

An alternative is to act at a lower level: IL bytecode. 
It is possible to compile the program, and then inspect the bytecode and even modify it. You can detect all the kind of unsafe code you do not want to execute (unsafe, pointers, ...), detect the usage of Types you do not want to load (e.g. through a whitelist), insert "probes" into the code to help you catch runaway code.

I'm definitely NOT thinking about "solving" the halting problem with some fancy new static analysis technique... :) Don't worry!

I'm talking about intercepting calls to "problematic" methods and wrap them. So for example:

static void ThreadMethod() {
   while (1) {
      new Thread(ThreadMethod).Start();
   }
}
This is a sort of fork bomb

(funny aside: I really coded a fork bomb once, 15 years ago. It was on an old Digital Alpha machine running Digital UNIX we had at the university. The problem was that the machine was used as a terminal server powering all the dumb terminals in the class, so bringing it down meant the whole class halted... whoops!)

After passing it through the IL analyser/transpiler, the method is rewritted (compiled) to:


static void ThreadMethod() {
   while (1) {
      new Wrapped_Thread(ThreadMethod).Start();
   }
}

And in Wrapped_Thread.Start() you can add "probes", perform every check you need, and allow or disallow certain behaviours or patterns. For example, something like: 

if (Monitor[currentSnippet].ThreadCount > MAX_THREADS)
  throw new TooManyThreadException();

if (OtherConditionThatWeWantToEnforce)
  ...

innerThread.Start();


You intercept all the code that deals with threads and wrap it: thread creation, synchronization object creation (and wait), setting thread priority ... and replace them with wrappers that do checks before actually calling the original code.

You can even insert "probes" at predefined points: inside loops (when you parse a while, or a for, or (at IL level), before you jump), before functions calls (to have the ability to check execution status before recursion). These "probes" may be used to perform checks, to yield the thread quantum more often (Thread.Sleep(0)), and/or to check execution time, so you are sure snippets will not take the CPU all by themselves. 

An initial version of Pumpkin used this very approach. I used the great Cecil project from Mono/Xamarin. IL rewriting is not trivial, but at least Cecil makes it less cumbersome. This sub-project is also on GitHub as ManagedPumpkin.

And obviously, whatever solution we may chose, we do not let the user change thread priorities: we may even run all the snippets in a thread with *lower* priority, so the "snippet" manager/supervisor classes are always guaranteed to run.

Control at execution time

Let's start with the basics: AppDomain sandboxing is the bare minimum. We want to run the snippets in a separate AppDomain, with a custom PermissionSet. Possibly starting with an almost empty one. 

Why? Because AppDomains are a unit of isolation in the .NET CLI used to control the scope of execution and resource ownership. It is already there, with the explicit mission of isolating "questionable" assemblies into "partially trusted" AppDomains. You can select from a set of well-known permissions or customize them as appropriate. Sometimes you will hear this approach referred to as sandboxing.

There are plenty of examples on how to do that, it should be simple to implement (for example, the PTRunner project).

AppDomain sandboxing helps with the security aspect, but can do little about resource control. For that, we should look into some form of CLR hosting.

Hosting the CLR

"Hosting" the CLR means running it inside an executable, which is notified of several events and acts as a proxy between the managed code and the unmanaged runtime for some aspects of the execution. It can actually be done in two ways:

1. "Proper" hosting of the CLR, like ASP.NET and SQL Server do

Looking a what you can control through the hosting interface  you see that, for example, you can control and replace all the native implementations of "task-related" (thread) functions.
It MAY seem overkill. But it gives you complete control. For example, there was a time (a beta of CLR v2 IIRC) in which it was possible to run the CLR on fibers, instead of threads. This was dropped, but gives you an idea of the level of control that can be obtained.

2. Hosting through the CLR Profiling API (link1, link2)

You can monitor (and DO!) a lot of things with it: I used it in the past to do on-the-fly IL rewriting (you are notified when a method is JIT-ed and you can modify the IL stream before JIT) (my past project used it for a similar thing, monitor thread synchronization... I should have talked about it on this blog years ago!)

In particular, you can intercept all kind of events relative to memory usage, CPU usage, thread creation, assembly loading, ... (it is a profiler, after all!).
An hypothetical snippet manager running alongside the profiler (which you control, as it is part of your own executable) can then use a set of policies to say "enough!" and terminate the offending snippet's threads.

Debugging

Another project I did in the past involved using the managed debugging API to run code step-by-step.

This gives you plenty of control, even if you do not do step-by-step execution: you can make the debugger code "break into" the debugger at thread creation, exit, ... And you can issue a "break" any time, effectively gaining complete control on the debugged process (after all, you are a debugger: it is your raison d'etre to inspect running code). It can be done at regular intervals, preventing resource depletion by the snippet.

# Sunday, July 31, 2016

Choices, choices, choices...

How would you design and write a system that takes some C# code and runs it "in the browser"?

In general, my answer would be: Roslyn. Roslyn was already quite hot and mature at the end of 2014; having something like scriptcs would give you complete control on each line of code you are going to execute.

But this particular project, being something that must work for StackOverflow, had several constraints, most of which were in stern contrast one with the other:
  • High fidelity: if I am asking a question about a peculiar problem I am having with C# 1 on .NET 1.1, I want my "snippet" to behave as if it is compiled with C# 1 and run on .NET CLR 1.1
  • Safe: can you just compile and execute your snippet inside your IIS? Mmmm.. not a great idea...
  • High performance: can you spin up a VM (or a container), wait for it to be ready, "deploy" the snippet, execute it, get it back? That would be very safe, but a bit slow.

Safety/security is particularly important. For example: you do not want users to use WMI to shutdown the machine, or open a random port, install a torrent server, read configuration files from your machine, erase files...
For safety, we want to be able to handle dependencies in a sensible way. Also, some assemblies/classes/methods just do no make any sense in this scenario: Windows Forms? Workflow Foundations? Sql?
For safety and performace, we want to monitor and cap resource usage (no snippet that does not terminate).

Going a deep further, I stared to dash out some constraints. It turns out that we need to disallow something, even if this means going againt the goal of "high-fidelity":
  • no "unsafe", no pointers
  • no p/invoke or unmanaged code
  • nothing from the server that runs the snippet is accessible: no file read, no access to local registry (read OR write!)
  • no arbitrary external dependency (assemblies): whitelist assemblies

Also, we need control over some "resources". We cannot allow snippets to get a unlimited or uncontrolled amount of them.
  1. limit execution time
    • per process/per thread?
    • running time/execution time
  2. limit kernel objects
    • thread creation (avoid "fork-bombs")
    • limit other too? Events, mutexes, semaphores...
    • deny (or handle in a sensible way) access to named kernel objects (e.g. named semaphores.. you do not want some casual interaction with them!)
  3. limit process creation (zero?)
  4. limit memory usage
  5. limit file usage (no files)
  6. limit network usage (no network)
    • in the future: virtual network, virtual files?
  7. limit output (Console.WriteLine, Debug.out...)
    • and of course redirect it
Does it sounds familiar? For me, it was when I learned about something called cgroups. Too bad we don't have it in windows! Yes, there are Job Objects, but they do not cover every aspect.

Could we have cgroups-like control for .NET applications?

# Saturday, July 30, 2016

Pumpink: a .NET "container"

More or less 20 months ago (gosh, time flies!) I started a side-project for a very famous company (StackExchange).
StackExchange had just launched, a few months before, a new feature on the main site of their network (StackOverflow).
This feature is called "Code Snippets", and it allows you to embed some sample HTML + JS code in a Question, or an Answer, and let the visitors of the page run it.
Of course, being JS it would run inside the browser, and with few focused precautions it can be made safe for both servers and clients (you do not want to leave an attack vector open on your servers, but you also don't want your visitors to be attacked/exploited as well!)

More details on how they implemented and safeguarded it can be found on their meta.stackoverflow.com site.

The feature got a lot of attention, and of course there where requests to extend it to other languages.
I was one of those that wanted more languages added, but I understood that JS was a very particular case.
Snippets in any other language would have meant an entirely different approach and an entirely different scale of complexity.

In October 2014 I visited NYC; before my visit I got in touch with David Fullerton, the "big boss" of SO development team. We were in touch since my previous "adventure", a few years before, when I interviewed for a position on their Q&A team. We discussed briefly about my past interview, and then he asked me a very interesting question: what would I add to StackOverflow? C# snippets immediately come to my mind.

We discussed briefly about it, drafted up some ideas, added requirements in the process (discarding most of the ideas) and finally David asked if I would like to try it out, as an Open Source experiment sponsored buy StackExchange.

... well, of course! Fun and challenging software, exchanging ideas with some of the most brilliant devs in the .NET ecosystem, and I get paid too! :)

So "Pumpink" was born. If you are curious, you can find it on my GitHub. It already contains a rather in-depth analysis about the structure of the project, and how it works.

Or, if you want to know "why?" instead of simply "how?", you can wait for the upcoming blog posts, in which I will detail some of the choices, problems, headaches that shaped the problem.

# Monday, April 06, 2015

jQuery UI datepicker: being notified of every date change

Recently, I was fighting with a Primefaces component: calendar. I was using it with my keyboard, and I immediately noticed that the ajax update that keeps the control synchronized with the bean was not working. Selecting a date with the mouse was fine, editing and pressing "Enter" was OK, but changing it and tabbing or clicking away was not.

Curious, I dug in and found that primefaces uses the standart jQuery UI datepicker, and wires itself to its standard onSelect event. But this event is fired only when you explicitly select a date, not when a date changes (through the keyboard, or code).

So, I decided to write a quick js to call onSelect when a date is updated. Here it is: I also keep track of the previous date, to avoid double notifications. And it works very well for us!
# Monday, December 15, 2014

Strangest bug of the day

System.TypeLoadException:
Could not load type 'System.Diagnostic.Debug'
from assembly 'MyAssembly'

Uhm... Hello?
Why are you looking for 'System.Diagnostic.Debug' inside my assembly? Go look inside System!

To be fair, I was fiddling with the CLR Hosting APIs, in particular IHostAssemblyStore.
Using this interface, you can override the CLR assemby probing logic, and load you own assemblies from wherever you want.
This is particularly helpful if you are using your own AppDomainManager, and you want to load it inside your sandboxed domain, which you carefully configured to disallow loading of any external assembly.
If you try to do that, binding fails, obviously. And since the AppDomainManager is created and loaded by the unmanaged portion of the CLR, you don't get a chance to use AssemblyResolve (tried, didn't work).

But that does not really justify this behavior: the Fusion log viewer was reporting no errors, and the exception was wrong (or, at least, not one of the usual exceptions you should look for when debugging binging failures).

There is a tiny parameter, called pAssemblyId. The docs are quite clear: it is used internally to see if that assembly was already loaded.
If it is, do not try to load it again. Sounds like a good optimization BUT:

The docs don't say it, but if you pass back "0", something very peculiar happens.
In my case, I had the Jitter looking for types inside my assembly. Others had different issues.

That was definitely the strangest bug of the day :)