LA.NET [EN]

Mar 06

Microsoft SQL Server 2012 Integration Services book release

Posted in Books           Comments Off on Microsoft SQL Server 2012 Integration Services book release

Pedro Perfeito’s MS SQL Server 2012 Integration Service’s book is  now available for pre-order from Packt. If you’re looking for a good reading in this area, then this is probably a book you should consider.

Jan 27

If you’ve been doing Web development from some time now and you’ve looked at several of the Windows 8 samples, you’re probably wondering which event you should handle if you’re interested in doing work as soon as you can. The first option you have is to handle the DOMContentLoaded event. As you probably know, this event will be fired when the current document has been parsed (but might not have been totally loaded – ex.: images might still being downloaded, but you can interact with all the DOM elements).

Since you’re writing a Windows 8 application, them you should also know that the WinJS library will handle this event. Internally, the library does some housekeeping, which lead to the generation of several WinJS custom events. Currently, you’ll end up with the following sequence of events: loaded (fired right after the DOMContentLoaded event), mainwindowactivated (similar to activated; in fact, it’s generated from the internal WinJS activated event handler), activated (occurs after WinRT activation has occurred), ready (occurs when the application is ready and all the housekeeping has been done).

Since we’re talking about events, then  don’t forget that you must always call the WinJS.Application.start method or you won’t get any of the WinJS events. This happens because, under the hood,  WinJS queues events and it will only start processing them after you call that method.

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

Jan 20

Windows 8 adventures: error handling and the async pattern

Posted in Windows8           Comments Off on Windows 8 adventures: error handling and the async pattern

In the previous post, we’ve started looking at the async pattern in Windows 8 Metro apps developed with JavaScript. By now, you know that all async operations are wrapped in Promise objects which you can use to be notified when that operation has ended (besides other interesting things!). We’ve also seen how we can “improve” the code readability associated with several async operations which are executed in chain.

What I didn’t mention at the time is that the then method expects three parameters (all functions). Besides the success function, you can also pass two other functions which will be called, respectively, for reporting an error and for reporting progress. If you follow my previous advice and return new Promises from the then method, then you can get “global” error handling by adding a final then method which defines the global method function. Here’s an improved version of the createFolderAndFile function:

function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder",
    Windows.Storage.CreationCollisionOption.openIfExists)
    .then(function (folder) {
        return folder.createFileAsync("testFile.txt")
    })
    .then( function (file) {
        return file.openAsync( Windows.Storage.FileAccessMode.readWrite);
    })
    .then( function (dataStream) {
        var stream = dataStream.getOutputStreamAt(0);
        var writer = new Windows.Storage.Streams.DataWriter(stream);
        writer.writeString("Howdy, there!");
        return writer.storeAsync()
        .then(function () {
            return stream.flushAsync()
            .then(function () {}, function () { }); }); })
    .then(null, function (err) { //handle error here! });;
    }

Notice that there’s a slight change and we’re returning the result of the storeAsync().then call so that all eventual errors can be handled in the error function passed to the last then method call. You can test this behaviour by adding throw statements in several places in the previous code and by setting a breakpoint inside that anonymous error function.

And that’s all for now. Stay tuned for more.

Jan 19

Windows 8 adventures: the async pattern in JavaScript

Posted in Windows8           Comments Off on Windows 8 adventures: the async pattern in JavaScript

After a small detour into ASP.NET MVC, I’m back into my “Windows 8 application development study”. One of the things you’ll notice when writing Windows 8 Metro applications is that most APIs don’t expose any synchronous methods. If an operation takes more than 15ms to be executed, then you’ll be getting an asynchronous call. And notice that asynchronous is not an option here! It’s simply the only way to go.

If you’re developing Windows 8 Metro apps with JavaScript, then it won’t be long until you meet the WinJS.Promise object (which I’ll be calling Promise from now on). Most (if not all) of the asynchronous method you’ll be using end up returning a Promise. For instance, if you’re trying to create a new file, you’ll probably be using the createFileAsync method. This method returns a Promise which you can then use for being called back when that operation is performed. To illustrate this point, lets see some code which creates a new file inside a new folder. Here’s our first try:

function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder",
    Windows.Storage.CreationCollisionOption.openIfExists)
    .then(function (folder) {
        folder.createFileAsync("testFile.txt")
        .then(function (file) {
            file.openAsync(Windows.Storage.FileAccessMode.readWrite)
            .then(function (dataStream) {
                var stream = dataStream.getOutputStreamAt(0);
                var writer = new Windows.Storage.Streams.DataWriter(stream);
                writer.writeString("Howdy, there!");
                writer.storeAsync()
                .then(function () {
                    //don't do anything in callbacks
                    stream.flushAsync()
                    .then(function () { }, function (err) { var r = ""; });
                });
            });
        });
    });
}

Wow!!! I’ve written the code and I’m already lost here! Fortunately, you can improve this code by returning promises from your .then methods. By doing that, you can write code which is a little bit more linear. Here’s our initial example rewritten:

 
function createFolderAndFile() {
    //create new folder inside temp folder
    var tempFolder = Windows.Storage.ApplicationData.current.temporaryFolder;
    tempFolder.createFolderAsync("testFolder", Windows.Storage.CreationCollisionOption.openIfExists)
        .then(function(folder) {
                return folder.createFileAsync("testFile.txt")
        }).then(function(file) {
                return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
        }).then(function(dataStream) {
            var stream = dataStream.getOutputStreamAt(0);
            var writer = new Windows.Storage.Streams.DataWriter(stream);
            writer.writeString("Howdy, there!");
            return writer.storeAsync()
                .then(function() {
                    return stream.flushAsync();
                });
        });
}

I’d say that this is better (at least, from a readability point of view). What do you think?

Btw, I’m almost positive that you’ve notice the empty then calls on the flishAsync method? Well, I’m still not sure why, but the thing is that “empty” call is needed in order for the bytes to be saved to the file. If you remove the .then call, you’ll end up with an empty file (no, are we talking about a bug here?? )

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

Jan 12

Windows 8 adventures: getting to know context menus

Posted in Windows8           Comments Off on Windows 8 adventures: getting to know context menus

In the previous post, I’ve talked about the new Flyout control. Today, we’ll take a quick look at the context menu. In practice, you’ll show a context menu when you need to show a menu which gives the user immediate access to actions on text or UI objects.

By default, there are predefined context menus for text and hyperlinks. For text, the default context menu ends up showing the traditional cut, copy and paste commands. For hyperlinks, you end up with commands which allow you to copy the link or to open the link in a new window. For instance, suppose you’ve got a textarea in your default landing page:

<p>
    <textarea rows="4" cols="50"></textarea>
</p>

After writing texto and right clicking over any text selection, you’ll end up with the following default context menu:

contextmenu

Now, it’s important to notice that the options shown may vary. For instance, if the text is read only, you’ll only see the copy option. To illustrate this option, lets add a new paragraph to our landing page:

<p id="paragraph1"  data-win-selectable="true">
    Some demo text just for testing purposes...
</p>

Now, you’ve probably noticed the use of the data-win-selectable attribute. You need to resort to this attribute when you want to make p’s content selectable. The next image shows the results:

contextmenu2 

If you’ve been paying attention to the HTML evolution, then you know that the HTML5 spec introduces the contenteditable attribute which can be used to make the content of an element editable. Even though the docs say that setting this attribute to true is enough for making the element selectable (and it is!), there’s a bug in the current preview release associated with the context menu: whenever you apply the contenteditable attribute to an element, you can select text, but right clicking over that selection will not show you the context menu. Since we’re talking about bugs, it’s also important to notice that right clicking over selected text will also end up showing the appbar (if there’s one). I expect to see both these problems solved until we get a final release.

Now that we’ve already discussed some of the basics, you might be wondering about the code needed to show a context menu. The strategy is rather simple:

  1. we start by setting up an event handler for the context menu event;
  2. we prevent the default behaviour from within that handler;
  3. we create a new PopupMenu control and populate it with the required UICommand entries;
  4. we show the menu in the appropriate place by using the showAsync or showForSelectionAsync method.

To illustrate these points, we’ll replace the default context menu shown when the user right clicks over the selected text of the paragraph presented in the beginning of this post. As I’ve said, the first thing we need to do is set up an event handler for the context menu event of our paragraph. This can be done from within an initialization function which, for instance, is called from within the DOMContentLoaded event handler:

document.getElementById("paragraph1").addEventListener(
    "context menu", showContextMenu, false);

Lets take a look at the code used inside the showContextMenu function:

function showContextMenu(evt) {
    evt.preventDefault();
    var menu = new Windows.UI.Popups.PopupMenu();
    menu.commands.append(
      new Windows.UI.Popups.UICommand("Copy", null, 1));
    menu.commands.append(
      new Windows.UI.Popups.UICommandSeparator());
    menu.commands.append(
      new Windows.UI.Popups.UICommand("Search", null, 1));    
    menu.showAsync({ x: evt.screenX, y: evt.screenY }, "above")
        .then(function (cmd) {
                //handle command
        });
}

After preventing the default context menu from being shown, we start by creating the PopupMenu which will replace the default  context menu. This new context menu is populated with two UICommand instances and one separator (represented programmatically by a UICommandSeparator instance). All UICommand instances expect at least two parameters: a string which will be displayed in the menu and a callback function which will be invoked when that option is selection (which you can set to null!). Optionally, you can also pass a third parameter, which is used for setting the command identifier (in the previous example, I’ve resorted to an integer, but you can pass any object you want).

In this example, I’ve opted for using the showAsync method and for placing the menu according to the screen coordinates of the event object. Notice also that I’m passing a success callback to the then method, which will be called when the context menu is dismissed. The cmd parameter will only hold a valid value when you pick a command from the menu. When that happens, you’ll end up receiving the UICommand that has been selected by the user. You can then inspect that object and decide what you should do. The next image shows our new context menu in action:

contextmenu3

And that’s it for now. Stay tuned for more about Windows 8 Metro dev.

Jan 11

