November 2009 - Posts

oh, gosh! SO many ways to require a script…
Mon, Nov 30 2009 20:45

I’d like to apologize for the lack of posts lately…no, I haven’t given up in my Silverlight series, but I’ve been busy updating my existing ASP.NET book to the 4.0 version. It seems like I will have a lot of work (much more than I had anticipated, but the truth is that I really enjoy writing about technical stuff) so the Silverlight series won’t really go as fast as the one on MS AJAX…sorry for that…now back to business :)

I really didn’t gave it any thoughts until I spoke with a friend who he asked me about the options we have for requiring a script (when using MS AJAX, of course!). So, lets see…we can specify it by:

  • using the scripts object : Sys.scripts.Core loads the basic MS AJAX JavaScript file
  • using the components object: Sys.components.dataView loads all the JavaScript files required for using the DataView component;
  • using the plugins object: Sys.plugins.bind will load all the JavaScript file required for using the bind method;
  • name: “History” will load all the scripts required for supporting the history feature.

All of them requires that you “define” your scripts in a JavaScript file which must be included in the page after the start.js file. And the best thing is that you can mix them all when using the Sys.required method. Fantastic, right?

Getting 503 errors on IIS 7 with custom application pool (Integrated Mode)?
Thu, Nov 26 2009 15:23

So today I’ve though about giving IIS’ integrated mode a shot…The idea was simple: create a new application pool, configure it to use ASP.NET 4.0 in integrated mode and then associated it to an existing web application. The problem: The first request would always kill the application pool and it returned a 503 error to the browser. IIS Manager seemed to confirm that the pool was really dead:

wrongversion

WTF? I’ve read a couple of posts on IIS 7 and 503, but none helped. Then I tried one more thing: I’ve configured the web app to use the default ASP.NET v4.0 application pool. And it worked…the mystery was solved when I looked carefully at the application pool list. Can you spot the problem? If you’re thinking that my custom livro application pool is using the wrong .NET version, you’re right! I don’t know how it happened, but it seems like all this beta stuff I’ve been adding to my machine removed the correct version of .NET from the .NET version dropdown (I only had v4.0 available from the dropdown list).

Running aspnet_iisreg from within the 4.0 framework folder made everything go back to normal. So, are you getting 503 in integrated mode? Don’t forget to check the .NET version used by the application pool…it might not exist and that means 503!

by luisabreu | 1 comment(s)
Filed under:
Changing the action attribute of an HtmlForm
Thu, Nov 26 2009 12:29

In these last days I’ve went back to ASP.NET world (server side) since I’m thinking in rewriting my ASP.NET book (which was written way back when ASP.NET 2.0 was released and which got a slight updated for .NET 3.5). One of the  things I’ve noticed is that now we can change the action attribute of a form and it sticks! According to my investigations, this behavior was changed with the release of .NET 3.5.

Now, you might be thinking on why you’d want to use this attribute…it’s specially cool when you’re using friendly urls (remember: in the past, we didn’t had any url routing engines). Suppose you’re using the old friendly urls introduced by ASP.NET 2.0:

<add url="~/Activities" mappedUrl="~/Activities.aspx"/>

Now, the problem with pre-3.5 releases was that you couldn’t set the Action property and you’d end up getting the Activites.aspx in your browser’s location box. There were some hacks, but….they were simply hacks…With the 3.5 behavior change, those hacks can finally go back into the garbage bin! hurray! :)

by luisabreu | with no comments
Filed under:
Reverting to Office 32 bits
Tue, Nov 24 2009 13:04

A few days ago I’ve installed Office 2010 beta 64 bits. Unfortunately, it simply destroyed sync with my HTC Windows Mobile phone. After a tip from Caio, I reverted back to 32 bits version and yes, it works!

Sorry Microsoft, sync between Outlook and my Windows Mobile Phone is really important to me. I can’t really use the 64 bits version like you asked if you can’t give me sync between Outlook and my mobile phone….

by luisabreu | 1 comment(s)
Filed under:
Asking feedback for ASP.NET book
Tue, Nov 24 2009 12:35

