Lars Wilhelmsen

Connected Systems MVP

Skip to: Content | Sidebar | Footer

Parsing the command line with MGrammar – part 1

16 March, 2009 (20:56) | C#, Codename+Oslo, DSLs, MGrammar | By: larsw

Let’s take a look at how we can use MGrammar to create a mini-DSL for a language most developers knows quite well; command line arguments. Most applications that accepts arguments on the command line in Windows (or in Linux/Un*x for that matter) is on the form:

Application.exe /a /b 123 /c “some input string goes here”

Some applications uses / as the “marker” that an argument is following, while other use - or . It is also quite common to allow both a verbose and an abbreviated version of the same command.

Well, that was the Command line 101. Here’s a brief explanation and some code on how we can do this with MGrammar + C#.

Here’s a screenshot of Intellipad where the MGrammar for the command line parsing DSL is displayed in the second pane (Click the image to show the picture in full size):

image If anyone has a Windows Live Writer plugin that does syntax highlighting of of M & MGrammar – please send me and email :-)

[Side note: Since the grammar for M & MGrammar is shipped as a part of the Samples in the Oslo SDK, it should be quite easy to put together a basic HTML syntax highlighter for both languages by loading the compiled grammar up and use the Lexer in System.Dataflow. Note to self: Investigate this further]

If you’re not familiar with MGrammar, I’ll walk through the cmd.mg for you. The general idea is that MGrammar helps you transform text (the input) into MGraph, a Directed-Label Graph, that can contain ordered an unordered nodes. The MGraph can then be traversed and acted upon.

The language CommandLineLang resides in a module named LarsW.Languages. the module keyword works pretty much as namespace NNN in C# and is used to divide the world into smaller pieces. Things that lives inside a module might be exposed to the outside by using the export keyword (not shown in the example) and thing from the outside might be welcomed in by using the import keyword.

The same way void Main(string[] args) is the default entry point in a C# application, syntax Main = …; Is the entry point in a MGrammar-based language.

In general, there are two things we need to work with in a MGrammar; syntax  and token statements. Last thing first; tokens are regular languages (regular expressions) where you can define the set of characters that will make a match using unicode characters, sequences of these and the normal Kleen operators; ? for optional elements, * for zero-to-many and + for one-to-many. Paranthesis – () – can be used for grouping of sets and | is used for choosing between two options. If you are familiar with regular expressions, writing tokens should be quite easy. Not that you can, and will, write the tokens in a hierarchical fashion, since your grammar would turn into a complete mess if you have to expand a lot of the regular expressions.

Syntax rules describe the context languages and can be made up by tokens and other syntax elements. You also have the possibility to project the matched tokens differently with the => operator. Without this you would have to do a lot more of coding in your backend code, so you will definitely want to exercise your grammar in Intellipad with some samples until you’re satisfied with the MGraph it outputs.

   syntax Rule = tToken tString tStatementTerminator;
   syntax Rule = tToken string:tString tStatementTerminator
             => Rule { Value { string }};

While not used in this sample, recursive rules is an essential building block in order to build grammars that can consume things like a comma-separated list (or repeating elements in general).

A repeating rule can look something like this:

   syntax Items = item:Item => Items {item}
                | items:Items item:Item
                 => Items {items, item};
   syntax Item = ...;

As you probably notice, the Items rule is used inside itself – so this rule is recursive. The “problem” with this type of syntax rules is that they produces nested nodes in the MGraph. This isn’t really a problem, but it makes the traversing in the backend more tedious. To mitigate this, The Oslo team came up with the valuesof() construction that will “flatten” out a set of hierarchical nodes for you:

   syntax Items = item:Item => Items {item}
                | items:Items item:Item
                  => Items {valuesof(items), item};

The Interleave keyword basically tells the lexer which tokens it can ignore. This will typically be whitespace and comments.

So now that we know some of  the basics, lets take a look at cmd.mg again. It basically consists of four syntax rules and four token rules. I’ve applied custom projections to most of the rules so that the MGraph production looks reasonable sane.

