Blog - Title

Visual Studio 2012 & 2013 Current Builds

  • The Ultimate Visual Studio Tips and Tricks Blog

    Calling a PowerShell Script From Your .NET Code

    • 15 Comments

     

    Well, Mike F. reminded me to write this article on 5/29 and I am FINALLY getting around to doing it.  Also wanted to give a shout out to Max T. who provided some inspiration on this one as well.  For the code, I borrow very heavily from the article written by Jean-Paul Mikkers found at: 

    http://www.codeproject.com/KB/cs/HowToRunPowerShell.aspx

     

    NOTE:  There is an async version of his code that he does as a follow up.  I don't use it because I want to remove extra code noise to focus on the act of calling the script itself.  If you want to take a stab at the async version (and there are LOTS of good reasons to do so) then you can go here:

    http://www.codeproject.com/KB/threads/AsyncPowerShell.aspx 

     

    So, on to the goodness!

     

    First, you need to make sure you have Visual Studio (any version) installed and have PowerShell installed.  You can get PowerShell from here:

    http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx

     

    You will also need to do this (WARNING:  MAJOR SECURITY ISSUE HERE AND THIS IS JUST FOR TESTING SO DON'T DO THIS ON PRODUCTION MACHINES):

    http://www.cubiczone.com/Articles/tabid/65/EntryID/17/Default.aspx

     

     

     

    1.   Now, let's crank out a simple PoweShell script that we are interested in calling.  We will call a simple script that takes a couple of numbers and returns the sum of those numbers.  This may seem overly simplistic but it is an easy way to demonstrate a complete round-trip between our app and the script without getting bogged down in extra BS that comes with a fancier script.  I'll call the script AddItUp.ps1 and it is included in the source code download, just put it anywhere you can get to easily.  Feel free to dig into the guts of it later on but for now just assume it does what we need it to do. 

     

    Here is the code for the script if you just want to make your own real quick:

     

    # begin

    function AddStuff($x,$y)
    {
       $x + $y
    }

     

    AddStuff 6 5

    # end

     

    NOTE:  Some inspiration and just a cool site for scripts came from http://www.powershellpro.com just as an fyi

     

     

     

    2.  Test the script by opening PowerShell and navigating to the directory where it is and typing what you see in the graphic, you should get the expected result.

    image

     

     

     

     

    3.  Okay!  We have a script that works but now what?  Well we have to call that puppy from our code so let's create a project and get ready to make our magic happen.  Crank out a new Windows App for us to use.  Call the Project CallMeCS or CallMeVB depending on your language.

     

     

    image

     

     

     

     

    4.  For the interface, just gimme a button and a label.  Resize the form a bit so we don't have wasted space.  Real simple stuff...

     

    image

     

     

     

    5.  Double-click on the button to go into our code.

     

    C#:

    image

     

    VB:

    image

     

     

     

    6.  Now we need to add an assembly that is one of a set we got with our install of PowerShell.  You can find these assemblies at C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0

     

    image

     

    7.  Right-click on your project and choose Add Reference...

     

    image

     

     

    8.  Select the Browse Tab and locate these assemblies then add a reference to the System.Management.Automation.dll

    NOTE:  If you want to dig deeper into the contents of this namespace, you can check it out here:  http://msdn.microsoft.com/en-us/library/system.management.automation(VS.85).aspx

     

    image

     

     

    9.  Now that we have our reference we need to add some using/imports statements to make getting to the classes we want to use easier.  Make sure to put these at the top of your code page outside any other code. 

     

    C#:

    using System.Collections.ObjectModel;
    using System.Management.Automation;
    using System.Management.Automation.Runspaces;
    using System.IO;

     

    VB:

    Imports System.Collections.ObjectModel
    Imports System.Management.Automation
    Imports System.Management.Automation.Runspaces
    Imports System.Text
    Imports System.IO

     

     

    10.  Okay, this next part is a little funkier.  While I liked the code that Mikkers had, I wanted to be able to load up a file from my file system and use it instead of just putting code into a textbox.  That created some VERY interesting new challenges but the end result worked out well.  So, to that end, we will create two helper methods:  RunScript and LoadScript.  RunScript is the code essentially unchanged from Mikkers' article and LoadScript is my helper function that will load the contents of a script file and return a string.

     

     

    11.  Let's begin with the RunScript method.  We will add this method to the Form1 class to make our life easier. 

     

    C#:

    private string RunScript(string scriptText)
       {
           // create Powershell runspace
           Runspace runspace = RunspaceFactory.CreateRunspace();

           // open it
           runspace.Open();

           // create a pipeline and feed it the script text
           Pipeline pipeline = runspace.CreatePipeline();
           pipeline.Commands.AddScript(scriptText);

           // add an extra command to transform the script output objects into nicely formatted strings
           // remove this line to get the actual objects that the script returns. For example, the script
           // "Get-Process" returns a collection of System.Diagnostics.Process instances.
           pipeline.Commands.Add("Out-String");

           // execute the script
           Collection<PSObject> results = pipeline.Invoke();

           // close the runspace
           runspace.Close();

           // convert the script result into a single string
           StringBuilder stringBuilder = new StringBuilder();
           foreach (PSObject obj in results)
           {
               stringBuilder.AppendLine(obj.ToString());
           }

           // return the results of the script that has
           // now been converted to text
           return stringBuilder.ToString();
       }

     

    VB:

    ' Takes script text as input and runs it, then converts
        ' the results to a string to return to the user
        Private Function RunScript(ByVal scriptText As String) As String

            ' create Powershell runspace
            Dim MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()

            ' open it
            MyRunSpace.Open()

            ' create a pipeline and feed it the script text
            Dim MyPipeline As Pipeline = MyRunSpace.CreatePipeline()

            MyPipeline.Commands.AddScript(scriptText)

            ' add an extra command to transform the script output objects into nicely formatted strings
            ' remove this line to get the actual objects that the script returns. For example, the script
            ' "Get-Process" returns a collection of System.Diagnostics.Process instances.
            MyPipeline.Commands.Add("Out-String")

            ' execute the script
            Dim results As Collection(Of PSObject) = MyPipeline.Invoke()

            ' close the runspace
            MyRunSpace.Close()

            ' convert the script result into a single string
            Dim MyStringBuilder As New StringBuilder()

            For Each obj As PSObject In results
                MyStringBuilder.AppendLine(obj.ToString())
            Next

            ' return the results of the script that has
            ' now been converted to text
            Return MyStringBuilder.ToString()

        End Function

     

     

    12.  Now we want to add in our LoadScript method to make getting the script into a variable easier.

     

    C#:

    // helper method that takes your script path, loads up the script
            // into a variable, and passes the variable to the RunScript method
            // that will then execute the contents
            private string LoadScript(string filename)
            {
                try
                {
                    // Create an instance of StreamReader to read from our file.
                    // The using statement also closes the StreamReader.
                    using (StreamReader sr = new StreamReader(filename))
                    {

                        // use a string builder to get all our lines from the file
                        StringBuilder fileContents = new StringBuilder();

                        // string to hold the current line
                        string curLine;

                        // loop through our file and read each line into our
                        // stringbuilder as we go along
                        while ((curLine = sr.ReadLine()) != null)
                        {
                            // read each line and MAKE SURE YOU ADD BACK THE
                            // LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
                            fileContents.Append(curLine + "\n");
                        }

                        // call RunScript and pass in our file contents
                        // converted to a string
                        return fileContents.ToString();
                    }
                }
                catch (Exception e)
                {
                    // Let the user know what went wrong.
                    string errorText = "The file could not be read:";
                    errorText += e.Message + "\n";
                    return errorText;
                }

            }

     

    VB:

    ' helper method that takes your script path, loads up the script
        ' into a variable, and passes the variable to the RunScript method
        ' that will then execute the contents
        Private Function LoadScript(ByVal filename As String) As String

            Try

                ' Create an instance of StreamReader to read from our file.
                ' The using statement also closes the StreamReader.
                Dim sr As New StreamReader(filename)

                ' use a string builder to get all our lines from the file
                Dim fileContents As New StringBuilder()

                ' string to hold the current line
                Dim curLine As String = ""

                ' loop through our file and read each line into our
                ' stringbuilder as we go along
                Do
                    ' read each line and MAKE SURE YOU ADD BACK THE
                    ' LINEFEED THAT IT THE ReadLine() METHOD STRIPS OFF
                    curLine = sr.ReadLine()
                    fileContents.Append(curLine + vbCrLf)
                Loop Until curLine Is Nothing

                ' close our reader now that we are done
                sr.Close()

                ' call RunScript and pass in our file contents
                ' converted to a string
                Return fileContents.ToString()

            Catch e As Exception
                ' Let the user know what went wrong.
                Dim errorText As String = "The file could not be read:"
                errorText += e.Message + "\n"
                Return errorText
            End Try

        End Function

     

    13.  Finally, we just need to add some code for our button's click event.

     

    C#:

    private void button1_Click(object sender, EventArgs e)
            {
                // run our script and put the result into our textbox
                // NOTE: make sure to change the path to the correct location of your script
                textBox1.Text = RunScript(LoadScript(@"c:\users\zainnab\AddItUp.ps1"));
            }

     

    VB:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            'run our script and put the result into our textbox
            'NOTE: make sure to change the path to the correct location of your script
            TextBox1.Text = RunScript(LoadScript("c:\users\zainnab\AddItUp.ps1"))
    End Sub

     

    14.  That's it!!  You should be able to run your code and you should get this:

    image

     

     

    Don't sweat it if you think this is a lot to type.  I have included the source code for you to use.  Enjoy!

  • The Ultimate Visual Studio Tips and Tricks Blog

    Visual Studio 2012 New Features: Preview Tab

    • 15 Comments

     

    Preview Tab Overview

    We all explore code and need to move quickly between files when examining code to get familiar with it or debugging or [insert file browsing scenario here]. In prior versions of Visual Studio you had to open a file to look at the contents which often resulted in many open files (tabs) when you were done. The Preview Tab eliminates the need to open files when browsing code. Most likely you’ll first encounter the Preview Tab when you are looking at files with Solution Explorer. When you click on a supported file type, you will see the contents of that file in the new preview tab (to the far right in the tab well):

    image

     

    If you click anywhere inside the file the tab will go from grey to purple to distinguish it from regular (blue) tabs:

    image

     

    Again, the point of the preview tab is to let you view the contents of a file without actually opening up a new tab in the tab well. As you look at different files the preview tab only shows the contents of the file you are currently on. This keeps the environment from getting cluttered with open tabs and allows you to focus on only those files that are interesting to you. Solution Explorer isn’t the only place you can use the preview feature. It turns up in several situations where you might need to look at file content. For example, when using Find in Files (CTRL + SHIFT + F) to locate information you will see the preview tab:

    image

     

     

    Promoting Previews

    At some point you may decide to promote the preview to an opened tab in the Tab Well so you can do additional work on the file or just keep it around for other purposes. There are a few ways you can make this happen.

     

    Click the Keep Open button

    Probably the least useful and and least likely technique you will use is to click on the tiny Keep Open button on the Preview Tab.  It’s not only useless it’s actually kind of annoying for some reason I can’t identify:

    image

     

    Double Click the File

    The most likely approach is you will just double click the file in Solution Explorer or whatever results dialog you happen to be in.

     

    Press CTRL + ALT + HOME

    With the cursor inside the file (the tab is purple), just press CTRL + ALT + HOME to open a tab for the file you are currently viewing.

     

    Change the File

    While previewing a file, if you make any change to the file it will automatically be promoted to an open tab so that you can make additional changes and do any other actions you need to perform.

     

    Click the Preview Selected Items button

    Another button is useless and a waste of space on the Solution Explorer toolbar is the Preview Selected Items button.  You can click it to preview the current file and its only use that I can find is if you turn off single clicking a file to preview it (see below).  Also the tooltip would lead you to believe that you can select multiple files and preview them.  Nope.  Doesn’t work.  Don’t waste your time with this button.

    image

     

     

    Turning Preview Off

    To see the options you have for using the preview feature, just type preview in Quick Launch (CTRL + Q) and click Environment -> Tabs and Windows:

    image

     

    This will take you to Tools | Options | Environment | Tabs and Windows:

    image

     

     

    To turn off the preview feature (NOT suggested unless you are having performance issues with it) uncheck the Allow New Files to be Opened in the Preview Tab option. Also notice you can decide if a single click open the files in for preview in Solution Explorer and Find dialogs. For Solution Explorer you can use ALT to prevent a file from being previewed when you click on it. While I see the value in using ALT to prevent preview from happening. I haven’t yet found any reason for turning off the single-click option as it, in effect, forces you to use the Preview Selected Items button which is a lot of extra work and kind of defeats the purpose of the feature.

     

     

    Finally

    The Preview Tab is one of my top two favorite features in Visual Studio 2012 (the other one being project round-tripping).  You definitely want to leverage this feature to make your life easier.

  • The Ultimate Visual Studio Tips and Tricks Blog

    Gimme Some Link Luv

    • 14 Comments

    Shoot me the URL to your blog and point out where you have linked to me.  I will pick one lucky victim...er...winner to reward with a Visual Studio 2008 Backpack or 3 Visual Studio T-Shirts.

    Contest ends a week from Saturday.
  • The Ultimate Visual Studio Tips and Tricks Blog

    Using Solution Folders

    • 14 Comments

    Menu:  Project -> Add New Solution Folder; [Right-Click Solution] -> Add -> New Solution Folder
    Command:  Project.AddNewSolutionFolder
    Versions:  2008,2010
    Published:  3/27/2010
    Code:  vstipProj0009

     

    Did you know there are special folders to help you organize large solutions?  There is!  They are called, appropriately enough, Solution Folders.  To create one just Right-Click on your solution (or go to Project -> Add New Solution Folder) and you will see this in Solution Explorer:

    image

     

    Simply give the folder a name and you are good to go.  But so what?  I mean, what can you actually DO with these things?  Here is a list of stuff you can do:

    • Move or add projects to them. Solution Folders can be nested to create greater organizational structure.

    • Add, delete, or rename Solution Folders at any time, if the organizational requirements of the solution change.

    • Unload all projects in a Solution Folder to make them temporarily unavailable for building.

    • Collapse or hide entire Solution Folders so that you can work more easily in Solution Explorer. Hidden projects are built when you build the solution. 

    • Build or rebuild all the projects. The projects are built in the order specified by the project dependencies.

    SPECIAL NOTE: 

    Solution Folders are an organizational tool in Solution Explorer; corresponding Windows folders are not created.  Microsoft recommends that you organize your projects on disk in the same way that you organize them in the solution.  But that is your call :)

  • The Ultimate Visual Studio Tips and Tricks Blog

    Announcing the Tips and Tricks SWAG Fest Beginning April 12th

    • 13 Comments

    ThinkGeek

     

    So, someone thought it would be a good idea to give me some money for SWAG to give to my readers.  Naturally, I loved the idea!  So I went and bought a whole bunch of $100 ThinkGeek gift certificates.  The problem is how to give them away?  After much thought (about 10 minutes, at least), I figured the best way was to give them away whenever I felt like it. 

     

    Okay so there you have it.  Beginning April 12th (Visual Studio 2010 Launch Day) I will be giving away ThinkGeek gift certificates.  I’ll be picking people who show love for the Visual Studio Tips and Tricks blog.  There are some basic ways you can do this:

     

    1. Leave some cool comments on the tip(s) you like the most
    2. Tweet about the Tips blog using the #vstips hashtag
    3. Show some blog love by cross posting to your blog if you have one

    Feel free to get creative and let me know about it.  That’s pretty much it.  Very simple really.  Look for the fun to begin on Launch Day.

  • The Ultimate Visual Studio Tips and Tricks Blog

    Select the Current Word

    • 13 Comments

    Keyboard:  CTRL + W
    Command:  Edit.SelectCurrentWord
    Versions:  2008,2010
    Published:  4/5/2010
    Code:  vstipEdit0039

     

    Download the seriously cool Tip of the Day Extension to get the daily tips delivered to your Start Page!

     

    You can easily select the current word in Visual Studio by simply putting your cursor in the word to select:

    image

     

    Then press CTRL + W and it will automatically select the current word:

    image

  • The Ultimate Visual Studio Tips and Tricks Blog

    Split Your Windows

    • 13 Comments

    Menu:  Window -> Split
    Command:  Windows.Split
    Versions:  2008,2010
    Published:  3/5/2010
    Code:  vstipEnv0004

     

    Did you know you can split your windows?  This feature has been available in a lot of Microsoft products for some time.  You can simply go to Window -> Split on the Menu Bar or you can use this mouse technique:

     

    1. Go the upper right-hand corner of a document window and look for the splitter control:
      image
    2. Click and hold on it and drag it down to begin the split process:
      image
    3. You can now see different places in your code to, for example, call a method while looking at the definition:
      image 
  • The Ultimate Visual Studio Tips and Tricks Blog

    Customize how Find in Files results are displayed in the Find Results Window

    • 13 Comments

    Keyboard:  CTRL + SHIFT + F
    Menu:  Edit -> Find and Replace -> Find in Files
    Command:  Edit.FindinFiles
    Versions:  2008,2010
    Published: 1/3/2010
    Code:  vstipFind0002 

       

    image

     

    You can customize your Find in Files results to show what you want to see and how you want to see it.

    Example:  You don't want to view the entire file path shown in the Find Results tool window.

    So instead of this:

    image

     

     

    You want this:

    image

     

    No problem! :)

     

    DANGER:  This involves hacking the Registry so use this tip at your own risk!

    1. Open up RegEdit
    2. Go to HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Find
    3. Add a new string called Find result format with a value of $f$e($l,$c):$t\r\n

      image
    4. Hop into Visual Studio and run a Find in Files search (NOTE: You do not need to restart VS to see the changes made in the Registry, which is great for testing different string combos)

     

    Here are valid values you can use in the string:

     

    Files

    $p      path                       

    $f      filename               

    $v      drive/unc share            

    $d      dir                        

    $n      name                       

    $e      .ext                   

        

    Location

    $l      line                        

    $c      col                        

    $x      end col if on first line, else end of first line

    $L      span end line

    $C      span end col

    Text

    $0      matched text                

    $t      text of first line

    $s      summary of hit

    $T      text of spanned lines

    Char

    \n      newline                   

    \s      space                     

    \t      tab                        

    \\      slash                    

    \$      $                 

  • The Ultimate Visual Studio Tips and Tricks Blog

    Using the Call Hierarchy (C# Only)

    • 13 Comments

    Keyboard:  CTRL + ALT + K (anywhere); CTRL + K,T (cursor must be on a member name)
    Menu:  View -> Call Hierarchy
    Command:  View.CallHierarchy; EditorContextMenus.CodeWindow.ViewCallHierarchy
    Versions:  2010
    Published:  1/19/2010
    Code:  vstipTool0005

    For the C# folks this is one heck of a great feature:  The Call Hierarchy.  It allows you to visualize all calls to and from a selected method, property, or constructor.  To see how it works just right-click on any method, property, or constructor in the Editor and select View Call Hierarchy:

    image

    You should get a window similar to this one (amount of information will vary):

    image

    Notice there are "Calls To" and "Calls From" areas related to your selection.  You can expand them out:

    image

     

    When you click on a node in the tree, the Call Sites window updates so you can visit the call if you want to:

    image

     

    You can continue expanding the hierarchy to see more "Calls To" and "Calls From" information:

    image

     

    The best part is you can right-click on a symbol and get all kinds of options:

    image

     

     

     

     

     

    Here are some options you may come across:

    Context Menu Item

    Description

    Add As New Root

    Adds the selected node to the tree view pane as a new root node.

    Remove Root

    Removes the selected root node from the tree view pane. This option is available only from a root node.

    You can also use the Remove Root toolbar button to remove the selected root node.

    Go To Definition

    Runs the Go To Definition command on the selected node. This navigates to the original definition for a method call or variable definition.

    You can also press F12 to run the Go To Definition command on the selected node.

    Find All References

    Runs the Find All References command on the selected node. This finds all the lines of code in your project that reference a class or member.

    You can also use SHIFT+F12 to run the Find All References command on the selected node.

    Copy

    Copies the contents of the selected node (but not its subnodes).

    Refresh

    Collapses the selected node so that re-expanding it displays current information.

  • The Ultimate Visual Studio Tips and Tricks Blog

    Using the WPF Tree Visualizer

    • 13 Comments

    Versions:  2010
    Published:  1/29/2010
    Code:  vstipDebug0004

     

    For those not familiar with WPF Trees, check out this article:  http://msdn.microsoft.com/en-us/library/ms753391(VS.100).aspx

     

    Now.  For those that ARE familiar with them have we got something for you:  WPF Tree Visualizer.  Yes, it started out as a CodePlex project and ended up in the product itself as a visualizer.  But how do you use it? 

     

    1. Enter debug mode using any method you prefer.
    2. Once you are there take a look at either a DataTip, the Watch window, the Autos window, or the Locals window.  For this example, I will use the Autos window.
    3. Choose any control in the Autos window and then click on the magnifying glass way over to the right of the control name.
      image
    4. You will see a drop down list.  Choose the WPF Tree Visualizer to get this dialog:
       image
    5. This thing has a lot of different parts so let's take a look at each one.  First, the Visual Tree shows you the hierarchy of the controls:
      image
    6. Clicking on any particular node of the tree will show you the Rendering view just below:
      image
    7. Also, the selected control will have its properties displayed in the large area to the right:
      image

    8. In, both, the Visual Tree and the Properties area you can search/filter the results by typing into the "Search" or "Filter" textboxes respectively:
      image

    9. WARNING:  Watch out for the results as they may not be what you expect.  See the extra items in the list that don't have the word "context" in them?  How did they get there?  Well, if I scroll to the right and look at other properties you can see how it happened:
      image 

      Currently, there is no way that I am aware of to change this behavior.
Page 3 of 135 (1,345 items) 12345»