This is a post to my Portuguese readers (ie, for those guys and gals that have read my Portuguese books). I’m still preparing material for a possible ASP.NET 4.0 book and I would really appreciate some feedback on the previous editions (that is, if you read the book). What did you like? What didn’t you like? What would you like to see covered?

If you want, you can put your comments in Portuguese. Thanks for your help.

by luisabreu | 4 comment(s)
Filed under: ,
Some observations on MS AJAX and JQuery integration
Tue, Nov 24 2009 9:16

In my last post, I’ve talked a little bit about the new plugins introduced by the latest release of MS AJAX (beta, at the time of writing). One of the things that didn’t enjoy much was that I had to call the JQuery’s get method in order to get a reference to the DOM element array. What I was forgetting was that MS AJAX has really good integration with JQuery (something that Dave Ward was kind enough to reminded me).

In practice, this means that I can simply pass a string with the selector I want and I’ll automatically get the correct DOM element array. here’s the updated code:

<script type="text/javascript">
  Sys.require(
        [Sys.scripts.jQuery, Sys.scripts.ComponentModel],
        function () {
          $.addHandler(
                "input",
                "click",
                function (evt) {
                  alert("JQuery: " + evt.target.id);
                });
        }
    );  
  </script>

Notice that you can use more complex selectors too. All the selectors which can’t be interpreted by MS AJAX will be delegated to JQuery. As you can see, MS AJAX is becoming a really cool lib, don’t you think?

by luisabreu | with no comments
Filed under: ,
MS AJAX beta – new plugins
Mon, Nov 23 2009 14:47

The MS AJAX beta release adds some new plugins to the previous ones. Besides the existing setCommand and bind, we now have access to the following plugins:

  • addHander: you can use this plugin to set up a handler for one event fired by one or several DOM elements;
  • removeHandler: as you can probably guess from its name, you can use this to cancel an existing DOM event subscription;
  • addHandlers: similar to the addHandler. However, in this case you can hook up several events (instead of passing the name of the event, you’re supposed to use a literal JS object where you specify the events and corresponding handlers);
  • clearHandlers: used for cancelling all event subscriptions that have been previously setup;
  • activateElements: used for activating the indicated elements with a specific binding context. Generally, you get activation for free. However, there are a couple of times where  you may need to activate an element explicitly. In those cases, this is the quickest (and shortest – yes, I’m counting key strokes) way to do that.

I’m not sure if you recall it, but plugins get promoted to Sys helper methods. Take a look at the following code which shows how to use the addHandler plugin to hook up the click event over all the existing buttons:

<head runat="server">
 <script type="text/javascript" 
src="Scripts/MicrosoftAjax/Start.debug.js">
</
script> <script type="text/javascript"> Sys.require([Sys.scripts.ComponentModel], function () { var buttons = document.getElementsByTagName("input"); Sys.addHandler(buttons, "click", function (evt) { alert(evt.target.id); }); }); </script> </head> <body> <input type="button" id="bt1" value="Button 1" /> <input type="button" id="bt2" value="Button 2" /> <input type="button" id="bt3" value="Button 3" /> </body>

Whenever you click over a button, you should get an alert message with the ID of the button. Now, since we’re talking about handlers, here’s how you’d use the addHanders plugin:

Sys.addHandlers(Sys.get("#bt1"),
    {
        click: function (evt) {
            alert("bt-1");
        }
    }
    );     

As you can see, I’ve used a literal JS object for specifying the events I want to handle. You should only use this plugin when you want to pass several handlers to different events. Notice that both plugins (addHandler and addHandlers) expect a reference to one or more DOM elements (you can see how to pass several references in the first snippet; the second passes a single DOM element reference). That’s why you should only use the second (addHandlers) when you need to setup several events at once.

Here’s what you get when you click “Button 1” after adding the last snippet to the page:

addHandlers

Notice that if you add this last snippet to the previous page, you should see two alert messages because you’re effectively adding two handlers to “button 1” click event.

