Archive

Author Archive

Factory pattern Vs Abstract Factory pattern


Factory: A factory that creates objects that derive from a particular base class.

Abstract factory: A factory that creates other factories, and these factories in turn create objects derived from base classes. You do this because you often don’t just want to create a single object (as with Factory method) – rather, you want to create a collection of related objects.

Real Life Example. (Easy to remember)

Factory

Imagine you are constructing a house and you approach a carpenter for a door. You give the measurement for the door and your requirements, and he will construct a door for you. In this case, the carpenter is a factory of doors. Your specifications are inputs for the factory, and the door is the output or product from the factory.

Abstract Factory

Now, consider the same example of the door. You can go to a carpenter, or you can go to a plastic door shop or a PVC shop. All of them are door factories. Based on the situation, you decide what kind of factory you need to approach. This is like an Abstract Factory.

 

Categories: C# Tags: ,

Dependency Properties in WPF

August 19, 2012 1 comment

Introduction

When you begin to develop appliations with WPF, you will soon stumble across DependencyProperties. They look quite similar to normal .NET properties, but the concept behind is much more complex and powerful.

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

The advantages of dependency properties are

Reduced memory footprint
It’s a huge dissipation to store a field for each property when you think that over 90% of the properties of a UI control typically stay at its initial values. Dependency properties solve these problems by only store modified properties in the instance. The default values are stored once within the dependency property.

Value inheritance
When you access a dependency property the value is resolved by using a value resolution strategy. If no local value is set, the dependency property navigates up the logical tree until it finds a value. When you set the FontSize on the root element it applies to all textblocks below except you override the value.

Change notification
Dependency properties have a built-in change notification mechanism. By registering a callback in the property metadata you get notified, when the value of the property has been changed. This is also used by the databinding.

Value resolution strategy

Every time you access a dependency property, it internally resolves the value by following the precedence from high to low. It checks if a local value is available, if not if a custom style trigger is active,… and continues until it founds a value. At last the default value is always available.
The magic behind it

Each WPF control registers a set of DependencyProperties to the static DependencyProperty class. Each of them consists of a key – that must be unique per type – and a metadata that contain callbacks and a default value.

All types that want to use DependencyProperties must derive from DependencyObject. This baseclass defines a key, value dictionary that contains local values of dependency properties. The key of an entry is the key defined with the dependency property.
When you access a dependency property over its .NET property wrapper, it internally calls GetValue(DependencyProperty) to access the value. This method resolves the value by using a value resolution strategy that is explained in detail below. If a local value is available, it reads it directly from the dictionary. If no value is set if goes up the logical tree and searches for an inherited value. If no value is found it takes the default value defined in the property metadata. This sequence is a bit simplified, but it shows the main concept.

Value Changed Callback

The change notification callback is a static method, that is called everytime when the value of the TimeProperty changes. The new value is passed in the EventArgs, the object on which the value changed is passed as the source.

private static void OnCurrentTimePropertyChanged(DependencyObject source,
DependencyPropertyChangedEventArgs e)
{
MyClockControl control = source as MyClockControl;
DateTime time = (DateTime)e.NewValue;
// Put some update logic here…
}

Readonly DependencyProperties

Some dependency property of WPF controls are readonly. They are often used to report the state of a control, like the IsMouseOver property. Is does not make sense to provide a setter for this value.

Maybe you ask yourself, why not just use a normal .NET property? One important reason is that you cannot set triggers on normal .NET propeties.

Creating a read only property is similar to creating a regular DependencyProperty. Instead of calling DependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you a DependencyPropertyKey. This key should be stored in a private or protected static readonly field of your class. The key gives you access to set the value from within your class and use it like a normal dependency property.

Second thing to do is registering a public dependency property that is assigned to DependencyPropertyKey.DependencyProperty. This property is the readonly property that can be accessed from external.

// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
DependencyProperty.RegisterReadOnly(“IsMouseOver”,
typeof(bool), typeof(MyClass),
new FrameworkPropertyMetadata(false));

// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty =
IsMouseOverPropertyKey.DependencyProperty;

// .NET Property wrapper
public int IsMouseOver
{
get { return (bool)GetValue(IsMouseoverProperty); }
private set { SetValue(IsMouseOverPropertyKey, value); }
}

Listen to dependency property changes

If you want to listen to changes of a dependency property, you can subclass the type that defines the property and override the property metadata and pass an PropertyChangedCallback. But an much easier way is to get the DependencyPropertyDescriptor and hookup a callback by calling AddValueChanged()

DependencyPropertyDescriptor textDescr = DependencyPropertyDescriptor.
FromProperty(TextBox.TextProperty, typeof(TextBox));

if (textDescr!= null)
{
textDescr.AddValueChanged(myTextBox, delegate
{
// Add your propery changed logic here…
});
}

Problem with Dependency Properties

1. Some people argues that the use of DependencyProperties the code extremely ugly. I myself think that this is exaclty the same.
2. DependencyObjects are not marked as serializable
3. A DependencyObject has thread affinity – it can only be accessed on the thread on which it was created


  .

Attached Properties

 

Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it’s not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Canvas>
<Button Canvas.Top=”20″ Canvas.Left=”20″ Content=”Click me!”/>
</Canvas>

public static readonly DependencyProperty TopProperty =
DependencyProperty.RegisterAttached(“Top”,
typeof(double), typeof(Canvas),
new FrameworkPropertyMetadata(0d,
FrameworkPropertyMetadataOptions.Inherits));

public static void SetTop(UIElement element, double value)
{
element.SetValue(TopProperty, value);
}

public static double GetTop(UIElement element)
{
return (double)element.GetValue(TopProperty);
}

How to clear a local value

Because null is also a valid local value, there is the constant DependencyProperty.UnsetValue that describes an unset value.

button1.ClearValue( Button.ContentProperty );

Categories: WPF Tags:

The Object Class


The Object class is a special type that is the base class for all other classes and types, including the value types. It defines a set of methods that are therefore inherited by every other type that is defined within the .NET framework class library.

What is the Object Class?

The Object class, held in the System namespace, is the base class for all classes and data types, including the value types. It is the class at the root of the .NET framework class library’s entire type hierarchy.

System.Object defines several public and protected methodsthat, due to inheritance, are automatically made available to all .NET classes, structures and types, including any classes or structures that you create yourself. If you create a class with no base class specified, it will implicitly derive functionality from Object.

Often developers overlookthe Object class. However, its importance is significant and the complexities if its members should be understood.

object = Object

The C# programming language declares a data type named “object”. This type is simply an alias for System.Object and so the two terms are interchangeable; they differ in capitalisation but not functionality.

Object methods

The Object class defines seven base methods. Of these, five are public methods that are available to be called by external objects. The remaining two methods are protected. These are only accessible internally and to derived classes. Each of the methods is described in the following sections.

Public Methods


Equals Method

The Equals method is used to compare two objects to determine if they are equal. The comparison of the objects depends upon their types. For the value types, a bit-by-bit comparison of the two values is made. If they are a perfect match, the method returns true. If not, the method returns false.

When comparing reference types, the values of the two references are compared. Only when both references are pointing to the same object does the method return true. If the properties of two objects are a perfect match but the references are different, the method returns false.

The Equals method can be overridden in a subclass. This permits the behaviour to be changed so that it is more appropriate. For example, in the case of the string data type, Equals is overridden so that a comparison of two strings can be made as though they were value types. Even when the two strings contain different references, if the underlying characters match, the method returns true.

string s1 = "Hello";
string s2 = "Hello";
bool result = s1.Equals(s2); // result = true

The Equals method is available in two forms. The instance version is shown in the above example. In this case, the method requires a single parameter containing the item to be compared to the invoking object. A static version of the method is also available. This requires two parameters, one for each of the items to be compared. The above example could therefore be rewritten as:

string s1 = "Hello";
string s2 = "Hello";
bool result = string.Equals(s1, s2); // result = true

When overriding the behaviour of the Equals method, there are several rules that must be followed to ensure correct operation. These are:

  • A call to x.Equals(x), where “x” is a variable of the class in question, must return true. The only exception to this rule is in the comparison of floating point data, where you may decide that a variable containing NaN (not a number) is not equivalent to itself. NB: Interestingly, the floating point types in the .NET framework return true when comparing NaN to NaN using the Equals method, but false when using the == operator. The == operator matches theIEC 60559:1989 specification whilst the Equals method does not.
  • A call to x.Equals(y) must return the same result as a call to y.Equals(x).
  • The expression “x.Equals(y) && y.Equals(z)” must only return true if x.Equals(z) returns true.
  • If x and y are not modified, successive calls to x.Equals(y) must return consistent results.
  • A call to x.Equals(null) must return false.
  • If the == operator is overloaded, the Equals method must be overridden to provide matching functionality, except in the case of floating point value types.
  • If Equals is overridden, the GetHashCode method must also be overridden for compatibility. Otherwise,Hashtables may function incorrectly.
  • If a class implements the IComparable interface, the Equals method should be overridden.
  • The Equals method must not throw exceptions.

GetHashCode Method

The GetHashCode method provides an algorithm to generate a hash code for an object. Hash codes are used when creatinghash tables to permit objects to be found quickly in large sets of data. The GetHashCode method is used by the Hashtable collection class for this purpose.

The GetHashCode method returns an integer containing the hash code for an object. The value is not unique and should not be used as an identifier or for any purposes other than when using a hashing function. This is particularly relevant when using multiple versions of the .NET framework as the hashing algorithms for classes vary between versions, leading to different results for identical objects.

You can see examples of the return values by executing the following code. The results shown are generated using version 3.5 of the .NET framework and may differ from those you see.

int i = 10;
float f = 10;
string s = "Hello";
int result;
result = i.GetHashCode(); // result = 10
result = f.GetHashCode(); // result = 1092616192
result = s.GetHashCode(); // result = -694847

The GetHashCode method can be overridden. When doing so, the following guidelines should be followed:

  • If GetHashCode is overridden, the Equals method must also be overridden for compatibility. Otherwise, Hashtables may function incorrectly.
  • The value returned from the hashing algorithm must be appropriate for value types. Two values that would be considered equal when using the Equals method must return the same hash code.
  • The hash codes generated by the algorithm should be well distributed amongst the available range of integer return values. If the algorithm produces many duplicates or similar values, the performance of Hashtables will be impacted.
  • The hashing algorithm should be as fast and efficient as possible to avoid performance issues with Hashtables.
  • The GetHashCode method must not throw exceptions.

GetType Method

The GetType method simply returns the type of the object that invokes it. This is useful when using polymorphismtechniques as the type of the underlying object can be identified, even if held in a variable declared as another type. For example, if “Dog” is a subclass of “Animal” and a Dog object is being held in an Animal variable, the type returned will still be Dog. The method is also used for reflection.

The type is returned in a System.Type object. A detailed description of the System.Type class is beyond the scope of this article. For demonstration purposes we will simply output a string representation of the type to the console.

string s = "Hello";
Console.WriteLine(s.GetType()); // Outputs "System.String"
object o = s;
Console.WriteLine(o.GetType()); // Outputs "System.String"

ReferenceEquals Method

The ReferenceEquals method is a static member of the Object class. It is used with reference types to determine if two instances of a class contain the same reference. If the references are the same, the method returns true. If the references are different, the method returns false, even if the values of the two instances match. If the two items to be compared are both null, the resultant value is true. If they are two value types, the result is always false.

The method is called with two parameters, each holding one of the references to be compared.

object o1 = new object();
object o2 = new object();
object o3 = o1;
bool result;
result = object.ReferenceEquals(o1, o2); // result = false
result = object.ReferenceEquals(o1, o3); // result = true
int i1 = 1;
int i2 = 1;
result = object.ReferenceEquals(i1, i2); // result = false

ToString Method

 

The ToString method is probably the most well-known and used member of the Object class. This method returns a human-readable, string representation of the current object. The default behaviour is to return the fully qualified name of the object’s type. However, this can be overridden to provide a more useful value, as in the case of thenumeric types where the ToString method is overridden and overloaded to allow the creation of formatted numeric strings.

The base version of ToString provided by the Object class accepts no parameters.

object o = new object();
Console.WriteLine(o.ToString()); // Outputs "System.Object"

Protected Methods


Finalize Method

The Finalize method is the first protected method of the Object class that we will consider. This method permits objects to clean up any resources and perform any other activities that are required before an object that is no longer required is reclaimed by the garbage collector. Finalizers in C# are declared as destructors.

The Finalize method cannot be overridden and may not be called during the normal execution of a program. The method is called automatically after an object is no longer accessible, due to all references to it being removed or going out of scope. However, there is no guarantee of the exact execution time of the Finalize method and certainly no assumption that it will run immediately should be made. It is also possible that the finalizer will not run at all if another Finalize method is blocked indefinitely or if the program terminates abnormally.

If two objects become inaccessible at the same time, there is no guarantee of the order in which their finalizers will be called. This is still the case when one of the objects refers to the other.

Classes must implement a destructor when they use unmanaged resources such as database connections or file handles. These resources cannot be reclaimed by the garbage collector and will otherwise not be correctly released. However, in these cases, the class should also implement the IDisposable interface.

MemberwiseClone Method

The MemberwiseClone method is used to create a shallow copy of an object. A shallow copy of an object contains the same values and references as the original. For value type members, this is a bitwise copy of the member data. For reference type members the reference only is copied, meaning that the copy and the original are references to the same object. The method is called with no parameters and returns the cloned object as a System.Object that may be cast to the correct type as required.

Categories: C# Tags:

WPF Custom Control

August 12, 2012 2 comments

The differences between CustomControls and UserControls

WPF has two concepts of controls: UserControls and CustomControls. But what’s the difference between them? In this article I try to list the characteristics of each of them to help you to choose the right type for your project.

UserControl (Composition)

  • Composes multiple existing controls into a reusable “group”
  • Consists of a XAML and a code behind file
  • Cannot be styled/templated
  • Derives from UserControl

This example of an “RGB user control” composes three labels and textboxes as well as a color field together to an reusable part. The logic in the code behind file adds a Color DependencyProperty that gets and sets the resolved color.

CustomControl (Extending an existing control)

  • Extends an existing control with additional features
  • Consists of a code file and a default style in Themes/Generic.xaml
  • Can be styled/templated
  • The best approach to build a control library

This example of a “Numeric up/down” control is an extension of a textbox. The up and down buttons are defined in the default template of the control and wired up in the OnApplyTemplate() override in the logic part of the control. The ControlTemplate can easily be exchanged by another that has the up,down buttons aligned left for example.

How to Create a WPF Custom Control

Step 1: Open VS 2010 and create a blank solution and  name it as ‘WPF_CustomControl’..

Step 2: To this solution, add a new WPF Custom Control Library Project and name it as ‘WPF40_FileUploadCustomControl’. This project will have ‘Themes’ folder containing ‘Generic.Xaml’. Also this project will contain ‘CustomControl1.cs’ code file. This file will contain necessary business logic of the control.

Step 3: Rename ‘CustomControl1.cs’ to ‘FileUploadCustomControl.cs’. Add the following code in ‘Generic.xaml’:

<ResourceDictionary

    xmlns:local=”clr-namespace:WPF40_FileUploadCustomControl”>
    <Style TargetType=”{x:Type local:FileUploadCustomControl}”>
        <Setter Property=”Template”>
            <Setter.Value>
                <ControlTemplate TargetType=”{x:Type local:FileUploadCustomControl}”>
                    <Border Background=”{TemplateBinding Background}”
                            BorderBrush=”{TemplateBinding BorderBrush}”
                            BorderThickness=”{TemplateBinding BorderThickness}”>
                        <StackPanel Orientation=”Horizontal”
                                          Width=”200″>
                            <TextBox Name=”TXT_FILE_NAME” Width=”150″></TextBox>
                            <Button Name=”BTN_BROWSE_FILE” Width=”50″Content=”Browse”></Button>
                        </StackPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
The above code defines only the control template which contains ‘StackPanel’, ‘TextBox’ and ‘Button’ visual elements. One important here is that since this is just a resource dictionary, you cannot define any event on the elements.
 –
Step 4: Now it’s time to define the business logic. Make sure that in the ‘FileUploadCustomControl.cs’ file, the class ‘CustomControl1’ is renamed to ‘FileUploadCustomControl’. Also rename the constructor. The code in the constructor will be as below:
 
static FileUploadCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FileUploadCustomControl),
 
newFrameworkPropertyMetadata(typeof(FileUploadCustomControl)));
}
Define TextBox and Button at class level as shown below. This will be instantiated using the controls names set in the template XAML above in Step 3.
 
TextBox txtFileName = null;
Button btnBrowse = null;
 .
Since this control is used to upload the image and this will be displayed in the container of this control, I have declared the following dependency property name ‘FileName’.
 .
public string FileName
{
    get { return (string)GetValue(FileNameProperty); }
    set { SetValue(FileNameProperty, value); }
}
 
