Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, January 23, 2012

C# out Parameter–Tuples (Multiple return values)

There will be times when you want to get multiple return values from methods and are to lazy to create a new object for it. Well recently the .NET framework now supports a couple of ways to return multiple values with more ease.
First of all we have the “Tuple” being now available and coming from the F# side of the .NET framework. A tuple is no more then a typesafe way to return a collection of different objects. As an example:

   1: public Tuple<string,int,double> TupleReturn()
   2: {
   3:     //... some DB action
   4:     return Tuple.Create("FirstItem", 1, 500.00);
   5: }

This method return as tuple with the first item being a string, the second an integer and the third a double. To work with this return value we can do the following:


   1: var x = TupleReturn();
   2: var i1 = x.Item1;
   3: var i2 = x.Item2;
   4: var i3 = x.Item3;
   5:  
   6: Console.WriteLine(String.Format("The type of i1 is {0}",i1.GetType()));
   7: Console.WriteLine(String.Format("The type of i2 is {0}",i2.GetType()));
   8: Console.WriteLine(String.Format("The type of i3 is {0}",i3.GetType()));
   9: Console.ReadLine();

The result will be:


  • The type of i1 is System.String
  • The type of i2 is System.Int32
  • The type of i3 is System.Double

To read more about tuples go to: MSDN (1) or Extended Tuples


The next solution to return multiple is to work with the “out” parameter. This type of method parameter allows for the method to use the same variable as it was passed to it. So in short, any change to the parameter will be reflected to the variable passed to it. Next to this, the method itself can off course still return a normal value.



   1: public string OutReturn(out string name, out string surName)
   2: {
   3:     //... some DB action
   4:     name = "Ferrari";
   5:     surName = "Bently";
   6:     return "are awesome!";
   7: }

The one thing to not about this type of parameter is that is has to be initialized before you pass it to the method! If you do so, you can use it as follows:


   1: string name;
   2: string surName;
   3: var r = OutReturn(out name,out surName);
   4: Console.WriteLine(String.Format("{0} and {1} {2}",name,surName,r));
   5: Console.ReadLine();


Which results into:
Ferrari and Bently are awsome!


Enjoy!

Friday, January 20, 2012

Creating a basic Silverlight control–DateItem

When you first start working in Silverlight every control you use is something basic and sometimes you just want more then the basic controls.
The good people of Microsoft allowed us to create custom controls so we can do nearly anything in Silverlight to have great interaction with the user,
thus increasing user experience.
Today I’ll show you one of the first controls I ever made, It was for a small website that needed a nice way to show the date.
They kind of wanted a small calendar style icon.
The result was as following:
DateItem
In XAML I didn’t have to do more then(NL-BE date format):
<ctrl:DateItem Date="01/02/2012" />
To start of create a new “Silverlight Class Library” and call it for example “CustomControlLibrary.DateItem”:

Project 
Rename the Class1.cs file to DateItem.cs ( don’t forget to rename the class itself! ).
Add a new folder called “Themes” and add a new “Silverlight Resource Dictionary” to the folder. Rename that to “generic.xaml”.
This will automatically be recognized by Silverlight.
Open the generic.xaml file and paste the following code inside:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlLibrary.DateItem">
</ResourceDictionary>
Make sure the xmls:local is referring to your own namespace, shouldn’t you have chosen to make it CustomControlLibrary.DateItem.
We have now the fundamentals for most, if not all custom controls.

  • a resourcedictionary
  • class file
We first want to create our layout of the control so I created the following code:
<Style TargetType="local:DateItem">
<
Setter Property="Template">
<
Setter.Value>
<
ControlTemplate TargetType="local:DateItem">
<
Border Width="50" Height="50" BorderBrush="#A0A0A0" BorderThickness="1">
<
Grid Margin="1">
<
Grid.RowDefinitions>
<
RowDefinition Height="auto" />
<
RowDefinition Height="*" />
<
RowDefinition Height="auto" />
</
Grid.RowDefinitions>
<
StackPanel HorizontalAlignment="Stretch" Margin="1,1" Grid.Row="0" Background="#DDE2E5">
<
StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<
TextBlock FontSize="9" x:Name="MonthPart" />
<
TextBlock FontSize="9" Margin="3,0,0,0" x:Name="YearPart" />
</
StackPanel>
</
StackPanel>
<
Viewbox Grid.Row="1" Stretch="Uniform" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<
TextBlock x:Name="DatePart"/>
</
Viewbox>
<
TextBlock Margin="0" HorizontalAlignment="Center" FontSize="9" Grid.Row="2" x:Name="DayOfTheWeekPart" />
</
Grid>
</
Border>
</
ControlTemplate>
</
Setter.Value>
</
Setter>
</
Style>
What I did here is create a “Style” that should be applied to the “DateItem” control, by overriding the template we can customize the look of our control.
We created a new “ControlTemplate”, with a border inside and a grid to arrange all the values. Very important: setting up the right names for your inner-controls.

