Tuesday, August 13, 2013

WPF Behavior and Trigger

Behaviors are a new concept, introduced with Expression Blend in Version 3, to encapsulate pieces of functionality into a reusable component. These components than can be attached to controls to give them an additional behavior.
The ideas behind behaviors are to give the interaction designer more flexibility to design complex user interactions without writing any code.
Example of a behaviors are drag&drop, input validation, pan and zoom, re-position of elements, etc... The list of possible behaviors is very long.
Imaging an application that has a list of customers and the user can add some of them to subscriber lists. This interaction can be designed by providing an "Add" button next to each subscriber list. But if the interaction designer wants to add drag&drop functionality, he needs to discuss it with the developer and wait until the implementation is done. With behaviors he just drags a drag and drop behavior on each list and we are done.

To add behaviors to an element you need some kind of an extension point. This is an attached property calledInteraction.Behaviors.
This attached property holds the list of behaviors for that element and pass a reference to the element into the behavior. The behavior than can register itself to events and property changes and so extend the functionality of the element.


Triggers in Styles

Triggers define a list of setters that are executed if the specified condition is fulfilled. WPF knows three diferent types of triggers
  • Property Triggers get active, when a property gets a specified value.
  • Event Triggers get active, when a specified event is fired.
  • Data Triggers get active, when a binding expression reaches a specified value.

Property Triggers

A property trigger activates a list of setters when a property gets a specified value. If the value changes the trigger undoes the setters.
 
<Style x:Key="styleWithTrigger" TargetType="Rectangle">
    <Setter Property="Fill" Value="LightGreen" />
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Fill" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>
 
<Rectangle Style="{StaticResource styleWithTrigger}"></Rectangle>

Class Vs Struct and Boxing unboxing

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system, in which a value of any type can be treated as an object.
In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
// The following line boxes i. 
object o = i;  
The object o can then be unboxed and assigned to integer variable i:
o = 123;
i = (int)o;  // unboxing
Feature
Struct
Class
Notes
Is a reference type?
No
Yes*

Is a value type?
Yes
No

Can have nested Types (enum, class, struct)?
Yes
Yes

Can have constants?
Yes
Yes

Can have fields?
Yes*
Yes
Struct instance fields cannot be initialized, will automatically initialize to default value.
Can have properties?
Yes
Yes

Can have indexers
Yes
Yes

Can have methods?
Yes
Yes

Can have events?
Yes*
Yes
Structs, like classes, can have events, but care must be taken that you don’t subscribe to a copy of a struct instead of the struct you intended.
Can have static members (constructors, fields, methods, properties, etc.)?
Yes
Yes

Can inherit?
No*
Yes*
Classes can inherit from other classes (or object by default). Structs always inherit fromSystem.ValueType and are sealed implicitly
Can implement interfaces?
Yes
Yes

Can overload constructor?
Yes*
Yes
Struct overload of constructor does not hide default constructor.
Can define default constructor?
No
Yes
The struct default constructor initializes all instance fields to default values and cannot be changed.
Can overload operators?
Yes
Yes

Can be generic?
Yes
Yes

Can be partial?
Yes
Yes

Can be sealed?
Always*
Yes
Structs are always sealed and can never be inherited from.
Can be referenced in instance members using this keyword?
Yes*
Yes
In structs, this is a value variable, in classes, it is a readonly reference.
Needs new operator to create instance?
No*
Yes
C# classes must be instantiated using new. However, structs do not require this. While new can be used on a struct to call a constructor, you can elect not to use new and init the fields yourself, but you must init all fields and the fields must be public!

Sunday, August 11, 2013

SQL Query Interview


Finding Duplicate Records
SELECT     orgName, COUNT(*) AS dupes  
FROM         organizations  
GROUP BY orgName  
HAVING      (COUNT(*) > 1)

Finding the nth highest salary of an employee

select max(Emp_Sal) from Employee_Test

--3rd Highest Salary
select min(Emp_Sal) from Employee_Test where Emp_Sal in
(select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc)

Deleting duplicate rows from a table

Using a temporary or staging table

