May 11, 2011

To wrap or Not to Wrap Exceptions

Posted in Uncategorized at 13:38 by winglinglang

We had this argument whether we should wrap C# Exception or not.

I found this articel that explains it nicely:

When wrapping an Exception we catch the exception and create a new exception with the InnerException property set to the old exception.

This should not be done, unles for critical Exceptions where the bottom exception does not make sense in the function context.

Also be aware that if you just re-throw the exception it could reset the Stack Trace. Depending on if you want this behavior or not.

See Example Below; The Exception is thrown in a function called Test3


private void test1()
 {
   try
   {
     test2();
   }
   catch (Exception e)
   {
     throw e;
   }
 }

System.OperationCanceledException was unhandled
Message=The operation was canceled.
Source=DataContextTest
StackTrace:
at DataContextTest.MainWindow.test1() //Note this should indicate DataContextTest.MainWindow.test3()
at DataContextTest.MainWindow.Action_Click(Object sender, RoutedEventArgs e)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()


private void test1()
 {
   try
   {
     test2();
   }
   catch (Exception e)
   {
     throw;
   }
 }

System.OperationCanceledException was unhandled
Message=The operation was canceled.
Source=DataContextTest
StackTrace:
at DataContextTest.MainWindow.test3()
at DataContextTest.MainWindow.test2()
at DataContextTest.MainWindow.test1()
at DataContextTest.MainWindow.Action_Click(Object sender, RoutedEventArgs e) i
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()

October 17, 2010

Deleting Sub Folders

Posted in Uncategorized at 09:08 by winglinglang

After running a tool like svn, it creates a ‘.svn’ folder in each sub folder. To clean your folder from the svn folders or delete all sub folders run the command below in the Windows  ‘Command’ window.

Open the Command window by typing ‘cmd’ in the ‘Run’ Box.

I Recommend you first test what will be deleted by running this command.

for /r %i in (.svn) do @echo rd %i /S /Q

After you are happy that the correct folders will be deleted run the same command without the echo.

for /r %i in (.svn) do rd %i /S /Q

 

November 15, 2009

WPFToolkit Calendar Control Step trough

Posted in Uncategorized tagged , at 14:07 by winglinglang

In this section we will dissect the wpf toolkit calendar control. To learn more on how Microsoft codes for wpf.

One of the challenges I had writing my own calendar control and some of the samples I looked at on the web was to display the day’s in the calendar control. At first it sounds easy, you use a uniform grid control with 7 columns and bind to a list of day’s, another solution was to use a list box and dived the days into weeks, then you have a week template and list box template. All very well. The problem was where do you store the list of day’s neatly away from the controls user yet make it easy to access for the data binding and flexible for new templates and styles to be applied.

Let see how the toolkit team did it.

WPF Toolkit Calendar Control

Calendar

WPF ToolKit Calendar Control

Lets start at the Calendar style, From the main Calendar style they have a CalendarItem.  The CalendarItem is a WPF Control on its own, a nice future of the Toolkit Calendar is that it support multiple Views, this is all handled by the CalendarItem style. Having the Calendar Control Contain one CalendarItem is a clever way of Hiding the Control Code from the actual code the developer will want to see when consuming the control.

The Toolkit CalendarItem use a Grid to display the day’s with 7 columns and 7 rows fields called ‘PART_MonthView‘ the grid is contained in parent grid with 2 rows and 3 Columns. The parent grid displays the left and right arrows and the heading.

Filling the Days in the PART_MonthView

After the Control Template is set, The C# code extracts all the Template ‘PARTs’ and assign it too internal variables prefixed with underscore. the one we are interested in is ‘_monthView’ which is the grid with 7 rows and 7 columns.

_monthView is populated with ‘CalendarDayButton’ Controls using a standard loop. The CalendarItem Control Populates the grid via a function ‘PopulateGrids()’

PopulateGrids() Sets the CalendarDayButton Owner and assign the events and binds the style property.

private void SetMonthModeDayTitles() Sets the Day Titles by looping trought the 1 ste 7 cells  in the Month View Grid. Then the day’s are set using the SetMonthModeCalendarDayButtons function.

Here is a quick view of this function.

