Sunday, August 2, 2009

New features in Silverlight 3: Bitmap API & AddHandler

Taking snapshot of playing video …  Handling already-handled route event …. Silverlight 3 has many new features, hasn’t it?  Read my post about these two features.

Bitmap API

One of the new features in Silverlight 3 is the Bitmap API which provides the ability to render UIElements to a bitmap and provides direct access to the pixel level information of bitmaps. It is useful for taking snapshots of playing video, generating fractals, and for data visualization. The key to generating a bitmap is the WriteableBitmap class. Note that it does not render popup controls, such as Popup, ToolTip and ComboBox.

WriteableBitmap

Routed Events: AddHandler

The API AddHandler provides a technique whereby you can attach a handler that will always be invoked for the route, even if some other handler earlier in the route has set Handled to true. This technique is useful if a control you are using has handled the event in its internal compositing or for control-specific logic but you still want to respond to it on a control instance, or higher in the route.

In order to use AddHandler, the routed event must expose a public static field that is the event identifier, which is required for the routedEvent parameter. This is only true for a limited set of events in the Silverlight core classes: KeyDown; KeyUp; MouseLeftButtonDown; MouseLeftButtonUp. Do not use Loaded event and AddHandler; Loaded is not a true routed event in the Silverlight implementation. MouseMove cannot be used with AddHandler because there is no Handled in its event data. BindingValidationError cannot be used with AddHandler because there is no event identifier, and also because there is no control handling of the event.

AddHandler

Saturday, August 1, 2009

New features in Silverlight 3: Browser Zoom Support & Hardware Acceleration

In this post, I’ll write about two new Silverlight features: Browser Zoom Support and Hardware Acceleration.

Browser Zoom Support

By default, Silverlight-based content resizes in response to changes in the browser zoom setting. You can disable this feature by setting Settings.EnableAutoZoom to false, or replace it by handling the Zoomed event. If you want to supplement the zooming feature instead of replacing it, handle the Zoomed event and set EnableAutoZoom to true. You can access the zoom setting for the current browser window through the ZoomFactor property.

zoom1zoom2

Hardware Acceleration

Caching visual elements as bitmaps allows you to take advantage of hardware acceleration.

ha

Hardware acceleration can benefit performance for the following scenarios:

  • Blending two static layers using opacity
  • Transforming objects (f.i stretching a VideoBrush, stretching and rotating objects)
  • Video

The GPU acceleration feature works only in managed code.

At the object level, you set cached composition information for graphics with the CacheMode property and BitmapCache values. But the GPU acceleration must be enabled at the Silverlight plug-in level, and by default the feature is disabled. Set EnableGPUAcceleration to true to enable GPU acceleration.

During profiling of application, you can set EnableCacheVisualization (Silverlight Plug-in Object) to true to produce an overlay visualization of the areas in your UI that are being hardware accelerated. Areas where optimisations are not being applied will be coloured (red) whereas areas where the optimisations are being applied will use their usual colours.

Caching objects can hurt performance if you misuse it. You only set CacheMode on objects that are either being transformed or having opacity changes applied because otherwise the object will not benefit from caching and performance could be worse than if you did not cache it.

EnableGPUAcceleration = false Without_GPU_CacheEnableGPUAcceleration = true, EnableCacheVisualization = true, CacheMode = null GPU_Without_CacheEnableGPUAcceleration = true, EnableCacheVisualization = true, CacheMode = BitmapCache With_GPU_and_Cache

Thursday, July 30, 2009

Silverlight 3 Puzzle: Binding & DataGrid

Yesterday I had a strange bug in our application after migration to Silverlight  3.  Inner DataGrid exception was thrown when DataGrid cell with ComboBox was changed.  It took me about one day to puzzle out the bug.

I have received the following error message:

