DCSIMG
July 2009 - Posts - Alex Golesh's Blog About Silverlight Development

July 2009 - Posts

Silverlight 3 and Expression Blend 3 Developers Day (22 July 2009) – Thanks for all participants!

image

Thank you all, who participated at Silverlight 3 and Blend 3 DevDay (Microsoft Israel offices)!

As promised, I uploaded presentation slides presented during the session to my homepage – you could get in and see them anytime for a reference.

My homepage is here.

image

 

Some demos already uploaded there (Sketch Flow Demo) and some others will be uploaded to the “Samples” page soon – stay tuned.

 

I’m really interesting within your feedback (leave comments) in order for me to be able to enhance it for future events.

 

Thanks and hope to see you again next time!

Alex

Utility: Extmap Maker

Silverlight 3 has nice feature to reduce the XAP package size of application by providing external assembly parts. To enable this feature use Silverlight project properties:

image

When this enabled, most of Microsoft assemblies will not reside inside XAP package, but as ZIP files alongside the XAP itself. The application manifest will point to those ZIP files. This will enable browser caching mechanism.

Actually, compiler “decides” which assembly will could be used as external ZIP assembly by presence of valid external map manifest file alongside assembly. I’ll not describe what is in this manifest – those, who want to know more about it could find information in very good post by Tim Heuer here.

I’m do extensive usage of this feature (because of many “infrastructure” assemblies which accompany me from project to project) and decided to build small utility for those manifest files creation.

image

Utility available for download from here.

Enjoy,

Alex

Silverlight Quick Tip: Resources in RESX files – Image Resources for Localization

This post was actually born in the middle of previous post :)

I had to find the way to use images as a RESX resources – this actually was second question of the person who asked me about forcing the rebinding.

Before starting, some theory about RESX usage in Silverlight.

Silverlight support usage of RESX files and localization via “SupportedCultures” attribute in CSPROJ file. The attribute itself even exists in project created with Silverlight 3  Tools, but for some reason there is no interface to change the cultures (or at least I didn’t found them). So the only way (for me) to change this attribute is via text editing the CSPROJ file.

<SupportedCultures>
    de,he,ru
</SupportedCultures>

After this attribute set, if we will use RESX files with standard .NET localization naming convention (<RESOURCE_NAME>.resx for culture neutral resources and <RESOURCE_NAME>.<LANGUAGE>.resx for language depended resorces) Visual Studio will compile resources and will create satellite assemblies for supported cultures.

I’ve added new “Resource” file to my project, and \added string values for HE, RU and DE languages. The 4th resource file is Neutral Culture (in my case EN) resources

image

imageimage

Here is first quick tip:

  • Change Access Modifier of your resources to “Public”, otherwise Silverlight will not be able to use it. image

Second tip:

  • Change access modifier of constructor in auto generated Resource class from internal to public (in my case the generated file was Strings.Designer.cs):
    internal Strings() -> public Strings()

The usage of those resources is very easy – simple StaticResource declaration in XAML and usage:

<Canvas.Resources>
  <local:Strings x:Key="res"/>
</Canvas.Resources>
<StackPanel x:Name="LayoutRoot" Orientation="Vertical">
  <TextBlock x:Name="txtSTR1" Text="{Binding tb1, Source={StaticResource res}}" FontSize="15" Foreground="Black"/>
</StackPanel>

This way the text displayed in TextBlock will depend on Thread.CurrentThread.CurrentUICulture value or on “uiculture” parameter for Silverlight plug-in:

<param name="uiculture" value="de" />

To see how to force re-binding when Thread.CurrentThread.CurrentUICulture value changes at the runtime – see this post.

Now to the main issue – when trying to add any non-textual resource to the resource file visual studio will generate wrong code in the Designer file:

image

For Image(of any kind)/Icon/Existing File (of image type) it will generate following code:

public static System.Drawing.Bitmap img1
{
  get
  {
    object obj = ResourceManager.GetObject("img1", resourceCulture);
    return ((System.Drawing.Bitmap)(obj));
  }
}

The “System.Drawing.Bitmap” does not exists in Silverlight, thus the application will not compile. From other hand, if Visual Studio will not identify the resource (unknown resource type) it will generate following code:

public static byte[] img1 {
    get {
        object obj = ResourceManager.GetObject("img1", resourceCulture);
        return ((byte[])(obj));
    }
}

This is much better :)

Third tip:

  • Before you adding the image resource to Silverlight resources rename them
  • Alternatively you left the file name as it was and edit RESX file in text editor as follows:
<data name="img1" type="System.Resources.ResXFileRef, System.Windows.Forms">
  <value>Resources\MVP_small.png;System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</data>

Now the usage of this resource is very simple – all we need is a converter to convert byte[] to BitmapImage (in case of images). Here the converter:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
  byte[] arr = (byte[])value;

  MemoryStream str = new MemoryStream(arr);
  BitmapImage img = new BitmapImage();
  img.SetSource(str);
  return img;
}

