Welcome to MSDN Blogs Sign in | Join | Help

On Silverlight 4 Beta / Silverlight 3 backward compatibility

Edit: Clarified the term quirks mode which Silverlight 4 implements to ensure compatibility with existing Silverlight 3 applications

Silverlight 4 Beta has publicly been among us for over a week now, and the customer I’m currently working for is jumping on the Silverlight 4 bandwagon thanks to its slew of new features. A very legitimate question we had when “porting” his application to Silverlight 4 / Visual Studio 2010 was about the way Silverlight 4 handled backward compatibility for existing Silverlight 3 applications and code. Here is a short brief on the subject :

  • Silverlight 4 is not an incremental update like .NET 3.0 was for .NET 2.0; this means that the runtime has evolved between the two versions
  • Silverlight 4 features a quirks mode to make sure your Silverlight 3 applications run as they always did. Technically, the Silverlight runtime does this based on the XAP’s manifest : if a runtime version prior to 4.0 is specified, Silverlight runs in quirks mode. This mode faithfully reproduces the behavior of previous runtimes (Silverlight 3, but also 1 and 2) by wrapping around changes between versions.
    clip_image001 
    When upgrading your application to Silverlight 4 check for binary assemblies (DLL) compiled with Silverlight 3 included in your new XAP file, as they will run outside of quirks mode. As it is very often the case, mixing binary versions should be avoided.
    • MyApp.xap (targeting SL4)
    • Main.dll
      • SL4Assembly.dll
      • SL3Assembly.dll <- this will not run in quirks mode!
  • When using Prism, since all assemblies load in the same AppDomain, they will all run in the mode defined by the main XAP’s manifest

In order to read AppManifest.xml, just explore the XAP file as if it were a ZIP file.

Note: Neat! My previous post was featured on This Week On Channel 9 !

Posted by lvovan | 0 Comments

Silverlight 4 et la rétrocompatibilité (compatibilité ascendante) avec Silverlight 3

Edit: Clarification de la fonctionnalité quirks mode, qui assure une compatibilité ascendante

Silverlight 4 Beta est disponible publiquement depuis plus d’une semaine, et le client avec qui je travaille actuellement a décidé de cibler cette version afin de profiter des nombreuses nouvelles fonctionnalités offertes. Une question légitime qu’il s’est posé lors du passage vers Silverlight 4/Visual Studio 2010 est celle de la rétrocompatibilité: comment Silverlight 4 gère-t-il les applications ciblant une version précédente du runtime? Voici un bref résumé sur le sujet :

  • Silverlight 4 n'est pas uniquement un ajout de nouvelles classes comme l’a été .NET 3.0 par rapport à .NET 2.0. Il s’agit d’une évolution: le runtime du 4 remplace celui du 3
  • Silverlight implemente le quirks mode pour assurer que la bonne exécution des applications existantes. Lorsque le manifest d’un XAP précise une version antérieure de SL3 dans son manifest, SL4 passe en mode quirks. Ce mode implémente des mécanismes permettant de s’exécuter à la manière des versions antérieures du runtime (il traite également de la rétrocompatibilité vers les runtimes 1 et 2).
    clip_image001
    Lors de la mise à jour d’une application vers Silverlight 4, vérifiez les assemblies (DLL) binaires SL3 présente dans le nouveau XAP en effet, l’application ayant pour cible la version 4, elle s’exécutera hors du mode quirks. Il faut en général éviter de mélanger des binaires ciblant des runtimes différents.
    • AppManifest.xaml (ciblant SL4)
    • Main.dll
      • SL4Assembly.dll
      • SL3Assembly.dll <- ne s’exécutera pas en mode quirks !
  • Lorsque l’on utilise Prism, puisque toutes les assemblies se chargent dans le même AppDomain, celles-ci s’exécuteront toutes dans le mode défini par le manifest du XAP principal

Pour voir le manifest d’une application (XAP), il vous suffit d’explorer le fichier XAP comme s’il s’agissait d’un fichier ZIP.

