Monday, December 11, 2006

Linux, ASP.Net and Apache

The mono project, which aims to provide an OSS alternative to the .Net framework, is capable of serving ASP.Net pages (amongst other things). On Friday I sat down to do this, and realized that while there are many pages that describe the process, none that I could find, covered all the info needed to actually get up and running. (I've built a Google Notebook of the better links I visited -- look [here](http://www.google.com/notebook/public/07937799986237074011/BDRQYIwoQi-HOhPQh) for those.)

## The Webserver ##

ASP.Net pages are served up by a web server called XSP (or XSP2). XSP is a stand alone web server, however it doesn't have much of the functionality of Apache. XSP is great for testing, and would work well on a dev machine, but it's not something you'd use directly for a live sever. Generally, you'll want to run Apache with mod_mono, which is essentially a wrapper around XSP[2].

XSP vs. XSP2 -- XSP2 is capable of serving up ASP.Net 2.0 pages, while XSP is only 1.1 capable.

## Packages ##

I work under Ubuntu, but the packages needed should be fairly easy to translate to other distros:
(I already had mono installed -- that step was trivial `apt-get install mono` or something similar. If you don't have mono running, do that first.)

* apache2
* apache2-common
* apache2-mpm-worker
* apache2-utils
* asp.net2-examples
* mono-xsp2
* mono-xsp2-base
* mono-apache-server2
* libapache2-mod-mono

Installing mod_mono will tell you to force-reload apache:


$ sudo /etc/init.d/apache2 force-reload
* Forcing reload of apache 2.0 web server...
apache2: could not open document config file /etc/mono-server/mono-server-hosts.conf [fail]


In Ubuntu, at least, the default `mod_mono.conf` is not setup for XSP2. If you see the failure above, then just pop open `/etc/apache2/mods-enabled/mod_mono.conf` and swap the commented lines to point to the correct mono-server directory. `/etc/mono-server2/mono-server2-hosts.conf`.

## Configuration ##

(The Ubuntu documentation has the best description of this process I've found. Look [here](https://help.ubuntu.com/community/ModMono) for their steps. I've included this section anyway because I still had difficulty connecting the problems I had with the solution posted on the Ubuntu page.)

I'll assume you've been able to install and load the `mod_mono` module. From this point, we need to set the ASP handler, and define mono web applications. The first step is straightforward, at least if you're familiar with Apache configuration:

# Enable ASP in /usr/share/asp.net2-demos
Alias /samples "/usr/share/asp.net2-demos"

SetHandler mono


The second step is new to me -- apparently mono needs an application root of some sort defined in addition to the handler configured above. Most pages suggest using the line:

MonoApplications "/samples:/usr/share/asp.net2-demos/"

However, that caused 'mod_mono' to segfault continuously (the apache logs were horrible:

Another mod-mono-server with the same arguments is already running
Another mod-mono-server with the same arguments is already running
[notice] child pid 7371 exit signal Segmentation fault (11)
[notice] child pid 7372 exit signal Segmentation fault (11)
[notice] child pid 7373 exit signal Segmentation fault (11)
[notice] child pid 7374 exit signal Segmentation fault (11)
....
# (about 1 / second)

It turns out that there is another way to accomplish the same thing. `/etc/mono-server2/` can contain `.webapp` files which define essentially the same thing. The format for these files can be found in 'man xsp2':



{appname}
{virtual host for application}
{port for application}
{virtual directory in apache}
{physical path to aspx files}
is true by default -->
{true|false}



For the asp.net2 samples, I used this webapp config:



samples
localhost
80
/samples
/usr/share/asp.net2-demos



After that, starting up apache worked without error and pointing a browser at http://localhost/samples popped up the Mono-project ASP.Net sample page.

Saturday, December 09, 2006

Blog migrations

I've moved [Bitwise Evolution](http://blog.ciscavate.org) to yet another blog -- this time I've moved from WordPress to MovableType. The motivating factor was that WordPress made it extremely difficult to post correctly formatted code along with other content. WordPress also doesn't store a non-html version of each post, so you can't easily edit old content without hacking auto-generated html.

Movable Type proved to be slightly more difficult to install, but it is much more configurable, and has a huge set of varied and useful plugins that actually do what they describe (*gasp*). Some of the things I've enabled include:

* [Markdown](http://daringfireball.net/projects/markdown/) for wiki-like markup
* [SmartyPants](http://daringfireball.net/projects/smartypants/) for smart quotes.
* [GeSHi](http://qbnz.com/highlighter/) for syntax highlighting. (This required a couple additional plugins)
* [Transcode](http://periodic-kingdom.org/ben/) To hook MovableType up to GeSHi
* [MTMacro](http://bradchoate.com/weblog/2002/08/12/mtmacros) Needed to make the transcode syntax bearable.
* [MTRegex](http://bradchoate.com/weblog/2002/07/27/mtregex) To add conditional behavior to the macros.
* [Acronym](http://gemal.dk/mt/acronym.html) Used to enable mouse-over acronym expansion (so you can easily find out what DTD, XHTML, PCMCIA and etc. stand for, and it's all automatic.)
* [LivePreview](http://plugins.movalog.com/livepreview/) because none of the stuff above (except for Markdown and Smartypants) render correctly in the default preview view.

Here's the macro used to turn '<pre lang="java"> .... </pre>' into the proper format for transcode:

<pre><code>transcode-language: java
...
</code></pre>

Macro:


transcode-language: 








Sooner or later I'll probably take another look at blogging from emacs.

Wednesday, November 08, 2006

Polymorphic Generics in C#

Generics are great for adding some level of type safety to C#, but you may run into problems when using Generic classes with objects that aren't of the exact Class or Interface indicated by the generic type template. Enter Generic Constraints.

Generic Constraints let you restrict the number of types a type variable can apply to. For example, Assume you have three classes:

  
class Aclass{/*...*/}
class Bclass : Aclass{/*..*/}
class Cclass : Aclass{/*..*/}


If you have a method that takes a list of Aclass, you may want to be able to call it with a list of Bclass or Cclass as well. The naive approach doesn't work however:

 
public void foo(List<Aclass> myList){ /* ... */ }


When you call foo with a List or List, the compiler will complain that the types don't match. (unless you provide overrides of foo). Instead, make foo a generic method, and specify a constraint on the type:

 
public void foo<T>(List<T> myList)
where T : Aclass
{
/* now you can treat
myList as a List<Aclass>*/
}


This link goes over generics in c# in detail:

MSDN on Generics

Tuesday, October 31, 2006

Vanity, chapter 1

...empty pride inspired by an overweening conceit of one's personal attainments or decorations; [1913 Webster]

I'm a sucker for pretty desktops and window managers. This weakness has yet to make me succumb to the lure of a full Gnome (or KDE) desktop, however. (Although I did play with the hack kludge known as XGL/compiz for a month or so.) I alternate between Enlightenment and FVWM, however, I do use a fair number of GTK apps. Eventually, I hope to create some gtk apps, (or wxWidgets, or etc... it all boils down to gtk showing up on screen though). Up 'till now I've suffered through with the dreadfull defaults -- in my opinion, of course -- but that just changed with gtk-theme-switch2.

gtk-theme-switch2

It is awesome :) theme loading, previewing, setting, etc.. all without a hint of the gnome infrastructure to screw your keyboard layout, fonts, or power management.

Monday, October 30, 2006

In agreement at last..

Finally, windows did something I agree with:

If only it had caught itself during the OS install instead of just a measly user-space app...

Maybe this has been fixed in Vista... (...could that be the reason it's still not out? I suppose I shouldn't get my hopes up.)

Saturday, October 07, 2006

At the Top of the Stack...

As is the case with many geek-endeavors, the things I'm currently working on have nothing to do with the goal I set out to achieve. At the moment I'm trying to find a way to convert xhtml into muse markup.

Why? Because your average Java programmer Just Doesn't Get It when it comes to building a UI with Swing. Obviously.

Frustration with Swing UIs led to the idea that I should throw together a tutorial on building a GUI with swing while paying attention to separation of concerns re: layout, manipulation, threading and data. Blogging seemed like a prime medium to present such a tutorial, since each post could be tagged with a meaningful tag (eg: swing_tutorial) and I could post in sections.

This, of course, necessitates a blog (which I have, obviously) but which does emphatically not have any input mechanisms worth using for an extended period of time. The wordpress on-line editors are, in a word, pathetic. They may work great if you just want to stream your consciousness out to the world where it can pollute everyone's Google results with poor spelling and meaningless chatter, but the editors available simply can't handle source code.

It is possible to feed the blog pure html, which is (unfortunately) a step up from the rich editor, but which also isn't going to cut it, because it could be so much better.

Seriously, look at Mediawiki, or twiki, or any of the millions of wiki engines out there. They ALL support better input mechanisms than wordpress. So why am I using wordpress at all? Because for everything else -- user support, rss feeds, tags, data-base backed storage, plugins etc... it works great (as far as I know, come back in a week when I've resolved the editor issue to hear what else sucks. That should be enough time for me to find it.).

Solutions


I hope to get around this pain-in-the-ass that is the wordpress editor by using emacs to post content via worpress's xml-rpc support. Therefore I need to find / enable or create support in emacs for the following things:
  • wiki-like markup, with support for code tags that can be interpreted by the geshi plugin on wordpress.

  • a translator that converts wiki-like markup to xhtml, and back

  • xml-rpc support, and the ability to retrieve and submit blog posts.

  • Multiple Major Mode support for the wiki-like text mode, so that the aforementioned code tags use the correct font-lock mode

  • A preview capability, so the blog posts can be converted, fed to a w3-el buffer and viewed, then edited again prior to posting and publishing.

  • Most of these are possible in some fashion or another, but currently I'm stuck on the "translator for xhtml to wiki-like markup". Stay tuned for improvements, and news as I pop things off the stack.

    Someday maybe I'll get around to talking about java.

    Friday, October 06, 2006

    Blogging with emacs + mt.el

    I've wanted to use emacs as a blogging tool for a long time, but I've
    always run into issues. Today I ran across a blog post that describes
    an approach that works:



    http://ektich.wordpress.com/2006/01/30/how-to-blog-from-emacs/



    In addition to the instructions there, I had to pull down:



  • elib (with apt)

  • xml.el (from: http://www.astro.princeton.edu/~rhl/skyserver/xml.el)


  • Ping me with questions -- more details soon to come as I play with
    mt.el, and possibly weblogger.el (which looks nicer, on first
    impressions.)

    Wednesday, September 13, 2006

    (not?) Ranting about .NET collections...

    The .NET collections continually frustrate me with the obvious ommisions, even in .NET 2.0. Coming from a Java / Lisp background, I really expect two things out of a data structures API:

    • Lots of collections to choose from.

    • and; Easy manipulation of the structures you have available.


    .NET doesn't fill either of these requirements very well. At least we have generics now (which, admittedly, is a step above what's available in Lisp -- with regard to types, anyway).

    Today I ran into (yet another) annoyance with .NET collections -- sorting arrays elegantly. Given an array, you can sort it in accending order (according to the default comparer) with Arrays.Sort(..).


    // build & populate the array.
    double[] values = source.ToArray();

    // destructively!! sorts values, returns void, of course.
    Array.Sort(values);


    That's nice. Now, sort it in reverse:


    // build & populate the array.
    double[] values = source.ToArray();

    Array.Sort(values);
    // reverse the array.. adds O(n) ops.
    Array.Reverse(values);


    or...


    // build & populate the array.
    double[] values = source.ToArray();

    Array.Sort(values, Double.ReverseComparer);


    Oh, wait. There is no ReverseComparer on Double.. actually, there's no Comparer on Double either, but there is for most objects... so in general I could just wrap the comparer in a delegate or an anon class (to invert it) and use that.

    Wait again.. c# doesn't have anon classes, and Sort doesn't take a delegate under any incantation. So, we could do this:


    private class ReverseDoubleComparer : IComparer<double>{
    public int Compare(double x, double y){
    return y.CompareTo(x);
    }
    }

    /*
    intervening code...
    */
    // build & populate the array.
    double[] values = source.ToArray();

    Array.Sort(values, new ReverseDoubleComparer());


    That will work, but wow... for every type, I'll need to create a new class, and I can only deal with classes that implement IComparable.CompareTo(..). Thankfully, I can use generics and some constructor overloading to deal with both situations:


    public class BackwardsComparer<T> : IComparer<T>{
    public BackwardsComparer(IComparer<T> c){
    _comparer = c;
    }

    public int Compare(T x, T y){
    return _comparer.Compare(y,x);
    }

    private IComparer<T> _comparer = null;
    }


    Now, we just need to do the following:


    string[] strs = strSource.ToArray();

    // sort strs in reverse alphabetical order:
    Array.Sort(strs,
    new BackwardsComparer<T>(StringComparer.CurrentCulture));


    And there we have it -- reverse array sorting without the additional cost of a Reverse() call, and avoiding the ugliness of case-specific classes floating around. (The complete listing for BackwardsComparer and test suite are here: BackwardsComparer.cs and BackwardsComparerTest.cs

    Tuesday, August 29, 2006

    Playing with Deepest Sender

    I ran across Deepest Sender, a firefox extension used for posting to a blog, today and thought I'd give it a shot. It supports a small, but reasonable set of blog apps (Wordpress, LJ, ... two or three others that escape me at the moment, and I can't find the list right now..) Setup was easy, and it wasn't difficult to connect to my wordpress install , but I don't see how to add multiple blogs, or choose a blog to post to that isn't the default. I'm also a bit mystified at how it manages drafts (you can save to a local file, but that doesn't quite cut it -- I want to take advantage of the draft capabilities of the blog app, so I'm not tied to one machine).

    I wonder if it will let me use code tags in the rich editor..


    -- haskell?
    foo :: Int -> Int
    foo x = x * x



    // Java test
    public static int foo(int x){
    return x * x;
    }


    ...not really... (although, there is a source view, and it's just a click of a tab to switch back and forth, which is how I entered the c# sample below, although it look horrible in the rich editor.) There are some interesting fields under the options menu, including a text area to enter a stylesheet, but no indication of what it does. I may need to dig into the help docs later, but I'll probably look into emacs extensions first. For now, the jury is out. /// /// Sample c# /// public static int Foo(int x){ return x * x; }


    Ah, when posting, I discovered how the draft works. There is a checkbox marked "draft" which publishes content as a draft, rather than to the site. It would be much clearer to just have two buttons: "Publish" and "Save as draft", it would take up the same amount of space, and require fewer clicks, but I suppose you could accidentally publish to the main site when you really wanted to click on draft. In any case, it ruined the formatting on the code snippet, so for my purposes it will not work.

    Monday, August 21, 2006

    Home is where .emacs is...

    I finally found a way to quickly navigate to my home directory in windows today. Being a long-time (well, 8-10 years) Linux user, when I started working in windows 40 hours a week, I had to adapt a bit, but most of that adaptation meant installing cygwin utilities, bblean, and emacs. Unfortunately, it's most natural to put all the configuration files for these apps in my home directory -- a concept that is almost completely alien to a windows system. As you probably know, in Win XP you do have a home dir, conveniently located at c:Documents and Settingsusername which is not extremely easy to navigate to, and there are no simple shortcuts to get there as there are in Linux / unix environments.

    This has been annoying me for some time. Everything goes into that directory -- I've moved firefox downloads, Visual Studio projects, symlinked My Documents to there, etc... Now before you shout out that I brought this upon my self, consider that:

    • I needed everything to be in the same location, for what should be obvious reasons. (but if the reason's arent obvious, try backing up all your crap from a multi-year old windows machine where you didn't keep everything in one place)

    • More things were already using this location than were not (remember, most of what I use is cygwin).

    • Cygwin makes it mildly painful to access things that don't fit nicely into the cygwin virtual filesystem thing.


    Today, however, I found a solution. Oddly enough, the integration between IE and Windows is why this works.

    1. Open the Windows Explorer

    2. Select View-Toolbars-customize

    3. Add the "Home" button to the toolbar

    4. Click on it. (This changes the Explorer "mode" to web-browser, and allows access to configure that button.)

    5. Select Tools-Internet Options

    6. Set your IE home page to c:Documents and Settingsusername

    7. Voila! Click on the home button again, and there you are :)

    Monday, August 14, 2006

    foreach(What?)

    I've been adapting to Java 1.5 and c# (and c#, with .NET 2.0), all of which feature a new construct: the foreach loop. The syntax is relatively similar to the construct in numerous other languages, such as perl's:


    foreach $var (@list){
    # ...
    }


    In c# (or java, the syntax is the same), to loop over an array or IEnumerable collection, you just do:


    foreach(int x in indices){
    // ....
    }


    Unfortunately, as I found today, the c# version shares something else with the Perl version: An absence of type checking. Despite the explicit types in the loop construct, and the presence of generics (although these are missing in .NET foreach in c# is not type safe. The end result is that you can do fun things like this with out the slightest hint of a warning:


    double[] values = new double[]{....};
    /* snip */
    foreach(int v in values){
    // guess what? v == Math.Floor(values[i]) !
    }


    I find this particularly vexing because if you simply re-write the foreach to be a standard for loop, then the type checker will jump in and complain about the loss of precision:


    for(int i=0; i

    With collections this becomes slightly more complex, and in .NET pre-2.0, Enumerators were not typed (they would simply return Objects, making it impossible to perform compile time type checking), with .NET 2.0, however these constructs could be parametrized, eg:


    foreach(T id in IEnumerable){
    // body
    }


    Why this isn't done is a mystery to me. At the very least a rewrite rule could be used to turn each foreach into an equivalent for loop. (There are plenty of ways around any performance problems this would cause at run time, and I'm happy to pay a compile-time penalty if it prevents run-time bugs!)

    Edit: Just for completeness, Java 1.5 does not exhibit this behavior, either when itterating over generic collections or arrays of basic data types:

    double[] values = new double[]{0.5, 0.6, 0.7};

    for (int v : values){ // causes compile time error.
    System.out.println("v="+v);
    }

    Note that it is actually an error in java, not a warning even. I would assume this has something to do with the requirements Sun placed on backwards compatability with older JREs -- much, if not all, of the java Generics changes are simply rewrite rules. C#, however, has no such constraints and can take advantage of a number of performance improvements that are not available to the java compiler. I still don't see that as an excuse for discarding type saftey. --ERC

    Wednesday, May 24, 2006

    Moving (moved?) the blog

    I've migrated over to a hosted blog at http://blog.ciscavate.org
    Bitwise Evolution is no longer published on blogger.

    Licensed to invent?

    My background in software development was built up on a strong belief that software should be freely available. This belief led me to start using GNU/Linux and various GPL'd projects as an undergrad at Oregon State University. Changing from the norm was painful - I had previously been on a window-only operating system diet, and while I could use Emacs, I was not yet zealous about it. Numerous times I tried to go back to Windows, but the 2-4 week reinstall cycle that I had convinced myself was required (and may have been... this was in the early Win 98 days) drove me back to open solutions.

    I eventually came to love the ability to customize everything. I have always been a "power user", and I spent many hours crawling through the NT registry when I was in High school. Linux, with the countless window managers and themeing sites drew me in like WinHack never could. As I became more skilled in software development, I began customizing apps to my liking, hacking out bug fixes and adding features as I wanted them. (Find a new game that looks cool, but can't stand playing it with the keyboard? Add joystick support!) All of this was made possible, or at least heavily benefitted from, open source licenses (Particularly the GPL).

    The intricacies of the various licenses were generally opaque to me, but I understood the gist of it:

    • The GPL let you release source code that was free but could not be made non-free by anyone but the author.

    • BSD-like licenses were less restrictive.


    That was about all I knew, or cared. I was happy with the GPL, and I've scoffed at the complaint that Viral licenses are evil.
    Recently, I started developing an application to assist with photograph management (back to the: customize everything point above... there are now to many applications to find exactly what I want, so I'm building my own--great solution, right?). I settled on Java for the programming language, and intended to use the SWT (released under the Eclipse Public License) as the widget toolkit, since it is a visually attractive cross-platform solution. However, I also want to make use of some GPL libraries. If you've read through the mentioned licenses, you probably see the problem already. It is not at all clear whether or not the SWT can be used with GPL applications. Azureus seems to be doing this, and releasing their code under the GPL. However, no one I've talked to can clearly state whether this is ok or not, and reference the relevant portions of legalese to support the claim.
    All this confusion has meant that the only "safe" route to either not release my program at all (I consider this unacceptable), or to settle on one of the two licenses above and only use compatible code, which means the GPL, simply because there is more GPL'd content available than EPL'd content. The depressing end is that the viral nature of the GPL is the reason there was a conflict, because the SWT cannot be re-released under an SWT-incompatible license (and it is not clear that I can do this and meet the GPL requirements that all source code be released as well.).

    I doubt that either the Gnu foundation or IBM would chase me down for voiding a license for my personal photo manager, but the open source movement relies on the copyleft licenses to stay afloat, to a certain degree. Without respecting those licenses we become hypocrits.

    I wonder if OCaml would work...

    Friday, January 27, 2006

    2005 in cities

    Copying an idea seen on Join-The-Dots:

    • Portland, OR

    • Corvallis, OR

    • Seattle, WA

    • Los Angeles, CA

    • San Diego, CA

    • Twin Falls, ID

    • Jackson Hole, WY

    • Lincoln, NE

    • Chicago, IL

    • DeBois, PA

    • New York, NY

    • Toledo, OH

    • Ogden, UT


    One or more nights in each city. Now, if only I had some ground-breaking reason for being in Ogden, UT and DeBois, PA :).