And usage (ByteArrConverter defined in Resources):

<Image x:Name="img" Width="100" Height="100" Source="{Binding img1, Source={StaticResource res}, 
       Converter={StaticResource ByteArrConverter}}" Margin="5"/>

Now image will be displayed on page, and it will will depend on Thread.CurrentThread.CurrentUICulture value or on “uiculture” parameter for Silverlight plug-in:

image

image

Live demo here

Sources here

 

Enjoy,

Alex

Silverlight Quick Tip: How to force re-binding

Today I’ll show how to do “dirty trick” to force re-binding and as a result UI value updating.

First of all – the reasonable question – “Why force rebinding? Why not use INotifyPropertyChanged mechanism?”

This was my questions also, but the person who asked the question had his reasons: he is using resources (Resx) to localize the application and bind the UI to those resources. Also UI gives user an ability to change the language (and code behind  does it by changing CurrentThread.CurrentUICulture). In this case what should be the notification?

The request was to keep binding definition at XAML and at the right time use those definitions to force the re-binding.

My approach was to get the BindingExpression from XAML element, and bind this XAML element to the same binding once again – this forces the binding

Sample code:

BindingExpression bindExp = txtSTR1.GetBindingExpression(TextBlock.TextProperty);
Binding bind = bindExp.ParentBinding;
txtSTR1.SetBinding(TextBlock.TextProperty, bind);
And this is actually works
image 
image 
Live demo here
Sources here
 
Enjoy,
Alex

New Website

Hello all! In addition to this blog I’ve got new website at http://www.devcorner.info/

From now on all samples related to this blog, samples from presentations and additional Silverlight (and not only) related stuff will be hosted there.

Right now the site is still almost empty (only default Silverlight 3 application there), but very soon I’ll fill it with content.

 

Alex

Posted by Alex Golesh | with no comments

Silverlight 3 Quick Tip: Analytics

Silverlight 3 has new feature which should help us to understand how good our application performs. This feature is Analytics class. It Has 2 read-only properties

AverageProcessLoad – average CPU used by this process across all the cores

AverageProcessorLoad – average CPU usage across all cores

In addition it has GpuCollection collection with objects of GpuInformation type. Each one of GpuInformation object provides information about:

DeviceId – device ID of the GPU

VendorId – vendor ID of the GPU

DriverVersion – video drivers version

 

Quick usage sample – show CPU usage:

Code behind:

public partial class MainPage : UserControl
{
  private Analytics theAnalytics;

  public MainPage()
  {
    InitializeComponent();

    theAnalytics = new Analytics();

    DispatcherTimer timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += (s, e) =>
      {
        txtCPULoad.Text = theAnalytics.AverageProcessorLoad.ToString();
        txtSLCPULoad.Text = theAnalytics.AverageProcessLoad.ToString();
      };
    timer.Start();
  }
}

XAML:

<StackPanel x:Name="LayoutRoot">
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="Average CPU Load:"/>
    <TextBlock x:Name="txtCPULoad"/>
    <TextBlock Text="%"/>
  </StackPanel>
  <StackPanel Orientation="Horizontal">
    <TextBlock Text="Average Silverlight CPU Load:"/>
    <TextBlock x:Name="txtSLCPULoad"/>
    <TextBlock Text="%"/>
  </StackPanel>
</StackPanel>

Running application:

image

 

 

Enjoy,

Alex

Silverlight 3 Quick Tip: Animation Easing and VSM

New version of VSM in Silverlight 3 got new interesting addition – ability to use Easing Function for visual state transition animation.

To use it, set the property “GeneratedEasingFunction” to desired VisuaStateTransition element and provide it with class instance with implements IEasingFunction.

From XAML:
<vsm:VisualTransition GeneratedDuration="00:00:10"
                               
To="ItemDeselected" x:Name="vtDeselected" >
  <
vsm:VisualTransition.GeneratedEasingFunction>
    <
ElasticEase Oscillations="10" Springiness="2"/>
  </
vsm:VisualTransition.GeneratedEasingFunction>
</
vsm:VisualTransition>

From Code Behind:
ElasticEase ease = new ElasticEase();
ease.EasingMode = EasingMode.EaseInOut;
ease.Oscillations = 15;
ease.Springiness = 1;
vtDeselected.GeneratedEasingFunction = ease;

 

Enjoy,

Alex

Silverlight 3 Quick Tip: Native Mouse Wheel Support

Silverlight 3 supports the mouse wheel events natively. To use this handy feature just subscribe to “MouseWheel” of UIElement. The reported values will be like follows:

  • Positive for forward scroll
  • Negative for backward scroll

 

Enjoy,

Alex

Silverlight 3 Quick Tip: Out Of Browser Settings

In MIX 09 Beta build of Silverlight 3, when we wanted to enable out-of-browser experience, we had to edit manually AppManifest.xml.