Note: Cool! Mon previous précédent a été cité sur This Week On Channel 9 (15:00) !

Posted by lvovan | 0 Comments

Windows Live Writer Silverlight App Plugin

I’ve been blogging about WPF and Silverlight using Windows Live Writer (WLW) for quite a while now. But there’s something I found really awkward : I never actually had some Silverlight running within a post! Since a XAP is worth way more than static screenshots, I got to work and three hours later I had the Silverlight App Plugin  working. It is now as easy as uploading your XAP, clicking “Silverlight XAP” from WLW, and paste the XAP’s URL to have your application running within your post.

Get Microsoft Silverlight

I’ve also added some optional parameters such as plugin size, background color as well as the minimum version of Silverlight required.

The plugin setup and its source code are attached to this post and are provided as examples. Happy blogging!

Silverlight App Plugin pour Windows Live Writer

Cela fait quelque temps que je blog à propos de WPF et Silverlight avec Windows Live Writer (WLW). Une chose me chiffonnait cependant… je n’avais jusqu’à maintenant jamais inclus d’application Silverlight directement dans mes posts ! Puisqu’un XAP vaut mieux que des images statiques, je me suis mis au travail et quelques heures plus tard le Silverlight App Plugin était né. Il suffit maintenant d’uploader votre XAP et de cliquer sur “Siverlight XAP…” dans WLW pour insérer l’application dans votre post.

Get Microsoft Silverlight

J’ai également ajouté quelques paramètres optionnels comme la taille du plugin, la couleur de fond ou encore la version minimale de Silverlight requise.

Le plugin et son code source sont attachés à ce post, et sont fournis à titre d'exemple. Bon blogging!

Ajouter des icônes vectorielles à vos application … grâce aux polices de caractère

Trouver des icônes est souvent une tâche pénible pour les développeurs. Ce post décrit une technique simple pour utiliser des polices « symboliques » dans vos applications WPF et Silverlight permettant ainsi :

  • D’avoir des icônes vectoriels donc retaillables sans perte
  • Une amélioration potentielle des performances en passant par la stack de rendu de texte optimisée
  • Avoir votre jeu d’icônes dans un fichier unique (Silverlight), voire sans aucune ressource supplémentaire (WPF)
  • Inconvénient : les polices étant définies de manière monochromatique, elles ne sont affichées qu’avec une unique brush. Bien que vous puissiez définir une brush des plus  extravagantes, vos icônes sont intrinsèquement monochromes.

FontsAsVectorIcons

Pour les applications WPF, il suffit de définir en tant que FontFamily le nom d’une police disponible localement :

<TextBlock FontFamily="Wingdings" Text="A B C 7 8 9"/>

Sur Silverlight 2 et supérieur, vous pouvez embarquer une police directement dans votre XAP en tant que fichier ressource. Vous pourrez ensuite la référencer par la syntaxe suivante :

<TextBlock FontFamily="MyFontFile.ttf#My Font" Text="A B C 7 8 9"/>

 ou si vous chargez la police depuis une autre assembly

<TextBlock FontFamily="/MyAssembly;Component/MyFontFile.ttf#My Font" Text="A B C 7 8 9"/>

En Silverlight, spécifier le nom d’une police disponible localement marchera dans certain cas, car les polices de l’OS sont mises à contribution lors de la résolution de FontFamily. Ce n’est cependant pas une bonne pratique de portabilité. Par exemple, Wingdings n’est pas disponible par défaut sur d’anciennes versions de Mac OS X, ce qui engendre l’utilisation de la police par défaut « Portable ».

FontsAsVectorIcons_mac

Veillez ainsi à inclure les polices que vous utilisez, et dont vous disposez des droits de distribution, dans vos XAPs.

Important : Les polices disponibles avec votre système, par exemple Wingdings sous Windows, sont soumises à des droits d’auteurs et ne sont pas librement distribuables. Vous pouvez obtenir des polices libres de droit sur le web en  utilisant votre moteur de recherche préféré ou en contactant le détenteur des droits de la police que vous souhaitez utiliser.