In the next installment of this series I will discuss how we can create a backend that will consume the MGraph and take action on the command line parameters.

The source is released under the Apache License 2.0 and can be found here: http://github.com/larsw/larsw.commandlineparser . This is the first project I release on GitHub, and if the experience is good, I believe I’ll continue to use it.

There’s a Download button that you can use to download either a zip or tar ball of the source tree, if you haven’t installed git.

kick it on DotNetKicks.com

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Awakening from the Winter Hibernation

15 March, 2009 (12:55) | Codename+Oslo | By: larsw

First of all; I would like to apologize for not producing any new content on this blog the last couple of month. There are many reasons for that; a lot of work for my current customer, being together with my son as much as possible – and the probably most important one; it’s been a really dark, cold and snowy winter here i Norway :-( I’m no bear – but I feel that I’ve been hibernating this winter. Since the days is getting longer, I need to do as the bear; wake up from the hibernation and get “online” again. For those of you that follow me on Twitter, you’ve probably noticed that that is almost the only social networking platform that I’ve used for a couple of months.

Another reason why I haven’t been around much either here or in the WCF forum is that I’ve gone into learning mode – and for the time being I’m focused at Codename “Oslo”.

I had the chance to attend the Global MVP Summit in Seattle last week and it was a blast! The whole conference was under a NDA that most people that use Twitter probably noticed, so I can’t go into a lot of details that was presented during keynotes and sessions.

But it’s not a secret that I’m a Connected Systems Developer MVP – and because of that, I “belong” to the Connected Systems Division. CSD as it is also called owns some great existing products like BizTalk, WCF & WF but the currently most hyped project is Codename “Oslo”. Revealed at the Professional Developers Conference in LA last October as Microsoft new platform for model-driven development. They state on the Oslo Development center that we should expect a ten-fold productivity increase – something that they’ve still to prove to us.

A lot of people I’ve talked to are really confused about what it is – and what technologies that sits under the “Oslo” umbrella.

For a period, I will try to write some blog posts to explain what “Oslo” is, what it can be used for and what I see as its strong and weak points (at the moment). No good explanations without code you might say – and that is totally correct.

First off, I’ll start with MGrammar – a language in the M* family for creating Domain-Specific Languages. This might not be a top-down approach to the Oslo platform, but I want to show some working code – and MGrammar is the technology I’ve been focusing mostly the last weeks.

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

A look at Microsoft Tag

13 January, 2009 (20:01) | Microsoft Tag, Mobile | By: larsw

Some days ago, Katrien De Graeve, a DE at Microsoft Belgium twittered

I want new full color business card with ‘attached’ vCard – http://www.microsoft.com/tag/ – no more typing over contacts!

Tag. Tag? Microsoft Tag? Business Cards? vCards? I had to check this out, so I popped the URL open in a web browser and took a look. I turned out to be a tag system that is currently in beta – developed by Microsoft. 2D Barcodes is nothing new, but until now, they have been composed by tiny black and white dots arranged in a rectangle.

Accompanying the new tag system is a mobile client – or more specific – mobile clients that enables you to just point your camera at at tag and it will automatically fetch the linked data, whether it is an URL, a vCard or some free text. You just point – you don’t have to press the camera button.  The current beta is free for personal usage, but Microsoft sees a commercial market for the system. When you have created an account and created your first tag – that you can render into PDF, WMF or XPS in different sizes and with different layouts, you will be able to track the usage of the tag with a reporting functionality located on the account page.

One of the render options is to add “Get the free app for your mobile at http://gettag.mobi/ ” a web site optimized for mobile clients, that sports the different kinds of mobile clients. The list of available clients are quite impressive;

  • Windows Mobile (of course)
  • Android
  • Blackberry
  • iPhone
  • Java 2 Micro Edition
  • PalmOS
  • Symbian S60 (incl. 1st, 2nd & 3rd edition).

 

So, I challenge you all to download the software to your mobile and see what’s underneath the following tag:Tag!

For extra credits, I challenge you to put up your own tag(s) on your blog (all of the Norwegian techie/twitter posse – consider yourself tagged) and optionally send me a link in the comments field below :-)

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Microsoft Connected Systems MVP 2009!

