Sign in
  • Blog
  • Archive
  • About
  • Contact

Welcome to rickardnilsson.net

rickardnilsson.net is a weblog and the online home of web developer and father of three, Rickard Nilsson... More

Rickard blogs about creating software solutions using ASP.NET and agile practices.

Sites I've visited recently

  • Scott Guthrie
  • Rtur.net
  • ASP.NET Forums
  • Karstad .NET User Group
  • JetBrains ReSharper
  • Scott Hanselman
  • dnrTV!
  • MIX 2009
  • BlogEngine.Net
  • YUI Theater

Categories

  • .NET
  • ASP.NET 2.0
  • BlogEngine.NET
  • C# 2.0
  • C# 3.0
  • CSS
  • Design by Contract
  • Design Patterns
  • JavaScript
  • TDD
  • User tip

Five most recent posts

  • ReSharper User tip #2: Refactor rename namespace
  • Building a Photo Album widget for BlogEngine.NET
  • Applying stylesheets dynamically with jQuery
  • ReSharper User tip: Refactor magical strings to variable
  • Blogging with MS Word 2007

Tag cloud

  • ajax
  • blog
  • blogengine.net
  • c#
  • css
  • dbc
  • design by contract
  • dom
  • douglas crockford
  • foto
  • getweekofyear
  • gregoriancalendar
  • highlight
  • html
  • humble dialog box
  • iso 8601
  • javascript
  • jquery
  • jscript
  • julian bucknall
  • metaweblog api
  • model-view-presenter
  • mvp
  • photo album
  • picasa
  • recent posts
  • refactor
  • refactoring
  • release
  • resharper
  • rhino mocks
  • syntax
  • syntax highlighter
  • tdd
  • test coverage
  • types
  • web service
  • week
  • widget
  • word 2007
  • yahoo
  • yui

Recent comments

  • Week and strong contracts in Design by Contact (3)
    Sulumits retsambew wrote: thanks nice tips RIckard [More]
  • Syntax highlighting in BlogEngine.NET (15)
    Sulumits retsambew wrote: great coding.. thanks for sharing it.. keep it up … [More]
  • Syntax Highlighter Release 0.2 Beta (17)
    SEO wrote: Nice post.I currently in a testing phase with this… [More]
  • Syntax highlighting in BlogEngine.NET (15)
    Max Glipmax wrote: Thanks for taking the time to discuss this, I feel… [More]
  • Building a Photo Album widget for BlogEngine.NET (11)
    tukang nggame wrote: nice widget, thanks for sharing download link [More]

ReSharper User tip #2: Refactor rename namespace

Tuesday, 26 August 2008 09:30 by Rickard

Have you ever wanted to rename a namespace but you have too many classes in the namespace that it would be an infeasible hassle changing all of them individually. Even using a tool like ReSharper to refactor the namespaces class by class is a hassle. I'm gonna show how to rename a namespace for all of its classes in a couple of key strokes using ReSharper.

Example

Mechanics

  1. Open Class View (Ctrl + Shift + C)
  2. Choose the namespace you want to rename
  3. Press Ctrl + R, R*
  4. Pick another name
  5. Hit Next

and you're done!

Please leave a comment if you found this useful.

* Visual Studio scheme

ddcec3ac-d58a-470b-aa35-ccc10cfdb394|0|.0
Tags:   resharper, refactoring
Categories:   .NET | User tip
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (1) | Comment RSSRSS comment feed

Building a Photo Album widget for BlogEngine.NET

Thursday, 14 August 2008 01:07 by Rickard

BlogEngine.NET has a widget framework from version 1.4 which are web part like components that can be added and removed, configured and dragged around directly in the page. Simple widgets are very easy to create and plug in to your blog and there are several blog posts explaining how to do that. In this post I'm gonna go through a more advanced example featuring Web services and Ajax.

The Photo Album Widget
The Photo Album Widget

Download: PhotoAlbumWidget-0.1.zip (7,96 kb)
Unzip to ~/widget/ folder. Requires jQuery library.


First we start with some requirements for the widget we're creating.

  1. BlogEngine.NET 1.4+ Widget
  2. Show thumbnail pictures
  3. Get pictures from Picasa web album
  4. Ajax style asynchronous loading
  5. Configurable number of pictures
  6. Clickable pictures to show full size picture 
  7. Picture repository provider model
  8. Flickr repository provider
  9. Folder repository provider
  10. Configurable picture count
  11. Provider specific configuration
  12. Configurable choice of provider
  13. Full size picture pops up in Lightbox
  14. Web 2.0 style controls for scrolling
  15. Larger preview on mouse over picture

The list above is a prioritized backlog and the first version should include items 1 - 4.

Widget 

We start off with number one, a BlogEngine Widget. To create a widget we add a new folder to the /widget/ folder and we call it PhotoAlbum. Then we create two user controls, one for widget presentation and one for configuration UI. They must be named, by convention, widget.ascx and edit.ascx respectively and should derive from WidgetBase and WidgetEditBase respectively. See more on basic widgetry here by Rtur and here by Mads as well as this, that and whatnot.

That was the easy part.

Picasa web album

With the next requirement we first need to get the pictures from somewhere so we skip to the next requirement. Picasa is Google's web album and it has its own REST API as well as a .NET client library. Conveniently there is also a public feed which contains all public photos uploaded to Picasa. (You can of course use your own Picasa album, see the Data API docs for more information). All we need to do is provide a query tag/tags to limit the search or we'll get an error message. The following code retrieves a couple of photos picturing cats:

PicasaService service =
    new PicasaService("exampleCo-exampleApp-1");

PhotoQuery query = 
    new PhotoQuery("http://picasaweb.google.com/data/feed/api/all");
query.Query = "cat";
query.NumberToRetrieve = 5;
PicasaFeed feed = service.Query(query);

foreach (PicasaEntry entry in feed.Entries) {
    string firstThumbUrl = entry.Media.Thumbnails[0].Attributes["url"] as string;
    writer.Write("<img src=\"{0}\" alt=\"{1}\" />",
                 firstThumbUrl, entry.Title.Text);
}

If we drop the code above into the widget.ascx.cs we affectivally fullfills both requirements 2 and 3 so lets get on with number 4.

Ajax

Requirement number four implies the Incremental Page Display pattern where the main part of the page is shown quickly and portions of the page that takes longer to load are fetched and displayed asynchronously. To give the user feedback of the loading we place an animated gif image in the widget which is later swapped out when the real pictures arrive. To accomplish this we're using the jQuery JavaScript library which let us get away with very little code for pretty advanced stuff.

First we need to do a little refactoring since the widget needs to do an asynchronous call somewhere to get its content, i.e. the pictures to display. We're gonna go with the simplest possible solution here, just enough to satisfy the requirement. The simplest thing from the widget's point of view is to have the html containing a number of <img> elements returned from the call. Then it's very simple to insert the html into the widget using jQuery. Given that the widget contains a div with the id "photoalbum" this is all it takes:

$("#photoalbum").html(the_html_to_insert);

As it is now, the widget codebehind is rendering the requested html and this is not god. We need to move the code to some place which we can make a http request to and get the html in response. This can be done with a regular aspx page. All we need to do is to put a simple Repeater control on a page and bind it to a list of image URLs which we get from Picasa web album. So, we add a new aspx page to the /widgets/Photo Album/ folder and call it PhotoService.aspx. All we want in response is the <img> tags which should be inserted into the widget so we clear the page from html and put a single Repeater on it like this:

<asp:Repeater ID="pictureRepeater" runat="server">
    <ItemTemplate>
        <asp:Image ID="image" runat="server"
            ImageUrl="<%# Container.DataItem.ToString() %>" />
    </ItemTemplate>
</asp:Repeater>

In the codebehind we insert something like before and makes sure we bind to the Repeater control.

// Error checking is omitted for clarity
List<string> pictures = new List<string>();
PicasaService service = new PicasaService("exampleCo-testApp-1");

string picasaUri = "http://picasaweb.google.com/data/feed/api/all";
PhotoQuery query = new PhotoQuery(picasaUri);
query.Query = "cat";
query.NumberToRetrieve = 6;
PicasaFeed feed = service.Query(query);

foreach (PicasaEntry entry in feed.Entries) {
    string firstThumbUrl = entry.Media.Thumbnails[0]
                               .Attributes["url"] as string;
    pictures.Add(firstThumbUrl);
}

pictureRepeater.DataSource = pictures;
pictureRepeater.DataBind();

To test the service we point a web browser to /widgets/Photo Album/PhotoService.aspx which should show a bunch of cats! Everything looks good and all we need to do to get the pictures into the widget are two things. First we need to register the jQuery JavaScript file, either localy or a referer to the jQuery official site. Last we need to add some custom JavaScript that makes the Ajax call and puts the html at the right place.

JavaScript blocks should allways, if possible, be placed as close to the </body> tag as possible. The reason is that the browser won't continue to load the remainder of the page when it hits a JavaScript block but rather wait until it is fully loaded. This is not a problem if we're dealing with short scripts but the jQuery library is relatively large in this context so we need to put it as far down the page as possible. Our own script that does the actual work depends on jQuery, thus it must be loaded last. The problem is that we need to do this in a User control in the middle of the page. To our help to solve this we have the ClientScriptManager that every aspx page has. With the method RegisterStartupScript we get to insert arbitrary scripts just before the </form> tag (which is close enough) of the surrounding page. We make the registrations when the widget is loaded, i.e. in the LoadWidget() method.

With this final step done we have our first version of the Photo Album Widget which is ready for demo.

Problems with the solution

Before the second iteration I'd like to summarize a couple of things with version one that are not of production quality.

  1. PhotoService mimics the behavior of a Web service (kind of) but is really a simple aspx page
    - We could have done a Generic handler (ashx) instead but then we couldn't have used a Repeater
    - We could have done a custom HttpHandler but that need to go into App_Code and edit web.config which is harder to install
  2. The requirements maybe fullfilled but no one cares for a widget that only display cats!
    - We need to be able to configure the feed as well as the query.
a3988f31-ed80-4694-b4ca-85641d66c15d|1|2.0
Tags:   widget, photo album, web service, ajax, jquery, picasa
Categories:   BlogEngine.NET | JavaScript
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (11) | Comment RSSRSS comment feed

Applying stylesheets dynamically with jQuery

Saturday, 2 August 2008 21:58 by Rickard

A colleague of mine asked me how to apply a stylesheet to a web page dynamically using jQuery and I had never done such a thing but my first thought was that is must be pretty simple. I've spent a lot of time thinking of so many things other than web et. al. so it was nice to delv into some of that stuff again. Check out the live demo.

As we know stylesheets are defined in the head section of an html file like this

<html>
    <head>
        <link rel="stylesheet" href="stylesheet.css" type="text/css" />
    </head>
    <body>
    ...
</html>

Now, say that we want to apply another stylesheet dynamically after the fact, so to speak, triggered by some event. This could be a button click or some other arbitrary event that is triggered. So, what we want to do is simply insert a new <link/> element into the head section of the page DOM. This can be done in a couple of lines of jQuery:

$(document).ready(function() {
    $("a").click(function() {
        $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
    });
});

The key is at what time we add the link to the style sheet. The first line in the code above repeated here asserts that the DOM is ready for manipulation.

$(document).ready(function() {
    //...
});

The second part repeated here adds a click event to all hyperlinks in the page.

