Dear visitor, thanks for stopping by! If you want, you can follow all updates on Snowball.be via RSS. You can also follow me on Twitter or Facebook. More interesting posts from other Microsoft Regional Directors can be found at The Region.
Gill Cleeren     .net | .NET 4 | C# | Silverlight | sl4 | VS2010     April 12, 2010    

After beta’s and one RC release, starting today, we can get our hands on Visual Studio 2010 RTM. Just hours ago, Microsoft held a keynote on the release of their flagship IDE, Visual Studio 2010. This release coincides with the release of .NET 4.0 and of course Silverlight 4, which has its official launch event tomorrow. This marks probably the largest release ever for developers from Microsoft.

 image

I need it badly

Visual Studio 2010 is like honey, developers swarm to it. It’s understandable that you want to get your hands on the bits. Where can you get them?
If you’re an MSDN subscriber, you’re in luck, as you can get all the bits from the MSDN subscription site. (http://msdn.microsoft.com/subscriptions)
If you are not, you have the following options:

image

 

Why you need it

If I wanted to make a list of reasons why you should be upgrading to Visual Studio 2010, I would be up all night I think. Since it’s quite late already, I’m going to make an all-but-complete list with my top features that make Visual Studio 2010 an not-to-miss upgrade. (For the complete list – you’re warned, it’s very complete – take a look here: http://msdn.microsoft.com/en-us/library/bb386063(VS.100).aspx)

The IDE looks really stylish!

Upon opening Visual Studio 2010 for the first time, you’ll immediately notice that something happened… Something big. No longer the traditional grey interface, but an exciting new look for the place you spend all your development hours in. Built entirely in WPF, the new shell offers plenty of extension points so you can make it feel even more like home.

image

New IDE features

I personally like the Navigate To function a lot (I blogged about it yesterday here: Visual Studio 2010 Tip- Navigate to functionality). Another one I like is the zoom in/out we can now do in the code editor. This is a real life-saver when doing demos on stage or when showing someone some code. Simply keep CTRL key pressed and rotate that mouse wheel of yours. For people who work on multiple monitors, Visual Studio now supports this much better!

Some other nice features:

  • Improved IntelliSense
  • Highlight references
  • Stub generation

New framework and languages

Visual Studio 2010 comes packed with new releases.

  • Silverlight 4 :) More on this at the launch event tomorrow!
  • C# 4.0 adds interesting new features to the language (more here). Also VB.net developers aren’t left outside in the cold, their favorite language gets an upgrade as well to Visual Basic 2010.
  • ASP.NET 4.0 as well as MVC 2 are born! If you want to get an overview of what’s new, download my talk of DevDays 2010 here. Most striking new features in WebForms 4 are client IDs, control over ViewState and more control over the HTML that’s being rendered.
  • Entity Framework makes a jump and goes straight to v4.
  • WCF and WF both get an upgrade to v4 as well.
  • TFS installation gets really simple using TFS Basic.
  • F# is now available for the functional programming needs.
  • SharePoint templates!

I want more

Not enough reading material for your brain? A free ebook is made available “Moving to Visual Studio 2010” here.

Warnings here!

Something to watch out for: currently, the Windows Phone 7 tools do not work with the RTM version of 2010. Read more on this here: http://forums.silverlight.net/forums/t/175181.aspx 

image

  Posted on: Monday, April 12, 2010 11:54:13 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 23, 2009    

Yes, I made it :) Welcome to this last post in my Silverlight Advent Calendar! From December 1st until today, December 24th, I have created each day, a Silverlight article. When I first thought about it, I feared there would be at least one day I would not be able to create my post. Well, this didn’t happen, and this means that after 24 articles, we have finally arrived at Christmas Eve. I really hope you enjoyed these posts and I’ll sure be doing something similar in the future!

On a “real” advent calendar, on December 24th, the final day of the calendar, you get a special surprise: a bigger image, a bigger gift or a larger chunk of chocolate than on other days. Well, I thought this needed to be the case in my advent calendar as well, so I decided to end my series with a special post. It gives a preview of something that can in much more detail be found in my upcoming book AND it brings some more Christmas spirit on this day: a Flickr Christmas image browser. All free as my gift to you!

Below is the interface of the application.

image

We’re in luck when working with Flickr: it exposes a cross-domain file so we can access their API services from a client Silverlight application, even without running with elevated permissions! Therefore, we do not need to create a service layer that sits in between our application and Flickr’s services.

When clicking on the Get Pictures button, we load thumbnails into a templated StackPanel. When clicking on any of these thumbnails, the large image is loaded. To store the information needed for a thumbnail, I created a class called SmallFlickrImage.

public class SmallFlickrImage
{
  public string ImageId { get; set; }
  public string FarmId { get; set; }
  public string ServerId { get; set; }
  public string Secret { get; set; }
 
  public string ImageUrl
  {
    get
    {
      return string.Format(
        "http://farm{0}.static.flickr.com/{1}/{2}_{3}_m.jpg", 
        FarmId, 
        ServerId, 
        ImageId, 
        Secret
        );
    }
  }
}

In the click event, we perform a service call to Flickr. To call Flickr’s API, you’ll need an API key which can be obtained for free at http://www.flickr.com/services/api/. Once obtained, you need to embed this key in each request your application will perform with Flickr. Also on this site, you’ll find a complete overview of all available methods. Here, I’m using the flickr.photos.search method, which accepts a search string and returns me an XML response, containing all the information I need to display images in my client side application.

Working with Flickr is a typical example of a REST service. When working with these services from Silverlight, we actually need to do 3 steps:

  • Create a URL
  • Send a request to this URL
  • Accept the response, mostly in XML, sometimes in JSON

The URL is constructed as follows (as directed by Flickr):

string searchUrl = 
  "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}
   &text=christmas tree snow";

To send a request to this URL, we can use either the WebClient, or the HttpWebRequest. WebClient is sufficient (there are cases where this is not the case, I spent many pages to this topic in my book ;) ). Working in Silverlight with WebClient is identical to working with this class in the full .NET framework. One thing though: just like any interaction with a service, the service call is to be done asynchronously. The code below sends a request to Flickr:

private void GetPicturesButton_Click(object sender, RoutedEventArgs e)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += 
      new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri(string.Format(searchUrl, api_key)));
}

In the callback, which is invoked automatically when the service returns, using some very simple LINQ-To-XML, we can parse the results. The returned XML is always of the same format and can be seen as the contract between Flickr and my application. Because we cannot set the Source property of an Image control directly, we need to go around using a BitmapImage.

protected void client_DownloadStringCompleted(object sender, 
  DownloadStringCompletedEventArgs e)
{
  XDocument xml = XDocument.Parse(e.Result);
 
  var photos = from results in xml.Descendants("photo")
               select new SmallFlickrImage
               {
                 ImageId = results.Attribute("id").Value.ToString(),
                 FarmId = results.Attribute("farm").Value.ToString(),
                 ServerId = results.Attribute("server").Value.ToString(),
                 Secret = results.Attribute("secret").Value.ToString()
               };
 
  foreach (var photo in photos)
  {
    Image image = new Image();
 
    BitmapImage bitmapImage = new BitmapImage(new Uri(photo.ImageUrl, UriKind.Absolute));
    image.Source = bitmapImage;
    image.Width = 160;
    image.Height = 160;
    image.Stretch = Stretch.Uniform;
    image.Tag = photo;
    image.Margin = new Thickness(3);
    image.HorizontalAlignment = HorizontalAlignment.Center;
    image.MouseLeftButtonDown += new MouseButtonEventHandler(img_MouseLeftButtonDown);
    PicListBox.Items.Add(image);
  }
}

At this point, the ListBox is filled. This ListBox is templated; the code for this can be seen in the sample code download.

When clicking (we attached a MouseLeftButtonDown event on each dynamically added image) on an image, we’ll load the "full” image into an Image control. This requires some code, mostly concerning which type of URL is used by Flickr for the image.

void img_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
  Image img = sender as Image;
  SmallFlickrImage smallFlickrImage = img.Tag as SmallFlickrImage;
  if (smallFlickrImage != null)
  {
    WebClient detailClient = new WebClient();
    detailClient.DownloadStringCompleted += 
      new DownloadStringCompletedEventHandler(detailClient_DownloadStringCompleted);
    detailClient.DownloadStringAsync(
      new Uri(string.Format(detailUrl, api_key, smallFlickrImage.ImageId)));
  }
}
 
void detailClient_DownloadStringCompleted(object sender, 
  DownloadStringCompletedEventArgs e)
{
  XDocument xmlDocument = XDocument.Parse(e.Result);
  XElement photoElement;
  Uri detailImageUrl;
 
  if (xmlDocument.Descendants("photo").Count<XElement>() > 0)
  {
    photoElement = xmlDocument.Descendants("photo").First<XElement>();
 
    string serverId = photoElement.Attribute("server").Value;
    string farmId = photoElement.Attribute("farm").Value;
    string imageId = photoElement.Attribute("id").Value;
    string secret;
    
    if (photoElement.Attribute("originalsecret") != null)
    {
      secret = photoElement.Attribute("originalsecret").Value;
      detailImageUrl = new Uri(string.Format
        ("http://farm{0}.static.flickr.com/{1}/{2}_{3}_o.jpg", 
          farmId, 
          serverId, 
          imageId, 
          secret)
         );
    }
    else
    {
      secret = photoElement.Attribute("secret").Value;
      detailImageUrl = new Uri(string.Format
        ("http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg", 
          farmId, 
          serverId, 
          imageId, 
          secret)
         );
    }
 
    BitmapImage bitmapImage = new BitmapImage(detailImageUrl);
    DetailImage.Source = bitmapImage;
  }
}

 

With that, the sample is working!

The complete code sample can be downloaded here: SLChristmasFlickr.zip (31.34 KB)

MERRY CHRISTMAS!

  Posted on: Thursday, December 24, 2009 12:50:15 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 20, 2009    

In the before-last post of my Silverlight Advent Calendar, I would like to spend some time with a Silverlight 3 feature that’s most helpful in real world projects: merged resource dictionaries. By most helpful, I mean that in real applications, resource files can become really really big. Files of 1000 lines of pure mark-up are no exception and are really hard to find your way in.

Silverlight 3 added support for merged dictionaries. Basically, using these, we can split resources over several files, dictionaries. Using them though is nothing different than using resources located in App.xaml or Resources of the current page/control.

Let’s take a look at using these merged resource dictionaries. I created some styles to style the ChristmasSong application we have been using a few times already.

 

image

In the beginning of this series, we already looked at implicit styles. For this application, I’m defining a few of these, meaning that this very project will only work for Silverlight 4. Of course, the merged dictionary function works also in Silverlight 3.

To define a resource dictionary, in the project, we need to add a XAML file (either via creating an empty text file and renaming the extension or creating a new user control and deleting the *.cs file). In this file, we can create a ResourceDictionary element. Below is the XAML code for the implicit styles, which I grouped into a file called DefaultStyles.xaml. I created a default style for a Button, TextBlock and TextBox.

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Button">
        <Setter Property="Foreground" Value="Black" />
        <Setter Property="Background" Value="Red" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="HorizontalAlignment" Value="Center"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
    </Style>
 
    <Style TargetType="TextBlock">
        <Setter Property="Foreground" Value="Green" />
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="HorizontalAlignment" Value="Left"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
        <Setter Property="Margin" Value="2"></Setter>
    </Style>
 
    <Style TargetType="TextBox">
        <Setter Property="Width" Value="150" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="HorizontalAlignment" Value="Center"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
        <Setter Property="Margin" Value="2"></Setter>
    </Style>
</ResourceDictionary>

Next, I created a second ResourceDictionary which has just one Style, designed for the title, in a file called SpecificStyles.

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="TextBlock" x:Key="TitleStyle">
        <Setter Property="Foreground" Value="Red" />
        <Setter Property="FontStyle" Value="Italic"></Setter>
        <Setter Property="FontWeight" Value="Bold" />
        <Setter Property="FontSize" Value="28" />
        <Setter Property="HorizontalAlignment" Value="Center"></Setter>
        <Setter Property="VerticalAlignment" Value="Center"></Setter>
    </Style>
</ResourceDictionary>

Now we need to let our application know about these resources. To do so, I have in the App.xaml added the following code. In the MergedDictionaries element, we link the seperate XAML files.

<Application 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  x:Class="SLMergedDictionaries.App"
  >
  <Application.Resources>
    <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary 
          Source="/SLMergedDictionaries;component/DefaultStyles.xaml">
        </ResourceDictionary>
        <ResourceDictionary 
          Source="/SLMergedDictionaries;component/SpecificStyles.xaml">
        </ResourceDictionary>
      </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
  </Application.Resources>
</Application>

We can now use the styles declared in the dictionaries just like we would do with regular defined styles.

The complete sample can be downloaded here: SLMergedDictionaries.zip (310.39 KB)

  Posted on: Monday, December 21, 2009 12:46:11 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 20, 2009    

Next to the full support of the data binding engine for the IDataErrorInfo interface, Silverlight 4 adds a new interface called INotifyDataErrorInfo, offering more options for particular scenario's. In this post, we’ll look at a small example using this interface.

IDataErrorInfo allows retrieving the error on a per-property basis. It’s not possible however to validate all properties of the entity in one go. This becomes possible with the INotifyDataErrorInfo. Let’s look at the interface first.

public interface INotifyDataErrorInfo
{
    bool HasErrors { get; }
 
    event EventHandler ErrorsChanged;
 
    IEnumerable GetErrors(
                    string propertyName);
}

This interface has some nice advantages. As said, we can check if the entity as a whole is in an invalid state through the HasErrors property. Retrieving the errors using the GetErrors can now retrieve other things than just strings which was all that we could do with the IDataErrorInfo. On top of that, a property can have more than just one validation error at the same time

The ErrorsChanged event can come in handy if there’s a long running process needed to perform validation: assume that for some validation, we need to go to the database over a service. The ErrorsChanged event allows us to notify the UI if the validation errors change. If ValidatesOnNotifyDataErrors is set to true on the UI, Silverlight will listen for the ErrorsChanged event and will display any errors if they are added afterwards.

That’s it for this interface, let’s now look at it in an example. I have changed the example created for the IDataErrorInfo to work with INotifyDataErrorInfo, so the interface has remained the same.

The errors I want to return to my interface are more than just strings. I created a custom error as follows:

public class ChristmasSongError
{
    public ErrorLevel Severity{ get; set; }
    public string ErrorName { get; set; }
    public string ErrorMessage { get; set; }
 
    public override string ToString()
    {
        return ErrorName + ": " + ErrorMessage;
    }
}

The ChristmasSong class now implements the INotifyDataErrorInfo interface. Let’s focus on the Title property. When its value is set, it calls a validation method. In this method, I create an instance of the custom error, specifying all the property values. If there’s an error, here the title being empty, I add it to a Dictionary called errors using the AddError method. If validation is satisfied, it’s removed using the RemoveError method. The errrors Dictionary is used so it is possible for each property to have more than one error: each property has as its value a List.

public class ChristmasSong : INotifyDataErrorInfo
{
    private string title;
    private string performedBy;
    private TimeSpan duration;
    private DateTime published;
 
    private string error;
 
    public Dictionary<string, List> errors = 
      new Dictionary<string,List>();
 
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(
                    this, new PropertyChangedEventArgs(propertyName));
    }
 
    public string Title
    {
        get
        {
            return title;
        }
        set
        {
            title = 
                    value;
            ValidateTitleProperty();
        }
    }
 
    private void ValidateTitleProperty()
    {
        ChristmasSongError christmasSongError =
new ChristmasSongError() 
        { Severity = ErrorLevel.Error, ErrorName =
"TitleRequired", 
          ErrorMessage = 
                    "Title should not be empty" };
        if (string.IsNullOrEmpty(title))
        {
            AddError(
                    "Title", christmasSongError);
        }
        else
        {
            RemoveError(
                    "Title", "TitleRequired");
        }
    }
 
    public string PerformedBy
    {
        get
        {
            return performedBy;
        }
        set
        {
            performedBy = 
                    value;
            ValidatePerformedByProperty();
        }
    }
 
    private void ValidatePerformedByProperty()
    {
        ChristmasSongError christmasSongError =
new ChristmasSongError() 
        { Severity = ErrorLevel.Error, ErrorName =
"PerformedByRequired", 
          ErrorMessage = 
                    "The artist should not be empty" };
        if (string.IsNullOrEmpty(performedBy))
        {
            AddError(
                    "PerformedBy", christmasSongError);
        }
        else
        {
            RemoveError(
                    "PerformedBy", "PerformedByRequired");
        }
    }
 
    public TimeSpan Duration
    {
        get
        {
            return duration;
        }
        set
        {
            duration = 
                    value;
            ValidateDuration();
        }
    }
 
    private void ValidateDuration()
    {
        ChristmasSongError durationNullError =
new ChristmasSongError() 
        { Severity = ErrorLevel.CriticalError, ErrorName =
"DurationNull", 
          ErrorMessage = 
                    "The duration should not be empty" };
        ChristmasSongError durationTooLongError =
new ChristmasSongError() 
        { Severity = ErrorLevel.Error, ErrorName =
"DurationTooLong", 
          ErrorMessage = 
                    "The duration is too long" };
        
        if (duration == TimeSpan.Zero)
        {
            AddError(
                    "Duration", durationNullError);
        }
        else
        {
            RemoveError(
                    "Duration", "DurationNull");
        }
 
        if (duration.TotalSeconds > 500)
        {
            AddError(
                    "Duration", durationTooLongError);
        }
        else
        {
            RemoveError(
                    "Duration", "DurationTooLong");
        }
    }
 
    public DateTime Published
    {
        get
        {
            return published;
        }
        set
        {
            published = 
                    value;
            VaidatePublished();
        }
    }
 
    private void VaidatePublished()
    {
        ChristmasSongError publishedTooLow =
new ChristmasSongError() 
        { Severity = ErrorLevel.CriticalError, ErrorName =
"PublishedTooLow", 
          ErrorMessage = 
                    "The date is too small" };
        ChristmasSongError publishedTooHigh =
new ChristmasSongError() 
        { Severity = ErrorLevel.CriticalError, ErrorName =
"PublishedTooHigh", 
          ErrorMessage = 
                    "The date is too high" };
 
        if (published < new DateTime(1900, 1, 1))
        {
            AddError(
                    "Published", publishedTooLow);
        }
        else
        {
            RemoveError(
                    "Published", "PublishedTooLow");
        }
 
        if (published > new DateTime( 2010, 1, 1))
        {
            AddError(
                    "Published", publishedTooHigh);
        }
        else
        {
            RemoveError(
                    "Published", "PublishedTooHigh");
        }
    }
 
    private void AddError(string propertyName, ChristmasSongError error)
    {
        
 
        if (!errors.ContainsKey(propertyName))
        {
            errors.Add(propertyName, 
                    new List() { error });
        }
        else// adding the error to the already existing list
        {
            var list = errors[propertyName];
            list.Add(error);
        }
 
        if (ErrorsChanged != null)
            ErrorsChanged(
                    this, new DataErrorsChangedEventArgs(propertyName));
    }
 
    private void RemoveError(string propertyName, string errorName)
    {
        if (errors.ContainsKey(propertyName))
        {
            var christmasSongError = errors[propertyName]
                .Where
(e => e.ErrorName == errorName).FirstOrDefault();
            var list = errors[propertyName];
            list.Remove(christmasSongError);
 
            if (list.Count == 0)//no more errors for this property 
            {
                errors.Remove(propertyName);
            }
 
            if (ErrorsChanged != null)
                ErrorsChanged(
                    this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
 
    public event EventHandler ErrorsChanged;
 
    public System.Collections.IEnumerable GetErrors(string propertyName)
    {
        if (string.IsNullOrEmpty(propertyName))//retrieve
                        errors for entire entity
        {
            return errors.Values;
        }
        else
        {
            if (errors.ContainsKey(propertyName))
                return errors[propertyName];
            return null;
        }
    }
 
    public bool HasErrors
    {
        get
        {
            if (errors.Count == 0)
                return false;
            return true;
        }
    }
}

With the entity in place, we can look at the UI. The XAML code is similar to the IDataErrorInfo example, although we should now use the ValidatesOnNotifyDataErrors and set it to True. Below is part of the code, for the entire listing, see the download.

<TextBox x:Name="TitleTextBox" Grid.Row="1" Grid.Column="1" Width="200" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="2"

Text="{Binding Path=Title,Mode=TwoWay,ValidatesOnNotifyDataErrors=True,NotifyOnValidationError=True}" />

The complete sample can be downloaded here: SLINotifyDataErrorInfo.zip (602.56 KB)

  Posted on: Monday, December 21, 2009 12:42:27 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 20, 2009    

Services and data access are the focus of the book I’m writing (more very very soon!). Working with services to get data into a Silverlight application is so vital, it should be code that’s known by every Silverlight developer by heart. Working with duplex bindings is somewhat more complicated. However, there are situations in which duplex communication is really necessary. Think of the typical example: a stock application that should send stock updates to the client without the client requesting for an update.

Duplex communications are possible with WCF. They “seem” initiated by the server: the service will send updates without the client requests the service to do so. This way, the client can receive updates whenever new information is available on the server (new stock info that becomes available) and act accordingly. I put seem between quotes. The reason for that is that a duplex binding is in fact still a normal request/receive process. Initially, the client has to do a request to the service and from then on, the service can send its updates to the client.

In the example I have created for this post, I created an application that posts updates about snow throughout Belgium (while writing this article, it has snowed quite a lot in Belgium, so that’s where the inspiration came from and Tienen is where I live :) ). Below is a screenshot.

image

Of course, you’re here to learn something and see some code, right? No problem! Let’s first focus on the service. For the data exchange, I created a small type called SnowUpdate.

public class SnowUpdate
{
    public string Location { get; set; }
    public double centimeter { get; set; }
}

One very important thing that we need to do, is adding a reference to an assembly available in the Silverlight SDK called System.Service.PollingDuplex.dll. By default, it’s installed in C:\Program Files (x86)\Microsoft SDKs\Silverlight\v4.0\Libraries\Server. Add a reference to this assembly. (Note the x86, that’s because I’m running 64bit).

The contract of the service makes it clear that we are working with a duplex service. There are some special things to note in this code. As you can see, two interfaces are defined here. The first one is the regular contract, the second one is what’s called the callback contract and defines the contract for the call to the client.

Also note that both OperationContracts have IsOneWay set to true. For the Connect method, we’re actually saying: a client can call Connect to make itself known to the service but it expects no response, hence the IsOneWay.

[ServiceContract(Namespace = "Silverlight", CallbackContract = typeof(ISnowServiceClient))]
public interface ISnowService
{
    [OperationContract(IsOneWay = true)]
    void Connect();
}
 
[ServiceContract]
public interface ISnowServiceClient
{
    [OperationContract(IsOneWay = true)]
    void SendSnowUpdate(SnowUpdate snowUpdate);
}

In the service implementation, I have created a Timer, which will periodically send a new message to the client. The OperationContext.Current.GetCallbackChannel gives us access to the callback channel which we can use to send messages to the client side. On a tick of the Timer, we’re sending a message.

private ISnowServiceClient client;
private Timer timer;
 
public void Connect()
{
    client = OperationContext.Current.GetCallbackChannel<ISnowServiceClient>();
    timer = new Timer(new TimerCallback(TimerTick), null, 500, 5000);
}
 
void TimerTick(object state)
{
    try
    {
        if (client != null)
        {
            client.SendSnowUpdate(GetLatestUpdate());
        }
    }
    catch (Exception)
    {
 
        client = null;
        timer.Dispose();
    }
}

With that, the service code is done, but it does require some specific configuration code to work. Take a look at the sample for this code. We can now look at the client code. The process to add a service reference is exactly the same, although you’ll notice that the ServiceReferences.clientconfig file remains empty (which it does not when referencing a normal service). Therefore, the code that we need to write is somewhat more complex: we have to create the binding and the address from code and pass this along with the proxy instantiation. Below you can see the client-side code.

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  EndpointAddress address = new EndpointAddress("http://localhost:59485/SnowService.svc");
 
  CustomBinding binding = new CustomBinding(
    new PollingDuplexBindingElement(),
    new BinaryMessageEncodingBindingElement(),
    new HttpTransportBindingElement());
  
  client = new SLDuplexSnow.SnowService.SnowServiceClient(binding, address);
 
  client.SendSnowUpdateReceived += 
    new EventHandler<SLDuplexSnow.SnowService.SendSnowUpdateReceivedEventArgs>
     (client_SendSnowUpdateReceived);
    client.ConnectAsync();
}
 
void client_SendSnowUpdateReceived(object sender, 
  SLDuplexSnow.SnowService.SendSnowUpdateReceivedEventArgs e)
{
    SnowDetailsGrid.DataContext = e.snowUpdate;
}

Note that we are calling ConnectAsync to let the service know about the client so it can send updates to it BUT we are handing SnowUpdateReceived events.

NOTE: This sample is written for Silverlight 3/VS2008. At this point, I have issues with VS2010 when generating the client proxy with SL4/VS2010 when using a duplex service.

The complete code can be downloaded here: SLDuplex.zip (111.91 KB)

  Posted on: Monday, December 21, 2009 12:38:33 AM (Romance Standard Time, UTC+01:00)   |   Comments [4]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 19, 2009    

In today’s post, we’ll take a look at Silverlight’s Isolated Storage, a feature already available in Silverlight since version 2. With this post, I want to show all there is possible with this handy option.

We all know cookies, small text files that are stored on our machines by sites. Most of the time, the goal of a cookie, is storing informational data for next visits of the user to that particular site. This data can vary from login information to perhaps a background color the user favors. Cookies are limited to containing just plain text as well as in size.

Isolated storage does not differ that much from cookies. It’s basically a file store for Silverlight: Silverlight applications can store in the Isolated Storage files during a session and retrieve them in a later session. Isolated storage is a per-user per-application storage, meaning that when userA works with SilverlightAppA, he’ll have a different isolated storage from userB working with the same application. Isolated storage information is not deleted when you clear your temporary internet files, it can be deleted through the Silverlight configuration, as shown below.

image

We can use isolated storage in a number of ways. Let’s take a look at the sample for this post. Below is a screenshot of the very simple UI I created for this sample. It allows a user to enter a text, representing his preferred background color for the application. We’ll store this value using the IsolatedStorage. Secondly, using another feature called IsolatedStorageSettings, I’m allowing the user to store a second value, which is used for the color of a StackPanel ( the blue bar in the screenshot).

image

First, let’s look at the code for the background color, using the regular IsolatedStorage. Below you can see the code. Working with IsolatedStorage is done using the IsolatedStorageFile class. It defines among others, the GetUserStoreForApplication static method, which returns the data store, for the specific user and the current application. From there on, working with IsolatedStorage is similar to working with the regular file system. Isolated storage is not to be seen as one file, it’s an entire file system, that can contain directories and files. In this code, we are creating using System.IO code a file called color.txt and writing some data to this file.

private void ColorButton_Click(object sender, RoutedEventArgs e)
{
  try
  {
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
 
    using (IsolatedStorageFileStream fs = isoStore.CreateFile("color.txt"))
    {
      StreamWriter writer = new StreamWriter(fs);
      writer.Write(ColorTextBox.Text);
      writer.Close();
    }
    ChangeColor(ColorTextBox.Text);
  }
  catch (Exception)
  {
    //handle error here, not for demo
  }
}

On load of the application, we need to check if this file already exists and if yes, read the file and set the background to that specific color. This is shown in the code below.

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
  try
  {
    IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
 
    if (isoStore.FileExists("color.txt"))
    {
      using (IsolatedStorageFileStream fs = isoStore.OpenFile("color.txt", FileMode.Open))
      {
        StreamReader reader = new StreamReader(fs);
        ChangeColor(reader.ReadLine());
        reader.Close();
      }
    }
  }
  catch (Exception)
  {
    //handle error here, not for demo
  }
}

In ASP.NET, we have the Application and Session objects, which provide an easy and quick way to store information between requests. Through a feature of the IsolatedStorage, we can have something quite similar. The IsolatedStorageSettings allow us a key/value lookup to store data. We don’t have to write code to actually store the files, it does that for us. Take a look at the following code. We allow the user to store a second string for the background of the StackPanel.

private void AppColorButton_Click(object sender, RoutedEventArgs e)
{
  IsolatedStorageSettings.ApplicationSettings["AppColor"] = AppColorTextBox.Text;
  ChangeStackPanelColor(AppColorTextBox.Text);
}

Using this approach, we say for the AppColor value, store the contents of the TextBox as value. Behind the scenes, this is persisted, so it can be retrieved after the application has been shutdown (it is thus not stored in application memory). Retrieving the value can be done as follows:

if (IsolatedStorageSettings.ApplicationSettings.Contains("AppColor"))
{
  string appColor = IsolatedStorageSettings.ApplicationSettings["AppColor"].ToString();
  ChangeStackPanelColor(appColor);
}