2 January, 2009 (13:40) | Connected Systems, Microsoft, Microsoft MVP | By: larsw

Microsoft MVP logo Yesterday, I received an email I have been hoping for (more than any of the Christmas gifts I got :-P ) with the subject:

Congratulations 2009 Microsoft MVP!

I’ve known for some time that I was nominated for the Connected Systems Developer MVP, so I have really been anticipating the arrival of 2009 – 01 – 01.

The mail didn’t show up before 1520-something in the afternoon, so I went around with butterflies in my stomach all day trying to keep my thoughts elsewhere; my son need a lot of attention, so we rolled out a gymnastics mat in the living room and had some fun.

Since I’ve now received the Connected Systems MVP award I feel quite humbled; If you check out the MVP awardees website (my profile isn’t up yet) you will probably notice a lot of hotshots in that category – to namedrop a few; Juval Löwy, Michèle L. Bustamante, Christian Weyer, Aaron Skonnard, Pablo M. Cibraro, Dan Rigsby, Brian Noyes (and the list goes on and on and on…)

Hopefully I’ll persuade my boss so that I can attend the Global MVP Summit in Redmond in the start of March. I believe that would be a really epic experience. I know a couple of other MVPs & RDs that probably will go – Einar Ingebrigtsen of Objectware being one of them (DirectX/XNA MVP) (Thanks man for mentioning my MVP before I got to blog about it myself :-) .

As a part of my continuing effort to put more time into community work, I would like to do more with this blog site, so I’ve decided to host it somewhere else, since my current host, wordpress.com, is quite limited. As of now, it looks like I’ll put up the site on one of my company’s servers.

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Configurable PrincipalPermission attribute

17 December, 2008 (13:50) | .NET, Programming, Security | By: larsw

I while ago, a question came up in the WCF Forum about configuring the role and/or user name properties of the PrincipalPermission attribute. As I answered, it is possible to create a custom version of the attribute (deriving from the CodeAccessSecurityAttribute, since the PrincipalPermission attribute is sealed) and pull the property values from the {web|app}.config file.

I implemented a solution for this about a year ago and planned to put up a blog post about it, but it never made it out to the public (the main cause is probably that I experienced a blog-block period of my life :-P ).

The same requirement may be a viable solution i system I’m currently working on for a customer, so I dug through my archives and found the old code.

I’ve polished it a bit made it available here under the Apache License 2.0.

The extended version, PrincipalPermissionEx can be used in two modes; either as a “normal” derivable PrincipalPermission attribute or an attribute that uses the configuration system (or a combination of both).

Instead of using the generic PrincipalPermission attribute, you’ll make derived version for each system role with a sensible name – making it more reliable and resistant to typos; e.g.

[MustHaveSuperUserPrivilegesPermission]
public void PrivilegedOperation(…)
{
}

instead of:

[PrincipalPermission(Role = "MYDOMAIN\SuperUsers")]
public void PrivilegedOperation(…)
{
}


Take a look at the supplied sample code to see how this is implemented.

The usage of PrincipalPermission-based authorization is useful in a variety of scenarios; it can be applied to WCF services, ASP.NET & Smart Client applications. Note that if you put the user name/role in the configuration file, you will need to ensure that the file is locked down with an appropriate ACL to prevent tampering by malicious users. This might not apply to solutions hosted on a locked down server (i.e. IIS-hosted web applications and services) but for smart / desktop clients where the user might have higher privileges to files on the local file system it is necessary to be aware of this.

As always, feedback is welcome :-)

kick it on DotNetKicks.com

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

LINQ to XML: XPathSelectElement Annoyance

12 December, 2008 (14:08) | .NET, Annoyance, Bug?, LINQ to XML, Programming, XPath | By: larsw

