Pixytech

Lead Architect  •  Full Stack Engineer

Tag: .NET

  • Persisting RIA Service Entities to Isolated Storage in Silverlight

    The Silverlight library in this article extends RIA service entities and provides save & load method to save/load entities directly into application storage (Isolation storage). The library supports dynamic quota management for application storage i.e. if an entity requires more space to store it will prompt user to confirm new size of quota store. The saving and loading supports asynchronous processing of entities with inbuilt compression which allows your application to provide non blocking UI. Library can be used to build online-offline mode based Silverlight applications without additional programming overheads.

    Code to save RIA Entities in the storage space

    EmployeeContext context = new EmployeeContext();
    dataGrid.ItemSource = context.Employees;
    Action<LoadOperation<Patient>> completeProcessing = delegate(LoadOperation<Patient> loadOp)
    {
        if (!loadOp.HasError)
            {
                loadOp.Entities.Save();
            }
            else
            {
                LogAndNotify(loadOp.Error);
                loadOp.MarkErrorAsHandled();
            }
    };
    context.Load(context.GetEmployeesQuery(), completeProcessing, null);

    Code to load RIA Entities from storage space

    EmployeeContext context = new EmployeeContext();
    context.Employees.Load();

    You can also use the same library to save and load genric data you need to provide the filename to which the object set is saved whereas with Ria EntitySet the fileName is optional which is calculated based on the data type of entity.
    Code to save List<string> into storge sapce

    List<string> names = new List<string>();
    names.Add("Employee1");
    names.Add("Employee2");
    names.Add("Employee3");
    names.Save("Employee4");
    names.Save("EmployeeesDataSet");

    Code to load List<string> into storge sapce

    List<string> names = new List<string>();
    names.Load("EmployeeesDataSet")

    Note: The Load method supports Asynchronous (default) and Synchronous operation where as Save method only supports Asynchronous operation.You can also override the Quota Management screen globally in your application and if not overrided the library will use in-built screen shown below (right image).

    How it works : diagram is self explanatory..

    Source code is now available here, Because of time constriants i was not able to comlete the code behind for the isolation storage screen above, however the library is now completed and published with silverlight unit test project.

  • ASP.Net Basic

    In this article we will explore the ASP.Net page events and stages which are part of page life cycle. Before we go ahead i would like to review what we have learnt so far in previous articles related to ASP.Net.

    IIS: IIS (Internet Information Server) is a Microsoft Web server that makes it possible to quickly and easily deploy powerful Web sites and applications. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. (By default, ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.)

    Note:

    • If a file name extension has not been mapped to ASP.NET, ASP.NET will not receive the request. It will be handled by the IIS. The requested page/image/file is returned without any processing.
    • If you create a custom handler to service a particular file name extension, you must map the extension to ASP.NET in IIS and also register the handler in your application’s Web.config file.

    ASPNET_ISAPI.DLL: This DLL is the ISAPI extension provided with ASP.NET to process the web page requests. IIS loads this DLL and sends the page request to this DLL. This DLL loads the HTTPRuntime for further processing.

    ASPNET_WP.EXE: Each worker process (ASPNET_WP.EXE) contains an Application Pool. Each Application Pool can contain any number of Applications. Application Pool is also called as AppDomain. When a web page is requested, IIS looks for the application pool under which the current application is running and forwards the request to the respective worker process.

    HTTP Pipeline: HTTP Pipeline is the general-purpose framework for server-side HTTP programming that serves as the foundation for ASP.NET pages as well as Web Services. All the stages involved from creating HTTP Runtime to HTTP Handler is called HTTP Pipeline.

    HTTP Runtime: Each AppDomain has its own instance of the HttpRuntime class—the entry point in the pipeline. The HttpRuntime object initializes a number of internal objects that will help carry the request out. The HttpRuntime creates the context for the request and fills it up with any HTTP information specific to the request. The context is represented by an instance of the HttpContext class. Another helper object that gets created at such an early stage of the HTTP runtime setup is the text writer—to contain the response text for the browser. The text writer is an instance of the HttpWriter class and is the object that actually buffers any text programmatically sent out by the code in the page. Once the HTTP runtime is initialized, it finds an application object to fulfill the request. The HttpRuntime object examines the request and figures out which application it was sent to (from the pipeline’s perspective, a virtual directory is an application).

    HTTP Context: This is created by HTTP Runtime. The HttpContext class contains objects that are specific to the current page request, such as the HttpRequest and HttpResponse objects. You can use this class to share information between pages. It can be accessed with Page.Context property in the code.

    HTTP Request
    : Provides access to the current page request, including the request headers, cookies, client certificate, query string, and so on. You can use this class to read what the browser has sent. It can be accessed with Page.Request property in the code.

    HTTP Response: Provides access to the output stream for the current page. You can use this class to inject text into the page, to write cookies, and more. It can be accessed with Page.Response property in the code.

    HTTP Application: An application object is an instance of the HttpApplication class—the class behind the global.asax file. HTTPRuntime uses HttpApplicationFactory to create the HTTPApplication object. The main task accomplished by the HTTP application manager is finding out the class that will actually handle the request. When the request is for an .aspx resource, the handler is a page handler—namely, an instance of a class that inherits from Page. The association between types of resources and types of handlers is stored in the configuration file of the application. More exactly, the default set of mappings is defined in the <httpHandlers> section of the machine.config file. However, the application can customize the list of its own HTTP handlers in the local web.config file. The line below illustrates the code that defines the HTTP handler for .aspx resources.

    <add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

    HttpApplicationFactory: Its main task consists of using the URL information to find a match between the virtual directory of the URL and a pooled HttpApplication object.

    HTTP Module: An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request. They also let you examine the outgoing response and modify it. ASP.NET uses modules to implement various application features, which include forms authentication, caching, session state, and client script services. In each case, when those services are enabled, the module is called as part of a request and performs tasks that are outside the scope of any single page request. Modules can consume application events and can raise events that can be handled in the Global.asax file.

    HTTP Handler: An ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request a .aspx file, the request is processed by the page handler. We can write our own handler and handler factory if we want to handle the page request in a different manner.

    Note: HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

    In brief, here is the explanation of what happen to request when it arries at IIS

    • Web page request comes from browser.
    • IIS maps the ASP.NET file extensions to ASPNET_ISAPI.DLL, an ISAPI extension provided with ASP.NET.
    • ASPNET_ISAPI.DLL forwards the request to the ASP.NET worker process (ASPNET_WP.EXE or W3P.EXE).
    • ISAPI loads HTTPRuntime and passes the request to it. Thus, HTTP Pipelining has begun.
    • HTTPRuntime uses HttpApplicationFactory to either create or reuse the HTTPApplication object.
    • HTTPRuntime creates HTTPContext for the current request. HTTPContext internally maintains HTTPRequest and HTTPResponse
    • HTTPRuntime also maps the HTTPContext to the HTTPApplication which handles the application level events.
    • HTTPApplication runs the HTTPModules for the page requests.
    • HTTPApplication creates HTTPHandler for the page request. This is the last stage of HTTPipelining.
    • HTTPHandlers are responsible to process request and generate corresponding response messages.
    • Once the request leaves the HTTPPipeline, page level events begin.
    • Page Events like load etc happens at this stage.
    • HTTPHandler generates the response with the above events and sends back to the IIS which in turn sends the response to the client browser.

    ASP.Net page life cycle

    ASP.Net page life cycle and stages involved several page stages and page events when it was triggered by HTTPHandler.Please not that there are Application stages which occurs before and after page life cycle which are discussed here.

    Stages

    Page goes through the several stages mentioned below alone with the description of each stage.

    Stages Description
    Page request The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.
    Start In the start stage, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. The page also sets the UICulture property.
    Initialization During page initialization, controls on the page are available and each control’s UniqueID property is set. A master page and themes are also applied to the page if applicable. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.
    Load During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.
    Postback event handling If the request is a postback, control event handlers are called. After that, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
    Rendering Before rendering, view state is saved for the page and all controls. During the rendering stage, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream object of the page’s Response property.
    Unload The Unload event is raised after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and cleanup is performed.

     Events

    Within each stage of the life cycle of a page, the page raises events that you can handle to run your own code. For control events, you bind the event handler to the event, either declaratively using attributes such as onclick, or in code.

    Pages also support automatic event wire-up, meaning that ASP.NET looks for methods with particular names and automatically runs those methods when certain events are raised. If the AutoEventWireup attribute of the @ Page directive is set to true, page events are automatically bound to methods that use the naming convention of Page_event, such as Page_Load and Page_Init. For more information on automatic event wire-up, see ASP.NET Web Server Control Event Model.

    Below are the page life-cycle events that you will use most frequently..

    Page Event Typical Use
    PreInit Raised after the start stage is complete and before the initialization stage begins.Use this event for the following:

    • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
    • Create or re-create dynamic controls.
    • Set a master page dynamically.
    • Set the Theme property dynamically.
    • Read or set profile property values.

    NoteNote :  If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

    Init Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.Use this event to read or initialize control properties.
    InitComplete Raised at the end of the page’s initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.Use this event to make changes to view state that you want to make sure are persisted after the next postback.
    PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
    Load The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.Use the OnLoad event method to set properties in controls and to establish database connections.
    Control events Use these events to handle specific control events, such as a Button control’s Click event or a TextBox control’s TextChanged event.

    NoteNote : In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
    LoadComplete Raised at the end of the event-handling stage.Use this event for tasks that require that all other controls on the page be loaded.
    PreRender Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object calls EnsureChildControls for each control and for the page.)The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page.Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
    PreRenderComplete Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
    SaveStateComplete Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
    Render This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control’s markup to send to the browser.If you create a custom control, you typically override this method to output the control’s markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
    Unload Raised for each control and then for the page.In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

    NoteNote : During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

     

    Those who want to go in depth study for life cycle events may explore msdn where you will find more than enough information what you are looking for.The next article “All about patterns” of this series is bit different in the sequence of the series i was writing under .Net Concepts category on this blog.

    In next my next article”All about patterns” i would like to take the opportunity to explore different kind of patterns and further series will include in depth study of MVC and MVVM architectural patterns.Once we finished pattern series we will further explore asp.net internals and other features.

  • .Net CLR Internals

    The CLR is described as the “execution engine” of .NET. It provides the environment within which the programs run. It’s this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety, and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version.

    The European Computer Manufacturers Association (ECMA) standard has defines the Common Language Specification (CLS); this enforces that software development languages should be interoperable between them. The code written in a CLS should be compliant with the code written in another CLS-compliant language. Because the code supported by CLS-compliant language should be compiled into an intermediate language (IL) code. The CLR  engine executes the IL code. This ensures interoperability between CLS-compliant languages.

    The ECMA standard, Common Language Infrastructure (CLI), defines the specifications for the infrastructure that the IL code needs for execution.The CLR is Implementation of CLI. The CLI provides a common type system (CTS) and services such as type safety, managed code execution and side by side execution.

    In my previous article (.Net CLR Overview) we have seen how CLR is get loaded when user executes .net executable on windows (say) platform.

    There are many components in CLR which are used to do specific tasks or functions of CLR.

    The above diagram show the various components of .Net CLR , Each component is responsible for specific functionality mentioned below.

    • Class Loader : It is used to load all the classes (MSIL Code) at runtime into CLR. The class loader component of the CLR uses metadata to locate specific classes within assemblies, either locally or across networks.
    • MSIL to Native compiler : It is a JIT (Just In Time) compiler it will convert MSIL code to native code.
    • Code Manager : It manages the code during execution.
    • Garbage Collector : Memory allocation and Garbage collector, this performs automatic memory management.
    • Security engine : this enforces security restrictions as code level security folder level and machine level security using tools provided by Microsoft .NET and using .NET Framework setting under control panel.
    • Type Checker : It enforces strict type checking.
    • Thread Support : It provides multithreading support to .Net applications.
    • Exception Manager : It provides mechanisum to handle execptions at runtime.
    • Debug Engine : Allows developer to debug different types of applications.
    • Com Marshaler : Allows .NET applications to exchange data with COM applications.
    • Base Class library support : Which provides the classes (types) that the applications need at run time.

    How it works

    When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called  the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It’s the job of the CLR to translate this Intermediate code into a executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that’s how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just In Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL.

    We will cover CLR core features like garbage collector, Thread support,Exception manager,Debug engine,Security engine in next articles.

  • Dependency Properties

    WPF introduces a new type of property called a dependency property, used throughout the platform to enable styling, automatic data binding, animation, and more. Definition of Dependency Properties on MSDN

    A dependency property depends on multiple providers for determining its value at any point in time. These providers could be an animation continuously changing its value, a parent element whose property value trickles down to its children, and so on. Arguably the biggest feature of a dependency property is its built-in ability to provide change notification. The motivation for adding such intelligence to properties is to enable rich functionality directly from declarative markup.

    Below is the demonstration of how Button effectively implements one of its dependency properties which is called IsDefault.

    public class Button : ButtonBase
    {
    // The dependency property
    public static readonly DependencyProperty IsDefaultProperty;
    static Button()
    {
    // Register the property
    Button.IsDefaultProperty = DependencyProperty.Register(“IsDefault”,
    typeof(bool), typeof(Button),
    new FrameworkPropertyMetadata(false,
    new PropertyChangedCallback(OnIsDefaultChanged)));
    …
    }
    // A .NET property wrapper (optional)
    public bool IsDefault
    {
    get { return (bool)GetValue(Button.IsDefaultProperty); }
    set { SetValue(Button.IsDefaultProperty, value); }
    }
    // A property changed callback (optional)
    private static void OnIsDefaultChanged(
    DependencyObject o, DependencyPropertyChangedEventArgs e) { … }
    …
    }

    The static IsDefaultProperty field is the actual dependency property, represented by the System.Windows.DependencyProperty class. By convention all DependencyProperty fields are public, static, and have a Property suffix.

    So one of the first things I thought was weird about the definition of a dependency property is that it is a static. This property needs to store info relevant to a particular instance of a class, how is it going to do that if it is static?

    As you read more about them, you will realized that a dependency property definition was exactly that – a definition. You are essentially saying that class A will have a property B – and it makes sense that that definition would be static. The actual storage of a value for a dependency property is deep inside the WPF property system – you never have to worry about it.

    Dependency properties are usually created by calling the static DependencyProperty.Register method, which requires a name (IsDefault), a property type (bool), and the type of the class claiming to own the property

    (Button). Optionally (via different overloads of Register), you can pass metadata that customizes how the property is treated by WPF, as well as callbacks for handling property value changes, coercing values, and validating values. Button calls an overload of Register in its static constructor to give the dependency property a default value of false and to attach a delegate for change notifications.

    Finally, the traditional .NET property called IsDefault implements its accessors by calling GetValue and SetValue methods inherited from System.Windows.DependencyObject, a low-level base class from which all classes with dependency properties must derive. GetValue returns the last value passed to SetValue or, if SetValue has never been called, the default value registered with the property.

    So at first glance, all the properties on the new WPF controls seem to be regular old properties. But don’t be fooled – this is often just a simple wrapper around a dependency property.

    The IsDefault .NET property (sometimes called a property wrapper) is not strictly necessary; consumers of Button could always directly call the GetValue/SetValue methods because they are exposed publicly. But the .NET property makes programmatic reading and writing of the property much more natural for consumers, and it enables the property to be set via XAML.

    GetValue and SetValue internally use an efficient sparse storage system and because IsDefaultProperty is a static field (rather than an instance field), the dependency property implementation saves per-instance memory compared to a typical .NET property. If all the properties on WPF controls were wrappers around instance fields (as most .NET properties are), they would consume a significant amount of memory because of all the local data attached to each instance. The benefits of the dependency property implementation extend to more than just

    memory usage, however. It centralizes and standardizes a fair amount of code that property implementers would have to write to check thread access, prompt the containing element to be re-rendered, and so on.

    Change Notification

    Whenever the value of a dependency property changes, WPF can automatically trigger a number of actions depending on the property’s metadata. These actions can be re-rendering the appropriate elements, updating the current layout, refreshing data bindings,and much more. One of the most interesting features enabled by this built-in change notification is property triggers, which enable you to perform your own custom actions when a property value changes without writing any procedural code.

    For example, imagine that you want the text in each Button to turn blue when the mouse pointer hovers over it. Without property triggers,you can attach two event handlers to each Button, one for its MouseEnter event and one

    for its MouseLeave event:

    <Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
    MinWidth=”75” Margin=”10”>Help</Button>
    <Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
    MinWidth=”75” Margin=”10”>OK</Button>

    These two handlers could be implemented in a C# code-behind file as follows:

    // Change the foreground to blue when the mouse enters the button
    void Button_MouseEnter(object sender, MouseEventArgs e)
    {
    Button b = sender as Button;
    if (b != null) b.Foreground = Brushes.Blue;
    }
    // Restore the foreground to black when the mouse exits the button
    void Button_MouseLeave(object sender, MouseEventArgs e)
    {
    Button b = sender as Button;
    if (b != null) b.Foreground = Brushes.Black;
    }

    With a property trigger, however, you can accomplish this same behavior purely in XAML. The following concise Trigger object is (just about) all you need:

    <Trigger Property=”IsMouseOver” Value=”True”>
    <Setter Property=”Foreground” Value=”Blue”/>
    </Trigger>

    This trigger can act upon Button’s IsMouseOver property, which becomes true at the same time the MouseEnter event is raised and false at the same time the MouseLeave event is raised. Note that you don’t have to worry about reverting Foreground to black when IsMouseOver changes to false. This is automatically done by WPF! You could apply the preceding Trigger to a Button by wrapping it in a few intermediate XML elements as follows:

    <Button MinWidth=”75” Margin=”10”>
    <Button.Style>
    <Style TargetType=”{x:Type Button}”>
    <Style.Triggers>
    <Trigger Property=”IsMouseOver” Value=”True”>
    <Setter Property=”Foreground” Value=”Blue”/>
    </Trigger>
    </Style.Triggers>
    </Style>
    </Button.Style>
    OK
    </Button>
    Three type of triggers are available in WPF

    Property Triggers : As mentioned above

    A data trigger is a form of property trigger that works for all .NET properties (not just dependency properties)

    An event trigger enables you to declaratively specify actions to take when a routed event. Event triggers always involve working with animations or sounds

    Property Value Inheritance

    The term property value inheritance or property inheritance doesn’t refer to traditional object oriented class based inheritance, but rather the flowing of property values down the element tree.

    Example :

    <Window xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    
    Title=”Property Inheritance sample” SizeToContent=”WidthAndHeight”
    
    FontSize=30FontStyle=Italic”
    
    Background=”OrangeRed”>
    
    <StackPanel>
    
    <Label FontWeight=”Bold” FontSize=”20” Foreground=”White”>
    
    WPF Property Inheritance
    
    </Label>
    
    <Label>Rajneesh</Label>
    
    <Label>Tech</Label>
    
    <ListBox>
    
    <ListBoxItem>.Net</ListBoxItem>
    
    <ListBoxItem>C#</ListBoxItem>
    
    </ListBox>
    
    <StackPanel Orientation=”Horizontal” HorizontalAlignment=”Center”>
    
    <Button MinWidth=”75” Margin=”10”>Cancel</Button>
    
    <Button MinWidth=”75” Margin=”10”>OK</Button>
    
    </StackPanel>
    
    <StatusBar>You have successfully created property inheritance</StatusBar>
    
    </StackPanel>
    
    </Window>
    

    Note : Window automatically resizes to fit all the content thanks to its slick SizeToContent setting!

    In above example we are explicitly setting window FontSize and FontStyle dependency properties.

    For the most part, these two settings flow all the way down the tree and are inherited by children. This affects even the Buttons and ListBoxItems, which are three levels down the logical tree. The first Label’s FontSize does not change because it is explicitly marked with a FontSize of 20, overriding the inherited value of 30.

    Note : Internally, dependency properties can opt in to inheritance by passing FrameworkPropertyMetadataOptions. Inherits to DependencyProperty.Register

    Support for Multiple Providers

    WPF contains many powerful mechanisms that independently attempt to set the value of dependency properties.

    Attached Properties

    An attached property is a special form of dependency property that can effectively be attached to arbitrary objects.

    Imagine that rather than setting FontSize and FontStyle for the entire Window (in above example), you would rather set them on the inner StackPanel so they are inherited only by the two Buttons. But StackPanel doesn’t have any font-related properties of its own! Instead, you must use the FontSize and FontStyle attached properties that happen to be defined on a class called TextElement.

    <StackPanel TextElement.FontSize=”30” TextElement.FontStyle=”Italic”
    Orientation=”Horizontal” HorizontalAlignment=”Center”>
    <Button MinWidth=”75” Margin=”10”>Cancel</Button>
    <Button MinWidth=”75” Margin=”10”>OK</Button>
    </StackPanel>

    Just like previous technologies such as Windows Forms, many classes in WPF define a Tag property (of type System.Object) intended for storing arbitrary custom data with each instance. But attached properties are a more powerful and flexible mechanism for attaching custom data to any object deriving from DependencyObject. It’s often overlooked that attached properties enable you to effectively add custom data to instances of sealed classes.

    *Beginners : I would like to recommended WPF fundamental tutorials by Christian Moser at http://www.wpftutorial.net

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