Apr
30.
2007

More on which WPF book to buy

Posted by: Drazen Dotlic in Categories: .NET (C#) | rant.
Tags:
Last time I touched this subject was to recommend Charles Petzold’s book. In fact I said something that I’d like to correct now. I said:

If for some reason you must choose only one book on WPF, you should choose Petzold’s.

Windows Presentation Foundation Unleashed (WPF) (Unleashed)A new book arrived that changed my recommendation: Adam Nathan's WPF Unleashed. It does not go as much in depth as Petzold’s but overall, due to the use of color for everything (even source code) and a lot of pictures, it fits the need of most of the developers better.

 

 

 It’s funny how after reading the same kind of criticism on Jeff’s blog (Petzold’s book is dry, we want more screenshots and color), the only thing Charles was able to mutter (at first) was that:

Apparently the battle for the future of written communication is over. Prose is dead. PowerPoint has won.

What a knee-jerk reaction! I definitely never expected this from an accomplished author.

There is no argument here as to whether the content is more important than form. What people as saying is that you can’t have UI book without a single screenshot!

Finally, my overall recommendation still is: if WPF is central to your future work, buy all of the books you can get your hands on, assuming the book got good reviews on the blogs of people whose opinion you respect. Commenting on Charles’ reaction above, Don Box said:

If a given technology is central to what I’m building, I’ll buy many books on the topic based on the principle that I will opportunistically glean value from them at some point.

I couldn't have said it better myself.

Essential Windows Presentation Foundation (WPF) (Microsoft .NET Development Series)Oh and by the way, Chris Anderson’s WPF book is out (he is one of the architects on the WPF team).

 

 

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
27.
2007

You’ve read about this many times – hobbyists, beginners and accidental developers prefer Visual Basic over other languages. I don’t disagree in principle but would like to point out why.

Historically, VB was the only environment that offered easy GUI development. Beginners don’t like console applications, they want forms and buttons. Thus it’s not the language they are gravitating toward, it’s the IDE.

That said, beginners also don’t like strict rules. They don’t want to strictly type the variables nor to even declare them at all. VB allowed all that, but so did Python and Ruby. Yet they did not have a fancy IDE with drag-and-drop GUI creation.

Don’t forget the horde of hobbyists who used to program in BASIC (all capitals) in the old days of 8–bit and 16–bit computers; Visual Basic is a BASIC after all, isn’t it?

Visual Basic has been and still is quite a chatty language. For beginners this is great – you don’t need to overcome a steep learning curve as the code is immediately readable (code is read many times more than it is written). Since you’re not gonna write a ton of it you never get tired of long lines and lots of words. Compare this to the cryptic curly braces used in C++/Java/C#, semicolons everywhere etc.

This deliberate toning down of VB continues to this day. For those who wish to do “real” programming with VB.NET (the only supported descendant of the VB languages branch on Windows platform) this hand holding can become quite a nuisance. Recently I was trying to explain the fundamental advantages of the generics to my wife (she’s trying to get Microsoft certified and is using VB.NET). I made sure that the relaxed settings that allow you not to declare the variables were all turned off. But the following code snippet compiled without warnings (!):

Dim ls As New List(Of String)
Dim li As New List(Of Integer)
ls.Add(1) ' should not work
li.Add("2") ' should not work

How is this possible? This is a classic example of the kind of type safety that usage of generics offer. What does this code snippet produce? Let’s have a look at the real truth(TM) in the shape of IL decompiled source using the most excellent Reflector:

Dim ls As New List(Of String)
Dim li As New List(Of Integer)
ls.Add(Conversions.ToString(1))
li.Add(Conversions.ToInteger("2"))

The compiler worked really hard to help you ignore the types and convert the values as needed. By chance, this will not fail at runtime because "2" is convertible to Integer. I’m not sure if a developer should consider this helpful or not. After all, what is a hobbyist doing using generic collections?

Finally, why did this compile? Because the settings for “compiler relaxness” exist both globally (for all projects) and locally (for each project). Turned out the project was opened from Microsoft provided demo CD and the settings were relaxed on the project level.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
25.
2007

I stumbled upon something that looked so unbelievable that I simply had to try it. Suppose you want to build a browser based application, rich in functionality. These types of apps are increasingly often now called RIA. If it’s going to be .NET based, you’d probably want to make it WPF based (XBAP). Silverlight is a possibility too but let’s say that because there’s no way of having full CLR available you disregard it.

Since the app is already .NET 3.0 because of the WPF, why not use WCF for the network connectivity? Well, there is one problem you can’t overcome – WCF does not run in a partial trust scenario (at least not in the .NET 3.0, 3.5 should partially resolve the issue).

Let’s say that you’d rather use WCF and thus you give up on the XBAP and decide to go with the full blown WPF app, ClickOnce installed.

WCFDualHTTPBindingSampleWhat you want to have is a simple stocks service - the server will fire the notifications when the price of a particular stock changes and the client will display it somehow, in a table or maybe as a fancy chart. The screenshot to the left shows two WinForms based applications (prototype obviously, real app will use WPF on the client), service and the client that communicate through WCF.

You need a two way channel – subscribe for updates to the server and then later on receive notifications from the server. Because you don’t want to have problems with the firewalls and such, you decide to pick one of the bindings with HTTP based transport. What do you know, there’s one binding in WCF that perfectly describes your needs – it’s called wsDualHttpBinding.

The app works as the screenshot shows, and it’s literally a couple of lines of code. It’s really easy to add transport and/or message security, transactions and whatnot, so what’s the problem?

The problem is the way that wsDualHttpBinding is designed. To support two-way communication, two HTTP connections (so two TCP connections) are used. The problem is that the second one, used to send messages from server to the client, is actually initiated from the server. Why is this a problem? Because client needs to be able to listen on a port, thus you need to have this port open on the firewall!

This makes no sense because one of the primary reasons you chose HTTP based transport is to avoid issues with the firewall. If I did not care about firewalls, I would have chosen TCP based transport like netTcpBinding which also gives me the benefit of using single TCP/IP connection for two-way communication. In fact, if the client had a simple one-way firewall protecting only incoming and not outgoing traffic (Windows XP firewall works like this as do many of the home routers/wireless access points) this would work even better – no need to touch the firewall!

But wait, why does wsDualHttpBinding require two TCP/IP connections? HTTP as a protocol is one-way, but it’s higher level than the TCP/IP, and it certainly was possible to use single TCP/IP connection for a two-way HTTP communication. I can only guess that time and/or resource constraints cut this feature out. Unfortunately, there’s no mention of rectification of this problem in the “Orcas” release.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
15.
2007

…if you live in France and are predicting the movie(s) that will be shown on a TV a couple of months in advance.

To understand this, you need to realize one very strong trend: production studios are churning movie sequel after sequel. Let’s have a look at the pipeline for the coming couple of months:

  • Spider-Man 3
  • Die Hard 4 (Live Free or Die Hard)
  • Pirates Of The Caribbean 3 (At World’s End)
  • Fantastic Four 2 (Rise of the Silver Surfer)
  • Ocean’s 11 3 (Ocean’s 13)
  • Harry Potter 5 (and the Order of the Phoenix)
  • Bourne’s Identity 3 (Bourne’s Supremacy)
  • 28 Weeks Later (28 Days Later 2)

It’s not hard to realize why: there’s almost no (financial) risk in shooting a sequel to a successful movie.

So, what does this have to do with French TV? Well, we all know how forgetful consumers can get. In order to refresh their memory on how awesome the Spider-Man is, just a few weeks before the next in the series (Spider-Man 3) hits the theaters, the good souls on TF1 (Télévision Française 1) are showing Spider-Man 1 today (ce soir, 20:50).

And if it’s not too expensive, we’ll most likely see Spider-Man 2 next week. Then Pirates of the Caribbean 1 in mid-May (the second one is probably too expensive to license as it’s a mere year since it’s been in the theaters). And then Die Hard 1 & 2 around middle June.

See? It’s easy. Find the premiere date, offset it by about a week or two and you can predict which movie will be shown on a French TV. Cool, huh?

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
12.
2007

If you haven’t seen the movie 300 you must have at least heard about it. It is violent, stylish and cool, full of special effects. It’s an adaption of Frank Miller’s comic, just like the most excellent Sin City.

Personally, I really liked the movie. At the very end, during one particularly sad scene, I noticed a familiar theme – at the time, I thought it was traditional Serbian folk song and even said so to my South African friend who I went to the cinema with.

Later on I realized that it wasn’t Serbian, but Macedonian song called “Zajdi, zajdi jasno sonce”. Macedonia is an ex-Yugoslavia republic that still cannot use the name Macedonia because of the name dispute with Greece. Having all this in mind, it is actually fitting that this song plays a role in a movie about ancient Greece.

But there’s an ugly side to all this: Tyler Bates, the composer of the soundtrack for the movie claims that the song in the movie is his own work, even after being confronted directly by a Macedonian portal, details on the Wikipedia.

Unless you’re tone deaf, at least in my mind there’s no question about it – he is lying. This is clearly a copyright violation because he used the song without any kind of attribution. Apparently, this is not the only controversial theme by this author, see the full story on Wikipedia (authors’ name is linked to an article about him).

I really don’t get it – did Tyler really thought he is going to get away with this? That nobody will recognize the songs in question? Today’s world is quite unlike yesterday’s world – everybody’s connected through this thing we call the Internet, and it’s really easy to report a copyright violation of this kind.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
11.
2007

The next version of Visual Studio “Orcas” and the .NET Framework brings a few changes to the BCL too, not just fancy WPF editors and such.

While implementing encryption support for my BitTorrent based product I noticed how the BCL lacks a few classes that I’d expect to be there, considering how good in general is support for encryption. The examples include at least some kind of Diffie-Hellman key exchange, RC4 (despite its shortcomings) and most notably BigInteger  – infinite precision integer class (which is already implemented in J# as well as in IronPython). I also noticed how managed AES implementation was unexpectedly slow compared to the test wrapper I built for the native implementation already present in the Windows API (XP and later, Windows Server 2003 and later).

I’m glad to report that all of these (sans RC4 support, but that’s not a problem as the algorithm is trivial to implement) are fixed/introduced in the next version of the .NET Framework.

The simplest improvement to use is to replace managed AES encryption with an unmanaged one. The benefits are huge, as I’ll demonstrate with the following short application. I am still puzzled as to why is managed implementation so much slower and can only guess that it’s because managed implementation allows for variability in block size while unmanaged doesn’t. Have a look at this short code snippet (requires March CTP of “Orcas” or newer):

namespace CryptoTest
{
  class Program
  {
    const int BLOCK_SIZE = 128;
    const int KEY_SIZE = 256;
    const int DATA_SIZE = 1024 * 1024 * 32;

    static void Main(string[] args)
    {
      RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
      byte[] iv = new byte[BLOCK_SIZE/8];
      rng.GetNonZeroBytes(iv);
      byte[] key = new byte[KEY_SIZE/8];
      rng.GetNonZeroBytes(key);

      ICryptoTransform encryptorManaged = GetEncryptor(iv, key,
new RijndaelManaged()); ICryptoTransform encryptorUnmanaged = GetEncryptor(iv, key,
new AesCryptoServiceProvider()); byte[] data = new byte[DATA_SIZE]; rng.GetBytes(data); Measure(data, encryptorManaged, true); Measure(data, encryptorUnmanaged, false); Console.ReadKey(); } private static void Measure(byte[] data, ICryptoTransform transform,
bool isManaged) { Stopwatch sw = new Stopwatch(); sw.Start(); Encrypt(data, transform); sw.Stop(); Console.WriteLine("Encrypting {0}MB took {1} ms with the {2} transform", DATA_SIZE / (1024 * 1024), sw.ElapsedMilliseconds,
isManaged ? "managed" : "unmanaged"); } private static void Encrypt(byte[] data, ICryptoTransform transform) { const int CHUNK = 1024; byte[] throwAway = new byte[CHUNK]; for (int i = 0; i < data.Length; i += CHUNK) transform.TransformBlock(data, i, CHUNK, throwAway, 0); } private static ICryptoTransform GetEncryptor(byte[] iv, byte[] key,
SymmetricAlgorithm sa) { sa.BlockSize = BLOCK_SIZE; sa.Mode = CipherMode.CBC; sa.KeySize = KEY_SIZE; sa.Key = key; sa.IV = iv; sa.Padding = PaddingMode.Zeros; return sa.CreateEncryptor(); } } }

The test consists of encrypting 32MB of random data. Both encryptors are initialized with exactly the same initialization vector (IV), key, mode, padding and block size. As you can see, since both RijndaelManaged and AesCryptoServiceProvider derive from SymmetricAlgorithm, the latter is a drop-in replacement for the former.

The results are clear – on average, the unmanaged implementation is between 2.1 and 2.4 times  faster than the unmanaged one! This is really important if you have a lot of data to encrypt/decrypt.

“Orcas” is shaping up to be a fine release indeed.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
4 Comments
Apr
10.
2007

We haven’t even started adopting .NET 3.0 but Microsoft is at work and plans to ship the next Visual Studio and the .NET platform (most likely to be called 3.5) by the end of this year!*

The most significant addition to the languages this time is LINQ. It is a very cool technology that mixes concepts from my two favorite paradigms – object oriented and functional.

The syntax looks a lot like SQL and will be used a lot in this context but LINQ is not just for the data stored in the database, it is for any structured data.

One of the features introduced with LINQ is the var keyword which helps with declarations of complicated, nested generic types. If you use var, you don’t have to spell the type of the left hand side of the assignment, which is a great help (an example will follow shortly).

Some seem to think that this reduces type safety somehow. This is not true – var is just a syntactic sugar, it does not change the semantics of the language in any way. The example should make things clearer (tested with Orcas March 2007 CTP):

namespace LinqPlayground
{
  class Data
  {
    private String _name;

    public string Name
    {
      get { return _name; }
      set { _name = value; }
    }
    private int _id;

    public int Id
    {
      get { return _id; }
      set { _id = value; }
    }

  }

  class Program
  {
    static void Main(string[] args)
    {
      List<data> data = new List<data> { new Data() { Name = "John", Id = 1 },
                    new Data() { Name = "Steven", Id = 2 },
                    new Data() { Name= "Scott", Id = 3}};
      var dt = from d in data
               where d.Name == "John"
               select d.Id;
      foreach (int i in dt)
        Console.WriteLine("Id is {0}", i);
    }
  }
}

There is a “dumb” class Data that keeps some simple info about a person like name and id. I stuff 3 objects in a list, then select only the persons named “John”. It does look a lot like SQL, but it really isn’t (I won’t go into details in this post).

The interesting part is the emphasized line – note how I’m not specifying the type of the result of the query “from d in data…”. That’s because compiler can infer it for me, but in compile time, not in runtime.

I could have also written this line like this:

IEnumerable<int> dt = from d in data
               where d.Name == "John"
               select d.Id;

but not like this

IEnumerable<string> dt = from d in data
               where d.Name == "John"
               select d.Id;

as this gives you the compile time error: CS0266: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<int>' to 'System.Collections.Generic.IEnumerable<string>'. An explicit conversion exists (are you missing a cast?)

Don’t treat the var keyword as a hack – it simply helps you type (pun intended) less  but the types of the variables are still there.

*The release date of the (tentative name) Visual Studio 2007 is only a rumour at this point, I don’t have any inside info whatsoever.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
6.
2007

Cool Vista feature

Posted by: Drazen Dotlic in Categories: .NET (C#) | general.
Tags:

I know that many don’t seem to appreciate Vista, but I like it. It does bring a few fundamentally revolutionary concepts (at least for Windows) like 3D composited desktop and is in general simply a newer better Windows.

The cool thing I’d like to mention today is one of those small things that make your life easier. Nothing earth shattering, but nice nevertheless.

If an app is running on a different desktop than the logged in user, it should not display any kind of dialogs or message boxes. The reason is simple – you can’ see them! The whole point of a message box is to inform the interactive user about something.

If Vista notices that an app did in fact do this, it notifies you and asks you if you’d like to see the message. In my case, avast! had problems downloading the updates and for some reason wanted to let me know, but on a different desktop. Vista kindly switched me to the other desktop so I can read and dismiss the dialog/message box. I’m not sure if the dialog was modal, but if it was and I wasn’t able to see (and dismiss) it, the app would have stayed stuck forever.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments
Apr
2.
2007

I guess you’ve noticed how (especially original) the music for the movies never gets the respect proportionally to its effect. All you hear about is the director, the actors and sometimes special effects, but there’s not much about the composer or the previously written songs that have been used for the movie (or the episode for the TV series). This is a shame because sometimes without the music the scenes wouldn’t be even the half as effective as they are with the music.

One of the greatest examples of masterful synergy between the picture and the sound has been a scene in the most excellent 28 Days Later. Almost at the very end, the situation in the soldier’s house intensifies and the theme, almost 5 minutes long, almost perfectly follows the events on the screen. The theme is called “In The House – In A Heartbeat”, written by John Murphy who wrote most of the music for this film. If you’ve seen the movie you’ll know what I am talking about, and if not, go see it (or, get it on a DVD or over the VOD), it is brilliant.

Well, I am happy to report that another scene, this time from the season 3 finale of the Battlestar Galactica has now taken the crown and is the best picture/sound combo of all time. It’s the last 5 minutes or so of the last episode of the season 3. The original take on Dylan’s “All Along The Watchtower” is absolutely mesmerizing and the events it follows are spectacular.

I find “Battlestar Galactica” the finest TV series showing at the moment, so if you have to choose and watch only one series I’d pick this one.

Finally, to partially justify the subtitle of this blog – on computing, women and beer – I’d like to point you to Maxim’s site (which is SFW) where you’ll find a great pictorial of the Tricia Helfer, also known as the Number Six Cylon. You might have noticed her, she’s a beautiful skinny blond that seduced Baltar

She doesn’t just look great but she can act too. She appeared recently in another TV series called Supernatural, in an episode Roadkill.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
0 Comments