// Using a DependencyProperty as the backing store for FileName. This enables animation, styling, binding, etc…
public static readonly DependencyProperty FileNameProperty =
    DependencyProperty.Register(“FileName”, typeof(string),typeof(FileUploadCustomControl),
        new FrameworkPropertyMetadata(string.Empty,FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
 .
Since the control has to expose the ‘FileName’ property to its container application, the CC should declare the following routed event:
 
public event RoutedEventHandler FileNameChanged
{
    add { AddHandler(FileNameChangedEvent, value); }
    remove { RemoveHandler(FileNameChangedEvent, value); }
}
 
public static readonly RoutedEvent FileNameChangedEvent =
    EventManager.RegisterRoutedEvent(“FileNameChanged”,
    RoutingStrategy.Bubble, typeof(RoutedEventHandler),typeof(FileUploadCustomControl));
 
Now it’s time to construct the control, so override ‘OnApplyTemplate()’ method as below:
 
public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
 
    txtFileName = this.Template.FindName(“TXT_FILE_NAME”, this) as TextBox;
 
    btnBrowse = this.Template.FindName(“BTN_BROWSE_FILE”, this) as Button;
    btnBrowse.Click += new RoutedEventHandler(btnBrowse_Click);
    txtFileName.TextChanged += new TextChangedEventHandler(txtFileName_TextChanged);
}
 .
The above method shows how the Button and TextBox objects are created using the respective control name from the ‘Generic.xaml’.
Write the following code in the Browse button event. This code will launch the open dialog box and then the file can be selected.
 
void btnBrowse_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog fileDIalog = new OpenFileDialog();
    fileDIalog.Filter = “Image files (*.bmp, *.jpg)|*.bmp;*.jpg|Doc Files (*.doc;*.docx)|*.doc;*.docx”;
    fileDIalog.AddExtension = true;
    if (fileDIalog.ShowDialog() == true)
    {
        FileName = fileDIalog.FileName;
        txtFileName.Text = FileName;
    }
}
 .
Write the following code in the TextChanged event of the textbox, here e.Handled = True’ will stop the event at the control level itself and the ‘FileNameChanged’ is raised. This event is then handled in the container WPF application.
 
void txtFileName_TextChanged(object sender, TextChangedEventArgs e)
{
    e.Handled = true;
 
    base.RaiseEvent(new RoutedEventArgs(FileNameChangedEvent));
}
 .
That’s it. Build the control.

Create a WPF Application for using the Custom Control.

Step 1: In the same solution, add a new WPF Application and name it as ‘WPF40_FileUploadContainer’.

Step 2: In this project, add the reference of the ‘WPF40_FileUploadCustomControl’ library so that the control can be used.
Step 3: Open MainWindow.Xaml and register the control in XAML (Gray Marked). Use the control in XAML and subscribe the ‘FileNameChanged’ event (Green Marked) as shown below :
<Window x:Class=”WPF40_FileUploadContainer.MainWindow”
        xmlns:ccFileUpload=”clr-namespace:WPF40_FileUploadCustomControl;assembly=WPF40_FileUploadCustomControl”
        Title=”MainWindow” Height=”481″ Width=”667″>
    <Grid>
        <Grid.RowDefinitions>
           <RowDefinition Height=”112*” />
            <RowDefinition Height=”330*” />
        </Grid.RowDefinitions>
        <ccFileUpload:FileUploadCustomControl x:Name=”fileUpload”
                                              Width=”600″ Margin=”12,29,34,0″Height=”56″
                                              VerticalAlignment=”Top”
                                              FileNameChanged=”fileUpload_FileNameChanged”></ccFileUpload:FileUploadCustomControl>
        <Image Grid.Row=”1″ Height=”264″ HorizontalAlignment=”Left” Margin=”30,24,0,0″Name=”imgUploaded” Stretch=”Fill” VerticalAlignment=”Top” Width=”589″ />
    </Grid>
</Window>
Step 4: Open MainWindow.Xaml.cs and write the following code in it:
 
private void fileUpload_FileNameChanged(object sender, RoutedEventArgs e)
{
    ImageSource imgSrc = new BitmapImage(new Uri(fileUpload.FileName));
    imgUploaded.Source = imgSrc;
}
 
The above code represents the event handled on the container for the Custom Control.
Step 5: Run the application.
Once the WPF window runs, click on ‘Browse’ button and the open dialog box will be displayed. Select a ‘.jpg’ file and click on ‘Open’ button. The selected image will be displayed as shown below:
WPF Custom Control
Conclusion:  
 .
WPF allows us to develop specialty controls using Custom Control. Before deciding to use a Custom Control, one must think about,
.

What functionality will be performed by the control?

This will help in selecting Visual Elements for designing UI for the control, along with the business logic for it.
.
What data will be either consumed by the control or published from the control?
This will help in defining dependency properties for the control. These properties will be used in DataBinding.
.
When will this control publish the data to its container?
This will help in defining routed event for the controls.
Categories: WPF Tags:

Bubbling and Tunneling


Let’s say you have a simple application that looks as follows:

 

 

 

 

 

 

 

 

 

 

 

When you hover over the Log-In button, which elements do you think receive notification of something happening?

One of the elements that gets notified is the button, as you would expect. What you may not realize is that the event propagates beyond the button and to other elements in its visual tree such as its parent, its parent’s parent, and so on.

That roundabout way of having events routed through the parents is what makes events in WPF and Silverlight known as routed events.

Let’s look at an example of a simple application broken down into its visual tree:

exampleHierarchy2

The application portrayed is fairly simple. It contains a Button and Label (aka TextBlock in Silverlight) control nested inside a Grid control which, in turn, is hosted by our overall Window/UserControl control. When you hover over your button, since the hover is a routed event, your MouseEnter event gets recognized by your Grid and Window/UserControl controls.

Peers are not affected. You interacting with your Button will have no affect on the Label control that is your peer. This is true even if your Label is overlapping your button. Since your Label/TextBlock is never hovered over and it is a peer of your button, it doesn’t partake in this event handling festivity!

Routing Strategies: Bubbling, Tunneling, and Direct
While I mentioned that your events get recognized by the parents, the order by which they get recognized depends on the routing strategy used. The two most popular routing strategies are bubbling and tunneling.

Bubbling Strategy
In a bubbling strategy, you start with the control that originated the event and traverse up the tree:

downUp

This is what I described earlier where the order of the elements that get notified by an event on the button goes from Button to Grid to Window. The tunneling strategy works in the opposite way.

Tunneling Strategy
With tunneling, when an event is fired, you go all the way to the root and traverse down until you hit the control that originated the event:

upDown

In WPF, you can specify which routing strategy to use based on the type of event you are listening for. If you look at the list of events your element supports, if it has the word “Preview” in front of it such as PreviewMouseLeftButtonDown, you are dealing with a tunneling event:

[ example of tunneling events ]

For most of the other events that do not have Preview in front of them, you are dealing with bubbling events.

Silverlight only supports bubbling, so you will always have events that move up to the root as opposed to starting with the root and moving down.

Tunneling and bubbling events processing sequence

The UIElement class defines many routed events for keyboard, mouse, and stylus input. Most of these are bubbling events, but many of them are paired with a tunneling event. Tunneling events can be easily identified because, by convention, they are named with a Previewprefix. These events, also by convention, are raised immediately before their bubbling counterpart. For example, PreviewMouseMove is a tunneling event raised before the MouseMove bubbling event.

Example :

The idea behind having a pair of events for various activities is to give elements a chance to effectively cancel or otherwise modify an event that’s about to occur. By convention, WPF’s built-in elements only take action in response to a bubbling event (when a bubbling and tunneling pair is defined), ensuring that the tunneling event lives up to its “”preview” name. For example, imagine you want to implement aTextBox that restricts its input to a certain pattern or regular expression (such as a phone number or zip code). If you handle TextBox‘s KeyDown event, the best you can do is remove text that has already been displayed inside the TextBox. But if you handle TextBox‘s PreviewKeyDown event instead, you can mark it as “handled” to not only stop the tunneling but also stop the bubbling KeyDown event from being raised. In this case, the TextBox will never receive the KeyDown notification and the current character will not get displayed

Where is the event for handling the pressing of a mouse’s middle button?

If you browse through the various mouse events exposed by UIElement or ContentElement, you’ll find events for MouseLeftButtonDownMouseLeftButtonUp,MouseRightButtonDown, and MouseRightButtonUp (as well as the tunneling Preview version of each event). But what about the additional buttons present on some mice?

This information can be retrieved via the more generic MouseDown and MouseUp events (which also have Preview counterparts). The arguments passed to such event handlers include a MouseButton enumeration that indicates which button’s state just changed: LeftRightMiddleXButton1, or XButton2. A corresponding MouseButtonStateenumeration indicates whether that button is Pressed or Released.

Categories: WPF Tags: ,

Association, Aggregation, Composition


en we have only one relationship between objects, that is called Association. Aggregation and Composition both are specialized form of Association. Composition is again specialize form of Aggregation.

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with single teacher and single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation is a specialize form of Association where all object have their own lifecycle but there is ownership and child object can not belongs to another parent object. Let’s take an example of Department and teacher. A single teacher can not belongs to multiple departments, but if we delete the department teacher object will not destroy. We can think about “has-a” relationship.

Composition is again specialize form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object dose not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different house if we delete the house room will automatically delete. Let’s take another example relationship between Questions and options. Single questions can have multiple options and option can not belong to multiple questions. If we delete questions options will automatically delete.

Categories: C# Tags: , ,

Select Find Nth Highest Salary Record In Sql Server


1st Method :

SELECT TOP 1 [Salary]
FROM
(
SELECT DISTINCT TOP N [Salary]
FROM [dbo].[Employee]
ORDER BY [Salary] DESC
) temp
ORDER BY [Salary]

 
2nd Method :

SELECT * FROM
(
SELECT DENSE_RANK() OVER(ORDER BY [Salary] DESC)AS RowId, *
FROM [dbo].[Employee]
) AS e1
WHERE e1.RowId = N

 
http://csharpdotnetfreak.blogspot.com/2011/09/select-nth-highest-record-sql-server.html
Categories: SQL Tags:

Database Normalization


Normalization is the process of organizing data in a database. This includes creating tables and establishing relationships between those tables according to rules designed both to protect the data and to make the database more flexible by eliminating redundancy and inconsistent dependency.

Redundant data wastes disk space and creates maintenance problems. If data that exists in more than one place must be changed, the data must be changed in exactly the same way in all locations. A customer address change is much easier to implement if that data is stored only in the Customers table and nowhere else in the database.

What is an “inconsistent dependency”? While it is intuitive for a user to look in the Customers table for the address of a particular customer, it may not make sense to look there for the salary of the employee who calls on that customer. The employee’s salary is related to, or dependent on, the employee and thus should be moved to the Employees table. Inconsistent dependencies can make data difficult to access because the path to find the data may be missing or broken.

There are a few rules for database normalization. Each rule is called a “normal form.” If the first rule is observed, the database is said to be in “first normal form.” If the first three rules are observed, the database is considered to be in “third normal form.” Although other levels of normalization are possible, third normal form is considered the highest level necessary for most applications.

As with many formal rules and specifications, real world scenarios do not always allow for perfect compliance. In general, normalization requires additional tables and some customers find this cumbersome. If you decide to violate one of the first three rules of normalization, make sure that your application anticipates any problems that could occur, such as redundant data and inconsistent dependencies.

The following descriptions include examples.

First Normal Form

  • Eliminate repeating groups in individual tables.
  • Create a separate table for each set of related data.
  • Identify each set of related data with a primary key.

Do not use multiple fields in a single table to store similar data. For example, to track an inventory item that may come from two possible sources, an inventory record may contain fields for Vendor Code 1 and Vendor Code 2.

What happens when you add a third vendor? Adding a field is not the answer; it requires program and table modifications and does not smoothly accommodate a dynamic number of vendors. Instead, place all vendor information in a separate table called Vendors, then link inventory to vendors with an item number key, or vendors to inventory with a vendor code key.

Second Normal Form

  • Create separate tables for sets of values that apply to multiple records.
  • Relate these tables with a foreign key.

Records should not depend on anything other than a table’s primary key (a compound key, if necessary). For example, consider a customer’s address in an accounting system. The address is needed by the Customers table, but also by the Orders, Shipping, Invoices, Accounts Receivable, and Collections tables. Instead of storing the customer’s address as a separate entry in each of these tables, store it in one place, either in the Customers table or in a separate Addresses table.

Third Normal Form

  • Eliminate fields that do not depend on the key.

Values in a record that are not part of that record’s key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table.

For example, in an Employee Recruitment table, a candidate’s university name and address may be included. But you need a complete list of universities for group mailings. If university information is stored in the Candidates table, there is no way to list universities with no current candidates. Create a separate Universities table and link it to the Candidates table with a university code key.

EXCEPTION: Adhering to the third normal form, while theoretically desirable, is not always practical. If you have a Customers table and you want to eliminate all possible interfield dependencies, you must create separate tables for cities, ZIP codes, sales representatives, customer classes, and any other factor that may be duplicated in multiple records. In theory, normalization is worth pursing. However, many small tables may degrade performance or exceed open file and memory capacities.

It may be more feasible to apply third normal form only to data that changes frequently. If some dependent fields remain, design your application to require the user to verify all related fields when any one is changed.


Other Normalization Forms

Fourth normal form, also called Boyce Codd Normal Form (BCNF), and fifth normal form do exist, but are rarely considered in practical design. Disregarding these rules may result in less than perfect database design, but should not affect functionality.

Normalizing an Example Table