The complete sample can be downloaded here: SLIsolatedStorage.zip (30.84 KB)
  Posted on: Sunday, December 20, 2009 12:26:40 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 19, 2009    

The day before yesterday, we looked at an sample with Twitter: we retrieved the tweets from the public timeline in an OOB trusted application. The public timeline feed on Twitter requires no credentials to be passed along. Some other feeds however do, such as the user timeline (containing your own tweets) and the friends timeline (containing the tweets of your friends).

Up until Silverlight 4, passing credentials to a service was not supported. Silverlight 3 added support for the ClientHttp stack, however, it was not possible to modify the authorization header, resulting in it being impossible to pass credentials. Silverlight 4 adds this support however. In combination with the support for cross-domain access for services for Silverlight if they are executed with elevated permissions, we can easily build a more complete Twitter client in Silverlight. We already did some work on this application, we will now extend it to make it possible to execute requests to services that require authorization.

Below is a screenshot of the modified application, running OOB as a trusted application.

image

We will not be looking at the code for the public timeline, that was already covered two days ago. Instead, let’s focus on the code we need to write to make the authorized request possible. Of course, we need the user’s credentials, therefore, I added a username/password field.

When clicking on the Submit button, two request are being executed:

Here’s the code for the first one. Note a few things. Passing credentials is only possible if using the ClientHttp stack. This is enabled by WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp). This selects the ClientHttp stack instead of the browser http stack, which is used by default. To pass the credentials, we use the Credentials property and set it to an instance of NetworkCredentials. Here’s the code.

WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
//try finding the user tweets and friends tweets
string userTimeLine = "http://twitter.com/statuses/user_timeline/" + 
  UserNameTextBox.Text + ".xml";
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(UserNameTextBox.Text, 
  PasswordTextBox.Password);
client.UseDefaultCredentials = false;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler
  (user_DownloadStringCompleted);
 
client.DownloadStringAsync(new Uri(userTimeLine, UriKind.Absolute));

A very important line is setting the UseDefaultCredentials to false. If we set it to true, Silverlight will pass the credentials of the logged-on user on the machine (NTLM). If this is the wanted behavior however, simply setting this property to true will of course enable this.

The complete code for this application can be downloaded here:

SLTwitterCredentials.zip (82.89 KB)
  Posted on: Saturday, December 19, 2009 9:24:22 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 18, 2009    

After looking at Twitter yesterday, we have arrived at another data binding-related feature new in Silverlight 4, namely the support for the IDataErrorInfo interface.

The fact that Silverlight supports this interface now, means we can fully use it to help with the display of validation errors in a data binding scenario. The interface itself is quite simple, as shown below:

public interface IDataErrorInfo
{
    string Error { get; }
 
    string this[string columnName] { get; }
}

When we are binding an object of a class that implements the IDataErrorInfo, Silverlight will automatically check each field for validation errors using the indexer. In here, we can write validation code that will check if the specified value is valid and if not, return the error message for that field. Silverlight will then automatically display the error for the field.

I have created a small sample that does exactly that. Being it almost Christmas, I have created a sample where the user can enter his christmas music collection, as shown below.

image

The type we are binding to is called ChristmasSong. This class implements both the INotifyPropertyChanged and the IDataErrorInfo interfaces. Both have been implemented in the code below. In the indexer, we are checking per column if the entered value is valid. If not, we are returning a message containing the validation error. Note that when we are entering “Last Christmas” by “Wham”, the application will not accept it! (Sorry to all Wham fans ;-) )

public class ChristmasSong : IDataErrorInfo, INotifyPropertyChanged
{
    private string title;
    private string performedBy;
    private TimeSpan duration;
    private DateTime published;
 
    private string error;
 
    public event PropertyChangedEventHandler PropertyChanged;
 
    protected void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
 
    public string Title
    {
        get
        {
            return title;
        }
        set
        {
            title = value;
            NotifyPropertyChanged("Title");
        }
    }
 
    public string PerformedBy
    {
        get
        {
            return performedBy;
        }
        set
        {
            performedBy = value;
            NotifyPropertyChanged("PerformedBy");
        }
    }
 
    public TimeSpan Duration
    {
        get
        {
            return duration;
        }
        set
        {
            duration = value;
            NotifyPropertyChanged("Duration");
        }
    }
 
    public DateTime Published
    {
        get
        {
            return published;
        }
        set
        {
            published = value;
            NotifyPropertyChanged("Published");
        }
    }
 
    public string Error
    {
        get { return error; }
    }
 
    public string this[string columnName]
    {
        get 
        {
            string error = string.Empty;
            switch (columnName)
            {
                case "Title":
                    if(string.IsNullOrEmpty(title))
                        error = "Title can not be blank";
                    break;
                case "PerformedBy":
                    if(string.IsNullOrEmpty(performedBy))
                        error = "The artist should be filled in";
                    else if(performedBy.Equals("Wham") && title.Equals("Last Christmas"))
                        error = "You should NOT be entering that song to your collection!";
                    break;
                case "Duration":
                    if(duration.TotalSeconds > 600)
                    error = "A song can not be longer than 10 minutes";
                    break;
                case "Published":
                    if (Published > new DateTime(2010, 1, 1))
                        error = "You found a song from the future?";
                    else if (published < new DateTime(1900, 1, 1))
                        error = "That's a bit too old, isn't it?";
                    break;
            }
            return error;
        }
    }
}

We can now bind our UI to an instance of this type. Below is the XAML code for the Grid containing the fields. Note especially the data binding expression, where I’m stating the fields should be reporting the error back. For spacing reasons, I only pasted the Title field, the others are similar.

<TextBlock x:Name="TitleTextBlock" Text="Title" Grid.Row="1"  
  Foreground="Red" HorizontalAlignment="Left" Margin="2" 
  VerticalAlignment="Center"></TextBlock>
<TextBox x:Name="TitleTextBox" Grid.Row="1" Grid.Column="1" Width="200" 
  VerticalAlignment="Center" HorizontalAlignment="Left" Margin="2" 
  Text="{Binding Path=Title, Mode=TwoWay, ValidatesOnDataErrors=True, 
    NotifyOnValidationError=True}" />

When we are entering data now, the validation will kick in whenever a validation error is encountered.

We can take it one step further though, using the BindingValidationError event, defined on FrameworkElement. This event will trigger whenever a binding error is reported by the binding source, being here the instance of the ChristmasSong class. In this event, we can through the e.Action property check if an error was added or resolved. In this particular code, I have specified that the Submit button will only become enabled when there are no more errors.

private void ChristmasSongGrid_BindingValidationError(object sender, 
  ValidationErrorEventArgs e)
{
  switch (e.Action)
  {
    case ValidationErrorEventAction.Added:
         errorsOnPage++;
         break;
    case ValidationErrorEventAction.Removed:
         errorsOnPage--;
         break;
  }
  if (errorsOnPage == 0)
    SubmitButton.IsEnabled = true;
  else
    SubmitButton.IsEnabled = false;
}

All this can be seen in action, when we are entering “Last Christmas” by “Wham”!

image

The sample code can be downloaded here: SLDataErrorInfo.zip (308.96 KB)

  Posted on: Friday, December 18, 2009 12:06:56 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 17, 2009    

In today’s article, we’re looking at cross-domain access to a service in Silverlight 4’s trusted applications.

As you may know, when accessing any service located in a domain different from the one in which the Silverlight application itself is hosted, Silverlight will check for a cross domain file being in place. Cross-domain policies prevent Silverlight applications to connect with services that are not in the same domain. However, a service can opt-in to be connected to if at the root of the domain, a cross-domain policy file has been deployed. Silverlight will check for its existence (the file should be named clientaccesspolicy.xml or crossdomain.xml, which is the cross-domain file of Flash) and if found, Silverlight will connect in a cross-domain manner.

Services such as Twitter and Facebook do not deploy this file anymore. Flickr does, meaning that we can connect to Flickr from a client-side Silverlight application. If we want to connect with Twitter from Silverlight, we have to create a service within the same domain as where the Silverlight application is hosted. This service can then communicate with Twitter and Silverlight can communicate with our service.

In Silverlight 4, the notion of trusted applications was added (we looked in this blog series already to some other concepts available when running a trusted application such as COM interop and local file access). If a Silverlight application is running as a trusted application, it can perform cross-domain calls, without there needing to be a cross domain policy file in place. That means that we can build a Twitter client as a trusted Silverlight application without having to build an extra service layer in between.

In the sample I have built for this post, I’m doing exactly that. Below is a screenshot. The UI of the application contains a templated ListBox. Note that the application is running OOB as a trusted application.

image

The code for this application is quite easy. It’s the same code we would write to access a “local” service, meaning a service in the same domain. Below is the code to access Twitter, an asynchronous web service call using the WebClient class.

public void GetPublicTimeLine()
{
    string publicTimeLine = "http://twitter.com/statuses/public_timeline.xml";
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler
      (client_DownloadStringCompleted);
    client.DownloadStringAsync(new Uri(publicTimeLine, UriKind.Absolute));
}
 
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
    XDocument document = XDocument.Parse(e.Result);
    twitterData = (from status in document.Descendants("status")
                   select new Tweet
                   {
                     Message = status.Element("text").Value.Trim(),
                     User = status.Element("user").Element("name").Value.Trim()
                     }).ToList();
 
    PublicTimeLineListBox.ItemsSource = twitterData;
}

This code is executed when a user clicks on the “Load Twitter Messages” button at the top. We do perform a check to see if the application is running OOB and is running with elevated permissions.

private void LoadTwitterButton_Click(object sender, RoutedEventArgs e)
{
    if (Application.Current.IsRunningOutOfBrowser && 
            Application.Current.HasElevatedPermissions)
    {
        //it's OK to access Twitter services cross domain now
        GetPublicTimeLine();
    }
}

Tomorrow, we will look at extending this sample by allowing to send credentials to Twitter to access personalized streams of tweets.

The complete sample can be downloaded here.

SLTrustedTwitter.zip (269 KB)
  Posted on: Thursday, December 17, 2009 4:52:54 PM (Romance Standard Time, UTC+01:00)   |   Comments [3]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 16, 2009    

The DataGrid is probably the most popular control in many business applications. Added in Silverlight 2, this control allows for easy displaying and editing of data in a tabular format. While already a very decent control, the DataGrid in Silverlight 2 and 3 still had some things that were missing or not working like you’d hope them to. In today’s post, we’ll look at the newly added changes to the control.

The first and probably biggest change is the auto-sizing option for columns. In previous versions, we could basically specify a column width or specify nothing at all, leaving it to Silverlight. What we could not do, was saying to a specific column: Take all the remaining space, similar to what we can do with the Grid control through the use of *.

Basically, there are now 5 options we have to specify how a column should behave (copied from the MSDN docs):

Member name
Description
Auto
The unit of measure is based on the size of the cells and the column header.
Pixel The unit of measure is expressed in pixels.
SizeToCells The unit of measure is based on the size of the cells.
SizeToHeader The unit of measure is based on the size of the column header.
Star The unit of measure is a weighted proportion of the available space.

Let’s take a look at using these in an example. I created a random data generator (see sample code download), which generates Employee instances. These are stored in a generic list which is then set as the ItemsSource for a DataGrid. The result can be see below.

image

As you can see in the screenshot, the Address column is wider than the others. I actually specified it to be twice as wide as the FirstName and the LastName columns. The City column has a specific width set.

<data:DataGrid AutoGenerateColumns="False" x:Name="EmployeeDataGrid" 
    HeadersVisibility="All" Grid.Row="1">
    <data:DataGrid.Columns>
        <data:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" Width="*"/>
        <data:DataGridTextColumn Header="LastName" Binding="{Binding LastName}" Width="*"/>
        <data:DataGridTextColumn Header="Address" Binding="{Binding Address}" Width="2*"/>
        <data:DataGridTextColumn Header="City" Binding="{Binding City}" Width="100" />
    </data:DataGrid.Columns>
</data:DataGrid>

We can also use the other options. By clicking on the Change button at the top, we switch the DataGrid to use another sizing option.

private void ChangeColumnsButton_Click(object sender, RoutedEventArgs e)
{
    EmployeeDataGrid.Columns[0].Width = new DataGridLength(1, 
        DataGridLengthUnitType.SizeToCells);
    EmployeeDataGrid.Columns[1].Width = new DataGridLength(1, 
        DataGridLengthUnitType.SizeToCells);
    EmployeeDataGrid.Columns[2].Width = new DataGridLength(1, 
        DataGridLengthUnitType.SizeToCells);
    EmployeeDataGrid.Columns[3].Width = new DataGridLength(1, 
        DataGridLengthUnitType.Star);
}

This results in the following:

image

The first three columns are sizing to their contents. The City column takes all the remaining space.

The second new feature concerning the DataGrid, is the ability to copy data from the DataGrid to Excel. This feature is really handy in business applications. Very often, we need to be able to export data from an application towards Excel. This can make this very easy to do.

When we start a copy by selecting one or more rows, we are shown a prompt, asking us if we want to allow access to the clipboard. If confirmed, the data is copied as textual information and can be pasted in Excel.

There’s an event fired per row that is copied to the clipboard, namely the CopyingRowClipboardContent event. In this event, we can see what data is being copied and if needed apply transformations on it.

private void EmployeeDataGrid_CopyingRowClipboardContent(object sender, 
    DataGridRowClipboardEventArgs e)
{
    // do something
}
The complete sample can be downloaded here. SLNewDataGrid.zip (1.04 MB)
  Posted on: Wednesday, December 16, 2009 10:10:05 PM (Romance Standard Time, UTC+01:00)   |   Comments [2]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 15, 2009    

In today’s article, we’ll be looking at another new feature that was added with Silverlight 4, namely the ability to react to right-clicks in a Silverlight application. This means that we can override the default behavior of Silverlight where it’s showing the context menu allowing us to go to the configuration screen.

Because Silverlight now supports right-clicking, we can create a context menu that appears on the right-click event. We can code this context menu as we want. Right-clicking is supported on any UIElement: on the UIElement class, there are two new events added, namely the MouseRightButtonDown and the MouseRightButtonUp. Both of these new events use MouseButtonEventArgs as their event arguments, which are also used for the normal left click events.

As said, by default, the Silverlight context menu is shown when a user right-clicks on a Silverlight application. To block this, in the MouseRightButtonDown, we have to set the e.Handled to true. This way, the default context menu is not shown and we can go ahead and create our own context menu. This will appear on the MouseLeftButtonUp event.

Let’s take a look at a simple application. In this application, we have attached a custom context menu on an Image control. Using this context menu, I can choose to delete the image I clicked on.

image

The image itself has both the MouseRightButtonDown and the MouseRightButtonUp events attached to it using XAML code:

<Image Height="195" x:Name="imgTree" Stretch="Fill" Width="249" 
   MouseRightButtonDown="imgTree_MouseRightButtonDown" 
   MouseRightButtonUp="imgTree_MouseRightButtonUp" 
   Source="tree.png" Canvas.Left="181" Canvas.Top="79">
</Image>

To prevent the default context menu from appearing, we can set the e.Handled to true in the mouse down event:

private void imgTree_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
    e.Handled = true;
}

In the mouse up event, we can then specify what context menu we want to have appear:

private void imgTree_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
    Image image = sender as Image;
    if (image != null)
    {
        ContextMenu contextMenu = new ContextMenu(PrintCanvas, image);
        contextMenu.Show(e.GetPosition(LayoutRoot));
    }
}

The ContextMenu used here is a custom control.

The complete source code can be downloaded here: SLRightClick.zip (473.2 KB)

  Posted on: Tuesday, December 15, 2009 11:21:21 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 14, 2009    

Only 10 days ‘till Christmas and thus only 10 more posts after this one to finish my series. In today’s post, we’ll be taking a look at the Local Connection API, a feature introduced with Silverlight 3.

Most of the time, we build full-screen Silverlight applications, meaning that the only function that the HTML still fulfills, is hosting a DIV that will contain the HTML OBJECT tag in which Silverlight will be hosted. However, sometimes Silverlight could be used as an “island” on an HTML page. For example, we could have an HTML page (perhaps rendered by ASP.NET) in which a table of data is shown. The end-user may want a richer experience with this data grid such as reordering rows, efficient paging and so on. We could decide to just convert that specific part to functionality to Silverlight, resulting in a Silverlight island.

To go even further, in some scenarios, it may be needed that two or more of these Silverlight islands live on a single page. Silverlight 2 introduced the HTML Bridge to allow these two Silverlight plug-ins to talk to one another: using Javascript as an intermediate, we could send messages from control 1 to control 2 and vice-versa. While possible, it’s not the easiest way of developing an application.

Silverlight 3 introduced something easier for this particular problem, namely the local connection API. It basically allows two or more Silverlight instances to communicate with each other. These two instances can live on the same page, but can even live on two different browser tabs or even two different browser windows. The API uses a concept of a named pipe: a named sender sends a message into a pipe and a receiver can intercept this message. The message needs to be a string.

The messaging system introduced is based on two types, LocalMessageSender and LocalMessageReceiver, both types that live in the System.Windows.Messaging namespace.

Let’s take a look at an example. The application I built for this post contains two Silverlight controls. The first control contains a few buttons. When clicking on a button, I want to change the background of control n° 2. (Note that these are actually 2 different Silverlight applications hosted on one single page).

image

The first thing we need to do is creating an instance of the LocalMessageSender class. As parameter, we pass in the name that will be used as the identification (ColorSender), like so:

private LocalMessageSender localMessageSender;
private LocalMessageReceiver localMessageReceiver;
 
public MainPage()
{
    InitializeComponent();
    localMessageSender = new LocalMessageSender("ColorSender");
 
}

When we click on a button, we’ll send a message using this instance. In this case, we pass in the name of the color we want:

private void RedButton_Click(object sender, RoutedEventArgs e)
{
  localMessageSender.SendAsync("Red");
}
 
private void GreenButton_Click(object sender, RoutedEventArgs e)
{
  localMessageSender.SendAsync("Green");
}
 
private void BlueButton_Click(object sender, RoutedEventArgs e)
{
  localMessageSender.SendAsync("Blue");
}

In the second application, we create a LocalMessageReceiver, passing in the same string, ColorSender, as the name of the sender it should listen to. We then specify the handler for the MessageReceived event, which will trigger when a string is received. The receiver starts listening for values by calling its Listen() method:

private LocalMessageReceiver localMessageReceiver;
 
public MainPage()
{
  InitializeComponent();
  localMessageReceiver = new LocalMessageReceiver("ColorSender");
  localMessageReceiver.MessageReceived += 
  new EventHandler<MessageReceivedEventArgs>(localMessageReceiver_MessageReceived);
  localMessageReceiver.Listen();
}

Based on the value of the received message, we change the color:

void localMessageReceiver_MessageReceived(object sender, MessageReceivedEventArgs e)
{
  switch (e.Message)
  {
    case "Red": LayoutRoot.Background = new SolidColorBrush(Colors.Red);
                ColorTextBlock.Text = "RED";
                break;
    case "Green": LayoutRoot.Background = new SolidColorBrush(Colors.Green);
                  ColorTextBlock.Text = "GREEN";
                  break;
    case "Blue": LayoutRoot.Background = new SolidColorBrush(Colors.Blue);
                 ColorTextBlock.Text = "BLUE";
                 break;
    default: LayoutRoot.Background = new SolidColorBrush(Colors.White);
             ColorTextBlock.Text = "WHITE";
             break;
  }
}

The code can be downloaded here: SLLocalConnection.zip (97.1 KB)

  Posted on: Monday, December 14, 2009 9:31:33 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 13, 2009    

In today’s post, we will be working with services. As some of you know, I’m currently finishing my first book titled Silverlight 4 Data Access Cookbook. If all goes well, it will be available in early access preview somewhere in the coming week. Therefore, I decided I needed to write a post that’s in the same area as my book. More specifically, I’ll be creating a application that works together with the services API exposed by Bing.com, Microsoft’s new and successful search engine.

Bing has a very rich API that we can use to incorporate search functionalities in our applications, including Silverlight applications. It allows us to use WCF (SOAP) and REST communication, because it exposes endpoints for both these technologies. In this particular example, I’m using the SOAP interface for communication using a WCF service. To get a complete overview of the functionalities, you can download the PDF describing the entire API at http://www.bing.com/developers/s/API%20Basics.pdf . It also contains some sample code.

The very first thing we should before we can actually start building applications with Bing, is obtaining an API key. This key is required so Bing can check that your request is valid (this key will be part of every request you’ll send to Bing). Obtaining a key is free and can be done at http://www.bing.com/developers/createapp.aspx .

The provided sample is a Silverlight 4/VS2010 solution, all the code included however also works with Visual Studio 2008/Silverlight 3.

First, we need to generate a proxy using Visual Studio 2010. For this, we need the address of the WSDL (Web Service Description Language) file. In the documentation, we can find that this address is: http://api.search.live.net/search.wsdl?AppID=12345 where 12345 needs to be replaced with your obtained API key. In Visual Studio, we add the service reference using the dialog and I have set the namespace to BingSearchService.

image

Visual Studio will at this point create the proxy for the service. A proxy contains a client-side copy of the types exposed by the service and its methods. The contents of the methods is replaced with a call to the real service method. In the client-side code, we can now work with these types and methods.

In the screenshot a bit further, you can see the interface of the application. It contains a TextBox and a Button to search and a templated ListBox to display the results. Let’s first create the code for the event handler of the click event. Bing accepts quite a lot of parameters for the search it needs to perform. These are encapsulated in an object of type SearchRequest. Since we are conducting a normal web search, we specify this in the Sources property of the SearchRequest instance. A search with Bing is a service request, so all communication needs to be done asynchronously. We can see this at the way we are calling the service using the SearchCompleted event and SearchAsync() method. Below is the code.

private void SearchButton_Click(object sender, RoutedEventArgs e)
{
  LiveSearchPortTypeClient soapClient = new LiveSearchPortTypeClient();
  SearchRequest request = new SearchRequest();
  request.AppId = "81691C6A195FBC3FB469594BAA30B50A99CF3D22";
  request.Sources = new SourceType[] { SourceType.Web };
 
  if (SearchTextBox.Text != string.Empty)
  {
    request.Query = SearchTextBox.Text;
    soapClient.SearchCompleted += 
      new EventHandler<SearchCompletedEventArgs>(soapClient_SearchCompleted);
    soapClient.SearchAsync(request);
  }
}

When the service completes asynchronously, meaning, when Bing’s results are ready and available, the *Completed event is called and executed. In this event handler, we have access to the results of the service call. The result can be found in the e.Result parameter and is always of the same type as returned by the service. In our specific case, the used type is a SearchResponse, again a type exposed by the Bing services. We can now loop through these results and using a simple LINQ query, create an IEnumberable<SearchResult> . SearchResult is a type created by us to allow us to data bind to the results. This type is very simple:

public class SearchResult
{
    public string SearchResultTitle { get; set; }
    public string SearchResultDescription { get; set; }
    public string SearchResultUri { get; set; }
}

The code for the event handler is shown next:

void soapClient_SearchCompleted(object sender, SearchCompletedEventArgs e)
{
    SearchResponse response = e.Result;
    if (response.Web.Results.Count() > 0)
    {
        var results = from result in response.Web.Results
                      select new SearchResult
                      {
                          SearchResultTitle = result.Title,
                          SearchResultUri = result.Url,
                          SearchResultDescription = result.Description
                      };
        ResultListBox.ItemsSource = results.ToList();
    }
}

The ListBox is as said templated; the ItemsTemplate has been replaced with a custom data template, as shown below:

<ListBox x:Name="ResultListBox" Grid.Row="1" Margin="3" Background="Black">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.RowDefinitions>
          <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding SearchResultTitle}" FontWeight="Bold" 
          FontSize="15" TextDecorations="Underline" Foreground="White"></TextBlock>
        <TextBlock Text="{Binding SearchResultDescription}" Grid.Row="1" 
          TextWrapping="Wrap" Width="400" HorizontalAlignment="Left" 
          Foreground="White"></TextBlock>
        <TextBlock Text="{Binding SearchResultUri}" Grid.Row="2" Foreground="#568e71">
        </TextBlock>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

When we now execute a search using our application, we see the following:

image

The complete sample can be downloaded here:

SLBing.zip (790.49 KB)
  Posted on: Sunday, December 13, 2009 12:48:53 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 11, 2009    

I made it through the first half of my Silverlight Advent Calendar! You’re currently reading the 12th installment of my article series. In this article, we are looking at the RichTextArea control, which was added to the platform with Silverlight 4.

Up until Silverlight 4, we had no real way to perform rich text editing. Some (open source) implementations have been built of which the best one is in my opinion VectorLight.com’s RichTextBox/RichTextBlock (check it out at www.vectorlight.com, they have quite some nice controls). Silverlight 4 introduces the RichTextArea control. Its name already implies what it is capable of: allowing us to do rich text editing in our Silverlight applications. Things like making text bold, italic or underlined are of course supported by this control. On top of that, more advanced options are available, such as adding hyperlinks in text, adding images and adding XAML content. It can also out-of-the-box work with the clipboard and offers BiDi support. The latter is important for some languages such as Hebrew, since these are right-to-left languages.

Behind the visual of the control, text is being added as XAML, so in fact, the control is rendering the result of that XAML. This XAML is XAML like we know it for displaying rich text using TextBlock controls, containing Paragraphs, Runs and LineBreaks. At the time of writing, there is no real Text property on the control to get the entered text without the markup. To get the contents, we can use the Blocks collection to loop through the content. This is a bit of a setback and I can only hope it will in some way become possible to get the text from the control as well (without the markup).

Using this new control, we can thus perform most of the actions we’ll want to do with text. The control does not have buttons by default, so we need to add them ourselves. Below is an implementation of the control in combination with a ribbon (found in the official Silverlight 4 whitepaper/documentation).

image

Let’s take a look a simple implementation now. My implementation will make it possible to add text (quite logically), make it bold, underlined or italic. We’ll also add the possibility to change the color of the selected text and print it using the new printing functions in Silverlight 4.

image

Below is the XAML for the RichTextArea (nothing special as you can see):

<RichTextArea x:Name="MainRichTextArea" Height="300"></RichTextArea>

To implement the different functions, we need to add some code in the event handlers of the button click events. For example, if we want to make the selected text bold, we start by checking if text is selected. If there is, we check if the selected text is already bold or not. We set it to bold if it isn’t and vice-versa of course. The code for this is shown below.

private void BoldButton_Click(object sender, RoutedEventArgs e)
{
  if (MainRichTextArea.Selection.Text.Length > 0)
  {
    if (MainRichTextArea.Selection.GetPropertyValue(Run.FontWeightProperty) 
        is FontWeight &&
        ((FontWeight)MainRichTextArea.Selection.GetPropertyValue
        (Run.FontWeightProperty)) == FontWeights.Normal)
        {
          MainRichTextArea.Selection.SetPropertyValue(Run.FontWeightProperty, 
            FontWeights.Bold);  
        }
    else
        MainRichTextArea.Selection.SetPropertyValue(Run.FontWeightProperty, 
          FontWeights.Normal);
        MainRichTextArea.Focus();
    }
}

The code is similar for the other actions, it can be found in the sample code download. When we want to print our added text, we have 2 options. The most simple one is pointing the PageVisual to the RichTextArea:

private void PrintButton_Click(object sender, RoutedEventArgs e)
{
  PrintDocument printDocument = new PrintDocument();
  printDocument.DocumentName = "My rich text";
 
  printDocument.PrintPage += (s, args) =>
  {
    args.PageVisual = MainRichTextArea;
  };
  printDocument.Print();
}

The second option exists out of looping through the Blocks collection of the RichTextArea, parsing each of the retrieved items and adding them to the Inlines collection of a TextBlock control.

The sample code can be downloaded here: SLRichTextArea.zip (84.68 KB)

  Posted on: Saturday, December 12, 2009 12:49:28 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 11, 2009    

One day away from finishing the first 12 (half of the total of 24 ;-) )of my Silverlight articles. In this post, we are looking at local file access in Silverlight 4. This new feature is another one that is only enabled with OOB apps with elevated permissions.

In Silverlight 2 and 3, we already had some basic file access. We could perform an OpenFileDialog starting with Silverlight 2. It gave us a read-only stream to the selected file, meaning that the only thing we could do with the file, was reading it and using its contents in the application. Silverlight 3 added the SaveFileDialog, which, surprisingly, allows us to save files to the local disk.

Silverlight 4 ads more or less real local data access. By more or less, I mean that Silverlight applications can only access some folders. More particularly, we can access the My Documents, My Pictures, My Videos and My Music folders (on Mac, an equivalent exists). Within this directory, we can read, create and delete files. One important side-note though: the application needs to be a trusted application, meaning that it needs to run with elevated permissions.

