Monday , 24 November 2014
Home » Silverlight

Silverlight

Whats new in Silverlight 5

Silverlight 5 adds over 40 new features over last Silverlight version.

For more information on the Silverlight 5 announcements check http://www.microsoft.com/silverlight/future.

Multiple Window Support

Multiple window support enables a trusted application to dynamically create additional top level
windows.

Ancestor RelativeSource Binding

Ancestor RelativeSource Binding enables a DataTemplate to bind to a property on the control that
contains it, equivalent to FindAncestor and AncestorType, AncestorLevel bindings in WPF.

Implicit DataTemplates

This feature enables the following capabilities:

  • ContentPresenter DataTemplates can be selected based upon the content type.
  • Implicit definition of DataTemplates
  • Dynamically update the ContentPresenter DataTemplate when its content changes
  • Enable proper scoping of DataTemplates

ClickCount

Enables Multi‐click input on left and right mouse button.

private void OnMouseDownClickCount(object sender, MouseButtonEventArgs e)

 

    {

 

        // Checks the number of clicks.

 

        if (e.ClickCount == 1)

 

        {

 

            // Single Click occurred.

 

        }

 

        if (e.ClickCount == 2)

 

        {

 

            // Double Click occurred.

 

        }

 

        if (e.ClickCount >= 3)

 

        {

 

            // Triple Click occurred.

 

        }

 

    }

 

Binding on Style Setter

Binding in style setters allows bindings to be used within styles to reference other properties.

<Style x:Key=”TextBlockStyle2” TargetType=”TextBlock”>
<Setter Property=”FontFamily”
    Value=/SL5;Component/Fonts/Fonts/.zip#Segoe UI/>
<Setter Property=”FontSize” Value=”0,3,0,0”/>
    <Setter Property=”Foreground” Value=
”{Binding Source={StaticResource SysColors},Path=ControltextBrush}”/>
</Style>

Realtime Sound (low‐latency Audio)

Enables pre‐loading of an audio source for precision timing of playback. Multiple playback instances are supported through creation of SoundEffectInstance objects.

Variable Speed Playback (“Trick Play”)

This API enables development of fundamental player experiences such as fast‐forward and rewind and

variable speed playback at common speeds (1.2x, 1.4x) – a very common scenario for enterprise training content. The MediaElement.Rate  property supports the values ‐8.0, ‐4.0, 0.5, 1, 4.0, 8.0. Note : AudioPitch correction is not present in the Beta but will be added for the final release

Additional Silverlight 5 Features included

  • Hardware video decode for H.264 playback.
  • Multi‐core background JIT support for improved startup performance.
  • ComboBox type ahead with text searching.
  • Full keyboard support in full‐screen for trusted in‐browser applications, enables richer kiosk and

    media viewing applications in‐browser.

  • Default filename in SaveFileDialog – Specify a default filename when you launch the

    SaveFileDialog.

  • Unrestricted filesystem access – trusted applications can Read write to files in any directory on

    the filesystem.

  • Improved Graphics stack – The graphics stack has been re‐architected to bring over

    improvements from WP7, such as Independent Animations.

  • Performance optimizations
    • XAML Parser performance optimizations.
    • Network Latency optimizations.
    • Text layout performance improvements.
    • Hardware acceleration is enabled in windowless mode with Internet Explorer 9.

Windows Phone Toolkit Explained

Straight from Microsoft, Silverlight for Windows Phone Toolkit provides the developer community with new FREE components, functionality, and an efficient way to help shape product development. Toolkit releases include open source code, samples & docs, plus design-time support for the Windows Phone platform as well as the Silverlight browser plugin.

In this toolkit you will find user interface controls like those found throughout the Windows Phone, with components like toggle switches, page transitions, picker controls and more.


Overview

Silverlight for Windows Phone Toolkit August 2011 offers the following 21 Components:

All Aug 2011 Components

New Components