These steps demonstrate the process of normalizing a fictitious student table.

  1. Unnormalized table:
    Student# Advisor Adv-Room Class1 Class2 Class3
    1022 Jones 412 101-07 143-01 159-02
    4123 Smith 216 201-01 211-02 214-01

     

  2. First Normal Form: No Repeating GroupsTables should have only two dimensions. Since one student has several classes, these classes should be listed in a separate table. Fields Class1, Class2, and Class3 in the above records are indications of design trouble.Spreadsheets often use the third dimension, but tables should not. Another way to look at this problem is with a one-to-many relationship, do not put the one side and the many side in the same table. Instead, create another table in first normal form by eliminating the repeating group (Class#), as shown below:
    Student# Advisor Adv-Room Class#
    1022 Jones 412 101-07
    1022 Jones 412 143-01
    1022 Jones 412 159-02
    4123 Smith 216 201-01
    4123 Smith 216 211-02
    4123 Smith 216 214-01

     

  3. Second Normal Form: Eliminate Redundant DataNote the multiple Class# values for each Student# value in the above table. Class# is not functionally dependent on Student# (primary key), so this relationship is not in second normal form.The following two tables demonstrate second normal form:Students:
    Student# Advisor Adv-Room
    1022 Jones 412
    4123 Smith 216

    Registration:

    Student# Class#
    1022 101-07
    1022 143-01
    1022 159-02
    4123 201-01
    4123 211-02
    4123 214-01

     

  4. Third Normal Form: Eliminate Data Not Dependent On KeyIn the last example, Adv-Room (the advisor’s office number) is functionally dependent on the Advisor attribute. The solution is to move that attribute from the Students table to the Faculty table, as shown below:Students:
    Student# Advisor
    1022 Jones
    4123 Smith

    Faculty:

    Name Room Dept
    Jones 412 42
    Smith 216 42
Categories: SQL Tags:

Difference between String and StringBuffer/StringBuilder


Well, the most important difference between String and StringBuffer/StringBuilder is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.

So suppose you declare a String object:

String myString = “Hello”;

Next, you want to append “Guest” to the same String. What do you do?

myString = myString + ” Guest”;

When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.

Now isn’t that a performance issue?

Yes, it definitely is.

Then how do you make your string operations efficient?

By using StringBuffer or StringBuilder.

How would that help?

Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.

Finally, whats the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence ofsynchronization.

Categories: C# Tags: , ,

Optimize SQL Queries (Theory an Practice)


This article assumes you already know SQL and want to optimize queries.

The reasons to optimize

Time is money and people don’t like to wait so programs are expected to be fast.

In Internet time and client/server programming, it’s even more true because suddenly a lot of people are waiting for the DB to give them an answer which makes response time even longer.

Even if you use faster servers, this has been proven to be a small factor compared to the speed of the algorithm used. Therefore, the solution lies in optimization.

Theory of optimization

There are many ways to optimize Databases and queries. My method is the following.

Look at the DB Schema and see if it makes sense

Most often, Databases have bad designs and are not normalized. This can greatly affect the speed of your Database. As a general case, learn the 3 Normal Forms and apply them at all times. The normal forms above 3rd Normal Form are often called de-normalization forms but what this really means is that they break some rules to make the Database faster.

What I suggest is to stick to the 3rd normal form except if you are a DBA (which means you know subsequent forms and know what you’re doing). Normalization after the 3rd NF is often done at a later time, not during design.

 Only query what you really need

Filter as much as possible

Your Where Clause is the most important part for optimization.

Select only the fields you need

Never use “Select *” — Specify only the fields you need; it will be faster and will use less bandwidth.

Be careful with joins

Joins are expensive in terms of time. Make sure that you use all the keys that relate the two tables together and don’t join to unused tables — always try to join on indexed fields. The join type is important as well (INNER, OUTER,… ).

Optimize queries and stored procedures (Most Run First)

Queries are very fast. Generally, you can retrieve many records in less than a second, even with joins, sorting and calculations. As a rule of thumb, if your query is longer than a second, you can probably optimize it.

Start with the Queries that are most often used as well as the Queries that take the most time to execute.

Add, remove or modify indexes

If your query does Full Table Scans, indexes and proper filtering can solve what is normally a very time-consuming process. All primary keys need indexes because they makes joins faster. This also means that all tables need a primary key. You can also add indexes on fields you often use for filtering in the Where Clauses.

You especially want to use Indexes on Integers, Booleans, and Numbers. On the other hand, you probably don’t want to use indexes on Blobs, VarChars and Long Strings.

Be careful with adding indexes because they need to be maintained by the database. If you do many updates on that field, maintaining indexes might take more time than it saves.

In the Internet world, read-only tables are very common. When a table is read-only, you can add indexes with less negative impact because indexes don’t need to be maintained (or only rarely need maintenance).

Move Queries to Stored Procedures (SP)

Stored Procedures are usually better and faster than queries for the following reasons:

Stored Procedures are compiled (SQL Code is not), making them faster than SQL code.
SPs don’t use as much bandwidth because you can do many queries in one SP. SPs also stay on the server until the final results are returned.
Stored Procedures are run on the server, which is typically faster.
Calculations in code (VB, Java, C++, …) are not as fast as SP in most cases.
It keeps your DB access code separate from your presentation layer, which makes it easier to maintain (3 tiers model).

Remove unneeded Views

Views are a special type of Query — they are not tables. They are logical and not physical so every time you run select * from MyView, you run the query that makes the view and your query on the view.

If you always need the same information, views could be good.

If you have to filter the View, it’s like running a query on a query — it’s slower.

Tune DB settings

You can tune the DB in many ways. Update statistics used by the optimizer, run optimization options, make the DB read-only, etc… That takes a broader knowledge of the DB you work with and is mostly done by the DBA.

Using Query Analysers

In many Databases, there is a tool for running and optimizing queries. SQL Server has a tool called the Query Analyser, which is very useful for optimizing. You can write queries, execute them and, more importantly, see the execution plan. You use the execution to understand what SQL Server does with your query.

 

Optimization in Practice

 

Example 1:

I want to retrieve the name and salary of the employees of the R&D department.

Original:

Query : Select * From Employees

In Program : Add a filter on Dept or use command : if Dept = R&D–

Corrected :

Select Name, Salary From Employees Where Dept = R&D–

In the corrected version, the DB filters data because it filters faster than the program.

Also, you only need the Name and Salary, so only ask for that.

The data that travels on the network will be much smaller, and therefore your performances will improve.

Example 2 (Sorting):

Original:

Select Name, Salary

From Employees

Where Dept = ‘R&D’

Order By Salary

Do you need that Order By Clause? Often, people use Order By in development to make sure returned data are ok; remove it if you don’t need it.

If you need to sort the data, do it in the query, not in the program.

Example 3:

Original:

For i = 1 to 2000

Call Query : Select salary From Employees Where EmpID = Parameter(i)

Corrected:

Select salary From Employees Where EmpID >= 1 and EmpID <= 2000

The original Query involves a lot of network bandwidth and will make your whole system slow.

You should do as much as possible in the Query or Stored Procedure. Going back and forth is plain stupid.

Although this example seems simple, there are more complex examples on that theme.

Sometimes, the processing is so great that you think it’s better to do it in the code but it’s probably not.

Sometimes, your Stored Procedure will be better off creating a temporary table, inserting data in it and returning it than going back and forth 10,000 times. You might have a slower query that saves time on a greater number of records or that saves bandwidth.

Example 4 (Weak Joins):

You have two tables Orders and Customers. Customers can have many orders.

Original:

Select O.ItemPrice, C.Name

From Orders O, Customers C

Corrected:

Select O.ItemPrice, C.Name

From Orders O, Customers C

Where O.CustomerID = C.CustomerID

In that case, the join was not there at all or was not there on all keys. That would return so many records that your query might take hours. It’s a common mistake for beginners.

Corrected 2:

Depending on the DB you use, you will need to specify the Join type you want in different ways.

In SQL Server, the query would need to be corrected to:

Select O.ItemPrice, C.Name

From Orders O INNER JOIN Customers C ON O.CustomerID = C.CustomerID

Choose the good join type (INNER, OUTER, LEFT, …).

Note that in SQL Server, Microsoft suggests you use the joins like in the Corrected 2 instead of the joins in the Where Clause because it will be more optimized.

Example 5 (Weak Filters):

This is a more complicated example, but it illustrates filtering at its best.

We have two tables — Products (ProductID, DescID, Price) and Description(DescID, LanguageID, Text). There are 100,000 Products and unfortunately we need them all.

There are 100 languages (LangID = 1 = English). We only want the English descriptions for the products.

We are expecting 100 000 Products (ProductName, Price).

First try:

Select D.Text As ProductName, P.Price

From Products P INNER JOIN Description D On P.DescID = D.DescID

Where D.LangID = 1

That works but it will be really slow because your DB needs to match 100,000 records with 10,000,000 records and then filter that Where LangID = 1.

The solution is to filter On LangID = 1 before joining the tables.

Corrected:

Select D.Text As ProductName, P.Price

From (Select DescID, Text From Description Where D.LangID = 1) D

INNER JOIN Products P On D.DescID = P.DescID

Now, that will be much faster. You should also make that query a Stored Procedure to make it faster.

Example 6 (Views):

Create View v_Employees AS

Select * From Employees

Select * From v_Employees

This is just like running Select * From Employees twice.

You should not use the view in that case.

If you were to always use the data for employees of R&D and would not like to give the rights to everyone on that table because of salaries being confidential, you could use a view like that:

Create View v_R&DEmployees AS

Select Name, Salary From Employees Where Dept = 1

(Dept 1 is R&D).

You would then give the rights to View v_R&DEmployees to some people and would restrict the rights to Employees table to the DBA only.

That would be a possibly good use of views.

Conclusion

I hope this will help you make your queries faster and your databases more optimized. This should make your program look better and can possibly mean money, especially for high load web applications where it means your program can serve more transactions per hour and you often get paid by transaction.

While you can put the above examples to practice in your database of choice, the preceding tips are especially true for major Databases like Oracle or SQL Server.


****************************************************************************************************

SQL Tuning/SQL Optimization Techniques:

1) The sql query becomes faster if you use the actual columns names in SELECT statement instead of than ‘*’.

For Example: Write the query as

SELECT id, first_name, last_name, age, subject FROM student_details;

Instead of:

SELECT * FROM student_details;

 

2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
For Example: Write the query as

SELECT subject, count(subject)
FROM student_details
WHERE subject != ‘Science’
AND subject != ‘Maths’
GROUP BY subject;

Instead of:

SELECT subject, count(subject)
FROM student_details
GROUP BY subject
HAVING subject!= ‘Vancouver’ AND subject!= ‘Toronto’;

 

3) Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
For Example: Write the query as

SELECT name
FROM employee
WHERE (salary, age ) = (SELECT MAX (salary), MAX (age)
FROM employee_details)
AND dept = ‘Electronics’;

Instead of:

SELECT name
FROM employee
WHERE salary = (SELECT MAX(salary) FROM employee_details)
AND age = (SELECT MAX(age) FROM employee_details)
AND emp_dept = ‘Electronics’;

 

4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.

For Example: Write the query as

Select * from product p
where EXISTS (select * from order_items o
where o.product_id = p.product_id)

Instead of:

Select * from product p
where product_id IN
(select product_id from order_items

 

5) Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
For Example: Write the query as

SELECT d.dept_id, d.dept
FROM dept d
WHERE EXISTS ( SELECT ‘X’ FROM employee e WHERE e.dept = d.dept);

Instead of:

SELECT DISTINCT d.dept_id, d.dept
FROM dept d,employee e
WHERE e.dept = e.dept;

 

6) Try to use UNION ALL in place of UNION.
For Example: Write the query as

SELECT id, first_name
FROM student_details_class10
UNION ALL
SELECT id, first_name
FROM sports_team;

Instead of:

SELECT id, first_name, subject
FROM student_details_class10
UNION
SELECT id, first_name
FROM sports_team;

 

7) Be careful while using conditions in WHERE clause.
For Example: Write the query as

SELECT id, first_name, age FROM student_details WHERE age > 10;

Instead of:

SELECT id, first_name, age FROM student_details WHERE age != 10;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE ‘Chan%’;

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE SUBSTR(first_name,1,3) = ‘Cha’;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE first_name LIKE NVL ( :name, ‘%’);

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE first_name = NVL ( :name, first_name);

Write the query as

SELECT product_id, product_name
FROM product
WHERE unit_price BETWEEN MAX(unit_price) and MIN(unit_price)

Instead of:

SELECT product_id, product_name
FROM product
WHERE unit_price >= MAX(unit_price)
and unit_price <= MIN(unit_price)

Write the query as

SELECT id, name, salary
FROM employee
WHERE dept = ‘Electronics’
AND location = ‘Bangalore’;

Instead of:

SELECT id, name, salary
FROM employee
WHERE dept || location= ‘ElectronicsBangalore’;

Use non-column expression on one side of the query because it will be processed earlier.

Write the query as

SELECT id, name, salary
FROM employee
WHERE salary < 25000;

Instead of:

SELECT id, name, salary
FROM employee
WHERE salary + 10000 < 35000;

Write the query as

SELECT id, first_name, age
FROM student_details
WHERE age > 10;

Instead of:

SELECT id, first_name, age
FROM student_details
WHERE age NOT = 10;

8) Use DECODE to avoid the scanning of same rows or joining the same table repetitively. DECODE can also be made used in place of GROUP BY or ORDER BY clause.
For Example: Write the query as

SELECT id FROM employee
WHERE name LIKE ‘Ramesh%’
and location = ‘Bangalore’;

Instead of:

SELECT DECODE(location,’Bangalore’,id,NULL) id FROM employee
WHERE name LIKE ‘Ramesh%’;

9) To store large binary objects, first place them in the file system and add the file path in the database.

10) To write queries which provide efficient performance follow the general SQL standard rules.

a) Use single case for all SQL verbs
b) Begin all SQL verbs on a new line
c) Separate all words with a single space
d) Right or left aligning verbs within the initial SQL verb

Categories: SQL Tags:

Lock, Monitor, Mutex, Semaphore

April 17, 2012 1 comment

Locking

Exclusive locking is used to ensure that only one thread can enter particular sections of code at a time. The two main exclusive locking constructs are lock and Mutex. Of the two, the lock construct is faster and more convenient.Mutex, though, has a niche in that its lock can span applications in different processes on the computer.

Let’s start with the following class:

class ThreadUnsafe
{
  static int _val1 = 1, _val2 = 1;

  static void Go()
  {
    if (_val2 != 0) Console.WriteLine (_val1 / _val2);
    _val2 = 0;
  }
}

This class is not thread-safe: if Go was called by two threads simultaneously, it would be possible to get a division-by-zero error, because _val2 could be set to zero in one thread right as the other thread was in between executing the if statement and Console.WriteLine.

Here’s how lock can fix the problem:

class ThreadSafe
{
  static readonly object _locker = new object();
  static int _val1, _val2;

  static void Go()
  {
    lock (_locker)
    {
      if (_val2 != 0) Console.WriteLine (_val1 / _val2);
      _val2 = 0;
    }
  }
}

Only one thread can lock the synchronizing object (in this case, _locker) at a time, and any contending threads areblocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis (a caveat is that nuances in the behavior of Windows and the CLR mean that the fairness of the queue can sometimes be violated). Exclusive locks are sometimes said to enforceserialized access to whatever’s protected by the lock, because one thread’s access cannot overlap with that of another. In this case, we’re protecting the logic inside the Go method, as well as the fields _val1 and _val2.

Monitor.Enter and Monitor.Exit

C#’s lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with atry/finally block. Here’s (a simplified version of) what’s actually happening within the Go method of the preceding example:

Monitor.Enter (_locker);
try
{
  if (_val2 != 0) Console.WriteLine (_val1 / _val2);
  _val2 = 0;
}
finally { Monitor.Exit (_locker); }

Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.

Mutex

Mutex is like a C# lock, but it can work across multiple processes. In other words, Mutex can be computer-wideas well as application-wide.

Acquiring and releasing an uncontended Mutex takes a few microseconds — about 50 times slower than a lock.

With a Mutex class, you call the WaitOne method to lock and ReleaseMutex to unlock. Closing or disposing aMutex automatically releases it. Just as with the lock statement, a Mutex can be released only from the same thread that obtained it.

A common use for a cross-process Mutex is to ensure that only one instance of a program can run at a time. Here’s how it’s done:

class OneAtATimePlease
{
  static void Main()
  {
    // Naming a Mutex makes it available computer-wide. Use a name that's
    // unique to your company and application (e.g., include your URL).

    using (var mutex = new Mutex (false, "oreilly.com OneAtATimeDemo"))
    {
      // Wait a few seconds if contended, in case another instance
      // of the program is still in the process of shutting down.

      if (!mutex.WaitOne (TimeSpan.FromSeconds (3), false))
      {
        Console.WriteLine ("Another app instance is running. Bye!");
        return;
      }
      RunProgram();
    }
  }

  static void RunProgram()
  {
    Console.WriteLine ("Running. Press Enter to exit");
    Console.ReadLine();
  }
}

If running under Terminal Services, a computer-wide Mutex is ordinarily visible only to applications in the same terminal server session. To make it visible to all terminal server sessions, prefix its name with Global\.

Semaphore

A semaphore is like a nightclub: it has a certain capacity, enforced by a bouncer. Once it’s full, no more people can enter, and a queue builds up outside. Then, for each person that leaves, one person enters from the head of the queue. The constructor requires a minimum of two arguments: the number of places currently available in the nightclub and the club’s total capacity.

A semaphore with a capacity of one is similar to a Mutex or lock, except that the semaphore has no “owner” — it’sthread-agnostic. Any thread can call Release on a Semaphore, whereas with Mutex and lock, only the thread that obtained the lock can release it.

There are two functionally similar versions of this class: Semaphore and SemaphoreSlim. The latter was introduced in Framework 4.0 and has been optimized to meet the low-latency demands of parallel programming. It’s also useful in traditional multithreading because it lets you specify acancellation token when waiting. It cannot, however, be used for interprocess signaling.

Semaphore incurs about 1 microsecond in calling WaitOne or ReleaseSemaphoreSlim incurs about a quarter of that.

Semaphores can be useful in limiting concurrency — preventing too many threads from executing a particular piece of code at once. In the following example, five threads try to enter a nightclub that allows only three threads in at once:

class TheClub      // No door lists!
{
  static SemaphoreSlim _sem = new SemaphoreSlim (3);    // Capacity of 3

  static void Main()
  {
    for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);
  }

  static void Enter (object id)
  {
    Console.WriteLine (id + " wants to enter");
    _sem.Wait();
    Console.WriteLine (id + " is in!");           // Only three threads
    Thread.Sleep (1000 * (int) id);               // can be here at
    Console.WriteLine (id + " is leaving");       // a time.
    _sem.Release();
  }
}

1 wants to enter
1 is in!
2 wants to enter
2 is in!
3 wants to enter
3 is in!
4 wants to enter
5 wants to enter
1 is leaving
4 is in!
2 is leaving
5 is in!

If the Sleep statement was instead performing intensive disk I/O, the Semaphore would improve overall performance by limiting excessive concurrent hard-drive activity.

Semaphore, if named, can span processes in the same way as a Mutex.

Categories: C# Tags: , , ,

ThreadPool


A thread pool takes away all the need to manage your threads – all you have to do is essentially say “hey! someone should go do this work!”, and a thread in the process’ thread pool will pick up the task and go execute it. And that is all there is to it. Granted, you still have to keep threads from stepping on each other’s toes, and you probably care about when these ‘work items’ are completed – but it is at least a really easy way to queue up a work item.

In fact, working with the ThreadPool is so easy, I’m going to throw all the code at you at once. Below is a pretty simple test app that gives 5 (or NumThreads) work items to the ThreadPool, waits for them all to complete, and then prints out all the answers. I will walk through the code step by step below:

 

using System;
using System.Threading;namespace ThreadPoolTest
{
class Program
{
private const int NumThreads = 5;

private static int[] inputArray;
private static double[] resultArray;
private static ManualResetEvent[] resetEvents;

private static void Main(string[] args)
{
inputArray = new int[NumThreads];
resultArray = new double[NumThreads];
resetEvents = new ManualResetEvent[NumThreads];

Random rand = new Random();
for (int s = 0; s < NumThreads; s++)
{
inputArray[s] = rand.Next(1,5000000);
resetEvents[s] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)s);
}

Console.WriteLine(“Waiting…”);

WaitHandle.WaitAll(resetEvents);

Console.WriteLine(“And the answers are: “);
for (int i = 0; i < NumThreads; i++)
Console.WriteLine(inputArray[i] + ” -> ” + resultArray[i]);
}

private static void DoWork(object o)
{
int index = (int)o;

for (int i = 1; i < inputArray[index]; i++)
resultArray[index] += 1.0 / (i * (i + 1));

resetEvents[index].Set();
}
}
}

 

We have three arrays at the top of the program: one for input to the work items (inputArray), one for the results (resultArray), and one for the ManualResetEvents (resetEvents). The first two are self explanatory, but what is aManualResetEvent? Well, it is an object that allows one thread to signal another thread when something happens. In the case of this code, we use these events to signal the main thread that a work item has been completed.

So we initialize these arrays, and then we get to a for loop, which is where we will be pushing out these work items. First, we make a random value for the initial input (cause random stuff is always more fun!), then we create aManualResetEvent with its signaled state initially set to false, and then we queue the work item. Thats right, all you have to do to push a work item out for the ThreadPool to do is call ThreadPool.QueueUserWorkItem.

So what are we queuing here? Well, we are saying that a thread in the thread pool should run the method DoWork, with the argument s. Any method that you want to queue up for the thread pool to run needs to take one argument, an object, and return void. The argument will end up being whatever you passed in as the second argument to theQueueUserWorkItem call – and in this case is the ‘index’ of this work item (the index in the various arrays that it needs to work with). And it makes sense that the method would have to return void – because it isn’t actually returning ‘to’ anything, it is running out there all on its own as a separate thread.

