Friday, 31 August 2012

WCF - Notes 7 Tools


Tool Support: WCF and Visual Studio

WCF has a tight relationship with Visual Studio, which provides a number of WCF-specific capabilities. They include the following:
·         Several WCF-specific project types to make it easier for developers to get started creating typical WCF applications. These include projects for building:
·         A Website or Web application that hosts a WCF service;
·         A library implementation of a WCF service;
·         A WCF application that exposes syndication feeds using RSS or ATOM;
·         A WCF service designed for use by an AJAX client. This service is automatically configured to use the WebHttpBinding with JSON encoding.
·         An AddServiceReference function that lets a developer specify an existing service’s endpoint, then let Visual Studio automatically generate a WCF proxy for that service.
·         The ability to generate a client for testing new WCF-based Web services.
·         A WCF Autohost that can automatically host a library-based WCF service.
·         The Service Configuration Editor, a tool that makes creating and modifying WCF configuration files easier.
·         IntelliSense for WCF configuration, allowing statement completion when creating XML elements in configuration files

WCF - Notes 6 Workflow Service


Creating a Workflow Service

As its name suggests, Windows Workflow Foundation (WF) lets developers create workflow-based applications. WF workflows can be useful in a variety of different situations. For example, WF can make it easier to create scalable applications that pause, perhaps for a long time, while waiting for input. Whatever its purpose, every WF workflow is built from activities, each of which performs some function. An activity might do something simple, such as implement a While statement, or carry out a more complex task, such as executing custom business logic.
While it’s certainly not required, a developer can use WF to create the logic for a WCF service. Known as a workflow service, this technology combination often makes sense. The developer builds scalable business logic as a WF workflow, then lets that workflow’s activities interact with the outside world via WCF services.
To help do this, WF includes several activities specifically intended to allow WCF communication. For example, the Send activity sends a message via WCF, while the Receive activity receives a message. WCF 4 also allows correlation of multiple requests sent to a particular workflow instance. For example, suppose an instance of a workflow sends a request via WCF, then pauses waiting for a message in response. While it’s waiting, this workflow instance will be deactivated, with its state stored on disk. When a response message arrives, WCF can determine from the message’s contents which workflow instance it’s intended for—it can correlate this response message with the request message sent earlier. The target workflow instance can then be reactivated and the message delivered to the appropriate activity in that workflow.
Not every WCF service should be built using WF. In a surprisingly large number of cases, however, using WF and WCF together is the right choice. Workflow services can be useful things.

WCF - Notes 5 Security and Transactions


Security

  • Exposing services on a network, even an internal network, usually requires some kind of security. How can the service be certain of its client’s identity? How can messages sent to and from a service be kept safe from malicious changes and prying eyes? And how can access to a service be limited to only those authorized to use it? Without some solution to these problems, it’s too dangerous to expose many kinds of services. Yet building secure distributed applications is difficult. Ideally, there should be straightforward ways to address common security scenarios, along with more fine-grained control for applications that need it.
  • To help achieve this, WCF provides the core security functions of authentication, message integrity, message confidentiality, and authorization. All of these depend fundamentally on the notion of identity: who is this user? Establishing an identity for a client or service requires supplying information such as a username and password, an X.509 certificate, or something else. A client or service can do this by directly invoking a WCF function, by using a config file, or in other ways, such as by referencing a certificate store. However it’s done, establishing an identity is an essential part of using WCF security.
  • Distributed security can get very complicated very fast. A primary goal of WCF’s designers was to make building secure applications easier. To allow this, WCF’s approach to authentication, data integrity and data privacy relies on bindings. Rather than require developers to insert the right attributes to secure each class and method, they can instead just use a binding that provides the right set of security services. A developer’s choices include the following:
  • Use a standard binding that directly supports security. For example, applications that require end-to-end security for messages that go through multiple SOAP intermediaries can use a binding that supports WS-Security, such as WsHttpBinding.
  • Use a standard binding that optionally supports security, then configure it as needed. For example, applications that need only transport-based security can choose BasicHttpBinding, configuring it to use HTTPS rather than HTTP. It’s also possible to customize other more-advanced security behaviors. For example, the authentication mechanism used by a binding such as WsHttpBinding can be changed if desired.
  • Create a custom binding that provides exactly the security behavior a developer needs. Doing this is not for the faint of heart, but it can be the right solution for some problems.
  • Use a standard binding that provides no support for security, such as BasicHttpBinding. While using no security is often a risky thing to do, it can sometimes be the only option.
<configuration>
  <system.serviceModel>
    <services>
      <service
        type="RentalReservations,RentalApp"
        <endpoint
          contract="IReservations"
          binding="basicHttpBinding"
          bindingConfiguration="UsingHttps"
          address=
            ”http://www.fabrikam.com/reservation/reserve.svc"/>
      </service>
    </services>
    <bindings>
        <basicHttpBinding>
        <binding
          configurationName="UsingHttps"
          securityMode="Https"/>
      </basicHttpBinding>
    </bindings>
  </system.serviceModel>
</configuration>
  • A WCF service can also control which clients are authorized to use its services. To do this, WCF relies on existing authorization mechanisms in the .NET Framework. A service can use the standard PrincipalPermission attribute, for example, to define who is allowed to access it. Alternatively, a WCF application that needed role-based authorization could use Windows Authorization Manager to implement this.
  • Transactions
  • Handling transactions is an important aspect of building many kinds of business logic. Yet using transactions in a service-oriented world can be problematic. Distributed transactions assume a high level of trust among the participants, so it often isn’t appropriate for a transaction to span a service boundary. Still, since there are situations where combining transactions and services makes sense, WCF includes support for this important aspect of application design.
  • Transactions in the .NET Framework: System.Transactions
  • The transaction support in WCF builds on System.Transactions, a .NET Framework namespace focused solely on controlling transactional behaviors. Although it’s not required, developers commonly use the services of System.Transactions in concert with an execution context. An execution context allows the specification of common information, such as a transaction, that applies to all code contained within a defined scope. Here’s an example of how an application can use this approach to group a set of operations into a single transaction:
using System.Transactions;
using (TransactionScope ts =
   new TransactionScope(TransactionScopeOption.Required)) {
   // Do work, e.g., update different DBMSs
   ts.Complete();
}
  • All of the operations within the using block will become part of a single transaction, since they share the transactional execution context it defines. The last line in this example, calling the TransactionScope‘s Complete method, will result in a request to commit the transaction when the block is exited. This approach also provides built-in error handling, aborting the transaction if an exception is raised.
  • Specifying TransactionScopeOption.Required for the new TransactionScope, as this example does, means that this code will always run as part of a transaction: joining its caller’s transaction if one exists, creating a new one if it does not.
  • Unlike Enterprise Services and its predecessors Microsoft Transaction Server (MTS) and COM+, however, System.Transactions is focused entirely on controlling transactional behavior. There is no required connection between a transaction and the internal state of an object, for example. While Enterprise Services requires an object to be deactivated when it ends a transaction, System.Transactions makes no such demand. Since WCF builds on System.Transaction, WCF-based applications are also free to manage transactions and object state independently.
  • WCF-based applications can use the types in System.Transactions directly, or they can control transactions using WCF-defined attributes that rely on System.Transactions under the covers. 
  •  A service’s methods can control transactional behavior via an attribute. Rather than explicitly relying on System.Transactions, a service can use the OperationBehavior attribute described earlier.
[OperationContract]
[OperationBehavior(TransactionScopeRequired=true,
                   TransactionAutoComplete=true)]
private int Reserve(int vehicleClass, int location, string dates)
{
  int confirmationNumber;
  // logic to reserve rental car goes here
  return confirmationNumber;
}
  • Finally, it’s worth emphasizing that applications built on WCF can participate in transactions that include applications running on non-WCF platforms. For example, a WCF-based application might start a transaction, update a record in a local SQL Server database, then invoke a Web service implemented on a Java EE-based application server that updates a record in another database. If this service is transactional and the platform it’s running on supports the WS-AtomicTransaction specification, both database updates can be part of the same transaction. Like security and reliable messaging, WCF transactions can work in the heterogeneous world that Web services make possible.

WCF - Notes 4 WCF Client


Creating a WCF Client

WCF Client talks to WCF service with a proxy.


A WCF client can use a proxy to access a service.
  • Creating a proxy requires knowing what contract is exposed by the target endpoint, and then using the contract’s definition to generate the proxy. In WCF, this process can be performed using either Visual Studio or the command-line svcutil tool.
  • If the service is implemented using WCF, these tools can access the service’s DLL to learn about the contract and generate a proxy. If only the service’s WSDL definition is available, the tools can read this to produce a proxy.
  •  If only the service itself is available, Visual Studio and svcutil can access it directly using either WS-MetadataExchange or a simple HTTP GET to acquire the service’s WSDL interface definition, and then generate the proxy.
  • However it’s generated, the client can create a new instance of the proxy, and then invoke the service’s methods using it.
  • Good programming practice to clean up the communications infrastructure that has been created.
  • One more thing remains to be specified by the client: the exact endpoint on which it wishes to invoke operations. Like a service, the client must specify the endpoint’s contract, its binding and its address, and this is typically done in a config file. In fact, if enough information is available, svcutil will automatically generate an appropriate client configuration file for the target service.
WCF supports several possibilities along with traditional RPC, including the following:
·         Asynchronous RPC, with non-blocking paired calls carrying lists of typed parameters.
·         Traditional messaging, with non-blocking calls carrying a single message parameter. Working directly with channels exposes methods to send and receive messages, and WCF defines a standard Message class that can be used to work directly with XML messages.
·         Direct manipulation of SOAP messages using the WCF-defined attribute MessageContract. Using two related attributes, MessageHeader and MessageBodyMember, an application can explicitly access the contents of a SOAP message’s header and body.
  • To allow creating a method that sends information but doesn’t block waiting for a response, the OperationContract attribute has a property called IsOneWay. Methods marked with this attribute and property can have only input parameters and must return void.
[OperationContract(IsOneWay=true)]
void NewCarAvailable(int vehicleClass, int location);
  • With this method, the caller gets nothing in return—it’s one-way communication. A typical use of one-way methods like this is to send unsolicited events.
  • It’s also possible to link together calls to methods, whether one-way or normal two-way methods, allowing both sides of the communication to act as client and service. To do this, each side implements a contract that’s linked with its partner, resulting in what are called duplex contracts. WCF provides special bindings for handling this case, such as WsDualHttpBinding for duplex contracts that use standard interoperable SOAP.

Controlling Local Behavior

  • How is concurrent access to a service instance managed, for example, and how is that instance’s lifetime controlled? To allow developers to set local behaviors like these, WCF defines two primary attributes, both of which have a number of properties. One of these attributes, ServiceBehavior, can be applied to any service class. The other, OperationBehavior, can be applied to any method in a service class that is also marked with the OperationContract attribute.
  • The ServiceBehavior attribute has various properties that affect the behavior of the service as a whole. For example, a property called ConcurrencyMode can be used to control concurrent access to the service. If set to Single, WCF will deliver only one client request at a time to this service, i.e., the service will be single-threaded. If this property is set to Multiple, WCF will deliver more than one client request at a time to the service, each running on a different thread. Similarly, ServiceBehavior’s InstanceContextMode property can be used to control how instances of a service are created and destroyed. If InstanceMode is set to PerCall, a new instance of the service will be created to handle each client request, and then destroyed when the request is completed. If it’s set to PerSession, however, the same instance of the service will be used to handle all requests from a particular client. (Doing this also requires setting ServiceContract‘s Session attribute to true and choosing a binding that supports sessions.) InstanceContextMode can also be set to Single, which causes a single instance of the service to handle all requests from all clients.
using System.ServiceModel;
[ServiceContract]
[ServiceBehavior(
   ConcurrencyMode=Multiple,
   InstanceContextMode=Single)]
class RentalReservations { ... }
  • Similarly, properties on the OperationBehavior attribute allow controlling the impersonation behavior of the method that implements a particular operation, its transactional requirements (described later), and other things.
  • Another aspect of local behavior is how a request from a client is routed within a WCF service. WCF in the .NET Framework 4 adds a standard content-based routing service that a developer can use with SOAP-based services. The routing service sits in front of other WCF services, routing each incoming message to one of those services based on the message’s content. 

WCF- Notes 3 Hosting


Selecting a Host

·         A WCF service class is typically compiled into a library. By definition, all libraries need a host Windows process to run in. WCF provides two main options for hosting libraries that implement services. One is to use a host process created by either:
ü  Internet Information Services (IIS) or a
ü  Related technology called the Windows Activation Service (WAS).
ü  The other allows a service to be hosted in an arbitrary process. 

Hosting a Service Using IIS or WAS

·         The simplest way to host a WCF service is to rely on IIS or WAS. Both rely on the notion of a virtual directory, which is just a shorter alias for an actual directory path in the Windows file system.
·         IIS-hosted WCF services can only be accessed using SOAP over HTTP. No other transport protocols are supported.
·         Although WAS doesn’t require a Web server to be installed on the system, WCF services hosted in IIS obviously do.
·         Whatever choice is made, both WAS and IIS provide WCF services with a range of support, such as the ability to configure automatic process recycling.
·         To allow a WCF service to take requests from its clients, the process that hosts it must remain running. With WAS-hosted services, the standard process ensures the host remains running, but a hosting application must solve this problem on its own. A WCF service hosted console would be running in a Windows service, allowing it to be started when a system boots, or be hosted in a GUI application, such as one built with Windows Presentation Foundation.

WCF : Notes 2 Service class


Implementing a Service Class

A service class is a class like any other, but it has a few additions. These additions allow the class’s creator to define one or more contracts that this class implements. Each service class implements at least one service contract, which defines the operations this service exposes. The class might also provide an explicit data contract, which defines the data those operations convey.


Defining Service Contracts

·         Every service class implements methods for its clients to use. The creator of the class determines which of its methods are exposed as client-callable operations by specifying that they are part of some service contract. To do this, a developer uses the WCF-defined attribute ServiceContract. In fact, a service class is just a class that either is itself marked with the ServiceContract attribute or implements an interface marked with this attribute. 
·         Namespace used here is using System.ServiceModel;

        Class should be decorated as [ServiceContract] attribute

using System.ServiceModel;
[ServiceContract]
class RentalReservations
{
}
·             

       Each method in a service class that can be invoked by a client must be marked with another attribute named OperationContract. All the methods in a service class that are preceded by the OperationContract attribute are automatically exposed by WCF as services.
[ServiceContract]
class RentalReservations
{
   [OperationContract]
   public bool Check(int vehicleClass, int location,
                     string dates)
   {
      bool availability;
      // code to check availability goes here
      return availability;
   }
}
·   

      Any methods in a service class that aren’t marked with OperationContract aren’t included in the service contract, and so can’t be called by clients of this WCF service.
·         It’s better to specify service contracts explicitly using a language’s interface type. class might look like this:

using System.ServiceModel;
[ServiceContract]
interface IReservations
{
   [OperationContract]
   bool Check(int vehicleClass, int location, string dates);
}
class RentalReservations : IReservations
{
   public bool Check(int vehicleClass, int location,
                     string dates)
   {
     bool availability;
     // logic to check availability goes here
     return availability;
   }
}
·     

            Using explicit interfaces like this is slightly more complicated, but it allows more flexibility. For example, a class can implement more than one interface, which means that it can also implement more than one service contract. By exposing multiple endpoints, each with a different service contract, a service class can present different groups of services to different clients.
·         Marking a class or interface with ServiceContract and one or more of its methods with OperationContract also allows automatically generating service contract definitions in WSDL. Accordingly, the externally visible definition of every WCF service contract can be accessed as a standard WSDL document specifying the operations in that contract. This style of development, commonly called code-first, allows creating a standard interface definition directly from types defined in programming languages such as C# or Visual Basic.
·         An alternative approach is contract-first development, an option that WCF also supports. In this case, a developer typically starts with a WSDL document describing the interface (i.e., the contract) that a service class must implement. Using a tool called svcutil, the developer can generate a skeleton service class directly from a WSDL definition.

Defining Data Contracts


·         A WCF service class specifies a service contract defining which of its methods are exposed to clients of that service. Each of those operations will typically convey some data, which means that a service contract also implies some kind of data contract describing the information that will be exchanged. In some cases, this data contract is defined implicitly as part of the service contract.
·          For services where every operation uses only simple types, it makes sense to define the data aspects of their contract implicitly within the service contract. There’s no need for anything else.
·         But services can also have parameters of more complex types, such as structures. In cases like this, an explicit data contract is required. Data contracts define how in-memory types are converted to a form suitable for transmission across the wire, a process known as serialization. In effect, data contracts are a mechanism for controlling how data is serialized.
·         In a WCF service class, a data contract is defined using the DataContract attribute. A class, structure, or other type marked with DataContract can have one or more of its members preceded by the DataMember attribute, indicating that this member should be included in a serialized value of this type. 


using System.Runtime.Serialization;
[DataContract]
struct ReservationInfo {
   [DataMember] public int vehicleClass;
   [DataMember] public int location;
   [DataMember] public string dates;
}
·    

            Nothing becomes part of either a service contract or a data contract by default. Instead, a developer must explicitly use the ServiceContract and DataContract attributes to indicate which types have WCF-defined contracts, and then explicitly specify which parts of those types are exposed to clients of this service using the OperationContract and DataMember attributes. One of WCF’s design tenets was that services should have explicit boundaries, so WCF is an opt-in technology. Everything a service makes available to its clients is expressly specified in the code.

Performance comparison between distributed technologies:


When we migrate distributed applications made with ASP.NET Web Services, WSE, .NET Enterprise Services and .NET Remoting to WCF, it will in almost all cases result in a performance boost:
Other Distributed Technologies
WCF Performance Advantage
ASP.NET Web Service
25%—50% faster
.NET Remoting
25% faster
WSE 2.0/3.0 implementations.
400% faster
.NET Enterprise Service
100% faster subject to the load.




WCF - Notes 1



·         Windows Communication Foundation (WCF) is a platform rich in features necessary for building distributed service-oriented applications. 
·         WCF is a service that exposes one or more endpoints.
·         Each of which exposes one or more service operations.
·         The endpoint of a service specifies an address where the service can be found.
·         A binding that contains the information that describes how a client must communicate with the service, and
·         A contract that defines the functionality provided by the service to its clients.
·         WCF allows creating clients that access services. Both the client and the service can run in pretty much any Windows process—WCF doesn’t define a required host. Wherever they run, clients and services can interact via SOAP, via a WCF-specific binary protocol, and in other ways.

WCF-based clients and services can run in any Windows process.

·         As the scenario described earlier suggests, WCF addresses a range of problems for communicating applications. Three things stand out, however, as WCF’s most important aspects:
·         Unification of the original .NET Framework communication technologies
·         Interoperability with applications built on other technologies
·         Explicit support for service-oriented development.

Rather than requiring different technologies for different communication styles, WCF provides a single unified solution.
·         An application built on WCF can interact with all of the following:
·         WCF-based applications running in a different process on the same Windows machine
·         WCF-based applications running on another Windows machine
·         Applications built on other technologies, such as Java EE application servers, that support standard Web services. These applications can be running on Windows machines or on machines running other operating systems, such as Sun Solaris, IBM z/OS, or Linux.
·         Messaging: SOAP is the foundation protocol for Web services, defining a basic envelope containing a header and a body. WS-Addressing defines additions to the SOAP header for addressing SOAP messages, which frees SOAP from relying on the underlying transport protocol, such as HTTP, to carry addressing information. The Message Transmission Optimization Mechanism (MTOM) defines an optimized transmission format for SOAP messages based on the XML-binary Optimized Packaging (XOP) specification.
·         Metadata: The Web Services Description Language (WSDL) defines a standard language for specifying services and various aspects of how those services can be used. WS-Policy allows specification of more dynamic aspects of a service’s behavior that cannot be expressed in WSDL, such as a preferred security option. WS-MetadataExchange allows a client to request descriptive information about a service, such as its WSDL and its policies, via SOAP. Beginning with the .NET Framework 4 release, WCF also supports WS-Discovery. This broadcast-based protocol lets an application find services available elsewhere on its local network.
·         Security: WS-Security, WS-Trust and WS-SecureConversation all define additions to SOAP messages for providing authentication, data integrity, data privacy and other security features.
·         Reliability: WS-ReliableMessaging defines additions to the SOAP header that allow reliable end-to-end communication, even when one or more SOAP intermediaries must be traversed.
·         Transactions: Built on WS-Coordination, WS-AtomicTransaction allows using two-phase commit transactions with SOAP-based exchanges.
·         Only WSE 3.0 can interoperate with WCF—earlier versions cannot. 

Every WCF service has three primary components:
·         A service class, implemented in C# or Visual Basic or another CLR-based language, that implements one or more methods.
·         A host process in which the service runs.
·         One or more endpoints that allow clients to access the service. All communication with a WCF service happens via the service’s endpoints.




References:

Thursday, 30 August 2012

WPF Architecture


WPF is built of three layers:

Layer1

Managed Layer

·         PresentationFramework.dll -: defines the layout etc
·         PresenationCore.dll : defines the control
·         WindowsBase.dll : defines the events, dispatcher , dependency properties
Layer 2
Unmanaged layer
·         Milcore.dll : Media Integration Library core , manages animation , videos etc
·         WindowsCodecs: manages the vector UI
Layer 3
Core API
·         Direct3D
·         User32
·         GDI



What is dispatcher and thread affinity in WPF?


When a windows application is loaded on the screen each control is handled using a win 32 handler.
Win32 Handle is very important for any Win32 applications. For every Win32 apps, Kernel maintains a Table which has entries to identify a memory address. A HANDLE is actually a DWORD (32 bit integer) which maps the memory address on the table. So if you get a HANDLE, you can easily locate the memory address it points to.  Each object that you have in Windows (like windows, buttons, mouse pointers, icon, menu, bitmap etc) has entries in the table and the object is traced using both internally by windows or by programs using those HANDLEs. Even though it is just an unsigned integer value, you should not edit the value, otherwise the HANDLE could not be used to point the object anymore.
WPF window is made up of two parts.

1.       Window area which is made up of Operating System Window
2.      Non - Window area which is inside a WPF window
WPF window has only one window handle (HWND) and each other controls are actually placed as content to the window and does not have any entry on Kernel table(no HWND) except of course Popup class in WPF. In this post I will try to cover the basis of HWND (for those of you who don't know) and later go on with what are the changes of it with WPF environment.
When WPF application starts, it actually creates two threads automatically. One is Rendering Thread, which is hidden from the programmer, so you cannot use the rendering thread directly from your program; while the other is Dispatcher Thread, which actually holds all the UI elements. So in other words, you might say Dispatcher is actually the UI thread which ties all the elements created within the WPF application. Conversely, WPF requires all the UI elements to be tied with Dispatcher thread, this is called Thread Affinity. 
Dispatcher is a class that handles thread affinity. It is actually a prioritized message loop through which all elements are channeled through. Every UIElement is derived from DispatcherObject which defines a property called Dispatcher which points to the UI thread. Thus from any other thread, if you want to invoke or access UI component, you need to Invoke using Dispatcher thread. DispatcherObject actually has two chief duties, to check and verify if the thread has access to the object.


Routed Events:


A routed event is an event that can invoke handlers in multiple listeners in an element tree , rather than the object who initially raised the event.
 In WPF, a typical example of control's hierarchy is root level Window object, than Grid object and then the other controls which are resides on Grid Control.



The concept of Routed Events comes into the picture when we want to handle an event, that is originated from some other control in the hierarchy.  Say for example if any user clicks the Button control, that event which is normally a Button_click event, can be raised by The Button, The Label, The Gird or The Window.

Types of Routed Events:

·         Direct Events
·         Bubbling Events
·         Tunneling Events
1.  Direct Events: Direct Events are very well known to .NET people who has worked on standard .NET controls.  A direct event gets raised by the control itself.  Say for example Button_click event which got raised by the Button control itself.
2.  Bubbling Events: Bubbling events are first raised by the control and then are raised by the controls in that control's hierarchy.  Taking our Button control example, If Button is clicked, first it will raise Button_click event, then the Grid event and at last the Window Event.
The below picture will clear all your doubts:


3.  Tunneling Events: The Tunneling Events are the opposite of the bubbling events as they are raised first by the root element in the hierarchy and then by the child elements.  Same as our previous example, First Window event will get raised, followed by the Grid Event and at last the Button_click event.



Dependency Objects:

Every WPF control is derived from DependencyObject. DependencyObject is a class that supportsDependencyProperty, a property system that is newly built in WPF.
A dependency property essentially means a property in one class can be used in other class.
For example the properties top and bottom are not defined in rectangle class but they can be used in rectangle class as

 Every object is derived fromDependencyObject and hence it can associate itself in various inbuilt features of WPF like EventTriggers,PropertyBindings, Animations, etc.
Every DependencyObject actually has an Observer or a List and declares 3 methods called ClearValue,SetValue and GetValue which are used to add/edit/remove those properties. Thus the DependencyPropertywill only create itself when you use SetValue to store something.

Difference between CLR properties and Dependency Properties

CLR property Syntax


private int count;
public int Count
{
   get
   {
      return count;
   }
   set
   {
      count = value;
   }
}

Dependency property syntax


//Registering Dependency Property
public static DependencyProperty PageSizeProperty =
DependencyProperty.RegisterAttached("PageSize",
typeof(int), typeof(AttachedPropertySample),
             new PropertyMetadata(25,
             new PropertyChangedCallback(OnPageSizePropertyChanged)));

//PageSize property declaration
public int PageSize
{
    get
    {
        return (int) GetValue(PageSizeProperty);
    }
    set
    {
        SetValue(PageSizeProperty, value);
    }
}

Major features of Dependency Properties are
·         Value Resolution
CLR property reads value directly from private member while dependency property dynamically resolves value when you call GetValue() method of dependency property. The GetValue and SetValue methods are inherited fromDependency Object. You can read more about Dependency Property here.

·         In Built Change Notification
Dependency provides change notification when its value has been changed. You can specify Call Back while registering dependency property so user will get notification. This is mainly used in Data Binding.

·         Value Inheritance
If you specify dependency property to top element it will inherited to all child elements until child element specifically override the property. Dependency property value is resolved at runtime when you call GetValue() method. 

Attached Events

The XAML language also defines a special type of event called an attached event. An attached event enables you to add a handler for a particular event to an arbitrary element. The element handling the event need not define or inherit the attached event, and neither the object potentially raising the event nor the destination handling instance must define or otherwise "own" that event as a class member.
The WPF input system uses attached events extensively. However, nearly all of these attached events are forwarded through base elements.


Object Hierarchy


There are quite a few objects in any WPF control. Let's discuss one by one as in the figure. (The abstract class is marked in ellipse while concrete class in Rectangles) 

  • ·         DispatcherObject: Mother of all WPF controls which takes care of UI thread
  • ·         DependencyObject: Builds the Observer for Dependency Properties
  • ·         Visual: Links between managed libraries and milcore
  • ·         UIElement: Adds supports for WPF features like layout, input, events, etc.
  • ·         FrameworkElement: Implementation of UIElement
  • ·         Shape: Base class of all the Basic Shapes
  • ·         Control: The UI elements that interact with the user. They can be Templated to change look.
  • ·         ContentControl: Baseclass of all controls that have single content
  • ·         ItemsControl: Baseclass for all controls that show a collection
  • ·         Panel: Baseclass of all panels which show one or more controls within it