Silverlight has a specific enumeration that we can use to get the physical location of the files: Environment.SpecialFolder. In it, we can find MyPictures etc. Note that it contains more than what we can access at this point, for example ProgramFiles. Even if we try to do something with this, we can’t since Silverlight won’t allow access to this directory.

Let’s take a look at a basic application as shown below.

image

Let’s first take a look at the left listbox, which is filled with the files of my My Pictures folder. Reading out the files, as well as other operations on the files, are done using the traditional classes contained in the System.IO namespace, such as Directory, File, Path etc. To read out the contents, we use the following code:

if (canWork)
{
  var files = Directory.EnumerateFiles(Environment.GetFolderPath
   (Environment.SpecialFolder.MyPictures));
  foreach (var file in files)
    {
      string fileName = System.IO.Path.GetFileName(file);
      imageNames.Add(fileName);
    }
    ImageListBox.ItemsSource = imageNames;
}

Note the canWork bool value. Since the application can only work if running OOB and with elevated permissions, we perform a check initially to see if the operations are permitted. The value is set through the following code:

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
  //check to see if application is running OOB and with elevated permissions
  if (App.Current.IsRunningOutOfBrowser && App.Current.HasElevatedPermissions)
    canWork = true;
  else
    MessageBox.Show("The application needs to run out-of-browser with 
      elevated permissions");
}

The second listbox is filled with all *.txt files, located in my My Documents folder: I’m simply applying a filter.

private void FetchTextFiles()
{
    var files = Directory.EnumerateFiles(Environment.GetFolderPath
     (Environment.SpecialFolder.MyDocuments))
     .Where(filename => filename.EndsWith("txt"));
    
    TextFilesListBox.ItemsSource = files;
}

As said, we can do more than just reading out the contents of a directory. We can for example delete a file. When we select a file in the second listbox, we can delete it using the following code:

private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
  if (canWork)
  {
    if (TextFilesListBox.SelectedItem != null)
    {
      string path = TextFilesListBox.SelectedItem.ToString();
      File.Delete(path);
      FetchTextFiles();
    }
  }
}

As you can see, working with the files is no different than working with files in plain .NET.

The code can be downloaded here: SLLocalFileAccess.zip (68.26 KB)

  Posted on: Friday, December 11, 2009 10:34:42 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 10, 2009    

Today, we are looking again at another new feature in Silverlight 4 which is the support for webcams and microphones.

Silverlight 4 gets support for microphones and webcams. It has access to the raw streams for both. The added support opens a lot of opportunities for new types of applications. For example, it becomes possible to write an application that reads barcodes of products you hold in front of the webcam, scans them and searches for product information.

The classes that expose this functionality live in the System.Windows.Media namespace. We’ll be using those to create a simple application that connects with the webcam and takes snapshots. Below is the interface of the application (a colleague of mine was just eating a banana :) )

image

The XAML for the application is shown below. The ComboBox displays the available webcams (only one on my machine), we are binding to the FriendlyName property. The ListBox is templated: both the ItemsTemplate and the ItemsPanel are overriden, to have the control display a horizontal list of images.

<Grid x:Name="LayoutRoot" Background="White">
  <Grid.RowDefinitions>
    <RowDefinition Height="330"></RowDefinition>
      <RowDefinition Height="50"></RowDefinition>
        <RowDefinition Height="140"></RowDefinition>
  </Grid.RowDefinitions>
  <Border BorderBrush="Black" BorderThickness="3" HorizontalAlignment="Center" 
    VerticalAlignment="Center">
    <Rectangle x:Name="WebcamRectangle" Fill="LightGray" Height="300" 
      Width="400"></Rectangle>
  </Border>
  <StackPanel Orientation="Horizontal" Grid.Row="1" VerticalAlignment="Center" 
    HorizontalAlignment="Center">
    <ComboBox x:Name="WebcamComboBox" Width="200" Margin="3" 
      SelectionChanged="WebcamComboBox_SelectionChanged">
      <ComboBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding FriendlyName}"></TextBlock>
        </DataTemplate>
      </ComboBox.ItemTemplate>
    </ComboBox>
    <Button x:Name="StartWebcamButton" Click="StartWebcamButton_Click" 
      Content="Start webcam" HorizontalAlignment="Center" Margin="3"></Button>
    <Button x:Name="TakePictureButton" Click="TakePictureButton_Click" 
      Content="Take picture" HorizontalAlignment="Center" Margin="3"></Button>
  </StackPanel>
  <ListBox x:Name="PicListBox"  Width="500" Height="120" 
    ScrollViewer.HorizontalScrollBarVisibility="Visible"  Grid.Row="2">
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Image Margin="5" Source="{Binding}" Stretch="UniformToFill" 
          Height="80" VerticalAlignment="Center"/>
      </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
        <StackPanel Orientation="Horizontal" VerticalAlignment="Top" 
          HorizontalAlignment="Left"/>
      </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
  </ListBox>
</Grid>

To fill the ComboBox with the available webcams, we can use the CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices(). This returns a Collection of VideoCaptureDevice instances. The VideoCaptureDevice class exposes the FriendlyName property we used in the data binding expression.

//fills the dropdown with all available webcams
WebcamComboBox.ItemsSource = 
  CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices();

We can instruct Silverlight to use the default capturing device, if nothing is selected by the user in the ComboBox:

//use the default
VideoCaptureDevice selectedVideoCaptureDevice = 
CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();

A little side note: we can change the default device in the Silverlight Configuration window as shown below.

image

Starting the webcam needs to be a user-initiated action. It’s impossible to start the webcam on load of the application for example. Therefore, we put this code in the event handler of the click on the Button. Whenever the webcam is started, a prompt is shown, asking the user if he wants to allow the application to access the device. This prompt can not be changed by the developer.

image

The following lines of code, located in the click event handler, check if the user has already granted permission in this particular session to access the webcam. If not, the prompt is shown following the RequestDeviceAccess() method call.

if (CaptureDeviceConfiguration.AllowedDeviceAccess 
    || CaptureDeviceConfiguration.RequestDeviceAccess())
{
...
}

To access the video capture of the webcam, we use the CaptureSource class.

VideoCaptureDevice videoCaptureDevice = selectedVideoCaptureDevice;
CaptureSource captureSource = new CaptureSource();
captureSource.VideoCaptureDevice = videoCaptureDevice;

This CaptureSource can then be used in combination with a VideoBrush to paint the video on any shape. Here, we used a Rectangle. To start the capturing of the device associated with the capture device (note that more than one device can be associated with one CaptureSource), we call its Start() method.

VideoBrush videoBrush = new VideoBrush();
videoBrush.SetSource(captureSource);
WebcamRectangle.Fill = videoBrush;
captureSource.Start();

If we want to capture a snapshot, we can use the AsyncCaptureImage method. It provides a WriteableBitmap to the Action(T) which is passed in as parameter. We add the image to the collection. Because of the applied binding, it is displayed automatically.

private void TakePictureButton_Click(object sender, RoutedEventArgs e)
{
    captureSource.AsyncCaptureImage((snapshot) =>
    {
        snapshots.Add(snapshot);
    });
}

The complete code for today’s article can be found here: SLWebcam.zip (60.67 KB)

  Posted on: Thursday, December 10, 2009 11:33:15 AM (Romance Standard Time, UTC+01:00)   |   Comments [1]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 9, 2009    
Article number 9 is here, a bit later on the day since I was home late yesterday from the MVP dinner we had and left at 6am this morning to do the Silverlight Road Show. But here we are with the article of today, December 9th!

Today we are looking at a data binding feature that was introduced with Silverlight 3. The reason I’m dedicating an article to it, is that not that many people seem to know about this little gem, namely element-to-element binding or simply element binding. Regular data binding happens between a source object (for example a Person or a Customer) and a control such as a TextBlock. Element binding happens between 2 controls: a property of element A is bound to a property of element B.

A good example to understand element bindings is the following: a Slider control of which the Value property is bound to the Text property of a TextBlock.

image

To make the link between the 2 values, we create a binding as usual, but we specify the “source” as being another element, in this case the Slider control using the ElementName property on the binding.

<StackPanel x:Name="SliderStackPanel" Orientation="Horizontal" Grid.Row="0">
    <Slider x:Name="YearsToPensionSlider" Width="300" Minimum="0" Maximum="40" 
      SmallChange="1" LargeChange="1" VerticalAlignment="Center"></Slider>
    <TextBlock x:Name="ValueTextBlock" 
      Text="{Binding ElementName=YearsToPensionSlider, Path=Value}" 
      VerticalAlignment="Center"></TextBlock>
</StackPanel>

We can also make this binding a bi-directional binding. In the image above, in the second row, it’s possible to specify a value manually in the TextBox control. Due to the binding, the slider will also change its value if we specify the binding to be a two way binding, as so:

<StackPanel x:Name="SliderStackPanel2" Orientation="Horizontal" Grid.Row="1">
    <Slider x:Name="YearsToPensionSlider2" Width="300" Minimum="0" Maximum="40" 
      SmallChange="1" LargeChange="1" VerticalAlignment="Center"></Slider>
    <TextBox x:Name="ValueTextBox" 
      Text="{Binding ElementName=YearsToPensionSlider2, Path=Value, Mode=TwoWay}" 
      VerticalAlignment="Center" Width="100"></TextBox>
</StackPanel>

You can download the code for this sample here. This is a Visual Studio 2008 project and works both with Silverlight 3 and Silverlight 4.SLElementBinding.zip (59.38 KB)
  Posted on: Wednesday, December 09, 2009 11:35:28 PM (Romance Standard Time, UTC+01:00)   |   Comments [3]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 7, 2009    

Today, I picked another new feature of Silverlight 4, namely the programmatic access to and from the clipboard in Silverlight 4.

Silverlight 4 has the ability to copy text to the clipboard, check if there is text available on the clipboard and paste the text from the clipboard back to the Silverlight application. To support this, it has 3 static methods available on the newly added ClipBoard class:

  • Clipboard.SetText()
  • Clipboard.ContainsText()
  • Clipboard.GetText()

Let’s look at using these in a sample. Below we see the interface of the basic text editing application, containing 2 RichTextArea controls.

image

When clicking on the left button, we check if there’s some text selected in the left RichTextArea control. As said, this is done through the use of the static SetText() method on the ClipBoard class. Note that any interaction with the Clipboard class can only happen after a user-initiated action, such as clicking a Button.

private void CopyButton_Click(object sender, RoutedEventArgs e)
{
    if (CopyTextArea.Selection.Text != string.Empty)
    {
        WarningTextBlock.Text = string.Empty;
        Clipboard.SetText(CopyTextArea.Selection.Text);
    }
    else
    {
        WarningTextBlock.Text = "Select some text first";
    }
}

This call is supported both in-browser and out-of-browser. There’s a difference though. When accessing the clipboard from an in-browser application, a warning will be shown to the user, asking if the action to the clipboard is trusted.

image

If we however make our application a trusted application by requiring elevated permissions when running out-of-browser, it will no longer display this prompt (we looked at elevating permissions yesterday).

When we want to paste in the text using the paste button, we can use the 2 other before mentioned methods, like so:

private void PasteButton_Click(object sender, RoutedEventArgs e)
{
    if (Clipboard.ContainsText())
    {
        PasteTexArea.Selection.Text = Clipboard.GetText();
    }
    else
    {
        WarningTextBlock.Text = "No text exists on the clipboard";
    }
}

In the current beta, we can only copy text to and from the clipboard. Objects such as images are not supported at this point!

The complete code for this sample can be found here: SilverlightClipboard.zip (61.65 KB)

  Posted on: Tuesday, December 08, 2009 12:04:05 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 6, 2009    

December 7th already, this post marks the first week of my Silverlight Advent Calendar!

In today’s post, I’ll be looking at how to create a simple kiosk application. A kiosk application is typically something you see at a booth or a registration desk, filling the entire screen and only allowing the user to perform a specific action. In this specific example, I’m looking at how to create a user registration application which could typically be used for a kiosk.

As said, the most specific requirement for this type of applications, is being full screen. Silverlight 2 and 3 already supported full screen applications: making an application full screen could easily be done using the following line of code:

App.Current.Host.Content.IsFullScreen = true;

This code will only execute following a user-initiated action, such as a click on a Button. It’s thus not possible to load the application full screen by putting this line in some loaded event of the control.

Seems all quite well, doesn’t it? Indeed,  but there was one disappointment in all this: when in full screen, the user could not enter text, the text input was limited to some keys such as the arrow keys. Every character key was ignored. This behavior changed in Silverlight 4. In fact, I should say “can be changed” in Silverlight 4. By default, it will still not accept character keys in full screen, but when creating the application as OOB (Out Of Browser) application and giving it elevated permissions, it will accept them perfectly.

Elevated permissions

Before we look at the application itself, let’s first look at elevated permissions. In Silverlight 1, 2 and 3, code executed  always ran in the sandbox of the browser. There was no way to get out of this sandbox. Silverlight 4 adds a new type of application, namely a trusted Silverlight application, running with elevated permissions and allowing actions that were not possible in the previous versions. This means that we now have 3 possible modes in Silverlight 4: in-browser, out-of-browser (but still in the sandbox) and trusted (out-of-browser with elevated permissions).

Each application can be created to require elevated permissions to run. We can enable this by in the Project Properties window, clicking on the Out-of-Browser settings and then checking the following checkbox:

clip_image002

When the application is now installed, another dialog is displayed, warning the user that this application will have more permissions than “normal” installed apps. This dialog looks like the following screenshot.

image

We’ll come across more features in the following days which require elevated permissions such as COM interop and cross-domain service access.

Back to the kiosk

OK, now that we know that for our application, we’ll need elevated permissions, let’s look at some code and screenshots. The application is built as a navigation application. The application starts (by setting the root page) to an admin screen. In this screen, the admin can set the application to full screen. From then on, it is full screen and cannot be changed by the user.

image

When clicking on the button, the following code is executed:

private void FullScreenButton_Click(object sender, RoutedEventArgs e)
{
    App.Current.Host.Content.IsFullScreen = true;
}

The admin can then click the Start Wizard hyperlink, which will set the kiosk-registration application to its waiting screen.

image

In the following screen, the user can enter his/her details. In full-screen mode, this would NOT have been possible if:

  • we had used Silverlight 2 or Silverlight 3
  • we would not have set the application to require elevated permissions

Try for yourself disabling the elevated permissions requirement. If you run the application in full-screen then (in OOB mode), all text input in the text fields is ignored.

image

How to quit the application

When putting a trusted application in full-screen, by default hitting the ESCAPE key will not resize it back to its original position. Therefore, we can handle the keydown event in the MainWindow.xaml for example, as follows:

private void UserControl_KeyDown(object sender, KeyEventArgs e)
{
    if(e.Key == Key.Escape)
        App.Current.Host.Content.IsFullScreen = false;
}
The full code can be downloaded here: KioskApplication.zip (166.63 KB)
  Posted on: Monday, December 07, 2009 12:08:01 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 3, 2009    

Here we are with the 4th article already in my Silverlight Advent Calendar series!

When using data binding in Silverlight, we often have to include one or more converters. A converter is a class that implements the IValueConverter interface. This class defines 2 methods, Convert and ConvertBack. Convert is applied when the data in the data binding action flows from source object to target control. A common use for converters is formatting a date value that comes from the database into a specific format or adding a currency symbol to a double value. Below is a sample converter class:

public class CurrencyConverter : IValueConverter
    {
 
        #region IValueConverter Members
 
        public object Convert(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
        {
            double amount = double.Parse(value.ToString());
            if (amount < 0)
                return "- " + amount.ToString("c", culture);
            else
                return amount.ToString("c", culture);
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
 
        #endregion
    }

Silverlight 4’s data binding engine has been extended with a few options that in some cases can avoid forcing us to create a converter. More specifically, three new options have been added: TargetNullValue, StringFormat and FallbackValue.

For these samples, we’ll use a class called Customer:

public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
    public string Email { get; set; }
}

I have instantiated this class and set it as DataContext for the entire UserControl:

 

customer = new Customer()
           {
               FirstName = "Gill",
               LastName = "Cleeren",
               BirthDay = new DateTime(1979, 1, 1),
               Email = "gillcleeren@somewhere.com",
               CustomerAddress = null
           };
 
           this.DataContext = customer;

Let’s take a look at what these new features offer us. TargetNullValue can be used in a data binding expression to specify what value should be used in case the binding returns null. In the previous sample, there is no value specified for the CustomerAddress property (it is null). If we want some replacement text, in this case “Unknown”, to be placed instead, we can use TargetNullValue like so:

<TextBlock x:Name="AddressTextBlock" Grid.Row="4" Grid.Column="0" 
    Text="Address:" FontWeight="Bold"></TextBlock>
<TextBlock x:Name="AddressValueTextBlock" Grid.Row="4" Grid.Column="1" 
    Text="{Binding CustomerAddress, TargetNullValue=Unknown}" ></TextBlock>

StringFormat can be used to format the value, just as was shown with the Converter earlier. For example, if we want the BirthDay to be formatted as a date in MM/dd/yyyy format, we can do so using the following code:

<TextBlock x:Name="BirthDateTextBlock" Grid.Row="2" 
    Grid.Column="0" Text="Birthday:" FontWeight="Bold"></TextBlock>
<TextBlock x:Name="BirthDateValueTextBlock" Grid.Row="2" Grid.Column="1" 
    Text="{Binding BirthDay, StringFormat=MM/dd/yyyy}"></TextBlock>

Finally, the FallbackValue can be used to display a value when the data-bound property on the source can not be located. In other words, this value will be displayed when we make an error in that we are trying to bind to a non-existent property. This is shown using the following code:

 

<TextBlock x:Name="InfoTextBlock" Grid.Row="5" 
    Grid.Column="0" Text="Info:" FontWeight="Bold"></TextBlock>
<TextBlock x:Name="InfoValueTextBlock" Grid.Row="5" Grid.Column="1" 
    Text="{Binding Info, FallbackValue=Nothing}" ></TextBlock>

The final result is shown below:

image

The complete code sample can be downloaded here: DatabindingInSL4.zip (64.44 KB)

Note: these new data binding features are a Silverlight 4 feature only!

  Posted on: Friday, December 04, 2009 12:02:03 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 2, 2009    

Silverlight is, as you probably know, a web technology. Basically, we have two choices to add Silverlight to a page (be this page ASP.NET, HTML, PHP or what have you):

  • Screen-filling Silverlight application
  • Silverlight “islands”: small piece(s) of Silverlight embedded on a webpage

Silverlight 4 adds a new option for bringing together Silverlight and HTML by means of the WebBrowser control. If you have done WinForms development, you may remember a similar control in that area as well. It basically allows us to display HTML content inside a Silverlight application.

For some scenarios, this is a very interesting addition to the platform. Imagine you are building a Silverlight application that’s actually a migration of an ASP.NET application. To cut costs, you must perform this migration in several parts. Instead of requiring that all the functionality is converted to Silverlight in one go, you can opt to leave some part in ASP.NET for the time being and still integrate it in the Silverlight environment.

As said, the control available for this, is the WebBrowser control.  The following properties are the most important ones when working with the WebBrowser control: 

· Source: gets or sets the URI that should be rendered in the WebBrowser control

· Navigate: specifies the URI that should be loaded in the control (works identical to the Source property)

· NavigateToString: you can also display an on-the-fly generated string of HTML. This can be done using this method.

The WebBrowser control only works when the Silverlight application is running out-of-browser. If we try running it in-browser, we’ll see a rectangle saying that the HTML is disabled.

image

If we’re running this sample out-of-browser and navigate to this very site (www.snowball.be), we’ll see the following:

image

Let’s now take a look at some code to create this.

The following is the declaration of the WebBrowser control itself:

<WebBrowser x:Name="MainWebBrowser" 
            Width="800" Height="600"></WebBrowser>

In the code-behind, in the click event of the Go-Button at the top, we can send the WebBrowser control to the requested page:

private void AddressButton_Click(object sender, RoutedEventArgs e)
{
    if (Application.Current.HasElevatedPermissions)
        MainWebBrowser.Navigate(new Uri(AddressTextBox.Text));
    else
    {
        string localIFrame = 
                "<HTML><HEAD></HEAD><BODY><IFRAME width='100%'      
                height='100%' src='" + AddressTextBox.Text + "' /></BODY></HTML>";
                MainWebBrowser.NavigateToString(localIFrame);
    }
}

As you can see, there are 2 implementations of the navigation. Why is that? When running out-of-browser, the WebBrowser control works, BUT it can only navigate to pages within the same domain as where the Silverlight application is hosted. To navigate to an external page (that is on another domain), the Silverlight application needs elevated permissions: it must be a Trusted Application. ( We’ll look at Trusted applications in a future post). This is reflected by the first check.

Now there’s a little workaround this limitation and that’s adding an IFRAME control manually and hosting the external page in there. This is done in the else-block.

Note: this is a Silverlight 4 feature which only works in Visual Studio 2010!

The sample can be found here.

  Posted on: Thursday, December 03, 2009 12:46:46 AM (Romance Standard Time, UTC+01:00)   |   Comments [1]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     December 1, 2009    

Question: how many times a day do you move things around in your PC environment? Placing a file on your desktop, picking it up and moving or dragging it into a folder is something we all know and do constantly. Also, personally, I often drag a file into a window to trigger the application to do something with it. Often when I’m doing some quick editing, I drag an image onto Photoshop’s desktop icon. Or when I want to send a mail with an attachment, I drag the file into the window. The application gets a handle to the file and knows what to do with it.

Silverlight applications could not be the target of a drag and drop operation. It was possible to drag stuff around inside the Silverlight window, but it was not possible to drag things into the window running Silverlight. Things changed in this area with the arrival of Silverlight 4. At the time of writing, it’s only possible to drag in one file or a list of files, however dragging in a directory is not supported. This feature is available on Windows and Mac.

Any UIElement within Silverlight can now be the target of a drag operation. IThe UIElement class now defines several events to support dragging, namely DragEnter, DragLeave, DragOver and Drop. DragEnter, DragLeave and DragOver can be used for example to highlight a control when content is being dragged over it. The Drop event fires when an object is dropped onto the UIElement. Let’s take a look at a sample.

Imagine we are building an application in which the user can drag and drop images on a canvas. The way the Canvas needs to be declared is as follows:

<Canvas x:Name="DropCanvas" AllowDrop="True" Drop="DropCanvas_Drop" >

In code-behind, we should handle the Drop event to react to a file being dropped on the UIElement.

private void DropCanvas_Drop(object sender, DragEventArgs e)
{
    IDataObject dataObject = e.Data;
    Point dropPoint = e.GetPosition(DropCanvas);
    if (dataObject.GetDataPresent(DataFormats.FileDrop))
    {
        FileInfo[] files = (FileInfo[])dataObject.GetData(DataFormats.FileDrop);
        
        if (files.Length > 0)
        {
            if (files[0].Extension == ".jpg")
            {
                //only take file 0
                System.Windows.Media.Imaging.BitmapImage bitmapImage = 
                    new System.Windows.Media.Imaging.BitmapImage();
                bitmapImage.SetSource(files[0].OpenRead());
                Image newImage = new Image();
                newImage.Source = bitmapImage;
                newImage.Width = 200;
                newImage.Height = 200;
 
                newImage.SetValue(Canvas.TopProperty, dropPoint.Y);
                newImage.SetValue(Canvas.LeftProperty, dropPoint.X);
 
                newImage.Stretch = Stretch.Uniform;
                DropCanvas.Children.Add(newImage);
            }
        }
    }
}

This event defines a DragEventArgs parameter, which defines a Data property, of type IDataObject. We can access the file or files using the GetData method. This method returns an array of FileInfo objects and these files can then be read out. The code for this is shown below.

We check if the file is an image (check for the file extension) and if it is, we create a new BitmapImage, passing in the dropped file. After that, we create a new Image control and set its source to the BitmapImage instance.

Note: this is a Silverlight 4 feature and the sample only works with Visual Studio 2010!

The complete code can be downloaded here: DragAndDrop.zip (29.78 KB)

  Posted on: Wednesday, December 02, 2009 12:42:41 AM (Romance Standard Time, UTC+01:00)   |   Comments [2]
         
Gill Cleeren     .net | Silverlight | Silverlight Advent Calendar | sl4     November 30, 2009    
Here’s the first article of the Silverlight Advent Calendar! We are starting quite easy…
 
While browsing through the new properties and types available in Silverlight, I came across this nice little new property on the TextBlock called TextTrimming. As the word says, it helps you with showing an ellipsis when the text is too wide for the TextBlock you want it to appear in.

Let’s take a look at this property in action. Suppose we have a TextBlock that has a specific width set to it. On this TextBlock, we specify the TextTrimming property to have the value WordEllipsis.

   1: <TextBlock Text="Hello, my name is Gill Cleeren" 
   2: Width="150" TextTrimming="WordEllipsis"></TextBlock>

Without the TextTrimming property, the result is the following. As you can see, the text is cut of where the TextBlock ends.

image

However, with TextTrimming enabled, Silverlight calculates where it should be placing the ellipsis, making the result look much more polished.

image

Note that is a Silverlight 4 only feature, which only works with Visual Studio 2010!

Tomorrow, we’ll be looking at… Oh can’t say, that has to be a surprise until tomorrow! You can’t go peeking in that advent calendar!

  Posted on: Tuesday, December 01, 2009 12:02:45 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Microsoft | Programming tools     September 27, 2009    

This week, Microsoft announced WebsiteSpark, a new program designed to jumpstart business development for small Web development/design companies that helps drive new business opportunities by providing tools, solutions, support, training, and increased visibility and connections with partners and customers.

image

The program offers companies with 10 members Microsoft software and solutions, including training, support and market exposure for their products. This way, Microsoft offers them the help they need in the crucial first years. Certainly in these hard economy, this program can help a starting business a lot.

The program offers an entire ecosystem of customer, partners and professionals to connect with one another. This way, a company can broaden its customer base (available via www.microsoft.com/web/websitespark/market, available later this fall). Also, support in provided where needed, including technical support from Microsoft, managed newsgroups and MSDN dev community resources. Last, but certainly not least, the program offers immediate access to all software your company may need: Microsoft dev tools and web server and database production licenses!

All the info you need to sign-up, can be found at www.microsoft.com/web.

  Posted on: Sunday, September 27, 2009 10:59:27 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
         
Gill Cleeren     .net | ADO.net     July 16, 2009    

Fiddler is a great http debugging tool, allowing you to see all traffic going in and out. It’s very useful when for example working with ADO.NET Data Services to see which request is being sent to the service.

It so happened that since I had been using Windows 7, I hadn’t used or installed it yet. I was just creating a Silverlight application that works with ADO.NET Data Services and there was a specific query I wanted to see. So I installed Fiddler 2 on this Windows 7 machine.

Normally, when using Fiddler for local debugging, you add a “.” after the localhost: http://localhost.:1234/whatever.aspx. This should show the requests in Fiddler. However, it didn’t seem to work on my machine.

Luckily, I knew there was another way to see the local requests: using the ipv4 notation: http://ipv4.fiddler:1234/whatever.aspx. This seems to work.

I’m not sure if this has something to do with Windows 7 though. In any case, this second approach seems to work, so it might come in handy if the first one doesn’t work on your PC either :).

Fiddler can be downloaded on www.fiddler2.com (thanks Dominiek)

  Posted on: Thursday, July 16, 2009 10:58:37 PM (Romance Daylight Time, UTC+02:00)   |   Comments [3]
         
Gill Cleeren     .net | Efficiency | Slide decks | TechDays     March 12, 2009    

From March 10 - 12, TechDays 2009 Belgium took place, for the first time in Metropolis Antwerp.

I've delivered quite some sessions, including part of the keynote. A lot of people asked me to share the slides as well as the demos, so here are all the items you need to complete your knowledge on both databinding in WPF as well as skinning controls in Silverlight.

WPF Databinding Deep Dive
Databinding always sounds a bit intimidating. It’s the concept of attaching objects to a user interface and letting the technology take care of what to display where. WPF has a lot of capabilities in store to make databinding really easy and to help you build data-driven applications a lot faster. In this session, we’ll tackle everything that databinding offers us, from the fundamentals concepts to the advanced topics. With a lot of demos woven into the session, you’ll walk away with the knowledge you need to more efficiently use WPF.
Slide deck - Demos

Under the hood in Silverlight's controls skinning framework
While Silverlight offers us a lot of controls to build business applications, you might feel the urge to change them even more to suffice the needs of your application. A round button perhaps? Or a non-rectangular textbox? It’s all possible with the Silverlight skinning framework. In this session, you’ll see how to overhaul the look of your controls as well as create your own from scratch.
Slide deck - Demos

I hope you enjoyed the sessions, any feedback is welcome.

  Posted on: Thursday, March 12, 2009 3:24:10 PM (Romance Standard Time, UTC+01:00)   |   Comments [6]
         
Gill Cleeren     .net | PDC     October 27, 2008    