So what are we doing in this DoWork function? Not that much in this case, just a simple summation. The important part is the very last call of the function, which is hit when all the work for this work item is done –resetEvents[index].Set(). This triggers the ManualResetEvent for this work item – signaling the main thread that the work is all done here.

Back up in main thread land, after it has pushed all these work items onto the ThreadPool queue, we hit the very important call WaitHandle.WaitAll(resetEvents). This causes the main thread to block here until all theManualResetEvent objects in the resetEvents array signal. When all of them have signaled, that means that all the work units have been completed, and so we continue on and print out all the results. The results change because we are seeding with random values, but here is one example output:

 

Waiting…
And the answers are:
3780591 -> 0.991001809831479
3555614 -> 0.991163782231558
2072717 -> 0.989816715560308
2264396 -> 0.989982111762391
544144 -> 0.99066981542858

 

Pretty simple, eh? There are a couple things to note, though. The default thread pool size for a process is 25 threads, and while you can change this number, this resource is not infinite. If all of the threads in the pool are currently occupied with other tasks, new work items will be queued up, but they won’t get worked on until one of the occupied threads finishes its current task. This generally isn’t a problem unless you are giving the pool very large quantities of work. And really, you should never assume that a task is executed immediately after you queue it, because there is no guarantee of that at all.

That’s it for this intro to thread pools in C#. If there are any questions, leave them below – especially if they push on the more advanced aspects of threads and thread pools (cause then I’ll have an excuse to write some more threading tutorials!).

Categories: C# Tags:

EventWaitHandler: AutoResetEvent vs. ManualResetEvent


WaitHandler
Threads can communicate using WaitHandlers by signaling. Mutex, Semapore and EventWaitHandle are derived from WaitHandle class.

EventWaitHandle 
There are two types of EventWaitHandlers. AutoResetEvent and ManualResetEvent. AutoResetEvent lets one waiting thread at a time when Set() is called but ManualResetEvent lets all waiting threads to pass by when Set() is called. ManualResetEvent starts blocking when Reset() is called.

AutoResetEvent
This acts like a turnstile which lets one at a time. When a thread hits WaitOne(), it waits till some other thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). For every Set() call from another thread, one thread will pass the turnstile.

I have created a simple application to test this. There are two buttons to span a thread DoWork. DoWork has WaitOne call and it blocks threads. Third button calls Set() to release one thread at a time. Click first two buttons to span thread and click third button twice to release blocked threads.

private EventWaitHandle wh = new AutoResetEvent(false);
private void DoWork()
{
    Console.WriteLine(Thread.CurrentThread.Name + ": Waiting for Set() notification");
    // Wait for notification
    //
    wh.WaitOne();
    Console.WriteLine(Thread.CurrentThread.Name + ": Notified");
}
private void buttonCreateThreadOne_Click(object sender, EventArgs e)
{
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
    a.Start();
}
private void buttonCreateSecondThread_Click(object sender, EventArgs e)
{
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
    b.Start();
}
private void buttonReleaseOneThread_Click(object sender, EventArgs e)
{
    wh.Set();
}

 

Please note that the code after WaitOne call in DoWork is not thread safe. A call to Set will let next waiting thread to enter even the first thread is still executing the code.

 

ManualResetEvent
This is like a gate which lets more than one at a time. When a thread hits WaitOne(), it waits till someother thread calls Set(). Take a look at the following picture. Thread1, Thread2 and Thread3 are waiting after calling WaitOne(). When Set is called from another thread, all waiting thereads will pass the gate.

Code snippet to illustrate the above.

private void buttonFirstThread_Click(object sender, EventArgs e)
{
    Thread a = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    a.Name = "A";
    a.Start();
}
private void buttonSecondThread_Click(object sender, EventArgs e)
{
    Thread b = new Thread(DoWork);
    // You can name the thread!.. for debugging purpose
    b.Name = "B";
    b.Start();
}
private void buttonCallSet_Click(object sender, EventArgs e)
{
    wh.Set();
}
private void buttonCallReset_Click(object sender, EventArgs e)
{
    wh.Reset();
}
Categories: C#, WPF Tags: ,

User-defined function in SQL


Functions in programming languages are subroutines used to encapsulate frequently performed logic. Any code that must perform the logic incorporated in a function can call the function rather than having to repeat all of the function logic

CREATE FUNCTION CubicVolume
— Input dimensions in centimeters.
(@CubeLength decimal(4,1), @CubeWidth decimal(4,1),
@CubeHeight decimal(4,1) )
RETURNS decimal(12,3) — Cubic Centimeters.
AS
BEGIN
RETURN ( @CubeLength * @CubeWidth * @CubeHeight )
END

A user-defined function that returns a table can also replace stored procedures that return a single result set. The table returned by a user-defined function can be referenced in the FROM clause of a Transact-SQL statement, whereas stored procedures that return result sets cannot. For example, fn_EmployeesInDept is a user-defined function that returns a table and can be invoked by a SELECT statement:

SELECT *
FROM tb_Employees AS E,
dbo.fn_EmployeesInDept(‘shipping’) AS EID
WHERE E.EmployeeID = EID.EmployeeID
This is an example of a statement that creates a function in the Northwind database that will return a table:

CREATE FUNCTION LargeOrderShippers ( @FreightParm money )
RETURNS @OrderShipperTab TABLE
(
ShipperID int,
ShipperName nvarchar(80),
OrderID int,
ShippedDate datetime,
Freight money
)
AS
BEGIN
INSERT @OrderShipperTab
SELECT S.ShipperID, S.CompanyName,
O.OrderID, O.ShippedDate, O.Freight
FROM Shippers AS S
INNER JOIN Orders AS O ON (S.ShipperID = O.ShipVia)
WHERE O.Freight > @FreightParm
RETURN
END

 Difference between Stored Procedure and Functions

1. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
2. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.

3. Inline UDF’s can be though of as views that take parameters and can be used in JOINs and other Rowset operations.

4. Stored Procedure retuns more than one value at a time while funtion returns only one value at a time.

5. We can call the functions in sql statements (select max(sal) from emp). where as sp is not so.

6. Function do not return the images,text whereas sp returns all.

7. Function and sp both can return the values. But function returns 1 value only. Procedure can return multiple values(max. 1024) we can select the fields from function. in the case of procdure we cannot select the fields.

8. Functions MUST return a value, procedures need not be.

9. You can have DML(insert, update, delete) statements in a function. But, you cannot call such a function in a SQL query.eg: suppose, if u have a function that is updating a table.. you can’t call that function in any sql query.

10. SP can call function but vice-versa not possible.

Categories: SQL Tags:

Clustered and Non-Clustered Index in SQL


1. Introduction

We all know that data entered in the tables are persisted in the physical drive in the form of database files. Think about a table, say Customer (For any leading bank India), that has around 16 million records. When we try to retrieve records for two or three customers based on their customer id, all 16 million records are taken and comparison is made to get a match on the supplied customer ids. Think about how much time that will take if it is a web application and there are 25 to 30 customers that want to access their data through internet. Does the database server do 16 million x 30 searches? The answer is no because all modern databases use the concept of index.

2. What is an Index

Index is a database object, which can be created on one or more columns (16 Max column combination). When creating the index will read the column(s) and forms a relevant data structure to minimize the number of data comparisons. The index will improve the performance of data retrieval and adds some overhead on data modification such as create, delete and modify. So it depends on how much data retrieval can be performed on table versus how much of DML (InsertDelete and Update) operations.

In this article, we will see creating the Index.

3. First Create Two Tables

To explain these constraints, we need two tables. First, let us create these tables. Run the below scripts to create the tables. Copy paste the code on the new Query Editor window, then execute it.

CREATE TABLE Student(StudId smallint, StudName varchar(50), Class tinyint);
CREATE TABLE TotalMarks(StudentId smallint, TotalMarks smallint);
Go

Note that there are no constraints at present on these tables. We will add the constraints one by one.

4. Primary Key Constraint

A table column with this constraint is called as the key column for the table. This constraint helps the table to make sure that the value is not repeated and also no null entries. We will mark the StudId column of the Studenttable as primary key. Follow these steps:

  1. Right click the student table and click on the modify button.
  2. From the displayed layout, select the StudId row by clicking the Small Square like button on the left side of the row.
  3. Click on the Set Primary Key toolbar button to set the StudId column as primary key column.

Pic01.JPG

Now this column does not allow null values and duplicate values. You can try inserting values to violate these conditions and see what happens. A table can have only one Primary key. Multiple columns can participate on the primary key column. Then, the uniqueness is considered among all the participant columns by combining their values.

5. Clustered Index

The primary key created for the StudId column will create a clustered index for the Studid column. A table can have only one clustered index on it.

When creating the clustered index, SQL server 2005 reads the Studid column and forms a Binary tree on it. This binary tree information is then stored separately in the disc. Expand the table Student and then expand theIndexes. You will see the following index created for you when the primary key is created:

Pic02.jpg

With the use of the binary tree, now the search for the student based on the studid decreases the number of comparisons to a large amount. Let us assume that you had entered the following data in the table student:

Pic03.jpg

The index will form the below specified binary tree. Note that for a given parent, there are only one or two Childs. The left side will always have a lesser value and the right side will always have a greater value when compared to parent. The tree can be constructed in the reverse way also. That is, left side higher and right side lower.

Pic04.JPG

Now let us assume that we had written a query like below:

Select * from student where studid = 103;
Select * from student where studid = 107;

Execution without index will return value for the first query after third comparison.
Execution without index will return value for the second query at eights comparison.

Execution of first query with index will return value at first comparison.
Execution of second query with index will return the value at the third comparison. Look below:

  1. Compare 107 vs 103 : Move to right node
  2. Compare 107 vs 106 : Move to right node
  3. Compare 107 vs 107 : Matched, return the record

If numbers of records are less, you cannot see a different one. Now apply this technique with a Yahoo email user accounts stored in a table called say YahooLogin. Let us assume there are 33 million users around the world that have Yahoo email id and that is stored in the YahooLogin. When a user logs in by giving the user name and password, the comparison required is 1 to 25, with the binary tree that is clustered index.

Look at the above picture and guess yourself how fast you will reach into the level 25. Without Clustered index, the comparison required is 1 to 33 millions.

Got the usage of Clustered index? Let us move to Non-Clustered index.

6. Non Clustered Index

A non-clustered index is useful for columns that have some repeated values. Say for example, AccountTypecolumn of a bank database may have 10 million rows. But, the distinct values of account type may be 10-15. Aclustered index is automatically created when we create the primary key for the table. We need to take care of the creation of the non-clustered index.

Follow the steps below to create a Non-clustered index on our table Student based on the column class.

  1. After expanding the Student table, right click on the Indexes. And click on the New Index.Pic05.jpg
  2. From the displayed dialog, type the index name as shown below and then click on the Add button to select the column(s) that participate in the index. Make sure the Index type is Non-Clustered.Pic06.jpg
  3. In the select column dialog, place a check mark for the column class. This tells that we need a non-clusteredindex for the column Student.Class. You can also combine more than one column to create the Index. Once the column is selected, click on the OK button. You will return the dialog shown above with the selected column marked in blue. Our index has only one column. If you selected more than one column, using the MoveUpand MoveDown button, you can change order of the indexed columns. When you are using the combination of columns, always use the highly repeated column first and more unique columns down in the list. For example, let use assume the correct order for creating the Non-clustered index is: ClassDateOfBirth,PlaceOfBirth.Pic07.jpg
  4. Click on the Index folder on the right side and you will see the non-clustered index based on the column class is created for you.Pic08.jpg

7. How Does a Non-Clustered Index Work?

A table can have more than one Non-Clustered index. But, it should have only one clustered index that works based on the Binary tree concept. Non-Clustered column always depends on the Clustered column on the database.

This can be easily explained with the concept of a book and its index page at the end. Let us assume that you are going to a bookshop and found a big 1500 pages of C# book that says all about C#. When you glanced at the book, it has all beautiful color pages and shiny papers. But, that is not only the eligibility for a good book right? One you are impressed, you want to see your favorite topic of Regular Expressions and how it is explained in the book. What will you do? I just peeped at you from behind and recorded what you did as below:

  1. You went to the Index page (it has total 25 pages). It is already sorted and hence you easily picked up Regular Expression that comes on page Number 17.
  2. Next, you noted down the number displayed next to it which is 407, 816, 1200-1220.
  3. Your first target is Page 407. You opened a page in the middle, the page is greater than 500.
  4. Then you moved to a somewhat lower page. But it still reads 310.
  5. Then you moved to a higher page. You are very lucky you exactly got page 407. [Yes man you got it. Otherwise I need to write more. OK?]
  6. That’s all, you started exploring what is written about Regular expression on that page, keeping in mind that you need to find page 816 also.

In the above scenario, the Index page is Non-Clustered index and the page numbers are clustered index arranged in a binary tree. See how you came to the page 407 very quickly. Your mind actually traversed the binary tree way left and right to reach the page 407 quickly.

Here, the class column with distinct values 1,2,3..12 will store the clustered index columns value along with it. Say for example; Let us take only class value of 1. The Index goes like this:

1: 100, 104, 105

So here, you can easily get all the records that have value for class = 1. Map this with the Book index example now.

Inversion Of Control(IOC) or Dependency Injection(DI)?


In designing an object-oriented application, a major tenet of design is “loose coupling”. Loosely, not meant for the pun, “loose coupling” means that objects should only have as many dependencies as is needed to do their job – and the dependencies should be few. Furthermore, an object’s dependencies should be on interfaces and not on “concrete” objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide “mock” objects in place of expensive services, such as a socket-communicator. “Dependency Injection” (DI), also more cryptically known as “Inversion of Control” (IoC), can be used as a technique for encouraging this loose coupling. There are two primary approaches to implementing DI: constructor injection and setter injection. Obviously, at some point, something must be responsible for creating the concrete objects that will be injected into another object. The injector can be a parent object, which I’ll call the “DI controller”, or can be externalized and handled by a “DI container” framework. What follows is a brief overview of the various approaches for using dependency injection techniques.

Constructor Injection

Constructor Injection is the DI technique of passing an object’s dependencies to its constructor. The below example includes a class, Customer, that exposes a method for retrieving every sales-order that the customer made on a particular date. Consequently, the Customer class needs a data-access object for communicating with the database. Assume, an OrderDao (“order data-access object”) exists which implements the interface IOrderDao. One way that a Customer object can get this dependency is by executing the following within the: IOrderDao orderDao = new OrderDao();. The primary disadvantage of this is two-fold:

1. the benefit of having the interface in the first place has been negated since the concrete instance was created locally, and
2. OrderDao cannot easily be replaced by a mock object for testing purposes. (Mock objects will be discussed shortly.)

The aforementioned example follows:
public class Customer {
public Customer(IOrderDao orderDao) {
if (orderDao == null)
throw new ArgumentNullException(“orderDao may not be null”);

this.orderDao = orderDao;
}

public IList GetOrdersPlacedOn(DateTime date) {
// … code that uses the orderDao member
// get orders from the datasource …
}

private IOrderDao orderDao;
}
In the example, note that the constructor accepts an interface; it does not accept a concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer invoking the object which dependencies need to be given to the Customer object for proper execution. But consider the following example… Suppose you have a class with ten methods that have no dependencies, but you’re adding a new method that does have a dependency on IOrderDao. You could change the constructor to use Constructor Injection, but this may force you to change constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? “Setter Injection” is another DI technique that can be used in situations such as this.

Setter Injection

Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:

1. supporting dependency injection without having to modify the constructor of a legacy class, and
2. allowing expensive resources or services to be created as late as possible and only when needed.
The code below modifies the Constructor Injection example to use

Setter Injection instead:
public class Customer {
public Customer() {}

public IOrderDao OrderDao {
set { orderDao = value; }
get {
if (orderDao == null)
throw new MemberAccessException(“orderDao” +
” has not been initialized”);
return orderDao;
}
}

public IList GetOrdersPlacedOn(DateTime date) {
//… code that uses the OrderDao public
//… property to get orders from the datasource …
}

// Should not be called directly;
// use the public property instead
private IOrderDao orderDao;
}
In the above example, the constructor accepts no arguments. Instead, the invoking object is responsible for setting the IOrderDao dependency before the method GetOrdersPlacedOn is called. With Constructor Injection, an exception is thrown if the dependency is not set immediately, i.e., upon creation. With Setter Injection, an exception isn’t thrown until a method actually attempts to use the dependency. Make note of the fact that GetOrdersPlacedOn uses the public OrderDao property; it does not call the private orderDao directly. This is so that the getter method has an opportunity to validate if the dependency has yet been initialized. Setter Injection should be used sparingly in place of Constructor Injection, because it:
1. does not make it clear to the developer which dependencies are needed when, at least until a “has not been initialized” exception is thrown, and
2. makes it a bit more difficult to track down where the exception came from and why it got thrown. With this said, Setter Injection can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.
The Injectors

The next logical question is, what actually creates the dependencies that are to be injected into “injectees”? There are two appropriate places for adding creation logic: controllers and containers.

DI Controllers