private void SetMonthModeCalendarDayButtons()
{
 DateTime firstDayOfMonth = DateTimeHelper.DiscardDayTime(DisplayDate);
 int lastMonthToDisplay = GetNumberOfDisplayedDaysFromPreviousMonth(firstDayOfMonth);
 bool isMinMonth = DateTimeHelper.CompareYearMonth(firstDayOfMonth,DateTime.MinValue) <= 0;
 bool isMaxMonth = DateTimeHelper.CompareYearMonth(firstDayOfMonth,DateTime.MaxValue) >= 0;
 int daysInMonth =_calendar.GetDaysInMonth(firstDayOfMonth.Year, firstDayOfMonth.Month);
 int count = ROWS * COLS;

 //Loop the cell's ignoring the first seven as they contain the day names for the title.
 for (int childIndex = COLS; childIndex < count; childIndex++)
 {
 CalendarDayButton childButton = _monthView.Children[childIndex] as CalendarDayButton;
 Debug.Assert(childButton !=null);
 int dayOffset = childIndex - lastMonthToDisplay- COLS;

  //Set DayButton Control with the new Content.
 if ((!isMinMonth || (dayOffset >= 0)) &&(!isMaxMonth || (dayOffset < daysInMonth)))
 {
 DateTime dateToAdd =_calendar.AddDays(firstDayOfMonth, dayOffset);
 //Sets and Calculates all the Properties for the Day
 SetMonthModeDayButtonState(childButton, dateToAdd);
 childButton.DataContext = dateToAdd;
 childButton.SetContentInternal(DateTimeHelper.ToDayString(dateToAdd));
 }
 else
 {
 SetMonthModeDayButtonState(childButton, null);
 childButton.DataContext = null;
 childButton.SetContentInternal(DateTimeHelper.ToDayString(null));
 }
 }
}
  • You Hide the complexities of the month and day calculations by wrapping the actual control by anouther more userfriendly control. This they did by wrapping CalendarItem with Calendar Control. CalendarItem is in a separate name space than the Calendar control, this hide’s the control from normal developers only intrested in the Calendar, but for more advance coding you can still access the the base control by adding the primitives names space.
  • They do not recreate the Day Controls but rather just update the content’s.
  • There was no magic to make this work its basic clever wpf and C# coding. What was intresting to me how much they still did in code.  When starting WPF you tend to do everything in WPF, and that is not always the correct or best way of doing things.

You can find the complete WPF ToolKit and source code here.

http://wpf.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29117

November 8, 2009

List2Code

Posted in Open Source tagged , , at 19:56 by winglinglang

List2Code is very Simple Application that takes comma delimited list and runs it a template to create code that can be copied and pasted in your application. The Goal is to quickly create large amount of properties or xml files using a comma delimited list.

Screen shot

List2Code Main Window

The Code and Source Code is available on CodePlex http://list2code.codeplex.com/

Here is some Template’s You can use.

Template Example’s

Clone a Object Template

{0}=fromobj.{0};

*where the fromobj the object is that you want to clone from.

Normal Property Template

public {0} {1} {get;set;}

INotifyPropertyChanged Property Template


private {0} m_{1};
public {0} {1}
{
get { return m_{1}; }
set
{
if (value != m_{1})
{
m_{1} = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("{1}"));
}
}
}

a Usefull SQL Query to retrieve the column names from a database table, You can copy and paste the columns names into the list2code content box to generate properties.
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableNameGoesHere'
ORDER BY ORDINAL_POSITION
[thanks to http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=57418]

November 4, 2009

Expression Blend 3

Posted in Quick Guide tagged , at 08:28 by winglinglang

I Just installed Expresion Belnd 3, and was playing around. It has many new controls and features that was not in Blend 2, Some intresting links to get me started is.

October 30, 2009

Creating a WPF Control

Posted in Quick Guide tagged , , , at 21:15 by winglinglang

Here is Some Basic Stuff to remember when creating a new WPF Control.

1. Remeber to set the the static property DefaultStyleKeyProperty This property links your XAML style to your Control. If you dont set this property a Default style settings your Control will not find the contol type to set it.

Example:

DefaultStyleKeyProperty.OverrideMetadata(typeof(ControlName), new FrameworkPropertyMetadata(typeof(ControlName)));

2. a Generic Control should focus on properties and functions to maunipilate the control behaviour and display.

Type reference cannot find public type named

Posted in Trouble Shooting tagged at 21:11 by winglinglang

Error “Type reference cannot find public type named” while running my applications. The following fixed help for me.

In my XAML template I had a button control calling a Command.
<button column=”0″ command=”MonthSelector.DecreaseMonth”/>

MonthSelector is the class name in the namespace.

xmlns:gclr=”clr-namespace:GControls.Date”

You need to add the namespace in the command refrence.

Example:

<button column=”0″ command=”gclr:MonthSelector.DecreaseMonth”></button>

Other Possible Problems

  • Having the assembly in the namespace while in the same dll as it is used in. Remove the assembly name.