Friday, December 30, 2011

WPF : Issue with red border appearing for Error elements even when parent panel is collapsed/hidden


In WPF there is an issue when you are using default error temple to show red borders around textboxes/datepickers/combo-boxes or any databound control.

Untill you have the panel visible to you everything looks okay, but moment you collapse that panel or hide it, the red boxes around those controls remain visible.
You can get away with this problem in following 2 steps

Step 1) First you need to change default error template to have only AdornedElementPlaceHolder, you don’t need any other control in error template.

Step 2) Then you need to change Trigger for “Validation.HasError” property, to mark border for control with Red color as shown below.


Wednesday, December 28, 2011

WPF Memory Leak (DataTemple)


In WPF programming, there is a well-known memory leak which occurs when you use a DataTemplate to display tabs in Tabcontrol.  

If in a tab control you are creating tabs dynamically and also generating contents of those tabs using datatemplate binding as show below
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
                <views:SomeView  />
    </DataTemplate>

Then, you are injecting a potential memory leak in your application. Because whenever your tab is highlighted WPF runtime creates a new instance if “SomeView” class and uses it.
As of now only workaround for this problem is to use a ViewFactory which will supply your views. This ViewFactory will have a static object which will create only one instance of “SomeView” class and use it through application lifetime.
So, your changed code would look like
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
        <ContentPresenter Content="{x:Static local:ViewsFactory.SomeViewInstance}" />
    </DataTemplate>

And implementation of your ViewFactory class would be something like
 public static class ViewsFactory
    {
        #region SomeViewInstance

        private static SomeView _SomeViewInstance = null;

        /// <summary>
        /// Gets or sets the  SomeViewInstance  property. 
        /// </summary>
        public static SomeView SomeViewInstance
        {
            get
            {
                if (_SomeViewInstance == null)
                {
                    _SomeViewInstance = new SomeView();
                }

                return _SomeViewInstance;
            }
        }

        #endregion
    }

Hope it helps!!!

Sunday, December 25, 2011

WPF : Setting default focus on a control when window is shown


Here is the trick to set focus on a particular control when windows is started up in WPF. It doesn’t require any code-behind.
Add FocusManager.FocusElement in Window tag as show below and bind it with the element that should receive focus when windows is started up.


Sunday, December 18, 2011

.Net ServiceHost Directives


1) For WCF Dataservice :
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory"
Service="NwdDataService" %>
Here as we can see that  BwDataService is wcf data service class which exposes Northwind database entities.
Factory property indicates DataServiceHostFactory which has logic of taking an entity and exposing its content using OData pattern.

2) For WCF service :
<%@ ServiceHost Language="C#" Debug="true" Service="Service" CodeBehind="~/App_Code/Service.cs" %>
Here we have path for code behind class file which happens to be Service.cs, this file contains definition of Service class.
Service defines name for wcf service class which has implementation of wcf service class.

3) Web Service
<%@ WebService Language="C#" CodeBehind="~/App_Code/WebService.cs" Class="WebService" %>
Here also we have location of Codebehind file and service class name which defines actual service content.

Saturday, December 17, 2011

WPF: Draw a 3D Border


The coolest technique to draw a3D border in wps is use a border element as a child element for existing border element.

1)      Create a regular border
2)      Decide on which side you want to show 3D edge
3)      Add another border as its child element, and set its as show in following code.
<Border Height="200" Width="299" BorderThickness="1,26,26,26" BorderBrush="LightBlue">
<Border Height="148" Width="270" BorderThickness="0,1,1,1" BorderBrush="Blue" />
          </Border>
its o/p would be as shown below.




Tuesday, December 13, 2011

Launching WSAT (Website Administration Tool) for a web site


1)      Open website in Visual Studio.
2)      Open “ Solution Explorer”, and Click on “ASP.Net Configuration” Icon as shown in below image


3)      It will launch WSAT as show below

Friday, December 9, 2011

WPF : Creating a Behavior for a TextBox which invokes a command when Enter key is pressed



Goal :  Execute a command when an enter key is pressed ,while focus is in a text-box.  This command can be a command bounded to a Button or any UI element.
Look at following code
Here I am going to create an attached property of ICommand type, which would be applied to TextBoxes. While that property is getting attached to a TextBox, I register an EventHandler for KeyUp event and in that I check for Enter key cod, if it matches I execute attached command property for that object.

/// <summary>
/// EnterKeyCommand Attached Dependency Property
/// </summary>
public static readonly DependencyProperty EnterKeyCommandProperty =
DependencyProperty.RegisterAttached("EnterKeyCommand"typeof(ICommand), typeof(TextBoxBehaviours), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(OnEnterKeyCommandChanged)));
 
/// <summary>
/// Gets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static ICommand GetEnterKeyCommand(DependencyObject d)
{
 return (ICommand)d.GetValue(EnterKeyCommandProperty);
}
 