Comme toujours, j’espère que ce post vous sera utile !

Posted by lvovan | 0 Comments
Attachment(s): FontsAsVectorIcons.zip

Get whole sets of vector icons using … Fonts!

Finding icons is a tedious task for most developers. In this post I will demonstrate how to use “symbolic” fonts in your WPF or Silverlight applications, which provide the following benefits:

  • Vector icons that are smoothly scalable
  • Potentially better performance, using the platforms’ optimized text rendering stack
  • Get a whole set of icons in single resource file (Silverlight), or no embedded resource at all (WPF)
  • Caveat: fonts are only rendered using a single brush. Just like any other text content you can make your own fancy brush, but your icons are defined monochromatically

FontsAsVectorIcons

For WPF applications, there is nothing to do but specify a locally available font for the FontFamily property:

<TextBlock FontFamily="Wingdings" Text="A B C 7 8 9"/>

For Silverlight 2 or later application, leverage the embedded font feature by embedding your font files as resources. Then reference them using the following syntax:

<TextBlock FontFamily="MyFontFile.ttf#My Font" Text="A B C 7 8 9"/>

or, if loading, your font from a different assembly

<TextBlock FontFamily="/MyAssembly;Component/MyFontFile.ttf#My Font" Text="A B C 7 8 9"/>

Simply specifying the font name like in WPF will work most of the time since Silverlight leverages the OS’ font system to resolve font families, but this is not good practice. For example Wingdings is not available by default on older versions of Mac OS X, which will cause Silverlight to fall back to the portable font on this platform.

FontsAsVectorIcons_mac


Thus, make sure that the fonts you use are embedded in your application and that you have the right to redistribute them.

Important: Be aware that most fonts usually available on your system, such as Wingdings on Windows, are copyrighted and not freely redistributable. You can get freely redistributable fonts from the web using your favorite search engine or contact the copyright holder to get information about font licensing.

As always, I hope you find this trick useful!

Posted by lvovan | 0 Comments
Attachment(s): FontsAsVectorIcons.zip

Silverlight: accéder à des fichiers en dehors du répertoire ClientBin

Accéder à un fichier quelconque sur votre site web est une action très courante dans les scénarios RIA. C’est d’ailleurs très facile avec Silverlight, si vos ressources se situent dans le répertoire ClientBin, ou si vous disposez de l’URI absolue (complète) du fichier en question. Malheureusement, la notation ../ ne permet pas à ce jour de remonter au dessus du répertoire ClientBin. Ce post montre une solution permettant d’accéder à un fichier hors de ce répertoire et de façon relative.

Imaginons que vous souhaitiez accéder aux fichiers Images/MyRobots.jpg ou Desert.jpg, tous deux hors du répertoire ClientBin :

image

Comme mentionné précédemment, l’utilisation de ../ ou / dans vos URI Silverlight 3 ne permettra pas de remonter dans l’arborescence. La seule façon d’accéder à ces images serait d’utiliser une URI absolue (du type http://www.abc.com/mysite/Images/MyRobots.jpg), ce qui ne vous conviendra probablement pas car il faudrait recompiler votre application si votre site vient à être déplacé.

La solution consiste à déterminer au runtime, le chemin absolu de votre application et de l’utiliser comme préfixe aux ressources auquelles vous souhaitez accéder. Cette adresse est obtenue par le biais du code suivant:

Application.Current.Host.Source.AbsoluteUri

Puis supprimez simplement ClientBin :

Regex.Replace(Application.Current.Host.Source.AbsoluteUri, @"ClientBin/[\w/.]*", string.Empty);

Comme à l’habitude, un projet exemple est attaché à ce post, et il fait usage de cette technique par le biais d’un Binding et d’un converter, et par une propriété statique.

<Image Source="{Binding Converter={StaticResource WebSiteRelativeURIConverter},ConverterParameter=Images/,Path=MyImageFilename/>

image

En espérant que vous trouverez cela utile :)