Key Fixes

  • AutoCompleteBox
  • ContextMenu
  • DatePicker
  • DateTimeConverters
  • DatePicker
  • ExpanderView
  • GestureService/GestureListener
  • HeaderedItemsControl
  • HubTile
  • ListPicker
  • LocalizedResources
  • LockablePivot
  • LongListSelector
  • MultiselectList
  • Page Transitions
  • PerformanceProgressBar
  • PhoneTextBox
  • RecurringDaysPicker (enables a day of the week selection)
  • TiltEffect
  • TimePicker
  • ToggleSwitch
  • WrapPanel

 

  • DateTimeConverters
  • HeaderedItemsControl
  • HubTile
  • LocalizedResources
  • LockablePivot
  • MultiselectList
  • PhoneTextBox
  • Smooth new LongListSelector designed for Windows Phone 7.1 OS
  • Improved Transitions performance
  • Improved ContextMenu performance
  • ListPicker supports multiselect
  • Various bug fixes
  • AutoCompleteBox focuses correctly after hitting return in the control.
  • ListPicker fixed to correctly bind BorderBrush.
  • ListPicker no longer opens on a “swipe” gesture.
  • ListPicker allows for retrieval of ActualFullModeItemTemplate.
  • LongListSelector smoothed for improved UI performance.
  • The out transition from a page immediately begins, yielding improved perception of performance. Transition values have been slightly tweaked.
  • Hitting the back button during a transition no longer causes a crash.

You can download the new release straight from the CodePlex site at http://silverlight.codeplex.com/ – it requires the latest ‘Mango’ developer tools as well.

The release is also available on NuGet as the SilverlightToolkitWP package.

New features in Windows Phone Toolkit  August 2011 release

Here are some of the new things you will find in this release:

LongListSelector has been rebuilt and redesigned to take advantage of the new smooth scrolling and off-thread touch input support in ‘Mango’. This is a buttery-smooth control for showing lists, including grouping and jump list support.

MultiselectList control enables multiple selection for easily working with lists of data, similar to the Mail app’s capability.

LockablePivot adds a special mode to the Pivot control where only the current item is shown (often used with multiple selection).

ExpanderView is a primitive items control that can be used for expanding and collapsing items (like the threaded views in the Mail app).

HubTile lets you add beautiful, informative, animated tiles to your application, similar to the new People groups in ‘Mango’.

ContextMenu control has been reworked: performance improvements and visual consistency fixes.

ListPicker now supports multiple selection.

RecurringDaysPicker lets your users select a day of the week.

Date & Time Converters localized to 22 languages. The converters let developers easily display date and time in the user interface in one of the many styles found throughout the phone’s UI, from a short date like ‘7/19’ to relative times like ‘about a month ago’.

Page Transitions have improved performance for a more responsive feel.

PhoneTextBox is an early look at an enhanced text box with action icon support, watermarking, etc.

All error messages and interface elements have been localized to all of the supported languages, making for a great experience for users around the world.

Other great components

If you’re new to the Silverlight for Windows Phone Toolkit, you’re in for a treat as an app developer: the simple developer library also contains these great components designed specifically for the Windows Phone:

AutoCompleteBox is a text box control that allows for simple auto-completion based on a filter.

DatePicker lets a user select a date, similar to that found in the Alarms app on the Windows Phone.

PerformanceProgressBar can be used to show indeterminate progress inside an app (though you should also consider the new ProgressIndicator support in ‘Mango’, too).

TiltEffect attached property that gives buttons, list items, and other components that nice ‘tilt’ touch experience.

TimePicker for choosing a time.

WrapPanel is a non-virtualized wrapping panel often used for displaying photo thumbnails.

Helper code for Gestures (touch input manipulations).

Check out the sample app

One of the best ways to learn about the controls is to use the sample app on your Windows Phone. We haven’t published it to the marketplace yet, so in the meantime, just deploy this .XAP to your developer-unlocked Windows Phone (or the Windows Phone Emulator). It should work with the latest Windows Phone ‘Mango’ developer tools.

You can find the sample XAP here.

The app includes a nice list of the controls, touch one to go into a sub-page. The full open source code to the sample is on the CodePlex site at http://silverlight.codeplex.com/

Pros and Cons of application library caching and GPU acceleration in Silverlight

Reduce XAP size by using application library caching

Advantages

This reduces the XAP size by allowing those libraries configured with a dllname .extmap.xml file to be placed in individual zip files. These zip files will be requested as part of the initial XAP download.