One of the nicest things about plugins is their integration with JQuery. For instance, take a look at the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <script type="text/javascript" 
src="Scripts/MicrosoftAjax/Start.debug.js"></script> <script type="text/javascript"> Sys.require(
[Sys.scripts.jQuery,Sys.scripts.ComponentModel],
function () { $.addHandler( $("input").get(), "click", function (evt) { alert("JQuery: " + evt.target.id); }); } ); </script> </head> <body> <input type="button" id="bt1" value="Button 1" /> <input type="button" id="bt2" value="Button 2" /> <input type="button" id="bt3" value="Button 3" /> </body> </html>

As you can see, I’ve started by requiring JQuery and the MS AJAX JavaScript files needed for using the addHandler method (oh, btw, I could have specified the dependency through the Sys.plugins.addHandler too). After getting all the files, my anonymous callback function will be called and that’s where everything interesting is happening.

There’s an addHandler method which got added to the jQuery object (aliased to the $) during JQuery loading. Notice that the addHandler plugin still expects the same arguments and that’s why we need to use the JQuery’s get method to get a reference to an array with all the DOM elements of the internal wrapped set.

This behavior is pretty cool and also works with other plugins. The only thing you should keep in mind is that non-behavior/control plugins always get added to the $ object; on the other hand, behaviors/controls get added to the $.fn object (and that means that these plugins are “transformed” into “instance” methods of the JQuery object – take a look at this post to see what I mean).

And that’s it'. Stay tuned for more on MS AJAX.

by luisabreu | with no comments
Filed under: ,
MS AJAX beta – ACT support
Mon, Nov 23 2009 13:35

In the last week, MS AJAX beta was released during PDC 2009. One of the things that this released added is ACT script loader support. If you go into the samples, you’ll see that there is an Extended folder which holds all the client files for the behaviors and controls exposed by the AjaxControlToolkit.

extended

The code files have all been updated so that its' definitions are wrapped into an execute function (which is also placed inside an anonymous function). As you probably recall from previous posts, this function is called when all the dependencies have been loaded. Notice that  with the previous CTP you could download the ACT from codeplex and make the changes present in all the files that come with this release. In other words, wrapping all the code within functions is the easiest part when you want to adapt an existing script so that it can be used with the new script loader component.

To me, the most important script file is the ExtendedControl Javascript file because it contains all the definitions (and dependencies) required by all the ACT controls. In practice, this means that you can simply drop this file on a page (plus the base start.js Javascript file) and use any of the ACT controls. Don’t believe me? Here’s some demo code which uses the calendar behavior:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <link rel="stylesheet" type="text/css" 
   href=
"Scripts/MicrosoftAjax/Extended/Calendar/Calendar.css" /> <script type="text/javascript" src="Scripts/MicrosoftAjax/Start.debug.js"></script> <script type="text/javascript" src="Scripts/MicrosoftAjax/Extended/ExtendedControls.debug.js"></script> <script type="text/javascript"> Sys.require([Sys.components.calendar], function () { Sys.create.calendar(Sys.get("#date")); }); </script> </head> <body> <input type="text" id="date" /> </body> </html>

And that’s it: I’ve just added two scripts and that’s all I needed to use the CalendarBehavior. Btw, here’s the results I got on my machine after loading the page:

calendar

Nice, right?

by luisabreu | with no comments
Filed under: ,
Markup extensions
Mon, Nov 23 2009 12:26

Markup extensions allows you to extend the expressibility of XAML. You use markup extensions to escape the general treatment that attribute values get (by default, we’ve seen that they are treated as strings or that a type converter is used to convert them to the adequate type). Markup extension expressions are always delimited by the pair { }.

Currently, the Silverlight’s XAML parser understands only four markup extensions:

  • Binding: used in data bound scenarios for getting the value of an object at run time. This extension is implemented by the Binding class and you can set several of its property from XAML (ie, from the markup extension expression itself). We’ll return to this class in future posts, when we talk about data binding operations;
  • StaticResource: used for setting the value of a property to a resource  already defined in a resource dictionary (resource dictionaries are used for saving objects by key and it can be used in both XAML and code). The current release of Silverlight does not have any managed code class for supporting this type of markup extension (in other words, this is implemented in unmanaged code);
  • TemplateBinding: another binding which is implemented in unmanaged code only. You’ll use this binding in your templates when you want to link the value of a control’s property to the value of another object’s property of the templated control (once again, this is only intro stuff and we’ll come back to this topic in future posts);
  • Null: used for setting the value of a property to null. You might find this markup extension odd at first, but the truth is that there’s no other way to set a property to null in XAML (don’t forget that passing string would probably result in using a type converter). Another interesting thing you should keep in mind is that not all properties have a default value of null (to understand this, we’ll need to go into dependency properties – and yes, that will be the topic of a future post).