Posted by lvovan | 0 Comments
Attachment(s): RelativeExternalUris_fr.zip

Silverlight: Accessing files outside of the ClientBin directory of your website using a relative URI

Accessing an arbitrary file on your website is a very common need in RIA scenarios. This is easily done from Silverlight when the files you are trying to access are under the ClientBin directory, or given an absolute URI path to the targeted file. Unfortunately, the ../ notation in Silverlight URIs  does not go up from the ClientBin directory.

Let’s say you want to access MyRobots.jpg from your site’s Images directory :

image

As previously stated, using ../ or just / in Silverlight 3 will only go up to the ClientBin directory. The only way to gain access to the image is to use an absolute URI in the form of http://www.abc.com/mysite/Images/MyRobots.jpg, which you probably do not want as moving your application to another site would require a recompilation of your program.

The solution is to determine at runtime the absolute path of your application, and use it as a prefix to the resources you want to access. You can get your application’s absolute URI using the following code:

Application.Current.Host.Source.AbsoluteUri

Just remove the ClientBin part and you are ready to go:

Regex.Replace(Application.Current.Host.Source.AbsoluteUri, @"ClientBin/[\w/.]*", string.Empty);

As usual, an example project is attached, where I make use of this technique in a Binding with a Converter and a static property.

<Image Source="{Binding Converter={StaticResource WebSiteRelativeURIConverter},ConverterParameter=Images/,Path=MyImageFilename/>

image

Have fun!

Posted by lvovan | 0 Comments
Attachment(s): RelativeExternalUris_en.zip

The FormatConverter, and XamlParseExceptions in Microsoft Expression Blend

A converter we very often use and reimplement is the so-called FormatConverter, which takes a string as a value and uses with the converter’s parameter in a call to String.Format. This eases sometimes shortens the XAML by quite a bit when concatenating strings, or can also be used to apply specific formatting to floating point numbers or dates.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    if (value == null) return null
    var parm = parameter as string
    if (string.IsNullOrEmpty(parm)) return value; 
    return string.Format(parm, value);
} 

Which is used as follows :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='{0:0.00}'}

Note that we escape the target string with single quotes, and that we use the {0} notation to specify the binding’s value we want to format.

The naive implementation for this converter has a major drawback : braces are reserved for XAML markup extensions, and they cause syntax/parsing errors with WPF and Expression Blend. Silverlight 3’s XAML parser being more permissive, the converter compiles and runs fine, but still causes an exception in Expression Blend.

image

The workaround for this is quite simple: replace braces with square brackets in the XAML, and do the reverse in the converter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

    if (value == null) return null;

    var parm = parameter as string;

    if (string.IsNullOrEmpty(parm)) return value;

    return string.Format(parm.Replace('[','{').Replace(']','}'), value);

}

Which is used as follows :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='[0:0.00]'}

This trick is simple, works on both frameworks, and will probably enlighten the life of your favorite XAML designer/integrator :)

Le FormatConverter, et les XamlParseException dans Microsoft Expression Blend

Un converter que l’on voit et réimplémente très souvent est le FormatConverter, qui consiste à prendre en entrée une chaîne et l’utiliser comme paramètre pour la méthode String.Format. Cela permet par exemple d’éviter une redondance de runs lorsque l’on souhaite concaténer des chaînes, ou encore d’appliquer un formatage spécifique aux flottants ou aux dates.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

    if (value == null) return null;

    var parm = parameter as string;

    if (string.IsNullOrEmpty(parm)) return value;

 

    return string.Format(parm, value);

}

 

Ce qui donne à l’utilisation :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='{0:0.00}'}

Notons que l’on échappe ici la chaîne à traiter par des apostrophes, et que l’on doit utiliser la notation {0} pour spécifier l’emplacement de la valeur du binding à formater.

L’implémentation naturelle de ce converter a un inconvénient majeur : les accolades étant normalement réservées aux markup extensions XAML, elles provoquent des erreurs de syntaxe/parsing avec  WPF et Expression Blend. Le parser de Silverlight 3 étant plus permissif, le converter compile et fonctionne au runtime pour les applications RIA, mais cause toujours une XamlParseException dans Expression Blend.

image

La solution de contournement est simple : remplacer les accolades par des crochets dans le XAML, puis effectuer la substitution inverse dans le converter :

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)

{

    if (value == null) return null;

    var parm = parameter as string;

    if (string.IsNullOrEmpty(parm)) return value;

 

    return string.Format(parm.Replace('[','{').Replace(']','}'), value);

}

Ce qui donne à l’utilisation :

{Binding MyValue, Converter={StaticResource BlendableFormatConverter}, ConverterParameter='[0:0.00]'}

Cette astuce très simple fonctionne sur les deux plateformes et permet, au grand bonheur du designer/intégrateur XAML, d’obtenir un rendu visuel interactif directement dans Expression Blend.

Différences de namescopes et DataContext entre WPF et Silverlight

Lors de l’implémentation d’un UserControl, vous aurez très souvent à databinder un objet déclaré en XAML à une ou plusieurs propriétés du UserControl lui-même. La façon la plus élégante de procéder consiste à utiliser un binding ElementName.

<UserControl x:Class="NameScopeExample.MyUserControl"x:Name="ucName">
<
TextBlock Foreground="White" Text="{Binding MyProperty.Description,ElementName=ucName}"/>

Ce scénario fonctionne sans accroc avec WPF mais n’est à ce jour pas supporté par Silverlight, comme la solution attachée à ce post le démontre.

Cette différence de comportement est dûe au fait que Silverlight ne supporte qu’un seul namescope, alors que WPF permet l’utilisation de namescopes imbriqués. Cela signifie qu’un contrôle utilisateur Silverlight ne peut disposer que d’une seule valeur x:Name par instance. Dans l’exemple, deux noms différents sont donnés à une même instance: une fois dans le fichier XAML du contrôle lui-même, et une autre par le biais de MainPage.xaml.

MainPage.xaml
<local:MyUserControl x:Name="ucNameInMainPage" MyProperty="{Binding MainPageProperty}"/>

MyUserControl.xaml
<UserControl x:Class="NameScopeExample.MyUserControl" x:Name="ucName">

Dans Silverlight, MyUserControl ne gardera que le nom donné par le contrôle le moins imbriqué, dans notre cas celui de MainPage (ucNameInMainPage), causant ainsi une erreur de résolution de nom d’élément dans le premier binding du UserControl. La solution de contournement est assez simple: utiliser le DataContext implicite et définir via le code le DataContext de l’élément racine (souvent une Grid nommée LayoutRoot). Ceci est possible après un appel à InitializeComponent, et en modifiant le binding en supprimant la propriété ElementName.

void MyUserControl_Loaded(object sender, RoutedEventArgs e)

{

    // Implicit DataContexts work on both frameworks 

    // Les DataContexts implicites fonctionnent sur les deux frameworks

    this.LayoutRoot.DataContext = this;

}

 

<UserControl x:Class="NameScopeExample.MyUserControl"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Loaded="MyUserControl_Loaded"

    Width="450" Height="300" x:Name="ucName">

    <TextBlock Foreground="White" Text="{Binding MyProperty.Description}"/>

La solution exemple démontre également deux astuces qu’il m’arrive parfois d’utiliser :

  • Utiliser un lien afin qu’un fichier source puisse être partagé entre une application Silverlight et une application .NET (WPF dans notre cas). Dans l’exemple, MyUserControl et MyClass sont compilés indépendamment pour les deux plateformes.
  • Vous pouvez insérer une accolade ouvrante dans une valeur d’attribut XAML en le préfixant de la séquence d’échappement {}
    <TextBlock Foreground="LightGray" Text="{}{Binding MyProperty,ElementName=ucName}"/>
Posted by lvovan | 0 Comments
Attachment(s): NameScopeExample.zip

WPF and Silverlight namescopes and DataContext differences

When authoring a UserControl, you will more often than not end up data binding properties of objects in your XAML file to properties of your UserControl itself. The most elegant way to do this would be without any code-behind at all, using ElementName bindings.

<UserControl x:Class="NameScopeExample.MyUserControl"x:Name="ucName">
<
TextBlock Foreground="White" Text="{Binding MyProperty.Description,ElementName=ucName}"/>

This scenario works well with WPF but is not supported by Silverlight. This is demonstrated in the attached solution, where the element name binding doesn’t return a value in the Silverlight project, but behaves as described with WPF.

image

The reason for this is that Silverlight only supports a single namescope, while WPF can handle nested namescopes for element names: meaning that a Silverlight control can only have a single x:Name. In the example, we are actually trying to give the instance of MyUserControl two distinct names, one in the UserControl’s declaration (MyUserControl.xaml) and another in the parent (MainPage.xaml).

MainPage.xaml
<local:MyUserControl x:Name="ucNameInMainPage" MyProperty="{Binding MainPageProperty}"/>

MyUserControl.xaml
<UserControl x:Class="NameScopeExample.MyUserControl" x:Name="ucName">

With Silverlight, MyUserControl will only keep the name given by the least nested control (ucNameInMainPage), thus causing a failure in the resolution of the ElementName binding. Working around this is quite simple, and works equally well for both frameworks: make use of implicit DataContexts and set the context of the topmost element of your XAML file (usually a Grid named “LayoutRoot” in Silverlight). You can do this after the call to InitializeComponent, and modify your bindings so as to remove the ElementName property.

void MyUserControl_Loaded(object sender, RoutedEventArgs e)

{

    // Implicit DataContexts work on both frameworks

    // Les DataContexts implicites fonctionnent sur les deux frameworks

    this.LayoutRoot.DataContext = this;

}

 

<UserControl x:Class="NameScopeExample.MyUserControl"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Loaded="MyUserControl_Loaded"

    Width="450" Height="300" x:Name="ucName">

   

<TextBlock Foreground="White" Text="{Binding MyProperty.Description}"/>

The sample solution attached to this post also demonstrates two tricks I sometimes use:

  • Use a link (http://msdn.microsoft.com/fr-fr/library/9f4t9t92.aspx) so that a source file is shared between a Silverlight and a .NET application (in our case, WPF). In the example, the MyUserControl and MyClass files are compiled independently for each platform.
  • You can escape an opening brace by prefixing it with the {} XAML escape sequence
    <TextBlock Foreground="LightGray" Text="{}{Binding MyProperty,ElementName=ucName}"/>
Posted by lvovan | 0 Comments
Attachment(s): NameScopeExample.zip

ParseException AG_E_PARSER_BAD_TYPE : les points &#224; v&#233;rifier

Lors de l'exécution d'une application Silverlight, il arrive parfois de rencontrer une ParseException(“AG_E_PARSER_BAD_TYPE”). Malgré sa description quelque peu crue, le message décrit bel et bien l'erreur rencontrée : un problème de type est survenu lors de la phase de parsing d'un fichier XAML.

J'ai compilé ci-dessous une liste des vérifications que j'utilise pour déterminer la cause de ce type d'exception :

  • Si vous avez récemment renommé un fichier XAML, vérifiez que la valeur de son attribut x:Class correspond bien à sa classe code-behind associée
  • Pour chaque déclaration XAML préfixée d'un namespace, vérifiez que les déclarations xmlns correspondent bien aux assemblies définissant l'objet déclaré
  • Vérifiez que votre projet référence les assemblies utilisées par vos objets déclarés dans le XAML ("Ajouter une référence..."), et que ces assemblies sont belles et biens présentes dans le fichier XAP compilé. Pour explorer le contenu d'un XAP, vous pouvez utiliser votre logiciel d'archivage préféré, ou bien changer son extension en .ZIP et l'explorer. Notez cependant que dans le cas des applications composites, une assembly peut avoir déjà été chargée par un autre module ou le shell.
  • Vérifiez les valeurs des propriétés Copy local des assemblies référencées par vos projets, afin de s'assurez vous que chaque assembly est chargée par au moins un projet lors de l'exécution
  • Si vous utilisez Prism, faire que votre shell référence les assemblies dont vos modules dépendent peut résoudre le problème, c'est d'ailleurs une façon populaire de résoudre le problème si vous utilisez le Silverlight Toolkit. Bien que référencer toutes les dépendances directement depuis le shell aille à l'encontre même de la philosophie composite, référencer les assemblies de contrôles utilisateurs est en général une bonne idée.
  • En dernier recours, vous pouvez utiliser l'astuce de David Yack : forcer une instanciation du type récalcitrant dans le constructeur, avant même d'appeler la méthode InitializeComponent()

Comme vous avez pu le constater, cette exception est en général causée par un problème de résolution de type: assurez-vous donc que les assemblies référencées par le XAML sont bien accessibles.

The XamlParseException AG_E_PARSER_BAD_TYPE checklist

While running a Silverlight application, you might sometimes encounter the dreaded runtime ParseException(“AG_E_PARSER_BAD_TYPE”). Despite its rather crude description, the message actually means something close to the words it uses: during the XAML parsing phase something went wrong with a type.
Here is a checklist I use to hunt down the cause for this exception:

  • If you recently renamed a XAML file, check that its x:Class attribute matches the one in the associated code-behind file 
  • For every prefixed declaration in your XAML file, check that the XML namespaces match the correct assemblies
  • Verify that your project references the assemblies used by the objects declared in your XAML files ("Add reference..."), and that these assemblies are present in the destination XAP files (use your favorite archiver, or change the XAP’s extension .ZIP and explore)
  • Verify the value for the Copy local property of the assemblies referenced by your project’s XAML files, so that the assemblies are loaded by at least one project at runtime
  • When using Prism, making your shell reference your assemblies (like the Silverlight Toolkit) can sometimes solve the issue. While making your shell reference every dependency your modules use definitely goes against the composite philosophy, referencing controls assemblies is usually a good idea.
  • If all else fails, you can David Yack’s tip: force an instantiation of the type that causes the error in the constructor, prior to calling the InitializeComponent method

As you might have noticed, the cause for this exception usually comes down to a failure in type resolution. So make sure your referenced assemblies are available at runtime and you should be set.

Posted by lvovan | 1 Comments

&quot;The configuration section for Logging cannot be found in the configuration source.&quot; or how to read an external configuration file for the Logging Application Block

When using the Logging Application Block, using an IConfigurationSource to read your logging configuration from an external reference might throw a ConfigurationErrorsException("The configuration section for Logging cannot be found in the configuration source."), or ignore your configuration changes. This exception is usually caused by the Logger façade, which forcibly initializes using the application default .NET configuration file and not the one specified in the IConfigurationSource. In this scenario, avoid using the Logger class and use the LogWriter created from the Iconfiguration source.

// Reads a Logging Application Block configuration from an external configuration file

var fcs = new FileConfigurationSource(@"C:\TEMP\MyLoggingConfiguration.config");

var logWriter = new LogWriterFactory(fcs).Create();

var logEntry = new LogEntry() { Message = "Hello logging!" };

 

// You can use the logWriter directly

logWriter.Write(logEntry);

 

// Throws a ConfigurationErrorsException "The configuration section for Logging cannot be found in the configuration source."

// Because the Logger facade forcibly initializs using the application’s default .NET configuration file and not the one
// we specified manually (EntLib 4.1)

Logger.Write(logEntry);

Thanks to Renaud providing me an idea for the post!

Posted by lvovan | 0 Comments
Filed under: , ,
More Posts Next page »
 
Page view tracker