jump to navigation

VS Solution Explorer – Collapse All May 15, 2009

Posted by codinglifestyle in CodeProject, Visual Studio.
Tags: , , , , ,
1 comment so far

I never knew I needed this until I saw it was a feature in a ReSharper demo.  After a quick search and I found a macro that has been around for years.  Slap to the head!  The amount of time I spend collapsing all my solution folders and this existed the whole time!

I never use macros, but even I was able to quickly get this working.

  1. Open Tools->Macros->Macro Explorer (Alt-F8)
  2. Right click MyMacros
  3. Select New Module
  4. Select default template and name to VSMacros
  5. Right-click VSMacros and click New Macro
  6. Copy and paste this over the opened macro file

    Imports System

    Imports EnvDTE

    Imports EnvDTE80

    Imports EnvDTE90

    Imports System.Diagnostics

    Public Module VSMacros

    Sub SolutionCollapseAll()

    ‘ Get the the Solution Explorer tree

    Dim solutionExplorer As UIHierarchy

    solutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object()

    ‘ Check if there is any open solution

    If (solutionExplorer.UIHierarchyItems.Count = 0) Then

    Return

    End If

    ‘ Get the top node (the name of the solution)

    Dim rootNode As UIHierarchyItem = solutionExplorer.UIHierarchyItems.Item(1)

    rootNode.DTE.SuppressUI = True

    ‘Find selected node

    Dim selectedNode As UIHierarchyItem = FindSelectedNode(rootNode, solutionExplorer)

    ‘ Collapse each node

    Collapse(selectedNode, solutionExplorer)

    ‘ Select the selceted node

    selectedNode.Select(vsUISelectionType.vsUISelectionTypeSelect)

    rootNode.DTE.SuppressUI = False

    End Sub

    Private Sub Collapse(ByVal item As UIHierarchyItem, ByRef solutionExplorer As UIHierarchy)

    For Each innerItem As UIHierarchyItem In item.UIHierarchyItems

    If innerItem.UIHierarchyItems.Count > 0 Then

    If innerItem.UIHierarchyItems.Expanded Then

    ‘ Re-cursive call

    Collapse(innerItem, solutionExplorer)

    End If

    ‘ Collapse

    If innerItem.UIHierarchyItems.Expanded Then

    innerItem.UIHierarchyItems.Expanded = False

    If innerItem.UIHierarchyItems.Expanded = True Then

    ‘ Bug in VS 2005

    innerItem.Select(vsUISelectionType.vsUISelectionTypeSelect)

    solutionExplorer.DoDefaultAction()

    End If

    End If

    End If

    Next

    End Sub

    Private Function FindSelectedNode(ByVal item As UIHierarchyItem, ByRef solutionExplorer As UIHierarchy) As UIHierarchyItem

    If item.IsSelected Then

    Return item

    End If

    For Each innerItem As UIHierarchyItem In item.UIHierarchyItems

    If innerItem.UIHierarchyItems.Count > 0 Then

    If innerItem.UIHierarchyItems.Expanded Then

    ‘ Re-cursive call

    Dim result As UIHierarchyItem

    result = FindSelectedNode(innerItem, solutionExplorer)

    If Not result Is Nothing Then

    Return result

    End If

    End If

    If innerItem.IsSelected Then

    Return innerItem

    End If

    End If

    Next

    Return Nothing

    End Function

    End Module

     

  7. You may now execute the macro via the Macro Explorer.  Click the folder you wish to collapse (or the Solution root to collapse everything).  Right click and run the macro.  To set a shortcut continue on with the steps below…
  8. Click Tools->Options->Environment->Keyboard
  9. Search for your macro in the Show commands containing textbox
  10. Select your macro, keep scope global, and in the assign macro keys textbox enter your preferred shortcut (I used “ALT-CTRL-\”)
  11. Click ASSIGN and then OK
  12. To use, select a node and then ALT-CTRL-\.  To collapse the entire solution, select the root of the solution.

Reference: http://www.codeproject.com/KB/macros/collapseall.aspx?df=100&forumid=7565&exp=0&select=396167

Advertisements

Code Snippets – List of C# snippets in VS2008 May 6, 2009

Posted by codinglifestyle in C#, CodeProject, Visual Studio, Visual Studio 2010.
Tags: , , ,
add a comment

In VS2010 we are told to expect a lot more code snippets.  To be honest, I don’t use them much but watching the demo I told myself it was time to give them another look.  Sometimes I get a great feeling of productivity in hammering out for loop templates and properties and tell myself who needs snippets?  But there is a lot of power there, and its going even further in VS2010.

My problems is I can never remember which code snippets are there.  I occassionaly see them in Intellisense, but there is so much there it’s hard to pick them out.  More than once I’ve carefully gone through the intellisense list trying to pound the useful ones in to my brain.

I decided to do a quick search for a list of code snippets in VS2008 for C#.  Surely I can’t be the first who just wants a simple list, right?  I came across Francesco’s blog who posted the code to iterate through your snippets and output them.  A quick change to update it for VS2008, C#, and to output a comma delimited line per snippet, then a paste in to Word, and Convert Text to Table (by comma) and voila!

