For those living under the scientist/math/geek/nerd radar, Pi Day is a celebration of the aforementioned famous constant that is hold on 14/03 every year (or as American would put it, 3/14 hence the catch). As always more information on the Wikipedia page.
To celebrate a bit, I rewrote from memory the demonstration I was given once that use congruence to demonstrate the well known division trick that says a number is divisible by 3 if the sum of its digit are also divisible by 3 (or vice versa).
So for instance, we know that 13905 is divisible by 3 because . In modular arithmetic terms, we say that .
Following is the demonstration in a obfuscated way for a sample 4 digits number (can be generalized to any digit number):
Some more explanations:
The basis of the demonstration is to first say that any number is a sum of power of ten. If I take my previous number 13905, I can also say it’s .
Then we start our equivalence chain by assuming we have a number n divisible by 3 and then walking our way by taking its power of ten sum representation
Due to the fact that 10 has a remainder of 1 when divided by 3 and using the properties of congruence, we reduce our initial expression to only use the initial number digits.
Then as the the initial number was divisible by 3, we come to the conclusion that the sum of its digit is also divisible by 3. Plus, since everything was made by equivalence, we know we can go the other way around too
That’s it. You can have a similar reasoning for the other well know multiplication trick that says a number divisible by 5 always ends up with 0 or 5 (this time based on the fact that any power of ten with a power superior to 0 is divisible by 5 and thus has a remainder of 0).
Macdoc is the new Mono API documentation browser build entirely with MonoMac (Cocoa bindings for .NET). It has been recently shipped as part of the latest MonoDevelop beta for Mac users where it replace the excellent GTK+ version we use everywhere else.
It was my first time hacking on any MonoMac app and along the way I came up with a couple of pieces of code that, I think, could be used as general recipes for MonoMac development.
Apple docs being severely lacking (or plainly useless) in some aspect of Mac development, some recipes also covers some general Mac constructs. MacDoc being a NSDocument-based application, recipes are given with respect to that style of Mac coding.
So, among the menu today we have:
Answering Open URL commands
Escalating privileges
Uncompressing .xar archives
Fighting WebView or how to handle image requests yourself
Redirecting printing to a WebView in a NSDocument application
Answering Open URL commands
Any Mac application after being started can receive an number of external signal called Apple events that are sent by other processes to ask the application to do something.
One of these Apple Events called GURL (the four chars code for « Get URL ») is a way for the application to receive URL request it can open from the outside world. So, for instance in MacDoc case, we respond to mdoc:// and monodoc:// that MonoDevelop send to update the documentation page we are showing to the user.
To answer these Apple events, there are a number of existing API. One of them is Carbon (part of the low level suite of Apple API) and an example of its usage can be seen in MonoDevelop and the GTK+ version of MonoDoc (e.g. MacInterop folder in MonoDevelop Mac addin).
But more interesting in the context of Cocoa application, there is a Objective-C wrapper called NSAppleEventManager around these C calls that is available as part of MonoMac master in the Foundation namespace.
If we return to our « Get URL » example, to let the system know that you can handle certain types of URL, you first need to set up some lines in your application Info.plist file. This will let tools like open (and more generally anything using the Launch Service API) automatically load your application when it’s used with an URL your are able to open. In MacDoc case, I paste below the relevant Info.plist lines for the two mdoc:// and monodoc:// URL schemes we support:
Now to catch an event, we decorate a callback method with the [Export] attribute and an Objective-C selector name. In MacDoc case we define the handler this way:
[Export ("handleGetURLEvent:withReplyEvent:")]
public void HandleGetURLEvent (NSAppleEventDescriptor evt,
NSAppleEventDescriptor replyEvt)
I will show in a minute how you can process the arguments of this callback to extract the URLs. For now, let’s see how we register this callback with the event system via the NSAppleEventManager class:
public override void WillFinishLaunching (NSNotification notification)
{
var selector = new MonoMac.ObjCRuntime.Selector ("handleGetURLEvent:withReplyEvent:");
NSAppleEventManager.SharedAppleEventManager.SetEventHandler (this,
selector,
AEEventClass.Internet,
AEEventID.GetUrl);
}
As you can notice, the call to NSAppleEventManager is made inside the NSApplicationDelegate.WillFinishLaunching override. In the Cocoa application startup cycle, this method is called when all default handler have been setup but no event has been processed yet making it a good candidate to register our own event handler.
Now, let’s see how we can extract the received URLs from the event data. Apple events can have complex data attached them ranging from simple number/string to nested list of them.
For the « Get URL » event, the URLs are stored in a simple list of string which you can process in normal for loop:
[Export ("handleGetURLEvent:withReplyEvent:")]
public void HandleGetURLEvent (NSAppleEventDescriptor evt, NSAppleEventDescriptor replyEvt)
{
NSError error;
// Received event is a list (1-based) of URL strings
for (int i = 1; i <= evt.NumberOfItems; i++) {
var innerDesc = evt.DescriptorAtIndex (i);
var url = new NSUrl (innerDesc.StringValue);
// Do something with URL
}
}
As you may have noticed, elements index inside a list are 1-based and not 0-based like we are used to.
Escalating privileges
Mac OS X being a UNIX operating system, it has a clear separation of privileges based on the traditional user mode system where root is the only account that can do anything on the system.
Although most applications are just fine running under a normal user, you may sometimes need to escalate privileges if at some point you want to, for instance, write files to a protected system directory.
There are two ways to do so, either upgrade the running process to a better user or launch an external process with better privileges than the calling one. Apple preferred way seems to be the second option (although they won’t really like an app that needs to be fully run as root in their Store anyway).
For Linux users, this is akin to using a sudo GUI (e.g. gksudo). Apple provides its own way to do the same thing with a C API of their own called SecurityFramework (and it’s Objective-C brother Security Foundation).
SecurityFramework, is a very much stupid low-level C API and although there is an Objective-C wrapper, it’s just an excuse for « Sorry we can’t do any better ».
Thankfully, we have the AuthorizationExecuteWithPrivileges shortcut call that make launching an external root process a bit easier. Be careful though because it was deprecated in Lion.
The following class and its LaunchExternalTool method let you start an external application as if run by the root user:
public static class RootLauncher
{
const string SecurityFramework = "/System/Library/Frameworks/Security.framework/Versions/Current/Security";
public static bool LaunchExternalTool (string toolPath)
{
IntPtr authReference = IntPtr.Zero;
int result = AuthorizationCreate (IntPtr.Zero, IntPtr.Zero, 0, out authReference);
if (result != 0) {
Console.WriteLine ("Error while creating Auth Reference: {0}", result);
return false;
}
AuthorizationExecuteWithPrivileges (authReference, toolPath, 0, new string[] { null }, IntPtr.Zero);
return true;
}
[DllImport (SecurityFramework)]
extern static int AuthorizationCreate (IntPtr autorizationRights,
IntPtr environment,
int authFlags,
out IntPtr authRef);
[DllImport (SecurityFramework)]
extern static int AuthorizationExecuteWithPrivileges (IntPtr authRef,
string pathToTool,
int authFlags,
string[] args,
IntPtr pipe);
}
Uncompressing .xar archives
Xar is an extensible archive format using an XML document to keep its inner filesystem information. It’s used by a lot of stuff distributed by Apple like, in MacDoc case, all their documentation bundles.
Xar is available by default on every Mac OS X installation and it has a very simple and straightforward API available in the libxar library making it really easy to bind.
In our case, we just needed to be able to decompress a Xar archive where we wanted which is easily achieved with the following class and its Extract method:
Process is pretty simple really, the only catch being that xar extract archive filesystem based on the current working directory which is why we adapt this setting to the given parameter. You thus need to be careful if for some reason you want to execute more than one call concurrently.
Fighting WebView or how to handle image requests yourself
WebView is the widget which can display any kind of rich HTML using Webkit. It has some integration with the embedder, letting it decide how the WebKit engine should handle some operation (e.g. link navigation). What it doesn’t let you do though is handle linked content request yourself i.e. any resource that needs to be downloaded separately (images, external scripts,
, …).
In our case, we try as much as possible to display inlined HTML (including the CSS and our small bit of Javascript) inside the widget for our documentation and for default images we could certainly well extract them in a known place on disk and point the browser to it.
What we couldn’t act on however were the internal images referenced from documentation as WebView doesn’t let you catch Web request and feed on your own data. Thus we needed a way to trick the system to let us inject our own bytes at some point.
As I said earlier, for convenience we try to inline as much stuff as possible, so taking that reasoning to images, we needed to do the same thing for them. Enter the Data URI scheme which let you embed raw data (or well, base64 encoded data) directly as content.
What we can thus do with our WebView is to hack on the DOM when the page has loaded to detect places where a <img /> tag referencing an internal image resource is used and fill that tag with raw data taken from our store.
If we want to manipulate the DOM, we need it to be properly initialized. A way to do that is to hookup our method to the FinishedLoad event which tells when the DOM is ready for consumption for the currently loading document (remember that loading a page is asynchronous in a WebView).
The method itself which fetch image tags and fill them with our data is given below:
var dom = e.ForFrame.DomDocument;
var imgs = dom.GetElementsByTagName ("img")
.Where (n => n.Attributes["src"].Value.StartsWith ("source-id"));
byte[] buffer = new byte[4096];
foreach (var img in imgs) {
var src = img.Attributes["src"].Value;
// Our specific call to get an embedded image stream
var imgStream = AppDelegate.Root.GetImage (src);
if (imgStream == null)
continue;
var length = imgStream.Read (buffer, 0, buffer.Length);
var read = length;
while (read != 0) {
if (length == buffer.Length) {
var oldBuffer = buffer;
buffer = new byte[oldBuffer.Length * 2];
Buffer.BlockCopy (oldBuffer, 0, buffer, 0, oldBuffer.Length);
}
length += read = imgStream.Read (buffer, length, buffer.Length - length);
}
var data = Convert.ToBase64String (buffer, 0, length, Base64FormattingOptions.None);
var uri = "data:image/" + src.Substring (src.LastIndexOf ('.')) + ";base64," + data;
((DomElement)img).SetAttribute ("src", uri);
}
The two application-specific parts of this method are how we recognize a tag pointing to an embedded image (in our case their src attribute value is prefixed with « source-id ») and the call which get us a Stream for the image (here we get it from our documentation bundle). The rest is mostly stream reading boilerplate.
Redirecting printing to a WebView in a NSDocument application
Having a NSDocument-based application means a couple of standard operation are made easier for you to use. One of them is printing which simply require a couple of plumbing with most of the heavy lifting left to Cocoa.
What you may want to do however is to only print a part of your UI, generally the one that display the actual document content which is not something Cocoa can guess for you.
In MacDoc case, the WebView that show the API documentation is what we are interested in printing so let’s see how can redirect global print request to that specific part of the application.
First, we need to register an action on the Print menu item that points to our subclass of NSApplicationDelegate. In the action implementation, we will simply redirect the call to the currently activated document:
Now by default, this will actually try to print the currently focused widget in your document UI which is most of time not something you want (feels weird to print a button).
As told earlier, most of the time what you rather want is to print a specific part of the UI. Fortunately, almost all widgets that display rich content also have an implementation of a print operation. WebView is no different and this the widget we are going to use as an example.
So, to redefine the printing behavior of a document, the first thing you need to do is to override the PrintOperation method in your NSDocument subclass.
Then, your simply fetch the current FrameView displayed by your WebView and proxy the print operation through it. This could be something like this:
public override NSPrintOperation PrintOperation (NSDictionary printSettings,
out NSError outError)
{
outError = null;
return webView.MainFrame.FrameView.GetPrintOperation (new NSPrintInfo (printSettings));
}
The given NSDictionary parameter is a raw representation of a NSPrintInfo so it’s enough to simply instantiate the later with the former. The returned print operation will contains what’s necessary to print the rendered HTML shown by the WebView.
A little more than a month ago, I had the last university exams of (hopefully) my whole life, closing a 5 years period of a fun student life.
At the end of this week, I’ll be back in Dublin (Ireland), a town I left a year ago to finish my master degree, where I will be working together with a well acquainted Irish fellow.
As you may have guessed, that means I’m now a full-time Xamarin employee!
I’m also in the slow process of getting a VISA which should allow me to move to Boston in a (preferably) reasonable amount of years.
This summer I have been working again as a Google Summer of Code student for Mono. This time, I re-implemented another parallel-related library called TPL Dataflow.
It’s still a research project at Microsoft and it has recently released a preview version of the framework which is designed to work well with the asynchronous features of the latest .NET CTP.
The goal of the framework is similar to PLinq in the sense that you construct a pipeline composed of blocks expressing individual operation (action, transformation, join, fork, …) with the notable difference that the model is push-based instead of pull-based.
Push-based basically means that, in the same way than the Reactive Extensions, you explicitly feed data to your pipeline instead of acquiring it from a source. Then the final data can be received or processed by a block at the other end of the chain.
All of that makes a nice model for asynchronicity that you can use both to send or receive data thanks to a number of extensions method in the framework (suffixed by Async) which returns a Task thus letting you setup continuations or use the new await keyword (also available in Mono master btw).
Under the hood the framework is built upon what ParallelFx provides like the concurrent collections and the task primitive meaning it’s also taking full advantage of the available parallelism on your machine.
The code is now available directly from Mono master and is built in the System.Threading.Tasks.Dataflow assembly with the 4.0 profile. While not totally complete, it’s still already usable.
MSDN doesn’t yet show the documentation so I uploaded the copy shipped with the preview.
You can also watch Stephen Toub introductory video for a tour of the framework (also embedded below).
It took around 20 years for CPU manufacturers to abandon the GHz war on the desktop and start going multicore.
In the mobile space and only 3 years after the first Android smartphone, we are already seeing dual-cores phones (with quad-cores around the corner). Recent tablets are on the same boat.
The brilliant thing is that with Monodroid and Monotouch, we have the possibility to harness this new found processing power today using all the existing ParallelFx constructs since they are part of both distributions (i.e. Tasks, continuations, parallel loops, PLinq and friends).
To illustrate that, I ported the now classic raytracer code from the Parallel sample gallery to Android using Monodroid. Code is on GitHub if you want to give it a spin.
While the application itself is painfully slow since all rendering is in software, it does exhibit the same speed improvement when you ran in parallel mode as with the desktop version on my dual-core smartphone. For iDevices lovers, Geoff also had a similar version running on an iPad 2.
If you are at Monospace and want to talk about that stuff (and ParallelFx in general), don’t hesitate to come and say hi. Anyhow, I’ll continue to post more examples of how you can use ParallelFx practically in your mobile apps.
PS: as you’ll see in the source, there are some hacks bundled because of a couple of Mono bugs but they will get fixed eventually.
_________________________________
< All your moos are belong to us >
---------------------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
Upon my latest Twitter question and getting no further answer, I carried out even more (useful) Manos world domination by writing Moo, an online cowsay generator (code on github under beer license).
Cowsay is one of those obscure Perl thing from the dark hacker age that once plagued mails and terminals.
It basically consists of a variety of ASCII animals (not limited to cows actually) telling some text inside bubbles. Useless therefore essential.
All of that offering me the shameless plug of telling the world I’m attending
Initial reading on what is WebMatrix can be found on Scott Guthrie blog.
After team WebMatrix was formed this week, I have reimplemented the Data part of WebMatrix, a cute layer on top of ADO.NET with support for the dynamic keyword (C# 4) so that you can directly call property equivalent to your column names.
Bonus point is that even though is has been shipped with a heavy slant towards SQL Server (and its new compact counterpart) since it’s implemented on top of stock System.Data.Common we can use any provider with it including the great old-fashioned SQlite provider.
Say I have the following SQlite database:
That is populated with these values:
You can now write code like this to query the database:
using System;
using WebMatrix.Data;
class WebMatrixSample
{
public static void Main ()
{
var db = Database.OpenConnectionString ("Data Source=sqlite.db;Version=3;", "Mono.Data.Sqlite");
var result = db.Query ("select * from Phonebook where Number glob '0*'");
foreach (dynamic row in result)
Console.WriteLine ("({0:D2}) {1}: [{2}]", row.Id, row.Name, row.Number);
var entry = db.QuerySingle ("select * from Phonebook where Name = @0", "Rupert");
Console.WriteLine ("Rupert number is {0} with id {1}", entry.Number, entry.Id);
Console.WriteLine ("but really his number is just {0}",
db.QueryValue ("select Number from Phonebook where Name = @0", "Rupert"));
// And let's add my bank number
db.Execute ("insert into Phonebook(Name, Number) values (@0, @1)", "Bank", "01xxxxxxx");
}
}
WebMatrix.Data assembly is now available when you compile Mono from Git master.
As a lot of people I started doing programming during my HTML days when I needed to add a bit of interactivity with some layers of PHP. Realizing that what I was coding was both ugly and useless, I moved on to other stuff and distanced myself from web development altogether.
Meanwhile, the Web became much more feature-full than what it was at the time and when I took another dive these past weeks I grasped how it had grew since with HTML 5, CSS3 or jQuery (yeah I know I was out of the wheel for a long time) to the point it was actually enjoyable.
But what really motivated me to come back was the recent release by my esteemed colleague Jackson of his Manos web framework which, even though designed for cartels, was at long last providing a simple environment and simple interface to read and output valid HTTP headers in .NET/Mono.
The use case
Since I never really bothered signing-up for these Twitter image sharing website for the two or three pics I post per year and since I had no need of a special app for a badass smartphone I don’t have, I was leaning towards something FOSS and simple I could deploy on my own server which of course I didn’t find (if I was mistaken, replace that part with « I love reinventing the wheel »).
Thus Apachaï was born (on GitHub). It’s a KISS solution to a basic workflow: « let me post a pic quickly and write my twitter message at the same time ».
It does so by leveraging Twitter’s SSO using code borrowed from Miguel de Icaza‘s TrollStation. It also have some nice goodies like simple image effects courtesy of Pinta (yay for easy code reuse).
Data management is handled by Redis because it wouldn’t have been wicked enough without some NoSQL sparkles (nice thing though). Plus Redis is so lightweight that it is not a big dependency really.
Oh and because eating your own soup is good, Apachaï uses ParallelFx’s Future and continuations to process long-running operations without blocking Manos itself so it’s an example of using ParallelFx in a web context. I also made a choice of not using any specific templating system, MVC or whatnot. The HTML is always served as a basic empty container and all specific elements are dynamically filled with Javascript and some JSON serialization routes (see why Manos and futures fit?).
Apachaï screenshot
Finally
So to summarize:
Apachaï is a small and lightweight photo and picture sharing application (for services like Twitter) built on the Manos framework
A public instance for your usage is available at apch.fr
The past few weeks, I have given some cycles to test and ultimately make sure existing ParallelFx softwares from the .NET world could run on our Mono implementation.
As a result, I’m happy to say I was able to run most of the three of them and they were of a great help pinpointing some non obvious corner case of the API. Practical consequence is that to also run them you will need Mono from master.
Following is a bunch of notes specific to each of these projects:
Parallel Extensions sample gallery
This project actually also contains the parallel extras library which provides a bunch of new constructs and extensions to the classic ParallelFx API that you can reuse in your own project.
At the moment though, you should be aware that the license used doesn’t allow reusing the code on a platform different than Microsoft Windows but this will hopefully be changed in the near-future to use a wider free/open-source license.
In this gallery, I was only able to test the projects that didn’t specifically use non-supported library in Mono such as WPF. For the rest of them, using our xbuild tool does the trick of compiling the code.
If you happen to have a software that use one of those code path I hadn’t had a chance to test and if you can share the application with me I can also give it a spin.
Microsoft Biology Foundation
This project is a heavy user of almost everything in the framework ranging from concurrent collections to PLinq and is quite a hungry memory and CPU eater.
Since I couldn’t find a proper application leveraging this framework, I simply turned to the performance test suite bundled in the project which works fine although some test eats up quite a lot of memory (as always, running under sgen helps here).
The code actually requires a couple of extra tweaks if you want to run the performance test suite correctly but for compiling the core framework itself, again xbuild should be sufficient.
RavenDB
Last but not least, RavenDB is an engine part of the NoSQL and document database movement but with a slant towards .NET (with Linq integration for instance).
Rob Ashton decided to try to run the beast on Linux and I gave him a hand to tackle the few incompatibilities between Mono and .NET result of which can be found in his GitHub repository: https://github.com/robashton/ravendb/tree/mono
The test suite is running well enough with a total of 531 tests passing out of 588. Some of the failure are perfectly normal (like the tests using Microsoft-only native librairies) and another good portion is probably casual portability mistake (like hardcoded path and such).
It would actually be much appreciated if those knowing how the framework work could help triage these failures and find what is Mono bugs and what is not so that we can fix them.
Some tests also depend on not implemented features in Mono so if you feel like it, you could also contribute these missing code pieces or provide a workaround in RavenDB.
Recently Dublin got busy with the first ever MeeGo conference being organized for developers. For 3 days, geeks invaded the shiny (and overly expensive) Aviva stadium for talks, fun and code. It was also a cool opportunity to meet up with someesteemedNovellcolleagues.
Among other goodness (hat off to the organizers for a truly top-notch event), Nokia and Intel in their great wisdom decided to hand out a free Lenovo S10-3t netbook/slate (pre)loaded with MeeGo to get our hand dirty with. I’ll probably discuss about MeeGo itself in another blog but for now I want to write here the couple of step I had to take to turn the Netbook edition into something suitable for the slate mode the Lenovo can adopt.
Basically by following this guide you will have: a working on-screen virtual keyboard and a tweaked Chromium understanding touch for scrolling.
The first step is to setup the keyboard. First of all, you have to enable the Handset repository to pull down some compatibility component (i.e. GTK+ immodule):
$ cd /etc/zypp/repos.d/
$ sudo -s
$ cp netbook.repo handset.repo
$ sed 's/netbook/handset/' -i handset.repo
$ zypper refresh # at this point you will probably have a security alert, ignore it
$ zypper install meegotouch-inputmethodbridges meegotouch-inputmethodkeyboard meegotouch-theme meegotouch-theme-meego libmeegotouch-qtstyle meegotouch-systemui
To avoid a weird parsing bug, comment out line 715 in /usr/share/themes/base/meegotouch/libmeegotouchcore/style/commonlayouts.css.
Then, open up the file /etc/xdg/autostart/meego-im-uiserver.desktop and change the Exec line to /usr/bin/meego-im-uiserver -target slate -bypass-wm-hint. Finally, append ;X-MEEGO-NB to the OnlyShowIn line (or remove it altogether), save, close up and restart your computer (all applications including MeeGo panel basically need to be relaunched to load up the new input engine so it’s the most straightforward way).
If everything went well (if not check that the process is alive and not choking), you should have a fair sized keyboard appearing at the bottom of the screen when a text field gets the focus.
Some comments here. The enter key on this keyboard is hidden behind the two modifier keys (bottom-left) and is only a n appender (read, it won’t fire any activated event). Thus when you need to validate something you have to either use your real Enter key or find a way around (« clicking » chrome first completion for an address, tweet/publish buttons, …). To make the keyboard go away (because it doesn’t resize any part of the UI it’s hiding) you have to use a ninja swipe to the bottom that precisely start at the top of the keyboard without touching a key (I did prepended ninja there).
On the web browser side (who use a slate for something else?), there is an extension that provide the scrolling gesture Android & IPhone user will be familiar with. To get websites to take you as a slate you can resort to the good old user-agent trick and make yourself look like an iPad though, as far as I tried using it, special interface such as GMail one doesn’t work.
To get back the MeeGo panel on the top when you don’t have access to the Windows key, a really high touch-click on the screen will still get it to slide down for you.
EDIT: on the matter of having the keyboard hiding the UI beneath it, if you don’t use the keyboard in software mode (that is, no -software switch in your .desktop), you can make most of the keyboard transparent by opening /usr/share/themes/base/meegotouch/svg/meegotouch-keyboard.svg and adding an opacity value in the style attribute of the svg root node, something like (extra attributes stripped for readability):