September 2007 - Posts

SVNBridge: getting your codeplex bits with tortoise
Sun, Sep 30 2007 23:41

SVNBridge is a Codeplex project which allows you to use TortoiseSVN (or other Subversion clients) with Team Foundation Server. Even though it's still in early alpha, I've been using it for the last days. It still crushes a lot, but currently I can't simply live without TortoiseSVN :)

Btw, there's good post by Scott Hanselman that shows the steps you need to take in order to use this tool. Just one more note: Scott uses tfs03 server in his tutorial, but this might not be the server you're interested in. For instance, if I'm not mistaken, the AJAX Control Toolkit is on the tfs01 server.

by luisabreu | with no comments
Filed under:
Page flow with Page modules
Sat, Sep 29 2007 12:40

A few days ago, my fried Paulo presented the concept of Page modules. Today I've just noticed that Paulo has already released a new post where he replaces the default modules that are used on the Page Flow Quick Start (Page Flow  Application Block) with page modules. He even measured the response time of the app in both cases and presents it in a nice table placed at the end of the article. Good work Paulo!

by luisabreu | 1 comment(s)
Filed under:
IIS: the process cannot access the file because it's being used by another process
Sat, Sep 29 2007 12:29

This is what happens when you install Skype on a machine that also has IIS. Fortunately, this has happen to others and you can find an explanation of what's happening here:

http://blogs.developerfusion.com/blogs/paulfp/archive/2007/04/16/2633.aspx

by luisabreu | with no comments
Filed under:
Configuring IIS for hosting Silverlight 1.1
Fri, Sep 28 2007 19:41

From time to time there's always a new post asking on how to configure IIS to host Silverlight content. I've already written something about it, but I'd like to point you to a more complete reference which can be found here:

http://silverlight.net/forums/t/479.aspx

by luisabreu | with no comments
Filed under:
Book review: Windows Developer Power Tools
Thu, Sep 27 2007 21:30

