Roxen Application Launcher 0.3

I just created an updated version of Roxen Launcher. I got an error report from one who tried to build the application:

./ApplCon.cs(232,24): error CS0122:
‘System.Net.Sockets.TcpListener.Server’ is inaccessible due
to its protection level

An explanation of the error can be found at MSDN. The reason seems to be due to TcpListener.Server being a protected property but I tried to access it as public. The strange thing is that I didn’t get an error about it nor on my machine at home or at work. Now I created a derived class of TcpListener.Server so that I can access the protected property.

We’ll see if it works!

Roxen Application Launcher 17:31, Sat 17 October 2009 :: 97.3 kB

Roxen Application Launcher for Linux

I thought I should broaden my C# knowledge a bit and you know how it is: To learn new stuff you need a real project to work on or else you will lose the fire sooner than later. So I came up with a good project that is actually useful to me: Porting Roxen’s “Application Launcher” to C#. There’s nothing wrong with the original one, written in Pike, except that it uses GTK 1 which is quite hideous (in an aesthetic meaning) compared to the newer GTK 2. And I also though it would be cool to create a panel applet (in the notification area of Gnome so you could put the Application Launcher in the background).

BTW: For those of you not knowing what the heck Roxen’s Application Launcher (AL here after) is here’s a brief explanation: Files in Roxen CMS is stored in a CVS file system which means that you don’t deal with files the way you normally do. To manage files you use a web browser interface (which is a darn good one I might add) but sometimes you actually want to edit files in your standard desktop application. And it is here the AL comes to play. You can download a file through the browser interface so that the file is opened in the AL. AL will then open the file in the desktop application you have associated with the file’s content-type. When you make your changes and saves them the AL will directly upload the changes to the server. So in short I could have said: The Application Launcher is a means to edit files on a remote Roxen server with a preferred desktop application.

The obstacles

I must say I’ve learned a lot from this project!

First off: If you download a file for editing and the AL is already started you don’t want to start a new instance of AL (this is something I have never ever thought about before – in general terms, not just concerning AL) but when you do think about it you find that it’s not a piece of cake to solve. I solved it the way it is solved in the original AL. The first instance of AL that is started also starts a “socket server” that listens for incoming traffic on a given port on the local IP. When a new instance is started it first checks if it can connect to said port and if it can it sends the arguments through the socket to the first instance which then handles the request. The second instance is simply terminated when it has send the data though the socket.

So there I had to do some socket programming. Great fun :)

Secondly: Stuff happens in the background of AL – data send through the socket remember – which means that nothing happens when you try to update the Graphical User Interface. (NOTE! This is the first more advanced desktop application I’ve done.) After “Google-ing” around a bit I came to know that this was a real newbie problem ;) The thing is that the GUI can only be updated through the same thread that started it so when using background threads – implicitly that’s what I’m doing although handled by the asynchronous callback infrastructure of C# – you need to make sure the GUI is updated through the main thread. This is the most simple way so solve it:

3 lines of C#
  1. Gtk.Application.Invoke(delegate{
  2. CallFunctionToUpdateGUI();
  3. });

That’s not too difficult when you know it ;)

Thirdly: The AL is sending data back and forth through the HTTP protocol which means we have to use some sort of HTTP client. C# has a couple of ways to do this but unfortunately they came up short, or I couldn’t use them anyway. I didn’t manage to figure out exactly why I always caught an exception saying something like: A protocol violation occurred!. I’m far from the only one who have fought with this and it has something to do with the headers sent from the remote server. You can invoke “unsafe header parsing” but that was to much of a hassle so I created my own little HTTP client.

One big annoying thing with C# is that is seems almost impossible to turn data from streams into strings without having to use any one of the System.Text.Encoding.* classes/objects which in my case meant that images and files in binary form got seriously fucked up. I manged to solve this my never turning the data into a string but keeping it as a System.Text.Encoding.* all the way from request to response to saving to disk. It was rather irritating but at the same time nice when solved (and I learned a whole bunch about System.Text.Encoding.*, System.Text.Encoding.*, System.Text.Encoding.* and System.Text.Encoding.*.)

