Showing posts with label Code Snippets. Show all posts
Showing posts with label Code Snippets. Show all posts

Monday, 1 November 2010

Silverlight ListBox Multi Select

For those who need to set the selected items (Multi Select) of the list box to a property,
you can use the following class:

     public static class ListBoxSelectedItems 
     {
         private static readonly DependencyProperty SelectedItemsBehaviorProperty =
             DependencyProperty.RegisterAttached(
                 "SelectedItemsBehavior" ,
                 typeof(SelectedItemsBehavior),
                 typeof(ListBox),
                 null);
 
         public static readonly DependencyProperty ItemsProperty = 
    DependencyProperty.RegisterAttached(
                 "Items" ,
                 typeof(IList),
                 typeof(ListBoxSelectedItems),
                 new PropertyMetadata(null, ItemsPropertyChanged));
 
         public static void SetItems(ListBox listBox, IList list) 
     {listBox.SetValue(ItemsProperty, list); }
         public static IList GetItems(ListBox listBox) 
     { return listBox.GetValue(ItemsProperty) as IList; }
 
         private static void ItemsPropertyChanged(DependencyObject d, 
    DependencyPropertyChangedEventArgs  e)
         {
             var  target = d as ListBox ;
             if  (target != null )
             {
                 GetOrCreateBehavior(target, e.NewValue as IList );
             }
         }
 
         private static SelectedItemsBehavior GetOrCreateBehavior(ListBox target, IList list)
         {
             var behavior = target.GetValue(SelectedItemsBehaviorProperty) 
        as SelectedItemsBehavior;
 
             if(behavior == null)
             {
                 behavior = new  SelectedItemsBehavior (target, list);
                 target.SetValue(SelectedItemsBehaviorProperty, behavior);
             }
 
             return behavior;
         }
     }
 
     public class SelectedItemsBehavior 
     {
         private readonly ListBox _listBox;
         private bool _isListChanging = false ;
         private bool _isSelectionChanging = false ;
         private IList _boundList;
 
         public SelectedItemsBehavior(ListBox listBox, IList boundList)
         {
             _boundList = boundList;
             _listBox = listBox;
             SetSelectedItems();
 
             // attach the selection changed event 
             _listBox.SelectionChanged += OnSelectionChanged;
 
             // attach the collection changed event 
             var collectionChanged = _boundList as INotifyCollectionChanged;
             if(collectionChanged != null )
             {
                 collectionChanged.CollectionChanged += BoundList_CollectionChanged;
             }
         }
 
         private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
         {
             // only fire this event when the list is not changing to prevent circular loop 
             if  (!_isListChanging)
             {
                 _isSelectionChanging = true;
 
                 _boundList.Clear();
 
                 foreach  (var item in _listBox.SelectedItems)
                 {
                     _boundList.Add(item);
                 }
 
                 _isSelectionChanging = false;
             }
         }
 
         private void BoundList_CollectionChanged(object sender, 
     System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
         {
             // only fire this event when the list is not changing to prevent circular loop 
             if  (!_isSelectionChanging)
             {
                 _isListChanging = true;
 
                 SetSelectedItems();
 
                 _isListChanging = false;
             }
         }
 
         private void SetSelectedItems()
         {
             if  (listBox.SelectionMode == SelectionMode .Single)
             {
                 if  (_boundList != null && _boundList.Count > 0)
                     _listBox.SelectedItem = _boundList[0];
             }
             else 
             {
                 _listBox.SelectedItems.Clear();
 
                 foreach(object item in _boundList)
                 {
                     // References in _boundList might not be the same as in _listBox.Items  
                     int  i = _listBox.Items.IndexOf(item);
                     if  (i >= 0)
                         _listBox.SelectedItems.Add(_listBox.Items[i]);
                 }
             }
         }
 
         private void ODataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
         {
             SetSelectedItems();
         }
     }
 


Thursday, 29 October 2009

Cool Generic Delegates in C#

Here are some cool generic delegates (.NET 3.5) I find useful in my day to day coding.

  • Action Delegate
    • Action
    • Action(T)
    • Action(T1, T2)
    • Action(T1, T2, T3)
    • Action(T1, T2, T3, T4)
  • Predicate Delegate
    • Predicate<T>(T obj)
  • Func Delegate
    • Func<T, TResult>
    • Func<T1, T2, T3, T4, TResult>
    • Func<T1, T2, T3, TResult>
    • Func<T1, T2, TResult>
    • Func<TResult>

ACTION DELEGATE

The Action delegate encapsulates a method that has no return value and accepts up to four parameters. Action alone represents no parameter, Action(T), Action(T1, T2) etc… represents the number of parameters.

Simple example: using Action to replace Console.WriteLine, because Console.WriteLine accepts a single string parameter, we can simply assign it to the Action<string> and call action(“ABC”) which is equivalent to the Console.WriteLine(“ABC”)

static void Main(string[] args)

{

Action<string> action = Console.WriteLine;

action("ABC");

Console.ReadLine();

}

Or you can pass the action as a parameter and use it as such, using lambda, which will print “stringA1” to the console:

static void Main(string[] args)

{

DoSomething((s, n) =>

{

Console.WriteLine(s + n);

});

Console.ReadLine();

}

private static void DoSomething(Action<string, int> action)

{

string rawString = "stringA";

int rawNumber = 1;

action(rawString, rawNumber);

}

PREDICATE DELEGATE

The Predicate(T) delegate encapsulates a method that returns a Boolean value and accepts a single parameter.

A simple example:

static void Main(string[] args)

{

Predicate<byte> predicate = bit =>

{

return bit == 1 ? true : false;

};

// This will return true

Console.WriteLine(predicate(1));

// This will return false

Console.WriteLine(predicate(0));

Console.ReadLine();

}

In fact, most LINQ Queries uses this predicate delegate, one simple example is the .Find method:

static void Main(string[] args)

{

var list = new List<string>()

{

"a",

"b"

};

string a = list.Find(i => i == "a");

Console.WriteLine(a);

Console.ReadLine();

}

Another useful usage is in LINQ statements like so:

var list = new List<int>()

{

1,

2

};

Predicate<int> p = val => val == 1;

var i = from item in list

where p(item)

select item;

FUNC DELEGATE

The Func delegate is the most powerful of the lot. A Func can return any type (TResult) and accepts zero or up to four input parameters.

var list = new List<string>

{

"one",

"two",

"three"

};

// This indicates a return type of boolean, and accepts

// two input parameters of IEnumerable<string> and string

// respectively.

Func<IEnumerable<string>, string, bool>

funcPredicate = (collection, item) =>

{

if (collection != null && collection.Count() > 6)

{

return collection.Contains("one");

}

return false;

};

var i = from item in list

where funcPredicate (list, item)

select item;

There you have it, the useful delegates you will definitely find handy!

Other delegates I will cover in a later post will include Expression<T>, EventHandler<TEventArgs>, Converter<TInput, TOutput> and Comparison<T>.

Have fun coding!

Friday, 24 July 2009

Concatenating multiple rows as a single column in a row in SQL Server 2005/2008 (TSQL)

Assuming we have a one to many table, and we need to list all children items per parent in a single row, here is a quick way of doing it in SQL Server 2005/2008 (TSQL)

The following will concatenate all children names belonging to the parent with a ',' delimiter.

 SELECT DISTINCT parent.id, parent.name, CA, CB
FROM ParentTable parent
CROSS APPLY
(
SELECT child.name + ','
FROM ChildA child
WHERE child.parentId = parent.id
ORDER BY child.name
FOR XML PATH('')
) childA(CA)
CROSS APPLY
(
SELECT child2.name + ','
FROM ChildB child2
WHERE child2.parentId = parent.id
ORDER BY child2.name
FOR XML PATH('')
) childB(CB)

Monday, 6 July 2009

Parameter constraint on dynamic type

It can be accomplished by using the new() keyword.
"new()" indicates the Type T's constructor must not contain any parameters.

Example:

public class A<T> where T : B, new()

Thursday, 23 April 2009

Attaching Inline Event using Lambda

textBox.TextChanged += (o, e) => { SomeMethod(); };

Friday, 17 April 2009

Coalesing in C#

// numberAfterCoalescing will be equals to 100 in this case
int? number = null; int numberAfterCoalescing = (number ?? 100);

Tuesday, 14 April 2009

Dynamic Class Instantiation

public void DynamicInstantiation(string fullname)

{  

    // Assign the fully qualified name to a string variable  

    // fullname = "Namespace.ClassName";  

    // Or to get the namespace dynamically  

    // string fullname = object.GetType().Namespace + ".ClassName";   

    // Then Create the object  

    SampleClass dynclass = (SampleClass)System.Activator.CreateInstance(Type.GetType(fullname));

}