[Disclaimer: I've received a free copy of this book for review, but I can assure you that this did not affect my review in any way]

I've just finished reading this huge book that presents several tools that will definitely make your life as a developer a lot easier. It's really a huge book with more than 1000 pages! Inside, you'll find several brief tutorials on several tools, most of them free. So, if you're looking for a reference with several tools and short tutorials, this is the book you should buy. As you'd expect, the books doesn't talk about any tool in-depth: its main objective is to present you the tools so that you can start using them quickly.

Even though I've enjoyed reading the book, there is one issue that I'd like to mention: some of the contents are outdated. For instance, ASP.NET AJAX is still called ATLAS and the book's site doesn't have an errata (maybe I've just missed it?).This is why I'm giving it a 7/10 (instead of an 8) for its content.

by luisabreu | with no comments
Filed under:
More info on the history of the name C#
Wed, Sep 26 2007 10:42

Some time ago I wrote a post about the history of the name of the C# language. As always, I should have asked about it to Paulo. Fortunately, he read my post and got an answer to it here.

by luisabreu | with no comments
Filed under:
The new ListView control
Tue, Sep 25 2007 23:10

A few days ago I've said I was starting to play with the new controls introduced by .NET 3.5. One of those controls is the new ListView control. There already several good articles on this control. For instance, both Scott Guthrie and Rick Strahl have written about it (Rick also describes how to use the grouping functionality). One of the things that got me lost was the grouping functionality. Like Rick, I've tried several things to make it work with data grouping without any success. So I've asked those "that know" (thanks guys) and it seems like the purpose of the grouping feature is to let you easilly build groups:

A | B | C
D | E | F

...

When you think about it, there really wasn't an easy way to achieve something like this in the past...If you're looking to get grouping based on data, then you'll have to use the old tricks based on nesting a data bound control inside another bound control.

by luisabreu | with no comments
Filed under:
Silverlight pages and VS integration
Tue, Sep 25 2007 23:01

Have you noticed that you can navigate from the "code-behind" file (cs file) to the designer by right clicking the page and choosing "View designer" (from the context menu that is shown when you perform right click), but there's isn't any option for going from the xaml page to the cs code file associated with it? am I blind?

by luisabreu | with no comments
Filed under:
How to share code between Silverlight and other kinds of applications?
Tue, Sep 25 2007 21:47

I really haven't looked at any Silverlight code for at least 2 months. In fact, I haven't really been around the forums until today. Now that I've returned :), I've noticed that there's a lot of similar questions around sharing code between .NET and the "mini-CLR" that is used Silverlight.

The first thing you should notice is that you cannot pass .NET components to Silverlight methods! Don't even try this :) Even though I haven't looked at it for more than 2 months I'm almost positivethat you cannot even interop with ActiveX controls without going through JS code!

What you can do is "share" code so that you can build a class and then use that class from your Silverlight code and from other .NET code. Don't worry: this is a short post :) Instead of giving you several pieces of advice, I'll just redirect you to a great article by Daniel Moth:

Write code once for both mobile and desktop apps

Don't let the title fool you! Even though Daniel has written it thinking about mobile apps, the concepts do apply to code that needs to be shared by SL and other kind of .NET apps. Btw, if you're not subscribed to Daniel's most excellent blog, then here's the RSS feed for it. There are really lots of cool posts over there!

by luisabreu | with no comments
Filed under:
C#: Signaling state changes through events
Tue, Sep 25 2007 0:19

[Update: Paulo was not impressed with this post but he didn't want to point it out in the comments. Next time, don't be shy :) He thinks I should drop the old sytax and write thread-safe code. As always, he's right. Let's be clear: if you're creating a new EventHandler event type, just use the generic EventHandler<T> type. You'll write less and achieve the same thing. Another thing: if you're writing multithreaded apps - for instance, Windows Forms apps - then don't forget to change the code for add/remove and even the code used for raising the event so that it's thread safe. There are already several good articles on how to achieve thread safety, so I'll just redirect you to them.]

The CLR's event model is based on delegates (this post presents the main features of delegates). Period. So, this may be a good time to refresh your knowledged on how delegates work.

Most types defined by the famework use events to communicate state changes to anyone that might be interested in being notified about that kind of operations. Generally, exposing an event implies that:

  1. you've defined a new type that is used to pass aditional information to the objects receiving the event notification. By convention, this type is a class that extends the EventArgs class;
  2. Build a new delegate that follows the pattern void Delegate_Name( object sender, Your_event_args_derived_type e)
  3. Add a member that exposes the event to the outside world

You should also keep in mind that the event pattern introduced by .NET recommends that your class defines a protected virtual method that is responsible for raising the event. By doing this, you can override that method in a derived class and perform some actions without incurring in the (small) performance hit associated with handling the event (this is a technique that is commonly used when handling ASP.NET page events on the page itself - ie, on the code behind file). Lets look at a simple example which generates an event when the age of a person changes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Livro
{
    public class AgeChangedEventArgs:EventArgs
    {
        internal AgeChangedEventArgs(int _age)
        {
            this._age = _age;
        }

        private Int32 _age;

        public int Age
        {
            get { return _age; }
        }
    }

    public delegate void AgeChangedEventHandler(object sender, AgeChangedEventArgs e);

    public class Person
    {
        private Int32 _age;

        public Int32 Age
        {
            get
            {
                return _age;
            }
            set
            {
                if( _age == value)
                {
                    return;
                }

                _age = value;
                OnAgeChanged(new AgeChangedEventArgs(_age));
            }
        }

        protected virtual void OnAgeChanged(AgeChangedEventArgs e)
        {
             if( AgeChanged != null )
             {
                 AgeChanged(this, e);
             }
        }

        public event AgeChangedEventHandler AgeChanged;
    }
    class Start
    {
        public static void Main()
        {
            Person p = new Person();
            p.AgeChanged += PrintAge;
            p.Age = 20;
        }

        public static void PrintAge(object sender, AgeChangedEventArgs e)
        {
            Console.WriteLine(e.Age);
        }
    }
}

As you can see, I start by defining a new EventArgs derived class, which is used to pass the new age to the interesting parties (btw, do notice that this might not be necessary since the object parameter always contains a reference to the Person object that raised the event). Then, a new delegate is defined. The delegate is important because it'll define the signature of the methods that can handle the event that will be fired by the  class.

Adding the event member is simple: we just need to use the event keyword and choose the delegate we want to "associate" with the event.

As a side note, we could have dismissed the delegate declaration and have used the EventHandler type for setting up the type of the event. This would be a better option for your production code, but i'm a sucker for history and so I've decided to do things "a la .NET 1.1" :)

