Monday, April 25, 2011

Array of WaitHandles (ManualResetEvent, AutoResetEvent, …) when waiting for operations to complete …

Reference :- http://blog.cincura.net/231837-array-of-waithandles-manualresetevent-autoresetevent-when-waiting-for-operations-to-complete/

Often, when you discover the beauty of multithreading and parallelism, you find a need to run some operations in parallel and wait for completion. Fairly common scenario. Although now, with .NET Framework 4, you can write it using Task Parallel Library‘s Parallel.Invoke, there are scenarios when you need to plug it in into some other methods/parameters, so you’ll do it yourself explicitly with threads or better to say ThreadPool.

The method I see from time to time looks basically like this:



Though it’s not wrong, except the ManualResetEvents are not Disposed, it’s suboptimal. You’re wasting resources creating array of these objects.

But if you think about it, you can write it better. Better in a way for scaling, performance and memory consumption.




I’m simply using one synchronization object (and using using statement ), because I’m really interested in only when all tasks are done (one stuff), and decrementing the total number of tasks every time one finishes. Using Interlocked class I’m sure no race condition will occur and I’ll get the right results. After it reaches zero I’m signaling I’m done and the method can continue.

Fewer resources, atomic operations usage … better/faster results.

Saturday, April 23, 2011

WPF Timer (DispatcherTimer)

Reference :- http://www.dotnetspider.com/resources/29705-WPF-Timer-DispatcherTimer.aspx

Most of us are from a background of C# (or VB.Net). You must have some point of time come across a scenario for performing a repetitive GUI operation after certain period of time. The solution in most cases has been the WinForm's Timer.


What about WPF ? Does it have a Timer ?

WPF no different to WinForm has it's own Timer equivalent. It is called DispatcherTimer. There are other options to get the Timer behavior but one of the most efficient for a Window based operation is the DispatcherTimer.

I have attached a sample Timer application demonstrating the functionality.
The window has a "Start timer" and "Stop timer" functionality. There is an input TextBox which takes the Timer frequency in milliseconds.

Just enter the Timer frequency in millisecond and hit the "Start timer" button. There is a status bar which displays the status of the time. At start it will be blank. When you start the Timer it will display the current Time and when you stop the Timer it will display the "Stopped" status.

Let us discuss the code to look into how we use it.

XAML,

< Window x:Class="TimerSample.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Timer" Height="148" Width="300" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">

1000 Not working

Code behind,

public partial class Window1 : Window{ DispatcherTimer _timer; public Window1() { InitializeComponent(); _timer = new DispatcherTimer(); _timer.Tick += new EventHandler(delegate(object s, EventArgs a) { status.Text = "Started: " + DateTime.Now; //MessageBox.Show("Dummy message"); //notify timer end //this.Close(); //close application }); } private void Start_Click(object sender, RoutedEventArgs e) { // Set the Interval _timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(time.Text)); // Start the timer _timer.Start(); status.Text = "Started"; } private void Stop_Click(object sender, RoutedEventArgs e) { // Stop the timer _timer.Stop(); status.Text = "Stopped"; }}

We have a local variable of type DispatcherTimer - _timer. We manipulate this variable to start and stop the timer. At start we initialize the variable with an Event delegate to fire whenever the Timer ticks.

_timer.Tick += new EventHandler(delegate(object s, EventArgs a) { status.Text = "Started: " + DateTime.Now; //MessageBox.Show("Dummy message"); //notify timer end //this.Close(); //close application });

I have specifically left the commented lines to show the different possibilities that can be done in the Event delegate. Whenever the Timer ticks the event is fired and Status bar is updated with the most recent DateTime.

DispatcerTimer runs on the UI thread and hence does not need marshaling back and forth as we have to do in the normal cases of a Thread.

Monday, April 18, 2011

Dependency Properties

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.



How to create a DependencyProperty

To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty must always end with ...Property. This is a naming convention in WPF.
To make it accessable as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the DependencyProperty as key.
Important: Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.
If you are using Visual Studio, you can type propdp and hit 2x tab to create a dependency property.
// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty = 
     DependencyProperty.Register( "CurrentTime", typeof(DateTime),
     typeof(MyClockControl), new FrameworkPropertyMetadata(DateTime.Now));
 
// .NET Property wrapper
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(CurrentTimeProperty); }
    set { SetValue(CurrentTimeProperty, value); }
}
 
 
Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on the dependency property.
new FrameworkPropertyMetadata( DateTime.Now, 
                       OnCurrentTimePropertyChanged, 
                       OnCoerceCurrentTimeProperty ),
                       OnValidateCurrentTimeProperty );
 
 

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

Coerce Value Callback

The coerce callback allows you to adjust the value if its outside the boundaries without throwing an exception. A good example is a progress bar with a Value set below the Minimum or above the Maximum. In this case we can coerce the value within the allowed boundaries. In the following example we limit the time to be in the past.
private static object OnCoerceTimeProperty( DependencyObject sender, object data )
{
    if ((DateTime)data > DateTime.Now )
    {
        data = DateTime.Now;
    }
    return data;
}
 
 

Validation Callback

In the validate callback you check if the set value is valid. If you return false, an ArgumentException will be thrown. In our example demand, that the data is an instance of a DateTime.
private static bool OnValidateTimeProperty(object data)
{
    return data is DateTime;
}
 
 


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); }
}
 
 


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:
>
    