Now for Silverlight 3 projects in Visual Studio 2008 we got the out of browser settings helper dialog box

image

image

The dialog will be saved in “OutOfBrowserSettings.xml” and this file contents will be merged on compile time to the AppManifest.xml.

For hardcore programmers, who wants to write every single piece of the application without wizards/helpers – you still could use AppManifest.xml with valid declarations :)

 

Enjoy,

Alex

Silverlight 3 Quick Tip: Multitouch support on Windows 7

Silverlight 3 supports Multitouch on Windows 7.

Touch class –provides input information and resides in System.Windows.Input namespace

“FrameReported” event - fired when touch action occurs. Event arguments provide the following info:

  • Timestamp: identify the touch event by time
  • GetTouchPoints function (over specific UI Element)
  • GetPrimaryTouchPoint function (over specific UIElement)
  • SuspendMousePromotionUntilTouchUp function
  • GetTouchPoints returns TouchPointCollection

In TouchPointCollection first point in the collection is the PrimaryPoint. Each member in collection is TouchPoint. TouchPoint provides following info:

  • Position
  • Size
  • TouchDevice
  • Action

Action is from TouchAction enumeration

  • Up
  • Down
  • Move

TouchDevice provides the following info

  • Id: identification provided by operation system
  • DirectlyOver: topmost UIElement under the point

Sample code for getting touch points and simple manipulation:

//Somewhere in code – subscription for touch events:
Touch.FrameReported += new TouchFrameEventHandler(Touch_FrameReported);

When event arrives:

void Touch_FrameReported(object sender, TouchFrameEventArgs e)
    {
      TouchPointCollection points = e.GetTouchPoints(null);
      TouchPoint primaryPoint = e.GetPrimaryTouchPoint(null);

      if (null != primaryPoint)
      {
        if (primaryPoint.Action == TouchAction.Down)
          e.SuspendMousePromotionUntilTouchUp();

        switch (primaryPoint.Action)
        {
          case TouchAction.Down:
            //Business logic here...
            break;

          case TouchAction.Up:
            //Business logic here...
            break;

          case TouchAction.Move:
            //Business logic here...
            break;
        }
      }

Now you application responds for touch events (if you lucky owned of touch-enabled computer) running Windows 7 :)

 

Enjoy,

Alex

Silverlight 3 Quick Tip: Browser Zoom Support

New version of Silverlight 3 supports zoom events from the hosting browser environment.

“Zoomed” event is the new event in Content static object, and the current browser’s zoom factor in “ZoomFactor” property of the Content object:

 

App.Current.Host.Content.Zoomed += (s, e) =>

{

    //Browser’s Zoom in:App.Current.Host.Content.ZoomFactor;

};

 

Enjoy,

Alex

Silverlight 3: Hebrew and Arabic Support

Since I’m constantly getting many questions about Hebrew and Arabic support and also huge amount of requests to provide/support it, I’ve updated the SilverlightRTL project at codeplex to support Silverlight 3.

The project homepage here.

Latest release for Silverlight 3 RTW is here.

 

The updated source also includes sample application to demonstrate Bidi controls usage and comparison with standard core controls with Hebrew and Arabic:

clip_image002 

clip_image002[12]

 

Enjoy,

Alex

Silverlight 3 is RTW!!!

As expected, Silverlight 3 runtime is online via official homepage!

image

Downloading…

DL Inst

Installing…

Inst_SL3

The RTM version has build number:

About

 

Download links:

Silverlight 3 tools for Visual Studio 2008  here.

Blend 3 + SketchFlow (60 days trail) available here.

DeepZoom composer here.

Silverlight Toolkit July 2009 here.

RIA Services July 2009 here.

 

 

Download and enjoy!

Alex

Silverlight on Xbox 360

According to this article Silverlight will hit our Xbox 360 consoles soon. Silverlight-powered media on Xbox will have the same appearance as ads seen on a Web browser. Also, it will deliver 1080p HD and 5.1 surround sound without discs directly into the Xbox.

 

Stay tuned for more updates!

Alex

Posted by Alex Golesh | with no comments

I’m a Microsoft MVP!

About three hours ago, I received an email presenting me with the Microsoft MVP award! 

 image

I’m the first Silverlight MVP in Israel!!!

I am very honored to be an MVP and I will continue contributing to the online and offline developer community in Israel and abroad.

This is also a good time and place to extend a great thanks to quite a few people who made this possible:

  • Guy Burstein of Microsoft Israel (and a former MVP himself) who nominated me for the MVP program;
  • My current and past managers (Dudu, Caro, Ishai, Alon, Erez) and coworkers at Sela Group, which is easily the best software company to work for that I could think of;
  • Tamir Khason who has been a professional role model for me in my work;
  • All other peoples who helped me get this MVP award;

Stay tuned for new excitement posts on Silverlight!

Alex