According to the docs, the Flyout control allows us to add lightweight popups which relate to what the user is currently doing. Creating a flyout is a simple operation which evolves a couple of steps:

  1. create the HTML snippet shown by the flyout;
  2. create the Flyout control and associate it with the HTML snippet created in step 1;
  3. control the dismissal of the flyout and perform a specific operation when the flyout is dismissed (if required).

To illustrate its use, let’s build a simple app which shows a flyout in response to a button click.  Here’s the HTML snippet responsible for the button and for the contents presented by the flyout:

<p> 
 <input type="button" value="show Flyout" id="showFlyout" /> 
</p> 
<div id="flyout" data-win-control="WinJS.UI.Flyout">
 <div>Your account will be charged!</div>
 <input type="button" id="confirmFlyout" value="Confirm" />
 </div>
<div id="info"></div>

The info div is used for showing a message which explains how the flyout was dismissed (since flyouts can be dismissed by just clicking outside them, we’ll be using this div to show a message which says how the flyout was dismissed). Notice that we don’t need to hide the flyout by setting its display to none because it will be automatically hidden from the display when we associate it with the Flyout control that is created during the ready event:

WinJS.Utilities.ready(initializeSample, true);
var _flyout = null;
function initializeSample() {
 WinJS.UI.processAll()
 .then(function () {
 _flyout = WinJS.UI.getControl( document.getElementById("flyout")); 
_flyout.addEventListener(
 "afterhide", performFlyoutAction, false);
 });
 document.getElementById("confirmFlyout").addEventListener(
  "click", confirmFlyoutDlg, false); 
 document.getElementById("showFlyout").addEventListener(
 "click", showFlyout, false); 
}

The initializeSample function will only be called after the DOMContentLoaded event has been fired. Internally, the ready method will resort to a Promise in order to execute the initializeSample callback. If you prefer, you can still rely on the DOMContentLoaded event to run your initialization logic.

After initializing all the controls defined in the HTML document (notice the WinJS.UI.processAll method call), we initialize a global variable with a reference to our Flyout control and set up an event handler which will be called in response to the afterhide event (this event is raised by the flyout after is has been fully hidden). You’ve probably noticed that we’ve hooked up the click events raised by the showFlyout and confirmFlyout buttons.

In the showFlyout button click’s event, we’re just showing the flyout:

function showFlyout(evt) {
 _flyout.show(evt.target, "top");
}

Showing the flyout requires us to pass an anchor control (in this case, we’re passing it the object responsible for raising the event) and specify it’s relative position to the anchor control (in this case, we’re showing it over the button). The relative position is used as a hint and the flyout position will also be influenced by the current available space (for instance, if our button is placed at the top of the screen, then you shouldn’t really be surprised to see the flyout shown below it, event though you’ve passed top as the flyout’s relative position).

The confirmFlyout’s click event handler will only be called when the user clicks over the button shown by the flyout. Since flyouts can also be dismissed by just clicking outside of them, then we’ll use this event handler to change the value of another global variable (_flyoutConfirmed) before closing the flyout:

var _flyoutConfirmed = false;
function confirmFlyoutDlg() {
 _flyoutConfirmed = true; _flyout.hide(); 
}

We’ll be using this global variable from within the flyout’s afterhide event handler to see if the flyout was dismissed because the user clicked outside of the flyout or because the user clicked in the confirmFlyout button:

function performFlyoutAction() {
 document.getElementById("info").innerHTML = 
 _flyoutConfirmed ? "YES" : "NO"; _flyoutConfirmed = false; 
}

In this example, we’re just writing yes or no to a div, but you can easily adapt the code to start some action in response to a flyout’s button click. Notice that we’re also reseting the _flyoutConfirmed variable so that future flyout dismissals are correctly processed

Besides the methods and events shown in this small example, the Flyout control exposes others properties, methods and events. You can find more info about them in the online docs.

And that’s all for now. Stay tuned for more.

Jan 09

Windows 8 adventures: playing with the Tooltip control

Posted in Windows8           Comments Off on Windows 8 adventures: playing with the Tooltip control

The Tooltip control is one of the new controls introduced by WinRT JavaScript API. After looking at the docs, I’ve decided to see how I could use it in a real world scenario. Since it’s a Windows 8 control, I knew that I could instantiate it by applying the win-data-control attribute to a div (and, of course, don’t Forget to initialize the controls by calling WinJS.UI.process/All method):

<div data-win-control="WinJS.UI.Tooltip" 
data-win-options="{placement: 'right'}"> 
 Testing another tooltip 
</div>

The placement property is used to hint the place where the tooltip should be set (it accepts the strings top, left, right and bottom). Now, the next step is understanding how we can associate the tooltip with an existing control. After checking the property list, I didn’t find any property which would let me associate the tooltip with an existing control. I did, however, find an innerHTML property, that can be used for setting the HTML shown by the control. And that’s when I thought about putting the Tooltip’s associated control inside the Tooltip’s div:

<div data-win-control="WinJS.UI.Tooltip" 
 data-win-options= 
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div>

And sure enough, it worked: putting the mouse over the button is all that it takes to see the custom tooltip:

simpletooltip

Well, the tooltip is shown, but the results aren’t probably the one you’d expect since you’re probably expecting to see the tooltip being presented besides the button. If you think about it for a minute, then the problema is rather obvious. By default, div’s display is set to block and that means it’ll occupy a whole line, relegating the tooltip’s text to the next line. One possible solution is chaning the div’s display CSS property by using a CSS class rule:

.tooltip { display: inline-block; }

And then, we need to apply the class to the tooltip’s div:

<div data-win-control="WinJS.UI.Tooltip" 
 class="tooltip" 
 data-win-options=
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div>

And then, everything works as expected:

toolti

If you want, you can also define the HTML shown by the tooltip in another HTML element. In order to do that, you need to set the contentElement property. Here’s how you can do that:

<div data-win-control="WinJS.UI.Tooltip" 
 data-win-options= 
 "{placement: 'right', innerHTML: 'Testing another tooltip'}"> 
 <input type="button" value="This is a simple button" /> 
</div> 
<div id="contentTooltipContainer"> 
 <div id="contentTooltip"> Just a simple toggle button... </div> 
</div>

Notice that I’m wrapping the HTML element which is used by the Tooltip in a another div so that I can hide it from the UI (by applying a CSS rule which targets the contentTooltipContainer ID). If you don’t do that, the div’s content will be shown in the UI. Looking at the docs, there’s another important property which needs some explaining: I’m talking about the infotip property. When you set it to true, you’re saying that the tooltip should be displayed for a little bit more time than usual. This is a good option when you have more than one line of text or when you need to worry about the finger occlusion problem (setting infotip to true requires a longer holding time before it appears, and once it’s opened, the underlying item will not be activated when the user lifts his or her finger). Here’s the result I’ve ended up with:adjustingtooltip

Before ending, there’s still time to mention the existence of the HTML title attribute. If you’ve been doing Web development, you probably know that you can add a tooltip by setting the title attribute. However, creating a tooltip by setting the title attribute is a rather limited approach. For instance, you can only pass it text and you have no multi-touch support. Whenever you need any of these options, you should rely on the Tooltip control.

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

Jan 05

Windows 8 adventures: getting external data from a local server might not be as easy as you expect…

Posted in Windows8           Comments Off on Windows 8 adventures: getting external data from a local server might not be as easy as you expect…

After a couple of days playing with the Windows 8 controls (more about them in future post), I’ve decided that it was time to see how to get remote data through the WinJS.xhr helper. To make things really simple, I’ve decided to create an HTML page on the server which would be obtained through WinJS.xhr helper. I’ve ended up with the following code on my WinRT page’s DOMContentLoaded event:

document.addEventListener("DOMContentLoaded",
 function (e) {
  WinJS.xhr({ url: http://localhost/samplepage.html })
 .then(handleResponse, handleError); },
 false);

The WinJS.xhr method expects an anonymous object which you can use to set several of the parameters associated with remote call (notice that his call ends up being performed by the XMLHttpRequest object). In our simple example, we’re only setting the URLfor the call (according to the docs, you can also set several other parameters)

The WinJS.xhr method returns, once again, a Promise objet. In this case, the handleReponse method will be called when everything runs without any glitches. If there are any problems, the WinRT runtime ends up calling our handleError method. In this case, both methods end up receiving an instance of the XMLHttpRequest object used for performing the call.

The first time I’ve ran my demo app, it took a while until… my error handler got called. Initially, I thought that the URL was wrong, so I’ve copied it and pasted it into the URL address of Chrome. Nop, there was nothing wrong with the HTML. So, I’ve went ahead and I’ve searched the forums and started emailing some guys. After some time, I got lucky and I’ve found this post. Tiago also gave me a hand by explaining that there was a difference between the local vs. Web context difference. It was only a matter of time until finding the checknetisolation tool.

According to the docs, localhost access is forbidden for security reasons and that means you’re into trouble when you’re developing apps which access local services. And that’s where this tool comes in: you can use it to create a rule which relaxes the WinRT localhost loopback restriction. To create a new rule, you must run the following command:

checknetisolation loopbackexempt –a –n=your_app_name

Alternatively, you can pass your app’s SID (in that case, you –p instead of –n), but I think that using your app’s name is easier. This brings us to the next question: what’s the name of my app? It turns out that the easiest way to get your app’s name is to open the manifest and copy the value of the Package Family Name entry in the Packaging tab:

manifest

Now, running the following instruction is all that you need to get that loopback restriction removed for our win8tests app:

checknetisolation loopbackexempt –a –n=win8tests_t2ggmrgk4m9fg

Before going on, we should always use the –s option to see if everything went well:

checking

As you can see, our rule is in place and everything should work out just fine…say again? are you sure? Unfortunately, it wasn’t working out fine…I was still getting the timeout and the error function that I’ve passed to the Promise object was still being called.

In despair, I’ve went back to the initial post and asked if there was anything I was missing. And the answer was yes, there was: I hadn’t opened port 80 on my firewall. It seems like WinRT xhr calls are always “served” as remote calls and they were being blocked by the firewall. After opening the HTTP 80 port (inbound rules), everything started running smoothly!

firewall

Btw, one extra note: if you’re trying to get a resource from an intranet machine, then you’ll probably need to require Home/work Networking capability in your manifest.

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

Jan 04

Windows 8 Adventures: Oh my god, it’s so easy to debug JavaScript apps!

Posted in Windows8           Comments Off on Windows 8 Adventures: Oh my god, it’s so easy to debug JavaScript apps!

After installing the Windows 8 Developer Preview With Developer Tools, I’ve finally managed to debug my JavaScript applications. Hurray and hurrah!!! And I must confess that the experience is really good!

Even though I’ve been using Windows 8 for some time now, the truth is that the Widows 8 Developer Preview version I’ve decided to install at the time didn’t allow me to build Metro Style apps nor to debug existing applications (btw, I’ve decided to go with that version because it was the only one which allowed me to upgrade from Windows 7 and, at the time, the page didn’t mention that you could only only build Metro style apps from the Developer Tools version).

Back to business: so, what do we get when we debug a Windows 8 Metro JavaScript app? We get *all* the goodies we’re used to when debugging HTML+JS pages. Ok, here’s a screen capture which shows VS2011 running a debug session:

debugging

As you’d expect, you can add breakpoints to your JavaScript code and you can check the values of your objects by looking at the traditional watch and locals windows. You can also navigate through the current stack trace (and this means you inspect the Win RT JS code which ends up calling your functions). JavaScript developers will also notice the existence of the console window, which allows you to inspect your code or run JavaScript code.

Even more interesting is the DOM Explorer window (which you can see in the first tab). The next image shows that window in detail:

domexplorer

Yep, you have total access to the DOM used by your Win 8 Metro JavaScript! You can see the styles which have been applied to an element and you can even change them. If you’ve got a dual monitor system, you can even see where each HTML element is on your app’s UI:

all

This should be a really huge help for building those nasty layouts. Btw, if you’re building an app for several devices, then you’ll probably be happy to know that you can use the simulator. To use the simulator, you must change the default properties of your project (to access the dialog, right click your project in Solution Explorer and choose the properties option):

simulator

After setting the debugger to launch dropdown to Simulator, you can simply hit F5 and you’ll end up with the simulator. Even though the simulator takes some time to start, it’s well worth it because you’ll end up with an environment where you can change the current screen resolution, change the way you interact with the app (mouse vs. touch) or even change the current orientation of your screen:

simulator2

This should be really useful for everyone who needs to build an app for several devices and is stuck with a PC (like me!).

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

Jan 03

Windows 8 Adventures: setting properties from the HTML

Posted in Windows8           Comments Off on Windows 8 Adventures: setting properties from the HTML

Yesterday I’ve started playing with the Windows 8 developer bits and I’ve decided to follow the JavaScript online docs. Windows 8 introduces lots of new things, but I’ve decided to start simple. It didn’t take long until I got into trouble though…One of the first controls that got me into trouble was the TimePicker control. The quick start docs are enough to start working with most of its features. And everything was fine, until I’ve tried running this code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Win8Tests</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script type="text/javascript" src="/WinJS/js/base.js">
</
script> <script type="text/javascript" src="/WinJS/js/ui.js">
</
script> <script type="text/javascript" src="/WinJS/js/binding.js">
</
script> <script type="text/javascript" src="/WinJS/js/controls.js">
</
script> <script type="text/javascript" src="/WinJS/js/res.js">
</
script> <script type="text/javascript" src="/WinJS/js/animations.js">
</
script> <script type="text/javascript" src="/WinJS/js/uicollections.js">
</
script> <script type="text/javascript" src="/WinJS/js/wwaapp.js">
</
script> <!-- Win8Tests references --> <link rel="stylesheet" href="/css/default.css" /> <script src="/js/default.js"></script> </head> <body> <div id="timer" data-win-options="{current: '12:15', disabled: true}" data-win-control="WinJS.UI.TimePicker"> </div> </body> </html>

Before talking about the problem, lets try to understand what’s going on here…

I’ve started by adding several (probably all?) of the client JavaScript libraries which will let me use the Win RT API from JavaScript (notice that I’ve included more libraries than needed for this small demo, but at least I know that all the required libraries have been included and I’m not missing any script reference). If you’ve just started looking at Windows 8 HTML code, then you’re probably wondering why we have all those data-XXX attributes applied to the div.

In the previous example, they’re used for transforming a simple div into a Windows 8 TimePicker control. You see, if you choose to build an Win RT app with HTML and JavaScript, you can reuse most (if not all!) of the traditional HTML controls. But there’s more: you can also use the new Windows 8 controls. One of the options for instantiating these controls is to apply the data-win-control attribute to a div and specify the type of control that should be created (in the previous example, we’ve used the WinJs.UI.TimePicker control). Notice that opting for this strategy means that you’ll need to call the process or the processAll method from your JavaScript code. I’ve decided to call the processAll method from the DOMContentLoaded event:

document.addEventListener("DOMContentLoaded", function (e) {
    WinJS.UI.processAll();
});

Alternatively, you can instantiate a control from your JavaScript code, but we’ll leave that for a future post. Going back to our HTML code, it shouldn’t be surprising to discover that the data-win-options attribute is used for initializing the properties of the control from the HTML markup. In our example, I’m trying to disable the control and set the time to 12h15. The problem is that I was always getting the default 12h00 time (btw, if you don’t set any value, you’ll end up with the current time):

timepicker

hum…what’s going on here? Shouldn’t this work? According to the docs, string properties can be wrapped in ‘ ‘ and it should work without any glitches. Unfortunately, the problem was rather simple: it’s a limitation of the current build and “You can always use the standard American English in this release”. And yes, changing the way date, time and number are formatted (in the regional settings of the control panel) solved the problem. Anyways, I’m living in Madeira (still part of Portugal, I believe – sorry, local joke :)), so I really want to see my data formatted in Portuguese. So, how can I solve this problem without changing the locale? Well, one solution to the problem is to work with the Promise object that processAll returns. Here’s a modified version of the JavaScript I’ve used initially:

document.addEventListener("DOMContentLoaded", function (e) {
    WinJS.UI.processAll()
                .then(initializePicker, Error);
});
function initializePicker() {
    var picker = WinJS.UI.getControl(document.getElementById("timer"));
    picker.current = new Date(2012, 3, 1, 12, 15);
}

One of the interesting concepts of Win RT is that most operations that “take time” are asynchronous. processAll must go through all the DOM and initialize all the Windows 8 controls it finds. That’s why it’s an async operation and, like all asynchronous operations, it ends up returning a Promise object. After getting a Promise object, we can configure it to invoke a callback method when the encapsulated operation is done. In our case, we’re also passing an error function that should be invoked if the “encapsulated” operation generates an error (notice that we can still pass one additional function, that would be called for progress feedback). Our initializePicker function is rather simple: we’re getting a reference to the Windows 8 control (notice the WinJS.UI.getControl method) and creating a new Date object (with the correct time) that is used for initializing the TimePicker’s current property.

And that’s it for now. Stay tuned for more!

Dec 31

Happy new year everyone!

Posted in Trivia           Comments Off on Happy new year everyone!

Just a quick post to wish you all a happy new year!

Nov 23

Reflexões ao almoço de um Madeirense orgulhoso que teima em continuar a ser Português

Posted in Trivia           Comments Off on Reflexões ao almoço de um Madeirense orgulhoso que teima em continuar a ser Português

Enough is enough! I tipically don’t discuss politics but this time I’ll make an exception . Since it’s about Madeira and Portugal, I’ll write in Portuguese. 

Se me dissessem no ano passado que hoje estaria a escrever um post político no meu blog e que ainda por cima estaria a defender algumas decisões tomadas pelo Governo Regional, eu diria que isso seria impossível. Não gosto de política, nem gosto dos partidos políticos. Mas a paciência tem limites e a informação apresentada nos meios de comunicação social é tão má, que me vejo forçado a gastar a minha hora de almoço a escrever sobre estes tópicos.

Durante os últimos meses, a Madeira tem sido constantemente atacada por todos os meios de comunicação social que insistem em duas teorias perversas e completamente desfasadas da realidade. A primeira é que a região é constituída por parasitas, que se limitam a roubar o dinheiro dos restantes contribuintes do estado Português (esses sim, trabalhadores incansáveis, que andam constantemente a sustentar os mandriões dos Madeirenses). A segunda, ainda mais desfasada da realidade, assenta na teoria de que o problema financeiro de Portugal só existe devido à divida total da Madeira (que ascende, ao que parece, aos 6.3 M milhões de euros).

Estas teorias ganham eco através do péssimo jornalismo feito num país onde muitos são pobres, alguns são remediados e poucos são ricos. Não é de agora que tenho dúvidas em relação à qualidade do jornalismo em Portugal. Por exemplo, veja-se este artigo de opinião, supostamente escrito pelo Mário Crespo (alguém que gosta de passar a ideia de ser um profissional a sério!), sobre a aquisição dos Falcon… Qualquer pessoa que não conheça a realidade pensa que esta compra foi apenas um capricho dos governantes. Pena que um jornalista da sua “craveira” não se tenha dado ao trabalho de investigar a realidade. Se o tivesse feito, não se teria também esquecido de dizer que estes aviões são usados, por exemplo, para efetuar a transferência de órgãos (sim, estamos a falar de salvar vidas humanas, ou acham que os órgãos são transferidos nos aviões comerciais da TAP?) e para garantir o número de horas dos nossos pilotos da Força Aérea (sem horas de voo, não têm brevet para voarem!). Mas enfim, num país onde a mediocridade é normal, também não se poderia esperar que os jornalistas fossem diferentes, certo?

Mas de volta à manipulação que tem sido feita sobre a Madeira, não posso deixar de referenciar duas noticias que saíram nos últimos dias: “Três milhões de euros para iluminações e fogo-de-artifício na Madeira” (o Público) e “Madeira tem carta branca para contratar funcionários públicos” (Diário Económico). Perante estes “roubos” efetuados pelos parasitas Madeirenses, não é invulgar encontrarmos vários comentários anti-Madeira. Já vi de tudo: desde o tradicional “venda-se já” (como se não estivéssemos numa economia de mercado, onde existe o conceito de propriedade privada!) ao já usual “Mamadeira” (forma como os contribuintes não Madeirenses gostam de designar a “Pérola do Atlântico”). Um exemplo típico deste comportamento é o comentário do sr. Open Mind (ao que parece, do Porto) que adicionou o seguinte comentário à noticia da iluminação (optei por colocar um que não fere as suscetibilidades dos mais novos):

“E a roubalheira continua!

O regabofe continua! Aqui no continente corta-se nos apoios a crianças, jovens, idoso, na saúde, corta-se os subsidios, aumenta-se a carga horária de trabalho, os impostos e sei lá que mais, para este louco continuar a gastar sem qualquer controlo! Isto é inadmissivel! (…)”

São comentários como este que me fazem ter a certeza de que nunca vamos sair do buraco onde nos encontramos. Mas vamos lá começar pelo início. E nada como analisar o Orçamento de Estado de 2011. Vejamos, então, o que diz o Correio da Manhã em relação às verbas retiradas do OE para a Madeira:

“Se o Orçamento de Estado para 2011 passar na Assembleia da República, vão ser transferidos para a Madeira 191,5 milhões de euros para cobrir custos da insularidade; 8,3 milhões de euros ao abrigo do fundo de coesão; e 50 milhões de euros para fazer face aos prejuízos dos temporais ocorridos este ano. No total, são transferidos do Orçamento de Estado para a Madeira 251,1 milhões de euros.”

Como é óbvio, a verba enviada para a Madeira é bem inferior à dos Açores (e sempre foi, ao contrário do que alguns jornalistas tentam fazer parecer) e inclui as verbas usadas na chamada Lei de Meios, que servem para ajudar a ilha a recuperar dos prejuízos do temporal. Para simplificar, vamos usar o valor 260 milhões como sendo o valor totalmente suportado pelos contribuintes não residentes da Madeira que é cedido à região. Agora, vejamos a receita projetada no mapa do orçamento regional da Madeira de 2011: valor final: 1.6M milhões. Bom, eu não tenho formação em economia ou finanças, mas parece-me que afinal os Madeirenses não estão a parasitar os contribuintes do continente, certo? Ou seja, o valor cedido do OE de estado é importante (que não restem dúvidas disto!), mas está longe de representar a única fonte de receitas do orçamento regional (ou de ser responsável pelas obras de infraestruturas efetuadas ao longo dos anos – vamos deixar a discussão das obras para outra altura).

Antes de passarmos à análise das notícias dos jornais Público e Diário Económico, nada como fazer um aparte e esclarecer outro mito que por aí circula. A teoria geral é: “pois bem, estão a ver? Nós pagamos impostos e o nosso dinheiro vai para a ‘Mamadeira’. Os impostos deles ficam na ilha”. Esta teoria é defendida pelo “grande comentador” Miguel de Sousa Tavares (mente iluminada, que todas as semanas ocupa espaço precioso na sic, a debitar baboseiras sobre todos os tópicos possíveis). Infelizmente esta teoria não corresponde à verdade, como é possível verificar através da Lei das Finanças Regionais. Se é verdade que a maioria dos impostos (ex.: IRS, IVA e selo) é, efetivamente, devolvida às regiões, o mesmo não acontece com impostos extra (como a 5% de redução média dos ordenados da função pública ou a retenção de 50% do subsidio de Natal) ou com IRC (onde a afetação devolvida à região depende da sede da empresa e/ou da existência de representação legal na região).

Portanto, a realidade é que existem muitos Madeirenses que estão a contribuir orgulhosamente (eu incluo-me nesse grupo) para equilibrar as contas públicas da nação (ao contrário do que, por exemplo, acontece com os Açores, onde a penalização não afeta todos os funcionários públicos). Já agora, e se o leitor não se importar, vamos deixar a discussão do pseudo-perdão de Guterres da divida regional e a existência de impostos mais baixos para outro post…e nessa altura, podemos até comparar a situação da Madeira e dos Açores com a existente nas Canárias, região autónoma da vizinha Espanha…

E, sem mais demoras, passo à primeira notícia, escrita pelo Sr. Tolentino Nóbrega, cuja cegueira política contra AJJ (para a qual tem, provavelmente, boas razões), levou à escrita de um artigo onde se depreende que a iluminação de Natal custa 3 milhões aos contribuintes continentais e é apenas feita por laxismo/opulência do “regime jardinista”. Nesta altura, a primeira falácia deve estar esclarecida (recordar receita total esperada da região de 1.6M milhões em 2011). Em relação à segunda, qualquer pessoa que conheça a Madeira sabe que ela só tem dois bens “transacionáveis”: turismo e praça financeira (hoje não vamos falar da praça financeira, mas se continuar a ouvir o Sr. Louçã a dizer asneiras na TV – e ainda por cima, dizem-me que o homem é formado em economia e, pasme-se, dá aulas sobre essa área na universidade – não vou ter outro remédio senão adicionar um outro tópico sobre este assunto tão importante para a sobrevivência económica da ilha).

Para quem não sabe, a quadra natalícia é o cartaz turístico da região. É aqui que tem de se investir (e não gastar, como apregoa o Sr. Tolentino!)  porque o retorno turístico é enorme. Em vez de analisar o ajuste direto (que é um tópico que interessa a toda a gente, incluindo os contribuintes Madeirenses), o Sr. Tolentino preferiu, ao que consta, inventar e então deu-se ao trabalho de escrever as seguintes pérolas:

“ Só nas iluminações natalícias, o executivo vai despender cerca de dois milhões de euros. A adjudicação foi feita por ajuste directo à Luzosfera, depois de ter sido anulado o concurso público devido aos pedidos de impugnação interpostos por outros concorrentes, que contestaram a escolha daquela empresa. “

“A Luzosfera, do grupo SIRAM, liderada pelo ex-deputado regional Sílvio Santos (PSD), ganha assim mais meio milhão de euros em relação ao valor anual da sua própria proposta a concurso. A celebração do contrato por ajuste directo decorreu na semana passada e o início dos trabalhos de montagem das iluminações foi imediato.”

”O Funchal, ao contrário de outras cidades que reduziram as iluminações natalícias devido às medidas de austeridade, mantém o mesmo programa de festas dos anos anteriores, incluindo a duração de 12 minutos de queima de fogo do réveillon. Municípios de todo o país estão a reduzir ou a dispensar as iluminações para conter despesas, tendo a Câmara de Lisboa diminuído os gastos para 150 mil euros (menos 700 mil do que no ano passado), enquanto o Porto cortou o investimento para cerca de metade.”

Com noticias destas, tenho de reconhecer que, se vivesse noutra zona do país, e pensando eu que andava a sustentar os mandriões dos Madeirenses, também estaria revoltado e a praguejar (aliás, a minha primeira reação ao ajusto direto foi mesmo um tradicional ‘WTF?’).

Mas acontece que o Sr. Tolentino, ao que parece nascido na Madeira, desconhece que o cartaz turístico da Madeira é a quadra natalícia e respetiva passagem de ano! Sim, Sr. Tolentino, no Natal a ocupação hoteleira ronda os 100%. E sim, os turistas vêm cá para ver as tais luzinhas e o tal desperdício de queima de fogo que o Sr. refere no seu artigo.

Para além da hotelaria, importa ainda notar que o porto fica repleto de navios de cruzeiro (em média, só no dia 31, temos tido entre 6 e 9 navios!). Se nos concentrarmos só nos navios, é fácil de perceber que as tais luzinhas e o espetáculo de queima de fogo chamam muita gente. Para ter uma pequena noção de valores, é só consultar este artigo, onde é possível verificar que o cancelamento das escalas de 2 navios de cruzeiro no porto do Funchal (em consequência da greve de 24 de Novembro) pode resultar na perda de 500 milhões de euros na economia regional! Portanto, Sr. Tolentino, se há dinheiro que ainda é bem investido na ilha, é este, que é gasto nesta quadra e que acaba por trazer cá vários milhares de turistas.

Parece-me também que querer comparar a afluência de turistas à Madeira (no final do ano) com o que acontece com os outros municípios é, no mínimo, estranho. Será que os restantes municípios de Portugal têm uma afluência tão grande de turistas nesta quadra como a Madeira? Bem, nunca ouvi dizer isso, mas posso estar errado…

Infelizmente, os leitores do continente não tiveram a oportunidade de ler o esclarecimento efetuado pelo governo regional em relação a esta notícia. Vejamos, então, os pontos mais interessantes desse esclarecimento. Em primeiro lugar, parece que a alegação efetuada (de que teriam havido pedidos de impugnação) não corresponde à realidade:

“ O Concurso Público das iluminações não foi anulado devido a pedidos de impugnação interpostos mas, sim, a irregularidades cometidas por todos os concorrentes, o que levou à sua exclusão, tendo o Governo Regional determinado a não adjudicação deste procedimento. Refira-se que, em causa, está um Concurso Público, autorizado pela resolução 1031/2011, do Conselho de Governo de 14 de Julho, que versava a criação e construção dos motivos decorativos, montagem e desmontagem das iluminações decorativas, nas Festas de Natal e Fim-de-ano 2011/2012, 2012/2013 e 2013/2014, nas Festas de Carnaval 2012/2013 e 2013/2014 e Festas do Vinho da Madeira 2012/2013 e 2013/2014 na Região. A este Concurso Público, que tinha como valor base, os 8.626.500,00 euros, concorreram quatro concorrentes, que apresentaram propostas que variavam entre os 4.313.251,50 euros e os 7.885.104,00 euros, propostas que, tal como atrás é dito, apresentavam irregularidades e não preenchiam os requisitos exigíveis por lei.”

Para além disso, parece que as 4 empresas concorrentes foram convidadas a apresentar propostas de ajuste direto:

“4. Posto isto, dadas as limitações temporais e de modo a garantir a concretização de uma das vertentes mais importantes do emblemático e maior cartaz turístico da Região, o Governo Regional, através da Secretaria Regional do Turismo e Transportes, optou por recorrer ao procedimento de ajuste directo, um dos mecanismos previstos nos casos em que os concursos públicos ficam desertos. De salientar que, sendo o turismo o principal motor da economia regional e, este evento em concreto, o principal cartaz turístico da Região, o interesse público de salvaguardar a sua realização em conformidade ao que estava previsto determinou que se recorresse a todos os mecanismos que garantissem a sua efectividade. Mesmo assim, importa aqui referir que só foram incluídas neste ajude directo, as iluminações das Festas de Natal e Fim-de-ano 2011/2012 e do Carnaval 2012, dado que, para as seguintes festividades, se procederá à abertura de um Concurso Público Internacional.
5. No âmbito do referido ajuste directo, foram endereçados convites para apresentação de propostas aos quatro concorrentes que já tinham apresentado os seus projectos ao concurso público. Para este procedimento, foi estabelecido um preço base no valor de 2.068.000,00 euros, valor que teve em conta os preços médios apresentados no âmbito do Concurso Público, assim como os custos de investimento associados ao arranque inicial dos trabalhos e à logística necessária para a sua efectivação no terreno, face ao prazo que era necessário cumprir para a abertura das iluminações, a 8 de Dezembro.”

E, segundo o governo, apenas 2 dos 4 participantes concorreram:

“6.      Dos 4 convites endereçados, apenas 2 concorrentes apresentaram propostas, concretamente as empresas “Som ao Vivo, Lda.” – no valor de 2.067.997,60 – e “Luzosfera, Construções Lda.” – no valor de 1.975.414,44 euros.
7.      O ajuste directo foi adjudicado à Empresa Luzosfera, no passado dia 8 de Novembro, pelo valor de 1.975.414,44 euros, mais IVA, sendo que a adjudicação deste procedimento não suscitou quaisquer recursos/reclamações.”

Para além disso, nenhuma das empresas recorreu ao Tribunal Administrativo, conforme afirma o Sr. Tolentino:

“8.      Por outro lado, e ao contrário do que refere a noticia, importa aqui esclarecer que os últimos dois Concursos das iluminações não foram parar ao Tribunal Administrativo. Apenas o Concurso de Fogo-de-artifício 2010/2011 foi alvo de uma acção contenciosa, tendo, tanto o Tribunal Administrativo do Funchal quanto o Tribunal Central Administrativo do Sul, dado razão à Região.”

Finalmente, e ao contrário do que é sugerido, a adjudicação do fogo-de-artifício ainda não foi efetuada ainda:

“9.      Finalmente, e no que se refere às declarações proferidas sobre o Concurso do fogo-de-artifício – e não estando o mesmo ainda encerrado – esta Secretaria Regional não irá tecer quaisquer declarações nem alimentar polémicas.”

Se nenhuma das empresas contestar estas alegações do governo, gostaria de saber como é que é possível continuarmos a ter notícias tão falaciosas nos jornais Portugueses! Sr. Tolentino, o que senhor deveria ter feito era investigar ao máximo a forma como foi feito o ajuste direto e não levantar suspeitas sem apresentar argumentos concretos e verdadeiros. Mas ao que parece, a Madeira vende tanto como o Benfica, e por isso nada como atiçar a opinião pública contra os parasitas residentes na ilha…

Se ainda houvesse alguma dúvida quanto à tentativa de transformar o problema nacional num problema causado pela Madeira, veja-se o título da capa do Diário Económico de hoje (23 de Novembro):

“Madeira tem carta branca para contratar funcionários públicos”

E depois, o primeiro parágrafo da notícia online diz o seguinte:

“O controlo do recrutamento de trabalhadores nas administrações regionais poderá não ficar, afinal, sob a alçada do Ministério das Finanças. A medida está prevista na proposta do Orçamento do Estado para 2012 entregue à Assembleia da República a 17 de Outubro, e tem como objectivo centralizar no ministério tutelado por Vítor Gaspar as decisões sobre as admissões de efectivos na função pública da Madeira e Açores.”

Será que li mal, ou diz Madeira e Açores? Então o título não deveria ser: Regiões Autónomas com carta branca para contratar funcionários públicos? Ou será que os Açores já não são uma região autónoma? Que raio de jornalismo é este? A ironia está no facto de serem os Açores (e não a Madeira) que não estão a penalizar todos os seus funcionários públicos, como acontece no restante país…

Este texto não está a ser escrito por um defensor do Governo Regional, mas sim por uma pessoa que acha que a verdade é mais importante do que estar constantemente a debitar falácias que apenas contribuem para clivagens desnecessárias entre os Portugueses (sim, ainda me considero Português!)

Infelizmente, terminou a hora de almoço e por isso não me vou poder alongar na questão da divida Madeirense (por acaso, existem vários aspetos importantes aqui que mereciam a pena serem discutidos). Fica para uma próxima vez…

Nov 16

Book review: Supercharged JavaScript Graphics

Posted in Books           Comments Off on Book review: Supercharged JavaScript Graphics

Disclaimer: I’ve received a free copy of this book for review.

Nowadays, HTML5, CSS and JavaScript are everywhere. And since these are really hot technologies, it’s really easy to find lots of books about these topics. This really ends up being a problem because it’s not easy to find one which fits makes everyone happy. Interestingly,  Supercharged JavaScript Graphics seems to be able to do just that.

Let me be more specific: it’s a book which will make anyone with a decent knowledge of HTML, CSS and JavaScript interested in web graphics technics happy. I say this because the author introduces a range of topics and technics related with graphics which will surely teach you something new. Interestingly, the book doesn’t concentrate only in the new HTML5 features (ex.: canvas) and you’ll end up doing lots of graphic work with the pre-HTML5 features. Overall, I’m recommending this book for anyone who needs to improve their skills on graphics for the Web. Score: 8/1’0.

Nov 16

I’m still here…really!

Posted in ASP.NET Books MVC           Comments Off on I’m still here…really!

It’s been more than one month since I’ve written something in this blog. Unfortunately, I’ve been really busy with work and lots of investigation in several areas…but I think now I’ll be able to return to my daily routines and I’ll try to write at least one post per day Winking smile.

So, what have I been doing lately? Glad you’ve askedSmile I’ve been playing with the latest bits of ASP.NET (Web Forms and MVC). The next release will have some interesting features and that’s why I decided to write a  book about ASP.NET MVC (once again, in Portuguese). This won’t be a big book (like the one about Web Forms), but it will cover all the important details related with MVC projects.

Since my previous experiences have gone really well, I’ve decided once again to ask for the help of the community: if you understand Portuguese and you want to help me improve this book, just drop me a line at labreu _at_gmail.com. I can only have a limited number of reviewers and (unfortunately!) I can only offer a free copy of the book when it’s out for all your hard work Smile

Oct 03

MVP award for another year

Posted in Trivia           Comments Off on MVP award for another year

Even though I though this was it, the fact is that MS renewed my ASP.NET MVP status for another year! (not sure why, but the notification email ended up in the spam area – bad boy Gmail!, bad body! Smile) Thanks MS!

Sep 28

Book review: Parallel Programming with Microsoft VS 2010

Posted in Books           Comments Off on Book review: Parallel Programming with Microsoft VS 2010

[Disclaimer: I’ve received a free copy of this book for reviewing]

A few days ago, I’ve received a copy of the Parallel Programming With MS VS 2010 book. Before delving into the parallel lib, the books starts by presenting several interesting concepts related with parallel/multithreaded programming. From chapter 2 onwards, it’s all about the Parallel Lib. Chapter 2 presents several concepts related with adding task parallelism in your apps and Chapter 3 moves forward and tries to present several interesting ideas associated with data parallelism. Chapter 5 wraps it up by presenting several PLINQ related concepts. In Chapter 5, the author presents the concurrent collections and Chapter 6 wraps it up by talking a little bit about the available options for customizing the parallel lib.

I must say that I was really excited when I received the book. After all, multithreading programming is one of the areas that I really like to dig into. Unfortunately, the excitement was gone after reading the first 3/4 chapters. I’ve got two problems with this book: the first is it presents the code step by step and then it shows all the code. In other words, the book has lots of extra pages which really don’t add anything to it. The second issue I have with the book is that it doesn’t go deep enough. The examples shown are rather simple and, in my opinion, don’t really bring much more than the online docs. Overall, I’m giving it a 5/10.

Sep 15

More thoughts about the new UI user experience

Posted in Windows8           Comments Off on More thoughts about the new UI user experience

After playing a little bit more with the new Windows 8 preview, I’m a little more used to the new metro UI. I’ve already removed all the default crap (oops, applications…that’s what I meant) and I’ve added shortcuts for most of the apps I use daily. I’m still trying to figure out how to place a shortcut for a folder or an application which works in “xcopy mode”…I’ll probably have to write some code for that, but I’ll need to dig a little more before being sure.

I do like the new Windows taskbar. It’s really great to be able to see the app icon in the correct screen. Another thing which I like is the new explorer window. Now it comes with a ribon…I’ve heard several complaints about it, but the truth is that I like it. btw, it brings some new things out of the box. For instance, now you can open the cmd from the folder you’re viewing (check the next image). To be honest, I’m a little surprised there’s no power Shell shortcut (come on, this is 2011 and we all love power shell, right? Smile).

explorer

The task manager is another app which has seen several improvements. When you activate the more details window, you’ll end up getting a fair ammount of info presented in a very useful way. For instance, there’s a users tab where you can see the apps associated to each user that is logged in to the machine. Another nice detail is the new copy dialog.

taskmanager

Another interesting improvemente is the new copy file dialog. As you can see in the next image, now we are faced with a graphic which show the corrente throughput. Even better: we can pause the current copy operation (notice the small icons on the top right corner of the dialog windows).

copydialog

Another good news: there’s an out of the box mount option for ISO images (almost sure it wasn’t here before)…There surely more, but I’ll leave it for future posts. Stay tuned for more.

Sep 14

Windows 8 first impressions

Posted in Windows8           Comments Off on Windows 8 first impressions

I’ve decided to use it in my home machine…couldn’t resist it, you know Smile

The first impressions are positive, though I’m not sure if this metro thingy is something I want to use in my day to day work. I would really be glad to end up with slick and fast UI + tools. After all, I’m a  dev, not a game player. So, how do I turn it off? If there’s a way, please share it with me Smile

There’s one thing that pissed me: no more Windows menu (you know, the one that was shown when you hit the windows key…). So how do I hibernate my pc now? I’ve already changed the default power plan and I’ve added the hibernate option to the shut down options menu…but that menu is no longer available and the window key will redirect you between the desktop and the metro UI. The only way I managed to see this shut down options was when I hit ctrl+alt+del and stumbled upon a power off icon…oh well, let’s see how things go after using it for another day…

Sep 13

Exceptions in .NET– part VII

Posted in .NET Basics C#           Comments Off on Exceptions in .NET– part VII

Before going on, I need to confess one thing: I’m really frustrated! Why? simple: I was watching the damn build keynote and it stopped…right in the middle of the whole JS app for Windows 8…oh well, it’s probably a sign that it’s time to go back to my blog…

As you probably recall, in the previous post I’ve started presenting some guidelines for working with exceptions in C#. Today, I’ll keep doing that and I’ll introduce another guideline: it’s ok to catch an exception and re-throw it as “something” else if:

  • you handle only the exceptions you know how to
  • don’t forget to pass the old exception as the inner one in the new one.
Person GetPerson(Int32 id){
    try {
        //open SQL Server database
        //can throw SqlException
    }
    catch(SqlException ex) {
        //log the error
        //re-throw it as something else
        throw new InexistingPersonException(id, ex);
    }
}

Since we’re opening a database connection, we know we might end up with an SqlException whenever we open that database connection. Getting the information from a database is really an implementation detail and that’s probably someone who is consuming your code doesn’t need to know about.

Another interesting to notice is that I’ve passed the caught exception to the InexistingPersonException constructor. By doing this, I guarantee that the original exception isn’t lost and that may help me find the problem when someone calls back and complains about that exception.

Oh look, it’s saying that the day 1 keynote video will be available shortly! It’s probably best to wrap this post up right now Smile

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

Sep 13

Exceptions in .NET– part VI

Posted in .NET Basics C#           Comments Off on Exceptions in .NET– part VI

As promised, today I’ll start presenting some interesting guidelines you should follow when working with exceptions. If there’s one guideline you should *always* follow, this is it: don’t catch every exception there is…especially if you’re developing libraries which will be used by other developers.

It’s important to realize that whenever you catch an exception, you’re saying that you’re expecting it and you know how to deal with it. In my experience, it’s far too common to see code like this (btw, I’ve used it before in previous posts, which was probably a bad idea…anyways, don’t do itSmile):

try {
    //some code
}
catch(Exception ex) {
    //just “eat it”
}

Whenever you write code like this, you’re saying that you know how to handle all the exceptions that might be thrown. Really? Are you sure about that? What do you expect to do whenever you get an OutOfMemoryException? Do you really know to handle it? And what about all the other exceptions which might be thrown? Things are even worse if you do something like this in a library which is going to be used by other developers. For starters, it’s difficult to know how the application which is consuming your library will respond to exceptions. Probably it can do more than you…probably, not…And that’s why it’s vital to let those exceptions your type can’t handle flow through the call stack. The worse thing that will happen is getting an unhandled exception which ends up killing the process. And this is not such a bad thing because 1.) most unhandled exceptions will probably be caught during development and 2.) sometimes ending the process is the best way to ensure that no data is corrupted.

