Pixytech

Category: Silverlight

  • Silverlight Hot Keys

    Hot keys like available in windows based application where you specify using caption like &print is not available in Silverlight.There are two ways to capture keydown or key up when silverlight is running inside web browser.The first way is the HTML Bridge to capture HTML event KeyUp on HTML document.This is fired when focus is not captured by silverlight application.Another way is to handle event in silverlight itself,since silverlight events are routed events i.e you need to capture hot / shortcut keys on root element i.e RootVisual.

    * Check for update in the bottom  of this article for simplified version of hot key library..

    There is limitation on keys like F1,F3 etc. which are handled by browser before they reach to the contents of web browser.These keys however can be used when running out of browser as HTML Bridge will be disabled while running out of browser.

    The code presented here in this article can be used in two ways.

    • Global Hot keys
    • Page Specific hot keys.

    Global Hot keys will be available throught the application life cycle where as page hot keys will be only available when specific page is active.

    To use global hot keys use below mentioned code.Where you need to specify ModifierKeys,Keys and EventHandler to the callback function.

    App.GlobalHotKeyHandler.RegisterShortcut(System.Windows.Input.ModifierKeys.Control,
                   System.Windows.Input.Key.D9, new KeyDownHandler(LogOff));
    
    void LogOff(object sender, System.EventArgs e)
            {
                LoginRegistrationWindow loginWindow = new LoginRegistrationWindow();
                loginWindow.Show();
            }

    Singleton Pattern is used to provide single instance of HotKeyHandler class throughout application.Normally GlobalHotKeyHandler code will be writen under either App.xaml.cs or MainPage.xaml.cs in your Silverlight business application.

    In case of shortcut keys for specific page use below mentioned code inside specific silverlight page.

    //Create module level variable in page
     HotKeyHandler hkeyHandler = new HotKeyHandler();
    
    //On Page_Loaded use Register and RegisterShortcut functions
    hkeyHandler.Register();
    hkeyHandler.RegisterShortcut(System.Windows.Input.ModifierKeys.None,
                      System.Windows.Input.Key.F1, new KeyDownHandler(LogOff));
    
    //On Page__Unloaded call Unregister
    hkeyHandler.Unregister();

    Note that the above code while running in out of browser silverlight application will behave properly.In case of web browser mode you need to avoid using shortcut keys assigned to browser.

    Here is the full code to add HotKey feature to your application.Add file HotKeyHandler.cs to your silverlight business application and paste the code for here…

    public partial class App : Application
    {
        public static HotKeyHandler GlobalHotKeyHandler { get; private set; }
        internal static Dictionary< Key,int> KeyCodeLookUp = new Dictionary();
        static App()
        {
            //start thread here to process this from backend
    
            GlobalHotKeyHandler = new HotKeyHandler();
    
            //  KeyCodeLookUp.Add(Key.D1,49);
            //Digits
            for (int i = (int)Key.D0; i <= (int)Key.D9;i++ )
                KeyCodeLookUp.Add((Key)i, i+28);
            //Chars
            for (int i = (int)Key.A; i <= (int)Key.Z; i++)
                KeyCodeLookUp.Add((Key)i, i + 35);
    
            //functional Key
            for (int i = (int)Key.F1; i <= (int)Key.F12; i++)             KeyCodeLookUp.Add((Key)i, i + 65);         KeyCodeLookUp.Add(Key.Escape, 1);     } } public delegate void KeyUpHandler(object sender,EventArgs e); public sealed class HotKeyHandler {     private List<Shortcut> shortcuts = new List<Shortcut>();
        public HotKeyHandler() {  }
        private bool isRegistered = false;
        public void Register()
        {
            if (this.isRegistered == false)
            {
                try
                {
                    App.Current.RootVisual.KeyUp += new System.Windows.Input.KeyEventHandler(RootVisual_KeyUp);
                    HtmlDocument document = HtmlPage.Document;
                    EventHandler<HtmlEventArgs> KeyDownHandler;
                    KeyDownHandler = new EventHandler<HtmlEventArgs>(OnBodyKeyUp);
                    bool b = document.AttachEvent("onkeyup", KeyDownHandler);
                }
                catch (Exception ex) { }
                finally
                {
                    this.isRegistered = true;
                }
            }
        }
    
        public void Unregister()
        {
            if (this.isRegistered)
            {
                try
                {
                    App.Current.RootVisual.KeyUp -= RootVisual_KeyUp;
                    HtmlDocument document = HtmlPage.Document;
                    EventHandler<HtmlEventArgs> KeyDownHandler;
                    KeyDownHandler = new EventHandler<HtmlEventArgs>(OnBodyKeyUp);
                    document.DetachEvent("onkeyup", KeyDownHandler);
                }
                catch (Exception ex) { }
                finally
                {
                    this.isRegistered = false;
                }
            }
        }
    
        private void RaiseOnKeyUp(ModifierKeys modKey,int keyCode,System.Windows.Input.KeyEventArgs ke,HtmlEventArgs he)
        {
            var handlers = (from h in this.shortcuts
                            where h.ModKeys == modKey &&
                            (ke!= null? h.Key == ke.Key : h.KeyCode==he.KeyCode)
                            select h);
            foreach (Shortcut s in handlers)
            {
                s.Handler(this, null);
            }
        }
    
        public void RegisterShortcut(ModifierKeys ModKeys, Key key, KeyUpHandler handler)
        {
            var shortAlready = from s in shortcuts
                                where s.ModKeys == ModKeys &&
                                s.Key == key && s.Handler.Method.Equals(handler.Method)
                                select s;
            if (shortAlready.Count() == 0)
            {
                Shortcut shortcut = new Shortcut { ModKeys = ModKeys, Key = key, Handler = handler };
                shortcuts.Add(shortcut);
            }
        }
    
        private void OnBodyKeyUp(object sender, HtmlEventArgs e)
        {
            RaiseOnKeyUp(GetModKey(e), e.KeyCode,null,e);
    
        }
    
        private ModifierKeys GetModKey(HtmlEventArgs e)
        {
            ModifierKeys modKey = ModifierKeys.None;
            if (e.CtrlKey) modKey = modKey | ModifierKeys.Control;
            if (e.AltKey) modKey = modKey | ModifierKeys.Alt;
            if (e.ShiftKey) modKey = modKey | ModifierKeys.Shift;
    
            return modKey;
        }
    
        void RootVisual_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
    
            RaiseOnKeyUp(Keyboard.Modifiers,e.PlatformKeyCode,e,null);
        }
    
        private class Shortcut
        {
            public KeyUpHandler Handler { get; set; }
            public ModifierKeys ModKeys { get; set; }
            Key key;
            public Key Key
            {
                get { return key; }
                set {key=value;
                    KeyCode = App.KeyCodeLookUp[value]; }
            }
            public int KeyCode { get; set; }
        }
    }

    Note that the code maintains the relationship beetwen HTML KeyCode and Silverlight Keys Enum.This is not required when you run in out of browser mode.The above code can be optimized by checking the out of browser mode at run time.

    You may even develop system wide hot keys which will work even if you silverlight application is not in focus. This can be achived by using the system32 api’s to register the system wide hooks.The logic needs to be developed in some COM based component which needs to be deployed on client machine and can be communicated via COM bridge available in Silverlight 4. No doubt this will add very nice feature but the cost is more.. like it can be used only on windows system, it needs to be run as out of browser. That all realy depends on your requirements.

    Code is available at : link /rajnish/uploads/code/HotKeyHandler.cs.txt

    include the cs file in your project and update appropriate name space.

    in you silverlight page use following code to register shortcut and define call back function

     public partial class MainPage : UserControl
        {
            HotKeyHandler hkeyHandler = new HotKeyHandler();
    
            public void RegisterShortcuts()
            {
                hkeyHandler.Register();
    	    hkeyHandler.RegisterShortcut(System.Windows.Input.ModifierKeys.Control,
                   System.Windows.Input.Key.D9, new KeyUpHandler(Logout));
            }
    
            void Logout(object sender, EventArgsKeyUp e)
            {
                App.RootActivity.ActiveContent = "Logging out...";
                App.RootActivity.IsActive = true;
    
                WebContext.Current.Authentication.Logout(false).Completed += new EventHandler(Logout_Completed);
            }
        }

    off-course you need to call RegisterShortcuts function on page load.

    /***************************************************************************************/

    Update 1.0 : Nov 2010

    Another simplified version of Hot Key library which can be used in XAML (without c# code) with just below mentioned two line. Hot key is exposed as attachable property.

    xmlns:hkey="clr-namespace:Silverlight.Controls.HotKeys;assembly=Silverlight.Controls.HotKeys"
    <Button Click="BtnAClick"   Grid.Column="0" Grid.Row="0" Height="25" Content="Button A"  >
     <hkey:HotKeyService.HotKey >
      <hkey:HotKey Shortcut="A" Click="BtnAClick" />
     </hkey:HotKeyService.HotKey>
    </Button>

    or with XAML code

    xmlns:hkey="clr-namespace:Silverlight.Controls.HotKeys;assembly=Silverlight.Controls.HotKeys"
    <Button Click="BtnAClick"   Grid.Column="0" Grid.Row="0" Height="25" Content="Button A" hkey:HotKeyService.HotKey="A" />

    Source code (Vs2010,Sl 4.0) is available here. This library can be used to provide office xp like shortcut navigation in your silverlight application.

    /***************************************************************************************/

  • Silverlight Page Flip

    Page flip is a very impressive features in displaying your documents, images, media, etc.. The technique behind page flip is pretty complicated. Below is the page flip live application & source code link.

    You can download the source code here (VS 2010).

    I could not spare much time to write implementation notes , however, Rick Barraza has a very good articles describing all the mystery behind this technique in his post. The code is based on his article and can be further extended to create silverlight generic control which could even flip silverlight pages, documents, images etc.

    Another interested implementation of page turn effect is available on Microsoft by Jeff & Mitsu’s.

    Another page flip (book) control is available here

  • WPF Introduction

    The Windows Presentation Foundation (or WPF) is a graphical subsystem for rendering user interfaces in Windows-based applications. WPF, was initially released as part of .NET Framework 3.0. Designed to remove dependencies on the aging GDI subsystem, WPF is built on DirectX, which provides hardware acceleration and enables modern UI features like transparency, gradients and transforms. WPF provides a consistent programming model for building applications and provides a clear separation between the user interface and the business logic.

    WPF also offers a new markup language, known as XAML which is an alternative means for defining UI elements and relationships with other UI elements. A WPF application can be deployed on the desktop or hosted in a web browser. It also enables rich control, design, and development of the visual aspects of Windows programs. It aims to unify a number of application services: user interface, 2D and 3D drawing, fixed and adaptive documents, advanced typography, vector graphics, raster graphics, animation, data binding, audio and video.

    Microsoft Silverlight is a web-based subset of WPF that enables Flash-like web and mobile applications with the same programming model as .NET applications. 3D features are not supported, but XPS and vector-based drawing are included.

    It is compatible with multiple web browser products used on Microsoft Windows, Linux (using Novell Moonlight), Mac OS X operating systems & Mobile devices.

    WPF is designed to allow you to create dynamic, data driven presentation systems. Every part of the system is designed to create objects through property sets that drive behavior. Data binding is a fundamental part of the system, and is integrated at every layer.

    Traditional applications create a display and then bind to some data. In WPF, everything about the control, every aspect of the display, is generated by some type of data binding. The text found inside a button is displayed by creating a composed control inside of the button and binding its display to the button’s content property.

    Display technology evolution on windows …

    • User32 : Standard controls like buttons, textbox etc. This provides the windows look and feel for buttons and textboxes and other UI elements. User32 lacked drawing capabilities. Window forms are using User32 to render several controls including .net 2.0,vb, vc++ etc.
    • GDI (Graphics device interface) : Abstract graphics of drawing from hardware’s like printers ,monitors etc. Microsoft introduced GDI to provide drawing capabilities. GDI not only provided drawing capabilities but also provided a high level of abstraction on the hardware display. In other words it encapsulates all complexities of hardware in the GDI API. Several GDI API are available in windows platform to perform custom drawing. Hooks like subclassing cab be used to override default drawing of win32 controls on windows Or developers can create custom controls and use GDI API’s to render on screen.
    • GDI+ : JPG, PNG Image support, gradient shading, Anti Alising. GDI+ was introduced which basically extends GDI and provides extra functionalities like jpg and PNG support, gradient shading and anti-aliasing. The biggest issue with GDI API was it did not use hardware acceleration and did not have animation and 3D support. Object oriented approach to flat GDI+ API’s are available in .net which internally based on GDI+.
    • DirectX : Targeted for game programmers, Hardware  Acceleration (is a process in which we use hardware to perform some functions rather than performing those functions using the software which is running in the CPU.),support for animation,3D support, full colour graphics, Capture and play streaming media. One of the biggest issues with GDI and its extension GDI+ was hardware acceleration and animation support. This came as a biggest disadvantage for game developers. To answer and server game developers Microsoft developed DirectX. DirectX exploited hardware acceleration, had support for 3D, full color graphics , media streaming facility and lot more.
    • WPF : Based on direct (internally), support for primitive objects like text, shapes, controls etc, declarative UI using XAML, support for audio , video formats, define styles and templates for UI elements.  DirectX had this excellent feature of using hardware acceleration. Microsoft wanted to develop UI elements like textboxes,button,grids etc using the DirectX technology by which they can exploit the hardware acceleration feature. As WPF stands on the top of directX you can not only build simple UI elements but also go one step further and develop special UI elements like Grid, FlowDocument, and Ellipse. Oh yes you can go one more step further and build animations.WPF is not meant for game development. DirectX still will lead in that scenario. In case you are looking for light animation ( not game programming ) WPF will be a choice. You can also express WPF using XML which is also called as XAML.In other words WPF is a wrapper which is built over DirectX.

     The figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore.

     User32 :  It decides which goes where on the screen. User32 is used to determine what program gets what real estate. As a result, it’s still involved in WPF, but it plays no part in rendering common controls.

    • DirectX : WPF uses directX internally. DirectX talks with drivers and renders the content.
    • Milcore :  Mil stands for media integration library. This section is a unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API. The composition engine in milcore is extremely performance sensitive, and required giving up many advantages of the CLR to gain performance. Milcore.dll is the core of the WPF rendering system and the foundation of the Media Integration Layer (MIL). Its composition engine translates visual elements into the triangle and textures that Direct3D expects. Though milcore.dll is considered a part of WPF, it’s also an essential system component for Windows Vista. The Desktop Window Manager (DWM) in Windows Vista uses milcore.dll to render the desktop.
    • Presentation core :– This is a low level API exposed by WPF providing features for 2D , 3D , geometry etc.,  includes base types, such as UIElement and Visual, from which all shapes and controls derive.
    • Presentation framework :  This section has high level features like application controls , layouts . Content etc which helps you to build up your application. The vast majority of Windows Presentation Foundation developers will work exclusively with this layer.
    • *Red colour box indicate WPF layer.

     

    Silverlight : WPF on web – platform independence

    The Silverlight runtime plug-in is essentially a ‘micro’ version of the .NET CLR. This runtime is hosted�
    within the client side browser. This runtime will host your Silverlight assemblies, as well as the Silverlight base class libraries. This runtime will JIT CIL code, handle threads, exceptions and garbage collection. This is a good thing, as your current .NET programming skills apply directly to Silverlight development.

    In addition to the ‘micro-CLR’, Silverlight supports a subset of the .NET base class libraries. When a�
    requesting browser loads a Silverlight page, any required assemblies are downloaded to the user’s machine, if they are currently not installed. Like any other .NET program, you can build your own code custom libraries for use within your Silverlight programs.

    A Silverlight application is deployed from a web server as an ‘XAP’ (zip file) package. The XAP file contains the compiled Silverlight assembly, any embedded resources, and any referenced assemblies. The Silverlight runtime downloads the XAP package and executes its contents in web browser.

    Once loaded by the plug-in, the SL application is able to make remote calls (to the web server or any arbitrary endpoint) using WCF technologies. The entire web page does *not* need to be refreshed when the SL web plug in changes state. This can greatly enhance the end user experience.

    Silverlight architecture is altogether different that WPF, however it tries to implement the features available in WPF. From developer prospective there is no major difference in WPF or Silverlight even though Silverlight CLR is not same as WPF CLR.

  • Prism 2.0

    Composite Application Guidance, affectionately known as Prism, version 2 was released in oct 2009.  Prism provides guidance and code that can help you build modular applications that can adapt to constant changing requirements. Prism guidance is a set of tools, samples, references and written guidance to help you more easily build modular applications.  Generally the “modular” application will feature several screens, flexible user interaction and role-based behavior.  Composite applications using these patterns are meant to be loosely coupled and contain independently evolving pieces that can work together. They are “built to last” and “built for change.” This means that the application’s expected lifetime is measured in years and that it will change in response to new, unforeseen requirements. This application may start small and over time evolve into a composite client—composite applications use loosely coupled, independently evolvable pieces that work together in the overall application. Applications that do not demand these features and characteristics may not benefit from the Composite Application Guidance.

     What’s new Prism 2.0?

    • Composite Support for Silverlight: Provides guidance on modularity, UI composition, commanding, and event aggregator in Silverlight. The Reference Implementation demonstrates how to use the Prism library with Silverlight.
    • Multi-targeting: Ability to share code between Silverlight and WPF. Provide guidance in the form of patterns, documentation, and tooling on how to share code between Silverlight and WPF. The tooling has its own msi that you can download.
    • Improved UI Composition: Added View Discovery to UI Composition. View Discovery: when a region is created, the region looks for all the ViewTypes associated with the region and automatically instantiates and loads the corresponding views. This is a simple approach to create new views.
    • Hands-on-Lab for Silverlight: Provide a Hands-on-Lab for Silverlight that walks you through how to create your first application using Prism.
    • New UI: Upgraded the UI with this release which includes new Silverlight and WPF animations.

     The Prism release adapts Model-View-ViewModel (MVVM) model (refers to this as the presentation model to match what some other pattern documentation in the greater technology world uses) in the reference implementation of the Stock Trader application.

    Prism 2 is an evolution from a July 2008 release (Prism 1) that was primarily for WPF applications.  The version v2 release brings updates and those concepts to Silverlight, including an implementation of commanding in Silverlight as well as demonstration of the use of input validation using these concepts.

    Prism consists of:

    • Reusable library components, for both WPF and Silverlight.
    • All source code, Unit tests, Automated acceptance tests.
    • Hands on labs (26) that guide you through all aspects of creating a composite application.
    • Quickstarts (9) that illustrate all components of prism.
    • A completely functional reference implementation that shows you how to build a composite application.
    • A lot of documentation and guidance:
      • How to create composite applications
      • How to use the Prism libraries
      • How to use Dependency Injection in your application (Unity)
      • How to create applications that target both WPF and Sliverlight.
      • Which design patterns were used to create prism
      • How to use separated presentation patterns (like Model – View – Viewmodel) to test your UI logic
      • And much, much more.
    • Api Reference documentation
    • A Visual Studio Plugin that helps you to target both WPF and Silverlight with a single codebase. 

    You should consider using prism:

    • If you want to create modular applications, in WPF and / or Silverlight so you can Develop, Test, Version and Deploy your modules independently of each other.
    • If you want to create an application that targets both WPF and Silverlight with a single codebase, or at least reuse a lot of code assets between WPF and Sliverlight.
    • If you want to minimize initial download size Silverlight applications. Prism allows you to just download the minimum of functionality you need to start your application. Other modules can be downloaded on a background thread or on demand.
    • If you are interested in using separated presentation patterns, because you want to create Unit Tests for your UI logic or if you want to make it easier to reskin your application.

    Links :

  • Which technology to choose ?

     

    The diagram represents a spectrum of application development approaches and technologies/platforms with increasing reach on one end, and increasing capabilities on the other. Applications have distinct scenarios and correspondingly gravitate toward a sweet spot. Some apps lie squarely on the left, with the need to first and foremost prioritize universal reach. At the same time, some apps have experience or functionality as the high order bit, where it is necessary to leverage a more capable platform, even if it means somewhat reduced reach. Still, the best apps will probably be those that leverage multiple front-end options to follow the user, with a common back-end.
    Why RIA App – Silverlight

    With Silverlight you get cross platform (almost all browsers on Mac and Windows) .NET runtimes.Silverlight is a powerful development platform for creating engaging, interactive user  experiences for Web, desktop, and mobile applications when online or offline.

    Silverlight is different. It is an immediate win if you have desktop .NET apps which you would like to convert to web applications, or ASP.NET apps for which you would like a richer client. Why Silverlight and not WPF? For one thing, cross-platform, essential for public web applications and very useful internally as well, with all those Mac-using designers (and now the CEO wants a Mac too). For another thing, lightweight deployment. When you install or upgrade the .NET runtime on a Windows box, you hold your breath as it updates a gazillion system components and hope that no bizarre error code appears. When you install Silverlight, you just click OK to a browser dialog, and it works.

    The contradiction in the title of this post is that both Silverlight and WPF use XAML, so in learning one you are to some extent learning the other. Nevertheless, I now believe that Silverlight will be a more significant platform than WPF
    WCF RIA Services

     
    Microsoft WCF RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

    As of this writing, WCF RIA Services is still in beta. however, in it’s current form, it clearly demonstrates that it allows dramatic reductions in development time. This is accomplished by providing a framework that greatly reduces the amount of code needed to communicate between a Silverlight application and the web server hosting it.Silverlight WCF RIA Services promises to bring greatly improved user interfaces with less development costs. Without writing any special code you will have a pageable, sortable, Grid that is bound to a Data Form. The Grid even allows for the headers to be dragged and reordered. Basic, client-side validation is also provided.

    HTML – Replaced by XAML – Very very powerfull (vector graphics) for rich UI

    Clientside Javascript – Replaced by client side C# without .Net framework – cross platform,cross browsers , even on mobile device

    Web services – Replaced by WCF RIA service – Fast and robust development.

    You can see the differences and that’s the future of developers technology – Next generation of applications..

    Rajneesh Noonia