The “DI controller” approach is the simpler to understand and implement. In a properly tiered architecture, an application has distinct layers for handling logic. The simplest layering usually consists of a data-layer for talking to the database, a presentation-layer for displaying the UI, and a domain-logic layer for performing business logic. A “controller” layer always exists, even if not well defined, for coordinating UI events to the domain and data layers, and vice versa. For example, in ASP.NET, the code-behind page acts as a rudimentary controller layer. More formalized controller-layer approaches exist: Struts and Spring for Java; Front Controller and Spring .NET for .NET. All of these approaches follow some form of variant of the Model-View-Controller pattern. Regardless of what you use as your controller, the controller is an appropriate location for performing Dependency Injection “wiring”. This is where concrete objects are created and injected as dependencies. What follows are two examples of DI performed by a controller. The first is an illustrative example of “production code” – code that you’d end up deploying. The second is an example of “test code” – code that’s used to test the application, but is not deployed and does not have the need to have a live database. Controller code performing the dependency injection (e.g., from an ASP.NET code-behind page):
//… code performed when the controller is loaded …

IOrderDao orderDao = new OrderDao();
// Using Setter Injection on a pre-existing customer
someCustomer.OrderDao = orderDao;
IList ordersPlacedToday =
someCustomer.GetOrdersPlacedOn(DateTime.Now);


Unit-test code performing dependency injection:
IOrderDao orderDao = new MockOrderDao();
// Using Setter Injection on a pre-existing customer
someCustomer.OrderDao = orderDao;
IList ordersPlacedToday =
someCustomer.GetOrdersPlacedOn(DateTime.Now);
One of the major benefits of using a DI-controller to inject dependencies is that it’s straightforward and easy to point to where the creation is occurring. The drawback to using DI-controllers is that the dependencies are still hard-coded somewhere; albeit, they’re hard-coded in a location that is often subject to frequent changes anyway. Another drawback is that now the DI-controllers themselves can’t be easily unit-tested with mock objects. (Granted, a powerful tool such as TypeMock can do just about anything when it comes to injecting mock objects. But a tool such as TypeMock should be used only when absolutely necessary as it can lead to habits of not programming-to-interface. In fact, I’d recommend only considering the use of it on very difficult to test, legacy applications.) In ASP.NET, I prefer to use the Model-View-Presenter (MVP) pattern, and have the ASP.NET code-behind page create dependencies and inject them to the presenter via Construction Injection. Additionally, I use UserControls as the View part of the pattern, so the ASP.NET code-behind acts purely as an MVP “dependency initializer” between the UserControls (View) and their presenters. Another option to implementing constructor or setter DI is the use of an application container…

DI Containers

Inversion-of-Control/Dependency-Injection “containers” can be used to watch an application and inject dependencies whenever a particular event occurs. For example, whenever a Customer instance is created, it automatically gets injected with its needed dependencies. It’s a strange concept at first, but can be useful for managing large applications with many service dependencies. Different container providers each have their own mechanism for managing dependency injection settings.

A very good example can be found at :

http://www.codeproject.com/Articles/26466/Dependency-Injection-using-Spring-NET/

http://www.youtube.com/watch?v=Jjp_EYEn4bc&feature=related

http://www.youtube.com/watch?v=IOZzxmJVus0&feature=relmfu

http://joelabrahamsson.com/entry/inversion-of-control-introduction-with-examples-in-dotnet

Categories: C# Tags: ,

Singleton Class


using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

This approach ensures that only one instance is created and only when the instance is needed. Also, the variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed. Lastly, this approach uses a syncRoot instance to lock on, rather than locking on the type itself, to avoid deadlocks.

This double-check locking approach solves the thread concurrency problems while avoiding an exclusive lock in every call to the Instance property method. It also allows you to delay instantiation until the object is first accessed.

Real World Example of a Singleton Class 

Thread pools, SQL Connection Pools, Registry objects, Objects handling user preferences, Caches, Factory classes, Builder classes and Statistics utilities like a hit counter, log4net, when you call its logger, it uses a singleton class to return it.

Difference between Singleton and Static Class

Another question that usually comes up when it comes to using a Singleton is “Why not just use a static class?”. Static classes still have many uses and lots of times, people get confused and will use a Singleton as much as possible. One easy rule of thumb you can follow is if it doesn’t need to maintain state, you can use a Static class, otherwise you should use a Singleton.

So here is a quick list of uses for static classes:
Math.pow(double a, double b);
Interger.parseInt(String s);
Interger.toString(int i);

As you can see, the state of these methods don’t matter. You just want to use them to perform a simple task for you. But if you coding your application and you are using a central object where state does matter(such as the ModelLocator example), then its best to use a Singleton.

The next reason you may want to use a Singleton is if it is a particularly “heavy” object. If your object is large and takes up a reasonable amount of memory, you probably only one of those objects floating around. This is the case for things like a if you have a factory method that is particularly robust, you want to make sure that its not going to be instantiated multiple times. A Singleton class will help prevent such the case ever happening.

Categories: C# Tags:

Thread Management


Download MultiThreading in .NET 2.0

Why Threads?

Some years ago I saw a letter-to-the-editor in response to the need of a multitasking system, the writer said “I don’t care about multitasking because I can only do one thing at a time.” Really? Does this person only do one thing at a time? This person continues with “I finish my Word document, print it, fire up my modem to connect to the Internet, read my e-mail, and go back to work on another document.” Does this person efficiently use his time? Many of us might suggest that this person could fire up his modem while the printer is printing, or work on another document while the previous one is being printed. Good suggestions, indeed. In fact, we are multitasking many tasks in our daily life. For example, you might watch your favorite TV program or movie and enjoy your popcorn. Or, while you are printing a long document, you might read a newspaper or company news. There are so many such examples demonstrating that we are doing two or more tasks simultaneously. This is a form of multitasking! In fact, multitasking is more common in industry. While each worker of an assembly line seems working in a sequential way, there could be multiple production lines, all of which perform the same task concurrently. Moreover, the engine assembly lines produce engines while the other lines produce other components. Of course, the car assembly lines run concurrently with all of the other lines. The final product is the result of these concurrently running assembly/production lines. Without this type of “parallelism” Detroit would not be able to produce sufficient airplanes and tanks for WW II and enough number of automobiles to fulfill our demand.

Unfortunately, before you learn how to split your program into multiple execution threads, all programs you wrote contain a single execution thread. The following diagram shows an example. Suppose we have a program of two parts, Part A and Part B. After Part A finishes its computation, we use some cout statements to print out a large amount of output. As we all know, when a program prints, the control is transfered to a function in C++’s library and the execution of that program is essentially suspended, shown in dashed line in the diagram, until the printing completes. Once this (i.e., printing) is done, the execution of the program resumes and starts the computation of Part B. Is there anything wrong with this? No, we are used to it and we are trained to do programming in this way ever since CS101. However, is this way of programming good enough in terms of efficiency? It depends; but, in many situations, it is not good enough.

If Part B must use some data generated by Part A, then Part B perhaps has to be executed after the output of cout completes. On the other hand, in many situations, Part A and Part B are independent of each other, or one may slightly rewrite both parts so that they do not depend on each other. In this case, Part B does not have to wait until cout completes. In fact, this is the key point! Therefore, before the execution of Part A, the program can be split into two execution threads, one for Part A and the other for Part B. See the diagram below. In this way, both execution threads share the CPU and all resources allocated to the program. Moreover, while Part A is performing the output which causes Part A to wait, Part B can take the CPU and executes. As a result, this version is more efficient than the previous one. Moreover, in a system with more than one CPUs, it is possible that the system will run both Part A and Part B at the same time, one on each CPU.

In real programming practice, a program may use an execution thread for handling keyboard/mouse input, a second execution thread for handling screen updates, and a number of other threads for carrying out various computation tasks.

Example: Quicksort

The quicksort algorithm consists of two steps in each recursion. First, the partition step divides the input array segment into two segments such that all elements in the left segment is smaller or equal to all elements in the right segment. Second, the sorting step simply sorts the left segment and the right segment. After these two steps complete, the input segment is sorted. While it is not so obvious if the partition step can have multiple execution threads, one can split the execution of the sorting step into two, one for sorting the left segment while the other for sorting the right one. This is shown in the diagram below:

Example: Merging

Consider another simple problem. Suppose we have two arrays a[ ] and b[ ] of n elements each. For simplicity, we assume that all of these 2n elements are different. Our job is to merge these two arrays into a sorted one. Everyone who took a data structures course knows how to do it; however, let us look at the same problem from a different angle.

Take an element from array a, say a[i]. We know that it is larger than i-1 elements of a. If we can figure out how many elements of b that are smaller than a[i], we will be able to know the exact location of a[i] in the sorted array. This is illustrated in the following diagram:

With a slightly modified binary search, we can easily determine the location of a[i] in array b. There are only three possibilities:

  1. a[i] is less than b[0]: In this case, a[i] is larger than i-1 elements in a and smaller than all elements in b. Therefore, a[i] should be in position i of the sorted array.
  2. a[i] is larger than b[n]: In this case, a[i] is larger than i-1 elements in a and n elements in b. Therefore, a[i] should be in position i+n of the sorted array.
  3. a[i] is between b[k-1] and a[k]. In this case, a[i] is larger than i-1 elements in a and k-1 elements in b. Therefore, a[i] should be in position i+k-1 of the sorted array.

After the main program reads in both arrays, it can split itself into 2n execution threads, each of which handles an element in a or in b. Each of these execution threads determines its position in the merged array and writes the values into the corresponding location. After this, we will have a merged array! Thus, we use 2n threads, each of which takes O(log2(n)) comparisons to get the job done. In the conventional serial case, we use one execution thread which uses O(n) comparisons to merge the arrays.

Example: Matrix Multiplication

Another interesting application is the multiplication of two matrices. Suppose we have two matrices Am×k (m rows and k columns) and Bk×n (k rows and n columns) and want to compute the product of A and B into a matrix C of m rows and n columns. The entry of C on row i and column j is the sum of the products of the corresponding elements on row i of matrix A and column j of matrix B as shown below:

How can we use multiple execution threads to solve this problem? We notice that the computation of Ci,j is independent of the computation of any other entries of matrix C. Because of this, after matrices A and B are read in, the main program can split m×n execution threads, one for each entry of matrix C. Each of these execution threads computes the products of the corresponding elements, sums them up, and stores the result into matrixC.

It requires k multiplications to compute a single entry of matrix C. Since there are m×n entries in C, the program with only one thread uses m×n×k multiplications. On the other hand, in the above scheme, each thread uses kmultiplications and there are m×n threads. If we have only one CPU, the multiple execution threads version may not be as efficient as the single execution thread one; however, if there are more than one CPUs, each of these CPUs may be assigned to a number of execution threads and the execution efficiency is higher. In the extreme case in which we have m×n CPUs to use, because all execution threads run at the same time, it only takes the time to compute one entry to complete the whole matrix multiplication. Thus, it is m×n times more efficient than the single execution thread version.

By now, you perhaps have had a good feeling of why splitting a program into multiple execution threads may increase the execution efficiency. However, just like in the movie Multiplicity, creating too many execution threads may lead to a chaotic situation because in addition to splitting a program into multiple execution threads these threads must communicate with each other properly in order to work together. Thus, in addition to learning the way of creating execution threads, we also have to learn the way of managing threads and the way of thread synchronization.

The above examples may look a little unrealistic and their benefits seem only about program efficiency. There are other benefits of using multiple execution threads.

There are four basic thread management operations: thread creationthread terminationthread join, and thread yield.

Thread Creation

We have discussed the creation of threads in a above page. Basically, we can split the execution thread into two. After this, both threads execute concurrently. The creating thread is the parent thread, and the created thread is a child thread. Note that any thread, including the main program which is run as a thread when it starts, can create child threads at any time. In the following diagram, Thread A runs initially. Sometime later, it creates Thread B as indicated by a yellow dot. After this creation, Thread A and Thread B runs concurrently. Later on, Thread A may create one more thread Thread C. After Thread C is created, there are three threads running concurrently, all of which compete to use the CPUs. However, which thread is run at a particular time is not known to any one of them. The quicksort example discussed on a above page employs this scheme, where Thread A receives an array segment, partitions it into two segments, creates Thread B to sort the left segment, and then creates Thread C to sort the right one. Or, after the given array segment is partitioned into two, Thread A creates Thread B to sort the left segment and sorts the right segment by itself. In this way, two threads, one parent – Thread A – and one child – Thread B – would be sufficient.

In the matrix multiplication example, the main thread (i.e., the main program) must create a number of threads, one for each entry of the resulting matrix. A possibility is shown below. Two for statements are used to create m×n threads. We shall see more examples that dynamically create threads later.

Thread Termination

For most of the cases, threads are not created and run forever. After finish their work, threads terminate. In the quicksort example, after both array subsegments are sorted, the threads created for sorting them terminate. In fact, the thread that creates these two child threads terminates too, because its assigned task completes. In the merging example, the threads created to determine the position of array elements a[i] and b[j] in the merged array terminate once the final positions are computed. Similarly, in the matrix multiplication example, once the value of C[i,j] is computed, the corresponding thread terminates. In general, when the assigned task of a thread completes, the thread may be terminated.

Moreover, if the parent thread terminates, all of its child threads terminate as well. Why is this important? We briefly mentioned in a above page that the child threads share resources with the parent thread, including variables. When the parent thread terminates, all of its variables are gone, and, as a result, the child threads will not be able to access to those resources that the parent thread owns. Thus, if the parent thread runs faster and terminates earlier than its child threads do, we have a problem! This is why we need the third thread management feature: thread join.

Thread Join

Imagine the following scenario. You are preparing for tomorrow’s final examine and feel a little hungry. So, you give your younger brother ten bucks and ask him to buy a pizza for you. In this case, you are the main thread and your brother is a child thread. Once your order is given, both you and your brother are doing their job concurrently (i.e., studying and buying a pizza). Now, we have two cases to consider. First, your brother brings your pizza back and terminates while you are studying. In this case, you can stop studying and enjoy the pizza. Second, you finish your study early and sleep (i.e., your assigned job for today – study for tomorrow’s final exam – is done) before the pizza is available. Of course, you cannot sleep; otherwise, you won’t have a chance to eat the pizza. What you are going to do is to wait until your brother brings the pizza back. This is exactly the problem and solution we mentioned at the end of the previous section.

Thread join is designed to solve this problem. A thread can execute a thread join to wait until the other thread terminates. In our case, you – the main thread – should execute a thread join waiting for your brother – a child thread – to terminate. In general, thread join is for a parent to join with one of its child threads. Thread join has the following activities, assuming that a parent thread P wants to join with one of its child threads C.

  • When P executes a thread join in order to join with C, which is still running, P is suspended until C terminates. Once C terminates, P resumes.
  • When P executes a thread join and C has already terminated, P continues as if no such thread join has ever executed (i.e., join has no effect).

A parent thread may join with many child threads created by the parent. Or, a parent only join with some of its child threads, and ignore other child threads. In this case, those child threads that are ignored by the parent will be terminated when the parent terminates.

Thread Yield

Suppose you run a number of programs at the same time on a computer. It is possible that some CPU hogs keep eating up the CPU cycles so that other programs may hardly run. Well, this may be a problem of the scheduling policy of the operating system. However, when we write our programs with multiple threads, we have to make sure that some threads will not occupy the CPU forever, or for a very long time, without relinquishing it. Otherwise, we will end up in the situation where one or two threads keep running while the others simply wait there for their turns. That is, we run our threads in a very “polite” way that once a while a thread takes some rest so that the CPU can be used by other threads. This is achieved by thread yield.

When a thread executes a thread yield, the executing thread is suspended and the CPU is given to some other runnable thread. This thread will wait until the CPU becomes available again. Technically, in process scheduler’s terminology, the executing thread is put back into the ready queue of the processor and waits for its next turn. The following shows an example, where a small circle indicates the execution of a thread yield, a small square means the control is transferred back, a solid arrow indicates thread execution, and a dashed line segment depicts a thread waiting for execution. Suppose we have three threads AB and C. Initially, A is running and executes a thread yield sometime later. This causes A is suspended temporarily and the CPU is given to the next thread, say B. Then, B runs for a while and executes a thread yield. Because there are two threads that are ready to run, A and C, the thread system picks one to run. Suppose it is C. When C executes a thread join, the control may switch back to A or B; however, the diagram shows the control is given back to A. In this way, threads execute in a cooperative way.

Thread Suspend and Resume

Thread suspend and resume are two more thread management features. When a thread executes a thread suspend to suspend the execution of itself or another thread, the indicated thread will be suspended until the execution of a thread resume that releases the indicated thread. For example, suppose we have three threads AB and C running concurrently. Then, thread A execute a thread suspend to suspend the execution of threadB. After this, we have only two threads A and C running concurrently. Note that even though both A and C are waiting for the completion of their own I/O activities and no thread is running, the suspended thread B cannot run. To run thread B again, one of the other threads must execution a corresponding thread resume. For example, thread C may execute a thread resume to resume thread B‘s execution. After this, all three threads are running concurrently.

Both thread yield and thread suspend cause the execution of a thread to be suspended. What is the difference? The difference is a big one! With thread yield, the yielding thread is put back to the ready queue and will run when its turn comes. Thus, a yielding thread is runnable if the CPU becomes free in the future, although it is suspended. With a thread suspend, the suspended thread is not in the ready queue, and, as a result, the scheduler will not be able to pick it up and let it run when the CPU becomes free. Instead, the execution of a suspended thread can be resumed only by a specific thread resume call.

Thread suspend/resume can be very useful. For example, suppose a program must handle five different tasks. The main program may create five threads, one for each task. Initially, all threads are suspended by the main program. Once a task comes, the main program just resumes the corresponding thread. After handling the task, the thread simply suspends itself. This may be more efficient that creating a new thread to handle the task and then terminating the thread. However, thread suspend and resume could post some problem. Suppose a thread acquire a lock so that it becomes the only thread that can access to a shared resource. If before the thread releases the lock, it is suspended by another thread. Should this happen, no other thread can access the shared resource until a thread resume the suspended thread for it to release the lock. Because of this potential problem, which may lead to a system deadlock, the use of thread suspend and resume is usually not recommended. Some systems such as the Pthread do not support thread suspend and resume.