Finally: Of course I learned a great deal more about C# but this blog post is starting to get pretty excessive so I will round it off by saying that MonoDevelop is starting to become pretty darn good! I just upgraded to the latest version of Ubuntu and that also meant that I got the latest MonoDevelop and I must say it’s more stable than ever (although it occasionally crashes) and a whole bunch of new features are in place. One I havn’t used before – although it might have existed before – is the “Deployment” stuff. It creates a package with configure and make files for optimal compilation. Really smooth!

Source and screens

I will finish off by adding the source files and a few screen shots:

Roxen Application Launcher 17:31, Sat 17 October 2009 :: 96.7 kB

Screen shot 1: Just a standard view
Roxen Application Launcher 1

Screen shot 2: The panel applet in action
Roxen Application Launcher 2

Screen shot 3: The Application Launcher in Swedish
Roxen Application Launcher 3

Screen shot 4: Adding support for a new content type
Roxen Application Launcher 4

A Pike syntax highlighting module

So I thought I should try to port my syntax highlighting script, Syntaxer, written in PHP to Pike. Mostly for the fun of it but also to improve my knowledge of string handling in Pike. The greatest concern here is that PHP is a dynamic language and Pike is not (in the same sense) and the PHP version of Syntaxer heavily depends on dynamic loading of PHP files. The reason for this is that I generate the “syntax maps” dynamically from syntax files of Edit+. That means that if you want support for a new language just drop a .stx file in the right location and there you go. My script will convert that into a static PHP file, so that the conversion only needs to be done once, and load that file on the fly when that particular language is requested.

I thought that this method would be hard to implement in Pike – although it might be possible – so I had to come up with a slightly different approach. Frankly; it’s not that often you alter the .stx files or implement support for new languages so my solution is to manually create definitions for what ever language. But I still use the .stx files from Edit+ although one needs to copy and paste bit.

In the Pike solution each language is its own class that inherits the master class .stx. The only thing you pretty much need to put in the derived class is some .stx, .stx and .stx that specify what is what in the language. For example, the C++ definition looks like this:

31 lines of Pike
  1. inherit .Hilite;
  2. public string title = “C++”;
  3. //| Override the keywords mapping
  4. private mapping(string:multiset(string)) keywords = ([
  5. “keywords” : (<
  6. “auto”,“bool”,“break”,“case”,“catch”,“char”,“cerr”,“cin”,
  7. “class”,“const”,“continue”,“cout”,“default”,“delete”,“do”,
  8. “double”,“else”,“enum”,“explicit”,“extern”,“float”,“for”,
  9. “friend”,“goto”,“if”,“inline”,“int”,“long”,“namespace”,“new”,
  10. “operator”,“private”,“protected”,“public”,“register”,“return”,
  11. “short”,“signed”,“sizeof”,“static”,“struct”,“switch”,“template”,
  12. “this”,“throw”,“try”,“typedef”,“union”,“unsigned”,“virtual”,
  13. “void”,“volatile”,“while”,“__asm”,“__fastcall”,“__based”,
  14. “__cdecl”,“__pascal”,“__inline”,“__multiple_inheritance”,
  15. “__single_inheritance” >),
  16. “compiler” : (<
  17. “define”,“error”,“include”,“elif”,“if”,“line”,“else”,“ifdef”,“pragma” >)
  18. ]);
  19. //| Override the default since # is no line comment in C++
  20. protected array(string) linecomments = ({ “//” });
  21. void create()
  22. {
  23. ::create();
  24. colors += ([ “compiler” : “#060” ]);
  25. styles += ([ “compiler” : ({ “<b>”, “</b>” }) ]);
  26. }

And you really don’t need to make it more fancy than that. For most C-based languages the definitions in the master class .stx is enough. Just add the keywords to the .stx mapping and it looks better than nothing ;)

HTML parser

One thing that differs from the PHP version of Syntaxer is that SGML-based, or tag based, languages will be run through a HTML-parser. The downside of the PHP version is that tag content will be highlighted as well, which of course isn’t what we want, but since Pike has a decent HTML parser that behaves like a SAX parser so I wrote a class, .stx, that uses that for highlighting tag based stuff. The .stx class also inherits .stx so the methods and members are the same.

I wonder why there’s no, built-in, HTML parser for PHP?

A Roxen tag module

Of course I had to write a Roxen tag module so that we can highlight source code in Roxen web pages. This was the reason for writing the Pike module at all. The tag is named .stx which might not be the most innovative name but what the heck! The beauty of it is that I made it possible, in the module settings tab, to create a surrounding HTML template for the output. When you run some code through the parser you get the highlighted source code as well as the name of the language and how many lines of code was highlighted and it might be nice to present that as well (just like the code blocks on this site). It’s tedious writing that surrounding HTML every time so now it’s just to put that in the settings and the code blocks will always look the same.

Finally

There’s some stuff left to do but the code works well enough to be usable. And I must say that the speed of the Pike version is like a thousand times faster than the PHP version!

Oh, and I have implemented support for the following language:

  • ActionScript
  • C
  • C++
  • C#
  • CSS
  • Java
  • JavaScript
  • HTML
  • Perl
  • PHP
  • Pike
  • Python
  • Ruby
  • RXML
  • XSL

And that’s that for now.

Codify RXML tag and Syntaxer.pmod 17:31, Sat 17 October 2009 :: 183.9 kB

A Pike module and a Roxen tag

When you’r used to one programming language and start learning a new one you sometimes miss some features from the former. That happened to me a couple of years ago when we started using Roxen at work. What I missed was the trim functions from PHP. Sure, Pike and RXML can trim strings from whitespace but the beauty of trim, trim and trim in PHP is that you can trim characters as well as whitespace. And to my knowledge there’s no equivalent to trim and trim – that is only trim the left and right side respectively of the string.

So I wrote a Pike module that did that and also created an RXML tag of it. Just yesterday I rewrote that code since I do think I’ve become a better programmer and have come to learn Pike a lot better since my first try.

And I also wrote a method to shorten a string from the center and out, i.e. trim.

So here are some examples of usage:

12 lines of Pike
  1. import .trim;
  2. string path = “/this/is/a/path/”;
  3. write(“%s\\n”, rtrim(path, “/”));
  4. // Will output: /this/is/a/path
  5. write(“%s\\n”, trim(path, “/”));
  6. // Will output: this/is/a/path
  7. string long_str = “This is some string that’s too long for us”;
  8. write(“%s\\n”, ctrim(long_str, 20));
  9. // Will output: This is…for us

And here’s the RXML implementation:

5 lines of RoXen Macro Language
  1. <trim right=“” char=“/”>/this/is/a/path/</trim>
  2. <!– /this/is/a/path –>
  3. <trim center=“” length=“20”>This is some string thats too long for us</trim>
  4. <!– This is…for us –>

And that’s that.

Trim Pike module 17:31, Sat 17 October 2009 :: 4 kB
Trim Roxen tag module 17:31, Sat 17 October 2009 :: 4.8 kB

Beautiful Roxen

I’ve been really busy lately at work with various things – developing a blogging system for starters. Most of the stuff you need for a blogging system is already available in Roxen CMS that we use at work. But one thing I needed, that isn’t available, was some commenting functionality. This is something that you could quite easily implement in the templates – Roxen uses XSLT for the templating system, or their own extension of XSLT so that you can write RXML code in the XSL templates.

RXML handles database driven things quite alright but if you develop things in this layer, the presentation layer, it gets harder to maintain or implement on a different server. What you can do then is writing a Roxen Module in Pike. You can create different types of modules – provider modules, RXML tag modules and so on – and you can also combine two or more modules into one. All RXML tags in Roxen is just wrappers for underlying Pike code, so you hide the logic in Pike and provide simple interfaces in RXML. First, let me give an example of how you loop over a database record set in RXML:

5 lines of RoXen Macro Language
  1. <emit source=“sql” host=“myhost” query=“SELECT name, email FROM employees”>
  2. <a href=“mailto:&_.email;”>&_.name;</a>
  3. </emit><else>
  4. No records found
  5. </else>

It doesn’t get more simple than that! Another thing that’s great about the modules is that you can run arbitrary functions when you load the module which means that you can create databases and database tables when you first load the module. Roxen runs on MySQL internally and Roxen provide API:s to the internal MySQL database. What this means is that if you create database driven modules it’s just to install the module and the database and its tables will be created. No fuss!

Roxen, without the CMS, is a standalone open source web server and support the same kind of modules as the CMS does, but there’s more to the CMS!

The CMS modules

I’ve been poking around in the Roxen CMS source code for a while now and I have written some pure RXML tag modules – which is quite simple – but now I saw the opportunity to extend my knowledge and make a real CMS module. Since the CMS provide access control you don’t want emit tags to list stuff that the user don’t have access to. For instance: There’s a emit tag that you can use to list the most recent pages for a given path or pats. For example:

11 lines of RoXen Macro Language
  1. <h2>Latest news</h2>
  2. <ul class=‘newslist’>
  3. <emit source=“site-news” unique-paths=“” maxrows=“20”
  4. path=“/comp-a/news/*/*.xml,/comp-b/news/*/*.xml,/secret/*/*.xml”
  5. >
  6. <li><a href=‘&_.path;’>
  7. <date type=‘iso’ date= iso-time=‘&_.published;’ /> |
  8. <span>&_.title;</span>
  9. </a></li>
  10. </emit>
  11. </ul>

Now, you don’t want unauthorized users to see the items from the emit path do you. This tag in particular won’t show them either and I wanted the same kind of functionality in my set of emit tags. So I poked some more!

Another thing: Each file in Roxen CMS is version controlled through CVS and I needed to get some information about the first published version so I needed to find out how to access the CVS logs. The CVS thing also means that the files in Roxen CMS is saved to a virtual file system with an actual path, i.e emit, and what if there are comments to a page and that page gets moved? Thankfully Roxen CMS provides an API to run your own code when some kind of action takes place on a particular file – if it get moved, edited, deleted, purged and so forth. And I came to understand that I needed to poke around even more ;)

Anyway; the more you dig around at the dark side of Roxen the more impressed you get by how clean the code is, how nice the API:s are and so on. I’m no Roxen beginner by now but up until now I haven’t really used the API:s to the internal workings of Roxen and I must say that after all, it was a bliss.

The comments module

So what will all this babbling lead up to? Well, what my module now does is:

  • Upon load it creates an internal database with the table in which to store the comments. Here you can also make a dump or load a dump of the comments DB. In the settings you can set the default value for how long commenting should be enabled – lets say that after 30 days no further commenting should be allowed. You can also set a default author name if you allow anonymous commenting.
  • It listens to the emit which means that when actions takes place on web pages in the CMS the module will be notified and take actions if necessary. If the page emit has comments to it and the page get moved the paths in the comments table will be updated to the new path so that comments always stick to its page even if the page is moved. Also, if a page gets deleted so will the comments.
  • It provides a set of RXML tags, one for listing comments – either to the page to which they belong or through globs so that you can make lists of “latest comments”, one for listing a particular comment for lets say editing, one tag for adding, one for updating, one for deleting a comment, one emit tag for checking if a user have admin permission to a given comment and one emit tag to check if the commenting form has expired or not and last one tag for counting the comments for a given page.
  • Not the least: I followed through and really documented, through Roxens module documentation functionality, the usage of the RXML tags ;)

So I think that it covers what you’d expect a “commenting system” should be capable of doing. There’s may be some small things to solve as always when you develop stuff but it seems to work quite satisfying.

For anyone curious, here’s the source code:

Comments – Roxen CMS Module 17:31, Sat 17 October 2009 :: 36.3 kB

Here’s some screen dumps

The module status tab:
Status tab

The module settings tab:
Settings tab

The module documentation tab:
Documentation tab

A simple implementation:
Status tab

Generating PDFs on the fly

One time or another you come to the point, at least when you work as a web developer, when you need to generate PDFs on the fly. In principle this wouldn’t be too hard: pass the document you want to convert through a PDF printer. Well, it doesn’t sound that hard but talk is one thing and implementation another! I came to the point recently where I, or we, really needed to generate PDFs on the fly. The question of just converting one document to a PDF was not the only problem ahead: We also needed to alter the content, which is some tremendously complex content, of the PDF on the fly.

The workflow is as follows: A person submits a web based application through a web form. The commision is received by a handling officer who continues the application. The commision is sent back to the applier who in turn continues the application. The commision is once again sent to the handling officer who finish the application.

The application form, originally a Word document with loads of checkboxes, input fields and what not it’s the document at the top), at hand here is really, really complex and more or less industry standard. The pure complexity of the form is the reason why we wanted to digitalize it and make it into a more workflow like thing. Since the application form is more or less a standard we wanted the ability to see what the web based application would look like in reality if it was handled the old way through the Word document and of course give us the ability to archive the application in a constant format. And this is the type of document that people like to put in a binder so it needs to be printable and look like it always has looked like.

The first problem

So how do you go about and fill the Word document with values from a database, or how do you dynamically create a PDF that looks exactly like that complex Word document? Creating simple PDFs from a PDF API is not that hard but this really isn’t a simple structured document we’re talkning about so that didn’t sound likely. So I started looking at Adobes LiveCycle products but that would be really expensive (I mean really, really, really expensive) so we had to throw that idea away.

Then it hit me: We’re running Windows servers at work so couldn’t I build a COM based solution and use the COM interface for Word and in that way use the original Word document as a template and dynmialcally fill it with content from the database? I had never touched COM before but I thoght nothing is impossible!

The first solution

So I fired up Visual C# Express and began writing a console application that could be called from the web server. The first thing to solve was how to get all the data from the web server to the console application. Of course the console application could call the database directly but that would make the application hard to maintain, it would make it less dynamic and in general no good (and there are more documents to create and alter than the one I’ve mentioned). XML is no news to me so I though that passing an XML tree as an argument with what fields to fill and with what values would be a good idea. And since during the commision there are several types of documents to generate another argument would be what Word template to use.

So the question of how to get what information to fill the Word document with to the console application was easily solved (I love XPath).

The next question was how to use the Word COM interface, and frankly that was quite easy (thanks to Google). If you use bookmarks in the Word document you can loop over them with ease and just as easily fill them with content. So the principle I used was the following: The XML tree passed to the console application looks like this:

9 lines of XML
  1. <!– The name of the root node doesn’t matter –>
  2. <n>
  3. <field name=“Some_Bookmark1” type=“text”>The value</field>
  4. <field name=“Some_Bookmark2” type=“text”>Another value</field>
  5. <field name=“Some_Bookmark3” type=“checkbox”>true</field>
  6. <!–
  7. … and just as many nodes neccessary …
  8. –>
  9. </n>

so the name attribute is correponding to the name of the bookmark/data field to alter and the node value is quite obvious the value to assign to the bookmark/data field. Text fields and checkboxes is delt with in different ways in the COM API so that’s why the name attribute.

When the bookmarks/data fields has been altered the document is saved in a temporary directory with a uniq name and the path to that document is returned by the console application.

Up to this point…

This is how things work so far:

  1. The console application is called with two aruments:
    1. What template to use
    2. An XML tree with what bookmarks/data fields to fill with what values
  2. The console application opens the template and fill it with data according to the XML tree passed as the second argument.
  3. The console application saves the document with a uniq name in a temporary directory and the path to that document is returned by the console application.

Quite clear I’d say ;)

The second problem

Okey, so now this application needed to be callable from a web page. And frankly that seemed like a minor problem, and so it was. The only minor concern was that the overall web based application workflow was (is) developed by Roxen as a consultant job so the implementaion of this little Word to PDF thing needed to be as simple as possible. So it was time to fire up JEdit and do some Pike hacking.

The second solution

Thanks to the fact that there’s a module in Roxen that can execute external applications and thanks to the fact that the source code of Roxen is available I borrowed some of the code written by Marcus Wellhardt at Roxen ;) . I’m no wicked Pike expert like the dudes at Roxen so I borrowed the code from name that creates a background process and altered it slightly to fit my needs. On top of that I wrote a RXML tag that would be the wrapper to call to create the background process. The tag, a container tag, takes one required argument, the Word template to use, and one optional argument, the path to the directory where the template is stored (this argument is optional because it can be set globally in the module settings), and the XML tree with the bookmarks to fill as content. So the tag would be used like this (still, not all functionallity is there yet):

7 lines of RoXen Macro Language
  1. <word2pdf template=‘the-template.doc’>
  2. <d>
  3. <field name=“Some_Bookmark1” type=“text”>The value</field>
  4. <field name=“Some_Bookmark2” type=“text”>Another value</field>
  5. <field name=“Some_Bookmark3” type=“checkbox”>true</field>
  6. </d>
  7. </word2pdf>

So I tried the tag and indeed a Word document with my given data was created in the temp directory on the server!

The third problem

Now it was time to create a PDF from the temporary Word document. I found an open source PDF printer software called PDFCreator and it looked promising so I went for it. PDFCreator can be installed in “server mode” which was what I wanted and thanks to this guide it was easy to set it up as a service as well.

First I wrote a standalone Pike script for debugging and testing that would kind of emulate a web page request (it’s some what tiresome developing new thing directly through Roxen since the module needs to be reloaded/re-compiled for every change you make to the code). Anyhow, things started to work pretty well: The script created a Word document by calling my console application, the script passed the path to that document to PDFCreator and MS Word was launched and a PDF was printed to the given temp directory. Yes! PDFCreator relies on the software the orginal document is associated with.

Okey, so the code worked fine so I altered my Roxen tag module so that my tag name would behave in the same manner as the standalone Pike script. But when I ran the tag through a web page request PDFCreator hung, or rather the MS Word process created by PDFCreator hung!

The third solution

It really puzzeled me: Everything went ok if I ran the process as my user through my standalone Pike script, but when the process was created by the web server (local system) MS Word got stuck. So I changed the server process to run as an ordinary user account, my user (local administrator) and now it worked perfectly. Then it hit me: maybe the MS Office applications relies on the directory name in name and the user name doesn’t have that (it’s no ordinary user). So it seems that to get MS office apps to run from another process, that process needs to have been created by a normal user account. I dunno, maybe there’s a way around this, like installing MS Office in some kind of server mode or something like that!

Anyhow, my little RXML tag name now did what I wanted and the result of the tag is the raw data of the created PDF, the temporary Word document and the PDF is wiped clean from the server, so we can just store the raw data in a database and deliver it easily to a user when the PDF is requested.

Word2pdf wrapped up

I’m quite satisfied with the solution I came up with: The console application I wrote (I call it WordWriter) seems to work like a charm and the fact that what data to fill the template with is passed as an XML tree makes it really easy to use for more than the specific purpose it was developed for. Plus, if the over all web application Roxen developed (is developing) is changed I don’t need to change the WordWriter application :)

Finally this is how this little name can be used in real life:

25 lines of RoXen Macro Language
  1. <?comment
  2. Here data is pulled from the database according to the
  3. application being handled
  4. ….
  5. ?>
  6. <define variable=“var.pdfdata” trimwhites=“”>
  7. <word2pdf temlplate=“my-template.doc”>
  8. <n>
  9. <field name=“My_Bookmark1” type=“text”>&sql.data1;</field>
  10. <field name=“My_Bookmark2” type=“text”>&sql.data2;</field>
  11. <field name=“My_Bookmark3” type=“text”>&sql.data3;</field>
  12. <!– … –>
  13. <field name=“My_Bookmark10” type=“checkbox”>
  14. <if variable=“&sql.data10; = 1”>true</if>
  15. <else>false</else>
  16. </field>
  17. </n>
  18. </word2pdf>
  19. </define>
  20. <sqlquery host=“dbhost”
  21. query=“UPDATE table SET pdf1 = :pdf WHERE id = :id”
  22. bindings=“pdf=var.pdfdata, id=sql.id”
  23. />

And that should do the trick!

The synergy

At my job we’re like 1200 people and sometimes people want to create PDFs either to put on our web site or e-mail to someone and of course not all computers have Adobe Acrobat installed so wouldn’t it be nice to have a form on the intranet where people could upload a file and get it back as a PDF? Since most of the PDF generating functionality was already at hand I just had to write another RXML tag that just creates a PDF from a document. Said and done so now we have PDF generating form on the intranet.

Finally

This has been a really fun thing to do from which I have learned alot of new stuff, and that is probably why I love my work so much: There’s always new things to dive into.