Notice that the problem isn’t really catching any exception. It’s swallowing it! So, if you need to log all exceptions and you’re writing library code, then this is the correct way to do it:

try {
    //some code
}
catch(Exception ex) {
    //just log it
    throw;
}

And now you’ll get your logging and you’re letting the exception flow through the call stack without changing its origin. And everybody is happy and you can go home an enjoy dinner in family…

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

Sep 09

Exceptions in .NET–part V

Posted in .NET Basics C#           Comments Off on Exceptions in .NET–part V

When someone with lots of experience in Win32 programming starts using .NET, they tend to be shocked with the regular use of exceptions. In fact, they tend to ask why do we define APIs which don’t return error codes and rely heavily on exceptions. Well, it’s a matter of “culture”. Notice that .NET and OO allows a developer to be very productive. For instance, just look at all those fluent APIs we have. For instance, here’s a snippet from Fluent NH:

HasMany( pat => pat.Documentos)
.Access.CamelCaseField( Prefix.Underscore )
.AsBag( )
.Cascade.All( )
.Inverse(  )
.KeyColumn( “IdPats” )
.Not.LazyLoad( );

When I write code like this, I’m assuming that all of those methods calls will be executed without errors. Code would need to be much more tedious if we had to check for errors in all those calls. I mean, we have lots of things going on here and we didn’t even went into the IL… It’s really hard to write defensive code for all of this and, in this case, I’m ok with getting an exception in the mappings that ends up terminating my app. Even though this might be a chock for people coming from Win32, the truth is that the productivity gains from doing this kind of things makes it “all right” to rely heavily in exceptions when you’re writing ,NET code.

