94 answers Pizza toppings Playstation 94 Poker 94 Reptiles 94 Rodents 94 Skiing 94
August, 2011 | Silverlight tips
Friday , 31 July 2015
Home » 2011 » August

Monthly Archives: August 2011

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

Reduce XAP size by using application library caching


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.


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.


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


  • 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


  • 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.


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 = 


     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.



DispatcherTimer SMNetworkTimer = new DispatcherTimer();

Sample implementation



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


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);

this timer will check for every 60 seconds for timeout logout

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

                // Remove the displayed page

                // 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)
                App.Timer = DateTime.Now;
            catch (Exception ex)