List of Code Snippets in VS2008 for C#

#if Code snippet for #if
#region Code snippet for #region
attribute Code snippet for attribute using recommended pattern
checked Code snippet for checked block
class Code snippet for class
ctor Code snippet for constructor
~ Code snippet for destructor
cw Code snippet for Console.WriteLine
do Code snippet for do…while loop
else Code snippet for else statement
enum Code snippet for enum
equals Code snippet for implementing Equals() according to guidelines
exception Code snippet for exception
for Code snippet for ‘for’ loop
foreach Code snippet for foreach statement
forr Code snippet for reverse ‘for’ loop
if Code snippet for if statement
indexer Code snippet for indexer
interface Code snippet for interface
invoke Code snippet for safely invoking an event
iterator Code snippet for a simple iterator
iterindex Code snippet for ‘named’ iterator/indexer pair using a nested class
lock Code snippet for lock statement
mbox Code snippet for MessageBox.Show
namespace Code snippet for namespace
prop Code snippet for an automatically implemented property
propg Code snippet for an automatically implemented property with a ‘get’ access or and a private ‘set’ accessor
sim Code snippet for int Main()
struct Code snippet for struct
svm Code snippet for ‘void Main’ method
switch Code snippet for switch statement
try Code snippet for try catch
tryf Code snippet for try finally
unchecked Code snippet for unchecked block
unsafe Code snippet for unsafe statement
using Code snippet for using statement
while Code snippet for while loop

You can see snippet’s keyword typically matches the operator.  So next time you type for or while or try remember to hit TAB-TAB to expand the snippet.  Next time we’ll look at making your own code snippets.

Visual Studio 2008 JumpStart December 18, 2007

Posted by codinglifestyle in ASP.NET, C#, Javascript, jQuery, linq.
Tags: , , , , , , , , , , ,
add a comment

Yesterday I attended the Visual Studio 2008 Jumpstart at Microsoft in Dublin.  This was a one-day course, presented by David Ryan, introducing some of the new features in C# 3.0 and VS2008.

 

I approach every release with excitement and trepidation.  There are some fantastic new features like JavaScript debugging, nested MasterPages, improved IDE for both coding and web design, and multi-target runtime support.  With multi-targeting support we can use VS2008 to continue to code or support .NET 2.  If you open a VS2005 project, you will be prompted to upgrade your project even if you continue to use .NET 2.  I asked was there any risk associated with this for those who need to continue to support .NET 2 and was told only the SLN file is changed.  So theoretically, there is no reason to keep VS2005 installed!  Do you believe it??  If only we could get rid of VS2003 as well.

 

Now, the reason I also approach each release with trepidation is because you know there is going to be some big, new, ghastly feature which will be force-feed to us like geese in a pâté factory.  This time that feature in LINQ.  Open wide because there is a big push behind LINQ and you’ll notice a using System.Linq statement in every new class (which is a real pain if you change target framework back to .NET 2).  But first, let’s review some of the changes made to C#:

 

  • Anonymous types
    • var dt = DateTime.Today;
    • Anything can be assigned to a var, but once it’s assigned its strongly typed and that type can’t be changed.  So I can’t reuse local variable dt and assign string “Hello” like I could with object.
  • Automatic Properties
    • This:

      private int m_nID;

         public int ID

         {

             get

             {

                 return m_nID;

             }

             set

             {

                 m_nID = value;

             }

         }

 

  •  
    • becomes this:

public int ID { get; set; }

 

  •  
    • The problem is in practice I prefer to use the private variables in code leaving properties for external access only.  Many times the get/set is doing something interesting, like reading the value from a cache or performing some complex operation.  We don’t necessarily want/need this code to execute every time it is accessed from within the class so I use the private variable.  Automatic Properties has us using the public property directly everywhere in the class.  So, personally, this will cause inconsistency in my coding style.
    • You can also specify the get as public but keep the set to just be accessible from within the class like this:

public int ID { get; private set; }

 

  • Object initalizers
    • Ever have to instantiate your own class and have to initialize it with a dozen properties?  Do you add 13 lines of code or go overload the constructor?  Now you don’t have to, imagine a simple Person class with 3 properties:

Person person = new Person { FirstName=“Chris”, LastName=“Green”, Age=33 };

 

  •  
    • Only initialize what you properties you want:

Person person2 = new Person { FirstName = “Chris”, LastName = “Green” };

 

  • Collection initalizers

List<Person> people = new List<Person>

         {

new Person { FirstName = “Chris”, LastName = “Green”, Age = 33 },

new Person { FirstName = “Bill”, LastName = “Bob”, Age = 46 },

new Person { FirstName = “Foo”, LastName = “Bar”, Age = 26 }

         };

 

  • Extension methods
    • This is a way of adding new inherent functionality to existing classes.  The objective is to add a new method to the DateTime type called LastDay() which will return the last day of the given date’s month.