This is because we will have to address them from the classfile. I created the following important controls:

  • a textblock (MonthPart)
  • a textblock (YearPart)
  • a textblock (DatePart)
  • a textblock (DayOfTheWeekPart)

Notice that I suffix them with “Part” this will allow easier recognition in the classfile. Talking of which, lets look at that.
The first thing I usually do is make the classfile “Blendable”, meaning it is easier to work with in Blend. I do this by adding the necessary class-attributes:



   1: [TemplatePart(Name = Parts.DatePART, Type = typeof(TextBlock))]
   2: [TemplatePart(Name = Parts.MonthPART, Type = typeof(TextBlock))]
   3: [TemplatePart(Name = Parts.YearPART, Type = typeof(TextBlock))]
   4: [TemplatePart(Name = Parts.DayOfTheWeekPART, Type = typeof(TextBlock))]
   5: public class DateItem : Control
   6: {
   7: }
Also notice I derived from the “Control” class.
By making an innerclass called Parts, it’s easier to work with the different parts. (It’s here that the naming in the resourcefile matters).


   1: public static class Parts
   2: {
   3:     public const string DatePART = "DatePart";
   4:     public const string MonthPART = "MonthPart";
   5:     public const string YearPART = "YearPart";
   6:     public const string DayOfTheWeekPART = "DayOfTheWeekPart";
   7: }
The next thing we need is a property on the object on which we can set our date, either manually or by databinding. This type of properties are dependency properties.


   1: public static readonly DependencyProperty DateProperty =
   2:             DependencyProperty.Register("Date", typeof(string), typeof(DateItem), new PropertyMetadata(DateTime.Now.ToShortDateString(),OnDateChanged));
   3:  
   4: private static void OnDateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   5: {
   6:     ((DateItem) d).UpdateDate(e.NewValue.ToString());
   7: }
   8:  
   9: protected virtual void UpdateDate(string value)
  10: {
  11:     Debug.Assert(DateTime.TryParse(value, out _date), "Date couldn't be converted to datetime value");
  12:  
  13:  
  14:     _day.Text = string.Format("{0:dd}", _date);
  15:     _year.Text = string.Format("{0:yy}", _date);
  16:     _month.Text = string.Format("{0:MMM}", _date);
  17:     _dayOfTheWeek.Text = string.Format("{0:ddd}", _date);
  18: }
  19:  
  20: public string Date
  21: {
  22:     get
  23:     {
  24:         return (string)GetValue(DateProperty);
  25:     }
  26:     set
  27:     {
  28:         SetValue(DateProperty, value);
  29:     }
  30: }
There we go and we have a dependency property to get our date, with databinding and if the the “Date” property isn’t set, we set it to the current date.
Now to apply our resourcedictionary style template, we must tell the class to override its defaultstylekey, this can be done in the constructor of the class:


   1: public DateItem()
   2: {
   3:     DefaultStyleKey = typeof(DateItem);
   4: }
To link our style controls with the code and apply our date to the right controls, we have to get them out of the template as control objects and apply the date to them.
We do this by overriding the “OnApplyTemplate()” methode.
To support the object we create them as private fields first:


   1: private TextBlock _day;
   2: private TextBlock _month;
   3: private TextBlock _year;
   4: private TextBlock _dayOfTheWeek;
   5: private DateTime _date;


   1: public override void OnApplyTemplate()
   2: {
   3:     base.OnApplyTemplate();
   4:  
   5:     _day = GetTemplateChild(Parts.DatePART) as TextBlock;
   6:     _dayOfTheWeek = GetTemplateChild(Parts.DayOfTheWeekPART) as TextBlock;
   7:     _year = GetTemplateChild(Parts.YearPART) as TextBlock;
   8:     _month = GetTemplateChild(Parts.MonthPART) as TextBlock;
   9:  
  10:     Debug.Assert(_day != null, "Date textblock can not be null");
  11:     Debug.Assert(_year != null, "Year textblock can not be null");
  12:     Debug.Assert(_month != null, "Month textblock can not be null");
  13:     Debug.Assert(_dayOfTheWeek != null, "DayOfTheWeek textblock can not be null");
  14:     
  15:     UpdateDate(Date);
  16: }
In this methode we fetch every part and make an object of it, then for safety I assert those objects to check if they are not "null”. Then we call the “UpdateDate()” method to apply our date.
To learn more about the “out” parameter and optional parameters, I have a new blogpost ready to talk about those ;)
At this point we should have a ready to use DateItem!
Just built it, reference the project and you can use it in other projects.

Enjoy!

Thursday, September 1, 2011