Let the table employee_test1 contain some duplicate data like:-
CREATE TABLE Employee_Test1
(
Emp_ID INT,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test1 VALUES (1,'Anees',1000);
INSERT INTO Employee_Test1 VALUES (2,'Rick',1200);
INSERT INTO Employee_Test1 VALUES (3,'John',1100);
INSERT INTO Employee_Test1 VALUES (4,'Stephen',1300);
INSERT INTO Employee_Test1 VALUES (5,'Maria',1400);
INSERT INTO Employee_Test1 VALUES (6,'Tim',1150);
INSERT INTO Employee_Test1 VALUES (6,'Tim',1150);
Step 1: Create a temporary table from the main table as:-
select top 0* into employee_test1_temp from employee_test1
Step2 : Insert the result of the GROUP BY query into the temporary table as:-
insert into employee_test1_temp
select Emp_ID,Emp_name,Emp_Sal
from employee_test1
group by Emp_ID,Emp_name,Emp_Sal
Step3: Truncate the original table as:-
truncate table employee_test1
Step4: Fill the original table with the rows of the temporary table as:-
insert into employee_test1
select * from employee_test1_temp
Now, the duplicate rows from the main table have been removed.
select * from employee_test1
gives the result as:-
Emp_ID Emp_name   Emp_Sal
1 Anees    1000
2 Rick    1200
3 John    1100
4 Stephen    1300
5 Maria    1400
6 Tim    1150

(b) Without using a temporary table

;with T as
(
 select * , row_number() over (partition by Emp_ID order by Emp_ID) as rank
 from employee_test1
)

delete
from T
where rank > 1

The result is as:-
Emp_ID Emp_name   Emp_Sal
1 Anees    1000
2 Rick    1200
3 John    1100
4 Stephen    1300
5 Maria    1400
6 Tim    1150

Wednesday, August 7, 2013

Dependency Property and Attached Property

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 callsGetValue(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 callDependencyProperty.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 theIsMouseOver 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 callingDependencyProperty.Register() you call DependencyProperty.RegisterReadonly(). This returns you aDependencyPropertyKey. 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 toDependencyPropertyKey.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:
<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);
}
 
 

Sunday, August 4, 2013

.NET Threading Part II

There is one thread pool per process. The thread pool has a default size of 250 worker threads per available processor, and 1000 I/O completion threads.

I might ask the candidate to describe at least 2 or 3 different ways to create multi-threaded applications in C#.
  • Explicit use of Thread class
  • Threadpool
  • Task Parallel Library
  • Action class with lambda functions
  • BeginInvoke
  • BackgroundWorker
I would also inquire how one might end up with an application that is multi-threaded without ever explicitly creating a thread.
  • Event handlers can run in another thread (SerialPort.DataReceived comes to mind, as does one or two of the three Timers in .Net).
You may also wish to talk about methods for creating re-entrant code.
  • lock
  • Monitor.Wait and Monitor.Pulse
  • ManualResetEvent
  • static classes/methods
Some more information could come from a post I wrote here.

Extension Method Part II

An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.
Static ClassExtension methods in Visual Studio

Example

Note
First, here is a custom extension method defined in a program written in the C# language. Generally, you will want to store your extension method class in a separate source file, such as "ExtensionMethods.cs" in your project.
Note:This file should store a static class with public static extension methods.
Public
Then:In the rest of your source code, you can invoke these extension methods in the same way as instance methods.
Program that uses extension method on string: C#

using System;

public static class ExtensionMethods
{
    public static string UppercaseFirstLetter(this string value)
    {
 //
 // Uppercase the first letter in the string this extension is called on.
 //
 if (value.Length > 0)
 {
     char[] array = value.ToCharArray();
     array[0] = char.ToUpper(array[0]);
     return new string(array);
 }
 return value;
    }
}

class Program
{
    static void Main()
    {
 //
 // Use the string extension method on this value.
 //
 string value = "dot net perls";
 value = value.UppercaseFirstLetter(); // Called like an instance method.
 Console.WriteLine(value);
    }
}

Output

Dot net perls
Program icon
In the first part of the program text, you can see an extension method declaration in the C# programming language. An extension method must be static and can be public so you can use it anywhere in your source code.
Tip:The extension method is called like an instance method, but is actually a static method. The instance pointer "this" is a parameter.
And:You must specify the this-keyword before the appropriate parameter you want the method to be called upon.
This keyword
The only difference in the declaration between a regular static method and an extension method is the "this" keyword in the parameter list. If you want the method to receive other parameters, you can include those at the end.
You can call an extension method in the same way you call an instance method. In Visual Studio, an extension method in IntelliSense has a downward arrow on it. This is a visual clue to how methods are represented.
Also:The text "(extension)" is used in IntelliSense. This applies to Visual Studio 2010.

LINQ

LINQ: language integrated query
There are many extension methods available in the .NET Framework currently used. These extension methods were written by Microsoft and are available in all C# programs targeting recent versions of the .NET Framework.
Tip:On most of the extension methods, you need to add the "using System.Linq" directive to the top of the source text.
LINQ Examples

Discussion

This section provides information
Extension methods can have many arguments. You can even use variable "params" arguments with extension methods, as with any method. Because extension methods are static methods, there is no significant performance difference.
Params
Extension methods are basically an altered-syntax form of instance methods in the C# programming language. They affect the high-level representation of the source text, not the low-level implementation.

Summary

Summary
We examined extension methods in the C# language. You can add extension methods to any type, even a value type. The original representation of the type does not change. Extension methods affect syntax, not execution.