If you’ve been doing some WPF development, you’ll probably be thinking that Silverlight is not as extensible as WPF. For starters, there is no MarkupExtension base class (which is extended by all markup extensions). In practice, this means that you cannot create your own markup extensions. Finally, you should also notice that unlike WPF, you can only use markup extensions with the attribute value syntax. Again, this is happening due to the limitations I’ve mentioned before (Silverlight must be small and we can’t forget that it runs across several platforms/browsers)

I guess that it’s time to see an example. We’ll get started with the StaticResource markup extension:

<Canvas>
    <Canvas.Resources>
        <SolidColorBrush x:Key="brush" Color="Green" />
    </Canvas.Resources>
    <Button Content="Say hi"
        Background="{StaticResource brush}" />
</Canvas>

In the previous snippet, I’ve started by creating a new Canvas resource brush and I’ve identified it with the name brush. This is all you need to be able to reuse that resource in all the Canvas’ children objects’ properties that expect a brush (in the previous example, I’ve used that resource to fill the background color of a button). Resource dictionary usage has some gotchas, but I’ll leave that for a future post (after all, the main objective of this post is to look at markup extensions).

StaticResource and Binding markup extensions expect only a single value. However, Binding is implemented through a managed class and if you check its definition, you’ll see that it has several properties which you can also set from XAML. In this case, the syntax is simple: you can specify a value for the “default” property (which is Path, in the case of the Binding markup extension) and you should indicate all the other properties through the key=value pair entries (separated by comma). For instance, here’s an example of how you can set a binding:

<TextBlock Text="{Binding Content, ElementName=origin}" />

In the previous snippet, I’m binding the value of the Text property to another element defined through XAML which is named origin (I guess it could be a button since it has  a Content property). There’s lot of things to say about bindings but for now I’m only worried in showing you how to use them from XAML (through the markup extension syntax).

Before ending up, there’s still time for one more topic: escaping the { } in attributes. By default, whenever you pass the pair { } to an attribute value, the XAML parser will interpret it as a markup extension. If you need to set the value of an attribute to a value which contains that { } pair, you’ll need to escape it. Here’s how:

<TextBlock Text="{}{Binding Content, ElementName=origin}" />

As you can see, using the {} pair at the beginning of the attribute’s value is all that it takes to escape the rest of the expression. If you put the previous XAML in a user control, you’ll see the {Binding….} text on the browser when you load that  control.

I’ve only been playing with Silverlight for a few days (and I really haven’t done any real work with it). Even though it has lots of potentials, I must confess that I’m a little disappointed with the gotchas I’ve already found. I guess that they won’t matter much if you’re using a tool like Blend for creating the interface, but I must say that all these little things which don’t always work as expected are starting to make me think that I should probably be working with WPF instead where everything makes sense and works as expected…

And that’s it for now. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under: ,
Book review: The back of the napkin
Sun, Nov 22 2009 15:43

This was one of the books I’ve read during my summer vacations. Dan Roam tries to show us how we can use visual thinking to solve problems. I found it interesting and enlightening, though I must confess that I still haven’t tested all of his ideas in my day-to-day work. Overall, I’m giving it 7.5/10.

by luisabreu | with no comments
Filed under:
MS AJAX Lib beta is out
Fri, Nov 20 2009 14:10

You can get it from here. I’m curious to see if it contains new features…

Reactive Extensions for .NET
Fri, Nov 20 2009 13:58

I’ve just noticed this post from the Parallel team. Now, this will be useful because it seems like it solves lots of the bugs introduced in the latest public CTP of the Parallel lib :)