The advantage comes in two scenarios. First if you update your code and rebuild the XAP most of the time the only thing that changes is the XAP, zip files remain unchanged. Hence when a client revisits your app and needs to download the latest version it may well be that only the XAP gets fetched, the zips being the same get served out of the browser cache (probably after a "304 Not Modified" response from the server).

The other scenario is where you have multiple SL applications on your site. They will share the same zips and therefore the total download for multiple apps is much reduced.

Disadvantages

For a one off application the first client visit will be a download at least as expensive if not more expensive than had the all the libraries been kept in the XAP. In some uses (high number of unique visitors of a site with a single app) it may be more desirable to keep the single XAP, especially if the XAP itself doesn’t change that often.

Where there are multiple XAPs sharing the same set of library zips there is a danger of "DLL Hell". Potentially someone can update a XAP which uses newer versions of libraries that the other XAPS have not been tested with and inadvertently break all the other XAPS. There are good practices that can eliminate this problem but it takes a little more effort than flicking on the Checkbox.

Conclusion

In light particularly of the second disadvantage I think it was a sensible choice not to default this feature on.

Use GPU Acceleration

I’m not going to go into the advantages/disadvantages of this. Just answer why its off by default.

You don’t get any advantage by just turning it on, you need to enable which elements in the XAML will get to use it via the CacheMode property. In addition depending on what you are doing this may still not bring you any advantages.

Just turning it on will consume extra resources such as video memory, you wouldn’t want that to happen unless you’ve specfically gone ahead used CacheMode at least somewhere in your app and hopefully where it would make a real difference. Also it is possible to get it wrong and make things worse.

Silverlight/WPF Interview Questions

Here is the list of some of the Interview questions for Silverlight technology.

Entry Level

  • Strong .NET 2.0 Background & willing to learn!
  • Explain dependency properties?
  • What’s a style?
  • What’s a template?
  • Binding
  • Differences between base classes: Visual, UIElement, FrameworkElement, Control
  • Visual vs Logical tree?
  • Property Change Notification (INotifyPropertyChange and ObservableCollection)
  • ResourceDictionary 
  • UserControls
  • difference between bubble and tunnel routing strategies – added by Carlo
  • XAML

Mid-level

  • Routed Events & Commands
  • Converters – Added by Artur Carvalho
  • Explain WPF’s 2-pass layout engine?
  • How to implement a panel?
  • Interoperability (WPF/WinForms)
  • Blend/Cider
  • animations and storyboarding
  • ClickOnce Deployment
  • Skinning/Themeing
  • Custom Controls
  • How can worker threads update the UI?
  • DataTemplate vs HierarchicalDataTemplate
  • ItemsControl vs ItemsPresenter vs ContentControl vs ContentPresenter
  • Different types of Triggers
  • How to do Animations through StoryBoards

Advanced

  • Example of attached behavior?
  • What is PRISM,CAL & CAG?
  • How can worker threads update the UI?
  • WPF 3D – Added by a7an
  • Differences between Silverlight 2 and WPF
  • MVVM/MVP – Added by a7an
  • WPF Performance tuning
  • Pixel Shaders
  • Purpose of Freezables

Other general questions :

  1. How do asynchronous calls work in Silverlight and what considerations must you take into account (if any) when working with them?
  2. What does it mean if a control is virtualized?
  3. What tactics can be used to reduce the initial XAP download? subsequent downloads?
  4. What is isolated storage? How much of it do apps get? Can they get more?
  5. What features are only available when using Silverlight Out of Browser?
  6. Explain how the Print functionality works in Silverlight 4? and any issues you can think regarding it?

How to profile a silverlight application

Try profiling with the Visual Studio profiler in order to get a good measure of your managed code and the native code executing within Silverlight. The profiler will help point you to where you’re spending the most of your time (what the hot path’s are) and whether or not your spending it in framework (SL) code or your own code.

The basics of profiling are:

  1. Open a Visual Studio Command Prompt (as admin), ‘cd’ to the directory where your DLL and PDB files are (typically your "Debug" folder)
  2. VSPerfClrEnv /sampleon
  3. VSPerfCmd -start:sample -output:somefile.vsp VSPerfCmd -globalon VSPerfCmd -launch:"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -args:""
  4. VSPerfCmd -shutdown
  5. VSPerfClrEnv /off