An other view on a Switch Case

As first post I'm was inspired by this post. I thought about what Anoop said and started thinking about possible variations.

But lets start with the basics, right. If you stranded on this page I assume you know a wee bit about programming or a lot more then I do. (Just to note that I'm always open for tips, hints, criticism, ...)


A basic switch case in c# looks like this:
   1: var str = "Toad";
   2:             switch (str)
   3:             {
   4:                 case "Bird" :
   5:                     Console.WriteLine("It's a bird!");
   6:                     break;
   7:                 case "Toad" :
   8:                     Console.WriteLine("It's a toad!");
   9:                     break;
  10:                 default:
  11:                     Console.WriteLine(string.Format("I don't know a {0}.",str));
  12:                     break;
  13:             }




Nothing really special about it, when you have read through Anoop’s post you can alter a switch case to be the following:



   1: public class SwitchCase : Dictionary<string, Action>
   2:    {
   3:        public Action DefaultAction
   4:        {
   5:            get;
   6:            set;
   7:        }
   8:  
   9:        public SwitchCase(Action defaultAction)
  10:        {
  11:            DefaultAction = defaultAction;
  12:        }
  13:  
  14:        public void Eval(string param)
  15:        {
  16:            if (ContainsKey(param))
  17:            {
  18:                this[param]();
  19:            }
  20:            else
  21:            {
  22:                if (DefaultAction == null)
  23:                    throw new NullReferenceException("Default action may not be null.");
  24:                DefaultAction();
  25:            }
  26:        }
  27:    }



Usage:




   1: var sc = new SwitchCase(() => Console.WriteLine("The default action"))
   2:                          {
   3:                              {"Case1", () => Console.WriteLine("Case 1")},
   4:                              {"Case2", () => Console.WriteLine("Case 2")},
   5:                              {"Case3", () => Console.Write("Case 3")}
   6:                          };
   7:  
   8:             sc.Eval("Case1");

Or converting this into a generic becomes:


   1: public class ActionSwitchCase<TTkey> : Dictionary<TTkey, Action>
   2:     {
   3:         public Action DefaultAction
   4:         {
   5:             get;
   6:             set;
   7:         }
   8:  
   9:         public ActionSwitchCase(Action defaultAction)
  10:         {
  11:             DefaultAction = defaultAction;
  12:         }
  13:  
  14:         public void Eval(TTkey key)
  15:         {
  16:             if (ContainsKey(key))
  17:             {
  18:                 this[key]();
  19:             }
  20:             else
  21:             {
  22:                 if (DefaultAction == null)
  23:                     throw new NullReferenceException("Default action may not be null.");
  24:                 DefaultAction();
  25:             }
  26:         }
  27:     }



Which you could use as:



   1: var asc = new ActionSwitchCase<string>(() => Console.WriteLine("Default!"))
   2:                                         {
   3:                                             {"Case1",() => Console.WriteLine("Case 1")},
   4:                                             {"Case2",() => Console.WriteLine("Case 2")},
   5:                                             {"Case3",() => Console.WriteLine("Case 3")}
   6:                                         };
   7:  
   8:             asc.Eval("Case1");



While actually putting it a bit further is applying it to functions, creating the following class:


   1: public class FuncSwitchCase<TTKey, TInpuType, TResultType> :
   2:         Dictionary<TTKey, Func<TInpuType, TResultType>>
   3:     {
   4:         public Func<TInpuType, TResultType> DefaultFunction
   5:         {
   6:             get;
   7:             set;
   8:         }
   9:  
  10:         public FuncSwitchCase(Func<TInpuType, TResultType> defaultFunc)
  11:         {
  12:             DefaultFunction = defaultFunc;
  13:         }
  14:  
  15:         public TResultType Eval(TTKey key, TInpuType param)
  16:         {
  17:             TResultType output;
  18:  
  19:             if (ContainsKey(key))
  20:                 output = this[key].Invoke(param);
  21:             else
  22:             {
  23:                 if (DefaultFunction == null)
  24:                     throw new NullReferenceException("Default function may not be null.");
  25:                 output = DefaultFunction(param);
  26:             }
  27:  
  28:             return output;
  29:         }
  30:     }



Which then could be used as:


   1: Func<string,string> f1 = (x) => x + "function 1";
   2:             Func<string, string> f2 = (x) => x + "function 2";
   3:             Func<string, string> df = (x) => x + "default";
   4:  
   5:             var fsc = new FuncSwitchCase<string, string, string>(df)
   6:                           {
   7:                               {"Case1", f1},
   8:                               {"Case2", f2}
   9:                           };
  10:  
  11:             Console.WriteLine(fsc.Eval("Case1","To hell with..."));

This opens a few doors in create switch cases. And credits to Anoop’s post putting down the idea.

Regards,
Kyor