>
 
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);
}
 
 


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...
    });
} 
 
 


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 );
 
 
For more details click here.

Wednesday, April 6, 2011

Disabling TFS Automatic Check out

Reference :- http://www.woodwardweb.com/teamprise/disabling_tfs_a.html

From time to time I hear from people who dislike the automatic check out behaviour common with TFS. One of the great things about TFS is the the pending changes list that shows you the files you have currently checked out and allows you to easily undo any un-intentional check outs. While I personally find the auto-checkout features a productivity boon - like most things there is a preference that you can use to adjust the default behaviour if you find it causes problems with the way you like to work.
In Visual Studio 2008 (with the Team Explorer 2008 installed), go to Tools, Options, Source Control, Environment and change the Checked-in items for Saving and Editing to "Prompt for check out" rather than the default which is "Check out automatically".
Options dialog of Visual Studio showing Source Control, Environment settings
This will then prompt you before the automatic checkout occurs and give you the opportunity to cancel if you wish.
In Eclipse with Teamprise installed, go to Window, Preferences (or Eclipse, Preferences on the Mac) and then Teamprise, Source Control to enable prompting before check out.
Teamprise Source Control preferences
That said, I would strongly encourage you to stick with the defaults and have Multiple check outs enabled in TFS for your Team Project and also keep the Pending Changes view on screen (in VS View, Other Windows, Pending Changes or in Eclipse Window, Show View, Other, Teamprise, Pending Changes). That way you can always see what you have checked out at any time and immediately undo any check-outs that you no longer need.

http://www.woodwardweb.com/teamprise/disabling_tfs_a.html

SQL SERVER – Difference Between Unique Index vs Unique Constraint

References :- http://blog.sqlauthority.com/2007/04/26/sql-server-difference-between-unique-index-vs-unique-constraint/

Unique Index and Unique Constraint are the same. They achieve same goal. SQL Performance is same for both.
Add Unique Constraint
ALTER TABLE dbo.<tablename> ADD CONSTRAINT<namingconventionconstraint> UNIQUE NONCLUSTERED(
<
columnname>
)
ON [PRIMARY]
Add Unique Index
CREATE UNIQUE NONCLUSTERED INDEX<namingconventionconstraint> ON dbo.<tablename>
(
<
columnname>
)
ON [PRIMARY]

There is no difference between Unique Index and Unique Constraint. Even though syntax are different the effect is the same. Unique Constraint creates Unique Index to maintain the constraint to prevent duplicate keys. Unique Index or Primary Key Index are physical structure that maintain uniqueness over some combination of columns across all rows of a table. It is a convenient way to enforce a Unique Constraint for SQL Server.
Reference : Pinal Dave (http://blog.SQLAuthority.com)