As you can see from the previous code, setting up a method to handle the event is really similar to what happened with delegates. Events usage is really simple; what's interesting (as always!) are their internals. We'll use the astonishing .NET Reflector tool (probably the best .NET free tool that you should keep in your toolbox) to see what's going on. we'll start by looking at what happens when we use the event keyword (I'll only copy the important bits from the Person class):

.field private class Livro.AgeChangedEventHandler AgeChanged
.event Livro.AgeChangedEventHandler AgeChanged
{
        .addon instance void Livro.Person::add_AgeChanged(class Livro.AgeChangedEventHandler)
        .removeon instance void Livro.Person::remove_AgeChanged(class Livro.AgeChangedEventHandler)
}

If you dig a little deeped (by selecting the event on the tree), you'll see that the add_AgeChangedEventHandler looks like this:

.method public hidebysig specialname instance void add_AgeChanged(class Livro.AgeChangedEventHandler 'value') cil managed synchronized
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: ldarg.0
    L_0002: ldfld class Livro.AgeChangedEventHandler Livro.Person::AgeChanged
    L_0007: ldarg.1
    L_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate)
    L_000d: castclass Livro.AgeChangedEventHandler
    L_0012: stfld class Livro.AgeChangedEventHandler Livro.Person::AgeChanged
    L_0017: ret
}

As you can see, the compiler will add a field of type AgeChangedEventHandler and the event will be transformed on a "special property" which delegates to the add_/remove_ methods added by the compiler. At the end of the day, you'll end up calling Combine when you use the += syntax to set up method to handle an event.

If you're worried about synchronization issues, don't be: the add_/remove_ methods are annotated with the synchronized attribute, which means that they're thread safe (at least in theory, since the I think things aren't really that safe when you're using static methods - but that's a topic for another post, right? :)).

Now it's the perfect time to say that, unlike what happens with several other features supported by the C# compiler (ex.: enum declarations), you can define your own "event properties" (ie, event declarations can be "customized"). Here's a quick example (only the important parts are listed here - note that this code is not thread safe!):

private AgeChangedEventHandler _ageChanged;
public  event AgeChangedEventHandler AgeChanged
{
    add
    {
        _ageChanged += value;
    }
    remove
    {
        _ageChanged -= value;
    }
}

protected virtual void OnAgeChanged(AgeChangedEventArgs e)
{
  if( _ageChanged != null )
  {
        _ageChanged(this, e);
  }
}

By now, you must surelly be worried, right? no? then think about the size of your class if you need to expose several events...not a pretty sight, right? for instance, if you think about windows forms or ASP.NET controls, it's easy to see that they surelly must be bloated, right? WRONG!

If you look at an event that is raised by one of those controls, you'll see that they use the Events property introduced by the Control base class (and this happens in windows forms and in ASP.NET applications) to save/get the delegates associated to the events. This property can be seen as a dictionary which is used to store the method that is going to handle the event. So, if you had several events on your class, you should change the previous example so that it looks like this:

protected virtual void OnAgeChanged(AgeChangedEventArgs e)
{
    AgeChangedEventHandler handler = (AgeChangedEventHandler) Events[_ageChangedKey];
  if( handler != null )
  {
        handler(this, e);
  }
}

private EventHandlerList _events;
protected EventHandlerList Events
{
    get
    {
        if(_events == null )
        {
            _events = new EventHandlerList();
        }
        return _events;
    }
}

private static object _ageChangedKey = new object();
public  event AgeChangedEventHandler AgeChanged
{
    add
    {
        Events.AddHandler(_ageChangedKey, value);
    }
    remove
    {
        Events.RemoveHandler(_ageChangedKey, value);
    }
}

Some important notes on the previous snippet:

  • you should define a key that uniquely identifies your event in the hastable maintained by the EventHandlerList
  • You no longer have one field per event with this strategy. This means that you're not wasting space with unused events
  • The code is not thread safe. nor is the EventHandlerList class. So, if this is important to you, don't forget to drop a few locks on your code (but please, please do pay attention to what and how you lock).
What can we find in the next version of ASP.NET
Fri, Sep 21 2007 15:08