by luisabreu | with no comments
Filed under:
XAML: what about events?
Thu, Nov 19 2009 12:54

A friend of mine asked me about events and XAML: can we setup event handlers in XAML? And the answer is, yes, you can. Here’s a quick example of how you can handle the click event of a button:

<Button Click="Button_Click"></Button>

And yes, you must define the Button_Click method in your code-behind file (note that you could do it inline – ie, in the XAML file – if you’re using WPF). I must confess that I’m not really a fan of this approach since I prefer to put all my code in the code-behind file. For making it work, I’ll need to change the previous code slightly by adding a name to the button:

<Button x:Name="bt"></Button>

And now, from within the constructor, I can setup my event handler like this:

bt.Click += Button_Click;

Final note: in the real world, I’ll probably end up with a Lambda expression for simple handlers. As you can see, setting up handlers from the XAML is possible (the syntax is the same as you’ve got for props) but I don’t really recommend it. And that’s it for now. In the next post, we’ll talk about Silverlight’s markup extension support. Stay tuned.

by luisabreu | with no comments
Filed under: ,
How to build types that can be consumed from XAML
Thu, Nov 19 2009 10:32

Now that you know how to use custom types in XAML, you might be wondering if there are any thing you should keep in mind when designing new types that should be consumed from XAML. I’ve already said before that collection properties need to have a getter that return a valid instance of an object. But there’s more. Here are a few things you should consider when designing types for being consumed from XAML:

  • Elements can only be public classes which have a public parameterless constructor (notice that nested classes aren’t supported);
  • structs are usable from XAML too (consider using a type converter in some scenarios where you don’t want to use the default constructor to initialize the struct)
  • non-collections properties which reference objects (ie, not primitive types) should ensure that the type has a default constructor (or that the type or property that is being defined has an adequate type converter);
  • you should use type converters when you’re using a reference type which does not have a default constructor (or when you’ve used an abstract type as the type of a property).

Regarding collections, you’ve already seen the requisites for using them from XAML: the type should implement the IList or the IDictionary/IDictionary<TKey, TValue> interfaces.

And I guess this sums it up quite nicely. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under: ,
Associating XAML namespaces to CLR namespaces
Thu, Nov 19 2009 10:10

Take a look at the following (simple) XAML:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Canvas x:Name="myCanvas"> </Canvas> </UserControl>

When I started talking about XAML, I said that the default XAML namespace is associated to several controls. You might be a little curious on how this is done. By using Reflector, you’ll see that many of the Silverlight assemblies associate CLR namespaces to XAML namespaces through the XmlnsDefinitionAttribute:

xmlnsdefinitionattribute

You’ll typically find this attribute in most assemblies that have been thought with Silverlight and WPF in mind. Notice, though, that its use isn’t mandatory to map a CLR namespace to XAML namespace because Silverlight (and WPF) supports a special mechanism for doing that. For instance, suppose you’ve got a type called BeautifulGrid, defined in the CLR Test namespace, in a Dumb assembly. Now, when you build the assembly, you didn’t knew anything about the XmlnDefinitionAttribute. How can you use the BeautifulGrid in your XAML file? Here’s the answer:

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:Test;assembly=Dumb"> <Canvas x:Name="myCanvas"> <my:BeautifulGrid> </my:BeautifulGrid> </Canvas> </UserControl>

There are some interesting gotchas  you should keep in mind when using this syntax:

  • the clr-namespace key is separated from its associated value by a semi-colon (:) while the assembly part of the expression uses an equal sign (=)
  • this is one of those places where you *can’t* use white spaces for improved readability;
  • you can omit the assembly part if the namespace you want to use is in the same assembly as the “current” XAML file.

Even though Silverlight supports the XmlnsDefinitionAttribute, the truth is that it doesn’t really play an important role for using custom types in Silverlight. The recommended approach for using custom types in XAML is to use the clr-namespace approach I’ve showed above.

And that’s it for now. Stay tuned for more in Silverlight.

by luisabreu | 2 comment(s)
Filed under: ,
South Africa 2010: here we go, here we go!
Wed, Nov 18 2009 21:49