You can find detailed instructions on using the profiler on my blog:http://www.nachmore.com/2010/profiling-silverlight-4-with-visual-studio-2010/

If you find that you are spending time within Silverlight, track down the code path to see where your code is triggering the expensive calls, so that you can then investigate specific solutions based on the cause of the slow down.

Update :

Performance Wizard for Silverlight – taken from VS2010 SP1 KB.

Visual Studio 2010 SP1 enables you to tune the Silverlight application performance by profiling the code. A traditional code profiler cannot tune the rendering performance for Silverlight applications. Many higher-level profilers are added to Visual Studio 2010 SP1 so that you can better determine which parts of the application consume time.

For more details refer to article Profiling Silverlight Applications After Installing Visual Studio 2010 Service Pack ?

Optimize Silverlight applications for smaller size

When putting content on the web, it’s important to get that content to the user as quickly as possible. In general, reducing the amount of data users need to download is a big step in the right direction. As Silverlight applications are usually linked with rich user interface these includes lot of images and other resources.

Performance can become a real issue when the user has to download a total of 5MB or more just to run your application.

In this article I will talk about a few tricks to reduce the size of your silverlight application and thereby reduce the time it takes the application to start on the client.

Remove Extra assembly

By default Visual Studio will add quite a lot assemblies to your Silverlight applications. You application might not require all these assemblies.

The first step in optimizing your silverlight application for size is to remove excess assemblies from the application. A good way to achieve the desirect effect is to remove all assembly references, except for the System reference.

After that you will need to recompile and check for any compile errors that are caused by missing references.A quick way to get rid of these unused usings is to right click on them in Visual Studio 2008/2010 and choose Organize usings / Remove unused usings.

Make sure that you’re including references to assemblies that you actually need and nothing more. Sometimes you’ll need a reference to an assembly but you don’t want it set to "Copy Local", as that adds to the XAP. Visual Studio 2010 is usually good about automatically setting "Copy Local" when appropriate. For example, System.Windows.Controls is not part of the runtime (it’s a part of the SDK). Visual Studio knows this and when you add System.Windows.Controls to the project it automatically sets "Copy Local" to true. But when in doubt about an assembly reference, try setting "Copy Local" to false and see what happens. If your application builds and runs fine, then you’re good.

Reducing Size of final XAP package

The silverlight XAP package format is actually a ZIP container with a special manifest inside that is recognized by the silverlight runtime. The package that Visual Studio will create however is not compressed as efficient as it could be. However Visual Studio 201o has improved quite a bit in this area.

Another tip to get more bang for the megabyte is to unpack the XAP package and repack it using Winzip, Winrar or any other zip application.

Reduce XAP size by using application library caching

(not available for out-of-browser applications). Check this option in Visual Studio 2010 and when your project is built there will be extra files automatically generated. So you’ll have to upload your XAP file and any auto-generated ZIP files to the same directory. The generated ZIP files contain any external assemblies that your XAP require. Behind the scenes this relationship is automatically maintained with the AppManifest. This feature is pretty cool and very easy to use. You should note, however, that the whole idea behind it is caching. And so it speeds up requests from repeat visitors, but in practice it doesn’t do a thing to speed up the experience for a new visitor. Read more about this featurefrom Microsoft.

Other Tools to Automate everything related to optimization of Silverlight application for You

  1. XAPs Minifier Visual Studio 2010 plug-in

sometimes when working with a Silverlight app you might have an assembly reference that has been set to "Copy Local" when it doesn’t need to be. This is easy to overlook when working with a large Silverlight app composed of multiple projects. The XAPs Minifier is intended to remove any redundant or unnecessary assemblies.

2. ComponentOne XAPOptimizer

The XAPOptimizer is not free, but it does take optimization to another level. It goes beyond assembly removal. It’ll dig into every assembly through reflection and actually detect unnecessary classes, resources and entire sections of XAML. It’s also configurable in case it makes a mistake you can actually specify what to remove and save your settings. On top of this, it’ll optionally obfuscate your application, making it hard to reverse-engineer.

Conclusion

Often the most significant optimizations involve removing unnecessary or unused components or assemblies.