So, we simply rely in catching known exceptions and understanding that things will go well most of the times. Notice, however, that we do get several interesting assurances from the CLR to mitigate state corruption:

  • a thread can’t be aborted when executing code is inside a catch or finally block;
  • we can rely on CERs (constrained execution regions) to reduce potential exceptions (more about this in a future post);

Even though these assurances do help, there will be times when you end up with corrupted data. In these cases, you probably should terminate your app’s process immediately. I’d say that the bottom line is that managed code has a different philosophy  and it probably is a good option if you’re writing  applications which can be terminated when data corruption occurs.

And that’s it for now. On the next post I’ll present some of the guidelines I try to follow when working with exceptions. Stay tuned for more.

Sep 09

Exceptions in .NET–part IV

Posted in .NET Basics C#           Comments Off on Exceptions in .NET–part IV

In one of the previous posts, I’ve mentioned that the CLR allows an instance of any type to be thrown for an exception (notice that this isn’t allowed by the CLS). In practice, this means that you should be able to throw ints or strings from CLR languages which allow you to write non-CLS compliant code. Since most people will use C# or VB.NET, they think that they’re only allowed to handle Exception derived exceptions and so they think that using the Exception type in a catch block is enough for getting all the exceptions. In other words, people think they would catch all the exceptions by writing this code:

try {
    //some code
}
catch(Exception ex) {
    //catches everything!
    //really???
}

And life was good until you needed to, say, consume some managed C++ code (which, for instance, interacted with some legacy code) that would end up throwing an exception which wasn’t derived from the base Exception type. There was a solution for this problem:

try {
    //some code
}
catch(Exception ex) {
    //catches everything!
    //really??? the answer is nop (<2.0)
}
catch {
    //but this does catch everything
    //(in all versions)
}

By using the catch all block, you are, in fact, catching all exceptions. In other words, the first catch block catches all the CLS compatible exceptions (ie, all Exception derived exceptions) and the second ends up catching all non-CLS compatible exceptions.

Now, the *GOOD NEWS*: you only need to worry about this if you’re running .NET 1.1. And that’s because MS recognized that it needed to “solve” this problem and introduced the RuntimeWrappedException class. Whenever you add the RuntimeCompatibilityAttribute to an assembly (which is done automatically by the C# compiler), all non-CLS compliant exceptions are wrapped by a RuntimeWrappedException object. This means that from 2.0 onwards, you can really catch all exceptions by using the 1st code snippet I’ve shown. Btw, if you want you can get the real thrown exception by accessing the WrappedException property (notice that it references an Object and not an exception).

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

Sep 08

Exceptions in .NET– part III

Posted in .NET Basics C#           Comments Off on Exceptions in .NET– part III

As I’ve said before, you’re supposed to throw an exception when a method cannot complete its task in the way it’s supposed to do it. Before throwing an exception, you should consider two things:

  • which type of exception should you throw?
  • What’s the message that  you’re going to pass into the Exception constructor?

The first step is really important: you should choose an exception type which is meaningful. This is an important decision because you need to consider what will happen when you throw that exception. You should start by looking at the predefined exceptions introduced by .NET. If none of those brings the semantics you’re looking for, then you should probably create a new one. In this case, I’d say that you’re better off by reusing Exception as the base type of the new exception (in fact, if you need to create several exceptions for a specific application, then it’s best to make the hierarchy shallow and wide, ie, with as few base classes as possible).

After choosing the exception type, you should also give some thought about the message you’re passing in when you instantiate that exception. As I’ve said before, this should be a technical message, so don’t be afraid to get into details. Whenever an exception isn’t caught, it will end up as an unhandled exception. In practice, this means that it will probably end up in the event log and, when that happens, this message should be a good starting point for us to know how to handle the current problem. Since this message shouldn’t really be shown to the user, then you probably don’t need to worry about localizing it.

Having said this, I must confess that there is a place where I don’t follow these guidelines: whenever I need to develop WCF services, I tend to catch eventual expected exceptions and transform them into new exceptions, with user friendly messages tackled into its, which are propagated into the client (WPF or Silverlight).

If you decide to create a new Exception derived class, then you can expect to have some tedious work ahead of you. For instance, suppose you’ve got a method which changes the value of a property. Furthermore, suppose you want to improve the semantics of your code by generating an IncorrectNameException whenever the string that is passed in is not limited to 30 characters…In that case, the first thing we need to do is build a new Exception derived class:

[Serializable]
public sealed class IncorrectNameException:Exception, ISerializable {
    private readonly String _incorrectName;
    public IncorrectNameException(String incorrectName = null,
        String message = null,
        Exception innerException = null)
    :base(message, innerException) {
        _incorrectName = incorrectName;
    }
    private const String serializedFieldName = "incorrectName";
    [SecurityPermission(SecurityAction.LinkDemand,
        Flags = SecurityPermissionFlag.SerializationFormatter)]
    private IncorrectNameException( SerializationInfo info,
        StreamingContext context )
        : base( info, context ) {
        _incorrectName = ( String )info.GetValue(
                    serializedFieldName, typeof(String) );
    }

    public override void GetObjectData(SerializationInfo info,
        StreamingContext context) {
        info.AddValue( serializedFieldName, _incorrectName );
        base.GetObjectData(info, context);
    }
    public override string Message {
        get {
            return String.IsNullOrEmpty( _incorrectName )
                       ? base.Message
                       : base.Message + "–>" + _incorrectName;
        }
    }
    public override bool Equals(object obj) {
        var aux = obj as IncorrectNameException;
        if(aux == null) {
            return false;
        }
        return _incorrectName == aux._incorrectName &&
                                 base.Equals( obj );
    }
    public override int GetHashCode() {
        return base.GetHashCode();
    }
    public String IncorrectName { get { return _incorrectName; } }
}

The first interesting point is that we should always make the new exception serializable. Besides applying the Serializable attribute, I’ve also implemented the interface and overrode the GetObjectData inherited from the base Exception class (the serialization part is simple and it will only save/restore the value of the _incorrectName field). In order to personalize the message, I’ve also opted for overriding the Message property so that it appends the name of the field to the message that is passed in the constructor. Btw, and since I’ve mentioned the constructor, notice how I’m taking advantage of optional parameters (instead of writing three constructors, I’m writing just one! – the second one is only there for deserialization purposes). I’ve also overridden the Equals method (and the GetHashCode) to ensure that the comparison between two instances of this type is perfomed correctly.

The code isn’t really complicated, but, as I’ve said before, is rather tedious. If you want, you can also use generics to create a new generic type which you can reuse for all your exceptions types (in this case, it’s clearly a good idea to transform the String parameter into a generic type parameter!).

After defining the class, we’re ready to throw our custom exceptions:

private const Int32 _maxNameSize = 30;
static void ChangeName(String name) {
    if(String.IsNullOrEmpty( name ) ||
        name.Length > _maxNameSize) {
        throw new IncorrectNameException( name, "The passed in name doesn't comply with the maximum name size rule" );
    }
    //rest of the code goes here
}
private static void Main( string[] args ) {
    try {
        ChangeName( "This is a really really huge name so it will probably trigger the exception" );
    }
    catch(IncorrectNameException ex) {
        Console.WriteLine( ex.Message);
    }
}

I couldn’t end this post without mentioning that I’d wouldn’t really create this new exception type in a “real world” application (at least, not in my domain code). The reason is simple: .NET already offers an ArgumentException class which is more than adequate for this kind of error. In fact, I would leave these verifications for the code contract framework, which does a very good job in verifying pre and post conditions and invariants!

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

Sep 08

Exceptions in .NET– part II

Posted in .NET Basics C#           Comments Off on Exceptions in .NET– part II

In the previous post, we’ve started looking at how to use exception in .NET. Even though the CLR allows an instance of any type to be thrown for an exception (more about this in a future post), the truth is that all CLS compliant languages can only catch and throw Exception derived exceptions. That’s why in C# you can only throw and catch exceptions whose type is derived from Exception. The class exposes several interesting properties which you can use to get more information about an exception. The StackTrace property is (probably) one of the more important ones and you can use it from within a catch block to get a string which indicate the methods that were called that led up to the current exception. The following snippet tries to illustrate the use of this property:

static void Method1() {
    Method2(  );
}
static void Method2() {
    Method3(  );
}
static void Method3() {
    throw new Exception("oopss");
}
private static void Main( string[] args ) {
    try {
        Method1();
    }
    catch(Exception ex) {
        Console.WriteLine( ex.StackTrace);
    }
}

And the next image shows the result at runtime:

stack

As you can see, we end up getting the names of all the methods until the one where the exception was thrown. Typically, you won’t be using this info at runtime (ie, don’t show it to the final user!), but you should probably log it so that you can get more info about the exception when the phone starts ringing and someone starts complaining about a crash Smile

If you’ve checked the docs for the Exception class, you’ve probably noticed the Message property. This property (which, btw, is read-only) contains info about the error and it should also explain how to fix the problem. Notice that this isn’t an error friendly message; in fact, it’s a technical message and this means that it shouldn’t be shown to the final user. There’s also a Data dictionary, where you can find a collection of key-value pairs with extra info about the exception (if you’re the middle-man, you can add-more information to this entry and re-throw it). The TargetSite and Source properties reference, respectively,  the method that threw the exception (MethodBase instance) and the name of the assembly that generated the exception. Finally, there’s also an InnerException property which references the previous exception when the current one was raised when handling the first one (we’ll return to this topic in future posts).

If you look at the MSDN docs on exceptions, you’ll notice that there’s a long long hierarchy. Many of the predefined exceptions inherit from ApplicationException or SystemException. Originally, MS recommended that all new exceptions should expand one of these types. The idea was not bad since new applications exceptions should inherit from ApplicationException and system exceptions should expand the SystemException class. If that guideline had been followed, then it would be possible to have catch blocks which would handle all system exceptions or all applications exceptions. Unfortunately, not even MS followed its own guideline! This means that there are system/CLR exceptions which inherit directly from Exception and others which inherit (wtf?) from ApplicationException… Bottom line: these two classes are useless in the real world!

And that’s it for now. In the next post, I’ll present some considerations you should keep in mind when throwing an exception. Stay tuned for more.

Sep 07

Exceptions in .NET–part I

Posted in .NET Basics C#           Comments Off on Exceptions in .NET–part I

After a great month of vacations, it’s time to go back to work.

And this time, I’ll write a couple of posts about exceptions and exception handing in .NET. In .NET, we should generate an exception when a member (method or property) fails to complete its task correctly. Did you noticed the “fails to complete its task correctly” part? It might be a little bit cryptic, so let’s expand it a little more. Say you’ve got a method which needs to change the value of an integer field as a result of some operation performed over another object it receives as a parameter. There might be some assumptions here…for instance, suppose that that method needs the passed in object to be in a specific state…if that doesn’t happen, then you probably should signal that by generating (ie, throwing) an exception. If you’re consuming that method, then you need to know how to handle an exception. And that is what I’ll discuss in this post.

Let’s take a look at an example…the following snippet illustrates how we can handle exceptions in our code:

private void DoSomething() {
    //some code
    //now enter region where we may get
    //an exception
    try {
                
    }
    catch(InvalidCastException ex) {
        //handle an invalid cast exception1
    }
    catch(AmbiguousMatchException ex) {
        //handle an invalid cast exception
    }
    catch(Exception ex) {
        //catch any exception
        //could also ommit the Exception variable
        //but using it lets us log the exception
        //after logging it, you should probably let it flow
        throw;
    }
    finally {
        //clean up everything here
    }
    //code after exception handling block
}

Whenever you write code that might throw an exception, it’s a good idea to wrap it up with a try block and specify the exceptions you’re prepared to handle . As you can see, the DoSomething method can recover from the specifics InvalidCastException and AmbiguousMatchException exceptions (notice the use if the catch keyword). Within a catch block, you’ll probably find some logging code which gets and logs information about the current exception. If you’re not able to recover from the exception, then your best option is simply to rethrow the current exception (as it’s shown in the catch all exception block – the third catch instruction). Don’t be tempted to rethrow the exception by writing throw ex;. If you do that, you’ll end up with a new exception stack and the original error stack is lost!

Having said this, there are several choices you can make at the end of the catch block. You can:

  1. rethrow the exception (as shown in the global catch block in the previous snippet);
  2. create a new (richer) exception and throw it (notice that this is not the same as throw ex; I’ve mentioned before);
  3. simply let the thread “leave” the current catch block.

(We’ll return to this in a future post.)

As you probably know, the catch block code will only be executed when the code in the try block generates an exception. When you have several catch blocks (as in the previous example), the CLR will evaluate them from top to botton in the order they were declared until it finds one whose parenthetical expression’s (ie, the expression which appears after the catch keyword) catch type is compatible with the current exception’s type. That’s why you should always put the more specific exceptions at the top.

If the CLR doesn’t find any matching catch code block associated with the try block where the exception was thrown (this doesn’t happen in the previous example because there’s a catch all code block), then it will keep looking in the current call stack until it finds a matching catch block or until it reaches the top of the call stack. In this last case, you’ll end up with an unhandled exception (more about this in future posts). On the other hand, when the CLR finds a matching catch block, then it will go “back” and execute all the “inner” finally code blocks, starting from within the one associated with the try block that threw the exception and stopping in the catch block that is responsible for handling the current exception. At this point, the CLR executes the code of that catch code block and, only then, will it execute the associated finally block code (provided that you don’t rethrow the current exception or throw a new exception from within the last catch code block!).

Notice that the CLR guarantees that the code in the finally block is always executed (even when there’s no exception), making it the appropriate spot for putting your clean up code. I’d say that the typical example of this is opening a file stream and ensuring it gets closed:

private void OpenAndCloseFile() {
    FileStream str;
    try {
        //open filestream here
        //might throw exception
    }
    catch(IOException ex) {
        //log it
        //just let go
    }
    finally {
        if(str!= null ) {
            str.Close(  );
        }
    }
}

The finally block is optional and it must always be defined after all catch blocks (if there are any). After finishing executing the instructions defined in a finally block, the thread will simply jump into the next instruction.

Before ending this post, there’s still time to mention that it’s possible that some code defined within catch or finally blocks might end up throwing an exception. This is definitely *not* a good thing, but it’s also not the end of the world. When this happens, the CLR’s exception handling mechanism I’ve explained in the previous paragraphs will kick in and execute again as if the exception was thrown after the finally block. Notice, however, that all the information about the original exception is completely lost (it’s as if it didn’t happen).

And I guess this is it for now. Stay tuned for more on exceptions.

Aug 04

Vacation time!

Posted in .NET Basics C#           Comments Off on Vacation time!

As I write this, I’m getting ready for enjoying month away from my daily job. I hope it’s enough for resting, but what I’d really love is to hear from you, my faithful reader Smile.  I know I haven’t really posted much in these last couple of weeks, but I’ve been really busy updating my HTML5 book (it will more examples which try to illustrate how you can combine several new features introduced by HTML5).

Anyways, I believe it’s time to check if any of the content I’m producing has helped you in any way. When I’ve started blogging, I was working mainly in web projects. That is no longer the case today, though I’m still quite interested in that area. If you’ve been following along, you probably recall that I’ve written about several features/areas (which have ranged from web  to some posts about multithreading in windows). So, would you be interested in keep reading more about .NET basic features? Would you prefer more web? Probably, more posts about JavaScript features? What about multithreading? Some Silverlight love maybe? Or would it be great if I kept writing about several areas?

I’m not really a guru in any of these areas but, as I said, I’ve been working in all of them for quite some time now and probably I can still write one or two interesting entries about them. Thanks for your feedback!

Aug 03

Getting started with delegates–part IV

Posted in .NET Basics C#           Comments Off on Getting started with delegates–part IV

Ah, the joy! Almost in vacations, but still one day to go!

We’ve already covered a lot of ground in this delegate series. As we’ve seen, creating a delegate is rather easy: we just need to provide a compatible method and pass it to the delegate constructor which is being initialized. However, there might be times where you don’t have all the required information for creating a new delegate at compile time. Fortunately, our job is not that complicated in these (rare!) cases because the Delegate type introduces several overloads of the CreateDelegate method which helps us in creating new delegate instances at runtime. To illustrate this strategy, we’ll reuse our old Logger delegate definition:

public delegate void Logger( String info );

And now, we’re ready to create dynamic delegates…Let’s start with creating a new delegate for the following static method:

public static class Holder {
    public static void DoIt(String info) {
        Console.WriteLine( "from static: " + info );
    }
}

And now, here’s how we resort to CreateDelegate to create a new delegate which “wraps” the DoIt static method:

var methodInfo = typeof( Holder ).GetMethod( "DoIt",
       BindingFlags.Static | BindingFlags.Public );
var aux = Delegate.CreateDelegate( typeof( Logger ), methodInfo );

After running the previous code, aux references a Delegate instance. At this point, we have two options: we can cast aux to the correct type (not something you’d be able to do when you’re creating delegates like this) or we can rely on Delegate’s DynamicInvoke method:

aux.DynamicInvoke( "Hello!" );

DynamicInvoke ends up calling the delegate’s callback method while sending it the arguments it received. Notice that DynamicInvoce will always ensure that the passed in arguments are compatible with the ones expected by the callback method (if they aren’t, you’ll end up with an exception). As you’re probably expecting, there are also other overloads which you can use for creating delegates that wrap instance methods. Suppose we modify our Holder class so that it looks like this:

public class Holder {
    public void DoIt(String info) {
        Console.WriteLine( "from instance: " + info );
    }
}

And here’s how you can create a new delegate dynamically:

var methodInfo = typeof( Holder ).GetMethod( "DoIt",
       BindingFlags.Instance | BindingFlags.Public );
var aux = Delegate.CreateDelegate( typeof( Logger ), new Holder(), methodInfo );

And now you can invoke the delegate by executing the DynamicInvoke method like we did before.

Before ending, there’s still time to say that you shouldn’t really use the CreateDelegate overloads which use strings (instead of MethodInfo instances) because there’s a chance of getting an ambiguous binding (and that might lead to unpredicted results).

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

Jul 27

Getting started with delegates – part III

Posted in .NET Basics C#           Comments Off on Getting started with delegates – part III

I’ve ended the previous post by saying what we can chain several method calls and that is what we’ll see in this post. With chaining, we can combine several delegates so that calling one of them ends up invoking all of them. A quick example is the best way to see this feature in action (I’m reusing the Logger delegate introduced in the previous posts):

Logger del1 = ( info ) => Console.WriteLine( "del1" );
Logger del2 = ( info ) => Console.WriteLine( "del2" );
Logger del3 = ( info ) => Console.WriteLine( "del3" );
var chain = (Logger)Delegate.Combine( null, del1 );
chain = ( Logger ) Delegate.Combine( chain, del2 );
chain = ( Logger ) Delegate.Combine( chain, del3 );
chain( "hi" );//all delegates are called

I’ve started by declaring three Logger variables which are initialized with three different lambda expressions. After that, I rely on the static Combine method for creating new delegates which “combine” our delegates variables. As you can see, I start by combining del1 with null. When this happens, chain an del1 end up referencing the same memory address. The second Combine call produces more interesting results. Since chain already references a delegate, then this Combine call ends up creating a new delegate whose internal delegate list is initialized with an array that holds the two elements passed to the Combine method.

As you’re probably expecting, the last Combine call will also return a new Delegate but notice that its internal invocation list will have three (not two!) delegate references. You might expect it to have two since our chain variable holds a delegate returned from the second Combine call and you might think that the third call would combine that delegate with del3. However, that doesn’t happen and the last delegate’s internal delegate list will reference our 3 delXXX delegates.  One interesting result of this behavior is that the delegate returned by the second Combine call can be garbage collected since there isn’t any variable referencing it. Btw, you can access this internal delegate list through the GetInvocationList method.

Now, if we invoke chain, all delegates’ methods end up being called. As we’ve seen, calling a delegate through the method syntax is the same as executing the Invoke method. Internally, this method will check the delegate list. When that list is not empty, it will call all delegates present on that list (when the list is empty, it will use the target and method fields for invoking the correct method). You’re probably wondering what happens when our delegate matches a method that returns a value (different from void). Well, in that case, the returned result is the one that is returned by the last delegate that gets executed.

By now, you’re probably thinking that if we can add delegates to the internal list, then we can probably remove them from that list. And that’s true: we can remove a delegate from the list by using the static Remove method. This method expects two parameters: the first references the delegate whose internal list will be searched for; the second identifies the delegate that should be removed from the list ( match is found when a delegate’s target and method fields reference the same objects as the delegate that is passed through the second parameter).

When there are several delegates in the array, the method  will return a new delegate whose internal delegate list has all the remaining delegates. When there’s only one delegate and that delegate is being removed, the method will return a reference to that delegate. It’s also important to understand that Remove will only remove one delegate from the list (even if there are several delegates that match the delegate passed to Remove through the second list). Now that we understand the theory, here’s some code that illustrates the use of the Remove method:

chain = ( Logger ) Delegate.Remove( chain, del2 );
chain( "h" ); //only del1 and del3 get executed

And that’s it for now. Stay tuned for more!

Jul 26

As we’ve seen in the previous post, delegates are really easy to use: you create a new delegate definition and then instantiate it through the new operator, passing it a compatible method reference. However, there’s a lot more going on behind the scenes and that’s what we’ll start seeing in this post. The first thing we need to understand is what happens when the compiler sees a delegate definition like the one show in the next snippet:

public delegate void Logger( String info );

In these cases, the compiler will automatically transform the previous delegate expression into a new class which inherits from MulticastDelegate and looks like this:

public class Logger:MulticastDelegate {
public Logger(Object aux, IntPtr method ) { }
public virtual void Invoke( String info ) { }
public virtual IAsyncResult BeginInvoke(
String info, AsyncCallback cb, Object aux ) { }
public virtual void EncInvoke( IAsyncResult result ){}
}

Notice that you can’t really reuse the MulticastDelegate type in C# because the compiler won’t allow you to use those classes directly from your C# code.

As you can see, a delegate definition expression ends up generating a new class with a new constructor and three methods: Invoke, BeginInvoke and EndInvoke. Lets start with the constructor. The two parameters it receives are used for initializing, respectively, the MulticastDelegate’s target and method private fields. When we use a delegate to call a static method, the target field is initialized to null. On the other hand, when we use it to call an instance method, the target field is initialized with a reference to the object whose instance member is being invoked. In both cases, the private method field references the method that should be called. Btw, you can access these values through the inherited Target and Method properties:

//we’re passing a static method
var aux = newLogger( ConsoleLogger );
Console.WriteLine( aux.Target == null );//true
Console.WriteLine( aux.Method );

If you take a look at the MulticastDelegate’s code, you’ll quickly notice that it doesn’t define these properties. In fact, these properties are exposed by the Delegate type, which is used as base by the MulticastDelegate type. To be honest, I really don’t have any good explanation for having two delegate classes since our delegates definitions end up always creating new classes which expand the MulticastDelegate type (and no, you can’t either create a new type which uses Delegate as a base type in C#)…Going back to the snippet, I believe I should mention  that the Method property returns a reference to a MethodInfo instance (this type provides us access to a method metadata – this means you also use it, for instance, to get the name of the method that is being invoked).

Now that we understand what happens when we instantiate a new delegate, it’s type to see how invocation works. So, what happens when the compiler finds something like this:

var aux = newLogger( ConsoleLogger );//seen this
aux( “hello” );//what happens here?

If we take a peek at the generated IL, we’ll find the following code:

IL

As you can see, our aux method called is translated into an instance Invoke method call. Btw, nothing prevents us from doing that call from our C# text:

aux.Invoke( “hello” );

And yes, it does compile without any errors (thank you for asking!). Internally, Invoke will use the information returned by the Target and Method properties to invoke the method. As you’ve probably inferred, BeginInvoke and EndInvoke can be used to invoke the methods asynchronously (and have been used for several years as a way to run code in parallel). We’ll probably return to the async methods in a future post…

But there’s more…the astute reader has probably noticed the “Multicast” string in the MulticastDelegate name’s type. It’s obvious that using indirection to invoke a method is really powerful, but what about using a delegate to chain the execution of several methods? We’ll see how we can do this in the next post. Stay tuned for more.