A friendly advice to the Bosnian coach: next time, play more and talk less!

by luisabreu | with no comments
Filed under:
XAML languages features
Wed, Nov 18 2009 15:15

As I’ve said before, Silverlight supports only a subset of the existing XAML keywords you can use in WPF. Here’s the list of keywords you can use in your Silverlight:

  • x:Class: you can apply this attribute to the root element of the XAML file (or object tree) that is going to be “compiled”. When you apply this attribute, you’ll end up creating a partial class (named after the value you’ve passed to the attribute) which is joined with the associated code-behind file. Even though you don’t really have to use this attribute, the truth is that you’ll probably use them in 99% of your XAML files;
  • x:Key: as you’ve seen in the previous post, you can use this attribute to set the key of a dictionary’s entry of a resource dictionary;
  • x:Name: used for identifying an object so that it can be easily recovered from the code-behind file. The “practical effect” of using this attribute is that you’ll end up having a field in the code-behind file which references the element you’ve defined on the XAML file. As you can see on the docs, you’re limited in the values you can pass to this attribute. It goes without saying that you must ensure uniqueness through the names you give to the elements;
  • x:Null: this *extension* is used for setting the value of a property to null. You can use this extension with the property element or attribute syntax.

The best way to understand these attributes is to build a demo user control and see what happens after everything is compiled. For instance, lets assume that we’re adding a new Silverlight User Control to an existing Silverlight application (this will let me show what happens when you use the x:Class and x:Name attributes). By doing that, we end up with two files: a XAML and its corresponding code-behind CS file (shown in the next figure).

xamlandcodebehind

Here’s the default generated XAML (I’ve removed the unnecessary namespaces):

<UserControl 
 x:Class="SilverlightApplication1.SilverlightControl1"
 xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> </Grid> </UserControl>

If you look at the properties of the XAML file, you’ll see that it looks like this:

xamlprops

The default configuration ends up embedding the XAML file in the assembly (check the next image):

xamlresources

You’ll also get a new C# file (.g.cs) from the XAML “compilation” (onde again, I’ve edited the code before pasting it here):

namespace SilverlightApplication1 {
 public partial class SilverlightControl1 : 
System.Windows.Controls.UserControl { internal System.Windows.Controls.Grid LayoutRoot; private bool _contentLoaded; [System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) { return; } _contentLoaded = true; System.Windows.Application.LoadComponent(
this, new System.Uri(
"/SilverlightApplication1;” +
“component/SilverlightControl1.xaml"
,
System.UriKind.Relative)); this.LayoutRoot = ((System.Windows.Controls.Grid)
(
this.FindName("LayoutRoot"))); } } }

There are several interesting things going on here:

  • the x:Class attribute is responsible for the creation of the partial class defined in the .g.cs file;
  • all the named elements (ie, all the elements that use the x:Name attribute) get added to this partial class as fields. Notice that the FindName method is used for grabbing a reference to an element that is defined through the XAML file;
  • the LoadComponent method is used for loading the XAML defined in the XAML file. In this case, the generated code is getting the embedded XAML file from the SiverlightApplication 1 assembly.

by now, you should be able to understand why you can use the same name you’ve used for the x:Name attribute to access that element from a code-behind file. 

As you’ve seen, you can access the XAML elements from your code behind because building a Silverlight project ends up generating a partial class which introduces fields with the same name as the ones you used for the elements defined through XAML. THis is only possible due to the use of the x:Class and x:Name attributes.

And that’s it for now. Stay tuned for more on Silverlight.

by luisabreu | with no comments
Filed under: ,
XAML and collections
Wed, Nov 18 2009 12:13

We’ve already talked about several features related to XAML. In this post, we’ll keep going and we’ll see how to specify collections in XAML. There are two basic types of collections you can use in XAML: lists and dictionaries. Before going on, it’s important to understand that you’re not really creating new collections in XAML; instead, we’re adding items to existing collections (in other words, if you’re building an object which has a collection like property and you want it to be set from XAML, then don’t forget to make sure that the getter returns a valid reference to a collection object).