public static class DateTimeUtils

{

        public static int LastDay (this DateTime dt)

        {

            return DateTime.DaysInMonth(dt.Year, dt.Month);

        }

}

 

  •  
    • Notice the this before the first parameter argument.  This tells the compiler that this is an extension method for the DateTime type.  We can now use this method as if it was built in to the DateTime class:
      • int nLastDay = dt.LastDay();
  • Lambda expressions
    • Too lazy or couldn’t be arsed to write a small 2 line function?  This is for you:

Func<string, bool> CheckName = sName => sName == “Bob”;

bool bBob = CheckName(person.FirstName);

Func<int, int> Square = x => x * x;

int nSquare = Square(5);

 

The fact is there’s an ulterior reason var, Lamda expressions, and many of above additions have been added to C# 3.0.  C# had been bent in order to accommodate LINQ.  LINQ allows you to perform queries on objects, DataSets, XML, and databases.  It’s interesting in that it offers an independent layer of abstraction for performing these types of operations.  This has actually occurred to me before when looking at data layers chock full of embedded SQL not being particularly ideal.  LINQ offers a generic and powerful alternative.  Let’s take a look at a simple example based on the people collection from above:

 

var matches = from person in people

              where person.FirstName == “Bob”

              select person;

 

The first thing that caught my attention was the select was last.  One reason they likely did this was to force us to state what we were querying first (the from clause) so that Intellisense could kick-in for the rest of the expression.  Notice person.FirstName was fully supported by Intellisense so the Person class was automatically inferred from the people collection.

 

You can create objects on-the-go from your expression.  For example:

 

var matches = from employee in people

              where employee.FirstName == “Bob”

              select new Person(employee.FirstName, employee.LastName);

 

 

Notice how var is inherently handy here (but bad practice for nearly everything else) as our LINQ expression returns System.Collections.Generic.IEnumerable.  Lambda expressions as well play a key part in LINQ:

 

var matchesBob = people.Select(CheckName => CheckName.LastName == “Bob”);

 

matchesBob.ToArray()

{bool[3]}

    [0]: false

    [1]: true

    [2]: false

 

var matchesInitials = people.Select(ChopName => ChopName.FirstName.Remove(1) + ChopName.LastName.Remove(1));

 

matchesInitials.ToArray()

{string[3]}

    [0]: “CG”

    [1]: “BB”

    [2]: “FB”

 

There is so much more to LINQ that I won’t attempt to cover any more.  Rest assured you will hear much more about LINQ in the months to come (fatten up those livers).  One thing is obvious, C# took a heavy hit in order to support it.  Let’s hope it’s worth it as every release we lean more and more towards VB.  A colleague recently remarked, “C# is all VB under the covers anyhow”.  He might be right.

 

Some other interesting new additions:

  • XElement – for anyone who has programmatically built XML before you will appreciate this quicker alternative
  • ASP.NET ListView – the singular new control this release.  Its basically a Repeater but with design-time support
  • Script Manager Proxy – typically the Ajax ScriptManager will be placed in the MasterPage.  When the content page needs to access the ScriptManager a ScriptManagerProxy can be used to get around the restriction of only one ScriptManager allowed per page.
  • Javascript enhancements – built-in libraries which extend string, add StringBuilder, and a number of other enhancements to make writing JavaScript more .NET-like
  • CLR Add-In Framework: essentially a pattern for loading modules (only from a specified directory) vs. using reflection, iterating classes for a specified type, and using the activator to instantiate the object
  • Transparent Intellisense: In VS2005 Intellisense went in to hyperdrive and our tab keys have never been the same.  However, I often found myself cursing it as it often got in the way.  So when VS is being too helpful and you can’t see what you’re doing press CTRL rather than ESC to turn Intellisense transparent.
  • Right-click the code and you will see an Organize Using menu below Refactor.  Here is a feature I’ve often dreamed of: Remove Unused Usings.  Pinch me!  Also, if you right-click the interface in a class’s definition (public class MyClass : Interface) there is an Implement interface option.   Last, if you are coding away and using a class before adding a using statement use ALT-Shift-F10 to automatically resolve the class and add the using statement to your file.
  • Improved support for debugging multithreaded applications
  • SQL Database Publishing Wizard is now integrated in the VS
  • Did I mention JavaScript debugging??!

 

You may notice I’ve omitted a few big topics.  I didn’t mention Ajax because that’s old news now.  However, there are new versions of the Ajax Control Toolkit and web deployment projects for VS2008.

 

I also didn’t mention Silverlight although I may find some interesting applications for it in the future.  For example, if you really hate writing JavaScript you could use Silverlight’s built-in mini CLR to write C# code which executes in the browser.  Oh, I hear it does some UI stuff too.

 

References: ScottGu 19-11-2007, ScottGu 13-03-2007, ScottGu 08-03-2007, C# 3.0 In a Nutshell, Pro ASP.NET 3.5 in C# 2008, and CodeProject.