It may be me – since I’m no XPath (or XSLT) pro, but the following is in my book a bug – or at least an annoyance category 3:

Given the following XML document loaded into an XDocument:

<?xml version="1.0" encoding="utf-8"?>
<Elements>
  <Element Id="1" />
  <Element Id="2" />
  <Element Id="3" />
  <Element Id="4" />
  <Element Id="5" />
</Elements>

The following XPath should  yield the first element of the list:

"//Element[@Id = '1']"


Guess what? If use the .XPathSelectElement() extension method, the result will be null – nada!

"//Element[@Id='1']"


The same query without the whitespace around the equal sign will give you the right result.

If you’re an XPath pro I would like your opinion on the matter – or else I’m turning this issue over to http://connect.microsoft.com/

Sigh.

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Codename “Velocity” WF/WCF Persistence Provider

11 December, 2008 (20:24) | .NET, Persistence Provider, Programming, WCF, WF | By: larsw

So, it’s been a bit quiet here lately. The natural cause of it is (in no particular order):

  • A lot of work
  • Spending quality time with my son
  • Hacking on different kinds of technology bits (mainly pieces released at the PDC 2008)

I’ve also tried to get a clear picture of my “blind spots” when it comes to WCF. Even though I feel quite competent, there are still tons of stuff that I don’t touch daily so I still have to “rehearse”.

Since I have “Get to know Workflow Foundation – for real” on my TODO list I spent some time playing with durable services.

The persistence provider mechanism that is located in System.WorkflowServices is not exclusive to to Workflows / Workflow services. It can also be used with “vanilla” WCF Services.

The idea is that the framework can persist the service instance after you have invoked a method and when a future method invocation comes down the wire, it can pull it from the persistence store – revive it and pass the call to the “same” instance. A perfect fit for the scenario of long running services.

So how do you enable durable services? It is quite easy. First, you decorate your service implementation with [DurableService] and one of the mechanisms that specifies that the type is serializable (I chose [Serializable] for the sake of simplicity).

image

In this code snippet we also see that there is another attribute that can be used to tell the persistence mechanism that a call to an operation creates the instance or tears it down; [DurableOperation].

The next thing you have to do is to wire up a persistence provider using either configuration or programmatically.

Out of the box there exists only one Persistence Provider; One suited for persisting the service instances to SQL Server – System.ServiceModel.Persistence.SqlPersistenceProviderFactory. You will have to set up a SQL Server Database instance with the schema located in C:\Windows\Microsoft.NET\Framework\v3.5\SQL\EN.

But that was a digression – now back to my custom “Velocity” Persistence Provider. If you don’t know what Codename “Velocity” is, I suggest that you head over here and read more about it. The short description:

It is Microsoft’s attempt to create an in-memory, high-performance, distributed caching supporting different scenarios that can suite many needs in both a web farm or other places where caching is needed. The current version that is publicly available is CTP2. We should expect a new CTP in March (around the time of MIX’09) and the RTW/RTM in the mid of 2009.

To implement a custom persistence provider, you will have to create two classes; the persistence provider implementation and its factory. It is the fully qualified type name of the factory that is specified when you set up the configuration.

The following configuration snippet shows how a custom service behavior is set up. You will have to set the behaviorConfiguration attribute on the service element to “defaultServiceBehavior” in this case.

image

The code for the provider is available here (Licensed under the Apache License 2.0).

Cheers :-)
kick it on DotNetKicks.com

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Zune Marketplace: Playlists – a Word of Warning

5 December, 2008 (19:29) | Crap, Playlists, Zune, Zune+Markedplace | By: larsw

I’m still very satisfied with the 120GB black Zune that I bought during my trip to the Microsoft Professional Developers Conference 2008 in the end of October. I found a way to use my own Norwegian credit card with the combination of the regional settings in Windows set to “USA” and a borrowed, real address in … LA :-) I first signed up for the 14 day Zune Pass trial – and I was definitely sold.

