Debug bindings in XAML with Breakpoints

19. April 2011

    In Silverlight 5 (Beta), one of the most interesting and important enhancement is the ability to set breakpoints in XAML and debug bindings. Before Silverlight 5 (and in WPF), debugging the binding is a difficult task, there is no direct way to put debug code.

Following are the options that we use to debug the binding errors.

  1. Look at the output window for all tyeh errors and try to resolve.
  2. Write dummy converters and attach to all the bindings. and set breakpoint inside the converter.

The binding xaml breakpoints in Silverlight 5 is a more flexible, powerful, and saves the time spend in debugging.

But the sad part is that WPF is not getting this ability to set breakpoint in XAML in the next version too. Pete Brow, Developer Division Community Program Manager at Microsoft mentioned this in his post.

He also mentioned that, "While from the outside they're very similar, the Silverlight and WPF codebases are very very different. It's actually a ton of work to implement some things in WPF due to those differences. In fact, most of Silverlight is native code whereas much of WPF is managed. If it were just an easy imp, the team would have done it.".

So, We have to wait till WPF 6(?) to get the same featuter.

.Net Tips, wpf , , ,

WPF : Not Using StringFormat when the data is null.

21. March 2011

 

When you are using StringFormat in XAML, if the data is null, the oputput will be just the format text.

For example, consider the following example.

 

<TextBlock Text="{Binding Path=Amount, StringFormat=Total: {0:C}}" />

 

When the Amount is null, the output of the above binding will be "Total:" This doesn't makes any sense. So, most of teh cases, you have to hide the text or display alternative text. You can achive this with converters (IValueConverter).

There is another simple way to do it without writing any C# code using TargetNullValue. Here is how you can achieve the result.

<TextBlock Text="{Binding Path=Amount,  
TargetNullValue={x:Static System:String.Empty},  
StringFormat=Total: {0:C}}" />

Note:-

If you are using TargetNullValue in Binding, if the value is null, it will ignore the StringFormat. In some cases, you might want to display the Text with formatted string. In this case, you cannot use the above mentioned method. you have to implement your converter.

.Net Tips, .Net, wpf , ,

Useful Visual studio Shortcut keys

12. January 2011


We all are familiar with visual studio shortcut keys, But not all the shortcut keys. I have listed few usefull shortcut keys that we don't use frequently.

Shortcut Key

Functionality

Ctrl-W

Selects the word containing the cursor or the word to the right of the cursor

Ctrl-= 

Selects from the current location in the editor back to the previous location in the navigation history

F7

Switches from the design view to the code view in the editor

Shift-F7

Switches from the code view to the design view in the editor

Shift-F12 

Finds a reference to the selected item or the item under the cursor (Find all references of the current item)

Ctrl-G

Displays the Go to Line dialog. If in TFS work item, it displays go to work item dialog.

Ctrl-] 

Moves the cursor to the matching brace in the document.
If the cursor is on an opening brace, this will move to the corresponding closing brace and vice versa

Ctrl-K, Ctrl-I

Shows a quick description about whatever object the cursor is currently resting on

Ctrl-Down Arrow 

Scrolls text down one line without moving the cursor.
This is useful for scrolling without losing your place.

Ctrl-Up Arrow 

Scrolls text up one line without moving the cursor.
This is useful for scrolling without losing your place.

Ctrl-K, Ctrl-C

Marks the current line or selected lines of code as a comment.

Ctrl-K, Ctrl-U

Uncomments the line/ or selected lines if commented.

Ctrl-K, Ctrl-\ 

Removes all the whitespaces in the selection or removes whitespace adjacent to the cursor if there is no selection.

Ctrl-L

Cuts all selected lines or the current line if nothing has been selected to the clipboard

Ctrl-Shift-L

Deletes all selected lines or the current line if no selection has been made

Ctrl-Enter 

Inserts a blank line above the cursor

Ctrl-Shift-Enter 

Inserts a blank line below the cursor

Ctrl-Shift-Spacebar 

Displays a tooltip that contains information for the current parameter, based on the current language

 

.Net Tips, Technical

VS 2008 Disable XAML Design View and Always load in full XAML View

28. September 2010

    Most of the developers don't like the XAML design view in VS 2008 as it takes long time to load the desin view and some times it will crash the visual studio also.

The design view can be disabled in visual studio 2008.

1. Go to Tools-Options in menu.

2. Select Text Editor -> XAML -> Miscellaneous node in the popup.

3. Check the 'Always open documents in full XAML view' checkbox.

 

Even if this is not improving load time , try this option.

Hope It helps.

 

.Net Tips, .Net, wpf , ,

WPF FrameworkElement Width, MinWidth, MaxWidth and ActualWidth

17. September 2010

 