Together with Windows Azures launch, Microsoft gave .net a new logo.

  Posted on: Monday, October 27, 2008 5:08:59 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Visual Studio.net | WCF     July 7, 2008    

Today, I had create a deployment procedure for a VSTO 2007 Excel Add-in. Since I'm not an expert in Office-related development, I started doing some research on the topic. Here's what I found out to be the best way to do such a deployment. (Note, again, I'm a rookie at Office development, so there might be better ways...) 

Initially, I found the most easy way to deploy an add-in is using the Publish function in Visual Studio 2008. This way, a ClickOnce is created.
Now, the add-in connects to a lot of WCF services. The addresses of the endpoints of these services, among other configuration information, is stored in the app.config from the add-in. This information needs to be editable, since the server address might change over time.

When using the ClickOnce setup, the deployed application worked fine. The application was able to read out the settings of the app.config file. However, it is not stored in a specific location, since it is in the cache of ClickOnce. So, I had to find another solution, so that the config file can be located and edited.

So, after doing some more research on the subject, I found the correct way to deploy an add-in is a simple setup project created from Visual Studio. However, you need to add some registry settings as well as some other configuration.
The complete procedure is explained here and here.

  Posted on: Monday, July 07, 2008 10:48:48 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
         
Gill Cleeren     .net | Silverlight     June 3, 2008    

Just a few hours ago, Silverlight 2 Beta 2 was announced at TechEd US. The new version will be available later this week.

Along with this announcement, the following was also announced:

Internet Explorer 8 beta 2 will be available this August in 20 languages worldwide. Internet Explorer 8 is the next version of Microsoft’s popular browser, and in beta 1 it delivers significantly improved standards support and developer platform investments with enhanced user experiences. Beta 1 for Internet Explorer 8 is currently available and is focused on Web developers and designers to help them deliver Web experiences that go beyond the page for consumers.
 
• Availability this week of Silverlight 2 beta 2, the latest version of Microsoft’s cross-browser, cross-platform and cross-device plug-in for delivering the next generation of .NET-based media experiences and rich interactive applications for the Web. Now available with a commercial Go Live license, Silverlight 2 beta 2 will be used to power the unprecedented online experience NBC Universal is creating for the 2008 Beijing Olympics. To help developers take full advantage of Silverlight, Microsoft also released Expression Blend 2.5 June 2008 Preview and Microsoft Silverlight Tools beta 2 for Visual Studio 2008.
 
• An alliance with IBM that will further simplify application development for enterprise teams working in heterogeneous environments. IBM and Microsoft have agreed to work together to integrate IBM DB2 database access with Visual Studio Team System 2008 Database Edition.
 
• Multiple partner wins and the latest community technology preview (CTP) of the Microsoft Sync Framework, a comprehensive synchronization platform that enables collaboration and offline scenarios for applications, services and devices. New partners include Fujitsu Siemens Computers, Ontela Inc. and SmugMug Inc. Microsoft Sync Framework will be released in the third quarter of 2008 with full support for the FeedSync open protocol format on devices. A CTP for Windows Mobile support will also be available in the third quarter 2008.
 
• The first CTP of the Microsoft project code-named “Velocity,” a distributed, in-memory application cache platform that makes it easier to develop scalable, high-performance applications needing frequent access to disparate data sources. Large clusters of machines can be seamlessly integrated into a single cache, providing high availability to data.
 
• Ongoing momentum for Microsoft code-name “Oslo.” Microsoft reiterated its commitment to model-driven development and focus on helping developers realize the full potential of declarative programming, inspiring collaboration across organizational roles and enabling developers and IT pros to more easily deploy, manage and evolve applications. Microsoft will bolster its investments in a unified modeling platform code-named “Oslo,” which will be used by future versions of Visual Studio, Microsoft System Center, BizTalk Server and Microsoft SQL Server. “Oslo” will include visual modeling and composition tools, a foundational repository built on SQL Server 2008 for managing application metadata, and a new, declarative modeling language to enable interoperability of models between tools and domain-specific modeling notations.
 
• A new version of Visual Studio 2008 extensions for Windows SharePoint Services 3.0 v1.2, which will allow developers to use Visual Studio 2008 to extend the value of Windows SharePoint Services and Microsoft Office SharePoint Server by providing a simplified development environment.
 

  Posted on: Tuesday, June 03, 2008 11:53:49 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
         
Gill Cleeren     .net | Silverlight | WPF | Expression | Mix 08     March 4, 2008    

Wow, what an exciting week this is! In fact, I'm having trouble waiting for all the info that will come our way tomorrow.
Why tomorrow, you might ask? Well, Mix'08 is starting in Las Vegas in just a few hours. And as expectec, a lot of great info and visions will be shared, mostly during the big opening keynote.

A little further in this post, I have collected some info I managed to find already. Some of the things we'll see being announced tomorrow will greatly expand the possibilities we as webdevelopers/designers have. In fact, the web is wide open, the oppurtunities coming are way are endless.

One of, if not THE biggest announcement tomorrow, will of course be Silverlight 2.0 beta. A great toolset will make it much easier to create next-gen UX for the web. Datagrids will be on the rendez-vous, whom are still missed in WPF however. Today, Nokia announced the availability of Silverlight on their (Symbian) smartphones, so it's a guess, but I think we'll see more on a mobile version of Silverlight tomorrow (as I said, it's a guess...)

I managed to find some info on Expression too... Expression Studio V2 is coming this April appearantly, if we can already believe the rumors. Laurent Bugnion has more info on that on his blog.

And if you're not in Vegas, do use the possibilites of the web to take a look at the future! The opening keynote will be broadcast live (750kbps, 300kbps, 100kbps) at 9:30am Pacific / 5:30pm GMT. Microsoft also made a promise that all sessions will be downloadable within 24 hours! That means, start your download engines, go get soms sleep today, as you won't be having any time to go to bed once all this info is online!

Stay tuned for more Mix info on Snowball.be!

  Posted on: Tuesday, March 04, 2008 10:03:50 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Enterprise Library     February 20, 2008    

The dreaded "Error 2869" when using the Smart Client Software Factory (SCSF) might be a known one if you've already tried using the SCSF with Visual Studio 2008 (beta 2 or later).

A solution was found: you can edit the MSI installer with "Orca" as described here. However, I ran into the issue again when I tried the installation with the now-out-of-beta version of the Guidance Automation Extensions (Feb 2008).

When uninstalling the 1.0 release of GAX, and installing the May 2007 version, everything worked (after editing the MSI of course).

Appearantly, the p&p team will have to update the installer again, there must be a reference to the May 2007 version of GAX in there that causes the error to pop up again.

  Posted on: Wednesday, February 20, 2008 10:31:23 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Visual Studio.net     February 11, 2008    

Today, I was reading the CodeProject's newsletter and I noticed an interesting poll they were doing on the use of the different IDE's of Microsoft people are using today. Here's a copy of it.

What was (or is) your favourite Microsoft IDE?

Survey period: 4 Feb 2008 to 10 Feb 2008

We know we missed a few, but during the evolution of The Code Project these were the ones most used by our members.

Option

Votes

%

 

Visual Studio 2005

1472

42.97

1472 votes, 42.97%

Visual Studio 2008

971

28.34

971 votes, 28.34%

Visual Studio 6.0

651

19.00

651 votes, 19.00%

Visual Studio .NET 2003

213

6.22

213 votes, 6.22%

Other

58

1.69

58 votes, 1.69%

Visual C++ 4.0

30

0.88

30 votes, 0.88%

Visual Studio .NET (2002)

18

0.53

18 votes, 0.53%

Visual Studio 97

12

0.35

12 votes, 0.35%

Total

3425

  100%

3426 votes

Now, as was to be expected, the largest part is still using Visual Studio 2005. While 2008 is not actually released to the public (it will in about 2 weeks), already over 1 out of every 4 is using it (and claiming it their favorite IDE for that matter!). Personally, I can only applaud this, as it shows people are happy with the way 2008 works.

What strikes me more however, is the number of people that's still using Visual Studio 6. Almost 20%! And come to think of it: this is a poll done by CodeProject: people reading this particular site are not your regular developers most of the time, but more the "hardcore" devvers.

Let's hope these people will all soon have the chance to upgrade their daily work environment to a much more modern IDE like VS 2005 or VS 2008.

Just today, I was having a discussion on the topics covered at TechDays: Tom Mertens said that many, many developers are still using "old" technology. This graph only shows he's right...

  Posted on: Tuesday, February 12, 2008 12:13:30 AM (Romance Standard Time, UTC+01:00)   |   Comments [2]
         
Gill Cleeren     .net | Visual Studio.net     January 28, 2008    

This is something handy: the largest comparison of Visual Studio 2008 versions ever made. It was created by Rob Caron and can be viewed here.

  Posted on: Monday, January 28, 2008 11:58:17 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | Events | Microsoft | TechDays     January 24, 2008    

As you may or may not know by now, in the last few months, I have been busy with the organisation of TechDays 2008 as content owner for the developer track (formerly known as Dev-ItPro days) at Microsoft. So far, it has been a wonderful experience, being in contact with some of the most renowned speakers of the world.

Today, Microsoft sent out the reminder for the early-bird registration, and meanwhile on the site, a partial list of speakers and sessions has been published. I've had great help from Tom Mertens, Arlindo Alves and since the second half of December, Katrien De Graeve. Thanks guys (and girl)!

Looking at the list of announced speakers and sessions, I'm proud to say that we have succeeded and that we are able to present you with a great line-up. Ingo Rammer, Nikhil Kothari, Dave Webster, Chad Hower, Roy Osherove, Alex Turner and more, together with some great Belgian speakers as Bart De Smet, Peter Himschoot, Joris Poelmans, Patrick Tisseghem and more... all agreed on making this the best TechDays ever!

Now, the party is not just the TechDays. The day before, on March 11th, it's the Belgian launchday for Visual Studio 2008, Windows Server 2008 and SQL Server 2008. This event, should you not already know, is free to attend for everyone!

Convinced that you HAVE to be on THE .NET event of 2008? Of course you are. Head over to www.heroeshappenhere.be to register.

One thing I really should add: just like we did last year, Visug is organizing their Geek Bowling! I'll open the registrations for that this week. The bowling evening (also in Gent of course) will take place on the 12th!

So, I hope to see you there on March 11, 12 and 13!!

To finish, here's a list of sessions we already announced:

Deep Reflection (Roy Osherove)
In this 400 level session Roy Osherove digs deep into the heart of some of the new features in Reflection 2.0 such as runtime code generation using DynamicMethod (Lightweight Code Generation - LCG), parsing IL at runtime, generics in reflection, debugging runtime generated code, understanding Reflection.Emit, ReflectionOnly Context's for security and using Code gen to improve performance. Put your thinking cap on.

The ABC of building services with WCF (Peter Himschoot)
In today’s highly connected world being able to communicate is very important, especially for your applications. But how? Web Services? Remoting? Enterprise Services? WCF is Microsoft’s unified framework for building communication into your application, ready for the future. In this session we will look at building services with WCF, getting our hands dirty through building a service live, in front of your eyes. After this session you should have a clear understanding of the development life-cycle for WCF, the advantages of using WCF and how to proceed with it yourself.

Architecture and Databinding in WPF (Dave Webster)
Now that we have had some time to get used to XAML and WPF and seen the shiny new UIs we can build, it’s time to get serious about architecture and understand the power of databinding.  In this talk we will discuss advanced topics in databinding, the use of MVC architecture patterns and we will stretch Expression Blend version 2.0 to its limits.

We’ve been hacked!  Web security for developers (Dave Webster)
This is a demo driven session showing the actual hack of a web site.  You will learn how to write your web sites securely, and what your IT department will need from you. Bring your laptop and join in!

Introduction to the new ASP.NET Model View Controller (MVC) Framework (Matt Gibbs)
A benefit of the MVC architectural pattern is that it promotes a clean separation between the models, views and controllers within an application. In the near future, ASP.NET will include support for developing web applications using an MVC based architecture.
The ASP.NET MVC Framework is designed to support building applications that exhibit the following traits:
- Testability – Red/Green test driven development.
- Maintainability –clear separation of concerns
- Extensibility – interfaces allowing custom implementation at all levels.
- Web Standards and clean URLs – with routing and giving developers tight control over the resulting HTML.
Join us for a dive into the new MVC Framework and learn how to leverage this new alterative in your own applications.

AJAX Patterns (Nikhil Kothari)
This session takes a deep look at the Ajax paradigm by discussing useful development patterns, common problems and associated solutions. Patterns covered range from development approaches such as unobtrusive script attachment, to fundamentals such as search optimization to user interface and usability patterns such as intuitive navigation and visual notifications. While the demonstrations are illustrated through basic scenarios, like any pattern, the concepts can be applied to your own applications. In the course of demonstrating the patterns, this talk will also cover various aspects of ASP.NET AJAX including the latest features.

Unit testing tips and tricks (Roy Osherove)
In this talk we'll explore techniques for dealing with various unit testing scenarios. From testing events, to testing databases to testing LINQ queries and anonymous types, we'll see many small scenarios and discuss the unit testing patterns that can help test them.

The .NET Language Integrated Query (LINQ) Framework (Alex Turner)
Modern applications operate on data in several different forms: Relational tables, XML documents, and in-memory objects. Each of these domains can have profound differences in semantics, data types, and capabilities, and much of the complexity in today's applications is the result of these mismatches. Alex Turner, C# Compiler Program Manager, explains how Visual Studio 2008 aims to unify the programming models through LINQ capabilities in Microsoft Visual C# and Visual Basic, a strongly typed data access framework, and an innovative Application Programming Interface (API) for manipulating and querying XML.

LINQ Under the Covers: An In-Depth Look at LINQ (Alex Turner)
Want to know what really happens when you execute your favorite LINQ queries? Join us as we peek behind the curtain in Reflector to see how the C# compiler translates LINQ query expressions into standard query operators, while digging into the iterators that make LINQ to Objects tick. Learn exactly when query evaluation is deferred, and see how lambda expressions and closures work together to enable LINQ's elegant syntax. Then we'll explore how nearly identical LINQ to Objects and LINQ to SQL queries will result in radically different translations as we dig into the details of IQueryable and expression trees. Finally, we follow our IQueryable objects across the language barrier to investigate the unique features VB brings to LINQ, including XML literals. It is suggested that you attend the session "The .NET Language Integrated Query (LINQ) Framework" before attending this session.

Creating Custom LINQ Providers – LINQ to Anything (Bart De Smet)
LINQ is all about unifying data access in a natural language integrated way. But there’s more than just LINQ to Objects, LINQ to SQL and LINQ to XML. In this session, we put ourselves on the other side of the curtain and explore the wonderful world of LINQ providers. You’ll learn how to create a fully functional LINQ query provider allowing users to target your favorite query language using familiar LINQ syntax in C# 3.0 and VB 9.0: LINQ to AD, LINQ to SharePoint, LINQ to AD, LINQ to Outlook, you name it! This is your chance to get to know the inner workings of LINQ.

Building internet web sites using Microsoft Office SharePoint Server 2007 (Joris Poelmans)
Microsoft Office SharePoint Server 2007 provides the necessary framework components to build an Internet web sites using master pages, page layouts and WCM specific functionality. In this session we will take an in-depth look at how to use these components and which are the best practices  for developing an internet web site while leveraging the MOSS platform. This session will conclude with a look at the Accessibility Kit for SharePoint as well as at the migration story for MCMS customers.

Building RIAs for WSS 3.0 and MOSS 2007 (Patrick Tisseghem)
In this session you’ll learn how to leverage Web 2.0 technologies to deliver a rich and interactive end-user experience for SharePoint sites and content. Topics that will be covered are: building ASP.NET AJAX 1.0 enabled Web Parts; creating and consuming SharePoint Web Services that are AJAX-enabled; Web Parts hosting Silverlight 1.0 and 2.0 applications; techniques to have the Silverlight applications communicated back and forth with SharePoint content such as items in lists and libraries, user profile information and search results; samples of how publishing portals can be enriched with Silverlight navigation controls and enhanced page layouts; demos on how to build Vista Gadgets that display SharePoint content using traditional UI techniques as well as using Silverlight.

Building Rich Web Experience with Silverlight using Expression Blend and Visual Studio (Wim Verhaegen)
Silverlight is a cross-platform technology that brings new user interface capabilities such as vector graphics, media, animations and XAML to the browser.
Learn about building Silverlight applications using JavaScript, and see how Silverlight fits naturally into the AJAX development model.
This session provides developers the in-depth knowledge they need to start building Silverlight 1.0 applications today using Visual Studio and Microsoft Expression Blend.

IIS7 End-to-End Extensibility for Developers (Brian Delahunty)
In IIS7 the server exposes a brand new, powerful extensibility model for building server features that can be used to extend its functionality, or replace any of the default features.  With the Integrated Pipeline architecture, managed modules become virtually as powerful as native modules. In part I of this two part session, we will illustrate extending the server in an end to end scenario, building a managed module to extend the runtime and replace existing functionality.  We will then extend IIS7 diagnostics to instrument our module with custom trace events.

WCF and WF: Integrating two key technologies of .NET 3.5 (Ingo Rammer)
Windows Communication Foundation and Windows Workflow Foundation are two cornerstones of .NET 3.5. In this session, you will learn about different ways to combine them to workflow-enable your WCF applications.

Advanced Debugging with Visual Studio (Ingo Rammer)
Basically every .NET developer knows the Visual Studio debugger, but only few know its little secrets. In this session, Ingo shows you what you can achieve with this tool beyond the setting of simple breakpoints. You will learn how advanced breakpoints, debugger macros and visualizers, interactive breakpoints, tracepoints and interactive object instantiation at development time can support your hunt for bugs in your applications.

Using Visual Studio 2008 as a RAD tool to build a distributed application (Jay Schmelzer)
In this demo intensive session we’ll take a look at improved support in Visual Studio 2008 for building distributed business applications.  We will focus on Visual Studio’s support for building and consuming WCF services, sharing business validation rules between client and server, implementing local caching of read-only data on the client, sharing common application services like authentication and authorization between Windows and Web client applications and much more.  Next we will turn our attention to web and see how Visual Studio 2008 allows us to easily incorporate rich experiences into our existing ASP.NET web sites using ASP.NET AJAX, the ASP.NET AJAX Control Toolkit and take advantage of improved HTML designer, CSS editor and JavaScript intellisense and debugging.  Visual Studio 2005 raised the productivity bar for business application developers.  Visual Studio 2008 builds on that foundation bringing unmatched productivity gains to distributed business application developers.

Visual Studio 2008: Building applications with Office 2007 (Jay Schmelzer)
This session provides an overview of the tools and technologies that enable developers to leverage the new Visual Studio 2008 and Office platform tools and technologies to build new and exciting Office Business Applications. You’ll learn a number of key technologies in this session, including the creation of Office smart clients, development of custom SharePoint workflow, and extension of Outlook to integrate key business data into one of our most popular productivity tools.

Visual Basic: Tips and Tricks for the Microsoft Visual Studio 2008 (Jay Schmelzer)
In this session, we combine some tips for existing Visual Studio features, and tricks for leveraging new Visual Studio 2008 features. We look at a variety of existing features including operator overloading, refactoring, creating your own snippets, some tips for using frameworks classes (and generics), and leveraging application settings. Then we look at new features including some LINQ Do’s and Don’ts, My Extensibility, and taking control of unit testing in Visual Studio. All of these tips are aimed at giving you a more productive, fun programming experience.

Office: Office Open XML Formats (Chad Hower)
Office 2007 now stores its documents in XML. This makes manipulation and creation of documents easy to do, even without Office installed. The Office Open XML format is also an ECMA standard and has backwards compatibility with older versions of Office as well as some capabilities on Linux and Macintosh, as well as Java. Surprised? Learn about these features and more in this session.

Architecture: Dude, where's my business logic? (Chad Hower)
Over the years we have moved from desktop, to client server, to 3-tier, to n-tier, to service orientation. In the process though many things have changed, but many habits have remained. This session discusses what we are doing wrong, and solutions.

.NET 3.0: WinForms and WPF (Chad Hower)
With two options for building forms, which is better to use? For the near future the answer often is both. In this session we will cover the strengths and weaknesses of each, and how to use them effectively together.

  Posted on: Thursday, January 24, 2008 9:05:01 PM (Romance Standard Time, UTC+01:00)   |   Comments [1]
         
Gill Cleeren     .net | Games     January 7, 2008    

Did you know that over at Coding4Fun they have been doing a series of articles on DirectX development for the past months? Well, at least, now you know!

At the moment of writing, the 10th article is up, talking about "Beginning Game Development Part X –Direct Sound Part III" and it can be found here.

The previous entries can all be found using the links below:

1. Beginning Game Development Part 1 - Introduction
2. Beginning Game Development Part II - Introduction to DirectX
3. Beginning Game Development: Part III - DirectX II
4. Beginning Game Development: Part IV - DirectInput
5. Beginning Game Development: Part V - Adding Units
6. Beginning Game Development: Part VI - Lights, Materials and Terrain
7. Beginning Game Development: Part VII –Terrain and Collision Detection
8. Beginning Game Development: Part VIII - DirectSound
9. Beginning Game Development Part IX –Direct Sound Part II

Enjoy!

  Posted on: Monday, January 07, 2008 11:38:32 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | .net 3.0 | Links     January 6, 2008    

As promised in my intentions-post for 2008, I'm going to create a links post every week. So here we go for week 1 of 2008!

  • Brad Abrams announced they're starting on version 2 of Framework Design Guidelines. Although it will not ship before the end of this year, you can suggest topics that you'd like to see included in the final release of the book. Got an idea? Add it here.
  • New free e-clinic on .net 3.0: included is an overview on WPF, WCF and WF. Go to https://www.microsoftelearning.com/eLearning/offerDetail.aspx?offerPriceId=138162 for 3 hours of free .net 3.0 training.

More to come, stay tuned...

  Posted on: Monday, January 07, 2008 12:13:06 AM (Romance Standard Time, UTC+01:00)   |   Comments [1]
         
Gill Cleeren     .net | Microsoft     December 19, 2007    

This is a first for me: I'm blogging live from the MSDN Belux evening in Utopolis Mechelen on Visual Studio 2008 Team System and ALM (Application Lifecycle Management). This session is presented by Yves Goeleven of Compuware.

I've been working with Team System for almost 2 years now, but I must confess that I had not spent any time with the new 2008 version. So before this session started, I hope Yves will show me something new. I'll be covering the things I'm learning here.

  • Annotation: In Visual Studio 2008 Team System, you can now annotate changes you make in code with some comment.
  • Comparing folders: you can now perform comparisons between folders in the source control to see differences between 2 versions of folders.
  • Code coverage: included in VSTS2008 is now code coverage. By using color coding, you can see where code that's not covered by your unit tests is located
  • Code metrics: can show you the complexity of your code to show where refactoring should be done
  • Performance wizard: the new performance explorer and wizard can help you inspect where bad performing code is to be found
  • "Enable get latest on check-out": this feature was a  SourceSafe feature that wasn't available in 2005. But because of the fact that a lot of people really missed it, it was added again

For the developer part of VSTS, all these new things will help you improving your code quality and thus support ALM.

Now, we're on to the part for Database Developers. I don't think that I'll profit a lot of this part, since I'm not really a DBA ;-) far from it actually. Again here the integration with version control is handy to see changes made to database scripts (whereas otherwise these changes would have been lost because they would be made on standard files). Yves also shows a unit test specifically for database code.
Also integrated is the database comparison. This will inspect the 2 schema's and show the differences. Not only can you compare schema, you can also compare the data between 2 tables. If there are differences, you can see the records that are not equal. One last handy thing is data generation tool that will generate sample data in a database from your choice.

In the final demo, we are shown the tester edition. Yves shows the load testing features included in Visual Studio TS with the embedded performance monitoring.

In the final part, we are going to see the new build automation and continuous integration, which are like the flagship features. A nice addition to Team System is the possibility to schedule builds. You can now specify when a build should be done.

On top of that, you can now queue manually started builds instead of risking an overload on the build agent. You can also set the build process so that every check-in triggers a build: this is the new continuous integration in VSTS 2008. This ensure that at every point, the code that is in the central store is of reasonable quality. No longer do we need all kinds of external tools and plugins in Visual Studio to get continuous integration, it's reduced to checking a checkbox.

Probably tomorrow I'll be doing some coverage of the Architect Forum day in Elewijt, Belgium.

  Posted on: Thursday, December 20, 2007 12:15:46 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | .net 3.5 | C# | Microsoft     December 9, 2007    

Earlier this month, Microsoft posted the first "blueprint" of a series that will help developers more easily build Software plus Services (S+S) applications. The project was released as a project on CodePlex, the open-source community from Microsoft.

This first blueprint is intended for developing S+S applications with Outlook 2007. Microsoft plans to offer blueprints for other office business applications, e-commerce, media/community and mobility.

The Outlook + Services Blueprint download -- available as a single file or two files -- includes the S+S framework, source code, Outlook Plus Services add-in library, workflow and other guidance. The blueprint is designed to help developers expose data and integrate services into Outlook 2007. It requires Outlook 2007, SQL Server Express 2005 and Visual Studio 2005.

Within the S+S framework, developers open up an Outlook + Services Visual Studio project and learn how to extend the e-mail app based on the guidance provided in Overview, Workflow and Detail tabs (a step-by-step walk-through). Microsoft expects to distribute a "more sophisticated" developer example, dubbed "My eBay," which features eBay Web services, a custom ribbon interface and HTML from an eBay page, in short order.

Source: reddevnews.

  Posted on: Sunday, December 09, 2007 3:02:11 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | .net 3.5 | ASP.net | C# | Silverlight | Visual Studio.net     November 20, 2007    

Finally, we can present the RTM version of the Visual Studio 2008 RTM Training Kit.
This kit is a real goldmine, containing presentations, Hands-On-Labs, demo's... on all topics related to Visual Studio 2008.
Now you only have to find about 5 days to complete all that's in here, and you're set!


All the info is below:
The Visual Studio 2008 Training Kit has been updated for the RTM and has been released on the Microsoft.com Download Center for anyone to download and use.

The Visual Studio 2008 Training Kit contains a full 5-days of technical content including 20 hands-on labs, 28 presentations, and 20 scripted demos.   The technologies covered in the kit include:  LINQ, C# 3.0, VB 9, WCF, WF, WPF, Windows CardSpace, Silverlight, ASP.NET Ajax, .NET Compact Framework 3.5, VSTO 3.0, Visual Studio Team System, and Team Foundation Server. 

Originally developed for early adoption work with ISVs, it is now available to all. 

You can download the entire training kit from the download center here:  http://go.microsoft.com/?linkid=7602397.  The kit is just over 120MB compressed.   After downloading the kit, simply run the installation program to extract the contents to your local machine.  Once the installation process is complete, you will see an HTML page that allows you to navigate through the contents of the kit.  

  Posted on: Tuesday, November 20, 2007 10:51:38 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
         
Gill Cleeren     .net | .net 3.5 | Visual Studio.net     November 19, 2007    

Yes, it's here, the eagle has landed!

Visual Studio 2008 has RTM'ed! If you're an MSDN subscriber, you can start your download engines, it's a whopping 3921 MB large file for the entire Team Suite.



From MS PressPass:
"On Monday, Nov. 19, Microsoft announced that Visual Studio 2008 and the .NET Framework 3.5 were released to manufacturing (RTM). With more than 250 new features,Visual Studio 2008 includes significant enhancements in every edition, including Visual Studio Express and Visual Studio Team System. Developers of all levels – from hobbyists to enterprise development teams – now have a consistent, secure and reliable solution for developing applications for the latest platforms: the Web, Windows Vista, Windows Server 2008, the 2007 Office system, and beyond."

You want it? Of course you do!

  • MSDN: Download full RTM now
  • Download Trial Editions of Visual Studio 2008
  • Download Visual Studio 2008 Express Editions
  • Download the .NET Framework 3.5
  • ISO of the Express Editions (800MB)


    More here:

     

  •   Posted on: Monday, November 19, 2007 1:39:27 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | .net 3.5 | ASP.net | Links | Programming | Silverlight     November 12, 2007    

    Here are some links you might find useful:
    -LINQ cookbook: series of solutions to specific scenarios, that the team comes across when writing code and using queries
    -Nice intro to ASP.NET MVC framework
    -Looking for a replacement for FreeTextBox? Maybe this newly created rich text box for ASP.NET is the solution: http://www.codeplex.com/rte



    -Automatic Properties and Initializers in C# 3.0: a nice introduction on these new features in C# 3.0.

    I hope you can find some use of these links. Feel free to post interesting links in the comments!
      Posted on: Monday, November 12, 2007 9:16:21 PM (Romance Standard Time, UTC+01:00)   |   Comments [2]
             
    Gill Cleeren     .net | Silverlight | WPF     November 12, 2007    

    Since the dawn of WPF (Windows Presentation Foundation), it became easy for developers to create applications that were nearly impossible to create without it. Creating animations, transformations, gradients is as easy as 1-2-3. In the end, the user who has to work with the application will benefit from this. The User Interface is what you are looking at every day, so don't you want it to look at least a little nicer than the old-school grey?

    Sadly enough, I still hear people complain that UI is not important, which is ignorant in my opinion(Ignorance is bliss, they say, however in this case, I beg to differ). If you have the nicest architecture imaginable, if your application is developed with the latest best practices or if you used the newest ways of service communication, it all falls apart when your application looks like it was developed in the 90's. The end user will not see this.
    Take your average customer and present him an ugly and nicely architectured program, and another one, only this time with a really cool looking UI, but not developed as it should.
    Which one will he choose? I would bet my money on the latter one.

    Maybe it's not obvious at first sight, but I'm sure that users really look for nicer looking apps. Computers are capable of displaying nicer graphics, well then, use this possibility.
    I rest assured that WPF and Silverlight really are the platforms to develop next-gen applications.

    In a question to Dino Esposito on DevConn07 on the fact if Silverlight and WPF will replace Winforms and ASP.net, he says the following:

    I firmly believe that the two worlds—Web and Windows—will remain neatly separated for most of the foreseeable future.  At the same time, though, the advent of WPF and Silverlight generates many more possibilities of interaction between Web and Windows that were just impossible or impractical before.  Once the next Silverlight is available you can develop for the Web with much of the same ease you experience today for the desktop. You could even get to the point of using the same WPF document to power the Web and Windows front-end of a multi-tier system. Well, not for free, but is definitely a scenario that the use of proper design patterns (i.e., the Model-View-Presenter pattern) may enable. At that point, I believe that you just have two options--deluxe experience with a 100% Silverlight solution or normally rich Web experience with a combination of AJAX and Silverlight in the same ASP.NET page. With Silverlight used in this case as a rendering engine for special data.

    To be more direct with the question: For Silverlight and WPF to dethrone ASP.NET and AJAX all developers on all platforms must agree to use it. Technologically speaking, nothing prevents this from happening. In practice, though, I wouldn’t bet on it. But I see a lot of interaction taking place between Silverlight and ASP.NET AJAX applications.

    I do think the same. I'm not suggesting WPF and Silverlight will replace ASP.net entirely, but I do believe that in the NEAR future, when the demand for RIA's (rich interactive applications) will rise, those companies that are ready for this, will profit from this.

    Do note that I'm not promoting bad architecture in my opinion here, quite the opposite in fact. BUT I reckon that it should be in combination with a well designed user interface, using the newest applicable technologies. I'm trying to convince people to start thinking this way... Let's hope for the best.

      Posted on: Monday, November 12, 2007 8:41:55 PM (Romance Standard Time, UTC+01:00)   |   Comments [1]
             
    Gill Cleeren     .net | Programming tools     October 8, 2007    

    I came across 2 interesting plugins for Visual Studio 2005 today, that could make your life as a developer a little easier again.
    The first one is a UML designer that integrates with the IDE. Best of all, it's completely free. To download it, go here (registration required, but as said, free!).

    As with everything, best things come in pairs. The second plugin is a new ORM tool that also integrates with Visual Studio 2005. It provides a rich API and a powerful definition generator which, with a few clicks, transforms your database into a full featured business object model, following the powerful Active Record pattern.

    To download (a free edition is available, see website for details on usage), go here.

    Now go and play with these new tools! If you have any good (or bad) experience with them, please share.

      Posted on: Monday, October 08, 2007 9:38:53 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Silverlight | Visug | WPF | XAML     August 10, 2007    

    I'll be doing a session on Silverlight next month, on September 20th for Visug, the Belgian Visual Studio User Group. In this session, I'll give an overview of XAML too, so that if you've got no knowledge, you'll still be able to follow the entire session. This event will take place in the Ordina (my company) buildings in Schelle.

    I will announce the complete overview in a few days, as I'll be working on my session in the coming week (I have a week off, but I'll be working anyhow ;-) ).

    If you want to register for this free training, please go to www.visug.be and click on the event! So, what are you waiting for?!?!

      Posted on: Friday, August 10, 2007 11:12:59 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Visual Studio.net     August 2, 2007    

    Microsoft has released a long-awaited Web interface for Team Foundation Server.

    The Power Tool, dubbed Team System Web Access, is based on technology Microsoft acquired in March from DevBiz.

    The company had already made the 1.0 and 2.0 versions of DevBiz's TeamPlain tool available for download, but did not provide customer support, according to a blog post from Brian Harry, a Microsoft distinguished engineer.

    You can read more and download the tool here.

      Posted on: Thursday, August 02, 2007 8:55:12 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | .net 3.0 | WPF | XAML     April 12, 2007    

    As WPF is becoming more and more used, the list of available tools and controls is growing fast.

    Therefore, it seemed a good idea to list all the tools that I use or know but don't use yet, and share that list with you!

    Professional tools

    Visual Studio 2005
    There's no doubt that Visual Studio 2005 is the best environment for developing WPF applications. So, if you have access to it (via MSDN for example), I certainly recommend using it.
    However, out of the box, it has no knowledge of WPF projects, so you'll have to install some additional software.
    First, you should install the Windows SDK (free), then you should add the Visual Studio 2005 extensions for .net 3.0 framework (they also include templates for WCF). These extensions install the templates for development of WPF projects, and also add Intellisense for XAML code (on a sidenote, when writing XAML code, the Intellisense is not always correct in flagging errors, due to the fact that the extensions are still in CTP phase!)

     


    Also, you now get a designer for WPF applications, which is code-named Cider. The complete version will be included in the Orcas release.

    Visual Studio Orcas
    There's life after Visual Studio 2005! And it is known as Orcas. Visual Studio Orcas, the successor of 2005, will probably be released in Q4 2007, but you can download the CTP since a few months.
    Just recently, the March 2007 CTP was released, which is considered a milestone on the road to the complete product.

     
    So, what will Orcas bring to the world of WPF? It will include full support for designing WPF windows and web applications, with the completed version of Cider.
    For now, it's possible to start using Orcas. You can download the CTP here (large download, beware!)

    Expression Suite
    The Expression suite is a range of new products from Microsoft. The collection includes Blend, Web, Design and Media. Web is more or less the (very much improved) successor of FrontPage.

    Blend is the tool that is the most interesting for WPF developers/designers. It allows you to open a WPF project, design it in a very advanced environment using a wide range of tools (much like Photoshop, but for designing user interfaces). After you're finished, you can open the project in Visual Studio again.
    At this time, Blend is in RC, but since it's a public download, you can start using it right now. I hope I'll find some time to do a tutorial on Blend soon.

    Design, a professional illustration and graphic design tool, is still in beta 2, but also available for download already. Design fully supports export to XAML, which makes it easy to incorporate your graphics with your other XAML code.
    On a sidenote, Web has been released and you can download a trial here.

    Controls

    Infragistics NetAdvantage 2007 for WPF
    Infragistics recently released Beta 1 of their first WPF controls. The suite, which can be downloaded here for free, includes the xamDataGrid and xamDataPresenter controls (pronounced "zamDataGrid" and "zamDataPresenter").


    Some controls, like the xamCarouselListBox seem very promising and seem to make it very easy to add advanced features to your applications.
     

     

     

    ActiPro Ribbon
    Last week, I got a mail from ActiPro, to introduce me to their ActiPro Ribbon. The control features Office 2007-like user interface for the Windows Presentation Foundation (WPF) and meets all of the core Microsoft licensing requirements for implementation of a ribbon user interface. I must say, it looks very nice. You can download a demo here.

     
    XCeed WPF DataGrid
    I found this control via a banner on Scott Hanselman's site... These guys simply give away FOR FREE the entire control, which is a fully featured WPF datagrid. It's risky to say but I think this replaces the missing datagrid in WPF.

     

    When you register, the license is royalty free and perpetual. So, no excuse for not having this control in your toolbox.
    Here you can check out some demo's and get the control.

    Tools

    XamlPad
    XamlPad (xamlpad.exe) is a basic visual editor for XAML. If you installed the SDK, it's probably already on your PC, since it's part of the default install.
    XamlPad is quite basic, and some say not the most user friendly. Therefore, I recommend using one of the two following tools in this list for basic XAML.

    XamlPadX
    XamlPadX(Extended) is a somehow extended version of XamlPad and has some handy features. Some of its most important features (from the site):

    • A xaml writer which parses the object back into xaml and vice versa.
    • Simple command interpreter with limited intellisense (please look at help window for limitations).
    • Viewer of default styles
    • Automatically closing of tags
    • Line-numbering
    • Possibility to save in different locations
    • Indentation feature (!)

    You can download the lastest version here.

     

    Kazaml
    Another editor, which is now in alpha 2 phase, and is thus not yet complete. You can download it here and more info can be found here.



     

     

     

    Adobe Fireworks XAML exporter
    This free extension from Infragistics makes it possible to convert anything that's currently selected to XAML. You can download it here.

    Performance Profiling tools
    WPFPerf is a set of tools that can help you find performance issues in WPF. It included Perforator, Event Trace, Trace Viewer, Visual Profiler and Working Set Analyzer. There's a very in-depth article on MSDN that you can read here.

    LocBAML
    LocBAML is actually a sample included in the SDK. After you compile your XAML into an assembly, it can extract the strings and place them into a *.csv file. This file can then be translated, and the file can then be given again to LocBAML, which will create culture-specific resource DLLs. Handy for when you're translating your WPF application.

    Reflector
    Since Reflector updated to version 5, it supports the .net 3.0 framework, and thus WPF files can be extracted from assemblies.


    I hope you find in this list some tools that can help you explore the world of WPF.

    If you know another tool not listed here, or if you have developed a control/tool you'd like to see in this list, please leave a comment or send me a mail.

      Posted on: Thursday, April 12, 2007 11:49:41 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | Enterprise Library     April 6, 2007    

    Oh yes! What a present I get on my free day... Enterprise library 3.0 is released!
    Go here to download it.

    From Tom Hollander's blog:

    • Validation Application Block. Allows you to centrally define validation rules using configuration or attributes, and easily validate data from anywhere in your application, including deep integration with Windows Forms, ASP.NET and WCF.
    • Policy Injection Application Block. Provides a powerful approach for separating cross-cutting concerns from business logic using declarative policies that are attached at runtime to methods on your objects.
    • Application Block Software Factory. Dramatically simplifies the process of building application blocks and providers through the magic of guidance automation.
    • Visual Studio-integrated Configuration Editor. Edit Enterprise Library configuration files directly within Visual Studio.
    • Environmental Overrides. Use the configuration tool to specify configuration settings that are common or different across multiple environments, and merge this information into configuration files to be deployed with your applications.
    • WCF Integration. Easily integrate the Logging, Exception Handling and Validation Application Blocks into service interfaces built using Windows Communication Foundation.
    • Pre-compiled, strong-named binaries. No need to compile and strong name the code unless you want to manage and evolve the code yourself.

    If you want to start using the new Validation Application Block, be sure to check out my tutorial I wrote some time ago!

      Posted on: Friday, April 06, 2007 11:00:44 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | ASP.net     April 5, 2007    

    A few days ago, a collegue asked me how it was possible to add tooltips to a gridview's header. This property is not present on the gridview by default.

    A few solutions came to mind. The first solution I thought of consisted of adding attributes to the cells. However, this seemed not to work.
    My second solution consisted of a client-side solution. Since I've been creating Vista Sidebar Gadgets, I've solved several problems with Javascript, and this one too seemed candidate to be solved with it.

    In this sample, I will explain how I added tooltips to the ASP.net 2.0 gridview header.

    First, we'll do some preparing work.
    Let's add a simple gridview to the page. I created a small database, and simply dragged a table from the server explorer into the Visual Studio designer.

    This gave me a simple gridview as can be seen on the figure on the left. What do you think about the great layout ;-) ?

    So far, not so exciting!

     

     

     


    Creating script from code-behind
    We'll use an javascript array of strings, that we create in the code-behind. This makes it possible to have the tooltips multilangual, which is often a requirement (in my case, it was).

    In the following code, I'll make use of the ClientScriptManager class and RegisterStartupScript method. The script added by the RegisterStartupScript method executes when the page finishes loading but before the page's OnLoad event is raised (from MSDN Library).

    private void AddTooltipToGridHeaders() { ClientScriptManager cs = Page.ClientScript; String csname = "ConcatScript"; Type cstype = this.GetType(); if (!cs.IsStartupScriptRegistered(cstype, csname)) { System.Text.StringBuilder cstext = new System.Text.StringBuilder(); //build client script from code-behind cstext.Append("<script type=\"text/javascript\">"); //this values can be added or translated string arrValue = "\"" + "CustomerId" + "\"," + "\"" + "Firstname" + "\"," + "\"" + "Lastname" + "\"," + "\"" + "Street" + "\"," + "\"" + "Number" + "\"," + "\"" + "ZIP" + "\"," + "\"" + "City" + "\"" ; //create array of the values cstext.Append("var ToolTips = new Array(" + arrValue + ");"); //call the javascript method defined in the aspx cstext.Append("gvAddToolTips(document.getElementById('" + GridView1.ClientID + "'), ToolTips);"); cstext.Append("</script>"); //register the script when the page finishes loading cs.RegisterStartupScript(cstype, csname, cstext.ToString(), false); } }


     Using the array in client side script

    The following function is added to the HTML/ASPX code. In this function, I first test if the TBODY tag is present, I use the firstChild method to retrieve the header row. If it isn't, I use the nextSibling method.

    In the for-loop, I loop through the cells of this row (headerRow.children) and set the title to the corresponding value of the array. The array is available from the code above.

    <script type="text/javascript"> function gvAddToolTips(gv, colTooltips) { var tableBody = null; if(gv.firstChild.tagName == "TBODY") { tableBody = gv.firstChild; } else { tableBody = gv.firstChild.nextSibling; } var headerRow = tableBody.firstChild; //check if the array has the same number of items than there are rows if(colTooltips.length > headerRow.children.length) colTooltips.length = headerRow.children.length; for(var i=0; i<colTooltips.length; i++) { var tableCell = headerRow.children[i]; tableCell.title = colTooltips[i]; } } </script>

    The result can be seen on the following image.

      Posted on: Friday, April 06, 2007 12:27:45 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Vista     April 3, 2007    

    Appeanantly, I have missed this one when it was released last week... Anyway, you can download the new MSDN Library, April 2007 Edition, which includes Visual Studio 2005 Service Pack 1 documentation, here.

    From the release notes:
    Updated content sets in this April 2007 Edition include:

    • Visual Studio 2005 Service Pack 1 documentation
    • Visual Studio 2005 general documentation updates
    • Windows Vista Developer documentation
    • Windows® Driver Kit (WDK) documentation
    • SQL Server™ 2005 Books Online product documentation
    • SQL Server 2005 Compact Edition Books Online
    • Microsoft Knowledge Base
    • And More...



    Beware, it's a hefty 2GB+ download!

      Posted on: Tuesday, April 03, 2007 9:40:13 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming tools | WPF     March 25, 2007    

    Last year, I had the opportunity to have a lunch meeting with Lutz Roeder. I was able to talk with him about life at Microsoft in Redmond, the creation of the Expression suite, and of course, Reflector, the very popular .net class browser, used by every .net programmer that respects himself!
    Since a few weeks, the new version of this popular program was released, version 5 that is.
    In this article, I’ll discuss some of the new functions and also some of the lesser known functions that were already in previous versions, so you can get the most out of this magnificent tool.

    Obtaining the newest version
    First, if you haven’t done already, download Reflector here:
    http://www.aisto.com/roeder/dotnet or if you have an old version installed, you can have it auto-update via the Help menu. There are a great number of extensions available. These are put together on a codeplex site that can be found here: http://www.codeplex.com/reflectoraddins.

    Getting started with version 5

    One of the very handy new functions is the possibility to register Reflector with Explorer. This way, Reflector will become the default option for your DLL files.



    Double-clicking on any .net DLL will open Reflector, and you’ll be able to see the contents of the assembly.
    To do this, open a command window, browse to the directory where you have extracted Reflector and run the following command: Reflector /register .You should now get a message that registering went OK, as can be seen on the image below.

     

    Assembly lists

    If like me, you use Reflector a lot, perhaps on different projects, the list of assemblies in Reflector can become very long. On top of that, the memory use is way higher (I noticed that on my PC, don’t know if this is the case everywhere though) if you have more assemblies loaded in the browser.

    There is however a feature that can help solve this annoyance: assembly lists. Press CTRL-L or File
    à Open List to open the Assembly List Management dialog.


    As you can see, I have a number of lists in my window. Each of these corresponds to a list of DLLs that will be displayed in the browser when loaded.
    You can create a new list, which is blank by default. In the browser, you can then load assemblies that will only be displayed when that particular list is selected.

    Code URL

    Something completely new in version 5 is the so-called “Code URL” support.
    Simply select any item in the browser and press Ctrl-Alt-C. This will copy the code-URI for that item in the following format (I selected System.Web.HttpCookie): code://System.Web:2.0.0.0:b03f5f7f11d50a3a/System.Web.HttpCookie.

    If you have Reflector installed, clicking the following link in IE will fire up Reflector and immediately browse to the class/method/assembly described in the URL. You can test it with the following link: code://System.Web:2.0.0.0:b03f5f7f11d50a3a/System.Web.HttpCookie.
    This feature can also come in handy to pass a link to a colleague, even over MSN!

    .net 3.5 support

    Even though it is still some months away, Reflector already offers support for .net 3.5. You can enable it via the Options window.

    Included in .net 3.5 are C# 3.0 and LINQ. Reflector now includes full support for both of these.

    Also, it now offers support for anonymous methods and nullable types.

    The new assembly browser
    The most important part of Reflector is of course the assembly browser itself. While it was already fast, it didn’t include the possibility to open multiple windows at the same time. That limitation is now gone! For example, you can open the Analyzer and the Disassembler at the same time.

    Disassembler and Analyzer

    Both the Disassembler and the Analyzer got some new functions in this new release.
    The Disassembler now has a “Expand Methods” function, that, like the name says, will expand all functions right in the same window.

     

     

    The result:

    The Analyzer, which you can find by right-clicking an assembly, also has some new functions: Exposed by, Instantiated by and Assigned by.
    These functions can greatly help you in funding where certain classes are used within the assembly.

    BAML Disassembling

    While Reflector is great, the extensions available for it make it even greater.
    Personally, I do a lot of WPF, and it’s very handy to be able to read the XAML code for things you encounter on the net. For this, we now have the BAML Disassembler. You can read more on this extension here:
    http://wpfwonderland.wordpress.com/2007/01/27/reflector-and-wpf-baml-disassembler-revisited/


      Posted on: Sunday, March 25, 2007 3:48:54 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | ASP.net | Atlas     February 12, 2007    
    • An interesting article on CSLA.net, ADO.net Entity framework and LINQ. More here
    • WinDevPowerTools on The MicroISV Show: more here
    • Continuous Integration the Microsoft way!!! - level 200: here
    • New ASP.net Ajax book coming up: http://www.manning.com/gallo/
    • “WPF/E” (codename) Community Technology Preview Sample Pack (Feb 2007): here

    Enjoy!

      Posted on: Monday, February 12, 2007 11:35:32 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C#     February 8, 2007    



    DinnerNow

    DinnerNow.net V1.0 is released.

    DinnerNow is a fictious marketplace where customers can order food from local restaurants for delivery to their home or office. This sample is designed to demonstrate how you can develop a connected application using several new Microsoft technologies.

    The demo utilizes several technologies including: IIS7, ASP.NET Ajax Extensions, Linq, Windows Communication Foundation, Windows Workflow Foundation, Windows Presentation Foundation, Windows Powershell, and the .NET Compact Framework.

    The DinnerNow sample application is now available for download. You can download the entire DinnerNow sample code from CodePlex.

    It's a free download, you can get it here.

      Posted on: Friday, February 09, 2007 12:11:55 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net     February 8, 2007    

    The new circular loading icon in Windows Vista is kinda neat. Here's how to make it: http://www.codeproject.com/cs/miscctrl/mrg_loadingcircle.asp

    There are times when our web form will be performing lengthy tasks (e.g. reading a file, retrieving high volumes of data, or maybe calling a remote web service, etc...). Here's how to do it: http://gbarnett.org/archive/2007/02/08/asynchronous-programming-in-asp-net.aspx

      Posted on: Friday, February 09, 2007 12:09:16 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming tools     February 6, 2007    

    "Refactor! is freely available to all ASP.NET 2.0 developers and offers a comprehensive suite of tools that enable you and your team to simplify and shape complex code and HTML markup - making your web applications easier to read and less costly to maintain."

    You can download it here: http://www.devexpress.com/Products/NET/IDETools/RefactorASP/

      Posted on: Tuesday, February 06, 2007 3:58:01 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Atlas | Microsoft | Visug     January 21, 2007    

    Snowball.be has a first for you!

    As webmaster of Visug.be, I just finished the work on the the registration page for this groundbreaking event: Scott Guthrie is coming to Belgium, and moreover, he's coming to Visug, the Belgian Visual Studio User Group.

     scott.jpg Scott Guthrie, co-creator of ASP.NET at Microsoft, will be in Belgium for the first time onFebruary 1st 2007.

    VISUG is very proud that it can host - in collaboration with MSDN Belux - 2 presentations of this renowned speaker.

    In the first presentation, Scott will talk about the next version of ASP.NET, code named ASP.NET “Orcas”; during the second presentation Scott will give practical tips and tricks on ASP.NET 2.0 and ASP.NET AJAX.

    Want to join this unique oppurtunity? Register here!

    Update: location is confirmed: Utopolis Mechelen!
      Posted on: Sunday, January 21, 2007 9:31:43 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | WPF     January 14, 2007    

    As Vista's launch is almost upon us, WPF and with it .net 3.0 are becoming more and more used.
    Just a couple of days ago, Yahoo (still my favorite start page) has announced that they'll be launching an entirely new version of their web messenger, written in .net and WPF.


    You can see it (with all kinds of typical WPF controls) in action here: http://messenger.yahoo.com/vista.

      Posted on: Sunday, January 14, 2007 11:18:27 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Enterprise Library     January 7, 2007    

    For some of my latest projects, I have been using Enterprise Library for the Data Access Layer (combined with other technologies).
    The week before Christmas, Tom Hollander, who leads development of the Enterprise Library, announced the first CTP of the enterprise library V3.0.
    This weekend, I decided to do a first test drive with it, since a lot of features that are now included (or will be included in the final release) seem very useful in the creation of enterprise applications.
    In this tutorial, I will explain the Validation Application Block, a complete new application block included in version 3 of the library. I’ll create some samples on how you can use the Validation block and I’ll also create a custom validator.

    Installation of the enterprise library V3.0

    As you probably guessed, to start using the EntLib V3.0, you should install the files. You can get the CTP from the all-new CodePlex.com site, entirely devoted to Enterprise Library. You should of course have Visual Studio 2005 installed on your PC. If you want to use the Guidance Packages, you’ll also need the Guidance Automation Extensions. You can read any further requirements in the Readme included in the download.
    When installed, you can find the library under Microsoft Patterns and Practices. As you can see, one of the items there is the Enterprise Library Source Code Installer. You can use this to create more than one “working copies” of the code included in the EntLib. Run this, you’ll be needing this if you want to follow along with this tutorial. I extracted the files to “C:\EntLib3Src”.
    In the folder, go to App Blocks à Src à Validation and open the project file you find here (Validation.csproj). To finish the installation, build the project. You’ll now have the DLLs needed to use the Validation Application Block.

    OK, but what is this Validation block then?

    Before I begin with the explanation on how to use the Validation Block, let me first introduce you to what it actually does and where it can be used.

    From Tom Hollander’s Blog:
    The Validation Application Block will include a comprehensive library of common validation rules that apply to primitive data types. For example, we'll include rules like string length, numeric range, date range, regular expressions and so on. However your applications will typically deal with more complex objects such as Customers or Orders (yes, here at Microsoft we assume every application is based on Northwind ;-), so while the built-in Validators should be great building blocks, you'll need to do some additional work to specify how these primitive rules apply to more complex objects. We plan on letting you do this in two primary ways: in configuration (which is ideal if you want the rules to be easily changed after deployment), or in code (which allows better encapsulation of rules and ensures the behavior won't change unless the code does).

    You can do validation using configuration, or you can do it in code. In this tutorial, I’ll be focusing on the code-approach using attributes, mainly because there is no support yet in the “Enterprise Library Configuration-tool” for this at this moment.

    Included in the library are a number of often needed validations: “not null”, string length, null… You can take a look at the included validators in the project you built earlier under Validation à Validators. In the final release, more will be added. In the first part of this tutorial, I’ll be using some of these to show you how it works.
    Of course, this collection will never be enough for full-scale enterprise applications, so you have the possibility to write your own validators, as I’ll show later in this tutorial.

    I’m convinced about the VAB! How can I use it?

    OK, now that you know what the block is about, let’s start using it. As said, in this first part of my tutorial, I’ll use some of the included validators.

    Create a new project in Visual Studio (I used a Winforms project and named it TestValidationApplicationBlock). While you’re at it, add a class library to the solution (for example: BLCustomers). This will be used as Business Layer in the sample application, and the objects in this layer will need to be validated using the Validation Application Block.

    In the class library, add a new class, Customer for example. Add 2 properties, name and email for example (you can of course take whatever you want).

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
    using Microsoft.Practices.EnterpriseLibrary.Validation;
    using MyCustomValidators;

    namespace BLCustomers
    {
        public class Customer
        {
            private string name;
            private string email;

            public Customer() { }

            public Customer(string name, string email)
            {
                this.name = name;
                this.email = email;
            }

            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            public string Email
            {
                get { return email; }
                set { email = value; }
            }
       }
    }

    To enable validation on this class, we first need to reference the necessary DLLs in this project. Right-click the “class library project” and select “Add reference”. Browse to where you built the enterprise library validation project, and in the bin folder, you’ll find 3 DLLs (Microsoft.Practices.EnterpriseLibrary.Common.dll, Microsoft.Practices.EnterpriseLibrary.Validation.dll and Microsoft.Practices.ObjectBuilder.dll). Reference these, and also create a reference to System.Configuration (which you’ll find under the .net tab).

    Now, we want to add some validation on the name and email properties of the Customer class. As said, we’ll use attributes on the properties. For example, we want the name to be a string with a length greater than 0, and we want both the email and the name to be not null.

    For this, we add the NotNullValidator and StringLengthValidator as attributes. The StringLengthValidator is overloaded: the first number stands for the lowerbound (we don’t want it to have a length of zero) and the second is the upperbound.
    Notice the extra “using” to be able to use the Validator attributes.

    using System;
    using System.Collections.Generic;
    using System.Text;
    using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
    using Microsoft.Practices.EnterpriseLibrary.Validation;
    using MyCustomValidators;

    namespace BLCustomers
    {
        public class Customer
        {
            private string name;
            private string email;

            public Customer() { }

            public Customer(string name, string email)
            {
                this.name = name;
                this.email = email;
            }

            [NotNullValidator]
            [StringLengthValidator(1, 100)]
            public string Name
            {
                get { return name; }
                set { name = value; }
            }

            [NotNullValidator]
            public string Email
            {
                get { return email; }
                set { email = value; }
            }
       }
    }

    At the moment, nothing actually triggers this validation yet. We can do this in several ways.
    The simplest manner is using the Validation façade, included in the VAB, as shown next.

    I have created a very simple interface in the Forms project, where the user can enter a name and email, as shown below.

    1.JPG

    In the click-event of the Validate button, the Customer instance is created. After that, the ValidateCustomer method is called, which is a method in the business layer. 

            private void btnValidate_Click(object sender, EventArgs e)
            {
                Customer customer = new Customer(txtName.Text, txtEmail.Text);

                MessageBox.Show(customer.ValidateCustomer());
            }


    Now, let’s take a look at the actual validation. This is performed in the business layer in the Customer class. Let’s look at the code.

            public string ValidateCustomer()
            {
                ValidationResults results = Validation.Validate(this);
                string message = string.Empty;

                if (!results.IsValid)
                {
                    // if this is not valid, we'll loop through the results to create the message
                    foreach (ValidationResult result in results)
                    {
                        message += result.Message;
                    }
                }
                if(message.Equals(string.Empty))
                {
                    message = "The input is valid!";
                }
                return message;
            }

    The ValidationResults is a collection of ValidationResult objects. When the Validate method is called, each attribute on every property is checked, and whenever one does not validate correctly, a new instance of ValidationResult is added to the collection. After the validation, you can loop through the collection to check the messages that were added (sort of “exception-messages” that are added). If all validation goes well, the IsValid method will return true.


    This concludes the first way of doing validation: we have not used the configuration files (which is however done very often with the enterprise library). We did use attributes and the Validate method to check if the object was valid.

    I said “the first way”… That means there are more ways of performing validation without using the configuration files? Yes, there is. In fact, this second method will look more familiar if you have used previous versions of the enterprise library.
    Other application blocks often make use of Factory methods (like for example the data access application block). The VAB also has a way of doing this.

    public string ValidateCustomerWithFactoryMethod()
            {
                string message = string.Empty;

                IValidator<Customer> validatorCustomer = ValidationFactory.CreateValidator<Customer>();

                ValidationResults results = validatorCustomer.Validate(this);

                if (!results.IsValid)
                {
                    // if this is not valid, we'll loop through the results to create the message
                    foreach (ValidationResult result in results)
                    {
                        message += result.Message;
                    }
                }
                if (message.Equals(string.Empty))
                {
                    message = "The input is valid!";
                }
                return message;
            }


    The result of the above code is the same.

    Creating your own Validators

    Up until now, we have used only the built-in validators. Nevertheless these are useful, a day will come (and if you’re developing large applications, it will come soon…) that they will not suffice. Therefore, the architecture of the VAB is open so you can easily create your own validators.
    In this second part, I’ll show you how.

    Let’s assume that we want to create an email validator. For the sake of simplicity, we’ll have it check if the string contains an “@” character.

    To start, let’s create an additional project in our solution named MyCustomValidators. Make this project a class library too. Add the same references as you did with the BLCustomers project.

    Create a class named EmailValidatorAttribute. This will be the attribute we’ll be adding to our Customer object later on.
    For a class to be used as an attribute, it must among others things, inherit from Attribute. We’ll have it inherit from ValidatorAttribute, that already inherits from Attribute.

    public sealed class EmailValidatorAttribute : ValidatorAttribute
        {
            public override IValidator CreateValidator()
            {
                return new EmailValidator(this.GetMessageTemplate());
            }
        }

    Now, let’s create the actual EmailValidator class, which is where the actual validation will take place.

        public class EmailValidator : ValidatorBase
        {
            public EmailValidator()
                : this(null)
            { }

            public EmailValidator(string messageTemplate)
                : base(messageTemplate)
            { }

            protected override void DoValidate(object target, ValidationResults validationResults)
            {
                try
                {
                    string converted = (string)target;
                    if (!converted.Contains("@"))
                    {
                        this.AddResult(validationResults, new ValidationResult(this.MessageTemplate));
                    }
                }
                catch
                {
                    this.AddResult(validationResults, new ValidationResult(this.MessageTemplate));
                }
            }

            protected override string GetDefaultMessageTemplate()
            {
                return "This is not a valid emailaddress since it does not contain the @ character";
            }
        }

    It inherits from ValidatorBase, and overrides 2 methods in particular: DoValidate and GetDefaultMessageTemplate.
    In the DoValidate method, the actual validation is done: here, I have written a few lines of simple code to check whether the passed string contains a “@”.
    If the string does not include this character (and is therefore not an email address), a new instance of ValidationResult is added to the collection. The message that is included here is the string returned from GetDefaultMessageTemplate.

    Now, we can use our own attribute. Return to the Customer class and add the EmailValidator-attribute to the email property.

            [NotNullValidator]
            [StringLengthValidator(1, 100)]
            public string Name
            {
                get { return name; }
                set { name = value; }
            }

    When you run the application again, and you enter a string without a @ as email, you’ll get a message window with the message you included in the EmailValidator class.


    I hope this will help you understand the Validation Application Block. If you have any questions, please feel free to post them.

      Posted on: Sunday, January 07, 2007 9:51:16 PM (Romance Standard Time, UTC+01:00)   |   Comments [4]
             
    Gill Cleeren     .net | Programming tools     January 2, 2007    

    I found this post very interesting. It contains a list of all tools a .net developer should have installed to work efficiently.
    Take a look here.

      Posted on: Tuesday, January 02, 2007 12:49:37 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Programming     January 1, 2007    

    In this first part, I will show you how to set up a portal with DotNetNuke.
    If you’re a beginner with DNN, you probably won’t be starting by cracking open the core of the framework. Instead, you’ll want to get your first DNN site up and running as soon as possible. Therefore, I advise you to download only the following files from the DNN site:

    • DotNetNuke 4.X Starter Kit
    • DotNetNuke 4.X Docs (optional)

    I included the Docs-download, since you’ll be needing that sooner or later anyhow, when you’ll be delving deeper into DNN (and I’m sure you will after reading my article!).

    The starter kit includes everything you’ll need right now: it’s a VSI (Visual Studio Content Installer) file, which will install a number of project and file templates to create your site and your modules in no time. In this very first part, we’ll be using the project template to create the site.

    So, go ahead, and let the installer to its work. It’s recommended that you exit Visual Studio while installing, to prevent files from being locked. Should you get a warning while installing, simply ignore and continue the installer.

    1.JPG

    Now, let’s open Visual Studio. By using one of the installed templates, we’ll have it create an entire web application for us. Remember that I said earlier that DNN was written in VB.net? Well, therefore, you will see the some templates only when you select VB.net in the language selector.

    Select “Create New Website” , and set the language to Visual Basic. You should now be able to select “DotNetNuke Web Application Framework”. Select the location for your site and give it a name and finish by clicking OK. For now, let it install on the file system. Depending on your computer, it will take up to a few minutes before your site is ready.

    2.JPG

    When finished, you’ll see a HTML page in the editor window of your IDE, where all the additional actions you need to do are explained.
    Because the explanations are not very long, I’ll go in a little more detail here.

    First, create the database. You can use SQL Server 2000, SQL Server 2005 or SQL Server 2005 Express. I’ll be using SQL Server 2005 for the rest of this explanation; the other versions are very similar.
    Open SQL Server Management Studio, and create a new database. I’ll name my database ArticleDemo, but you can name it whatever you like.

    3.JPG

    I use a “testuser”-account for the login on the database (so no trusted connection). For this, I created a login on the database server, and added this user to the users of the database.

    No further actions are needed on this database, all tables and stored procedures will be created via script when you first run your portal.
    Now we’ll be creating the site on IIS 7. Earlier, we let the site create on the file system. However, there is a known bug in DNN at the moment, that will make it impossible for users to subscribe on your site if you use the internal ASP.net server instead of IIS. Therefore, we’ll use IIS!

    Open IIS 7, and right-click on “Web Sites”, then select “Add Web Site”. In the dialog, enter the name of your site (I entered DemoDNN), and set the Physical Path to the directory where you let Visual Studio extract all the files. You can select to either use the DefaultAppPool, which is new in IIS 7, or you can use the IIS 6 model by selecting the “Classic .Net AppPool”, which is what I selected here.

    To end with, set the port to something else than 80 (for example, 81 is OK). If you use my settings, you’ll be able to browse to your site via this URL: http://localhost:81/DemoDNN .

    4.JPG

    To be able to debug our portal from Visual Studio, Windows Authentication must be enabled.Under Authentication for the new site, simply enable Windows Authentication. If you have not configured IIS 7 correctly, you won’t be able to select this! See my other article to do this!

    6.JPG

    Since I’m doing this installation with Windows Vista, I’ve shown the necessary steps to get DNN running on IIS7. If you’re using Windows XP, you’ll be using IIS 5.1. In 5.1, you can’t create more websites than the default web site. In this case, you’ll be creating a virtual directory under this default web site, and you’ll connect to http://localhost/DemoDNN . If you use Windows 2003 with IIS 6, the set up is analogue.

    To configure IIS 7 correctly to be able to debug from Visual Studio, see my other article!

    Only 2 things left to do now.
    First, we’ll make some changes in the web.config to make DNN use the newly created database. So, go ahead and open the web.config file. First, search for the connectionstrings-tag. You should see the following:

    <!-- Connection String for SQL Server 2005 Express -->

        <add

          name="SiteSqlServer"

          connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|Database.mdf;"

          providerName="System.Data.SqlClient" />

        <!-- Connection String for SQL Server 2000/2005

        <add

          name="SiteSqlServer"

          connectionString="Server=(local);Database=DotNetNuke;uid=;pwd=;"

          providerName="System.Data.SqlClient" />-->

    As you can see, this is a connection-string that’s OK should you be working with SQL Server Express and a datafile as database. In my case, it’s not what I need, since I’m using SQL Server 2005. So, comment out the first “add”, and uncomment the second one. Then, make the necessary changes to this one: use the correct server name, database name, user ID and password. I have created a login “testuser” on the database, with the password also set to “testuser”.
    In my case, this is what the connection string will look like:

    <connectionStrings>

        <!-- Connection String for SQL Server 2005 Express -->

        <!--<add

          name="SiteSqlServer"

          connectionString="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|Database.mdf;"

          providerName="System.Data.SqlClient" />-->

        <!-- Connection String for SQL Server 2000/2005-->

        <add

          name="SiteSqlServer"

          connectionString="Server=vista;Database=ArticleDemo;uid=testuser;pwd=testuser;"

          providerName="System.Data.SqlClient" />

      </connectionStrings>


    Now, you have to change this connection string on one other place in the web.config. In the appSettings-tag, you’ll see the following line:

    <add key="SiteSqlServer" value="Data Source=.\SQLExpress;Integrated Security=True;User Instance=True;AttachDBFilename=|DataDirectory|Database.mdf;"/>

    Change the value-attribute to the same connection string as above, so in my case, you’ll get:

    <add key="SiteSqlServer" value="Server=vista;Database=ArticleDemo;uid=testuser;pwd=testuser;"/>

    You can now save the web.config.

    The last thing we have to do before we can actually test the portal, is change the server on which your application should run.
    Right-click on the project in the solution explorer, and select “Property Pages”. In the left-menu, select “Start Options”. Under “Server”, you’ll see that it is now set to “Use default web server”, in this case, the internal ASP.net server. Remember that this is not what we wanted, so we’ll have it call IIS. Therefore, select “Use custom server”, and enter as Base URL the URL you specified in IIS (in my case: http://localhost:81/default.aspx ) .

    Finally, click OK to close.

    5.JPG

    That’s about it! Now, let Visual Studio build the project, for now, we’ll do a debug build. Simply hit F5, and the build process will start. After a few moments (the first build is normally quite slow, so it might actually take a few minutes…), your browser will open.

    At this point, DNN will start executing scripts (all called via code) and extracting files. This will also take a few minutes. Some versions of DNN throw an error here on the AppDomain being unloaded. You can ignore this however.

    If you’re using DNN 4.4.0 or higher like me, the install will be shorter, because less is installed by default.

    7.JPG

    To finally access your portal, and see the result of all your hard work, click on the link at the bottom of the page. You should see the following screen.

    8.JPG

    There you go, your portal is ready! The installation was not that hard, was it?
    In the next part, I’ll take you through the basic administrator settings, so you can start customizing your portal (because the standard is just… let’s say “standard”)!

      Posted on: Monday, January 01, 2007 3:34:52 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | DotNetNuke | Programming     January 1, 2007    

    Lately, I have been doing a lot of projects with Dotnetnuke. I first started using it for my own use, but lately, I have used it to create some large portal sites for some of our customers.

    To start with, let me first introduce Dotnetnuke (DNN). The very first sentence on the DNN homepage states the following: DotNetNuke is an Open Source Framework ideal for creating Enterprise Web Applications.

    Let’s analyze this sentence, shall we? For starters, it’s a framework that you can use out-of-the-box to set up a portal site. Included in the download package are a number of modules that are sufficient to build an entire portal. Modules included vary from a simple HTML module to an entire forum and an image gallery. Of course, these are not enough to build an entire enterprise application. But DNN is very versatile, and so for every need, new modules can be build.
    Since it’s an open-source project, it’s easy to tweak the framework where needed, to meet the needs of the application you are designing with it.

    Sometimes, if an web-application is needed very fast, nothing comes close to use a portal framework like DNN. Lately, I have built the new Visug (Visual Studio User Group: www.visug.be ) site with DNN. We needed a site quickly, and DNN brought us the solution.
    Some people I met are skeptical towards the use of DNN. The main concerns are mostly speed, reliability and not being in control. Personally, I admit that sometimes the latter can be true. I have had some problems with included features that are hard to override or undo. But since it’s open-source, I have been able to conquer them all.

    One little thing, though. DNN is written in VB.net (the core and the core modules, that is). If you’re like me and you don’t program in VB.net, but still want to develop modules, you can do so in C#! Since Visual Studio 2005, it’s not a problem to have a solution with VB.net and C# files. Should you require to modify some core settings, you’ll have to write your code in VB.net, however.

    So, now that I have been using DNN for several large projects, I have decided to share my knowledge on it via a series of articles.

    In the first article, I will discuss how to install DNN and create the first portal with it. In the articles to come, I will show you how to create a module, how to skin the portal and how to extend DNN to use it to create full enterprise applications where DNN is used in a SOA environment. Stay tuned!

      Posted on: Monday, January 01, 2007 3:29:31 PM (Romance Standard Time, UTC+01:00)   |   Comments [2]
             
    Gill Cleeren     .net | C# | Programming     December 26, 2006    

    Since I didn't spend much time on the computer these last days, I hadn't noticed that last Friday, December 22nd, Enterprise Library V3.0 CTP was released! Shame on me ;-)

    If you don't know what EntLib is, here's a short description: The patterns & practices Enterprise Library is a library of application blocks designed to assist developers with common enterprise development challenges. Application blocks are a type of guidance, provided as source code that can be used "as is," extended, or modified by developers to use on enterprise development projects.

    I used it myself in 2 projects, and I'm very pleased with it.
    In V3.0, some new features will (of course) be included, which will make it more complete. No complete lists is available, but here's an overview.

    Core

    • Source Code installer
    • Partial Trust Support
    • Strong-Named Binary Assemblies

    Validation Application Block

    • Core validation API
    • Minimal Validator Library
    • Attaching validators to objects via attributes
    • Attaching validators to objects via configuration
    • Not included yet (but in the works): Configuration tool support, complete validator library, integration with ASP.NET, Windows Forms, WCF etc.

    Data Access Application Block

    • SQL Server Compact Edition Support
    • New Database.UpdateDatabase overload with updateBatchSize parameter

    Configuration Tool

    • Visual Studio IDE integration
    • AppSettings support
    • Encryption support

    Application Block Software Factory

    • Templates and recipes for creating application blocks and provider libraries
    • Preliminary documentation

    Strong Naming Guidance Package

    • Recipes to assist in strong-naming and updating [InternalsVisibleTo] across multiple projects

    If you're like me, you are gonna play with it already! So, download it here on the new Codeplex-site!

      Posted on: Tuesday, December 26, 2006 12:36:34 PM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming | WinFX | WPF | XAML     November 7, 2006    

    The .NET Framework 3.0 has officially been released!  You can download the .NET Framework 3.0 components here:

    If you use Vista, they are installed by default.

    Th  If you have a previous CTP installed, please be sure to review the uninstall instructions

      Posted on: Tuesday, November 07, 2006 11:09:54 AM (Romance Standard Time, UTC+01:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Vista | Visual Studio.net | WinFX | WPF | XAML     November 2, 2006    

    With Windows Presentation Foundation coming closer to its release date with Vista almost being upon us, more and more people are taking a look at programming in WPF… Lately, people searching on Google for WPF-related information is soaring. How do you know that, you might ask? Well, in my logs, I notice a steep increase in people landing on my blog who searched for information on WPF. That’s a good thing!! ?

    However, what I do notice, is that there is still some confusion on some topics.  In this article, I want to help clear out the difference between the different application types in WPF/Vista. Since this is a major change with previous application models, lots of people, including me when I first heard about it, seem confused.

    So, let’s get to it!

    WPF has 2 main applications models: standalone and browser. On the other hand, it also has 2 types of navigation: menu-driven, which is what we’re all used to in traditional Windows applications and link-driven, which is the default for web applications. The first thing to note is that in WPF, both types of navigation can be used in either of the application models. Neat, isn’t it?
    That basically means that you can create a web application as if it were a windows application, containing a menu to navigate around. Or, create a standalone desktop application that feels like a web application, with all buttons replaced by links.
    No longer are you bound to one application model with is “natural” navigation model!

    Standalone applications

    When you want to create a “traditional” Windows application, you should choose to create “Windows Application (WPF)”.

    The Windows Form now became a Window, each of these is declared as Window1.xaml. Notice that the build action for a Window file is automatically set to Page. What this means, is that the markup is turned into a special type of resource that can be identified uniquely by a Uniform Resource Identifier (URI). This way, WPF can load the window using a URI, as is done set the starting point in your App.xaml.

    <Application x:Class="WindowsApplication2.App"
        xmlns="
    http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="
    http://schemas.microsoft.com/winfx/2006/xaml"
        StartupUri="Window1.xaml"
        >

    This way, your application knows which window it has to load up first. This window is loaded modeless, meaning that it has no problems with you clicking anywhere else in the application.

    Page’d applications

    Should you want to create an application that mimics the web experience but still run as a standalone application, you should start by adding a Page(WPF).

    Just like in the Window, you can add controls and content to the page. However, when you change the startupuri in the App.xaml to your newly added page, some things will change.

    A window can host itself, like a form did in traditional Windows Forms programming. A HTML/ASPX page requires a browser. Now, we created a “standalone” application with the starting point set to a page. Kinda weird, right?

    Well, the Application class in WPF is smart enough to detect if your startupuri is set to a page. It will then create a window to host your application.


    Now, where does this “hosting window” come from?
    When the startupuri is set to a XAML page or HTML page, Application  creates an instance of NavigationWindow to host them. This class derives from Window but extends it to make it look like a mini-browser window, providing navigation buttons at the top.

    When content changes or when you click a link to navigate to another page, the previous content is added to the history. The management of the history itself is managed too by the NavigationWindow.

    XAML Browser applications

    The final type of application is the XAML browser application. While the previous type of application basically is a web application, being hosted in its own mini-browser, you can’t really take advantage of all the features modern browser have today. If that’s what you need, you should create a XAML browser application or XBAP.

    To create one, you should choose new “XAML Browser Application (WPF)”. After that, you can copy all the code you created for that WPF standalone application to one or more pages, and your application is ready for the web!

    One more thing you can do with XBAPs is publish them on a web- or intranet server. This is done using ClickOnce, which creates the executable along with 2 manifest files. One of these 2 has the extension XBAP, and that’s were the user navigates too. It then “downloads” the application to the local computer.

    Because of the security risk, XBAPs are not installed and run in a security sandbox: some operations like writing to the registry are not allowed. Basically, XBAPs can only do things that are allowed for apps launched from the Internet zone, a restricted set of operations.

    Conclusion
    As you can see, the ways an application is build are different from what you are used to in traditional programming. I hope this guide is clear enough to help you choose the correct type when building a WPF application for Vista.
     

      Posted on: Thursday, November 02, 2006 4:01:59 PM (Romance Standard Time, UTC+01:00)   |   Comments [1]
             
    Gill Cleeren     .net | Windows | WinFX | WPF     October 30, 2006    

    Today, I was installing the VPC (Virtual PC image) that Microsoft provides for all early adopters on future technologies, including .net 3.0. I intend to use this VPC for my presentation later this month.

    This image-file includes a whole lot of CTP/preview versions, as can be seen here.

    However, when opening the file, I received the following notice: E:\VPC\TimeBombedBase\Base01.vhd cannot be found... Appearantly, this is the parent image, of which the CTP is a differencing disk.

    On the setup instructions page, MS appearantly forgot to mention that this 4GB download also requires you to obtain the parent VPC image, a 1.1GB download...
    This file can be found here: http://download.microsoft.com/download/5/4/9/5499b008-8ae7-46f0-89ae-aeeb18df67ae/VSCTPBase.exe 

    Should you want to play around with .net 3.0/LINQ... and don't feel like installing all these on a VPC yourself, you can grab the download here: http://www.microsoft.com/downloads/details.aspx?FamilyID=82243606-d16d-445c-8949-9ee8c10cda2e&DisplayLang=en  

      Posted on: Monday, October 30, 2006 12:48:56 PM (Romance Standard Time, UTC+01:00)   |   Comments [4]
             
    Gill Cleeren     .net | ASP.net | Atlas     October 27, 2006    

    While I'm blogging this a few days too late, I still want to mention the release of the beta 1 of the Microsoft AJAX library, formerly Atlas.

    From Scott:
    You can download it now from the http://ajax.asp.net site. Available on the site are three download options:

    1) The ASP.NET AJAX v1.0 “Core” download. This redist contains the features that will be fully supported by Microsoft Product Support, and which will have a standard 10 year Microsoft support license (24 hours a day, 7 days a week, 365 days a year). The download includes support for the core AJAX type-system, networking stack, component model, extender base classes, and the server-side functionality to integrate within ASP.NET (including the super-popular ScriptManager, UpdatePanel, and Timer controls).

    2) The ASP.NET AJAX “Value-Add” CTP download. This redist contains the additional higher-level features that were in previous CTPs of “Atlas,” but which won’t be in the fully-supported 1.0 “core” redist. These features will continue to be community supported as we refine them further and incorporate more feedback. Over time we’ll continue to move features into the “core” download as we finalize features in this value-add package more.

    3) The ASP.NET AJAX Control Toolkit. This project contains 28 free, really cool, AJAX-enabled controls that are built on top of the ASP.NET AJAX 1.0 “Core” download. The project is collaborative shared source and built by a combination of Microsoft and non-Microsoft developers, and you can join the community or just download it on CodePlex today.

    I'm testing AJAX a lot at the moment, since I'll be using it for a new project at my company. Since this new application requires a lot of database calls, and works with large table, AJAX should provide me with a nice and responsive user interface combined with minimal load on the DB server.

    Oh, and while I'm on it... I recently became the webmaster of www.Visug.be , the belgian Visual Studio User Group, backed by Microsoft. So in the next few weeks, you'll be able to register over there for upcoming events (which will be announced very very soon!).

      Posted on: Friday, October 27, 2006 11:58:43 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming     October 22, 2006    

    Today, I was programming on the new www.visug.be of which I recently became the webmaster.
    I needed a time picker control for ASP.net. I already downloaded Basic Date Picker, which includes a date picker for free and a time picker. Sadly, the time picker isn't free.

    So I searched a little, and stumbled on a free library of custom controls which can be found here: http://www.eworldui.net/ .
    It includes among others a very nice Time Picker control for ASP.net, that works under ASP.net 1.1 and 2.0.
    Great controls, I must say!

      Posted on: Sunday, October 22, 2006 10:22:22 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | C# | Microsoft | Programming tools | WPF | XAML     October 20, 2006    

    My article on WPF (Windows Presentation Foundation) triggers and styles is online on the MSDN website! You can read it here!

    From MSDN:
    In this article, Gill Cleeren focuses on the aspect of styles and triggers in Windows Presenation Foundation. Styles make it possible to create applications with a uniform look and with a high level of maintainability. Triggers allow WPF styles to change one or more properties in response of a user interaction. In this document, we will use both these technologies to create a richer user experience.

    This is my first article on MSDN (more will come, now that I'm into it ;-) )

    Here's a screenshot of the MSDN Belux site (Click for larger version)



    Thanks to the MSDN Belux team, Wim Verhaegen and Tom Mertens.

      Posted on: Friday, October 20, 2006 1:38:00 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net     October 18, 2006    

    Today, I'm testing Infragistics NetAdvantage 2006 Vol 2 for CLR 2.0. It has all kinds of Ajax enhancements, and that's exactly what I need for a project I'm working on.

    I was installing the demo on a Virtual PC, and got the following error:
    Error message: Error 1609. An error occurred while applying security settings. ASPNET is not a valid user group. This could be a problem with the package, or a problem connecting to a domain controller on the network. Check your network connection and click Retry or Cancel to end the install.

    My first thought was that it was caused by ASP.net 1.1 not being installed on the system (since ASP.Net 2.0 does not install the ASPNET account). I didn't feel like installing .net framework 1.1, so I tried adding a user with the name ASPNET.

    And voila, it worked... Saved the day ;)

    Btw, you can set the account to inactive, so it doesn't appear at your login-screen!

      Posted on: Wednesday, October 18, 2006 3:00:19 PM (Romance Daylight Time, UTC+02:00)   |   Comments [3]
             
    Gill Cleeren     .net | ASP.net | C# | Programming     October 17, 2006    

    The november issue is available, free for download as always!

    This issue focuses on security and writing more secure code...

      Posted on: Tuesday, October 17, 2006 8:39:01 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Vista | WinFX     October 17, 2006    

    Free training alert!!!

    Microsoft Learning developed some free online training(Collection 5134 : Developing Rich Experiences with Microsoft® .NET Framework 3.0 and Visual Studio® 2005) that you can use for a limited time.
    You will learn how to develop rich experiences using Windows Presentation Foundation, Windows Workflow Foundation, and Windows Communication Foundation.

    This collection of 3 2-hour premium clinics teaches about the new capabilities provided by the .NET Framework 3.0. These clinics are for experienced Developers and Software Architects who are looking to adopt Microsoft's next generation technology within their solutions.

    From: Collection 5134 : Developing Rich Experiences with Microsoft® .NET Framework 3.0 and Visual Studio® 2005

      Posted on: Tuesday, October 17, 2006 8:28:30 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Vista | Visual Studio.net     October 4, 2006    

    A key Microsoft executive disclosed this week that the coming Service Pack 1 for Visual Studio 2005 may not be totally compatible with Windows Vista -- though it remains unclear what his statements mean.

    "Visual Studio 2005 SP1 will run on Vista but will likely have a few compatibility issues," said Somasegar's posting. "We are working with the Vista team to understand those, to provide workarounds where possible and also work on providing you with a set of fixes beyond SP1," he continued, although he did not reveal what the problems are or when those fixes will be made available.

    However, he did mention that Windows Vista will ship with the .NET Framework 3.0 pre-installed.

    More here.

      Posted on: Wednesday, October 04, 2006 2:40:45 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Atlas | Programming | Programming tools     October 2, 2006    

    From the site:

    Web.UI for ASP.NET AJAX is deeply integrated into the AJAX Library client-side type system:

    All controls inherit from the Sys.UI.Control client-side base class;
    All controls implement AJAX Library type descriptors, providing type information at runtime;
    The namespace and all types are registered with the AJAX Library type system;

    Web.UI for ASP.NET AJAX exposes comprehensive client-side APIs:

    An industry first, the same level of programmatic control is available on the client as on the server;
    The new APIs fully comply with the AJAX Library client-side syntax and semantics;
    State of the art client-side API reference documentation is included with the product;

    Web.UI for ASP.NET AJAX is optimized to work with the ASP.NET AJAX UpdatePanel control:

    All client-side programmatic changes are persisted to the server upon callbacks or postbacks;
    Proper client-side dispose mechanisms are used to optimize browser's memory consumption;
    Control footprint is highly optimized in order to provide the fastest callback response time.

    More here: http://atlas.componentart.com/

      Posted on: Monday, October 02, 2006 11:41:06 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming     September 29, 2006    

    Regular expressions... I don't like them. Or, no, let me specify: I don't like to WRITE them. Tools like The Regulator help create them, but they're not easy to use.

    I found a library in C# which contains a lot of predifined regular expressions: http://developer.coreweb.com/articles/Default15.aspx.
    Enjoy ;-)

     

      Posted on: Friday, September 29, 2006 9:20:23 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming | Vista     September 27, 2006    

    Yet another .net related release today: beta 2 of Powershell is available as from now.

    Today Microsoft announced the availability of Microsoft Windows PowerShell RC2, the command line shell and scripting language that helps IT Professionals achieve greater productivity and control of system administration. Using a new admin-focused scripting language and consistent syntax and utilities, Windows PowerShell accelerates automation.  Windows PowerShell is easy to adopt, learn, and use, because it works with existing IT infrastructure and scripting tools. 

    This Release Candidate 2 of Windows PowerShell addresses numerous customer requests based on their evaluation of Beta3 and RC1 including:

    ·         Direct ADSI support to allow IT Pros to more easily administer Active Directory
    ·         Improved support for Windows Management Instrumentation through ability to change WMI properties via methods
    ·         Additional logical operators (XOR and binary XOR) that make it easier to write sophisticated scripts
    ·         Improved help content and help functionality including new views that make it easier to find the right information.
    ·         Windows PowerShell 1.0 will release-to-web in Q4 CY06
    ·         Windows PowerShell will be leveraged by Microsoft Exchange Server 2007 and System Center Operations Manager 2007.

     

    To download, go here.

      Posted on: Wednesday, September 27, 2006 8:54:31 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Microsoft     September 27, 2006    

    Today, MS announced the first beta of the developer kit of the .net Micro Framework.

    Microsoft Corp. today released a beta developer kit for the Microsoft® .NET Micro Framework, a new development platform for use with devices that are typically constrained by cost, memory, processor and/or power consumption. Announced at the Embedded Systems Conference in Boston, the .NET Micro Framework broad beta extends the advantages of .NET and the Visual Studio® toolset into a class of the smallest of devices.

    “The .NET Micro Framework is a natural extension of Microsoft’s embedded offerings and provides a compelling, easy-to-use solution for developers,” said Colin Miller, director of the .NET Micro Framework at Microsoft. “We have utilized this platform with several projects at Microsoft and are excited to provide this kit to developers so they can use Microsoft tools to extend their skills to a set of smaller devices.”

    More can be found in the press release.

      Posted on: Wednesday, September 27, 2006 8:52:39 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | ASP.net | Programming | Programming tools | Visual Studio.net     September 27, 2006    

    Microsoft has released a new add-in tool to help Visual Basic developers preserve Visual Basic 6 applications and breathe .Net into them.  Microsoft released its Interop Forms Toolkit 1.0 as a free add-in that simplifies the process of displaying .Net WinForms in a VB6 application.

    The new toolkit not only helps to preserve VB6 applications, but also lets developers add functionality to them through additional .Net forms. For example, a developer could provide more dynamic content by adding a WinForm that accesses Web services or RSS feeds, Microsoft said.

    Moreover, instead of upgrading the entire code base, VB6 applications can be extended one form at a time, Microsoft said.

    "The goal is a phased upgrade, with production releases at the end of each iteration containing both Visual Basic 6 and Visual Basic .Net forms running in the same Visual Basic 6 process," according to a Microsoft Web page describing the new toolkit.

    More here.

      Posted on: Wednesday, September 27, 2006 8:50:22 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Vista | Visual Studio.net | WinFX | WPF | XAML     September 24, 2006    

    Another new release of the .net framework 3.0 has been released! This time, it's the September CTP.

    The Microsoft .NET Framework 3.0 (formerly known as WinFX), is the new managed code programming model for Windows. It combines the power of the .NET Framework 2.0 with new technologies for building applications that have visually compelling user experiences, seamless communication across technology boundaries, and the ability to support a wide range of business processes.
    These new technologies are Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation, and Windows CardSpace (formerly code named "Infocard"). Microsoft plans to ship .NET Framework 3.0 as part of the Windows Vista operating system. In addition, Microsoft is making these technologies available on Windows XP and Windows Server 2003.
    The following Community Technology Preview of .NET Framework 3.0 enables you to continue experimenting with early builds of these technologies, get acquainted with the development experience, and provide feedback to Microsoft. For more information on these technologies, click here.

    Installation
    To start the installation process, you will need to run the download file; this will initiate the installation of the .NET Framework 3.0 September CTP; If you have troubles with the download manager, you can download the entire package for x86 or for x64 which are both .EXE files.

     

    Enjoy!

      Posted on: Sunday, September 24, 2006 11:25:15 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | ASP.net | Atlas     September 20, 2006    

    A new update of the Atlas Control is released, with a few nice new controls. It can be downloaded here.

    Shawn Burke has some nice information on this latest build. More here. ScottGu also made a nice article here with very useful demo code.

      Posted on: Wednesday, September 20, 2006 9:38:11 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C#     September 20, 2006    

    I found a nice string manipulation library via www.ASP.net: you can access it here. Certainly a nice help if you have to work with strings a lot...

      Posted on: Wednesday, September 20, 2006 9:25:15 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Atlas | C# | Programming     September 11, 2006    

    After a naming game, Atlas finally got its final name!

    -Microsoft AJAX Library:  The client-side JavaScript library that works with any browser and also supports any server-side framework, not just ASP.NET.

    -ASP.NET 2.0 AJAX Extensions: The server-side functionality that seamlessly integrates with ASP.NET and uses the same programming model familiar to existing ASP.NET developers.

    Atlas will also ship in version 1.0 (final) before the end of the year!!!

    Scott Guthrie has an entire article devoted to the Atlas roadmap. You can read it here.

      Posted on: Monday, September 11, 2006 10:43:40 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | WPF     September 10, 2006    

    Just a cool link to a cool screencast: http://mattgriffith.net/PermaLink.aspx?guid=a1cb7215-2719-4c38-8ce3-ba7408aa69aa .

    In this short screencast I show how you can use IronPython and Snoop together to explore the Windows Presentation Foundation (WPF).

    IronPython is a wonderful dynamic language with full access to the .NET Framework. Snoop is a great WPF debugging tool. Together they can help you climb the steep WPF learning curve.

    A nice way to pass your lazy zundayzzz ;-)

    And if you're not satisfied with that, here's an interesting article on Settings in C#: http://msdn.microsoft.com/vcsharp/default.aspx?pull=/library/en-us/dnvs05/html/SettingsCS_RL.asp 

      Posted on: Sunday, September 10, 2006 11:58:32 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Visual Studio.net     September 10, 2006    

    For the first time, the Visual Studio SDK is available for online viewing, without having to register for the VSIP program.
    So, no excuses anymore for not developing your own plugins for Visual Studio ;-) .

    Here you can access the SDK.

      Posted on: Sunday, September 10, 2006 11:54:58 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Visual Studio.net     September 7, 2006    

    Today, I discovered a 'feature' of Visual Studio 2005.
    In VS 2003, I used the //TODO comment a lot, so that a list of all my ToDo items would show up in the Task List.

    Today, I was explaining to my collegue how to use this useful command... only to find out that it doesn't work in VS2005 anymore...

    This is what MSDN has to say about it:
    'Task List comments are not attached to the solution and project nodes displayed in Solution Explorer. For this reason, they do not appear when a solution is first opened. Rather, they are embedded within individual code files. Whenever a code file is opened for editing, any comments that begin with recognized tokens are displayed in the Task List. '

    So, you can only see them when the file is open... not project-wide anymore :(

    Anyone have another solution to this?

      Posted on: Thursday, September 07, 2006 9:57:16 AM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | C# | Microsoft | Programming | Microsoft | Vista | Windows | WinFX | WPF     September 6, 2006    

    Is today "Release Day" or something? So many new releases...

    Let's begin with IronPython, which reached status 1.0:

    IronPython 1.0 has been released to the .NET community and is available on CodePlex.  IronPython is an implementation of the Python dynamic programming language.  IronPython is built on top of the .NET Framework and is interoperable with other .NET languages.  Binaries, source code, and tutorials are available at CodePlex.

    Click here to download IronPython at CodePlex.

    Another release is Expression Web Beta 1:

    We are pleased to present the Beta 1 release of Expression Web (formerly Expression Web Designer).

    Expression Web is a professional design tool that helps you create and work with:

    • Standards-based Web sites
    • Sophisticated CSS-based layouts
    • Extensive CSS formatting and management
    • Rich data presentation
    • Powerful ASP.NET 2.0-based technology

    To download, go here.

    Still going strong ;-) Next is WCF, which reached RC1 also.

    The release candidate 1 for the .NET Framework 3.0 is now available!  You can download the components for the RC1 here:

    More info on RC1.


    The Interactive Designer got updated, and now the September CTP is available:
    Microsoft® Expression® Interactive Designer September 2006 Community Technology Preview (CTP) is a professional design tool used to create engaging, rich user interfaces for desktop and Web applications.

    To download, go
    here.

    To finish, this one isn't actually released as of yet, but it's an interesting project being researched at MS:

    Microsoft researchers are experimenting with an automatic code zapper for the company's Internet Explorer Web browser.

    Researchers at the Redmond, Wash., company have completed work on a prototype framework called BrowserShield that promises to allow IE to intercept and remove, on the fly, malicious code hidden on Web pages, instead showing users safe equivalents of those pages.

    The BrowserShield project—the brainchild of Helen Wang, a project leader in Microsoft Research's Systems & Networking Research Group, and an outgrowth of the company's Shield initiative to block network worms—could one day even become Microsoft's answer to zero-day browser exploits such as the WMF (Windows Metafile) attack that spread like wildfire in December 2005.
    More here.

    That's all folks ;-)

      Posted on: Wednesday, September 06, 2006 10:12:58 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | WinFX | WPF | XAML     September 6, 2006    

    My new bible has arrived :-)



    Appearantly, one of the first in Europe, since the release was scheduled for 13th September in the US.

    At first glace, it seems a very complete book, covering every aspect in WPF. I'll be posting a review later when I have read more in the book...

    From Amazon.com:
    In this book, Windows programming legend Charles Petzold covers in parallel the two interfaces that make up the Windows Presentation Foundation (WPF). From the outset, the reader can shift focus seamlessly between Extensible Application Markup Language (XAML) and C# to see them as flip sides of the same processes. Beginning in the first chapter, Petzold presents the general syntax of the XAML and corresponding programming code with numerous illuminating examples on how the two correspond and interrelate. The book builds on this base, providing the classic Petzold Windows user interface (UI) treatment, to show Windows developers how to create next-generation interfaces for their applications.

      Posted on: Wednesday, September 06, 2006 9:59:07 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Microsoft | Software | Windows     September 6, 2006    

    CA's eTrust software wrongly identified Windows' in-built security as malware, and a fix has been made available.

    Some Windows 2003 users have been experiencing problems with the operating system recently after antivirus software from CA wrongly detected part of the operating system as malware.

    At the heart of the problem is part of Windows' in-built security, a file called Lsass.exe. This was wrongly detected as a virus by CA's eTrust software and was deleted, causing some servers to crash and fail to reboot.

    More here.

      Posted on: Wednesday, September 06, 2006 5:48:51 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Microsoft | Programming | Software | Microsoft | Visual Studio.net     August 31, 2006    
    MS released XNA Game Studio Express (Beta), the first beta for this tool that can help every individual to become a game programmer.

    From the site:
    XNA Game Studio Express enables individuals and small teams to more easily create video games using new, optimized cross-platform gaming libraries for Windows and Xbox 360. This beta release targets the development of games for Windows. The final version of XNA Game Studio Express will be available this holiday season and will enable development of games which target Windows and upon purchase of a XNA Creators Club subscription, the Xbox 360 as well.

    While we’re very proud of this Beta milestone, it does not represent all of the great features we are enabling in XNA Game Studio Express which will be available in final release form by this holiday. Some of the key feature areas that were not able to make it into this beta include:
    - The XNA Framework Content Pipeline feature is not present in this release of XNA Game Studio Express (Beta). It will be made available in a future beta release of XNA Game Studio Express
    - Support for retail Xbox 360 game development. This feature will be made available upon final release of XNA Game Studio Express later this holiday
    - Additional starter kits and tutorials will be made available upon final release of XNA Game Studio Express

    It's a free download of 91MB. You can find it here
      Posted on: Thursday, August 31, 2006 5:11:34 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Programming | WPF     August 31, 2006    



    My article on WPF reflections can also be read on CodeProject. Since it was put there, it received almost 2000 reads and a rating of 4 out of 5!

    Putting nice articles on CodeProject enhances your visibility, so if you're a blogger and write technical articles, it's a nice place to put them!

    Here is the link :-)

      Posted on: Thursday, August 31, 2006 8:28:45 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Microsoft | Programming     August 20, 2006    

    Just came across a post that marks the completion of the book: Windows Developer Power Tools: Turbocharge Windows Development with More.


    From Amazon:
    There is a wealth of open and free software available today for Windows developers who want to extend the development environment, reduce development effort and increase productivity. Windows Developer Power Tools is an encyclopedic guide to more than 100 free and open source tools available to programmers who build applications for Windows desktops and servers, including web applications and services. With its unique task-oriented organization, this book will help you find the tools you need to solve common (and uncommon) problems. Each tool in the book includes a capsule summary -- a mini user's guide -- to help readers get up to speed quickly. Also, plenty of links point you to additional detail online if you wish to delve more deeply into features and functionality. This one-stop resource covers a wide range of open source and freeware tools to help you answer questions around planning, developing, testing, and rolling out great software.

    Here you can find the list of tools described in the book.

    This seems like a book well worth buying if you're a Windows developer like me. Publish date is November 1st in the US, so expect it here about 2 weeks later!

      Posted on: Sunday, August 20, 2006 9:41:36 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming | WinFX | WPF | XAML     August 18, 2006    

    In this tutorial, I'm going to explain several 2D effects that can be performed on images, using only XAML code. By the end of this tutorial, you'll know:

    • how to create image refections
    • how to skew images
    • how to drop shadows

    So let's get to it!

    Create an empty WinFX application. We'll use the Window1.xaml.
    Make the background of the image somewhat darker, so we can better see the effects we'll create further on. For this, simply use the Window.Background property. Also, set the Height to 600 and Width to 800.

    <Window x:Class="Reflection.Window1"
       xmlns="
    http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       Title="Reflection" Height="600" Width="800" 
       Background="#CCCCCC"
    >


    Add the image to your project
    Select an image to include in your project. I'll do this tutorial with the image included in my project, but you can of course use any image you want. The image has to be included in your project. Once included, go to the properties window, and with the image selected in the solution explorer, set the "Build Action" to "Content" and "Copy to output directory" to "Copy always". This ensures that the image will be available when running the project.

    Let's XAML
    Finally, we're ready to do some XAML'ing (don't know if that is already a word, but I vote it should become one though!).
    Since we will not be needing any advanced layout of the window, we'll use a simple StackPanel. By default, a stackpanel places all content it receives in 1 invisible vertical column. That's enough for this sample.

    So, delete the <Grid> and </Grid> and replace them with <StackPanel> and </StackPanel>.

    For the image effects, we'll need ... an image. Add an simple image element to begin with. Also, give it a name, we'll be needing this name later on. Use the following code:

    <Image Source="image.jpg" Width="200" Height="300" x:Name="myImage"></Image>

    We'll now start adding the reflection effect. For reflections, the VisualBrush is very handy.
    What is the VisualBrush? It's a brush, like DrawingBrush, but it can paint with the contents of any other visual element that derives from Visual. Since Visual is the base class of all UI elements in WPF, you can paint with almost any markup in a VisualBrush.
    Before we can reflect our image, we must add an element in which we can make the reflection appear. You can do this with a Rectangle, a Border...
    For now, I'll use the Border. Add the Border element to the same StackPanel where you put the image. Since it's a StackPanel, the border is put below the Image (you can visualize this by setting the Background to some color).

    <Border Width="210" Height="300"></Border>

    Now, we'll use the recently introduced VisualBrush to fill the background of the Border with the contents of the image (this is why we needed to name the image!).
    Add a VisualBrush to the Border like so:

    <Border.Background>
       <VisualBrush Visual="{Binding ElementName=myImage}">
       </VisualBrush>
    </Border.Background>


    You should now see something like this:

    Of course, for a reflection, we need a mirror effect. This can be achieved by adding a ScaleTransform on the VisualBrush. By providing a value of -1, the image will be flipped around the Y-axis.

    <VisualBrush.Transform>
       <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="200" CenterY="150"></ScaleTransform>
    </VisualBrush.Transform>

    Now, to complete the reflection-part of this tutorial, we'll add an OpacityMask to the Border. With this in place, we can make the reflected image fade out into the backgroud, creating a nice effect.

    <Border.OpacityMask>
       <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
          <GradientStop Offset="0" Color="Black"></GradientStop>
          <GradientStop Offset="0.6" Color="Transparent"></GradientStop>
       </LinearGradientBrush>
    </Border.OpacityMask>

    This again uses a LinearGradientBrush, with the color being Transparant from 0.6 on. This means that at 60% of the reflected image, nothing can be seen anymore.

    We'll also add a border around the original image in this code. Add the following code around your image element:

    <Border BorderBrush="White" BorderThickness="5" HorizontalAlignment="Center" VerticalAlignment="Center">
    ...
    </Border>

    Your code should now look like the following:

    <StackPanel>
       <Border BorderBrush="White" BorderThickness="5" HorizontalAlignment="Center" VerticalAlignment="Center">
          <Image Source="image.jpg" Width="200" Height="300" Stretch="Fill" x:Name="myImage"></Image>
       </Border>
       <Border Width="210" Height="300">
          <Border.Background>
             <VisualBrush Visual="{Binding ElementName=myImage}">
                <VisualBrush.Transform>
                   <ScaleTransform ScaleX="1" ScaleY="-1" CenterX="200" CenterY="150"></ScaleTransform>
                </VisualBrush.Transform>
             </VisualBrush>
          </Border.Background>
          <Border.OpacityMask>
             <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                <GradientStop Offset="0" Color="Black"></GradientStop>
                <GradientStop Offset="0.6" Color="Transparent"></GradientStop>
             </LinearGradientBrush>
          </Border.OpacityMask>
       </Border>
    </StackPanel>

    And the result should resemble this:



    Skew and Shadows
    In the latest part of this tutorial, I'm going to add a shadow to the original image, and skew both the images, to create a 3D effect.
    First, the shadow. Shadows are created using a BitmapEffect. A bitmap effect takes visual content as input and produces a new surface by applying one or more image filters, such as a blur or a drop shadow. Currently, there are, among other, the DropShadowEffect, the BlurBitmapEffect and the EmbossBitmapEffect. More might be added later. We'll focus on the DropShadowEffect for now. Information on the other effects can be found in the Windows SDK.

    Add the following code to the Border where the original images resides:

    <Border.BitmapEffect>
       <BitmapEffectGroup>
          <DropShadowBitmapEffect Color="Black" Direction="20" ShadowDepth="25" Softness="1" 
             Opacity="0.5"/>
       </BitmapEffectGroup>
    </Border.BitmapEffect>

    This adds the dropshadow to the white border containing the image. These properties are self-explaining, so I'm not going any deeper into this.

    Now, to finish, we have to skew both the image and the reflection to create the effect of depth. For this, we'll again use a transformation, this time a RenderTransform. The Angle-properties provided indicate the angle for the rotation.
    The following code has to be added to the original image.

    <Border.RenderTransform>
       <SkewTransform CenterX="0" CenterY="0" AngleX="0" AngleY="10" />
    </Border.RenderTransform>

    The reflection needs a re-centering, so we provide a value for the CenterX and CenterY properties.

    The result you get should like the following:



    I hope this WPF example can help you in creating great layouts with this fantastic new language!

    The complete solution can be downloaded below.

    ImageEffects.zip (120.66 KB)

    Note that you need Visual Studio 2005/Visual C# Express with .net 3.0 installed. This code is tested with the June CTP.

     

      Posted on: Friday, August 18, 2006 11:15:10 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming | Visual Studio.net | WinFX | WPF | XAML     August 18, 2006    

    I'm through with learning WPF (Windows Presentation Foundation), so now I'll have more time to write some samples for my blog, so everybode can start learning a little on WPF (that double-U-P-F ;-) ).

    Today, I'm going to show you a small sample, in which I use a gradient and a storyboard to create a sort of a flashing circle. This could be used to draw the user's attention to something in the UI.

    Here is the sample code:

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    WindowTitle="www.snowball.be - WPF Examples" Background="White">
    <DockPanel>
       <Ellipse Width="200" Height="200" Name="MyEllipse">
          <Ellipse.Fill>
             <RadialGradientBrush >
                <GradientStop Offset="0" Color="#CCCCCCCC" />
                <GradientStop Offset="0.5" Color="white" />
                <GradientStop Offset="1" Color="black"/>
             </RadialGradientBrush >
          </Ellipse.Fill>
       </Ellipse>
    <DockPanel.Triggers>
       <EventTrigger RoutedEvent="Page.Loaded">
          <BeginStoryboard Name="MyBeginStoryBoard">
             <Storyboard Name="MyStoryBoard">
                <DoubleAnimation Storyboard.TargetName="MyEllipse" Storyboard.TargetProperty="(Ellipse.Height)" 
                   From="0" To="200" AutoReverse="true"
                   RepeatBehavior="0:0:10" BeginTime="0:0:0" />
                <DoubleAnimation Storyboard.TargetName="MyEllipse" Storyboard.TargetProperty="(Ellipse.Width)" 
                   From="0" To="200" AutoReverse="true"
                   RepeatBehavior="0:0:10" BeginTime="0:0:0" />
             </Storyboard>
          </BeginStoryboard>
       </EventTrigger>
    </DockPanel.Triggers>
    </DockPanel>
    </Page>

    First, I create an circle, which is actually an ellipse with identical width and height (one could also use the RadiusX and RadiusY properties, the result would be the same).

    <Ellipse Width="200" Height="200" Name="MyEllipse">

    Then, we use a Brush, in this case, the RadialGradientBrush, to create a gradient fill in the ellipse. No longer are the "GradientStops" or the "GradientStopsCollection" tags neccessary (they were in previous CTP's, but now they can be omitted).
    To specify the colors, we use several GradientStop elements. The offset specifies where the color should "start". This is a relative value, and thus can't be more than 1. In this case, I specify 3 colors.

    <GradientStop Offset="0" Color="#CCCCCCCC" />
    <GradientStop Offset="0.5" Color="white" />
    <GradientStop Offset="1" Color="black"/>

    Now, to create the flashing effect, we have to use an animation. To start the animation, we use a trigger, in this case, an event trigger, which is routed to the Loaded event. This results in the trigger firing when the page loads.

    <EventTrigger RoutedEvent="Page.Loaded">

    For the animation itself, we use the storyboard. In this storyboard, which is like the name says, a series of steps that will be executed. You can compare it to a band of drawings that form a comic.
    The storyboard thus consists of several animations. In this case, I use a DoubleAnimation, because the property I'm going to change, is of value Double: I'm going to alter the Height and Width property of the Ellipse. These are indeed Double values.

    In the first animation, I specify that I want to animate the ellipse I created earlier, by setting the TargetName, and the property I want to change is the Height. In the From and the To properties, I specify what the values for the Height should be. In this case, I want the ellipse to pop up out of nothing, so I set the From to 0 and the To to 200.

    The RepeatBehavior property specifies how long this animation should repeat, in this case, I set it to 10 seconds. Note that several animations can have different RepeatBehaviors: one can go one longer than the other. The BeginTime simply specifies when the animation should start: you can build in a delay.
    Finally, the AutoReverse property indicates that WPF should reverse the animation after completed.

    The second animation does essentially the same, but for the width.
    Both these animations can't be grouped into one, which is a pity.

    The result looks like this:



    kick it on DotNetKicks.com
      Posted on: Friday, August 18, 2006 6:37:02 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming | Software | Visual Studio.net     August 17, 2006    

    Already added 2 posts about new stuff today, so I'm going to bundle these last 2 for today...

    Yesterday, while I was at Disneyland (you can see my pics on my Flickr account...), MS released SP1 for Visual Studio 2003. It's a 160MB download, and once installed, you can't return without uninstalling, so install with care!

    Go here for the download.

    Something I came across are Nuggets. In Disneyland, you might ask? Yes, there were Chicken Nuggets, but since this a technical blog, I'm not going to bother you with what I ate... I'm talking about MSDN nuggets, hosted by Microsoft UK.

    Don't have the time to read a 10-page how-to article or watch a full length webcast? Try an MSDN Nugget, a webcast that takes you step-by-step to discovering new functionality or exploring a hot developer topic, all in 10-15 minutes. View them online now or download for later reference.

    Head over here for a lot of good content!

      Posted on: Thursday, August 17, 2006 3:44:17 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | WinFX     August 17, 2006    

    Last week, a collegue of mine told me about a video on the ADO.net entity framework over at Channel9. I watched it, and was very impressed.

    Today, MS released the first CTP for this framework that is to be included later on in the .net framework. 

    From the release notes:

    This package is the first Community Technology Preview (CTP) of ADO.NET vNext and includes the preview build of the ADO.NET Entity Framework along with samples and whitepapers. The ADO.NET Entity Framework supports Object Relational Mapping scenarios using ADO.NET Entities, in this build you can:
    - Query of persistent Entities using LINQ to Entities or Entity SQL
    - Save new and dirtied entity instances through the object abstractions which also handle
    o State management
    o Identity resolution
    o Change tracking
    - Work with persistent object graphs and leverage a programming and query model where relationships are a first class concept
    - Use optimistic concurrency and server generated values with persistent entities
    - Program against persistent entities as values using the new Map Provider
    - Get first hand experience with Entities and the Entity Data Model
    - Work with mappings based on view maintenance concepts to support
    o Entity Splitting (entities split across multiple tables)
    o Table Per Hierarchy, Table Per Class and Table Per Type mappings
    o Property renaming
    o Conditional mappings

    It's a small download, if you want to give it a try, head over to Microsoft downloads.

      Posted on: Thursday, August 17, 2006 3:31:15 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Atlas     August 17, 2006    

    It is confirmed that the Atlas framework will not be named Atlas when it is released in a few (6?) months...

    So, Steven Smith has organised a small game: Name that Microsoft product. In this game, he is in search of the name Microsoft should give its new framework.

    He already has some good (and some less good) proposals:

    • Rich Web Programming Foundation - RWPF
    • Web Technology Framework - WTF (!)
    • AJAXX (aka let's just add an 'X' to the existing name to make it sound cooler)
    • Rich Language ASP Framework
    • Big ASP Rich Foundation - BARF
    • Active Client Pages - ACP

    So head over to his blog and post your suggestions! Who knows, you might be the inspiration MS needs!

      Posted on: Thursday, August 17, 2006 3:24:24 PM (Romance Daylight Time, UTC+02:00)   |   Comments [10]
             
    Gill Cleeren     .net | C# | Programming | Visual Studio.net     August 14, 2006    

    More and more languages seem to be getting "the .net treatment". Next on the list is PHP.
    Microsoft is hosting a project on its CodePlex site to deliver a PHP language compiler for the .Net Framework.

    The project's name is as Phalanger, the project reached Version 2.0 Beta 2 on July 30.

    The primary goal of the project, released under Microsoft Shared Source Permissive License, is to enable full functionality of existing PHP scripts on .Net without any modification, Microsoft said.

    Unlike the original PHP interpreter, Phalanger compiles scripts into MSIL (Microsoft Intermediate Language).

    The object model in Phalanger is compatible with PHP 5.0, and it lets developers combine PHP objects with .Net ones.

    In fact, developers can use a class written in PHP from a .Net application or to import a .Net class—that might be written in C# or Visual Basic—into PHP scripts.

    Currently, one of the major features is to incorporate Phalanger in Visual Studio.net.

    More on this can be found at CodePlex.com!

      Posted on: Monday, August 14, 2006 2:56:14 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming tools | Microsoft | Visual Studio.net     August 14, 2006    

    Yesterday, Microsoft announced during the Gamefest 2006-event in Seattle, the XNA Game Studio Express. Like the name says, it is a development tool to allow developers, hobbyists and students to write games for the PC and XBox360.

    Like the other express editions, it will be available for free, at least if you want to develop for the PC. If however you want to develop for the 360, a fee of 99 dollar is to be payed. This way, developers get access to the "Creators Club". Members of this club can build and test their games on the 360 platform. The distribution of these home-brewn games is probably to be done via the Xbox Live Arcade.

    The mayor reason Microsoft wants to attract more people to developing games, is the current cost involved these days to develop a full-blown game. "Big" games cost big money and take up to 3 years to develop. Companies like EA, MS... don't dare to take risks to develop anything new, so the creativity is limited. Developers can't really try out new concepts. With these tools, more people are able to make their ideas into reality, perhaps opening up a whole new world for the game-industry.
    Over time, MS hopes to have an entire community where people can distribute their games, and can express their opinion on other games, seperating the hits from the flops.

    Now, about the launch date... Microsoft is expecting to launch the first CTP by the end of August. The final version will be released be released in November or perhaps December of this year!
    The programming language used will be C#.

    Microsoft is said to be doing this to keep get more people on the 360 platform, and keep them away from the PS3, which is due somewhere later this year.

      Posted on: Monday, August 14, 2006 12:25:31 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | WinFX | WPF     August 12, 2006    

    Just like me, my collegue Gabriel dislikes the renaming of WinFX to .net 3.0. On his blog, he points to an online petition to convince Microsoft to go back to WinFX, instead of .net 3.0.

    So, if you share the same opinion, don't hesitate to sign the petition too!

      Posted on: Saturday, August 12, 2006 5:12:16 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Microsoft | Programming | WinFX | WPF | XAML     August 10, 2006    

    As previously announced here, on September 25th, Microsoft is organizing an event on .net 3.0 in Kinepolis Brussels. David Boschmans announced the complete agenda on his site today.
    Today, the line-up and sessions are announced. A new item is that we, the visitors, can now vote which sessions we want to see.

    So, everybody, go vote AND PLEASE don't vote for the introductions!!

    Vote here.
    General information on the event can be found here.

      Posted on: Thursday, August 10, 2006 9:38:54 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Microsoft | Visual Studio.net | Programming tools     August 9, 2006    

    My favorite documentation tool in Visual Studio 2005 is updated to a new version, namely 1.9.5.

    Don't know GhostDoc? Here's some info:
    GhostDoc is a free add-in for Visual Studio that automatically generates XML documentation comments. Either by using existing documentation inherited from base classes or implemented interfaces, or by deducing comments from name and type of e.g. methods, properties or parameters.


    Go here to download the tool.

      Posted on: Wednesday, August 09, 2006 11:07:15 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Microsoft | Microsoft     August 9, 2006    

    OK, all you Visual Studio 2005 gurus out there!
    I was just creating a new class in VS 2005, while calling to my girlfriend over the phone...
    My screen looked like this:



    Because I was on the phone, I was staring a little at the screen... a bit amazed by the number of items that are available in this version.
    Suddenly, my eye fell on something... Look at this screen...



    See something "special"? No?

    Maybe this will help...



    "An empty class definiton"... not a definition, but a definiton.

    Nothing worldshocking, but funny anyway... considering that millions of people see this window every day, and it actually got through beta-testing. Nobody's perfect :-)
      Posted on: Wednesday, August 09, 2006 10:49:44 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | ASP.net     August 9, 2006    

    Today, I was trying to get build a C# custom module for a DNN (DotNetNuke) portal. DNN is completely wirtten in VB.net, but since Visual Studio 2005 came along, it is possible to build modules in C# too.

    When using the module template from the site, it creates a subdirectory under the App_code directory. Now, since DNN is written in VB.net, some files like Global.asax.vb are already there. So, we are actually mixing C# and VB.net files under the app_code directory, which is not possible, since these are to be compiled into 1 dll.

    The error I got was: The files '/MySite/App_Code/MyGuestbook/DataProvider.cs' and '/MySite/App_Code/AssemblyInfo.vb' use a different language, which is not allowed since they need to be compiled together.

    After some searching, I found out that using the <codeSubDirectories> tag in the web.config would bring me the solution.

    How to do it? Add the following (if not already there) to your web.config.
    <codeSubDirectories>
       <
    add directoryName="MyModule"/>
    </codeSubDirectories>

    This results in the subdirectory of the app_code directory being compiled into a seperate assembly, thus seperating the C# from the VB.net code.

      Posted on: Wednesday, August 09, 2006 10:09:00 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C#     August 8, 2006    

    Some links for my students in summerschool in .net:

    -Reflector: tool to disassemble compiled .net code (dll)
    -Resharper: plug-in for Visual Studio
    -MSDN event in Kinepolis!!
    -Express editions of Visual Studio and SQL Server
    -Third party controls: Infragistics
    -Consolas font

    If I forgot any, please make a comment and I'll add it.

      Posted on: Tuesday, August 08, 2006 1:14:23 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C#     August 4, 2006    

    August has only just begun, but the September issue of the Visual Studio magazine is already here (not that we're complaining!!).



    I haven't had the time to read anything, but this month, there are a lot of interesting articles IMO.
    The one on Virtual Earth seems very interesting. In this article, the Virtual Earth API's and the Virtual Earth map control, a JavaScript component that provides all the functionality you need to draw maps, search for locations, and get driving directions, are explained.

    The article on downloading files are needs reading! Here the author explains how you can force the browser to start a download window for some file-types, which would generally be opened in the browser, like for example, a JPEG.

      Posted on: Friday, August 04, 2006 8:37:42 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming     August 4, 2006    

    Resharper... almost every .net developer respecting himself (or herself for that matter!) , has it installed on the development machine.

    I had build #249 of Resharper 2.0 for Visual Studio 2005 installed. Problem was, since the installation, my Visual Studio opened very slow. Once it was up and running, I didn't notice any slowdown anymore.

    Yesterday, Gabriel pointed my to build #256. I installed it (it took quite some time uninstalling and then reintegrating with Visual Studio 2005), and then my IDE opened much faster!

    So, if you are having the same problems, update to the new build.

    Now that we are at it, I found a very interesting article on Resharper.

      Posted on: Friday, August 04, 2006 8:23:00 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | C#     August 3, 2006    

    After a short period, Paint.net, one of the largest open-source .net projects out there, is once again updated, now up to version 2.70.

    Some new stuff included in this version:

    * New effect: Glow
    * New effect: Bulge
    * New effect: Polar Inversion
    * New effect: Tile Reflection
    * New effect: Twist

    You can download this free imaging tool here.

      Posted on: Friday, August 04, 2006 12:15:44 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | Atlas     August 3, 2006    

    A new version of the Atlas Control Toolkit has been released.

    For the first time, there are some components that are not developed by Microsoft themselves included in the release: PasswordStrengthExtender by Paul Glavich, and the FilteredTextBox by Christian Wenz.

    Apart from some bugs being resolved, some new controls are introduced too: RatingControl, NumericUpDown, and PagingBulletedList.

    You can download this new version from Codeplex. Have fun Atlas'in ;-)

      Posted on: Friday, August 04, 2006 12:11:36 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming | Vista | WinFX | WPF | XAML     August 2, 2006    

    People have been asking me questions about WPF, mostly how to get started.
    Since WPF is still somewhat obscure, in this article I’m going to try to make things a little more clear to get you on your way using WPF.

    As you might or might not know, WPF is part of .net 3.0, formerly known as WinFX. Other components included in .net 3.0 are WCF (Windows Communication Foundation), WF (Windows Workflow Foundation) and CardSpace (formerly InfoCard).

    For starters, you need an operating system supporting WPF. This can be:
    -Windows XP SP2
    -Windows 2003
    -Windows Vista

    I do recommend running .net 3.0 in a virtual pc environment! Since a lot of CTP’s, beta’s and RC’s are coming our way, it’s easier to just create a VPC with Windows XP or 2003 , and install .net 3.0! Since Virtual PC is free anyhow, I don’t see a reason why not doing it this way!
    Uninstalling beta software can be a real pain, so why compromise your precious production environment!?
    (For Virtual PC go here)

    On both XP and 2003, you need to install the runtime, to be able to run WPF applications. This can be a web-install (of around 2.5 MB, and then the rest is downloaded) or you might as well download the whole package.

    Now, there are some issues with the latest CTP of July… This latest release does not come with the Visual Studio 2005 extensions, required to build your WPF applications in VS.
    Therefore, if you want to start developing (or better, start playing around…), I suggest you stick to the June CTP, which has full support for all the tools.

    So, if you want to develop within Visual Studio, follow the next steps. If not, skip this section.
    The June CTP runtime can be downloaded here.

    To start developing, you might want to install the SDK. It’s a big download of around 1.1GB. It comes with lots of samples and tools, like XAMLPad. The SDK can be downloaded here.

    The SDK is however not required when you intend to develop in Visual Studio! For VS, Microsoft has released some extensions and templates, which will make your WPF-life a lot easier! If you don’t have Visual Studio, you can use one of the free Express editions.
    For the download, go here.

    We’re almost done!
    Microsoft is also preparing a set of designer tools for WPF, the Expression suite.
    The Interactive Designer outputs XAML code, which can be used to enhance the layout of your applications, without even knowing XAML!
    For the Interactive Designer, go here.
    The Graphic Designer allows you to create images and export these as XAML code to be included in your WPF projects.
    This can be downloaded here.

    That’s it! Now, you are ready to start!

    If you want the latest release, and don’t care for the Visual Studio Extensions, go for the July CTP, which was released July 18th.

    The runtime can be downloaded here.
    And the SDK is found right here.

    I did find some work around to get this latest CTP working with Orcas, but since I didn’t try it myself, I cannot guarantee that it will work.
    The “fix” goes as follows:

    Instal Orcas in VS using the misexec override: msiexec /i vsextwfx.msi WRC_INSTALLED_OVERRIDE=1

    The override bypasses the installation version checking so you can install the extensions.

    After this you have July CTP installed and Orcas from the previous version. This works just fine.

    To solve your problem with the Orcas designer trying to open:

    Right click on a .xaml file in your solution and choose "open with...". Choose "xml Editor" and click on "Set as default". Now all .xaml files will open with the xml editor instead of trying to open the unfinished Orcas designer.

    In a next article, I’ll post some interesting resources to get you building WPF applications in no time!

    kick it on DotNetKicks.com
      Posted on: Wednesday, August 02, 2006 12:06:10 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Programming     July 30, 2006    

    Sandcastle is NDoc. No, not really, but it is very much alike.

    Like NDoc, it is a documentation compiler for .net. It's a plugin for Visual Studio 2005, and the first CTP can be downloaded as of today.

    Some information from the blog:
    Mission Statement:

    Enable managed class library developers throughout the world to easily create accurate, informative documentation with a common look and feel

     

    Sandcastle Overview:

    • Produces quality, comprehensive, familiar MSDN-like documentation.
    • Works with or without authored comments.
    • Supports Generics and .NET Framework 2.0
    • Sandcastle has 2 main components (MrefBuilder and Build Assembler)
    • MrefBuilder generates reflection xml file for Build Assembler
    • Build Assembler includes syntax generation, transformation..etc
    • Sandcastle is used internally to build .Net Framework documentation
      Posted on: Sunday, July 30, 2006 12:24:13 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Microsoft     July 30, 2006    

    Since I work in a consultancy firm, I see what's going on in the industry. More and more .net projects keep coming in, in favor of Java applications. Over time, a lot of Java programmers have been introduced to the world of .net.

    It's easy to see this, but when talking to non-Microsoft people, it's quite hard to convince them to face reality.

    Yesterday, Bob Muglia, Microsoft's senior vice president of Server and Tools business, said Microsoft's .Net platform has outpaced Java, particularly the Java Enterprise Edition, over the past five years to become the development platform of choice for enterprise development.

    "Five years ago we had problems with J2EE [Java 2 Platform, Enterprise Edition]," Muglia said. However, "We've grown from having a quarter of the market to, now, 60 percent," he said. Microsoft displayed the FAM presentations via Webcast.

    "J2EE has run its course," Muglia said.

    Yet, he also said that although Microsoft is strong in the database and developer tools spaces, the company sees that in both areas, "we are mature and we have high usage, but our revenue numbers are lower than our usage numbers… As we focus on the enterprise segment, we have the ability to drive up our revenue share."

    I don't see an immediate threat in the future, with upcoming technologies as .net 3.0 (WPF and WCF), Atlas... Way to go .net!

      Posted on: Sunday, July 30, 2006 12:12:01 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming | Software | Microsoft     July 26, 2006    

    Is it me, or is it like every day I have been announcing that Microsoft is giving yet some other software away for free?

    Maybe it's the heat that's getting to them?

    Anyway, a big thank you for all you not-MSDN subscribers to the big M, since they are giving away the complete MSDN library for free. You can download the May 2006 edition.

    Prepare your computer however, since the download is quite large, up to 1.7 GB!

    Go here for the download!

    Thank you Microsoft... What?? Again no thank you... Tssss.... ;-)

      Posted on: Wednesday, July 26, 2006 11:31:54 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | C# | Microsoft | Programming | Vista | WinFX | WPF | XAML     July 11, 2006    

    WPF not only stands for new fantastic tools for layout. There are also some very interesting new ways to implement databinding in your applications.
    In this article, I’m going to show how you can easily build an RSS reader using the new databinding features in WPF.

    How databinding works in WPF
    In order not to go too fast, first, let me explain some basic concepts of databinding in WPF.

    To keep data used in UI in sync with data in the datasource (for example a database), we can of course use properties. There is nothing wrong if you keep doing this under WPF.
    However, WPF provides very handy binding features, that will make your life a lot easier!

    We could bind the value of a textbox with the following code:
    <TextBox Text="{Binding Path=Age}">
    </TextBox>

    Databinding under WPF uses a Binding object. The above code declares a textbox in XAML, and assigns the text-property the value of a property named Age of an object that it is bound to. This is done using the Path property. The Path property refers to the property of the object we are binding too.

    To know to which object we are binding, we have the DataContext property. In WPF, every FrameworkElement and also every FrameworkContentElement has a DataContext property. It is of type object, so we can bind to whatever we like.
    The binding does however have some interesting behaviour: if no DataContext is specified on the object itself (like with our textbox), it goes up the tree in which the controls are nested. So if we add our textbox in a Grid, it will look if this Grid has a DataContext. If not, it goes up higher…
    This is of course very useful if we have more than one object (say 5 textboxes) binding to the same object.

    Let me show you how to declare an object to which we’ll bind in XAML code (this uses the new syntax, so to run this, you have to upgrade to beta 2 or higher!)

    <Window x:Class="Snowball.Window2"
        xmlns="
    http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="
    http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Snowball"
        Title="Snowball" Height="300" Width="300"
        >
      <Window.Resources>
        <local:Person x:Key="Gill" Name="Gill Cleeren" Age="27"/>
      </Window.Resources>
        <Grid DataContext="{StaticResource Gill}">
          
          <TextBox Text="{Binding Path=Name}">
          </TextBox>
        </Grid>
    </Window>

    And in the code-behind:
    namespace Snowball
    {
        public class Person
        {
            private string name;

            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            private string age;

            public string Age
            {
                get { return age; }
                set { age = value; }
            }

            public Person()
            { }
        }
    }

    What I have done here, is creating a Person object in XAML. For this to work, you have to provide a default constructor.
    First, we have to wire the CLR namespace to be known in XAML: xmlns:local="clr-namespace:Snowball".
    Now, we can use the tag “local” to refer to the namespace in which the Person class resides.
    Using the following line, we instantiate a Person using XAML:
    <local:Person x:Key="Gill" Name="Gill Cleeren" Age="27"/>

    The result is a textbox showing my name:

    Note that if you try this in Visual Studio at the time of writing, you get an error viewing the design view. Don’t worry, when running, it all works fine.

    Binding XML data to a list
    Most of the time, we bind data to a list: a dropdown, a grid… In this part, I’m going to bind an RSS feed from my website www.snowball.be to a list.
    To do this, we’ll need an XmlDataProvider.

    Data can be accessed by using a Provider. Currently, 2 providers exist: the XmlDataProvider and the ObjectDataProvider.
    An XmlDataProvider object must be declared within the resources, for example the resources of the grid:

    <Grid.Resources>
            <XmlDataProvider x:Key="SnowballRSS" Source="
    http://www.snowball.be/SyndicationService.asmx/GetRss" />
    </Grid.Resources>


    The x:Key assigns a name, which we can use in our code-behind.

    We can now use this object as a datasource for a listbox, like this:

    <ListBox ItemsSource="{Binding Source={StaticResource SnowballRSS}, XPath=//rss//channel//item }">
    </ListBox.ItemTemplate>

    We provide a value for the ItemSource, being an instance of Binding. For this Binding instance, we provide the Source property. Since we’re dealing with a resource that is defined in the XAML itself, we again use StaticResource and as value, the name of the dataprovider. A second attribute is the XPath expression, to locate the value we want to show in the listbox.

    This is the result:



    What happens, is that the entire XML tag is being read into a listitem. This is not desired, so we have to provide some kind of formatting, to tell WPF exactly what we want to show in the items.
    This can be accomplished using a datatemplate.

    We provide an instance of DataTemplate to be used as value for the ItemTemplate property of the listbox. In this datatemplate, we can specify what to show as listitem.
    In the following code, I’m telling to make each listitem consist of a TextBlock. The text to be shown is taken from the surrounding Listbox (remember searching for the data up in the controltree?). In the data it finds, which is an XML tag with subnodes, we can to take the title as the value for the item.

    <ListBox.ItemTemplate>
       <DataTemplate>
          <TextBlock Text="{Binding XPath=title}"></TextBlock>
       </DataTemplate>
    </ListBox.ItemTemplate>

    When we now run this, we get the following:



    Much better, isn’t it?!

    In the next part, we’re going to make the application a little bit more complete, providing a click event for the listbox, and making sure that some fields are filled in, again using databinding.

    Adding the detailsform
    We’ll now change the program somewhat to make it display the details of the item selected in the listbox.

    We’ll add a Grid to make it easy to display 3 rows and 2 columns with textblocks, labels and textboxes.
    This can be done with the following code:

    <Grid>
       <Grid.RowDefinitions>
          <RowDefinition Height="30"></RowDefinition>
          <RowDefinition Height="30"></RowDefinition>
          <RowDefinition Height="*"></RowDefinition>
       </Grid.RowDefinitions>
       <Grid.ColumnDefinitions>
          <ColumnDefinition Width="0.2*"></ColumnDefinition>
          <ColumnDefinition Width="0.8*"></ColumnDefinition>
       </Grid.ColumnDefinitions>
       <TextBlock Grid.Row="0" Grid.Column="0">Title</TextBlock>
       <Label Grid.Row="0" Grid.Column="1"></Label>
       <TextBlock Grid.Row="1" Grid.Column="0">Link:</TextBlock>
       <Label Grid.Row="1" Grid.Column="1" ></Label>
       <TextBlock Grid.Row="2" Grid.Column="0">Article</TextBlock>
       <TextBox Grid.Row="2" Grid.Column="1"></TextBox>
    </Grid>

    After adding the Grid, we’ll also have to change the rest of the markup a little. Take a look at the sample code provided with this article to see the rest of the layout.

    We now want the detail-fields display more info on the selected item in the Listbox.  Therefore, the Grid containing these fields should have its DataContext set to the item selected in the list. We do this with the following code:

    <Grid DataContext="{Binding ElementName=RSSList, Path=SelectedItem}" >

    The element is the name of the listbox, the path is once again the property within the source to which we’ll be binding the grid (and thus the detail fields).

    Now, every time we select an item in the listbox, the grid has its datacontext set to this selected item. The fields can now get details as follows:


    <Label Grid.Row="0" Grid.Column="1" Content="{Binding XPath=title}"></Label>

    <Label Grid.Row="1" Grid.Column="1" Content="{Binding XPath=link}">
                </Label>

    <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding XPath=description}"></TextBox>

    The result should resemble the following:



    Congratulations, you built your first databound application, using WPF databinding and a simple datatemplate!

    In my next (large) article, we’ll be looking at the styling tools provided by WPF to make this application look TONS better!

    RSS Reader.zip (45.32 KB)


    kick it on DotNetKicks.com
      Posted on: Tuesday, July 11, 2006 3:56:47 PM (Romance Daylight Time, UTC+02:00)   |   Comments [2]
             
    Gill Cleeren     .net | C# | Programming     July 11, 2006    

    I was today a small project to write Excel files from .net. As you might (or might not...) know, you have to reference the Office DLL's for that.
    I opened the project I made on a work-pc on my laptop, and all of a sudden, it didn't compile anymore.

    The Microsoft.Office.Interop.Excel was missing. However, Office (and thus Excel) 2003 is installed on my system. After some googling (it's an official word know, so let's use it ;-) ), I found out that I probably installed Office 2003 before I installed the .net framework 1.1 (shame on me...). If you install in this order, the PIA's are not installed with a typical install.

    The solution was simply run the Office setup, and install the .net Programmability Support. Problem solved... Another thing to remember when installing a new development PC!

      Posted on: Tuesday, July 11, 2006 11:55:48 AM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | Programming     July 7, 2006    

    Today, I had the oppurtunity to have lunch with 2 great Microsoft developers, Lutz Roeder and Peli de Halleux.
    If you are a .net developer, the name of Lutz Roeder might ring a bell... Ever heard of Reflector? Yes? Well then, then you heard about Lutz too. Reflector is like his "hobby" program, but for being a hobby, it's like one of the most useful programs for .net ever.

    Peli is Belgian, Lutz is German, they both work in Redmond for the big M itself. Peli works on the CLR, while Lutz has been on the Expression suite team for a few years now.

    We got some very indepth talk on programming topics, as well as some "lighter" ones, such as 'What's the weather in Seattle?' (it's very rainy, so they say...) or 'How is it like to work in Redmond'.

    A funny anecdote Peli told: it appears that in Redmond, one programmer can debug the actual bytes... If IL is not enough for him, he "simply" turns to bytecode... Go figure :-p .

    Over dinner, I got to talk to Lutz about the new Expression suite. It is actually the first program to be build in WPF entirely. He told me that building these applications wasn't always easy, since they went through the very early stages of the new platform. The Expression suite can thus be thought of as "the big test" for WPF.

    This talk was a unique chance to get to know people that you hear of, but rarely have the chance to meet. Thanks to David Boschmans and VISUG, I had this chance!

      Posted on: Saturday, July 08, 2006 1:11:20 AM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming     July 6, 2006    

    The August 2006 issue of MSDN Magazine is now available online here. And for those of you on the go, a downloadable CHM file of the entire issue is available here


     

      Posted on: Thursday, July 06, 2006 9:59:26 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming     June 18, 2006    

    For some time, I have been wondering how to create flashing, animated notify icons that appear in your taskbar. Windows has a lot of these, like for example MSN Messenger uses one when a person signs in. Or the flashing network icon when there is traffic going in or out.

    I started thinking at first it used some kind of animated gif, but soon realized that that isn’t possible, since the NotifyIcon control in WinForms programs can only handle *.ico files or *.bmp files.

    Now I found out how this actually works: the key element is the Timer control. It fires events at a regular interval, and what actually happens is that the icon is changed at these regular intervals.

    To show “the magic”, I created a little demo-project.

    First, create an array of icons:
    private Icon[] icons = new Icon[4];

    Then, load in the images. It’s actually creating an animated gif, only that now, you have to programmatically change between the steps.

    icons[0] = new Icon("green.ico");
    icons[1] = new Icon("red.ico");
    icons[2] = new Icon("green.ico");
    icons[3] = new Icon("red.ico");

    Add a NotifyIcon and a Timer control to your program. Set the timer to an interval of 1000 (that is milliseconds).

    Now, create the Tick event of the timer, to fire the event that will change the icon displayed in the NotifyIcon.
    Since we have loaded the icons in an array, all we have to do is change the index in the array, and update the icon in the NotifyIcon accordingly.

    private void timerChangeIcons_Tick(object sender, EventArgs e)
    {
       animatedIcon.Icon = icons[currentIcon];
       currentIcon++;
          if (currentIcon == 4)
             currentIcon = 0;
    }

    Don’t forget to add the timer.Start() to the load of your form!

    I did however notice something strange in the behavior of C#. It appears that icons created with for example PhotoShop or Paint throw an error when loaded: "Argument 'picture' must be a picture that can be used as a Icon”. This appears that have been a problem already in C# 1.0 and it is not addressed under C# 2.0.
    To correctly display the created icons, you have to change the headers, based on Windows API documentation.
    A workaround I found, is simply to open the icons in Visual Studio and save them again. This worked correctly afterwards.

    The complete code can be found in the zip-file.

    FlashingNotifyIcon.zip (14.98 KB)

    kick it on dotnetkicks.com
      Posted on: Sunday, June 18, 2006 12:13:28 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Programming | Vista | Windows     June 13, 2006    



    Soma announced a few days back on his blog that WinFX is to be renamed .net Framework 3.0. Kinda confusing, isn't it?

    When speaking to developers about WinFX one question that repeatedly comes up is, “WinFX sounds great, but what happens to .NET?” .NET Framework has becomes the most successful developer platform in the world.  Developers know and love .NET.

    Ok, that is true... But why not WinFX.net or something like it?

    The .NET Framework has always been at the core of WinFX, but the WinFX brand didn’t convey this.
    ...
    With this in mind we have decided to rename WinFX to the .NET Framework 3.0.  .NET Framework 3.0 aptly identifies the technology for exactly what it is – the next version of our developer framework.

    And... is the name all that changes? Appearantly yes...

    The change is in name only and will not affect the technologies being delivered as part of the product.

    Still, some things remained unclear...
    That's why I'll try to de-mistify some facts anout .net Framework 3.0.
    -The compilers used to compile 3.0 compilers are still the 2.0 compilers. 3.0 is built on 2.0,  including the CLR and BCL.

    -3.0 will NOT contain LINQ support. LINQ will be included in the Orcas release, which is due in Q4 2007. 3.0 will ship with Vista (Q4 2006).

    -It will install into %windir%\Microsoft.NET\Framework\V3.0. This is to be updated in the next CTP.

    -3.0 will install 2.0 in the same installer. This is to make things easier (yes, they are already quite complicated now).

    -For all the resources you need, Microsoft launched a community site: http://www.netfx3.com/ .

    A question that is still open: what version number will the Orcas release get then? 3.5?

      Posted on: Tuesday, June 13, 2006 10:49:18 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming | Software | Windows     June 13, 2006    

    The new issue of MSDN magazine is available. All articles can be read online for free here: http://msdn.microsoft.com/msdnmag/issues/06/07/default.aspx .



    This month, among others, 2 articles in particular are a very good read: the one on Ajax (on which I'll be doing a presentation later this week at Ordina Lummen) and one on WinFX.

    Did you also know that you can download a chm-copy of the magazine for free? Go here for this months issue or here for an entire archive on back-issues!

      Posted on: Tuesday, June 13, 2006 9:58:47 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | C# | Programming | Windows     June 8, 2006    

    MSDN now has its official Wiki! Yes, it's true :-)
    For the "official" announcement, you should take a look at Soma's blog (http://blogs.msdn.com/somasegar/archive/2006/06/08/622875.aspx).

    In the MSDN Wiki beta, you can add code samples and content directly alongside the Visual Studio 2005 and the .NET Framework 2.0 documentation in a Community Content section that we have added to each documentation topic.  Right now the MSDN Wiki site only features English documentation, but we are planning to expand this functionality to the localized documentation in the future.

    Pay a visit to them at: http://msdnwiki.microsoft.com/en-us/mtpswiki/default.aspx .

    Great work, guys!

      Posted on: Thursday, June 08, 2006 11:02:01 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | Office 2007 | Programming | Software | Microsoft | Windows     June 7, 2006    

    Over 500.000 people have downloaded Office 2007 Beta 2 in the couple of first days it was available. That's a lot, a whole lot! Chances are that you are 1 of these, isn't it?

    Now, finding some spare time to get to know the new interface, learning how to program for the new office... that's the hardest part.


    Here are some interesting resources to get you started with the new suite in no time (even without installing it!!)
    1. To get to know the basics, go to the Office 2007 preview site. Don't feel like installing it? No problem, just watch some videos on the new interface.

    2. If you are a developer like myself, you're probably more interested in developing for the new Office. Chances are that you find what you are looking for in the Office developer center. In the What's new section, you can also find links to the most important Office blogs.

    3. If Microsoft Office Sharepoint Server is your cup of tea, you're gonna be thrilled when reading in the Servers section of the developer site. Some nice screenshots of Office Sharepoint 2007 can be found here.

    Hope this brings some clarity in all the "Office violence" that awaits us!

      Posted on: Wednesday, June 07, 2006 9:00:08 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming     May 31, 2006    

    I for sure didn't...

    Let me explain the situation.
    I'm building a multilanguage ASP.net 2.0 application at KBC Bank. The underlying database is Oracle 9i. This application uses masses of dates, all are in the format required by the database, MM/YY/DDDD.

    A collegue of mine wrote some lines of code using a rowfilter to filter out some records from a dataset, retrieved from the Oracle database. So he used a simple DateTime.ToString(). This appeared to be working... until someone came along and tested it with Dutch IE browser settings.

    This resulted in a 'String was not recognized as a valid DateTime' error.

    After some research, I found that the RowFilter always uses SQL Server syntax when filtering out results, no matter if the data retrieved originates from Oracle or SQL Server.

    An article on calendars on CodeProject says the following:
    ...The code forces a "MM/dd/yyyy" date format when constructing the RowFilter as required for date comparisons in such expressions. The filter is also constructed to take into account the possibility of time values within the DayField column. 

    So, what did I do in the end? This:

    dv.RowFilter = string.Format(
                       "{0} >= #{1}# and {0} < #{2}#",
                       this.DayField,
                       day.Date.ToString("MM/dd/yyyy"),
                       day.Date.AddDays(1).ToString("MM/dd/yyyy");


    And that line saved the day :-)

      Posted on: Wednesday, May 31, 2006 11:27:17 PM (Romance Daylight Time, UTC+02:00)   |   Comments [1]
             
    Gill Cleeren     .net | ASP.net | C# | Programming     May 31, 2006    

    Today, 2 interesting programs were suggested to me by collegues on the project I'm currently working on.

    Up first is Snippet Compiler. It's a "small IDE", that enables you to do some quick tests on code. Instead of making a dummy project in VS, where you can test if for example myDateTime.ToShortDateString() also includes the hours, minutes and seconds, you just tap in the line(s) of code in Snippet Compiler. It then runs these lines as a Console application.

    To get this free tool, go here.

    The second interesting tool I discovered is "The Regulator". I had to a quite nasty regular expression, but with this open-source tool, it is much easier than sitting down and writing them by hand.

    The homepage mentions the following:
    It allows you to build and verify a regular expression against any text input, file or web, and displays matching, splitting or replacement results within an easy to understand, hierarchical tree.

    For this application, go here.

    These two applications are gonna be in my toolbox for sure ;-)

    Oh and while I'm at it, did you know the VS 2005 version of Resharper, Resharper 2.0 was released. Go here: www.jetbrains.com/resharper

      Posted on: Wednesday, May 31, 2006 11:15:37 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    Gill Cleeren     .net | ASP.net | C# | Programming | Microsoft     May 4, 2006    

    If you weren't there (like me... Vegas is a little too far ;-) ), you can now download or view all sessions of Mix06 online.

    Go here to get them all! (There are some very interesting ones on Atlas!)

      Posted on: Thursday, May 04, 2006 11:49:27 PM (Romance Daylight Time, UTC+02:00)   |   Comments [0]
             
    9/2/2010   9:23:18 PM