Thursday, July 25, 2013

Dependency Injection


http://msdn.microsoft.com/en-us/library/ff921152(v=pandp.20).aspx

 public class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer(new BasicLogger());
            Customer customer2 = new Customer(new AdvancedLogger());

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public Customer(ILogger logger)
        {
            logger.WriteToLog("creating the customer");
        }
    }

    public interface ILogger
    {
        void WriteToLog(string text);
    }

    public class BasicLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine(text);
        }
    }

    public class AdvancedLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine("*** {0} ***", text);
        }
    }Problem
You have classes that have dependencies on services or components whose concrete type is specified at design time. In this example, ClassA has dependencies on ServiceA and ServiceB. Figure 1 illustrates this.
Ff921152.07e319ee-bf28-4695-a194-4ce8e467e90d(en-us,PandP.20).png

Figure 1 
ClassA has dependencies on ServiceA and ServiceB
This situation has the following constraints:
  • To replace or update the dependencies, you must change your classes' source code.
  • The concrete implementation of the dependencies must be available at compile time.
  • Your classes are difficult to test in isolation because they have a direct reference to their dependencies. This means that these dependencies cannot be replaced with stubs or mocks.
  • Your classes contain repetitive code for creating, locating, and managing their dependencies.

Forces

Any of the following conditions justifies using the solution described in this pattern:
  • You want to decouple your classes from their dependencies so that these dependencies can be replaced or updated with minimal or no changes to your classes' source code.
  • You want to be able to write classes that depend on classes whose concrete implementation is not known at compile time.
  • You want to be able to test your classes in isolation, without using the dependencies.
  • You want to decouple your classes from being responsible for locating and managing the lifetime of dependencies.

Solution

Do not instantiate the dependencies explicitly in your class. Instead, declaratively express dependencies in your class definition. Use a Builder object to obtain valid instances of your object's dependencies and pass them to your object during the object's creation and/or initialization. Figure 2 illustrates this.
Ff921152.81db980b-fa2d-4fe3-b6b6-f40995120159(en-us,PandP.20).png

Figure 2 
Conceptual view of the Dependency Injection pattern
Ff921152.note(en-us,PandP.20).gifNote:
Typically, you express dependencies on interfaces instead of concrete classes. This enables easy replacement of the dependency concrete implementation without modifying your classes' source code.
The following are the two main forms of dependency injection:
  • Constructor injection
  • Setter injection
In constructor injection, you use parameters of the object's constructor method to express dependencies and to have the builder inject it with its dependencies. In setter injection, the dependencies are expressed through setter properties that the builder uses to pass the dependencies to it during object initialization.

Implementation Using the Unity Application Block

The Dependency Injection pattern can be implemented in several ways. The Unity Application Block (Unity) provides a container that can be used for dependency injection. For more information about the Unity Application Block, see Unity Application Block.

Example

The NewsReaderPresenter class of the Stock Trader Reference Implementation (located at StockTraderRI.Modules.News\Article\NewsReaderPresenter.cs) uses constructor dependency injection to obtain a valid instance of a view that implements the INewsReaderView interface. The class definition is shown in the following code.
public class NewsReaderPresenter : INewsReaderPresenter
{
    private readonly INewsReaderView view;

    public NewsReaderPresenter(INewsReaderView view)
    {
        this.view = view;
    }

    public INewsReaderView View
    {
        get { return this.view; }
    }

    public void SetNewsArticle(NewsArticle article)
    {
        this.view.Model = article;
    }
}
Because the NewsReaderPresenter class uses dependency injection to obtain its dependencies, its dependencies can be replaced with mock implementations when testing. The following test methods, taken from the fixture file StockTraderRI.Modules.News.Tests\Article\NewsReaderPresenterFixture.cs, show how theNewsReaderPresenter class can be tested in isolation using mock implementations to replace the classes' dependencies and verify behavior.
[TestMethod]
public void SetNewsArticlesSetsViewModel()
{
    var view = new MockNewsReaderView();

    var presenter = new NewsReaderPresenter(view);

    NewsArticle article = new NewsArticle() { Title = "My Title", Body = "My Body" };
    presenter.SetNewsArticle(article);

    Assert.AreSame(article, view.Model);
}

Liabilities