There are 3 Properties which specifies the Width Information for FrameworkElement (parent class for WPF Controls). Width , MinWidth and MaxWidth. As the name says, With Property specifies the Width of the Element and MinWidth and MaxWidth specifies the constraints for the Width of the element. If there is any conflict in these values, MinWidth takes higher priority and then MaxWidth, and finally if both of these values are within bounds, Width. If you Apply all these properties and if you want to check the rendered Width, then you can use ActualWidth Property (which is read only property).

In short, 

 

  • Width is the requested Width and MinWidth, MaxWidth are constraints for the Width.
  • ActualWidth is the rendered size. 

 

The same Applies to Height, MinHeight, MaxHeight and ActualHeight Properties.

 

Here is Example, 

Scenario 1:

If you set Width = 75, MinWidth = 25, MaxWidth = 100

and the calculated width (ActualWidth) = 75 (Width value is used as the value set for Width is withing the bounds of Min and Max Widths)

 

Scenario 2:

if you set Width = 25, MinWidth = 50, MaxWidth = 75, 

and the calculated width (ActualWidth) = 50 (Min Width takes precedence as the requested width is smaller than Min Width)

 

Scenario 3:

if you set Width =100, MinWidth = 50, MaxWidth = 75, 

and the calculated width (ActualWidth) = 75 (Max Width takes precedence as the requested width satisfies Min Width and is bigger than Max Width)


Hope this helps.

 

.Net Tips, Technical, wpf , , , ,

ScrollViewer default to HorizontalScrollBarVisibility and VerticalScrollBarVisibility values

17. September 2010

 

If you check the WPF(as well as Silverlight) ScrollViewer's default values for HorizontalScrollBarVisibility (Disabled) and VerticalScrollBarVisibility (Visible). 

I was curious to know Why does the ScrollViewer default to HorizontalScrollBarVisibility Disabled and VerticalScrollBarVisibility Visible, and found this page which explains the reason.

"For compatibility with the WPF defaults, of course. :) Regarding the obvious next question about why those values are the WPF defaults, I don't know. Auto/Auto would seem more generally useful to me and, in fact, the WPF ListBox (and Silverlight ListBox) overrides the ScrollViewer defaults to set Auto/Auto! But maintaining compatibility wins, so the Silverlight ScrollViewer defaults to the same values used by WPF."

 

In most of our application we need HorizontalScrollBarVisibility and VerticalScrollBarVisibility to be Auto by default. To achieve this behaviour, we can add teh following style in your applications style.

 

<Style TargetType="{x:Type ScrollViewer}">

            <Setter Property="HorizontalScrollBarVisibility" Value="Auto"/>

            <Setter Property="VerticalScrollBarVisibility" Value="Auto"/>

      </Style>

 

 

.Net Tips, Technical, wpf , , ,

Useful Extension Methods - Part 1 of n

28. August 2010

    Extension methods let you add new features to existing classes, even classes that you didn't write yourself. You can use them to add new methods to your own types, types written by others including basic data types.

In this series, I Will be posting some useful extension methods for the all the types. To begin with I am providing extension methods for strings.

String Extension Methods -1:

IsValidUrl

Checks if the string is a valid URL

public static bool IsValidUrl(this string input) 

{

    Regex rx = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");

    return rx.IsMatch(input);

}

//Usage

"http://elangovanr.com".IsValidUrl();

 

IsValidEmailAddress

Checks if the input string is a valid email address

public static bool IsValidEmailAddress(this string input)

{

    Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");

    return regex.IsMatch(input);

}

 

//Usage

"admin@elangovanr.com".IsValidEmailAddress();

 

IsNotNullOrEmpty

Checks if the input is not null or empty, negation of IsNullOrEmpty

public static bool IsNotNullOrEmpty(this string input) 

{

    return !String.IsNullOrEmpty(input);

}

 

//Usage

"test".IsNotNullOrEmpty();

 

ToBase64

Converts the string to base 64 encoded string

static public string ToBase64(this string input)

{

    byte[] toEncodeAsBytes

        = System.Text.ASCIIEncoding.ASCII.GetBytes(input);

    string returnValue

        = System.Convert.ToBase64String(toEncodeAsBytes);

    return returnValue;

}

 

//Usage

"test".ToBase64();

 

FromBase64

Decodes base 64 encoded string

static public string FromBase64(string input)

{

    byte[] encodedDataAsBytes

      = System.Convert.FromBase64String(input);

    string returnValue =

    System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);

    return returnValue;

}

 

//Usage

"test".FromBase64();

 

IsValidIPAddress

Checks if the given string is a valid IP Address

public static bool IsValidIPAddress(this string s)

{

    return Regex.IsMatch(s, 

            @"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b");

}

 

//Usage

"test".IsValidIPAddress();

 