Silverlight MVVM light toolkit best practices

Basic Usage of MVVM-Light

  1. Intialize the DispatcherHelper in the App.cs file’s Application_Startup function
  2. Create ViewModels from the BaseClass
  3. Always Create a ViewModelLocator class, which contains all your view models and is Linked in your application Resources
  4. Use RelayCommands to expose Functions to your view
  5. Learn when to use the DispatchHelper.

Clean-Up Ideas:

    1. When appropriate, add to your ViewModel to clear your DomainContext’s EntitySet on Cleanup()?
    2. Call your ViewModelLocator’s CleanupSomeVM() function to clear viewmodels when they are no longer actively needed in the application.

I would love to hear from others about when/how you use CleanUp functions. As my application grows, I do feel the need to add some cleanup functions to better manage client memory usage.

For Blendability:

  1. Abstract the Service / Query Implementations to an Interface.
  2. Create 2 classes for each Service Implementation classes (1 for Design, 1 for Production)
  3. Within your each ViewModel, implement its own Service Class (use IsInDesignMode) to create Blendable Service implementations as necessary.
  4. Use a Static variable to hold your DomainContext within the Service Implmentation Class.
  5. Add DispatcherHelper.Initialize() in constructor of ViewModels, but only when in Design Mode. Blend does not load App when loading a page, and this works around that.

For Added Business Logic:

  1. Add Business Logic in the Model first, then in the ViewModel.
  2. Use the Model’s partial methods to add logic for appropriate change / update events.
  3. Add Read-Only properties (only getter) to provide summary and calculated values on your model.

For Views:

  1. Always Bind the root to the Locator Object.
  2. Try to keep code-behind logic to layout or custom UI logic only. Avoid referencing your ViewModel.

For Collections:

  1. Use CollectionViewSource for collections in your ViewModels, with a source of the DomainContext’s EntitySet
  2. Apply all Filtering, Sorting, and Grouping Logic to the CollectionViewSource in your ViewModel.
  3. After ServiceCalls, Call .View.Refresh() on your CollectionViewSource objects as necessary to update the UI.

For ViewModel coordination (Controller Logic)

  1. Use Messages sparingly, too much complexity can be difficult to manage.
  2. Use the NotificationMessage and PropertyChangedMessage classes to Send/Receive with.

For RIA DomainServices:

  1. Implement any logging in the persist changes function, not the update/insert/delete logic.
  2. During Insert,Update,Delete functions, if you need to reference another Entity via Navigation Property, either check the EntityStatus first, or load the entity from another Context, to prevent EntityStatus conflicts.

For Debugging / Testing:

  1. Check the Output Window for Binding Errors and Fix them. Binding Errors fail silently to the user, but degrade application performance and expected behavior.
  2. Create Unit Tests in Silverlight to verify any added Model / Business Logic
  3. Create Unit Test project to test server-side logic and functions

For Entity Framework:

  1. Keep 1-to-1 Match of EntitiesContext to Domain Service. Trying to split this another way causes issues.
  2. Do NOT use the [Composition] attribute unless you fully intend to spend a lot of time carefully building your Insert, Update, and Delete logic.
  3. Use a separate service to serve custom types back to your RIA Client. Do not add them to your DomainService for your EntityFramework Object
  4. Perform Server-side update/integration logic (such as updating other systems) in the PersistChangeSet function, not in the Insert, Update, Delete functions. This will prevent you from accidentally pulling in an entity via Navigation Properties, which will leave your detached version non-updated.
  5. Create an additional Context to find current values during update/integration logic.

What is Dependency Property

A dependency property is a property on one object whose value depends on some other object. So, for instance.

  • The value of the FontFamily property of a TextBox can (and usually does) depend on the FontFamily property of its container. If you change the property on the container, the value on the TextBox changes.
  • The value of the Text property of a TextBox can depend on a bound data source. When the value of the bound property changes, the value of the Text property changes.
  • The value of the Opacity property of a Label can depend on an animation storyboard, in the common scenario where you’ve set up a UI element to fade in or fade out in response to some event.
  • The value of all kinds of properties on any UI element can depend on the style that you’ve applied to them.