What is difference between Daemon and Non Daemon Thread

In java we have two type of Threads :
Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn’t terminates unless all the user thread terminate.

On the other hand we have Daemon threads. These threads are generally ‘Service provider’ threads. They should not be used to execute your program code but system code. These thread run in parallel to your code but JVM can kill them anytime. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus you should never depend on daemon thread to perform any program code.

Events with Threading

Use events with thread; this is one of the techniques to synchronize one thread with other like ManualResetEvent 

Difference between a computer process and thread

A single process can have multiple threads that share global data and address space with other threads running in the same process, and therefore can operate on the same data set easily. Processes do not share address space and a different mechanism must be used if they are to share data.

If we consider running a word processing program to be a process, then the auto-save and spell check features that occur in the background are different threads of that process which are all operating on the same data set (your document).

Process 

In computing, a process is an instance of a computer program that is being sequentially executed[1] by a computer system that has the ability to run several computer programs concurrently.

Thread

A single process may contain several executable programs (threads) that work together as a coherent whole. One thread might, for example, handle error signals, another might send a message about the error to the user, while a third thread is executing the actual task

Interlocked class

Provides atomic operations for variables that are shared by multiple threads. Interlocked class provides methods by which you can achieve following functionalities :-

1. increment Values.
2. Decrement values.
3.Exchange values between variables.
4.Compare values from any thread.
in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)

Categories: C# Tags:

Dispatcher in WPF

February 21, 2012 2 comments

Consider the following program

MainWindow.xaml
   1:  <Window x:Class="DispatcherTrial.MainWindow"
   2:          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:          Title="MainWindow" Height="350" Width="525">
   5:      <Grid>
   6:          <Grid.RowDefinitions>
   7:              <RowDefinition/>
   8:              <RowDefinition/>
   9:          </Grid.RowDefinitions>
  10:          <Button Name="MyButton" Content="Click Here" 
                             Click="MyButton_Click"></Button>
  11:          <TextBlock Grid.Row="1" Name="myText"></TextBlock>
  12:      </Grid>
  13:  </Window>
MainWindow.xaml.cs
namespace DispatcherTrial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            Thread myThread = new Thread(DisplayTime);
            myThread.Start();
        }

        private void DisplayTime()
        {
            myText.Text = DateTime.Now.ToString();
        }
    }
}

The code is fairly simple. Grid having two rows, one containing button control and other having a TextBlock. In the click of event of button, I have initialized a new thread. Assigned to that thread is method called “DisplayTime”. Inside “DisplayTime” method, I am assigning the current time to the textblock control. All in all , I am trying to update the UI from code which is running on a separate thread. Ideally the code should run fine but it doesn’t. It throws an exception of type :- InvalidOperationException. And following is the error message : The calling thread cannot access this object because a different thread owns it.

I guess the error description is verbose enough to tell us what’s wrong in the above implementation. We simply cannot update the UI from a seperate thread. To understand more on this consider the following code snippet :

   1:  [STAThread]
   2:  static void Main()
   3:  {
   4:         Application app = new Application();
   5:         Window win = new Window();
   6:         win.Show();
   7:         app.Run();
   8:  }

The main method here is tagged with “STAThread” attribute. STA stands for “Single Threaded Apartment” model of programming. What STA states(or enforces) is that only one thread at a time will be executing our code and it will always be the same thread. All our Winform based application runs on STA model. Indeed one thread controlling the complete application looks like a big constraint and WPF people actually decided to move away from this model by opting an all together different approach. But the plan was abandoned because of various compatibility issues with other already existing applications. So our WPF applications too run on STA model. The thread the controls the application is commonly known as UIThread. “Dispatcher” concept is a mechanism introduced in WPF , with the help of which developer can have more explicit control on this UI thread as of what executes when. We will look into this in more details in the remaining section of this article. But before we take a deep dive, just try to keep in mind the below mentioned points about STA model.

  • Thread that creates a given WPF application also own it and its not possible for any other thread to interact with these elements.
  • In practice entire WPF application runs of single thread and its this thread that owns all the elements in the application.

Dispatcher Concept

As the name implies, the dispatching system is responsible for listening to various kinds of messages and making sure that any object that needs to be notified of that message is notified on the UI thread.

The classes responsible for “Dispatcher” concept are : DispatcherObject and Dispatcher. Actually its the “Dispatcher” class which provides the core implementation of dispatching mechanism. But its the “DispatcherObject” class which exposes a public property called “Dispatcher” , through which we can access the current instance of “Dispatcher” class. Have a look at the following class hierarchy diagram :

image

From the above picture its evident that almost every single entity in WPF derives from the “DispatcherObject” class. Following is the internal implementation of “DispatcherObject” class.

   1:  public abstract class DispatcherObject
   2:  {
   3:      // Fields
   4:      private Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
   5:   
   6:      // Methods
   7:      protected DispatcherObject()
   8:      {
   9:      }
  10:   
  11:       public bool CheckAccess()
  12:      {
  13:          bool flag = true;
  14:          Dispatcher dispatcher = this._dispatcher;
  15:          if (dispatcher != null)
  16:          {
  17:              flag = dispatcher.CheckAccess();
  18:          }
  19:          return flag;
  20:      }
  21:   
  22:      internal void DetachFromDispatcher()
  23:      {
  24:          this._dispatcher = null;
  25:      }
  26:   
  27:       public void VerifyAccess()
  28:      {
  29:          Dispatcher dispatcher = this._dispatcher;
  30:          if (dispatcher != null)
  31:          {
  32:              dispatcher.VerifyAccess();
  33:          }
  34:      }
  35:   
  36:      // Properties
  38:      public Dispatcher Dispatcher
  39:      {
  40:          get
  41:          {
  42:              return this._dispatcher;
  43:          }
  44:      }
  45:  }
  46:

“DispatcherObject” class offers a public accessor property called “Dispatcher” using which we can access the current instance of “Dispatcher” class. Speaking about “Dispatcher” class, it is responsible for managing the work that takes place in our WPF application.Its this class which owns the application thread and internally it maintains a queue of work items. As the WPF application runs , Dispatcher class accepts incoming requests and executes them one at a time. In short dispatcher is an object which receives messages and delivers it to the correct object for further processing. Dispatcher class is pretty dense with lots of properties and methods. Going into the depth of Dispatcher class is beyond the scope of this article. One final thing on dispatcher class is that a given application can have only one instance of dispatcher class( as the application runs on single thread) , so Dispatcher class implements the very famous “Singleton” pattern. Because of that its impossible to create an instance of Dispatcher class in our custom code. Only with the help of public property “Dispatcher” offered by “DispatcherObject” that we can invoke members defined inside the “Dispatcher” class. Dispatcher class is instantiated as soon as any class which derives from “DispatcherObject” is accessed. All further request are processed by this newly created instance.

Coming back to “DispatcherObject” class , it offers two methods namely CheckAccess and VerifyAccess.

  • CheckAccess : Determines whether the calling thread has access to this DispatcherObject. Only possible return values are true and false.
  • VerifyAccess : VerifyAccess is more stringent compared to CheckAccess. It checks whether the calling thread is the one which created the DispatcherObject. If not it throws “InvalidOperationAccess” exception. Getting back to the example which I gave in the beginning, in that we were trying to update the UI through code which was running on a different thread. Internally VerifyAcess is invoked and once it verifies that calling code is different from the one which controls the application, it throws the “InvalidOperationError” exception.

DispatcherPriority

I have spoken so much on the classes which enable dispatching scenario in WPF. But at the end of the day WPF works on STA model. So how does this whole “Dispatcher” stuff going to help us ? As mentioned before , Dispatcher maintains an internal queue of work items and it process each work items one after the other. Each work item in the queue is has its associated priority. Items are executed relatively to each other on the basis of their priority values. Items with high priority value will be executed before any other items with low priority values. Possible values for the priority field is represented by an enum called “DispatcherPriority”.

   1:  public enum DispatcherPriority
   2:  {
   3:      ApplicationIdle = 2,
   4:      Background = 4,
   5:      ContextIdle = 3,
   6:      DataBind = 8,
   7:      Inactive = 0,
   8:      Input = 5,
   9:      Invalid = -1,
  10:      Loaded = 6,
  11:      Normal = 9,
  12:      Render = 7,
  13:      Send = 10,
  14:      SystemIdle = 1
  15:  }

Now as a WPF programmer, we can push our custom time consuming logic into the queue maintained by the “Dispatcher” class and associate a lower priority value to that work item. Based on the value of priority field the corresponding code will be executed at the specified interval. Important thing to note here is that all the work is still being done by the UIthread, its just that with the help of DispatcherPriority we have prioritized our tasks. Ideally its recommended to give priority values less then 7(render) to the custom logic that we wish to execute with the help of Dispatcher. Most often priority value “Background” is used for application specific custom logic. MS Word spell check is implemented with the help of this mechanism and priority value is “ApplicationIdeal”. Following is the modified code for the example which I have provided in the beginning of the article:

   1:  namespace DispatcherTrial
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for MainWindow.xaml
   5:      /// </summary>
   6:      public partial class MainWindow : Window
   7:      {
   8:          public MainWindow()
   9:          {
  10:              InitializeComponent();
  11:          }
  12:   
  13:          private void MyButton_Click(object sender, RoutedEventArgs e)
  14:          {
  15:              this.Dispatcher.BeginInvoke(new Action(this.DisplayTime)
                                           , DispatcherPriority.Background);
  16:          }
  17:   
  18:          private void DisplayTime()
  19:          {
  20:              myText.Text = DateTime.Now.ToString();
  21:          }
  22:      }
  23:  }

”BeginInvoke” is a member exposed by the “Dispatcher” class. BeginInvoke adds the delegate to the Dispatcher’s event queue but gives you the opportunity to specify a lower priority for it. This ensures that the Dispatcher processes all loading and rendering events
before executing the delegate that loads the data. This allows the control or window to be displayed and rendered immediately, whilst the data waits in the background to be loaded.

_______________________________________________________________________________________________

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 from DispacterObject. 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 using BeginInvoke. 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 DispatcherOperation that 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. The System.Windows.Threading namespace contains a lot more useful objects that extends the power of the dispatcher even further. If you’ve got questions or have found crazy uses for the Dispatcher, leave them in the comments.

Categories: WPF Tags:

UI Thread, Dispatchers, Background Workers & Async Network Programming

February 5, 2012 1 comment

Both Silverlight and WPF have the concept of a UI thread. Whenever you tie that thread up, you make your application unresponsive. In Silverlight, if you’re on a page with other plug-ins, you make all the plug-ins unresponsive. (It’s actually per-process, but most modern browsers separate processes by tabs)

Async Network Calls

In order to keep from tying up the UI thread, you have to perform long-running processes on another thread. Often, but not always, those processes are network calls. In Silverlight, all network calls are async with no provision to handle them any other way. This lets you off the hook threading-wise, but requires that you understand how to chain those calls, and how to deal with libraries that have IAsyncResult callbacks that return on different threads.
TestServiceClient client = new TestServiceClient();

client.DoSomethingSlowCompleted+= (s, ea) =>{

     // do something with the results here
     Debug.WriteLine(ea.Result);
};
client.DoSomethingSlowAsync();

Background Worker

For other processes, the BackgroundWorker is a great, simple, way to do some background work while reporting progress to the UI. It takes all the dispatching work away, so you can feel free to manipulate the UI from the ProgressChanged and RunWorkerCompleted events. Do not touch the UI from the DoWork event, as that is actually running on a separate thread.

private BackgroundWorker _worker = new BackgroundWorker();

private void RunLongProcess() {    

     _worker.WorkerReportsProgress = true;

     ProgressBar.Minimum = 0;

     ProgressBar.Maximum = 100;

    // runs in Background Thread
     _worker.DoWork += (s, e) =>
     {
           for (int i = 0; i < 100; i++)
           {
                 // simulate long-running work
                System.Threading.Thread.Sleep(500);
                ((BackgroundWorker)s).ReportProgress(i+1);
           }
     };

 // runs in UI Thread

     _worker.ProgressChanged += (s, e) => {
            // this is on the UI thread, so you can update UI from here.
            ProgressBar.Value = e.ProgressPercentage;
     };

   // runs in UI Thread

     _worker.RunWorkerCompleted += (s, e) => {
            // clean up after your stuff, yes, you can touch UI here.
       };
      _worker.RunWorkerAsync();
}

Of course, knowing how to set up event handlers using lambda expressions is always helpful 🙂

Dispatcher

Sometimes, you spin off a thread of your own, or you have to deal with some of the crufty stacks where the callbacks come back on a different thread from the one that created the call. In those cases, you need to use a dispatcher to make a call back to the UI thread.

If the code is on a page, you can call the dispatcher property and pass it a function to execute (yes, more lambda in this example).

private void UpdateUI(){Dispatcher.BeginInvoke(() =>{ProgressBar.Value = 50;});}

But, if the code is in some sort of non-UI class, it gets more complex. You can do it this way, using a dummy control (like we did in Silverlight 2):

TextBlock _dispatcherObject = new TextBlock();private void UpdateUINasty() // avoid this approach unless it’s all you’ve got{_dispatcherObject.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50; });}

This example assumes the object itself was created on the UI thread. The better way is to use the Deployment object:

private void UpdateUINotSoNasty(){Deployment.Current.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50;});}

That’s better. Definitely the recommended approach for recent versions of Silverlight, including Windows Phone 7.

Timers

What about when you need to run something on a timer? The normal timer classes require manual dispatching to do any UI updates. However, Silverlight and WPF both have the DispatcherTimerclass that handles all that for you.

private void StartTimer(){DispatcherTimer timer = new DispatcherTimer();timer.Tick += (s, e) =>{
// do some very quick work here update the UI

StatusText.Text = DateTime.Now.Second.ToString();
};

timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}

Of course, realize that what you’re doing here is interrupting the UI thread, not really running anything on a separate thread. It’s not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.

Threads

In general, I discourage folks from spinning off real threads. Very few people understand how to efficiently work with threads, so even if you’re a threading genius, the person coming in after you probably isn’t. In most cases, the Background Worker will provide you with what you need.

Silverlight doesn’t yet have it, but the Parallel Tasking support built into .NET 4 can really help you out should you really need to do more than two things at once. Definitely check it out.

Conclusion

Threading in Silverlight and WPF is a little trickier than some other technologies, because you have to worry about the UI thread. My intention here was to both inform you that this trickiness exists, and then show some ways of dealing with it.

Using Statement


Defines a scope, outside of which an object or objects will be disposed.

using (Font font1 = new Font(“Arial”, 10.0f))
{
}

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement theIDisposable interface. This interface provides the Dispose method, which should release the object’s resources.

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

using System;

class C : IDisposable
{
     public void UseLimitedResource()
     {
         Console.WriteLine(“Using limited resource…”);
     }

     void IDisposable.Dispose()
     {
         Console.WriteLine(“Disposing limited resource.”);
     }
}

class Program
{
    static void Main()
    {
      using (C c = new C())
      {
        c.UseLimitedResource();
      }
      Console.WriteLine(“Now outside using statement.”);
      Console.ReadLine();
    }
}

Output:
Using limited resource…
Disposing limited resource.
Now outside using statement.

 

Difference Between Finalize and Dispose Method

.NET Framework provides two methods Finalize and Dispose for releasing unmanaged resources like files, database connections, COM etc. This article helps you to understand the difference between Finalize and Dispose method.

Finalize vs dispose method

 

Implementing Finalize method (with dispose())

 

If you want to implement Finalize method, it is recommended to use Finalize and Dispose method together as shown below:

// Using Dispose and Finalize method together

public class MyClass : IDisposable

{

       private bool disposed = false;

       //Implement IDisposable.

       public void Dispose()

      {

            Dispose(true);

            GC.SuppressFinalize(this);

       }

       protected virtual void Dispose(bool disposing)

       {

              if (!disposed)

              {

                     if (disposing)

                    {

                           // TO DO: clean up managed objects

                   }

                   // TO DO: clean up unmanaged objects

                  disposed = true;

               }

       }

       //At runtime C# destructor is automatically Converted to Finalize method

      ~MyClass()

       {

             Dispose(false);

        }

}

Note

  1. It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary.
  2. At runtime C#, C++ destructors are automatically Converted to Finalize method. But in VB.NET you need to override Finalize method, since it does not support destructor.
  3. You should not implement a Finalize method for managed objects, because the garbage collector cleans up managed resources automatically.
  4. A Dispose method should call the GC.SuppressFinalize() method for the object of a class which has destructor because it has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object’s Finalize method.
Categories: C# Tags:

MVC, MVP, MVVM


The goal of this article is to clearly explain the differences between these 3 architectures.

Common Elements

First, the let’s define common elements.  All 3 of the architectures are designed to separate the view from the model.

Model

  • Domain entities & functionality
  • Knows only about itself and not about views, controllers, etc.
  • For some projects, it is simply a database and a simple DAO
  • For some projects, it could be a database/file system, a set of entities, and a number of classes/libraries that provide additional logic to the entities (such as performing calculations, managing state, etc)

Implementation: Create classes that describe your domain and handle functionality.  You probably should end up with a set of  domain objects and a set of classes that manipulate those objects.