$("a").click(function() { //...

And the very task is performed by the last piece of code where the head element is appended with a new link element.

$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');

5c25bdf1-2101-472d-ac43-4f9582f2455c|3|3.3
Tags:   jquery, css
Categories:   CSS | JavaScript
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (3) | Comment RSSRSS comment feed

ReSharper User tip: Refactor magical strings to variable

Thursday, 31 July 2008 00:28 by Rickard

I've been using Jetbrains ReSharper a while now and I love it. I can't even imagine going back to plain Visual Studio anymore because there are so many things in my daily work that involves ReSharper, even simple tasks like editing source code and navigating through code and source files, let alone creating files and running unit tests.

Now I want to share a user tip I found that isn't obvious to find nor part of any context menu. It's actually a refactoring and I call it Magical strings to variable. You can use it when you end up with multiple equal string literals in a piece of code. You would probably want to gather all of the string literals in a variable and reuse it through out the code. You can use ReSharper to do it for you in a couple of key strokes.

Example

[Test]
public void ParentPresenter_Update_should_update_view() {
    var model = new User {
                        Name = "foo"
                    };

    using (mockery.Record()) {
        Expect.Call(parentView.Username = "foo");
    }

    using (mockery.Playback()) {
        IParentPresenter presenter = new ParentPresenter(parentView) {
                                Model = model
                            };
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo("foo"));
    }
}

[Test]
public void ParentPresenter_Update_should_update_view() {
    var name = "foo";
    var model = new User {
                        Name = name
                    };

    using (mockery.Record()) {
        Expect.Call(parentView.Username = name);
    }

    using (mockery.Playback()) {
        IParentPresenter presenter =
            new ParentPresenter(parentView) {Model = model};
        presenter.Update();
        Assert.That(presenter.Model.Name, Is.EqualTo(name));
    }
}

Mechanics

1. Highlight one of the string literals

2. Press Ctrl+R, V (Ctrl+Alt+V)* to introduce a variable

3. Select to replace all occurrences (default option)

4. Pick a name for the variable

..and you're done! Please leave a comment if you find this usefull.

* Visual Studio scheme (ReSharper 2.x / IDEA scheme)

c10c5f10-8f62-4ef6-8fde-670c0b683e60|0|.0
Tags:   resharper, refactoring
Categories:   C# 3.0
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (0) | Comment RSSRSS comment feed

Blogging with MS Word 2007

Monday, 28 July 2008 19:13 by Rickard

Thanks to the new MetaWebLog API in BlogEngine.NET you can use MS Word 2007 to write your blog posts including using graphics, charts and the full feature set of Word 2007. Read about how you set it up at Rtur.net. You can even use Word 2007 to edit posts on the blog server.

Note: This post was published using Word 2007.

9cd94949-db79-4d60-b0f2-33d1af825313|0|.0
Tags:   blogengine.net, word 2007, metaweblog api
Categories:   BlogEngine.NET
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (0) | Comment RSSRSS comment feed

Problem with Related Posts in BlogEngine.NET 1.4

Sunday, 27 July 2008 03:35 by Rickard

With the new release of BlogEngine.NET a new feature was added that shows the description or part of the post when listing related posts. If the description is empty a small part of the post content is listed instead and here in lies the problem. The post content is simply clipped as a certain length without regard to any tags in the post. Let's say a related posts goes like this:

With the new release of
<a href="http://www.dotnetblogengine.net">BlogEngine.NET</a> a new feature was added.

Now, when the post is clipped it may end up cutting in the middle of the href:

With the new release of <a href="http://www.dotnetblo...

And this may probably screw up the layout and content of the remainder of the page, besides producing an html that will not validate.

Solution

This issue has been discovered and fixed for a future release of BlogEngine.NET. However, if you, like me don't or can't wait that long here's a fix:

The problem is that the html tags are not closed so the simple solution is to strip the related post of all html. My first thought was to parse the post and close all open tags but when I thought about the actual intent of the related posts I realized that it is to provide a preview of the post content, not to show part of the actual post. So, by stripping all html tags all images and links are removed and only the text remains, which provides a really nice preview.

To implement the solution you only have to edit one line of code in the App_Code/Controls/RelatedPosts.cs file on row 139:

string content = post.Content;

 

string content = Utils.StripHtml(post.Content);

Or you can download the appended file and replace the one in the App_Code/Controls/ folder.


RelatedPosts.cs (3,77 kb)

 

8e71f70b-132b-4dd0-8d89-7bdffeec05b1|0|.0
Tags:   blogengine.net, recent posts
Categories:   BlogEngine.NET
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (0) | Comment RSSRSS comment feed

The Humble dialog v.2

Tuesday, 15 July 2008 20:41 by Rickard
Update! Download source: TheHumbleDialog2.zip (29,96 kb)
I've been working to get my head around the Model-View-Presenter pattern and I've focused primarily on a Winforms scenario. As it turns out there are numerous sources out there on MVP, some of which are focused on Winforms, e.g. [2, 8] and some which are not focused on Winforms but highly valuable just the same, e.g. [1, 4].


Figure A. Screen mock up 

However, none of the referenced sources discusses the issue of communication between MVP triads. All of them thoroughly discusses the ins and outs when you have a single presenter talking to a single view and a single model, but nothing about communicating with other MVP sets. I've also found that other people are also struggling with this problem and how to best solve it but no really good solution has presented itself.

The problem

Well, we start with an example to formulate the problem. If we look at the example of the humble dialog [8] this only covers a single triad so we make it slightly more complicated. We have two views, a parent view and a dialog view, and each view has an associated presenter, i.e. parent presenter and dialog presenter. Now, the requirement is that when a user clicks a button on the main view the dialog should pop up modally giving the user the possibility to change a property value. The value change should then be reflected in the parent view. Sounds simple enough, right?

The problem is to implement this leveraging the MVP pattern to achieve a loosely coupled, highly cohesive, and test friendly solution. Some of the questions are; who has the responsibility to create the dialog view, who has the responsibility to show the view, what is the result from the dialog view and who should act on it.

MVP Solution

There are many different ways we can go about doing this but since I'm into Test-Driven Development I'm gonna do it test first. I also like to do UI up front so I create a Winforms project in Visual Studio and start dragging and dropping. The simplest possible screens are shown in figure A.

OK, now let's start with our first test. We want the dialog to appear when the "Edit user name" button is clicked and following MVP the view should simply pass on control to its presenter. The parent presenter should then have the dialog view popping up. This is the first test using Rhino Mocks [3]:

[Test]
public void ParentPresenter_EditUsername_should_open_a_dialog() {
    var view = mockery.DynamicMock<IParentView>();
    var dialogPresenter = mockery.CreateMock<IDialogPresenter>();
   
    using (mockery.Record()) {
        dialogPresenter.Load();
    }

    using (mockery.Playback()) {
        var presenter = new ParentPresenter(view)
                            {
                                DialogPresenter = dialogPresenter
                            };
        presenter.EditValue();
    }
}

The parent presenter should simply pass the control to the presenter of the dialog. Thus, the parent presenter has a dependency on the presenter of the dialog and the dependency is injected through a property:

var presenter = new ParentPresenter(view)
                    {
                        DialogPresenter = dialogPresenter
                    };

Now, these interfaces and classes doesn't exists so first we have to create them. But before we do I see some code that has no test, namely dialogPresenter.Load(), so let's write another test:

[Test]
public void DialogPresenter_Load_should_call_show_on_view() {
    var view = mockery.DynamicMock<IDialogView>();

    using (mockery.Record()) {
        view.Show();
    }

    using (mockery.Playback()) {
        var presenter = new DialogPresenter(view);
        presenter.Load();
    }
}

So, the presenter simply tells the view to show itself. Remember that we're talking to an interface and that the view in the test is not the real implementation. We're only driving out the behavior of the presenter at this point but we're doing it in such a way that the view implementation should be as thin a possible.

Code generation

I'm using ReSharper [7] to generate the interfaces and classes that I dreamed up in the tests.

More testing

When the initial tests are passing let's move on. The next thing that should happen is the user providing a new user name in the dialog and clicks on OK. So lets write a test for the OK event. I realize that some refactoring is also in place:

[Test]
public void DialogPresenter_ChangeName_should_change_value_and_close_dialog() {
    var model = mockery.CreateMock<User>();
    var callBack = mockery.CreateMock<Action>();
    var expectedName = "foo";

    using (mockery.Record()) {
        Expect.Call(dialogView.Username).Return(expectedName);
        dialogView.Close();
        callBack();
    }

    using (mockery.Playback()) {
        IDialogPresenter presenter = new DialogPresenter(dialogView)
                                         {
                                             Model = model
                                         };
        presenter.NameChanged += callBack;
        presenter.EditName();

        Assert.That(model.Name, Is.EqualTo(expectedName));
    }
}

Passive view and Observer synchronization

The last requirement states that the user name change should be reflected in the parent view. There are a couple of ways to do this but in this example I'm gonna go with the Observer synchronization [6] strategy because it provides a nice separation of concerns and is easy enough to mock. Note, however, that it is the presenter which acts as the Observable, not the domain object itself (User in this case). This is because I do not want to polute the domain model with event code. The previous test verified that a callback method is called whenever the name in the dialog is changed. Now, the parent presenter only has to hook up an event handler to the dialog presenter's event. Our next test shoes what should happen in the parent presenter when the event is triggered:

[Test]
public void ParentPresenter_Update_should_update_view() {
    var model = new User {Name = "foo"};

    using (mockery.Record()) {
        Expect.Call(parentView.Username = "foo");
    }

    using (mockery.Playback()) {
        var presenter = new ParentPresenter(parentView)
                            {
                                Model = model
                            };
        presenter.Update();
    }
}

So, the presenter explicitly tells the view what to do. The parent view is an example of a Passive view [5]. The presenter's code is included below for completeness:

// Parent Presenter
public class ParentPresenter {
    private readonly IParentView view;

    public ParentPresenter(IParentView view) {
        this.view = view;
        this.view.Presenter = this;
        Model = new User();
        DialogPresenter = new DialogPresenter(new DialogView())
                              {
                                  Model = Model
                              };
        DialogPresenter.NameChanged += Update;
    }

    public IDialogPresenter DialogPresenter { get; set; }
    public User Model { get; set; }

    public void Load() {
        view.Show();
    }

    public void EditValue() {
        DialogPresenter.Load();
    }

    public void Update() {
        view.Username = Model.Name;
    }
}

// Dialog Presenter
public class DialogPresenter : IDialogPresenter {
    public event Action NameChanged;
    private readonly IDialogView view;

    public DialogPresenter(IDialogView view) {
        this.view = view;
        this.view.Presenter = this;
    }

    public User Model { get; set; }

    public virtual void Load() {
        view.Show();
    }

    public void EditName() {
        Model.Name = view.Username;
        view.Close();

        if (NameChanged != null)
            NameChanged();
    }
}

And then the view implementation which is as minimalistic as possible:

// Parent View
public partial class ParentView : Form , IParentView {
    public ParentView() {
        InitializeComponent();
    }

    public ParentPresenter Presenter { private get; set; }

    public string Username {
        set { username.Text = value; }
    }

    void IParentView.Show() {
        Application.Run(this);
    }

    private void editValueButton_Click(object sender, EventArgs e) {
        Presenter.EditValue();
    }
}

// Dialog View
public partial class DialogView : Form , IDialogView {
    public DialogView() {
        InitializeComponent();
    }

    public IDialogPresenter Presenter { private get; set; }

    public string Username {
        get { return nameTextBox.Text; }
    }

    void IDialogView.Show() {
        ShowDialog();
    }

    void IDialogView.Close() {
        Close();
    }

    private void acceptButton_Click(object sender, EventArgs e) {
        Presenter.EditName();
    }
}

Conclusion
The way the MVP parts are separated makes a UI with allmost 100% test coverage but above all the UI logic is in a separate class which is not tied to a frame, thus enabling us to discover duplicated code and oportunities to refactor and keep the UI maintainable. I think that this is a great way of driving out a design since I start out with the client hat on and not the other way around were I first list a bunch of methods and properties on a class. IMO this kind of interaction based testing really lends itself to driving out interaction design, and tools like ReSharper really makes the developer experience pleasant and productive.
References

[1] Jean-Paul Boodhoo. Design Patterns: Model View Presenter
[2] Dan Bunea. Model View Presenter - is testing the presenter enough
[3] Oren Eini. Rhino Mocks - dynamic mocking framework
[4] Michael Feathers. The Humble Dialog Box
[5] Martin Fowler. Passive View
[6] Martin Fowler. Observer Synchronization
[7] JetBrains. ReSharper
[8] Jeremy Miller. A Simple Example of the "Humble Dialog Box"

3a386a58-6c19-421c-b641-d83055e84ead|0|.0
Tags:   model-view-presenter, mvp, humble dialog box, tdd, rhino mocks, resharper
Categories:   C# 3.0 | Design Patterns | TDD
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (4) | Comment RSSRSS comment feed

Syntax Highlighter Release 0.2 Beta

Monday, 5 May 2008 21:50 by Rickard

Thanks to a great deal of interest on my post on syntax highlighting in BlogEngine.NET a while ago I'm now releasing a new version. It is based on the version that ships with BlogEngine.NET but it has been augmented as well as refactored to support more language elements like types in C#. The code formatter has been extracted and the new version is released through CodePlex.

Additional features compared to version 0.1

  • Highlighting of types in C#
  • Architecture to support additional language elements

Syntax Highlighter Extension

  • The code block is recognized anywhere in the blog post and does not require any special formatting before or after the code tags
Download
  • www.codeplex.com/syntaxhighlighter

I will start a series of blog posts on using and developing the new version. I thank those who have shown interest.

0d3dca08-f8e1-4ffb-abc5-d3919c69ea9d|0|.0
Tags:   syntax highlighter, c#, types, blogengine.net, release
Categories:   BlogEngine.NET
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (17) | Comment RSSRSS comment feed

Syntax highlighting in BlogEngine.NET

Saturday, 12 April 2008 00:22 by Rickard

BlogEngine.NET ships with an extension that automatically highlights source code in blog posts. All that is required is that the source code block is surrounded with [code:lang][/code] tags. The extension will markup the code with CSS classes and the default theme includes a default color scheme for code elements like keywords, comments, and so forth. The extension ships with support for HTML, C#, JavaScript, T-SQL, MSH, and Visual Basic.

In forums and blogs in the BlogEngine community issues with the syntax highlighter extension has been brought up. Some of it can be found here, here, and here. Many has complained about how hard it is to use and lack of proper documentation. To get the tags to be recognized by the extension you have to format your post in a really precise manor with a leading and trailing <p></p>. Besides taking up a lot of unnecessary space when editing the post, this is why so many has complained that they can't get it to work. If the block is not correctly surrounded with the right amount of line breaks two things can happen. Either the whole code block is masked or the code is shown but the tags are rendered as part of the code block.

My own experience with this is pretty much the same and the only way to find out how it works was for me to read and step through the code. Since the extension is open source there is no hinder for improving the code base, hence I've been working to improve it to meet the community need, as well as my own. In addition to the mentioned usability issues I missed highlighting of types in C#, that is class, interface, and struct names which we are used to see in Visual Studio colored in cyan.

New version

I'm about to present a new version of the extension which will include the following improvements:

  • Highlighting of types in C#
  • The code block is recognized anywhere in the blog post and does not require any special formatting before or after the code tags.

Leave a comment on this post if you wish to be notified when the new version is available.

Example of syntax highlighting in BlogEngine.NET using the improved version

ICustomer customer = new Customer("kalle");
RegEx regex;
ICollection<Customer> coll = new ICollection<Customer>();
Stack<Name.Space.Customer> stack = new Stack<Name.Space.Customer>();
stack.Put(customer);
customer.Age = 24;

[Serializable]
public class Customer : ICustomer , IComparable<ICustomer> {
    public Customer(string name) {
        this.name = name;
        person = new Person(name);
    }
    public int Age {
        get { return age; }
        set { age = value; }
    }
    IPerson _p = Person.CurrentUser;
    IPerson person;
    internal IPerson Person {
        get {
            return this.person;
        }
    }

    private ShopingCart cart = new ShopingCart();
    protected ShopingCart GetCart() { return cart; }
}

Related work
  • C# code format
    • by Jean-Claude Manoli
    • author of the syntax highlighter extension for BlogEngine.NET
    • Not the same code as shiped with BlogEngine.NET
    • does not support types in C# 
  • Syntax highlighter
    • by Wilco Bauwer
    • linked from the extensions list on dotnetblogengine.net
    • does not support types in C#

 

ac496c26-4832-4a53-ae23-d3917ea0689e|0|.0
Tags:   syntax, highlight, c#, blogengine.net
Categories:   ASP.NET 2.0 | BlogEngine.NET | C# 2.0 | CSS
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (15) | Comment RSSRSS comment feed

Week and strong contracts in Design by Contact

Monday, 31 March 2008 02:22 by Rickard

Answer to Fredrik Normén on Defensive programming and Design by Contract on a routine level.

"Design by Contract is about creating a contract between the client and the supplier. The idea of the Design by Contract theory is to associate a specification with every software elements. This specification will define a contract between client and the supplier. When a supplier writes a contract with the client, it should document the obligations and benefits"

There is always a contract between a software element and its client. The question is if the contract is implicit or explicitly stated. Lets look at an example from the .NET framework:

public virtual void Add(object key, object value) 
    Member of System.Collections.Hashtable

Summary:
Adds an element with the specified key and value into the System.Collections.Hashtable.

Parameters:
key: The key of the element to add.
value: The value of the element to add. The value can be null.

Exceptions:
System.ArgumentNullException: key is null.
System.ArgumentException: An element with the same key already exists in the System.Collections.Hashtable.
System.NotSupportedException: The System.Collections.Hashtable is read-only.-or- The System.Collections.Hashtable has a fixed size.

A short analysis conducts that the method's contract can be expressed like this:

Precondition:
 ○ true
Postcondition:
 ○ If key is null ArgumentNullException is thrown
 ○ If ContainsKey(key) ArgumentException is thrown
 ○ Else this[key] == value
 ○ And Count == old Count + 1
 
An analysis of the contract shows that the contract can be made stronger like this:

Precondition:
 ○ Key != null
 ○ !ContainsKey(key)
Postcondition:
 ○ this[key] == value
 ○ Count == old Count + 1
 
In the theory of contracts there is this concept of strong versus week contacts where the first is more demanding on the client than the last. Hence, the precondition is now more demanding on the client and this can be taken advantage of in the routine implementation. In the pseudo code below we can see the difference:

Week contract supplier

public virtual void Add(object key, object value) {
 if (key == null) {
  throw new ArgumentException(…);
 }
 if (ContainsKey(key)) {
  throw new ArgumentException(…);
 }
 this.buckets[hashcode(key)] = value;
}

Strong contract supplier

public virtual void Add(object key, object value) {
 this.buckets[hashcode(key)] = value;
}

Using the stronger contract we get a much cleaner implementation of the routine. How about the client code then? Well, take a look:

Week contract client

try {
 hashtable.Add(key, foo);
} catch (ArgumentException ex) {
 // oops, we made a mistake!
}

Strong contract client

if (!hashtable.ContainsKey(key) {
 hashtable.Add(key, foo);
}

Of course, the code for the strong contract client can be used with the week contract as well. The main point is that with the strong contract no error handling should be made because then there is an error in the client code which should be corrected, not handled at runtime. The routine only promise to satisfy the post condition if and only if  the pre condition is satisfied by the client. If the pre condition is not met the outcome is undefined and anything can happen from nothing at all to the system crashing. This is where frameworks that permit developers to express the contract in code comes in.

Design-by-Contract Frameworks
As Fredrik mentions Eiffel was the first programming language to have syntactic support for expressively stating contracts. For .NET there has been several attempts to do the same in addition to Spec#. Here is a list:
  • nContract
    • MS thesis by Wes Haggard
    • Example:

[FormallySpecified]
public class Test {
  [Pre("i > 0")]
  public void DoWork(int i) { }
}

  • ContractN
    • By Dave Sexton
    • Example:

public class Person : ContractN.ProgrammingByContract
{
  [InRequired, OutRequired]
  public string Name { get; set; }
}

  • Design by Contract Framework
    • By Kevin McFarlane
    • Example:

public virtual int B.Foo(int x)
{
  Check.Require(1 < x < 3);
  ...
  Check.Ensure(result < 15);
  return result;
}

I might find a reason to return with a more thorough review of the frameworks in the future.
afe77f7f-e460-465d-80a4-34ac5fb675b5|0|.0
Tags:   dbc, design by contract
Categories:   C# 2.0 | Design by Contract
Actions:   E-mail | Permalink | Kick it! | DZone it! | del.icio.us | Comments (3) | Comment RSSRSS comment feed
<< Previous posts
 
Copyright © 2008-2009 rickardnilsson.net