The central concept behind dependency is that the thing that’s depending should get the property value from the thing it’s depending on. This is why a dependency property is implemented as a CLR property whose getter calls a method.

When the TextBox, or the thing that’s rendering it, needs to know what its FontFamily is, the FontFamily getter calls the GetValue method. That method finds the value from the container, or animation, or binding, or whatever.

There’s a lot of complexity in that method. If the value’s inherited, for instance, it works in a way that’s pretty analogous to how WPF finds styles in a resource dictionary: it looks in a local dictionary to find the value, and if there’s no entry it looks in its parent’s dictionary, and so on all the way up until it finds a value or reaches the top of the hierarchy, in which case it uses a default value.

If you look at the implementation of dependency properties, that’s what you’ll find. A dependency object has a dictionary that may or may not contain an entry for a given property. The GetValue method gets values from that dictionary (which is how objects with dependency properties can have local values that override what they’re inheriting from), and if it doesn’t find the value, it uses the metainformation about the property to figure out where it should look.

Since that metainformation is the same for every object in the class (i.e., TextBox.Text works the same for every TextBox), the dictionary it’s stored in is a static property of the class.

So when you see code like this:

static Button()

{

   // Register the property

   Button.IsDefaultProperty = 

     DependencyProperty.Register("IsDefault",

     typeof(bool), typeof(Button),

     new FrameworkPropertyMetadata(false,

        new PropertyChangedCallback(OnIsDefaultChanged)));

}

 

what’s happening is that the metainformation that defines the IsDefault property on all Button objects is being added to that dictionary. And when you see this:

public bool IsDefault

{

  get { return (bool)GetValue(Button.IsDefaultProperty); }

  set { SetValue(Button.IsDefaultProperty, value); }

}

what you’re seeing is the getter method that looks up the property’s value (from the local dictionary, the parent object, or whatever) based on that metainformation.

Remember how I said that the first place the getter looks to find a property’s value is in the object’s local dictionary? The SetValue method in the setter is how that entry gets added to the dictionary (if it’s ever called, which it will only be if you’re overriding the dependency by explicitly setting the property, i.e. saying "I want this TextBox to display text in Consolas irrespective of what the other controls in the window are using.").

A hugely significant benefit that we get from this kind of apparently-complex system is that dependency properties on objects only consume memory if they’re set. If I create 10,000 TextBox controls and add them to a Window, not one of them actually contains a reference to a FontFamily object. That’s 10,000 object references that I’m not allocating memory for, and that the garbage collector isn’t checking. In fact, if a TextBox has 100 dependency properties (and it does, just about), whenever you create a TextBox, that’s 100 backing fields you aren’t allocating memory for. Dependency properties only consume memory if you explicitly set them. Since the vast majority of properties on UI objects never get explictly set, these are fantastic savings.

Silverlight Auto logout user after 10 minutes of inactivity

 

Many projects have requirement to logout a user after some time of Inactivity user has not performed any activity for past 10 minutes we need to auto logout the user.

Solution

Use

DispatcherTimer SMNetworkTimer = new DispatcherTimer();

Sample implementation

App.xaml.cs

 

Declare a timer in app file as as follows
public static System.Windows.Threading.DispatcherTimer _Logouttimer = new System.Windows.Threading.DispatcherTimer();
private static DateTime App.timer=DateTime.Now; // this variable helps in finding the user interaction time in master page

public Timer
(
set{};
get{};
)

 

public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;
            _Logouttimer.Tick += new EventHandler(_Logouttimer_Tick);
            __Logouttimer.Interval = TimeSpan.FromSeconds(60);
            InitializeComponent();
        }


this timer will check for every 60 seconds for timeout logout

void __Logouttimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if ((DateTime.Now - App.Timer) > new TimeSpan.Minutes(20))
                {
                    
App app = (App)Application.Current;


            
            
                // Remove the displayed page
                app.root.Children.Clear();

                // Show the next page
                app.root.Children.Add(new LoginPage); //load the loginpage or the specific page you want to naviagte the user after timeout
            }
                
            }
            catch (Exception ex)
            {

            }
        }
           



Keep this event in master page to get the users last interaction time with the application

void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                App.Timer = DateTime.Now;
            }
            catch (Exception ex)
            {
            }
        }