Operation is not valid due to the current state of the object.   at System.Windows.Data.BindingExpression.UpdateSource()
   at System.Windows.Controls.DataGrid.EndCellEdit(DataGridEditAction editAction, Boolean exitEditingMode, Boolean keepFocus, Boolean raiseEvents)
   at System.Windows.Controls.DataGrid.SetCurrentCellCore(Int32 columnIndex, Int32 slot, Boolean commitEdit, Boolean endRowEdit)
   at System.Windows.Controls.DataGrid.ProcessSelectionAndCurrency(Int32 columnIndex, Object item, Int32 backupSlot, DataGridSelectionAction action, Boolean scrollIntoView)
   at System.Windows.Controls.DataGrid.UpdateSelectionAndCurrency(Int32 columnIndex, Int32 slot, DataGridSelectionAction action, Boolean scrollIntoView)
   at System.Windows.Controls.DataGrid.UpdateStateOnMouseLeftButtonDown(MouseButtonEventArgs mouseButtonEventArgs, Int32 columnIndex, Int32 slot, Boolean allowEdit)
   at System.Windows.Controls.DataGridCell.DataGridCell_MouseLeftButtonDown(Object sender, MouseButtonEventArgs e)
   at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
   at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)

I have debugged my application with the sources (controls: DataGrid, DataGridColumn, DataGridTemplateColumn, DataGridCell, etc.)

This error was caused by setting binding to SelectedItem property of  ComboBox twice:

  1. In cell editing template of DataGridTemplateColumn
  2. In the body of a method overriding OnPreparingCellForEdit method of DataGrid

To resolve this problem you should remove on of binding definition.

I have reproduced this bug by creating my sample below.

bug-sh

Wednesday, July 29, 2009

New features in Silverlight 3: better styles, high contrast & system colors

Today I present new features of styles and integration with operating system display settings.

Styles

Now styles can be applied more than once. It is possible to build a new style based on an existing style. You can also manage easier resources (see Merged Resource Dictionaries).

Here is my sample using these new features.

styles1-sh styles2-sh styles3-sh

High-Contrast

Users can increase the contrast in the operating system to improve interface visibility. Control code can examine the HighContrast property, and should use techniques to increase visibility when operating in high-contrast mode. On computers that run Windows, the HighContrast property is true when the user has enabled High Contrast in Control Panel. On Macintosh computers, HighContrast is true when the user has selected the White on Blackoption in Universal Access.

System colors

Silverlight 3 now supports operating system colors. In System.Windows namespace exists new static class SystemColors with colors definitions. Those colors could be use as a Color in any brushes.

Here is my sample application using the HighContrast property and SystemColors class.

contrast1-sh contrast2-sh

Monday, July 27, 2009

New features in Silverlight 3: Networking and Communication

In new version of Silverlight there are some changes in communication. I’ll write about them.

Browser or Client HTTP Handling

You can specify whether the browser or the client provides HTTP handling for your Silverlight-based applications. By default, HTTP handling is performed by the browser. In addition, you can specify the scope for the handling: all messages, a scheme (HTTP or HTTPS), a particular domain, or a single request object.

Typical scenarios with client HTTP handling:

  • Using HTTP methods other than GET and POST.

  • Using response status codes headers, response bodies in your application or for debugging purposes.

  • Sending XML HTTP requests such as REST and SOAP messages.

  • Manually managing cookies.

SOAP Faults

There are two ways to enable SOAP fault consumption:

  • You can modify your service to return SOAP faults with an HTTP status code of 200. This will make the service non-compliant with the SOAP protocol, since SOAP requires a response code in the 400 or 500 range for faults. If the service is a WCF service, you can create an endpoint behavior that plugs in a message inspector that changes the status code to 200. Then, you can create an endpoint specifically for Silverlight consumption, and apply the behavior there. Your other endpoints will still remain SOAP-compliant.
  • You can register client HTTP stack using the RegisterPrefix method. Client HTTP Handling allows you to process SOAP-compliant fault messages. However, a potential problem of switching to the alternative HTTP stack is that information stored by the browser (such as authentication cookies) will no longer be available to Silverlight, and thus certain scenarios involving secure services might stop working, or require additional code to work.

Message Credentials Authentication