The dependency injection pattern has the following liabilities:
  • There are more solution elements to manage.
  • You have to ensure that, before initializing an object, the dependency injection framework can resolve the dependencies that are required by the object.
  • There is added complexity to the source code; therefore, it is harder to understand.

Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.
So, you want to use DI to defer that choice to one that can be configured by the client.
This is some pseudocode (roughly based on Unity):
You create a logging interface:
public interface ILog
{
  void Log(string text);
}
then use this interface in your classes
public class SomeClass
{
  [Dependency]
  public ILog Log {get;set;}
}
inject those dependencies at runtime
public class SomeClassFactory
{
  public SomeClass Create()
  {
    var result = new SomeClass();
    DependencyInjector.Inject(result);
    return result;
  }
}
and the instance is configured in app.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name ="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
              Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <typeAliases>
      <typeAlias alias="singleton"
                 type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
    </typeAliases>
    <containers>
      <container>
        <types>
          <type type="MyAssembly.ILog,MyAssembly"
                mapTo="MyImplementations.SqlLog, MyImplementations">
            <lifetime type="singleton"/>
          </type>
        </types>
      </container>
    </containers>
  </unity>
</configuration>
Now if you want to change the type of logger, you just go into the configuration and specify another type.

Monday, June 10, 2013

WPF Threading and Dispatcher

1. Thread and Thread Pool
2. way to create Thread.
3. WPF and CheckAccess
4. Begin Invoke and Invoke
5.Notifier
6. Invoke Required
7.IDispatcher

Working With The WPF Dispatcher


Proper use of threads can greatly increase the responsiveness of your WPF applications. Unfortunately, you can't update any UI controls from a thread that doesn't own the control. In .NET 2.0, you used Control.Invoke(). Now, we've got something similar but more powerful - the Dispatcher. This tutorial will explain what the Dispatcher is and how to use it.
First of all, you need to know where the Dispatcher lives. Every Visual (Button, Textbox, Combobox, etc.) inherits fromDispacterObject. This object is what allows you to get a hold of the UI thread's Dispatcher.
The Dispatcher is why you can't directly update controls from outside threads. Anytime you update a Visual, the work is sent through the Dispatcher to the UI thread. The control itself can only be touched by it's owning thread. If you try to do anything with a control from another thread, you'll get a runtime exception. Here's an example that demonstrates this:
public partial class Window1 : Window
{
  public Window1()
  {
    InitializeComponent();

    CheckBox myCheckBox = new CheckBox();
    myCheckBox.Content = "A Checkbox";

    System.Threading.Thread thread = new System.Threading.Thread(
      new System.Threading.ThreadStart(
        delegate()
        {
          myCheckBox.IsChecked = true;
        }
    ));

    thread.Start();
  }
}
This code creates a Checkbox, then creates a thread which tries to change the checked state. This will fail because the Checkbox was created on a different thread than the one trying to modify it. If you run this code, you'll end up with this exception:
The calling thread cannot access this object because a different thread owns it.
So the question is, how do you update the Checkbox from this thread? Fortunately, the Dispatcher gives us the ability to Invoke onto its thread. Invoking probably looks really familiar if you've programmed in .NET 2.0. We actually have an in-depth tutorial on invoking that you might want to read. Below is code using the Dispatcher that will run and update the Checkbox without throwing an exception.
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        myCheckBox.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));
      }
  ));

  thread.Start();
}
Now we've introduced the Dispatcher object. The call to Invoke needs to take a few pieces of information. First is the priority you'd like your work executed with. Next is the delegate that contains the work you actually want to do. If your delegate takes parameters, the Invoke call will also accept an Object or Object[] to pass into the delegate function. It will also accept a timespan that limits the amount of time the Invoke call will wait to execute your code.
The call to Invoke will block until your function has been executed. Depending on the priority you've set, this might take a while. The Dispatcher also has the ability to invoke code asynchronously usingBeginInvoke. Let's look at the same example using BeginInvoke.
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        System.Windows.Threading.DispatcherOperation
          dispatcherOp = myCheckBox.Dispatcher.BeginInvoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));

        dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
      }
  ));

  thread.Start();
}