/// <summary>
/// Sets the EnterKeyCommand property. This dependency property 
/// indicates ....
/// </summary>
public static void SetEnterKeyCommand(DependencyObject d, ICommand value)
{
 d.SetValue(EnterKeyCommandProperty, value);
}
 
/// <summary>
/// Handles changes to the EnterKeyCommand property.
/// </summary>
private static void OnEnterKeyCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
 ICommand oldEnterKeyCommand = (ICommand)e.OldValue;
 ICommand newEnterKeyCommand = (ICommand)d.GetValue(EnterKeyCommandProperty);
 if (d is TextBox )
 {
   (d as TextBox).KeyUp += new KeyEventHandler(TextBoxBehaviours_KeyUp);
 }
}

Tuesday, December 6, 2011

Hashtable

  • It’s a data structure which is used to store a collection of key/value items, each object has a HashCode which uniquely identifies that object and based on it the object is places in a bucket from where its retrieved as and when needed.  
  • To generate Hash-Code for an object a Hashing algorithm is used,  it’s the efficiency of Hashing algorithm which decides performance of Hashtable.  A good hashing algorithm will always generate a   unique and same hashcode for any object.  
  • Each object in hashtable is stored in a bucket, and a bucket corresponds to a hashcode.  Based on number of items stored on bucket, load-factor for hashtable is collected.   Loadfactor is defined as a ration of number of items present in bucket to its size.  Best value of Loadfactor is 1, but it can be any number between 0 to 1 based on memory available and requirement.
  • As elements are added to a Hashtable, the actual load factor of the Hashtable increases. When the actual load factor reaches the specified load factor, the number of buckets in the Hashtable is automatically increased to the smallest prime number that is larger than twice the current number of Hashtable buckets.
  • Hashtable in .Net implemens IDictionary<TKey,TValue> interface.The objects which are used as keys are supposed to implement “IEqualityComparer” or “IHashProvider” & “IComparer”. IEqualityComparer is nothing but it’s a union of IHasProvider and IEqualityComparer.
  • Based on your requirement you can avoid implementing IHashProvider for Key Object by implementing it separately and then passing that implementation in Hashtable constructor.
  • IHashProvider has method GetHashCode which is used to get Hash-Code and that Hash-Code is used for deciding a bucket in which the element will be placed. This condition makes it compulsory for key objects to be immutable, as if they change then their corresponding Hash-Code will also change.
  • IComparer has Equal method which is used for comparing 2 objects.
  • Hastable in C# implements IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable.

Monday, December 5, 2011

5 OOAD principles


1) Open Close Principle (OCP): It states that a class/module/package should be open for extension and close for modification.
2) Dependency Inversion Principle (DIP): It states that classes should not depend on concrete classes instead they should depend on abstract classes.
3) Interface Segregation Principle (ISP): It states that a class should not be needed to implement any part of any interface which it’s not going to use.
4) Singe Responsibility Principle (SRP): It states that a class should have only one responsibility.
5) Liskov’s Substitution Principle (LSP):It states that  a class a derived class should be able to completely replace base class without changing their behavior.

Sunday, December 4, 2011

Steps for Creating a Dependency Property


Here are the steps for creating a Dependency property
1) Derive your class from DependencyObject class, and define a readonly static variable of type Dependency Property
Eg. public static readonly DependencyProperty FlavorProperty;

2) Add static constructor for parent class and using DependencyProperty.Regitser method register property created in Step 1
Eg.
static ParentClass()
{
 ParentClass.FlavorProperty = DependencyProperty.Register("Flavor",typeof(string), typeof(PieClass), md);
}

Steps 1 and 2 can be combined as
public static readonly DependencyProperty FlavorProperty = DependencyProperty.Register("Flavor",typeof(string), typeof(PieClass), md);


3) Create an instance property which for class which will wrap dependency property
public string Flavor
{
 get
 {
  return (string)GetValue(PieClass.FlavorProperty);
 }
 set
 {
   SetValue(PieClass.FlavorProperty, value);
 }
}
Same steps need  to be followed for creating attached properties by replacing DependencyProperty.Register by DependencyProperty.RegisterAttached method.

Here is the Dependency Property Setting Precedence list, I am just going to list their names which are self explanatory more details you can find from http://msdn.microsoft.com/en-us/library/ms743230.aspx
1) Property system coercion.
2) Active animations, or animations with a Hold behavior
3) Local value
4) TemplatedParent template properties
5) Implicit style
6) Style triggers
7) Template triggers
8) Style setters
9) Default (theme) style.
10) Inheritance.
11) Default value from dependency property metadata




Saturday, December 3, 2011

Some do’s and Don’ts’s and tips on Finalize, Dispose and GC


1)      Override Finalize only when you want GC to perform cleanup for unmanaged resources.
2)      GC calls Finalize method just before reclaiming memory from that object, so you don’t have any control when Finalize method is called.
3)      Dispose method is called to cleanup managed resources and it can be called anytime when object is not needed in program by calling Dispose method.
4)      Objects which have destructor/Finalize methods take 2 steps before memory is claimed from them.
5)      If you don’t want Finalize to be called for a particular object, then call GC.SuppressFinalize for that object anytime, best place for this call would be in Dispose method. To re-register that object for Finalization you can call GC.ReRegisterForFinalize.
6)      Freachable is pronounced as F-Rechable and it means Finalizer-Reachable queue.
7)      Dispose method is not thread-safe, if your object is accessed by more than 1 thread then you should make Dispose a thread safe method.
8)      If your program uses a significant amount of unmanaged memory then you should call GC.AddMemoryPressure to make GC aware of memory chuck which was consumed by program through unmanaged way, and same way when memory is released for that unmanaged resource you can call GC.RemoveMemoryPressure .
9)      You can call GC.KeepAlive on an object when you fear that Object may be calimed by GC while its being used. This kind of scenario can occur when you have passed any object using ByRef to some unmanaged method , and that unmanaged application is using it forever.
10)   By default every application in 32 bit computer gets 2 GB of virtual address space.
11)   GC works in 2 modes which are Server and Workstation.
12)   Workstation garbage collection is always used on a computer that has only one processor, regardless of the <gcServer> setting. If you specify server garbage collection, the CLR uses workstation garbage collection with concurrency disabled.
13)   In case of Server GC mode, there is a separate dedicated thread which manages collection.
14)   Number of threads on server = Number of application * Number of processor.
15)   Since .Net 4 Non-concurrent garbage collection became Background garbage collection.
16)   Concurrent Garbage collection / Background Garbage collection is performed on Generation 2 items in Workstation mode.
17)   Background garbage collection is not currently available for server garbage collection.
18)   Background garbage collection can be defined as collection of generation 2 objects by a separated thread which is paused whenever there is foreground garbage collection happening.
19)   Concurrent garbage collection has a slightly bigger working set (compared with non-concurrent garbage collection), because you can allocate objects during concurrent collection. However, this can affect performance, because the objects that you allocate become part of your working set. Essentially, concurrent garbage collection trades some CPU and memory for shorter pauses.
20)   Background garbage collection removes allocation restrictions imposed by concurrent garbage collection, because ephemeral garbage collections can occur during background garbage collection.

21)   Finalizers should always be protected, not public or private so that the method cannot be called from the application's code directly and at the same time, it can make a call to the base.Finalize method.

22)  When an application instantiates a new object, if the object's type defines a Finalize method, a pointer to the object is placed on the finalization queue just before the type's instance constructor is called. The finalization queue is an internal data structure controlled by the garbage collector. Each entry in the list points to an object that should have its Finalize method called before the object's memory can be reclaimed.
23)  The garbage collector scans the finalization queue looking for pointers to the objects which are identified as garbage. And when found, it is moved to freachable queue which is another data structure maintained by garbage collector's internal. A special high-priority CLR thread is dedicated to calling Finalize methods and CLR uses a high priority thread to finalize these objects which appear in this freachable queue. The object in Freachable queue is reachable only to this finalization thread. So When writing the finalization method it should concentrate on disposing the local and native objects and shouldn't execute any that makes any assumptions about the thread that's executing the code.
24)   For more information on Garbage Collection please refer  http://msdn.microsoft.com/en-us/library/0xy59wtx.aspx.



A trick to find how many times a sub string exists in a Main String


The coolest trick to find how many times a substring exist in a main string is to use RegEx class, we can see following sample code:

        static void Main(string[] args)
        {
            string words = "This is a list of words, with: a bit of punctuation" +
                           "\tand a tab character.";

            string[]split = Regex.Split(words, "is");

            Console.Write("Number of times : {0}", split.Length);

            Console.ReadLine();
        }


Output of above code would be :


Friday, December 2, 2011

Evolution of Extension Methods


When I first heard about extension method in C#, I was excited that’s what I have been in OOPS. But to tell you the history about extension methods they got evolved out of Operator overloading, if you closely monitor syntax for Operator overloading which used to be in C++ as :
Public static Type1 operator op(Type1 t1,Type1 t2)
{
…….
}
 
Here Type1 could be any class, and “op” is any operator which is +,++, -, ..ext
 
An example of “+” operator overloading for “Complex” class would be
 
Example:
public static Complex operator +(Complex c1, Complex c2) 
{
   return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
 
 
Now if you closely monitor syntax for extension methods it is…
 
Extension Methods:
Public static Type2 MethodName(this Type1 objType1,…. [other type variables])
{
….
}

Here Type2 could be any type that would be returned by Extension method, and as it says first variable has to be of the type for which you are defining extension method…
So if you monitor it closely you can see that I am attaching an extra method to a type by defining its functionality for Methodname (which is like an operator for me).

WPF - Trick to Show selected item as ComboBox tooltip


A simple trick to show Selected Text in combobox as tooltip using WPF. You would need this when width of ComboBox is limited and its selected content is not displayed fully. So, to let the user see what they have selected you can show same content in tooltip when they hover their mouse on that combobox.

You would bind Tooltip property in Combox as shown below.