A small subset of the WS-Security protocol is supported, namely, the ability to send username and password tokens in messages. When message credentials authentication is used in Silverlight, every request message will contain a SOAP header that conforms to the WS-Security protocol. The header will contain an unencrypted token with a user name and a password. You must provide them in your Silverlight code. Because the user name and password credentials are sent in plaintext (that is, unencrypted) form, you must use a secure transport (such as HTTPS) to prevent attackers from stealing the credentials while they are in transit. If you attempt to use this feature with a non-secure transport (such as HTTP), an exception will be thrown.

Other changes

  • Binary XML (binary encoding,  default encoding in Silverlight-enabled WCF Service VS template)
  • SLsvcutil.exe
  • Proxy in PollingDuplexHttpBinding

More information you can find here

I have build two samples for SOAP Faults and username authentication. I have made two versions each of them:  with  endpoint behavior and with client HTTP handling. BTW, I have little problem with reading error messages when I throw authentication or fault exceptions in username validator. Have you any idea how it should be done ?

wcf-sh

Wednesday, July 22, 2009

New features in Silverlight 3: Binding & Validation

Silverlight 3 has enhanced support for binding and data entry validation. I’ll describe it.

Binding

In Silverlight 3 you can use the ElementName property or the RelativeSource property to specify the binding source.

The ElementName property is useful when you are binding to other elements in your application.

The RelativeSource property is useful when the binding is specified in a ControlTemplate or a Style. RelativeSource markup extension has two modes:  Self or TemplatedParent. The Self mode is useful for cases where the same element should be used as the source object and target object for a binding, but different properties are the source and the target. The TemplatedParent mode is used for a data validation scenario where a template can establish the UI for error handling that occurs at run time.

In Silverlight 3 you can disable automatic source updates and update the source at times of your choosing. To do it set the UpdateSourceTrigger property to Explicit.

Validation

Silverlight 3 supports basic data validation in TwoWay bindings for target-to-source updates. Silverlight provides visual feedback for validation errors when you set the ValidatesOnExceptions property to true on the binding object. In order to receive notification that a validation error has occurred, you must also set the NotifyOnValidationError property to true on the binding object.

When you use data classes in your application, you can apply attributes to the class or members that specify validation rules, specify how the data is displayed, and set relationships between entity classes. The System.ComponentModel.DataAnnotations namespace contains the classes that are used as data attributes.

The validation and display attributes are automatically applied when used with the DataGrid control.

The ValidationSummary control displays a consolidated list of validation errors for a given container.

For more information about binding and validation look here:

I have tested all features described in the post. There are three samples in the zip file.

validation1-sh

validation2-sh 

Tuesday, July 21, 2009

New features in Silverlight 3: Pixel Shader Effects & Easing Functions

Today I’ll write about pixel shaders and easing functions.

Pixel Shader Effects

There are two pixel shader effects included with the Silverlight runtime: DropShadowEffect and BlurEffect. You can create your own effects, too.

Pixel shader effects in Silverlight are rendered in software. Any object that applies an effect will also be rendered in software. Therefore, you should be careful.

pi-invert

Easing Functions

Easing functions allow you to apply custom mathematical formulas to your animations. For example, you may want an object to realistically bounce or behave as though it were on a spring. There are many predefined functions or you may create your custom.

BackEase

BackEase EasingMode graphs.

BounceEase

BounceEase EasingMode graphs.

CircleEase

CircleEase EasingMode graphs.

CubicEase

CubicEase EasingMode graphs.

ElasticEase

ElasticEase with graphs of different easingmodes.

ExponentialEase

ExponentialEase graphs of different easingmodes.

PowerEase

QuarticEase with graphs of different easingmodes.

QuadraticEase

QuadraticEase with graphs of different easingmodes

QuarticEase

QuarticEase with graphs of different easingmodes.

QuinticEase

QuinticEase with graphs of different easingmodes.

SineEase

Cc189019.SineEase_Graph(en-us,VS.95).png

You can simply apply these easing functions to From/To/By and Key-Frame animations.

I had created simple pixel shader which inverts colors. The zip file also contains examples of other pixel shaders and easing function which I had found and I have updated to RTW.