View

  • Code that handles the display
  • Note that view related code in the codebehind is allowed (see final notes at the bottom for details)

Implementation:  HTML, WPF, WindowsForms, views created programmatically – basically code that deals with display only.

Differences between Presenters, ViewModels and Controllers

This is the tricky part.  Some things that Controllers, Presenters, and ViewModels have in common are:

  • Thin layers
  • They communicate with the model and the view

The features of each.

Presenter (Example: WinForms)

  • 2 way communication with the view
  • View Communication: The view communicates with the presenter by directly calling functions on an instance of the presenter.  The presenter communicates with the view by talking to an interface implemented by the view.
  • There is a single presenter for each view

Implementation:

  • Every view’s codebehind implements some sort of IView interface.  This interface has functions like displayErrorMessage(message:String), showCustomers(customers:IList<Customer>), etc.  When a function like showCustomers is called in the view, the appropriate items passed are added to the display.  The presenter corresponding to the view has a reference to this interface which is passed via the constructor.
  • In the view’s codebehind, an instance of the presenter is referenced.  It may be instantiated in the code behind or somewhere else.  Events are forwarded to the presenter  through the codebehind.  The view never passes view related code (such as controls, control event objects, etc) to the presenter.

ViewModel (Example: WPF)

  • 2 way communication with the view
  • The ViewModel represents the view.  This means that fields in a view model usually match up more closely with the view than with the model.
  • View Communication:  There is no IView reference in the ViewModel.  Instead, the view binds directly to the ViewModel.  Because of the binding, changes in the view are automatically reflected in the ViewModel and changes in the ViewModel are automatically reflected in the view.
  • There is a single ViewModel for each view

Implementation:

  • The view’s datacontext is set to the ViewModel.  The controls in the view are bound to various members of the ViewModel.
  • Exposed ViewModel proproperties implement some sort of observable interface that can be used to automatically update the view (With WPF this is INotifyPropertyChanged; with knockoutjs this is done with the functions ko.observable() and ko.observrableCollection())

Controller (Example: ASP.NET MVC Website)

  • The controller determines which view is displayed
  • Events in the view trigger actions that the controller can use to modify the model or choose the next view.
  • There could be multiple views for each controller
  • View Communication:
    • The controller has a method that determines which view gets displayed
    • The view sends input events to the controller via a callback or registered handler.  In the case of a website, the view sends events to the controller via a url that gets routed to the appropriate controller and controller method.
    • The view receives updates directly from the model without having to go through the controller.
      • Note: In practice, I don’t think this particular feature of MVC is employed as often today as it was in the past.  Today, I think developers are opting for MVVM (or MVP) over MVC in most situations where this feature of MVC would have been used.  Websites are a situation where I think MVC is still a very practical solution.  However, the view is always disconnected from the server model and can only receive updates with a request that gets routed through the controller.  The view is not able to receive updates directly from the model.

Implementation (for web):

  • A class is required to interpret incoming requests and direct them to the appropriate controller.  This can be done by just parsing the url.  Asp.net MVC does it for you.
  • If required, the controller updates the model based on the request.
  • If required, the controller chooses the next view based on the request.  This means the controller needs to have access to some class that can be used to display the appropriate view.  Asp.net MVC provides a function to do this that is available in all controllers.  You just need to pass the appropriate view name and data model.


.

MVVM and MVP implementation seem pretty straightforward but MVC can be a little confusing.  The diagram below from Microsoft’s Smart Client Factory documentation does a great job at showing MVC communication.  Note that the controller chooses the view (ASP.NET MVC) which is not shown in this diagram.  MVVM interactions will look identical to MVP (replace Presenter with ViewModel).  The difference is that with MVP, those interactions are handled programmatically while with MVVM, they will be handled automatically by the data bindings.

 

 General rules for when to use which?

MVP

  • Use in situations where binding via a datacontext is not possible.
  • Windows Forms is a perfect example of this.  In order to separate the view from the model, a presenter is needed.  Since the view cannot directly bind to the presenter, information must be passed to it view an interface (IView).

MVVM

  • Use in situations where binding via a datacontext is possible.  Why?  The various IView interfaces for each view are removed which means less code to maintain.
  • Some examples where MVVM is possible include WPF and javascript projects using Knockout.

MVC

  • Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
  • This clearly describes the situation where a web API is separated from the data sent to the client browsers.  Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework.

Final notes

  • Don’t get stuck on semantics.  Many times, one of your systems will not be purely MVP or MVVM or MVC.  Don’t worry about it.  Your goal is not to make an MVP, MVVM, or MVC system.  Your goal is to separate the view, the model, and the logic that governs both of them. It doesn’t matter if your view binds to your ‘Presenter’, or if you have a pure Presenter mixed in with a bunch of ViewModels.  The goal of a maintainable project is still achieved.
  • Some evangelists will say that your ViewModels (and Presenters) must not make your model entities directly available for binding to the view.   There are definitely situations where this is a bad thing.  However, don’t avoid this for the sake of avoiding it.  Otherwise, you will have to constantly be copying data between your model and ViewModel.  Usually this is a pointless waste of time that results in much more code to maintain.
  • In line with the last point, if using WPF it makes sense to implement INotifyPropertyChanged in your model entities.  Yes, this does break POCO but when considering that INotifyPropertyChanged adds a lot of functionality with very little maintenance overhead , it is an easy decision to make.
  • Don’t worry about “bending the rules” a bit so long as the main goal of a maintainable program is achieved
  • Views
    • When there is markup available for creating views (Xaml, HTML, etc), some evangelists may try to convince developers that views must be written entirely in markup with no code behind.  However, there are perfectly acceptable reasons to use the code behind in a view if it is dealing with view related logic.  In fact, it is the ideal way to keep view code out of your controllers, view models, and  presenters.  Examples of situations where you might use the code behind include:
      • Formatting a display field
      • Showing only certain details depending on state
      • Managing view animations
    • Examples of code that should not be in the view
      • Sending an entity to the database to be saved
      • Business logic
Categories: C#, WPF Tags: , ,

Delegate in WPF


 

Introduction

In this article we will first try to understand what problem delegate solves, we will then create a simple delegate and try to solve the problem. Next we will try to understand the concept of multicast delegates and how events help to encapsulate delegates. Finally we understand the difference between events and delegates and also understand how to do invoke delegates asynchronously.

Once we are done with all fundamentals we will summarize the six important uses of delegates.

Abstraction problems of methods and functions

Before we move ahead and we talk about delegates let’s try to understand what problem does delegate solve. Below is a simple class named ‘ClsMaths’ which has a simple ‘Add’ function. This class ‘ClsMaths’ is consumed by a simple UI client. Now let’s say over a period of time you add subtraction functionality to the ‘ClsMaths’ class, your client need to change accordingly to accommodate the new functionality.
In other words addition of new functionality in the class leads to recompiling of your UI client.

In short the problem is that there is a tight coupling of function names with the UI client. So how can we solve this problem?. Rather than referring to the actual methods in the UI / client if we can refer an abstract pointer which in turn refers to the methods then we can decouple the functions from UI.
Later any change in the class ‘ClsMath’ will not affect the UI as the changes will be decoupled by the Abstract pointer. This abstract pointer can be defined by using delegates. Delegates define a simple abstract pointer to the function / method.

Ok, now that we have understood the tight coupling problem and also the solution, let’s try to understand how we can define a simple delegate.

How to declare a delegate?

To implement a delegate is a four step process declare, create, point and invoke.

The first step is to declare the delegate with the same return type and input parameters. For instance the below function ‘add’ has two input integer parameters and one integer output parameter.

private int Add(int i,int y)
{
return i + y;
}

So for the above method the delegate needs to be defined in the follow manner below. Please see the delegate keyword attached with the code.

// Declare delegate
public delegate int PointetoAddFunction(int i,int y);

The return type and input type of the delegate needs to be compatible, in case they are not compatible it will show the below error as shown in the image below.

The next step (second step) is to create a delegate reference.

// Create delegate reference
PointetoAddFunction myptr = null;

The third step is to point the delegate reference to the method, currently we need to point the delegate reference to the add function.

// Point the reference to the add method
myptr = this.Add;

Finally we need to invoke the delegate function using the “Invoke” function of the delegate.

// Invoke the delegate
myptr.Invoke(20, 10)

Below figure sums up how the above four step are map with the code snippet.

Solving the abstract pointer problem using delegates

In order to decouple the algorithm changes we can expose all the below arithmetic function through an abstract delegate.

So the first step is to add a generic delegate which gives one output and takes two inputs as shown in the below code snippet.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);
}

The next step is to expose a function which takes in operation and exposes an attached delegate to the UI as shown in the below code snippet.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}
}

Below is how the complete code snippet looks like. All the algorithm functions i.e. ‘Add’ , ‘Sub’ etc are made private and only one generic abstract delegate pointer is exposed which can be used to invoke these algorithm function.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}

private int Add(int i, int y)
{
return i + y;
}
private int Sub(int i, int y)
{
return i - y;
}
private int Multi(int i, int y)
{
return i * y;
}
private int Div(int i, int y)
{
return i / y;
}
}

So at the client side the calls becomes generic without any coupling with the actual method names like ‘Add’ , ‘Sub’ etc.

int intResult = objMath.getPointer(intOPeration).Invoke(intNumber1,intNumber2);

Multicast delegates

In our previous example we have see how we can create a delegate pointer to a function or method. We can also create a delegate which can point to multiple functions and methods. If we invoke such delegate it will invoke all the methods and functions associated with the same one after another sequentially.
Below is the code snippet which attaches 2 methods i.e. method1 and method2 with delegate ‘delegateptr’. In order to add multiple methods and function we need to use ‘+=’ symbols. Now if we invoke the delegate it will invoke ‘Method1’ first and then ‘Method2’. Invocation happen in the same sequence as the attachment is done.

// Associate method1
delegateptr += Method1;
// Associate Method2
delegateptr += Method2;
// Invoke the Method1 and Method2 sequentially
delegateptr.Invoke();

So how we can use multicast delegate in actual projects. Many times we want to create publisher / subscriber kind of model. For instance in an application we can have various error logging routine and as soon as error happens in a application you would like to broadcast the errors to the respective components.

Simple demonstration of multicast delegates

In order to understand multicast delegates better let’s do the below demo. In this demo we have ‘Form1’, ‘Form2’ and ‘Form3’. ‘Form1’ has a multicast delegate which will propagate event to ‘Form2’ and ‘Form3’.

At the form level of ‘Form1’ (this form will be propagating events to form2 and form3) we will first define a simple delegate and reference of the delegate as shown in the code snippet below. This delegate will be responsible for broadcasting events to the other forms.

// Create a simple delegate
public delegate void CallEveryOne();

// Create a reference to the delegate
public CallEveryOne ptrcall=null;
// Create objects of both forms

public Form2 obj= new Form2();
public Form3 obj1= new Form3();

In the form load we invoke the forms and attach ‘CallMe’ method which is present in both the forms in a multicast fashion ( += ).

private void Form1_Load(object sender, EventArgs e)
{
// Show both the forms
obj.Show();
obj1.Show();
// Attach the form methods where you will make call back
ptrcall += obj.CallMe;
ptrcall += obj1.CallMe;
}

Finally we can invoke and broadcast method calls to both the forms.

private void button1_Click(object sender, EventArgs e)
{
// Invoke the delegate
ptrcall.Invoke();
}

Problem with multicast delegates – naked exposure

The first problem with above code is that the subscribers (form2 and form3) do not have the rights to say that they are interested or not interested in the events. It’s all decided by ‘form1’.
We can go other route i.e. pass the delegate to the subscribers and let them attach their methods if they wish to subscribe to the broadcast sent by ‘form1’. But that leads to a different set of problems i.e. encapsulation violation.
If we expose the delegate to the subscriber he can invoke delegate, add his own functions etc. In other words the delegate is completely naked to the subscriber.

Events – Encapsulation on delegates

Events help to solve the delegate encapsulation problem. Events sit on top of delegates and provide encapsulation so that the destination source can only listen and not have full control of the delegate object.
Below figure shows how the things look like:-
• Method and functions are abstracted /encapsulated using delegates
• Delegates are further extended to provide broadcasting model by using multicast delegate.
• Multicast delegate are further encapsulated using events.

Implementing events

So let’s take the same example which we did using multicast delegates and try to implement the same using events. Event uses delegate internally as event provides higher level of encapsulation over delegates.
So the first step in the publisher (‘Form1’) we need to define the delegate and the event for the delegate. Below is the code snippet for the same and please do notice the ‘event’ keyword.
We have defined a delegate ‘CallEveryOne’ and we have specified an event object for the delegate called as ‘EventCallEveryOne’.

public delegate void CallEveryone();
public event CallEveryone EventCallEveryOne;

From the publisher i.e. ‘Form1’ create ‘Form2’ and ‘Form3’ objects and attach the current ‘Form1’ object so that ‘Form2’ and ‘Form3’ will listen to the events. Once the object is attached raise the events.

Form2 obj = new Form2();
obj.obj = this;
Form3 obj1 = new Form3();
obj1.obj = this;
obj.Show();
obj1.Show();
EventCallEveryOne();

At the subscriber side i.e. (Form2 and Form3) attach the method to the event listener.

obj.EventCallEveryOne += Callme;

This code will show the same results as we have got from multicast delegate example.

Difference between delegates and events

So what’s really the difference between delegates and events other than the sugar coated syntax of events. As already demonstrated previously the main difference is that event provides one more level of encapsulation over delegates.
So when we pass delegates it’s naked and the destination / subscriber can modify the delegate. When we use events the destination can only listen to it.

Delegates for Asynchronous method calls

One of the other uses of delegates is asynchronous method calls. You can call methods and functions pointed by delegate asynchronously.
Asynchronous calling means the client calls the delegate and the control is returned back immediately for further execution. The delegate runs in parallel to the main caller. When the delegate has finished doing his work he makes a call back to the caller intimating that the function / subroutine has completed executing.

To invoke a delegate asynchronously we need call the ‘begininvoke’ method. In the ‘begininvoke’ method we need to specify the call back method which is ‘CallbackMethod’ currently.

delegateptr.BeginInvoke(new AsyncCallback(CallbackMethod), delegateptr);

Below is the code snippet for ‘CallbackMethod’. This method will be called once the delegate finishes his task.

static void CallbackMethod(IAsyncResult result)
{
int returnValue = flusher.EndInvoke(result);
}

Summarizing Use of delegates

There are 6 important uses of delegates:-
1. Abstract and encapsulate a method (Anonymous invocation)

This is the most important use of delegates; it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods. In the previous section we have shown a simple example of a maths class. Later addition of new algorithm functions does not affect the UI code.

2. Callback mechanism
Many times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

3. Asynchronous processing
By using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously. In our previous section we have explained the same in detail.

4. Multicasting – Sequential processing
Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate. This is already explained in the multicast example shown above.

5. Events – Publisher subscriber model
We can use events to create a pure publisher / subscriber model.

Difference between delegates and C++ pointer

C++ pointers are not type safe, in other words it can point to any type of method. On the other hand delegates are type safe. A delegate which is point to a return type of int cannot point to a return type of string.

Why do we need delegates

Simple answer: the code needing to perform the action doesn’t know the method to call when it’s written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of “perform action X at the appropriate time” you need some representation of the action, so that the method calling the action doesn’t need to know the exact implementation ahead of time.

For example:

  • Enumerable.Select in LINQ can’t know the projection you want to use unless you tell it
  • The author of Button didn’t know what you want the action to be when the user clicks on it
  • They also make certain designs cleaner (for example, instead of a switch statement where you call different methods, you call the delegate passed in) and easier to understand and allow for extending your code without changing it
  • Delegates are also the basis of the eventing system – writing and registering event handlers without delegates would be much harder than it is with them

Func and Action Delegates

The Func and Action generic delegates were introduced in the .NET framework version 3.5. They provide flexible delegates with generic parameters that can be used for many purposes, including passing lambda expressions to method parameters.

Generic Delegates

The .NET framework version 3.5 introduced two new sets ofgeneric, parameterised delegates named Func and Action. The Func delegate can be used to encapsulate a method that accepts between zero and four arguments and returns a value. The Action delegate also represents methods with zero to fourparameters but differs from Func in that the method must return void.

The new delegates can be used to reduce the number of delegates that you define explicitly. In situations where you would need a delegate that matches one of the predefined Func or Action signatures, you may decide to use the built-in version. You should consider the naming of the delegate however, as “Func” or “Action” may not express your intent as clearly as another name.

One of the key reasons for the introduction of Func and Action is their relationship with lambda expressions. Every lambda expression’s underlying type is one of these generic delegates. This means that lambda expressions can be passed to method parameters of the appropriate type without explicitly creating a delegate. Many of the LINQ standard query operators accept Func arguments to take advantage of this feature.

Func Delegate

There are five variations upon the Func delegate, each allowing a different number of parameters to be represented. In each case, the return value and the parameters are defined as generic types, allowing the types to vary according to the method that the delegate encapsulates. The five signatures are shown below. Note that the return value of the method is always the last element in the list of types.

public delegate TResult Func<TResult>()
public delegate TResult Func<T, TResult>(T arg)
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3)
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Func<TResult>

The most basic variant of Func is Func<TResult>. This delegate represents methods that return a value but have no parameters. We can demonstrate this with the following sample code. In the example, a new delegate is created using ananonymous method. The method returns a double-precision floating-point number containing a tax rate value.