“List collections” are collections which expose an Add method (generally, we’re speaking about objects which implement the IList interface). In these cases, you’ll typically put the elements within the collection property and the XAML parser will create an object that represents each item before adding them to that collection through the Add method:

<Rectangle Width="300" Height="150">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
        <LinearGradientBrush.GradientStops>
          <GradientStop Color="White" Offset="0" />
          <GradientStop Color="Black" Offset="1" />
        </LinearGradientBrush.GradientStops>
      </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>

Btw, we could have simplified the XAML because GradientStops is the content property for the LinearGradientBrush object:

<Rectangle Width="300" Height="150">
    <Rectangle.Fill>
      <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
       <GradientStop Color="White" Offset="0" />
       <GradientStop Color="Black" Offset="1" />
      </LinearGradientBrush>
    </Rectangle.Fill>
</Rectangle>

You can always write the previous code in C# (assume rect is a reference to the rectangle):

rect.Fill = new LinearGradientBrush()
{
    StartPoint = new Point(0, 0),
    EndPoint = new Point(1, 1),
    GradientStops = {
             new GradientStop()
            {
                Color = Colors.White,
                Offset = 0
            }
            ,
            new GradientStop()
            {
                Color = Colors.Black,
                Offset = 1
            }
    }
};

Dictionaries are a different kind of collection: in these cases, each entry is a pair composed by a key and a value. The important thing here is understanding that you specify the key through the x:key attribute:

<UserControl.Resources>
    <Color x:Key="Black" A="0" B="0" G="0" />
</UserControl.Resources>

For now, lets forget that we’re specifying resources and we’ll only concentrate on the syntax. As you can see, we added a tag which identifies the resource as a color and we’re identifying it with the word Black (ie, Black is the key that identifies this entry). Once again, you could translate the previous code into C# (Resources is an object of type ResourceDictionary), but I’ll leave it to you (if you don’t have anything better to do, that is :) )

Notice x:Key is one of the few XAML keywords Silverlight supports. Besides it, there’s also the x:Class, the x:Name and x:Null attributes (we’ll come back to them in a future post). If you’re coming from WPF, then this might seem limited at first, but it’s all we have in Silverlight.

And I guess this sums it up for now. Stay tuned for more on Silverlight.

by luisabreu | 2 comment(s)
Filed under: ,
Type converter on Silverlight
Wed, Nov 18 2009 11:09

Today we’ll talk a little bit about the role played by type converters in “transforming” XAML into C# objects. Here’s a quick example:

<Button xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="bt" Click="bt_Click" Width="100" Content="Say Hi" Background="Red" />

If you look carefully, you’ll see that Background expects a Brush object. All XAML attribute are strings by default. In  other words, you’d need the following C# code to set the background of the button:

bt.Background = new SolidColorBrush(Colors.Yellow);

So, what’s going on here? Well, it’s simple: the parser uses a type converter to convert the string into the correct object. In practice, type converters are objects which inherit from TypeConverter class. You can associate a type converter to a type or to a property by using the TypeConverterAttribute. The parser will respect that option and will use the indicated type converter to translate the string into the expected object type.

Now, unlike WPF, where everything is really based on managed type converters, in Silverlight, there is an *unmanaged* type converter which is used for performing most of the common conversions you’d expect to happen (take a look at the internal SilverlightTypeConverter class and you’ll notice that you’ll end up using the “unmanaged” XcpImports type).

So, don’t expect to find many type converters by firing up .NET Reflector. Btw, you should keep in mind that you can still build and use your own type converters for your types. The XAML parser will always check the current property and/or type and if it’s associated with a managed type converter, it will honor that relationship and your converter will be used.

And I guess it’s all for now. Stay tuned for more on Silverlight.

by luisabreu | 2 comment(s)
Filed under: ,
Plano Inclinado: Portuguese talk show which looks at how things are in the real “Portugal”
Tue, Nov 17 2009 12:37

If you’ve missed it, then don’t forget to check it online. It’s really a shame that most Portuguese people won’t ever watch this program (which is probably one of the first programs with real quality in Portugal) because they’re watching soap operas or some other low quality programs…

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

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover