New C# 4.0 How-To Review

Of course I  think you should go get my book, but so do other people. 🙂 Here’s a recent, good review of the book: C# 4.0 How-To by Ben Watson.

Some excerpts:

There were a couple things about this book that really compelled me.  The format (this is a first How-To book by Sams for me so I assume it goes across the board) was very much like a focused blog.  It was broken up into small posts about each topic.  The other thing that compelled me was the amount of code samples.

That is definitely the style I was going for and I don’t know if anyone else has picked up on that yet.

Instead, this is a book that you set on your desk and put post-its and dog ears for key sections that you use and use and use before you put the pattern to memory.

I myself use the book in that manner whenever I need a refresh on how to accomplish something.

Go get it from Amazon or B&N or other great bookstores everywhere!

Birth of Emma Watson

Emma-20100820-27On August 6, 2010, our first baby, Emma, was brought into this world. It’s over a month since then, but as you can imagine, I’ve been busy. Smile She’s a beautiful, healthy, wonderful girl. Every day is a new adventure with her, as she learns something new, does something different, changes her patterns, and explores her world. Right now, she’s just fallen asleep with no almost no effort on our part for the first time.

Of course, I had to mark the occasion of her birth with a LEGO crib!

lego_crib-1-Edit

(more at flickr, click the image)

Another C# 4.0 How-To Book Give-away

In celebration of the beginning of the school year here in the USA, I’m going to give away a few more copies of my book C# 4.0 How-To .

If you’ve ever wanted a step-by-step guide with practicable code examples for hundreds of tasks in C#, .Net, and Windows, then this is the book for you. So far, I’m very pleased with the reviews its gotten (if you already have the book and haven’t left a review, why not? Smile)

Just leave a comment on this post, and I’ll choose two people at random. You must be in the US or Canada.

Also, for twitter users, if you retweet a link to this post using the hashtag #cs4howto, I’ll include you in the drawing as well.

The more comments and #cs4howto re-tweets there are, the more books I’ll give away!

Measure Amount of Data to Serialize with a Null Stream

If you’ve got to serialize some data, especially in a binary format, it’s common to output the length of the data. This is useful for versioning, random access, knowing when you’re done reading the records, among other reasons.

Therefore, you need to know the size of the data you’re going to serialize. There are a few ways to do this:

  1. Measure the position you’re at, write the data, measure the new position, subtract, and that’s your length.
  2. If you want to write the length first (which is usually better), you can write a dummy value, such as 0, then writing the data, then backing up in the stream, and writing the real value.
  3. If you can’t back up the stream (very possible in some situations, or undesirable in others), you can measure the amount of data before you write. However, now you have to maintain that code in addition to the actual serialization.
  4. My solution presented here, avoids having to maintain separate code by writing the data to a null stream which does not write any data, but keeps track of how much data was “written.”
class NullStream : System.IO.Stream
{
    public override bool CanRead { get { return false; } }
 
    public override bool CanSeek { get { return false; } }
 
    public override bool CanWrite {get { return true; } }
 
    public override void Flush() { /*do nothing*/ }
 
    public override long Length { get { return Position; } }
 
    private long _position = 0;
    public override long Position 
    { 
        get 
        {
            return _position;
        }
        set
        {
            _position = value;
        }
    }
 
    public override int Read(byte[] buffer, int offset, int count)
    {
        throw new InvalidOperationException();
    }
 
    public override void Write(byte[] buffer, int offset, int count)
    {
        Position += count;
    }
 
    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new InvalidOperationException();
    }
 
    public override void SetLength(long value)
    {
        throw new InvalidOperationException();
    }
}

You can use it like this:

long GetDataSize()
{
    using (NullStream stream = new NullStream())
    {
        if (SaveData(stream))
        {
            return stream.Position;
        }
    }
    return 0;
}

There is a downside to something like this: you’re still essentially doing a lot of the work of serialization. Sure, you’re not writing out the bytes anywhere, but if, say, you need to encode a string as bytes before writing to the stream, that’s still going to happen.

Still, this technique made sense in my case, maybe it will work for you.

Get a Free, Autographed Copy of C# 4.0 How-To!

To celebrate how well C# 4.0 How-To is doing, I’m going to give away two free copies of the book!

Here’s how it’s going to work:

1. Leave a comment on this post describing a project you’d like to build with C# 4.

2. I’ll pick two people from those comments at random.

(Make sure you enter your e-mail address where asked—it won’t be published to the blog, but I need it to contact you.)

I’ll leave the comments open for a while and I’ll update this post with the closing date.

Feel free to share a link to this blog post, tweet it, etc. If I get a lot of responses I may give away more.

Thanks to all those have already bought it!

UPDATE 18 May: I am going to close comments on Saturday morning (22 May) and pick the winners then. Thanks for commenting!

UPDATE 22 May: Comments are closed.

Blog moving hosts this weekend

I looked at my site’s settings in Google’s webmaster center and it told me that my site was in the top 5% slowest sites on the Internet. Wow. That really sucks. I’m sorry, dear reader. In any case, this was the final straw, after a string of outages and other general unhappiness. So I’m moving on…

I hope to make this change with no downtime, but who knows who well that will work.

C# 4.0 How-To Available Now!

Well, it’s finally out! Amazon no longer lists the book as available for pre-sale, and it should be shipping to purchasers today or tomorrow. If you’re a B&N shopper, you can also order it there, or grab it in stores within a few days.

From the product description:

Real Solutions for C# 4.0 Programmers

Need fast, robust, efficient code solutions for Microsoft C# 4.0? This book delivers exactly what you’re looking for. You’ll find more than 200 solutions, best-practice techniques, and tested code samples for everything from classes to exceptions, networking to XML, LINQ to Silverlight. Completely up-to-date, this book fully reflects major language enhancements introduced with the new C# 4.0 and .NET 4.0. When time is of the essence, turn here first: Get answers you can trust and code you can use, right now!

Beginning with the language essentials and moving on to solving common problems using the .NET Framework, C# 4.0 How-To addresses a wide range of general programming problems and algorithms. Along the way is clear, concise coverage of a broad spectrum of C# techniques that will help developers of all levels become more proficient with C# and the most popular .NET tools.

Fast, Reliable, and Easy to Use!

  • Write more elegant, efficient, and reusable code
  • Take advantage of real-world tips and best-practices advice
  • Create more effective classes, interfaces, and types
  • Master powerful data handling techniques using collections, serialization, databases, and XML
  • Implement more effective user interfaces with both WPF and WinForms
  • Construct Web-based and media-rich applications with ASP.NET and Silverlight
  • Make the most of delegates, events, and anonymous methods
  • Leverage advanced C# features ranging from reflection to asynchronous programming
  • Harness the power of regular expressions
  • Interact effectively with Windows and underlying hardware
  • Master the best reusable patterns for designing complex programs

I’ll be doing a book giveaway at some point as well, once I get my own shipment. Stay tuned!

Get it from Amazon

Get it from Barnes and Noble

How to position windows correctly at 120 DPI in WPF

If you want to place a window at a specific place in WPF, it will work pretty much as you expect—unless your DPI is 120 (the default is 96). Here’s a sample that shows how to put it where you want.

In this case, I want to put a window just under another control, aligned to its left side.

 

CalcWindow calc = new CalcWindow();
Point point = this.PointToScreen(
    new Point(0, this.ActualHeight));
 
PresentationSource source = 
    PresentationSource.FromVisual(control);
 
double dpiX = 
    96.0 * source.CompositionTarget.TransformToDevice.M11;
double dpiY = 
    96.0 * source.CompositionTarget.TransformToDevice.M22;
 
calc.Left = point.X * 96.0 / dpiX;
calc.Top = point.Y * 96.0 / dpiY;
 
calc.Show();

The crux of this is getting the current DPI. You could use P/Invoke to call native methods to get this, but the transformation matrix contains the same information as well.