Func<double> taxRate = delegate { return 17.5; };
Console.WriteLine("{0}%", taxRate());   // Outputs "17.5%"

We can create the same functionality using a lambda expression. Any lambda that accepts no arguments and returns a double is of the type Func<double>. To demonstrate, try executing the following:

Func<double> taxRate = () => 17.5;
Console.WriteLine("{0}%", taxRate());   // Outputs "17.5%"

Using Func with Parameters

Func can represent methods with up to four parameters. In the next example a Func delegate is used to reference an anonymous method that accepts three integer arguments and returns a long integer.

Func<int, int, int, long> multiply = delegate(int a, int b, int c) { return a * b * c; };
Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Again, the code can be recreated using a lambda expression in place of the anonymous method. In this case, the three parameters are named a, b and c. The parameter types do not need to be included in the lambda expression as they, and the return type, are inferred by the compiler.

Func<int, int, int, long> multiply = (a, b, c) => a * b * c;
Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Action Delegate

As with Func, the Action delegate has five variations. These allow the encapsulation of methods that have up to four parameters but do not return a value. Again, all of the parameters are generic types allowing any type to be used for each argument. The five signatures are as follows:

public delegate void Action()
public delegate void Action<T, >(T arg)
public delegate void Action<T1, T2>(T1 arg1, T2 arg2)
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Action

The simplest Action delegate is used with methods that accept no parameters and return no values. The following code demonstrates this with an anonymous method that outputs text to the console.

Action showMessage = delegate { Console.WriteLine("Hello, world"); };
showMessage();                  // Outputs "Hello, world"

As with the Func delegates, Action can be used with lambda expressions. The equivalent of the previous example can be created using a statement lambda, as follows:

Action showMessage = () => { Console.WriteLine("Hello, world"); };
showMessage();                  // Outputs "Hello, world"

Using Action with Parameters

As a final example of the basic use of Action, consider the following example. This code uses a single string parameter for the delegate. The parameter accepts a message to be outputted to the console.

Action<string> showMessage = delegate(string msg) { Console.WriteLine(msg); };
showMessage("Hello, world");    // Outputs "Hello, world"

This example can be recreated using a statement lambda that includes a parameter. In this case the string parameter’s type is inferred.

Action<string> showMessage = (msg) => { Console.WriteLine(msg); };
showMessage("Hello, world");    // Outputs "Hello, world"

Using Generic Delegates as Parameter Types

The Func delegate is commonly used as the type for parameters of methods that accept lambda expressions. These include LINQ standard query operators and similar methods that you create in your own projects. We will demonstrate this with this article’s final example.

The following method defines an array containing the names of ten fruits. The method returns a filtered list of these fruits based upon the delegate passed as the only argument. Note that the types assigned to the Func delegate specify that the encapsulated method must receive a single string parameter and return a Boolean value. We could execute the passed method against each fruit string in a for-each loop. However, for simplicity the example uses the “Where” query operator.

private static string[] Fruit(Func<string, bool> filter)
{
    string[] fruit = new string[] { "Apple", "Banana", "Cherry", "Damson", "Elderberry", "Fig", "Grapefruit", "Huckleberry", "Lemon", "Mango" };
    return fruit.Where(filter).ToArray();
}

To test the method, add the following code to the Main method of a console application. This code calls the Fruit method, applying a filter that returns only fruit with a name shorter than six characters. The fruit names are then outputted.

string[] shortFruit = Fruit(f => f.Length < 6);
foreach (string fruit in shortFruit)
    Console.WriteLine(fruit);

/* OUTPUT Apple Fig Lemon Mango */


Categories: WPF Tags:

Garbage Collection in .NET


Garbage Collection in .NET – How it really works

Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced. This is done in different ways and different manners in various platforms and languages. We will see how garbage collection is being done in .NET.Garbage Collection basis
  • Almost every program uses resources such as database connection, file system objects etc. In order to make use of these things some resources should be available to us.
  • First we allocate a block of memory in the managed memory by using the new keyword.
  • Use the constructor of the class to set the initial state of the object.
  • Use the resources by accessing the type’s members
  • At last CLEAR THE MEMORY

But how many times have programmers forgotten to release the memory. Or how many times the programmers try to access the memory which was cleaned.

These two are the serious bugs, which will lead us to memory leak and commonly occurring. In order to overcome these things the concept of automatic memory management has come. Automatic memory management or Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released. Hurrah… Thanks to Microsoft’s Automatic Garbage collection mechanism.

Automatic Garbage Collection in .NET

When Microsoft planned to go for a new generation platform called .NET with the new generation language called C#, their first intention is to make a language which is developer friendly to learn and use it with having rich set of APIs to support end users as well. So they put a great thought in Garbage Collection and come out with this model of automatic garbage collection in .NET.

They implemented garbage collector as a separate thread. This thread will be running always at the back end. Some of us may think, running a separate thread will make extra overhead. Yes. It is right. That is why the garbage collector thread is given the lowest priority. But when system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time), then garbage collector thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.

How does Garbage collector locate garbage

When an program is loaded in the memory there will be a bunch of memory allocated for that particular program alone and loaded with the memory. This bunch of memory is called Managed Heap in .NET world. This amount of memory will only be used when an object is to be loaded in to the memory for that particular program.

This memory is separated in to three parts :

  • Generation Zero
  • Generation One
  • Generation Two

Ideally Generation zero will be in smaller size, Generation one will be in medium size and Generation two will be larger.

When we try to create an object by using NEW keyword the system will,

  • Calculate the number of bytes required for the object or type to be loaded in to the managed heap.
  • The CLR then checks that the bytes required to allocate the object are available in the reserved region (committing storage if necessary). IF the object fits, it is allocated at the address pointed to by NextObjPtr.
  • These processes will happen at the Generation zero level.

When Generation Zero is full and it does not have enough space to occupy other objects but still the program wants to allocate some more memory for some other objects, then the garbage collector will be given the REALTIME priority and will come in to picture.

Now the garbage collector will come and check all the objects in the Generation Zero level. If an object’s scope and lifetime goes off then the system will automatically mark it for garbage collection.

Note:

Here in the process the object is just marked and not collected. Garbage collector will only collect the object and free the memory.

Garbage collector will come and start examining all the objects in the level Generation Zero right from the beginning. If it finds any object marked for garbage collection, it will simply remove those objects from the memory.

Here comes the important part. Now let us refer the figure below. There are three objects in the managed heap. If A and C are not marked but B has lost it scope and lifetime. So B should be marked for garbage collection. So object B will be collected and the managed heap will look like this.
But do remember that the system will come and allocate the new objects only at the last. It does not see in between. So it is the job of garbage collector to compact the memory structure after collecting the objects. It does that also. So the memory would be looking like as shown below now.
But garbage collector does not come to end after doing this. It will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects.

If Generation One does not have space for objects from Generation Zero, then the process happened in Generation Zero will happen in Generation one as well. This is the same case with Generation Two also.

You may have a doubt, all the generations are filled with the referred objects and still system or our program wants to allocate some objects, then what will happen? If so, then the MemoryOutofRangeException will be thrown.

Dispose

Instead of declaring a Finalizer, exposing a Dispose method is considered as good.

public void Dispose()
{
// all clean up source code here..
GC.SuppressFinalize(this);
}

If we clean up a object, using Dispose or Close method, we should indicate to the runtime that the object is no longer needed finalization, by calling GC.SuppressFinalize() as shown above.

If we are creating and using objects that have Dispose or Close methods, we should call these methods when we’ve finished using these objects. It is advisable to place these calls in a finally clause, which guarantees that the objects are properly handled even if an exception is thrown.

Object.Finalize Method

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the current object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.

This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to GC.SuppressFinalize. During shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible.

Finalize operations have the following limitations:

  • The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling aClose method or a Dispose method.
  • The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
  • The thread on which the finalizer is run is unspecified.
Categories: C# Tags:

Design Patterns


Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns. They are categorized in three groups: Creational, Structural, and Behavioral. Here you will find information on these important patterns.

To give you a head start, the C# source code is provided in 2 forms: ‘structural’ and ‘real-world’. Structural code uses type names as defined in the pattern definition and UML diagrams. Real-world code provides real-world programming situations where you may use these patterns.

A third form, ‘.NET optimized’ demonstrates design patterns that exploit built-in .NET 4.0 features, such as, generics, attributes, delegates, object and collection initializers, automatic properties, and reflection.

 

  Creational Patterns
  Abstract Factory   Creates an instance of several families of classes
  Builder   Separates object construction from its representation
  Factory Method   Creates an instance of several derived classes
  Prototype   A fully initialized instance to be copied or cloned
  Singleton   A class of which only a single instance can exist
  Structural Patterns
  Adapter   Match interfaces of different classes
  Bridge   Separates an object’s interface from its implementation
  Composite   A tree structure of simple and composite objects
  Decorator   Add responsibilities to objects dynamically
  Facade   A single class that represents an entire subsystem
  Flyweight   A fine-grained instance used for efficient sharing
  Proxy   An object representing another object
  Behavioral Patterns
  Chain of Resp.   A way of passing a request between a chain of objects
  Command   Encapsulate a command request as an object
  Interpreter   A way to include language elements in a program
  Iterator   Sequentially access the elements of a collection
  Mediator   Defines simplified communication between classes
  Memento   Capture and restore an object’s internal state
  Observer   A way of notifying change to a number of classes
  State   Alter an object’s behavior when its state changes
  Strategy   Encapsulates an algorithm inside a class
  Template Method   Defer the exact steps of an algorithm to a subclass
  Visitor   Defines a new operation to a class without change

A good explanation can be found at : http://www.dotnetuncle.com/Design-Patterns/dot-net-design-pattern-interview-questions.aspx

Categories: C# Tags:

WPF Triggers


There are three types of triggers:

· Property triggers— Invoked when the value of a dependency property changes

· Data triggers— Invoked when the value of a plain .NET property changes

· Event triggers— Invoked when a routed event is raised

Property Triggers

A property trigger (represented by the Trigger class) executes a collection of Setters when a specified property has a specified value. And when the property no longer has this value, the property trigger “undoes” the Setters.

For example, the following update to buttonStyle makes the rotation only happen when the mouse pointer is hovering over the Button (and sets the Foreground to Black rather than White):

<Style x:Key=”buttonStyle” TargetType=”{x:Type Button}”>

<Style.Triggers>

<Trigger Property=”IsMouseOver” Value=”True”>

<Setter Property=”RenderTransform”>

<Setter.Value>

<RotateTransform Angle=”10″/>

</Setter.Value>

</Setter>

<Setter Property=”Foreground” Value=”Black”/>

</Trigger>

</Style.Triggers>

<Setter Property=”FontSize” Value=”22″/>

<Setter Property=”Background” Value=”Purple”/>

<Setter Property=”Foreground” Value=”White”/>

<Setter Property=”Height” Value=”50″/>

<Setter Property=”Width” Value=”50″/>

<Setter Property=”RenderTransformOrigin” Value=”.5,.5″/>

</Style>

Data Triggers

Data triggers are just like property triggers, except that they can be triggered by any .NET property rather than just dependency properties. (The Setters inside a data trigger are still restricted to setting dependency properties, however.) To use a data trigger, add a DataTrigger object to the Triggers collection and specify the property/value pair. To support plain .NET properties, you specify the relevant property with a Binding rather than a simple property name. The following TextBox has a Style that triggers the setting of IsEnabled based on the value of its Text property, which is not a dependency property. When Text is the string “disabled,” IsEnabled is set to false (which is admittedly an unusual application of a data trigger):

<StackPanel Width=”200″>

<StackPanel.Resources>

<Style TargetType=”{x:Type TextBox}”>

<Style.Triggers>

<DataTrigger Binding=”{Binding RelativeSource={RelativeSource Self}, Path=Text}” Value=”disabled”>

<Setter Property=”IsEnabled” Value=”False”/>

</DataTrigger>

</Style.Triggers>

<Setter Property=”Background” Value=”{Binding RelativeSource={RelativeSource Self}, Path=Text}”/>

</Style>

</StackPanel.Resources> <TextBox Margin=”3″/>

</StackPanel>

Expressing More Complex Logic with Triggers The logic expressed with the previous triggers has been of the form “when property=value, set the following properties.” But more powerful options exist: · Multiple triggers can be applied to the same element (to get a logical OR). · Multiple properties can be evaluated for the same trigger (to get a logical AND).

Logical OR

Because Style.Triggers can contain multiple triggers, you can create more than one with the exact same Setters to express a logical OR relationship:

<Style.Triggers>

<Trigger Property=”IsMouseOver” Value=”True”>

<Setter Property=”RenderTransform”>

<Setter.Value>

<RotateTransform Angle=”10″/>

</Setter.Value>

</Setter>

<Setter Property=”Foreground” Value=”Black”/>

</Trigger>

<Trigger Property=”IsFocused” Value=”True”>

<Setter Property=”RenderTransform”>

<Setter.Value>

<RotateTransform Angle=”10″/>

</Setter.Value>

</Setter>

<Setter Property=”Foreground” Value=”Black”/>

</Trigger>

</Style.Triggers>

This means, “if IsMouseOver is true or if IsFocused is true, apply the rotation and black foreground.”

Logical AND

To express a logical AND relationship, you can use a variation of Trigger called MultiTrigger, or a variation of DataTrigger called MultiDataTrigger. MultiTrigger and MultiDataTrigger have a collection of Conditions that contain the information you would normally put directly inside a Trigger or DataTrigger. Therefore, you can use MultiTrigger as follows:

<Style.Triggers>

<MultiTrigger>

<MultiTrigger.Conditions>

<Condition Property=”IsMouseOver” Value=”True”/>

<Condition Property=”IsFocused” Value=”True”/>

</MultiTrigger.Conditions>

<Setter Property=”RenderTransform”>

<Setter.Value>

<RotateTransform Angle=”10″/>

</Setter.Value>

</Setter>

<Setter Property=”Foreground” Value=”Black”/>

</MultiTrigger>

</Style.Triggers>

This means, “if IsMouseOver is true and if IsFocused is true, apply the rotation and black foreground.” MultiDataTrigger works the same way as MultiTrigger, but with support for plain .NET properties.

EventTriggers

An event trigger (represented by the EventTrigger class) is activated when a routed event is raised. The event is specified by the trigger’s RoutedEvent property, and it can contain one or more actions (objects deriving from the abstract TriggerAction class) in its Actions collection. Animation classes such as DoubleAnimation are not actions themselves, so you can’t add them directly to an EventTrigger’s Actions collection. Instead, animations are placed inside an object known as a Storyboard, which is wrapped in an action called BeginStoryboard. Therefore, placing the preceding DoubleAnimation inside an event trigger that is activated when a Button is clicked can look as follows:

<Button> OK

<Button.Triggers>

<EventTrigger RoutedEvent=”Button.Click”>

<EventTrigger.Actions>

<BeginStoryboard>

<Storyboard TargetProperty=”Width”>

<DoubleAnimation From=”50″ To=”100″ Duration=”0:0:5″ AutoReverse=”True”/>

</Storyboard>

</BeginStoryboard>

</EventTrigger.Actions>

</EventTrigger>

</Button.Triggers>

</Button>

Categories: WPF Tags:

Call User Interface (UI) thread from a Asynchronous method

October 13, 2011 2 comments

using System.Window.Threading;

public static class UIThread

{

       public static Dispatcher {get; set;}

      public static void Run(Action a)

      {

             Dispatcher.BeginEnvoke(a);

      }

}

and call it inside a Asynchronous  method like,

public void AsynchronousMethod()

{

      ….

      ….

      UIThread.Run(delegate()

     {

         CustomUIMethod();

     });

}

Open a ‘File Save Dialog’ window in Silverlight – During Asynchronous Call

October 13, 2011 3 comments

Generally its not possible to open a SaveFileDialog window in Synchronous complete method like,

Wrong Method :

private void Method(Object param)
{
Client consoleClient = new Client(“”);
consoleClient.XXXCompleted+=new EventHandler<XXXCompletedEventArgs>(Method_Completed);
XXXRequest request = new XXXRequest();
request.p_Parameters = param;
consoleClient.XXXAsync(request);
}

void Method_Completed(object sender, XXXCompletedEventArgs e)
{
var result = (YYY)e.Result.XXXResult;
UIThread.Run(delegate() {
SaveFileDialog dlg = new SaveFileDialog();      // This will throw a Exception
dlg.DefaultExt = “.zip”;                        // Default file extension
dlg.Filter = “Zip Archive (.zip)|*.zip”;       // Filter files by extension
if (dlg.ShowDialog() == true)
{

}
}
}

Right Method:

private void Method(Object param)
{
Client consoleClient = new Client(“”);
consoleClient.XXXCompleted+=new EventHandler<XXXCompletedEventArgs>(Method_Completed);
XXXRequest request = new XXXRequest();
request.p_Parameters = param;
consoleClient.XXXAsync(request);
}

void Method_Completed(object sender, XXXCompletedEventArgs e)
{
var result = (YYY)e.Result.XXXResult;
ChildWindowDlg _confirmationWnd = new ChildWindowDlg ();
_confirmationWnd.Show();
}

and inside that ChildWindowDlg  class create a method and call SaveDialog window, like

void Save_ButtonClick(object sender, routedEventArg e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = “.zip”;
dlg.Filter = “Zip Archive (.zip)|*.zip”;
if (dlg.ShowDialog() == true)
{
using(Stream s = (Stream)dlg.OpenFile())
{
s.Write(data, index, length);
s.Close();
}
}
}

Categories: WPF Tags:
%d bloggers like this: