Showing posts with label Architecture. Show all posts
Showing posts with label Architecture. Show all posts

Wednesday, 30 January 2013

MVVM- An Introduction


What is MVVM?

MVVM is a UI design pattern.
 The main use of this pattern to remove make least View (the UI) less dependent on ViewModel (Business logic) and Model (data)
The view calls View model with actions and data. The View Model class sends data to model class.
So, view model acts as a bridge between Model and View.
Changes in Model is notified to view using the INotifyPropertyChange interface.

Advantages of using MVVM

  • Keeps code clean by separation of concerns.The view , looks after UI , ViewModel takes care of business logic and Model contains data.
  • Its easy to Design, Develop, Test and Maintain
  • The change is code has to do anything with UI , making it very easy to use in a collaborated development environment. 
  • Since all business logic is independent of UI , so re-usability of code increases.
  • Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.
  • "Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".
  • No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.
  • Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.

MVVM architecture

Following shows how data moves in MVVM from a higher level
This figure shows a granular detail of how view interacts with view model.



Frequently used words in MVVM

  • Data Binding :  Data binding is a mechanism to ensure that any change made to the data in a UI components is automatically carried over to the target ViewModel based on a predefined binding relationship. (and vice versa). Application developers only have to define the data binding relationship between UI component's attribute and the target object, it's usually a ViewModel, by data binding annotation expression.Typically, this means that they must implement the correct interfaces.

  • Data Templates : Data Templates describe the visual structure of a data object.Data Template is used  to specify the visualization of your data objects.DataTemplate objects are particularly useful when you are binding an ItemsControl such as a ListBox to an entire collection. Data Templates gives you a very flexible and powerful solution to replace the visual appearance of a data item in a control like ListBox, ComboBox or ListView. If you don't specify a data template, WPF takes the default template that is just a TextBlock. If you bind complex objects to the control, it just calls ToString() on it. Within a DataTemplate, the DataContext is set the data object. So you can easily bind against the data context to display various members of your data object.

  • Commands : In WPF and Silverlight, actions or operations that the user can perform through the UI are typically defined as commands.Commands provide a convenient way to represent actions or operations that can be easily bound to controls in the UI. They encapsulate the actual code that implements the action or operation and help to keep it decoupled from its actual visual representation in the view.Commands can be visually represented and invoked in many different ways by the user as they interact with the view. In most cases, they are invoked as a result of a mouse click, but they can also be invoked as a result of shortcut key presses, touch gestures, or any other input events. Controls in the view are data bound to the view model's commands so that the user can invoke them using whatever input event or gesture the control defines. Interaction between the UI controls in the view and the command can be two-way. In this case, the command can be invoked as the user interacts with the UI, and the UI can be automatically enabled or disabled as the underlying command becomes enabled or disabled.

  • Notifications :Notification is an interface that is used to ensure that the UI is kept up to date when the data changes in the view model, it should implement the appropriate change notification interface.If the view defines properties that can be data bound, it should implement the INotifyPropertyChanged interface. Implementing the INotifyPropertyChanged interface allows views to react to changes originated in models and view models. These changes are not limited to domain data shown in controls; they are also used to control the view, such as view model states that cause animations to be started or controls to be disabled.
 The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view.

We will see the various details of data binding, commanding etc in upcoming blogs.

Monday, 28 January 2013

Design Vs Architecture



  • Architecture is strategic, while Design is tactical.
  • Architecture comprises the frameworks, tools, programming paradigms, component-based software engineering standards, high-level principles.
  • Architecture and design are closely related; the main difference between them is really about which way we face.Architecture faces towards strategy, structure and purpose, towards the abstract. Design faces towards implementation and practice, towards the concrete.
  • Architecture without design does nothing: it can too easily remain stuck in an ‘ivory-tower’ world, seeking ever finer and more idealised abstractions. Design without architecture tends toward point-solutions that are optimised solely for a single task and context, often developed only for the current techniques and technologies, and often with high levels of hidden ‘technical debt’.
  • Both architecture and design are essential. We may only arrive at appropriate, useful, maintainable solutions when architecture and design are both in use and in appropriate balance.
  • While design is an activity concerned with local constraints, such as design patterns, programming idioms, and refactorings.
  • They are at the same time: different (1) stages, (2) areas of responsibility, and (3) levels of decision-making.
  • Architecture is the bigger picture: the choice of frameworks, languages, scope, goals, and high-level methodologies
  • Design is the smaller picture: the plan for how code will be organized; how the contracts between different parts of the system will look; the ongoing implementation of the project's methodologies and goals. Specification are written during this stage.
These two stages will seem to blend together for different reasons.
Smaller projects often don't have enough scope to separate out planning into these to stages.
  • A project might be a part of a larger project, and hence parts of both stages are already decided. (There are already existing databases, conventions, standards, protocols, frameworks, reusable code, etc.)
  • Newer ways of thinking about the SDLC somewhat rearrange this traditional approach. Design (architecture to a lesser extent) takes place throughout the SDLC on purpose. There are often more iterations where the whole process happens over and over.
  • Software development is complicated and difficult to plan anyway, but clients/managers/salespeople usually make it harder by changing goals and requirements mid-stream. Design and even architectural decisions must bemade later in the project whether that is the plan or not.
One of the reasons that good architects are relatively rare is that, to work well, the architecture must cover an ever-wider scope, linking across more and more domains, yet still remain grounded in the immediacy of everyday practice. Designers need only focus on the single task at hand (though it always helps if they pay attention to proven architecture principles such as re-use, re-purpose, consistency and so on).

Smart Client applications

Introduction:
Smart client when we divide them into words we get two words; 'smart' and 'client'.
In application development terms 'client' application is a application which runs in your local system and takes full advantage of the local hardware resources and advantages which are featured in your local operating system.
Now comes the term 'smart', smart in general terms is someone who knows by itself what to do? There is no necessity for someone to tell a smart person what to do.
So, a smart client is an application ,which runs in your local system and is designed so as to know what it has to do at a given point of time. To be more specific, it gives application access to local hardware when not connected to internet and when connected allows application to take full advantages of remote services and information available.
I can say smart client = thick client + thin client.
Now we have introduced two terms thick client ; thin client.
Let us know explain these terms one by one.
Thick clients:
Thick clients are also known as rich client applications.
Thick/Rich client applications are the windows or more generally speaking desktop applications which we use more often.These were very popular in mid- nineties. Thick client applications take advantage of local hardware resources and features of the client operating systems.
Advantages of thick clients:
Thick client/ Rich client applications have following advantages:
a. High qulaity
b. Responsive user experience
c. Easy to maintain
d. Take full capabilities of local hardware resources.
e. Esay to develop.( Developer friendly ;) applications)
Disadvantages of thick clients:
a. Applications are stand-alone and operate on the client computer.
b. Integration between applications is limited .
c. At times features are limited to the features provided by .
d. Transfer of data between applications is very difficult.
e. These applications are very difficult to deploy and maintain.
f.One application can easily break another application if an incompatible shared component or library is deployed.Thi s is also known as application fragility.
g. New versions of the application are made available by redeploying the entire application, which can increase an application fragility problem.
Thin Clients:
Thin clients are browser-based applications . HTML and .NET and java Web applications can be called as thin clients. These applications are deployed and updated on a central Web server. These applications solve a lot of disadvantages of thick clients for example the interaction between different systems in network is very good, even the deployment and upgradation of these applications are relatively simpler and easy.
Advantages of thin clients:
a. Thin client model allows companies to expose their applications to a large and diverse external audience. Retail and banking sites can take advantages of these applications.
b. It is easier to deploy and maintain thin client applications.
Disadvantages of thin clients:
a. Thin applications are browser based . These applications must have a network connection at all times.
b.Usability of these applications are not that very good as these applications cannot take advantages of local operating systems.
c. Latency period of the application is quite high. That is the wait period of the application when the client requests for a data, server process the data and sends it back is quite high.
d. Donot support ocassionally connected applications.
Smart Client Applications
As discussed earlier, Smart client applications are designed to combine the benefits of a rich client application with the benefits of a thin client applications.
Advantages of smart client applications
a. Make use of local hardware resources
b. Make use of network resources
c. Easier for update installations
d. supports ocassionally supported clients.
e. We can develop smart windows application, smart office applications and mobile smart client applications.
Challenges of smart client applications
a. Creating the architecture of a smart client applications is very difficult.
b. Handling data in smart client applications is a real difficulty because in smart client application data resides both in the client and web server.
Following are various types of smart clent applications:
a. Windows smart client applications
b. Office smart client applications
c. Mobile smart client applications
Windows smart client applications:
Windows smart client application are suitable when we need an application that has to be deployed and accessed like a desktop-type application.
Windows smart client applications typically provide the msot of their functionality as a stand-alone application but when needed these applications can integrate themseleves with other applications when required. These applications provide functionality that can be tuned to particular tasks . These applications take the very advantage of rich UI of thick clients.
Windows smart client applications are most suitable for applications that run on desktop, laptop, or tablet PCs. These applications are not tightly associated with a particular document or
document type.
Office smart clients:
I have not worked much on office smart clients , so I maynot be able to explain office smart clients completly.
But briefly speaking , office smart clients are Microsoft office applications which can provide context-sensitive data as the user works ,these applications also provide workflow and task guidance, data analysis, collaboration, reporting etc. smart office applications are exposed by Web services and help transform data into useful information.
Mobile smart client applications:
Mobile smart client applications are used to provide stable connected and disconnected access to mobile users, laptop and tablet PC users. These are similar to Windows smart client applications with a small difference that these applications are developed in Micrsoft .NET compact framework.More or less these applications are similar to Windows smart client applications.

Conclusion:
At this age , mobile client users are increasing so smart clients are taking up the thick client applications , because using smart client it is easier to address these client who are connected/disconnected based on business use.

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