Tigraine

Daniel Hoelbling-Inzko talks about programming

Printing in .NET is simply broken

Ok, I blogged about the failed GDI+ API yesterday and complained about it. Those of you who are following me on twitter may already know that my little liaison with GDI+ is due to some printing my application has to do and the experience hasn’t been good so far.

My requirement is quite simple, print invoices and some other papers that may (or may not) span multiple pages.
So I came up with a very simple design for my printing needs that lets me reuse all printing dialogs by supplying different strategy classes that do the printing.

image

This has worked out so far, but I’ll have to adjust since I found out that printing multiple pages works totally different from what I expected. In my stupid little world I was thinking that going on to the next page would be as easy as calling NextPage() somewhere and the Graphics object would start drawing to the new page.

And I was so wrong.
Apparently, how it really works is by specifying in your print event that your document has multiple pages and the print event will fire as long as eventargs.HasMorePages is true. Yep, that’s right, the event will fire again!

So apparently, all code that gets called has some way of determining what stuff doesn’t fit on the page (that itself is a huge pain in the ass with graphics.MeasureString and everything) and it also has to find out what parts have already been printed to another page.

So, in a simpler world I’d have a switch statement that would branch depending on the page number like this:

private int pages = 3;
private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    switch (pages)
    {
        case 1: 
            //print page 1
            break;
        case 2:
            //...
            break;
    }
    pages -= 1;
    e.HasMorePages = pages > 0;
    if (pages == 0)
        pages = 3;
}

The irony of this is that this no longer works if you can hit a new page once your string exceeds one page. You’d have to cut off the string (after heaving measured that it won’t fit), and somehow store it so that when the method gets called next time the “part” that’s not printed yet will get printed. Can it get more stupid than that?
Having multiple entries into one method just seems plain wrong and leaves me no option as to have code everywhere to determine if something has already been printed (no need to say all the hassle there is to cut off something on page A and print the overflow on page B).


This whole RectangleF/SizeF acrobatics with almost static method calls in between feels so much like last century that I am very well inclined to write some OO library in the future to save me the hassle next time.

By the way, first I was thinking that if printing from within .NET turns out to be too hard I had this fallback plan to just generate HTML, display it in a Webbrowser control and print it from there. I should have done it that way, simple things tend to work :).

Filed under net, net, c, programmierung, printing

Anatomy of a pattern: Singleton

Singleton is one of the simplest patterns that does just one thing: Ensure that there is one object to rule them all, one object to bind... (Ok sorry got dragged away).

The idea is simple: Sometimes (especially when writing to disk with open file handles) you need to ensure that there is only ONE instance of a class going on at any time. And that's it. It's so simple, you could turn it into a 1-liner:

public static Singleton _Instance;

But things never are that simple ;). By using only a shared variable you may end up calling the constructor twice, resulting in 2 objects that may get used by two different clients.

To avoid this you'll need to get an exclusive lock of the Singleton to ensure it's really empty before you instance it.
And that's how it's usually done

private static Singleton _Instance;
private static Object __LockObject = new object();

public static Singleton GetInstance() {     if (_Instance == null)     {         lock(__LockObject)         {             if (_Instance == null)                 _Instance = new Singleton();         }     }     return _Instance; }

In the singleton implementation the static Singleton variable holds the reference to the Singleton, and whenever we try to get a reference to this instance we check if it's already set and return the value.

If not, it get's tricky when 2 threads are getting a cache-miss at the exact same time (_Instance == null). If you aren't synchronizing at this point you may end up with two different references of a singleton object being used (and causing problems with resources being consumed twice, causing ). So it's important to perform another check when you have exclusive reign over the shared object (by using a lock object here).


This ensures that no two threads will try to create a new instance to your singleton, while not slowing down your read-performance at all.

Sample code: Singleton.cs

Enumerators in C#

I am still trying to figure out if what I did was useful or not.

Based on the assumption that sometimes you may need a variable typed IEnumerable<T> to hold a value that only implements IEnumerable I wrote this adapter class (you find it after the jump).

What's IEnumerator?
IEnumerator it the old non-generic implementation of the Iterator pattern, while IEnumerator<T> is the strongly-typed generic version introduced in .NET 2.0.

IEnumerable<T> implements IEnumerable, but there is no way to cast IEnumerable to IEnumerable<T>. So I wondered how you could comply to the Iterator pattern.

My first suspicion came when I tried foreach on both IEnumerables. Foreach has no problem with both of them, so I dug out my C# language spec and discovered that foreach has to use two different methods for either IEnumerable or IEnumerable<T> (That's not really clear there, anyone to falsify my assumption?).
They could have gone the other way and use the non-generic IEnumerable for the iteration, but that would need an implicit typecast on every iteration (and that would slow things down I guess).

In a scenario like the following one you can't pass the Enumerator created by an Array.GetEnumerator() because it uses IEnumerator instead of the generic version IEnumerator<T>.

public void PrintList(IEnumerable<String> MyList)
{
  
foreach (String Entryin MyList)
    {
      
Console.WriteLine("{0}", Entry);
    }
}

Because IEnumerable<T> implements IEnumerable you could just switch back to the non-generic version, but that's something I don't really like (although it may be more practical).

So here are 2 (very simple) adapter classes that will provide upward-compatibility to your IEnumerable and IEnumerator needs:


public class GenericEnumerableAdapter<T> : IEnumerable<T>
{
    private IEnumerable _Old;
    
    public GenericEnumerableAdapter(IEnumerable OldEnumerable)
    {
        this._Old = OldEnumerable;
    }

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator() { return new GenericEnumeratorAdapter<T>(_Old.GetEnumerator()); }

#endregion

#region IEnumerable Members

IEnumerator IEnumerable.GetEnumerator() { return _Old.GetEnumerator(); }

#endregion }

public class GenericEnumeratorAdapter<T> : IEnumerator<T> { private IEnumerator _OldEnum; public GenericEnumeratorAdapter(IEnumerator OldEnumerator) { _OldEnum = OldEnumerator; }

#region IDisposable Members

public void Dispose() { this._OldEnum = null; }

#endregion

#region IEnumerator<T> Members

public T Current { get { return (T)_OldEnum.Current; } }

object IEnumerator.Current { get { return _OldEnum.Current; } }

public bool MoveNext() { return _OldEnum.MoveNext(); }

public void Reset() { _OldEnum.Reset(); }

#endregion }

C# Talk

Now and then I delve through some Java tutorials or Java applications for my studies. And everytime I do so I immediately lack the getter/setter language features of C#.

To make myself clear (to non-C# Developers). Java has either Public or Private properties, but no way to add validation Logic etc to those. It is usually considered bad coding technique to expose instance variables outside of the class so almost everything has to be accessed through functions. So to expose a integer variable called State you would have to create something similar to this:

get_set_Java 

It works and once you're used to it you will create setter/getter methods in your sleep. But, when pulling up your IntelliSense (ok, you don't have that in Java, but you know what I mean) on that class you will be somewhat overwhelmed by get/set functions :).

So, how did C# handle this? They borrowed a bit from Delphi and C# and created properties with get/set blocks (nothing new). So our code from above would look like:

get_set_C

The great thing: Intellisense gets easier, you have something clearly marked as property not as function (that's used to access a property). Usability for your API has just increased :).

But, despite the awesomeness of this function (already in the .NET Framework since 1.0) in .NET 3.5 they managed to improve this feature a bit. How? Imagine all those cases where you don't have any validator logic on your properties, you just want a simple public field in your class. In older Frameworks you'd have to create get/set Blocks for this Field although you don't want any logic there (exposing Instance-Variables is stupid no matter how you do it).

So, 3.5 Introduced this:

get_set_35

Great, we came down to 1 line of code, and what happened? .NET creates the private instance-variable automatically and handles the simple get/set stuff for us. When we decide we need validation or something in the get/set blocks we can just come back and expand those blocks without having to change any code outside the class (it was a get/set property all the time)

My Photography business

Projects

dynamic css for .NET

Archives

more