void dispatcherOp_Completed(object sender, EventArgs e)
{
  Console.WriteLine("The checkbox has finished being updated!");
}
BeginInvoke takes many of the same arguments as Invoke, but now returns a DispatcherOperationthat lets you keep track of the progress of your function. In this case, I simply hooked the Completed event that notifies me when the work has been completed. The DispatcherOperation object also lets you control the Dispatcher by changing its priority or aborting it all together.
As I mentioned above, we can limit the amount of time an Invoke is allowed to take my passing the Invoke call a TimeSpan structure. Here's an example that will wait 1 second for the queued function to complete:
public Window1()
{
  InitializeComponent();

  CheckBox myCheckBox = new CheckBox();
  myCheckBox.Content = "A Checkbox";

  System.Threading.Thread thread = new System.Threading.Thread(
    new System.Threading.ThreadStart(
      delegate()
      {
        myCheckBox.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.SystemIdle,
          TimeSpan.FromSeconds(1),
          new Action(
            delegate()
            {
              myCheckBox.IsChecked = true;
            }
        ));
      }
  ));

  thread.Start();
}
Unfortunately, there's no way to determine if the invoke finished or timed out from the outside. You can always put code inside the invoked function to determine if it executed.
All right, so we've got our dispatchers working and code is being executed where it's supposed to be. Invokes, however, are kind of an expensive process. What happens when your controls are being updated from both external threads and the main UI thread. How do you know if you're supposed to use Invoke? The Dispatcher object provides a function that tells you whether or not you have to use Invoke. In WinForms you call InvokeRequired on the actual control. In WPF, you call CheckAccess() on the Dispatcher object. CheckAccess() returns a boolean indicating whether or not you can modify the control without Invoking.
if (!myCheckBox.Dispatcher.CheckAccess())
{
  myCheckBox.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.Normal,
    new Action(
      delegate()
      {
        myCheckBox.IsChecked = true;
      }
  ));
}
else
{
  myCheckBox.IsChecked = true;
}
So now, before I invoke, I check to see if I even need to. If I do, I invoke the function, if I don't, I simply update the control directly.
As you can see, the Dispatcher provides a great deal of flexibility over the WinForms Invoke. There's a lot about WPF's dispatching model that we didn't touch in this tutorial. TheSystem.Windows.Threading namespace contains a lot more useful objects that extends the power of the dispatcher even further.


Saturday, June 8, 2013

WPF Interview Question and Answer part I



What is WPF?

The Windows Presentation Foundation is Microsofts next generation UI framework to create applications with a rich user experience. It is part of the .NET framework 3.0 and higher.

WPF combines application UIs, 2D graphics, 3D graphics, documents and multimedia into one single framework. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

What is the need of layout panels in WPF?

Layout of controls is critical to an applications usability. Arranging controls based on fixed pixel coordinates may work for an limited enviroment, but as soon as you want to use it on different screen resolutions or with different font sizes it will fail. WPF provides a rich set built-in layout panels that help you to avoid the common pitfalls.

What are the different types of layout panels in WPF?

There are mainly 5 types of layout panels in WPF. These are: 

Grid Panel
Stack Panel
Dock Panel
Wrap Panel
Canvas Panel

What is XAML

XAML (pronounced as Zammel) is a declarative XML-based language by which you can 
define object and properties in XML. XAML document is loaded by a XAML parser. 
XAML parser instantiates objects and set there properties. XAML describes objects, 
properties and there relation in between them. Using XAML you can create any kind of 
objects that means graphical or non-graphical. WPF parses the XAML document and 
instantiates the objects and creates the relation as defined by XAML.

What is Attached Properties
These are dependency properties that belong to one class but can be used in another. 
Consider the below code snippet:- 
<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> 
4 7 9 
Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas. 
Left is dependency property as it belongs the canvas class. It’s used by the Rectangle to 
specify its position within Canvas.

What is Routed Event
In a typical WPF application, it contains many elements. These elements exist in an element tree relationship with each other. A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

What are core adssembly of WPF
WindowsBase.dll:- It defines the core types constituting the infrastructure of WPF API. 

PresentationCore.dll:- Defines numerous types constituting foundation of WPF GUI layer. 

PresentationFoundation.dll:- It defines WPF control types, animation & multimedia support, data binding suport and other WPF services. 

Besides these three libraries WPF also uses an unmanaged binary called milcore.dll which acts as a bridge between WPF assemblies and DirectX runtime layer.

What is the use of System.Windows.Media namespace?
It is the root namespace to several other media related namespaces. It provides different types to work with animations, 3D rendering, text rendering and other multimedia services.