I've finally started looking at the next version of the ASP.NET 3.5 platform. I've already seen that there are some new controls there, but in this post I'd like to reference one or two things that look promising and that are related with stuff that didn't work in the previous versions. First, a word about validation: it seems like you don't really need the extra download anymore if you're building ajax sites. the validators were updated and work correctly with the UpdatePanel control (at least, my old tests that used to break in this scenario run without any problems). If I recall correctly, the team said that the windows update would automatically update the existing code, but to be honest, I never cheched it again (yes, in the last months I haven't really been working with ASP.NET or AJAX).

There are also good news for web parts: on the 3.5 platform, you can do everything by using partial postbacks, ie, you no longer need to have a full postback if, for example,  you're changing the position of a web part to a different zone.The only thing you should keep in mind is  that you need to put everything inside the same UpdatePanel! Oh, and I didn't make it work in Firefox, but i might be missing something...

by luisabreu | with no comments
Filed under:
Still on NHibernate...
Fri, Sep 21 2007 12:13

Yesterday I was complaining about the way NHibernate persists entities that contain collection of components. After some discussions on the Forums, Karl suggested that I should call session.Flush after calling the Save(OrUpdate) method to force the generation of the collection of components maintained in the collection. This means that something along these lines should work:

  • Open a session
  • Begin transaction
  • Insert into db by calling the Save(OrUpdate) method
  • Flush the session by calling session.Flush
  • //perform other work here
  • Rollback or commit the transaction

Notice that I no longer call session.Flush after ending the transaction...After trying this approach, I can confirm that it does work. However, I still think that this is not intuitive and it really shouldn't work like this. When I persist an entity, I'm expecting that all of its depend objects are persisted too (persisted here means that the necessary insert commands are automatically generated and executed over the existing transaction). For instance, if I had to write SQL code to perform this operation, I'd do something like this:

  • start transaction
  • insert into main table
  • insert into secondary table (ie, insert the components)
  • //perform other work here (ie, write some code that tests the insertion)
  • rollback the transaction

I guess that the main problem here is that NHibernate has its own way of persisting entities to the database and, most of the time, everything works out as expected. Unfortunately, that is not the case when an entity has a collection of components. And even though I really don't know much about NHibernate, I really can't see how the default behavior is the correct one in this kind of scenarios...

by luisabreu | 7 comment(s)
Filed under:
Any NHibernate experts out there?
Thu, Sep 20 2007 15:04

I've started looking at NHibernate and I must say that I'm impressed with several of its features. However, I've reached a point where something isn't quite right. I'm not sure if it's me (which is probably the case) or if it's a limitation/bug of NHibernate. Since I'm really a beginner, I thought I should write a quick post that explains what's going on. Maybe someone that reads this might help me :).

It's really a simple scenario: there's an entity which has a collection of components and I expected that calling the Save method over an instance of that entity would also be cascaded to the components maintained by that object.

Instead of describing everything here, I'll just point to a post I've written in the NHibernate forums (it has all the info on what's happening). If anyone is interested in having a go, then please download the code I've attached to this bug entry (it has the necessary SQL to create the tables so getting a repro environment should really be easy).

by luisabreu | 3 comment(s)
Filed under:
Dave again: the Renderer control
Wed, Sep 19 2007 23:07

Dave Reed keeps surprising me everyday, Another great control with so few lines of code. I'll keep referencing just in case i get a new reader which hasn't added his cool blog to his RSS feed (if you're not new here and still haven't subscribed, what are you wainting for?)

by luisabreu | with no comments
Filed under:
Inline scripts inside UpdatePanels
Tue, Sep 18 2007 23:31

Dave Reed has another great post that shows how to build a simple control that lets you put your script inside an UpdatePanel.

by luisabreu | with no comments
Filed under: ,
ASP.NET page modules
Mon, Sep 17 2007 23:27

My good friend Paulo has a cool article on what he calls "Page Modules". "Page Modules" can be seen as a small framework that will let you be notified about all the events of the page life time, even in those scenarios where you're using Server.Transfer. Check it out here.

by luisabreu | with no comments
Filed under:
Properties on C#
Mon, Sep 17 2007 23:23

Properties are strange beasts...in fact, when you access a property, you're really calling a method. Let's start with a simple example that shows a "parameterless property":

public class Person
{
    public String Name;
    private String _address;

    public String Address
    {
        get { return _address; }
        set { _address = value; }
    }
}

The Person class has two fields: Name and _address with different access modifiers applied to them. What this means is that you can access the Name field directly, but you must go through the Address property if you want to get or set the value of the _address field. Here's some code that shows how you can use the field and the method from C# code:

Person p = new Person();
p.Name = "Luis";
p.Address = "Funchal, Madeira";

When you compare both approaches, they really do look similar. However, when you're setting the address, you're really calling a method, as the following IL for the last line of the previous code shows:

L_0013: ldstr "Funchal, Madeira"
L_0018: callvirt instance void Livro.Person::set_Address(string)

If you're thinking "where does the set_Address method comes from?" then the answer is simple: the C# compiler generates 2 methods by prefixing the property name with get_/set_ prefixes. Here's the IL code for the Address property:

.property instance string Address
{
    .get instance string Livro.Person::get_Address()
    .set instance void Livro.Person::set_Address(string)
}

The previous snippet also shows an interesting thing: the C# compiler groups the get_Address and set_Address methods and annotates them with the .property instruction on the metadata of the class. This info is used by compilers and IDEs making you believe that you're using properties. However, the CLR does not use this info and will always call one of the methods you've defined (as you've seen in one of the previous snippets).

One interesting thing about properties (which most people don't know) is that you can have different access modifiers applied to the get and set methods. For instance, the following definition of the Address property makes the set method available only to types defined in the same assembly as the Person type (or in "external" types defined in an assembly that has been passed to the InternalsVisibleToAttribute):

public string Address
{
   get { return _address; }
   internal set { _address = value; }
}

As I've said, the type of property presented in the previous is know as "parameterless property" because you don't pass any properties to the get/set methods when you call them. C# will also let you define properties that let you pass parameters to its get/set methods. In C#, these properties are called indexers and they're exposed through an array-like syntax (you need to use the [] operator). Here's a quick example of how you can define and use this kind of property:

 public class CustomArray
{
    private Int32[] _arr = new Int32[10];

    public Int32 this[Int32 pos]
    {
        get
        {
            return _arr[pos];
        }
        set
        {
            _arr[pos] = value;
        }
    }
}

The next snippet shows how to use indexed property from C# code:

CustomArray ar = new CustomArray();
ar[0] = 10;
Console.WriteLine(ar[0]);

If you've been following along, then the IL generated by the C# compiler shouldn't really look weird:

.property instance int32 Item
{
    .get instance int32 Livro.CustomArray::get_Item(int32)
    .set instance void Livro.CustomArray::set_Item(int32, int32)
}

The main difference is that there's an aditional parameter passed to the get/set methods that are automatically generated by the compiler. There's one thing that might be bothering you: why aren't the IL methods named get_this and set_this? After all, you've used the reserved this term for the property name, right? I thought about this too and Richter's excellent CLR via C# book has the best explanation i've see on the subject. According to Jeffrey, the name's choice was necessary because you cannot name the indexed properties you build in C#. That's why all the classes that have an indexer have a property called Item. btw, you can change this default name by annotating the indexer with the IndexerNameAttribute attribute. One more thing: the this identifier was chosen so that you can only define indexers on instances of objects. Currently, C# does not offer you any chance of defining static indexers.

by now, you've already seen most of the important things you should know about properties. Properties are really important in some scenarios. For instance, if you need to perform some sort of validation when setting the value of a field, then using a property will let you do that without sacrificing the syntax you're already accustomed to. Another good example where properties are necessary is binding in Windows forms.

However, it's really important to always keep in mind that properties are really methods and that there are certain things you can do with fields but cannot do with them. For instance, you cannot pass a property as a ref or out parameter (Mike Stall has a good post on this subject). Another thing that might surprise you is that properties aren't "side-effect free". When you access a field, it will always return its content. If you don't change it, that means that you'll always get the same value. That might not be the case with properties. For instance, take a look at the following property:

public DateTime MyDate
{

   get { return DateTime.Now; } //the value of this property is never the same
}

Even though there are some people that say that porperties aren't really that good, I must say that I'm not against its use if you do keep in  mind that they're really methods...

by luisabreu | 2 comment(s)
Filed under:
John Robbins and a cool vista explorer trick
Fri, Sep 14 2007 23:46

Besides writing really cool books and articles on debugging, John Robbins has also written a post on how to improve the switching time of programs in windows vista.

by luisabreu | with no comments
Filed under:
Windows vista: finally someone agrees with me about the copy file dialog...
Fri, Sep 14 2007 23:31

I've been using Vista for some time now and i'm still not used to the new copy file dialog that is shown when you're copying a file to a place that already has a file with the same name. I was already starting to feel old and grumpy, but then Doug Stewart's post made me realize that i'm not alone...

by luisabreu | 1 comment(s)
Filed under:
Installing windows 2008 server
Thu, Sep 13 2007 8:58

After giving it some thought, I've decided to install windows 2008 on my development machine. After the 1st hour, where I had several problems with my NVidia Quadro4 which ended with its replacement by an old Matrox adapter(it simply didn't start after one of the automatic reboots), everything went on smoothly.

Now it's time to start seeing what's new. btw, MS is offering access to a free ebook about 2008 server. Check it out here.

by luisabreu | with no comments
Filed under:
More Posts Next page »