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

WPF - Link Button Style

29. September 2010

    In Some cases, you might want to make a button to look like hyper link. (There is a Hyperlink control, which we can use to open some URL). Here is the simple re-usable style for button to make it look like a Hyper link button (LinkButton).

 

<Style x:Key="LinkButtonStyle" TargetType="{x:Type Button}">        
       
<Setter Property="Template">
           
<Setter.Value>
               
<ControlTemplate TargetType="{x:Type Button}">
                   
<TextBlock TextDecorations="Underline">
                       
<ContentPresenter />
                   
</TextBlock>
               
</ControlTemplate>
           
</Setter.Value>
       
</Setter>
       
<Setter Property="HorizontalContentAlignment" Value="Center"/>
       
<Setter Property="VerticalContentAlignment" Value="Center"/>
       
<Setter Property="Foreground" Value="Blue" />
       
<Setter Property="Cursor" Value="Hand" />
       
<Style.Triggers>
           
<Trigger Property="IsMouseOver" Value="true">
               
<Setter Property="Foreground" Value="Red" />
           
</Trigger>
       
</Style.Triggers>
</Style>

 

 

 

Technical , ,

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# ,

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 , ,

Get active Window on WPF

24. August 2010

 

We can scan the list of open windows in the application and check which one of them has IsActive = true:

Application.Current.Windows.Cast<Window>().SingleOrDefault(x => x.IsActive);

If you want to get teh active window in many places , you might want to create extension method for getting active window.

public static Window GetActiveWindow( this Application currentApp)

        {

            return Application.Current.Windows.Cast<Window>().SingleOrDefault(x => x.IsActive);

        }

and you can get the active window using the following code

Application.Current.GetActiveWindow();

 

Update:

Note that the Cast<> method is a Linq method, you need to reference System.Linq namespace.

Technical, wpf ,

C# - Conditional Attribute

20. August 2010

 

  If you are working on C#, you probably know about methods like Debug.WriteLine. The important part of their usage is that they only do stuff if you are running an application compiled in Debug mode. If you are running in release mode, it works like those calls in your code don't even exist. When you compile your code  with Debug.WriteLine() method call in debug mode and look at the MSIL, you can see the method call to Debug.WriteLine() and when you compile the same code in the Release mode and look at the MSIL, you cannot find the method call in the MSIL.Have you ever wondered how these methods are implemented? Have you ever wanted to create a method like this? 

    This can be achieved using pre-processor directives in C#, but wait, when you use pre-processor directives, you have to use the pre-processor directives before the method declaration and of course, before the method usage otherwise the compiler will give error. But here, we are not using any pre-processor directives before the method call. How the magic is done? This is simple, if you look at the syntax of the method Debug.WriteLine(), you can find one attribute [Conditional("DEBUG")] before the method.

What is Conditional Attribute?

 

    Conditional Attribute tag on the method signature means that the method call only exists if the specified pre-processor directive is defined. In this case, the method call only exists if the symbol DEBUG is defined.

For example, take a look at the following code:

 class Program
    {
        static void Main(string[] args)
        {
            DebugInfo();
        } 

        [Conditional("DEBUG")]
        public static void DebugInfo()
        {
            Console.WriteLine("This is debug information");
        }
    }

When this code is compiled in debug mode, if you take a look at the MSIL for the Main() method inside the assembly, you will see the following: 

.method private hidebysig static void Main(string[] args) cil managed

{

    .entrypoint

    .maxstack 8

    L_0000: nop 

    L_0001: call void ConditionalAttributeTest.Program::DebugInfo()

    L_0006: nop 

    L_0007: ret 

}

And if you compile the same code in in Release mode and look at the MSIL for the Main() method, you can see the following:

.method private hidebysig static void Main(string[] args) cil managed

{

    .entrypoint

    .maxstack 8

    L_0000: ret 

}

    Here, we cannot see the call to the method DebugInfo(). But we can see the Method DebugInfo present in the MSIL. The Conditional attribute instructs the compiler to remove the method call to this method.

 

Where is this usefull?

 

    For example, you wanted to gather some performance data when the symbol TIMERS is defined. You can have some code like the following:

public static class StopWatches

    {

        private static Dictionary<string, Stopwatch> _stopwatches

      = new Dictionary<string, Stopwatch>();

 

        [Conditional("CHECKPERFORMANCE")]

        public static void StartStopwatch(string key)

        {

            if (_stopwatches.ContainsKey(key))

            { return; }

            _stopwatches.Add(key, Stopwatch.StartNew());

        }

 

        [Conditional("CHECKPERFORMANCE")]

        public static void StopStopwatch(string key)

        {

            if (!_stopwatches.ContainsKey(key))

            { return; }

            var watch = _stopwatches[key];

            watch.Stop();

            _stopwatches.Remove(key);

            Console.WriteLine(String.Format("Timer: {0}, {1}ms", key,

                watch.Elapsed.TotalMilliseconds));

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            StopWatches.StartStopwatch("forloop");

            int total = 0;

            for (int i = 0; i < 10000; i++)

            { total += i; }

            Console.WriteLine(total);

            StopWatches.StopStopwatch("forloop");

 

            Console.Read();

        }

    }

When you run the above code with #define CHECKPERFORMANCE, you will get the following output.

 

49995000

Timer: forloop, 0.9802ms

 

When you run the above code without defining the pre-processor directive CHECKPERFORMANCE, you will see the following output.

49995000


 

.Net Tips, Technical, c# , ,

Patch for the VS 2010 Find and Replace Dialog size increase

18. August 2010

    If you are using Visual studio 2010, you might have noticed the following issue. Each time you open Find and replace dialog, the width of the window increases little bit (16px) and the width keeps on increasing even after it reaches the screen width also.

 

 

   On repeated use, this can quickly take up your entire screen real estate.

Microsoft is now having a patch available for this issue, which you can download it from here.

 

 

.Net Tips, English, Technical , ,