Luckily, the tricks worked with the real Zune Pass subscription too – so now I’m in my first month of using the Zune Marketplace for for real. I’ve download a great deal of the music I own from before since I’m lazy and haven’t hooked up the external hard drive with the backup of all my music (I’m a recovering CD junkie, so my shelves are filled with albums) so it is a bit weird not having the physical media for some my newly-acquired music.

Here the other day some ads for “The very best of 199X” hit lists turned up on the front page of the Picks section of the Marketplace. Guess what, the summer of 1996 I was 18 and could legally get into pubs and drink beer, so there is a lot of the music from that year that awakes good memories. A good example is The Fugees, that had at least 3 or 4 big hits during the spring, summer and fall.

Back to the playlist. When I saw this “The very best of 1996” playlist I immediately added it to my Downloads list and went to bed. The morning after it was all sitting on my local disk, so I synchronized the Zune and head off for work.

At the train I picked up the Zune, plugged in my Bose QC2 headphones and navigated to the 1996 playlist.

Guess what?

My Zune was infested with crap. Crap. More crap. Unmentionable crap. Boring crap. Boyband crap. Dull drama crap. Crap.

Some example crap artist & songs:

  • Celine Dijon – err. Dion
  • Los del Rio – Macarena
  • Maxi Priest
  • Coolio
  • Barbra Streisand
  • Toni Braxton
  • Hanson

And the list just goes on and on and on and on.

And I forgot to mention that I also downloaded the list for 1997 & 98. sic.

So, what is the morale of this story?

DON’T – I REPEAT DON’T – DOWNLOAD PLAYLISTS FROM OTHER PEOPLE / BEST OF / HIT LISTS WITHOUT CHECKING THE CONTENT OF IT FIRST.

It really garbles the navigation system of the Zune so I have a major cleanup in front of me.

I kept the worst part to the last: Guess what? Since the fine piece of hardware (and the SW player too) keeps tracks of all the tunes you’ve played – the crap may show up on your Zune Tag and possibly affect the content that turns up in the Picks section.

Urgh. Sorry for bothering you with this rant – but the warning is well-meant. Have a nice weekend :-)

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

What’s new in WCF 4.0

25 November, 2008 (20:54) | .NET, NNUG, Talks, WCF | By: larsw

Tonight I held a talk for the Norwegian .NET User Group Oslo on “What’s new in WCF 4.0”. The feedback was good and I think it went fairly well, especially considered the time I’ve had to prepare.

There should probably have been more time allocated for demonstrations but to cover all the areas of improvements in WCF (and related technologies) I really need (at least) 45 minutes. If I’m asked to do this talk for other NNUG chapters (or internal for other companies/clients) I think it would be wise to either cut down on the content – and only mention the left out parts briefly – or extend it to a two hour talk.

If you attended the talk, I would love feedback (both positive & negative), comments, questions, speaking & consultancy offers. Contact me at lw at miles dot no

You can download the slides here.

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone

Where are the System.ServiceModel .Discovery bits?

21 November, 2008 (10:51) | .NET, NNUG, System.ServiceModel.Discovery, WCF, WS-Discovery | By: larsw

I’m currently preparing my talk for next Tuesday – “What’s new in WCF 4.0” and one of the features I want to talk about is the new WS-Discovery implementation. My only problem so far (until today) was that I couldn’t find the bits on the Virtual PC Image! I have been searching high and low with .NET Reflector – to no luck.

So I wrote a post in the WCF forum and asked if anyone knew where I could find it. No good answers, so I sent the question to a couple of the PM’s in Connected Systems Division that I know work with WCF. No answer. Finally I turned to the Email form on Nicholas Allen’s blog – and he was kind enough to mail me back.

Turn out that the bits is in the System.WorkflowServiceModel – one of the assemblies I didn’t bother to search since I thought they only contained Workflow-specific bits…

The invitation to the talk on Tuesday can be found here (In Norwegian). I’m hoping for at least 70-80 attendees.

Share and Enjoy:
  • del.icio.us
  • DotNetKicks
  • Digg
  • Google Bookmarks
  • DZone