ToHTMLEncoded

Encodes the input string as HTML (converts special characters to entities)

public static string ToHTMLEncoded(this string input)

{

    return HttpContext.Current.Server.HtmlEncode(input);

}

 

//Usage

"<span>test</span>".ToHTMLEncoded();

 

ToURLEncoded

Encodes the input string as a URL (converts special characters to % codes)

public static string ToURLEncoded(this string input)

{

    return HttpContext.Current.Server.UrlEncode(input);

}

 

//Usage

"http://elangovanr.com/?q=extension&page=2".ToURLEncoded();

 

HTMLDecoded

Decodes the HTML Encoded string

public static string HTMLDecoded(this string input)

{

    return HttpContext.Current.Server.HtmlDecode(input);

}

 

//Usage

"test".HTMLDecoded();

 

URLDecoded

Decodes the HTML Encoded string

public static string URLDecoded(this string input)

{

    return HttpContext.Current.Server.UrlDecode(input);

}

 

//Usage

"test".URLDecoded();

 

StripHTML

Removes any HTML tags from the input string

public static string StripHTML(this string input)

{

    return Regex.Replace(input, @"<(style|script)[^<>]*>.*?</\1>|</?[a-z][a-z0-9]*[^<>]*>|<!--.*?-->", "");

}

 

//Usage

"<span>test</span>".URLDecoded();

.Net Tips, Technical, c# ,

Catch multiple Exceptions together in C#

27. August 2010

    It is discouraged to simply catch System.Exception, instead only the "known" Exceptions should be caught. Now, this sometimes leads to unneccessary repetetive code, for example:

            try

            {

                DoSomething();

            }

            catch (FormatException ex)

            {

                LogException(ex);

                DisplayMessage(ex.Message);

            }

            catch (OverflowException ex)

            {

                LogException(ex);

                DisplayMessage(ex.Message);

            }

    if want to perform same operation on two different "known" Exceptions, C# does not allow you to catch exceptions like:

catch(FormatException | OverflowException ex)  // may be implemented in future versions of C#...

    But, you can refactor the above code to avoid the code repetitions. You can change the above code like:

            try

            {

                DoSomething();

            }

            catch (Exception ex)

            {

                if (ex is FormatException 

               || ex is OverflowException)

               {

                   LogException(ex);

                   DisplayMessage(ex.Message);

               }

               else

               {

                   throw;

               }

            }            

or, in other way,

            try

            {

                DoSomething();

            }

            catch (Exception ex)

            {

                Type exType = ex.GetType();

               if (exType == typeof(System.FormatException) 

               || exType == typeof(System.OverflowException))

               {

                   LogException(ex);

                   DisplayMessage(ex.Message);

               }

               else

               {

                    throw;

               }

            }            

    You can use the second option only if you want to handle the particular exception and not its derived Exceptions types. C# catch staement catches the Exception and Its derived types, so the best alternative for the original code can be the option 1.

.Net Tips, c# , ,

Using var (Implicitly Typed Local Variables) in your C# code.

26. August 2010

    Local variables can be given an implicit type of 'var' instead of explicit types. The compiler will resolve the type from the expression. Note that var can only be used when a local variable is declared and initialized in the same statement.

    I found some people discouraging the usage of 'var' in C# code and the reason that they are giving is that the var type makes the code more difficult to understand. It is not always true, using the var keyword should be discouraged in a places like the following code:

var data = GetData();

    When you read the above code, we will not know the type of the variable 'data'. This code is not understandable as it can be more it can be. If you change the above code like below, it makes the code more understandable.

DataTable data = GetData();

    'var' can be used in places like where below. <.p>

var data = new DataTable();

Here, the reader will not have any misunderstanding about the type of the variable ‘data’.

It makes sense to use var in teh following places.

  1. When creating anonymous types : var person = new { Name = "Name", Age = 25 };
  2. Object creation : var data = new DataTable();
  3. Cast expression: var data = (DataTable)obj; or var data = obj as DataTable;
  4. Generic method call or property with explicit type arguments, when return type is generic: var manager = serviceProvider.GetService<IManager>() or var manager = Singleton<Manager>.Instance;

.Net Tips, Technical, c# , ,

WPF TargetNullValue Binding Property

25. August 2010

    .net fromework SP1 introduced a property in BindingBase called TargetNullValue.

Usage : 

<TextBox Text="{Binding Total, TargetNullValue=0.00}" />

    The above code will set the Total property to null if the value is entered is 0.00 and if Total property is null it will display 0.00. The same functionality can be achieved by checking for null in the property getter and setters, but this is very handy and you don't have to do it in all the places where you want to achieve this behaviour.

For, more information about this property, check http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue.aspx .

 

.Net Tips, Technical, wpf , ,