Sunday, October 26, 2008

This post shows how to create an Automatic Property, by turning an existing private field into a property.

 

You've got a private field that you would like to expose to users of your class, but you only want them to be able to get, not set the value.

You could expose the field itself to callers, but it's better to expose a property so that you can set different permissions for get and set, add behaviour when the value is set, and make it easy to version your class so that callers won't notice when you change your internal features.

For this walk-through, I'll assume you've already got a private field on your class that you want to expose publicly.

Encapsulating Fields

So starting with your private field, that has no public access:

class TestClass

{

    private int _Property1;

}

You can use the refactoring support in Visual Studio's right-click menu to wrap the field with a property:

Right-click field, and choose encapsulate field 

Go ahead and select the "All" option to update all usages of the _Property1 to use the new property we are creating:

EncapsulateField2 

Now all code will reference the Property1 property, rather than the private field:

class TestClass

{

    private int _Property1;

 

    public int Property1

    {

        get { return _Property1; }

        set { _Property1 = value; }

    }

}

Our final requirement was that Getting the value should be public, but the setter should be private, so external callers can't update our fields value.

You can do this by overriding the access of the setter, to make it more restricted:

class TestClass

{

    private int _Property1;

 

    public int Property1

    {

        get { return _Property1; }

        private set { _Property1 = value; }

    }

}

Note the addition of the private keyword to the property setter, while the public keyword now will just apply to the getter.

Automatic Properties

C# 3.0 added a handy new feature called Automatic Properties.

If all your accesses to a field (e.g. _Property1) are going through a property (Property1), then it seems like a waste to have to create a private field by hand.

Automatic Properties in C# will let the compiler do the work of creating the private field for you. All you have to do is create the property.

Change the code to:

class TestClass

{

    public int Property1

    {

        get;

        private set;

    }

}

If you have no body for the getter and setter, the C# compiler will automatically create a field to store the value in. The accessibility of the setter can be set to private as above, so you have all the benefits of a private field, without having to create it yourself.

Now external callers can only reference the property Property1, while internal callers within your class can access both the getter and setter.

By following the above sequence of encapsulating, you won't have to manually change any of the callers of your original field to use the property:

  1. Encapsulate field
  2. Update all references to point to the new field
  3. Remove the original field, and the contents of the getter and setter
  4. Update access of the getter and setter as desired (e.g. make set private)

Snippets

If you're starting from scratch, and you don't already have a field to encapsulate, there are a couple of handy snippets you can use:

prop [tab] [tab] - this will create a regular automatic property, and let you set the type and name:

public int MyProperty { get; set; }

propg [tab] [tab] - this will do the same, but with a private setter:

public int MyProperty { get; private set; }

 

I hope this post gives you some quick tips when dealing with properties.

Kirk

 

Extras

It's always tempting to go off on a tangent talking about technicalities. If you're interested in such stuff, read on...

Field names for automatic properties

The compiler will choose a "magic" name for your field that is storing the data exposed by the automatic property. You can't refer to it directly from your code, and the compiler will make sure it's unique.

For example, my "Property1" has the following fieldname chosen by the compiler:

private int <Property1>k__BackingField;

You can see how it can be guaranteed to be unique -- it uses characters that are not allowed in C#!

Encapsulation

Why is it nicer to use a property than a field? There's a few reasons that I listed above: different permissions for get and set, add behaviour when the value is set, and make it easy to version your class so that callers won't notice when you change your internal features.

Accessibility

If you expose a field as public, you can't restrict your callers from updating it's value. A property can be made public for get, and private for set, which makes it easy to expose data, but still encapsulate it within your class.

Behaviour

Sometimes you'll want to do some validation checks when a property is set. For example, you might want to check that Property1 is never set to 0:

set {

   if (_Property1 != 0)

      _Property1 = value;

}

If you use a property, then you have the ability to add this logic inside the get or set method -- with a field that's not possible.

Versioning

If you expose a public field to callers, changing the name or data type of that field breaks the contract your class has with it's callers, and they will all need to be updated.

With a property, you can change the internals of your class, and where it stores the data, without affecting the caller of your property -- as long as the property has the same name, type and accessibility, they won't know anything has changed.

This helps with versioning your class, as changes to your class won't affect the rest of your program.

 

Cheers,

Kirk

 

Previous C# tips:

And other Visual Studio tips:

    posted on Sunday, October 26, 2008 8:59:49 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]
     Saturday, October 25, 2008

    Here's a great Visual Studio 2008 option that I didn't know existed until a few months ago:

    Save new projects when created option in Visual Studio

    Under Tools -> Options -> Projects and Solutions, you can uncheck the "Save new projects when created" option to let you whip up a little project to test something out, without having to bother with saving it somewhere permanent.

    When creating a new project, instead of this:

    File -> New Project dialog, with prompts for location and solution name

    You'll get this:

    File -> New Project dialog, with prompt only for project name 

    No longer do you have to name your project "ConsoleApplication64"! You can use ConsoleApplication1 as often as you want :)

    Where does it save these temporary projects, you may ask? They get stashed in a Temporary Projects folder underneath your profile's AppData directory.

    When you close the project or quit Visual Studio, you'll get a prompt asking you if you want to keep the project:

    NewProject3

    If you choose Discard, it will be removed from disk and you'll never see it again!

    ConsoleApplication1, here I come!

    Kirk

     

    Previous tips:

    posted on Saturday, October 25, 2008 10:06:03 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Friday, October 24, 2008

    Just placed my order for the second edition of Framework Design Guidelines by Kryzstof Cwalina and Brad Abrams at Fishpond. They've got a good pre-order special of $59.42 (might be today only).

    I'm really looking forward to reading all of the new guidelines in book format, although Kryzstof has been reasonably open by publishing them on his blog as they were developed, and has released a Framework Design Guidelines Digest with some of the useful nuggets from the book.

    posted on Friday, October 24, 2008 1:35:17 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]
     Thursday, October 23, 2008

    A common scenario is wanting to delete an item while iterating over a collection using foreach:

    foreach (string name in names)

    {

        if (name == "Kirk")

        {

            names.Remove(name);

        }

    }

    Unfortunately, this will give the dreaded InvalidOperationException:

    Collection was modified; enumeration operation may not execute.

    This is because modifying the state of a collection invalidates the enumerator that foreach uses behind the scenes to loop over the collection.

    A common work-around is to convert the foreach to a for loop:

    for (int i = names.Count - 1; i >= 0; i--)

    {

        if (names[i] == "Kirk")

        {

            names.RemoveAt(i);

        }

    }

    You'll notice that the for loop goes backwards from the end of the list (position: Count - 1) back to the start (position: 0), so that when an item is removed, our current index i is still a valid position in the list.

    How do you do it?

    Kirk

    Source (such that it is) Program.txt

    posted on Thursday, October 23, 2008 11:08:06 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]

    Via Scott Wylie's blog - you can join a focus group to tell Microsoft NZ what you think about being a Microsoft developer.

     

    It could be another opportunity to provide feedback that may feed back to the product development teams within Microsoft, plus they say you'll receive a "token of appreciation", and those are always good :)

     

    Details below:

    This is your chance to tell us what you think about Microsoft!

    Invitation for The Microsoft New Zealand Developers Focus Groups 2008

     

    We want to hear from you. Tell us what you love and hate about Microsoft! Every year we use your feedback to improve our products and services. This year, in addition to the annual online survey, we are planning to hold focus groups around the country and are looking for NZ developers to have their say.

     

    Scott Wylie (http://blogs.msdn.com/scottwylie), the Director of the Developer and Platform Strategy Team for Microsoft NZ, will be facilitating these sessions. Scott’s role is to listen and understand your feedback which will enable his team to provide better support and resources for NZ developers.

     

    If you would like to participate, please email your interest to nzeditor@microsoft.com with your contact details and preferred focus group (by session number as listed below) you would like to attend. We will confirm you attendance shortly after via email and phone. You can be assured that all information shared will be kept confidential.

     

    Christchurch Convention Centre / Tuesday 11th November 2008

    Kilmore Street, Christchurch

    Session 1: 8:30 -10:00

    Session 2: 11:00 -12:30

    Microsoft New Zealand Wellington Office / Thursday 13th November 2008

    Level 12, Vodafone on the Park, Lambton Quay, Wellington

    Session 3: 8:30 -10:00

    Session 4: 11:00 -12:30

    Microsoft New Zealand Auckland Office / Wednesday 19th November 2008

    Level 5, 22 Viaduct Harbour Avenue, Auckland

    Session 5: 8:30 -10:00

    Session 6: 11:00 -12:30

     

    Refreshments and a token of our appreciation will be provided for your participation.  We look forward to hearing from those of you who are interested to participate in the focus groups. Please note that there are limited spaces available so please respond early to secure your space for the focus group.

    MSDN NZ Team

    nzeditor@microsoft.com

    posted on Thursday, October 23, 2008 1:11:45 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Wednesday, October 22, 2008

    I've recently read two interesting accounts of the history of C#, one from Bart De Smet, and the other on Computerworld's website.

    “The C# Programming Language Third Edition” and thoughts on language evolution

    Bart does a quick run-through of the evolution of C# through version 1, 2 and 3, and briefly covers three of the influences on C# now and into the future: concurrency, dynamic languages and meta-programming.

    The A-Z of Programming Languages: C#

    This interview with Anders on Computerworld covers a lot of the 10 year history of C#, along with the influences and problems encountered along the way. Anders lists the same future influences as above, with the addition of declarative programming (LINQ, functional and DSLs being examples).

    Both articles are interesting reading if you want a brush-up before we hear all about what's going to be in C# 4.0 next week as the PDC news rushes into our RSS readers.

    Kirk

    posted on Wednesday, October 22, 2008 11:14:44 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Wednesday, October 15, 2008

    I'm enjoying presenting in a few new locations around the country at the moment. Coming up, I'll be presenting at:

    All of the above events are free of charge, so hopefully you'll have a chance to come along!

    Kirk

    * More info about the "PDC Fireworks!" event will come shortly.

    posted on Wednesday, October 15, 2008 9:18:56 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Monday, October 13, 2008

    As well as (or despite) the commercial videos on YouTube, there's a whole culture and community of people on there.

    This video, An anthropological introduction to YouTube is a good watch, covering the back-story behind the YouTube phenomena, and a bit on how the culture is building around vlogging and personal messages on YouTube.

    It's 55 minutes:

    posted on Monday, October 13, 2008 11:03:17 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    I enjoyed reading this book. Christopher Fairbairn, organiser of the Christchurch .NET User Group recommended it to me as containing a bunch of useful tips for running a user group, and I have to agree with him.

    The author is Dr. Greg Low, who has spent a long time organising MSDN and SQL Server user groups in Queensland, Australia. Greg is a big supporter of Code Camps, and has helped organise Code Camps in Australia and spoken in New Zealand. When I first met Greg, I was impressed by his enthusiasm and energy.

    The Rational Guide to Building Technical Communities is all about improving your user group, with ideas on running your group more consistently; finding, recruiting and growing your speaker pool; recruiting volunteers; and running the meeting successfully.

    The book has the following sections:

    • Overview
      • People, Not Technology
      • Something for everyone
      • Finding speakers
      • Tried and true
    • Starting and growing user groups
      • Pizza does not define a user group
      • Don't reinvent the wheel
      • Recruiting members
      • Content and handouts
    • User group meetings and conferences
      • Using technologies
      • Recruiting volunteers
      • Conducting meetings
      • Tips for presenters
    • Legal and finance
      • The fine print
      • Funding

    Some things (like Legal and Finance), we've got sorted now in New Zealand with our incorporated society (although the section on different types of insurance we might need was an eye opener), and others I still struggle with.

    Most interesting to me was how to attract and keep new members by making them feel welcome in the group. Some ideas, like introducing new members at the start of a meeting I will try out at our next meeting.

    Greg repeats a marketing adage: "the easiest customer to find is the one you already have", and that's too true. Each time someone comes along to our user group, we have to give them as much opportunity as possible to stay in our group -- by pitching future topics at their level, and making sure that they know about them. In our Wellington group we're trying to have some more introductory or general purpose topics to try and appeal to more people.

    In summary, I guess the most useful things I drew from this book were about the human side of running a user group. That's what I find the most enjoyable and rewarding, and Greg gives some good tips on how to make it happen.

    Cheers,

    Kirk

    posted on Monday, October 13, 2008 9:09:11 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Monday, October 06, 2008

    Some of the common hacks use an inner frame to host your site, while the attacker controls the surrounding frame.

    Using the following Javascript code, you can make sure your site is running the top frame in the browser:

            <script type="text/javascript">
              
              if (parent.frames.length > 0) {
                parent.location.replace(self.document.location);
              }
              
            </script>

    The code will reload the current page in the parent window if it is within a frameset.

    Kirk

    posted on Monday, October 06, 2008 10:55:17 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [3]
     Thursday, October 02, 2008

    Cool to see that Amazon will be offering Windows pay-as-you-go EC2 instances:

    Coming soon: Amazon EC2 with Windows

    It will be good to have another option for running SQL and ASP.NET solutions out in the cloud.

    posted on Thursday, October 02, 2008 9:14:13 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]

    If you're using certificates to authenticate, and you get the above error, then the root cause may be this:

    System.ServiceModel.Security.MessageSecurityException
    The security timestamp is invalid because its creation time ('2008-10-02T02:50:25.161Z') is in the future. Current time is '2008-10-02T02:44:44.909Z' and allowed clock skew is '00:05:00'.

    Basically, if your client and server have clocks that are different by more than 5 minutes, the timestamp that they send to each other when they authenticate may be more than the tolerance allowed (default 5 minutes).... and it will fail.

    The solution is to change one of the clocks :)

    Kirk

    posted on Thursday, October 02, 2008 3:30:58 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [2]
     Tuesday, September 30, 2008

    Finding it hard to click on that little red line to bring up the menu?

    image

    I find it really hard to get the mouse in the right place to bring up the smart tag menu:

    image

    My favourite key combo in Visual Studio is Ctrl + . (hold down control, press the dot). If you do this when you have the cursor near the smart tag, the menu will pop up. You can then use the keyboard arrow keys to go up and down to select (Enter) the option you want.

    Ctrl + .

    Magic.

    Kirk

    Previous tips:

    posted on Tuesday, September 30, 2008 9:16:16 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Monday, September 29, 2008

    I've been using Vista since it came out, and to tell you the truth I haven't found it as annoying as it's made out to be -- and I develop with UAC still turned on :)

    The Tweakguides site has a nice writeup of Vista annoyances, and how to resolve them:

    1. Constantly changing folder views - how to stop the folder view switching from details to large icons semi-randomly when you're in the file explorer.
    2. Nagging UAC prompts - not that there's anything wrong with it :)
    3. Constant hard drive activity - configure super fetch, indexing, defragmenting, malware scanning. I didn't realise the defragmenter still ran weekly.
    4. Vista has bad driver support - well that's really the device manufacturer's fault...
    5. Vista is a memory hog - I didn't understand what SuperFetch did before this.
    6. Drive space keeps shrinking - shadow copies, restore points and other stuff that fills up your drive.
    7. Windows Photo Gallery freezes - haven't had this problem myself.
    8. Vista's eye candy is a performance drain - not as bad as they say, really.
    9. Vista is loaded with DRM - huh?

    I haven't run into many of these problems myself, but I've picked up a few interesting things reading this article.

    Kirk

    posted on Monday, September 29, 2008 9:51:56 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    I'm always underwhelmed by the 4 cent per litre discount vouchers offered by the supermarkets.

    On our fill up yesterday, we saved the whopping total of $2.04 on our $100.94 petrol purchase, thanks to a supermarket voucher.

    Dick Smiths have gone a bit higher with their discount - 49 cents per litre:

    image

    I've been using Fuelly for the past few months to track our fuel spending. I don't know that it's providing a lot of value, but it is cathartic to process my receipts as if it's somehow helping :)

    Kirk

    posted on Monday, September 29, 2008 8:00:24 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    Now this definitely isn't the right blog to answer that question, but James O'Neill has written a nice post that summarises my experience trying to get Server Core up and running. The long and the short of it is that you shouldn't bother for a one-off installation:

    Server Core -- Too dry and crunchy?

     

     

    posted on Monday, September 29, 2008 9:23:27 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Saturday, September 27, 2008

    Sara Ford points to the release of Snippet Designer by Matthew Manela.

    Snippets are a remarkably cool productivity tool within Visual Studio. I say "remarkable", because many people don't even know they exist!

    It's great to have a UI over the top of the snippet XML files, which are a little painful to edit by hand. Snippet Designer lets you select a section of code, and export it to the designer to create a snippet:

    image

    (I had to cheat to get the screenshot of the menu... anyone know how to do that?)

    Then you're dropped into the Snippet Explorer's designer surface, where you have three or four simple steps:

    image

    1. Right-click a symbol and create a replacement (above, I turned the 'argument' variable into a replacement). A replacement is text that the user can edit when using your snippet.
    2. Edit the details of the replacement, including the default value and tooltip text.
    3. Add a shortcut to your snippet.
    4. (Optionally) Enter $selected$ $end$ where you'd like the cursor to appear after the snippet is finished. This is imported for SurroundsWith snippets, as the text you're surrounding will be replaced here.

    Then simply save the snippet into your snippets directory inside My Documents (the default location is probably right), and now you can use your snippet when editing code.

    Type the shortcut string (mine was 'fow'):

    image

    Press "Tab" "Tab":

    image

    And you end up in the first replacement variable, with the default value entered. Over-write the text with what it should be, and press Tab to jump to the next replacement. Continue pressing tab until everything is correct, and press Enter. You'll jump to the middle of the replacement text:

    image

    The snippet file is just XML, so you can edit it directly, or copy it to other computers easily.

    There are a lot of snippets installed out of the box, you can browse them using the old Code Snippets Manager (under the Tools menu), or using the new Snippets Explorer installed by the Snippets Designer (under View -> Other Windows).

    I'll be showing off the Snippets support in future Visual Studio tips n tricks talks. If you're interested in more tips, I have a Visual Studio 2008 series on this blog, or you can visit Sara Ford's blog.

    Previous:

    posted on Saturday, September 27, 2008 11:29:59 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [3]
     Tuesday, September 16, 2008

    Last month the guys from Mindscape released a Visual Studio File Explorer Addin. This is really useful if you don't have good source control integration within Visual Studio, or you want access to the full goodness available from an explorer window, but within Visual Studio.

    The feature list:

    • Fully Shell Enabled – So shell extensions like TortoiseSVN work just fine.
    • Command Prompt Here – Opens a command prompt at the current folder.
    • Snap to Solution – Sets the root folder to the current solution’s folder.
    • Split View – Windows Explorer style.
    • Open Item – Either in Visual Studio or the registered application.
    • Options Dialog – For configuring the add-in.

    And a screenshot:

    dump1

    It's good at twice the price! Download for free from the Mindscape site: Visual Studio File Explorer Addin

    Kirk

    posted on Tuesday, September 16, 2008 1:00:50 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    The presenters at last months Code Camp have made their slides available via their own blogs:

    Thanks for presenting guys!

    Kirk

    posted on Tuesday, September 16, 2008 12:08:53 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Saturday, September 13, 2008

    Sara Ford has been publishing a great series of Visual Studio 2008 tips of the day, since July 2007.

    I have given a couple of Visual Studio tips'n'tricks talks lately, and have recommended to the audience that they should go back to the beginning of the series and read her tips from the start.

    If the thought of reading over a years worth of daily posts in a web browser scares you, I have assembled a Yahoo Pipe that grabs posts from 410 days ago and sends them out in an RSS feed, just like it was July 2007:

    http://pipes.yahoo.com/cpkirk/saraford410

    Each day you'll get the most recent posts from 410 days ago showing up in your feed reader.

    Click the above link, and choose one of the options to add it to your feed reader, or you can even subscribe to email alerts each time there is new content (well, actually it's 410 day old content masquerading as new content).

    Yahoo Pipes

    Yahoo Pipes are pretty cool, they let you do transformations on a bunch of different types of data sources, and then re-expose them as a new feed.

    In this case I have used an RSS feed from a Google blog search, as they allow you to search for posts on a given site and return all the results Google has cached. In Sara's case, Google will return 368 posts whereas her own feed only gives the most recent 15.

    The pipe just builds up the right query string for Google, and then passes the url to the feed fetcher. The source is visible when you visit the pipe, although I have to admit that it's pretty simple and you could probably figure it out yourself :)

    Blog series

    It's interesting when you try to join part-way through a long running series on someone's blog.

    The newest post at the top of their site (and your feed reader) is halfway through the series, so you have to scroll or read through the archives to get the earlier posts.

    I often find when I stumble across "Part 7 of 11" blog posts that entering late puts me off subscribing to that blog, because of the weight of having to read so much to catch up so I can join the conversation.

    Perhaps having a "Subscribe to this series from the beginning" link using a similar trickle fed time shifted approach would help people overcome that?

    Irony

    It did feel a little like having 10,000 spoons when all I needed was a knife to use a Yahoo beta product to pull data from a Google search to send people to a Microsoft employee's blog posts. Ain't the internet great!

    Many thanks to Sara for the great series.

    Kirk

    posted on Saturday, September 13, 2008 12:16:34 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Thursday, September 11, 2008

    I got asked this last night in Christchurch: "How do you make it so regions are always expanded?"

    There's a couple of different ways to do this:

    • You can turn off outlining altogether, in the Advanced Settings under C#:
      OutliningToggle
    • You can learn the keyboard shortcuts for expanding and contracting outlines: Did you know how to collapse and expand code - Sara Fords blog
    • Or, you could reduce your use of regions (I've found they're often used to hide code, when really it should be refactored).

    Kirk

    posted on Thursday, September 11, 2008 12:08:41 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
    That was embarrassing. I went to demo the "Copy References" feature in Visual Studio 2008, and I couldn't remember how to do it.

    That's because it's not in the standard install of Visual Studio, but is part of the PowerCommands for Visual Studio 2008 package.

    Check out the feature list that I've copied below. Some really useful stuff, you should download now and install it!

    Enable/Disable PowerCommands in Options dialog
    This feature allows you to select which commands to enable in the Visual Studio IDE.  Point to the Tools menu, then click Options.  Expand the PowerCommands options, then click Commands.  Check the commands you would like to enable.
    Note: All power commands are initially defaulted Enabled.

    Format document on save / Remove and Sort Usings on save
    The Format document on save option formats the tabs, spaces, and so on of the document being saved.   It is equivalent to pointing to the Edit menu, clicking Advanced, and then clicking Format Document. The Remove and sort usings option removes unused using statements and sorts the remaining using statements in the document being saved.
    Note: The Remove and sort usings option is only available for C# documents.
    Note:  Format document on save and Remove and sort usings both are initially defaulted OFF.

    Clear All Panes
    This command clears all output panes. It can be executed from the button on the toolbar of the Output window.

    Copy Path
    This command copies the full path of the currently selected item to the clipboard. It can be executed by right-clicking one of these nodes in the Solution Explorer:
    The solution node; A project node; Any project item node; Any folder.

    Email CodeSnippet
    To email the lines of text you select in the code editor, right-click anywhere in the editor and then click Email CodeSnippet.
    Insert Guid Attribute
    This command adds a Guid attribute to a selected class.  From the code editor, right-click anywhere within the class definition, then click Insert Guid Attribute.

    Show All Files
    This command shows the hidden files in all projects displayed in the Solution Explorer when the solution node is selected.  It enhances the Show All Files button, which normally shows only the hidden files in the selected project  node.

    Undo Close
    This command reopens a closed document , returning the cursor to its last position.  To reopen the most recently closed document, point to the Edit menu, then click Undo Close.  Alternately, you can use the Ctrl+Shift+Z shortcut.
    To reopen any other recently closed document, point to the View menu, click Other Windows, and then click Undo Close Window.  The Undo Close window appears, typically next to the Output window. Double-click any document in the list to reopen it.

    Collapse Projects
    This command collapses a hierarchy in the solution explorer starting from the root selected node. It can be executed from three different places: solution, solution folders and project nodes respectively.

    Copy Class
    This command copies a selected class entire content to the clipboard. It can be executed from a single project item or a project item with dependent sub items.

    Paste Class
    This command pastes a class entire content from the clipboard. It can be executed from a project or folder node.

    Copy References
    This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.

    Paste References
    This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.

    Copy As Project Reference
    This command copies a project as a project reference to the clipboard. It can be executed from a project node.

    Edit Project File
    This command opens the MSBuild project file for a selected project inside Visual Studio. It can be executed from a project node.

    Open Containing Folder
    This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node

    Open Command Prompt
    This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.

    Unload Projects
    This command unloads all projects in a solution. It can be executed from the solution node.

    Reload Projects
    This command reloads all unloaded projects in a solution. It can be executed from the solution node.

    Remove and Sort Usings
    This command removes and sort using statements for all classes given a project. It can be executed from a solution node or a single project node.
    Note: The Remove and Sort Usings feature is only available for C# projects since the C# editor implements this feature as a command in the C# editor (which this command calls for each .cs file in the project).

    Extract Constant
    This command creates a constant definition statement for a selected text. It can be executed from the code window over a selected text.

    Clear Recent File List
    This command clears the Visual Studio recent file list.

    Clear Recent Project List
    This command clears the Visual Studio recent project list.

    Transform Templates
    This command executes the associated custom tool with text templates items. It can be executed from a DSL project node or a folder node.

    Close All
    This command closes all documents. It can be executed from a document tab.



    Kirk

    posted on Thursday, September 11, 2008 9:51:09 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Wednesday, September 10, 2008
    Well, what a nice town centre.

    I was down in Christchurch this afternoon presenting at the Christchurch .NET users group. It was great to finally see the group in action, since it has been running as long as our group in Wellington.

    I presented a repeat of my Visual Studio Tips n Tricks talk to a crowd of about 40 keen Cantabrians. It was good to see that a couple of newcomers had come along for the night, hopefully they'll see you back again!

    It was my first trip to Christchurch in 28 years.

    I don't remember much about Christchurch from my first trip (I was two years old). I remember Dunedin well, as I had a traumatic experience after locking myself in a bathroom, but obviously nothing as memorable happened in Christchurch.

    The town centre is very picturesque, and walking alongside the Avon River in the sun was lovely. Reminds me that I should get out of the office more often.

    The highlight of my walk was seeing the trams in action. It's great to see rails through the centre of town.

    In other news, I was happy to see that Paula Tesoriero won a gold medal in track cycling (and later, a bronze) at the Paralympics. Paula was at Kapiti College the same time as me -- it's great to see a fellow student succeeding on the international stage!

    Kirk

    posted on Wednesday, September 10, 2008 11:39:36 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    I talked about this briefly last week -- if you want to administer Hyper-V using PowerShell, what options do you have?

    WMI

    Hyper-V proffers some functionality through WMI classes in the “root\virtualization” namespace. You can access the raw WMI classes from PowerShell using examples like in my talk, or you can use the great library James O'Neill has uploaded to CodePlex: PowerShell Management Library for Hyper-V

    Ben Pearce is doing a series on scripting Hyper-V with WMI which you should definitely check out.

    System Centre Virtual Machine Manager 2008

    SCVMM is a new product that will be releasing soon. It offers a unified management interface and set of services for managing a datacenter full of virtual machines. It is an additional product purchase, and so not everyone will have it.

    I haven't used them, but apparently SCVMM's PowerShell cmdlets are a lot more natural to use than WMI. Further information about the PowerShell interface is available in this Scripting Guide.

     

    Ultimately, you'll need to evaluate both approaches to see which one fits. WMI-based scripts will probably be usable in more situations, but SCVMM scripts will be easier to author and maintain.

    Kirk

    posted on Wednesday, September 10, 2008 12:12:57 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Tuesday, September 09, 2008

    As promised, here's the transcript of the PowerShell commands I used in my talk:

    TechEdTranscript.txt (107.64 KB)

    The bulkservers scripts that I used were from Ben Pearce's blog: Administering Servers in Bulk. I've uploaded my versions of the scripts here: BulkServerScripts.zip

    Following is a synopsis of the commands I used in the talk.

    Get a list of all classes in the CIMV2 namespace:

    > get-wmiobject -namespace "root\cimv2" -list

    Get a list of all disks on a remote machine:

    > gwmi -class win32_logicaldisk -computer columbus

    Update the Volume Name of a disk. Note that often when making changes to WMI properties, you need to Put() the object to set your changes back on the original machine:

    > $disks[0].VolumeName = "Kirks disk"
    > $disks[0].Put()

    List hotfixes applied to a machine:

    > gwmi win32_quickfixengineering | format-table hotfixid

    Get a representation of the running OS. You can shutdown, reboot etc:

    > $os = gwmi win32_operatingsystem

    Get all the network adapters on a machine:

    > $nics = gwmi win32_networkadapterconfiguration

    You can update the IP addresses, netmasks etc:

    > $mynic.enablestatic($newip, $newmask)

    Get a list of the Hyper-V virtual machines:

    $vms = Gwmi –namespace “root\virtualization” –class msvm_computersystem

    Set one of the virtual machines to the running state:

    > $VM.RequestStateChange(2)

    I hope that these examples show you the variety and power of things you can manipulate using PowerShell over WMI. You can access almost every physical or logical device that is connected to your computer (or another computer on your network), as well as administer many different software products.

    Kirk

     

    posted on Tuesday, September 09, 2008 11:52:50 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

    I had fun preparing and presenting the Visual Studio Tips n Tricks talk at TechEd last week... although I think about half the jokes fell flat!

    Here's the slides -- you'll see there's not much of value in them:

    DEV313-Jackson-VisualStudioTips-Clean.pptx (1.4 MB)

    ...and that's because most of the talk was the demo. I walked through a lot of Visual Studio keyboard combinations that I find useful, as well as walking through some of the features that can make you more productive, such as the snippet manager, settings management and macros.

    Here's a table of all the keyboard shortcuts I used:

    C# Key Combo VB Key Combo
    View.ShowSmartTag CTRL + . CTRL + .
    Edit.ParameterInfo CTRL + SHIFT + SPACE CTRL + SHIFT + SPACE
    Edit.Find CTRL + F CTRL + F Quick find
    Edit.IncrementalSearch CTRL + I CTRL + I Incremental find
    Edit.FindInFiles CTRL + SHIFT + F CTRL + SHIFT + F Find in files
    Edit.Replace CTRL + H CTRL + H Quick replace
    Edit.ReplaceInFiles CTRL + SHIFT + H CTRL + SHIFT + H Replace in files
    Edit.GotoNextLocation F8 - Go to next location (in search results)
    Edit.GotoPrevLocation SHIFT + F8 - Go to previous location (in search results)
    Edit.FindNext F3 F3 Repeat search
    Edit.FindPrevious SHIFT + F3 SHIFT + F3 Search previous
    Edit.FindNextSelected CTRL + F3 CTRL + F3 Search for next with selected text
    Edit.FindPreviousSelected CTRL + SHIFT + F3 CTRL + SHIFT + F3 Search for previous with selected text
    View.NavigateBackward CTRL + - CTRL + - Go back to previous location (Browser-style)
    View.NavigateForward CTRL + SHIFT + - CTRL + SHIFT + - Go forwards to next location
    View.ViewCode F7 F7 View code
    View.ViewDesigner SHIFT + F7 SHIFT + F7 View designer when in markup
    View.ViewMarkup SHIFT + F7 SHIFT + F7 View markup when in designer
    Edit.CycleClipboardRing CTRL + SHIFT + V CTRL + SHIFT + V Cycle through Visual Studio clipboard
    Edit.GotoBrace CTRL + ] - Jump to opposing brace / XML tag
    Edit.GotoBraceExtend CTRL + SHIFT + ] - Select text to the opposing brace / tag
    Edit.GotoFindCombo CTRL + / - Jump to the find combo in the toolbar
    Window.ShowEzMDIFileList CTRL + ALT + DOWN ARROW CTRL + ALT + DOWN ARROW Show popup of all open files
    Debug.Start F5 F5 Start with debugger
    Debug.StartWithoutDebugging CTRL + F5 CTRL + F5 Start without debugger
    Debug.Restart CTRL + SHIFT + F5 SHIFT + F5 Restart the program
    Debug.StopDebugging SHIFT + F5 CTRL + ALT + BREAK Stop debugger
    Debug.RunToCursor CTRL + F10 CTRL + F10 Run to the cursor
    Debug.ToggleBreakpoint F9 F9 Set / remove breakpoint
    Debug.DeleteAllBreakpoints CTRL + SHIFT + F9 CTRL + SHIFT + F9 Delete all breakpoints
    Debug.EnableBreakpoint CTRL + F9 - Enable a breakpoint
    Debug.StepInto F11 F11 Step into a method
    Debug.StepOut SHIFT + F11 SHIFT + F11 Step out of a method
    Debug.StepOver F10 F10 Step over a line
    Tools.RecordTemporaryMacro CTRL + SHIFT + R - Start recording a macro
    Tools.PlayTemporaryMacro CTRL + SHIFT + P - Playback a macro

    If you want an even more comprehensive list of keyboard combinations, you can check out the following links, or go exploring in Tools > Options > Keyboard:

    C# Keybindings

    VB Keybindings

    C++ Keybindings

    Cheers!

    Kirk

    posted on Tuesday, September 09, 2008 11:02:41 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [5]
     Sunday, September 07, 2008

    It just struck me while playing around with Chrome that I have been using Gmail for more than 4 years.

    At the time, I thought "I'll never use up 1 gig of mail storage", but luckily, Google has been steadily adding to my quota - faster than the rate I'm using it up.

    I primarily use my Gmail account for mailing list subscriptions, as it is really fast for scanning and reading mailing list posts, and still has the nicest interface for reading conversation threads that I have seen. As most of my mailing list subscriptions are "read only" (I lurk, without posting), Gmail is my own private little search engine over the mailing lists I subscribe to.

    Fears of instability, data lock-in or data loss have so far been unfounded. There have been occasional issues accessing Gmail, but none that have caused me undue distress.

    All in all, I'd say a pretty good 4 years.

    posted on Sunday, September 07, 2008 4:44:24 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Thursday, September 04, 2008

    Hello TechEd campers....

    I hope I didn't freak you out too much with my awesome dance moves -- hopefully I woke you up!

    I've cleaned up my slide deck marginally, and I will upload it to Commnet shortly.

    I'll be posting up the slides, sample scripts and the transcript of my demo over the next few days, so subscribe to my RSS feed, or check back soon.

    Always welcome to hear feedback (good or bad), or receive dance tuition. Contact me at kirk@pageofwords.com.

    Cheers!

    Kirk

    SVR316 - Windows PowerShell and Windows Management Instrumentation: Unveiling Microsoft's best kept secret

    posted on Thursday, September 04, 2008 6:17:35 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [5]
     Friday, August 22, 2008
    Just read that Red Gate are taking over development of Reflector from Lutz Roeder.

    Reflector is one of the best .NET development tools, and it is awesome that Lutz has provided it free for so long. I have learnt a lot from playing around inside that UI, and it has helped me out of many a pickle.

    Red Gate have a pretty good track record of producing great software (SQL Compare is awesome!), and it is cool that they are giving back to the community by developing and enhancing Reflector going forward. I'm looking forward to seeing what they do with it!

    Kirk.

    posted on Friday, August 22, 2008 12:55:31 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Thursday, August 21, 2008
    Many years ago in late 2002, I spent quite a few hours playing around with Rotor, the Shared Source CLI implementation.

    Back then Rotor was the easiest way to get a peek at how the .NET runtime and supporting libraries might have been implemented. Not everything was there, and that which was there wasn't guaranteed to function in exactly the same was as the shipping CLR, but it let you look at the C# and C++ source code that made things happen.

    I played around with the Gyro patch half-heartedly, but by the time the v2 release of SSCLI came out, my thirst was adequately quenched by Reflector so I never really got into the genericised version.

    I didn't read Stutz, Neward and Shilling's Shared Source CLI Essentials book (sorry guys!) but it did sit on my wishlist for a while.

    Now Ted Neward and Joel Pobar are self-publishing the sequel to the book, and will be giving away the electronic version of it through the Microsoft site.

    I have had a brief skim through the draft, and it's a CLR geeks heaven. I'm looking forward to curling up with it some time in the near future.

    Check it out: Shared Source CLI 2.0

    I believe Joel is at TechEd Australia next month - make sure to go along to his F# talk if you're there.

    posted on Thursday, August 21, 2008 3:00:47 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
     Wednesday, August 13, 2008
    We've finalised the speakers for Code Camp on 31 August -- and I'm very happy to report that we have some great local and international speakers coming along to present. I thank them in advance for volunteering their time to prepare and present to us.

    • Owen Evans from Xero will be talking about the ASP.NET MVC project
    • Jonas Folleso a Senior Consultant at Capgemini and a Microsoft Regional Director for Norway will be taking us through Silverlight from a developers perspective
    • Robert Fonseca-Ensor from Datacom Systems Limited will be talking about Test Driven Development and Dependency Injection
    • Scott Hanselman, Community Liaison and blogger from Microsoft will be talking about Dynamic Data
    • Ivan Towlson from Mindscape will be presenting a session on Thinking in WPF

    As you can see, we've got a wide variety of sessions, from general development techniques, to web and desktop technologies. We haven't completely finalised the ordering of the sessions, but as you'll see on the Code Camp website, we're running from 9am till 6pm, and will be providing a free lunch and afternoon tea courtesy of our sponsors.

    We also have a number of lightning talks which will feature a wide range of different topics, from technologies such as WCF, to products, and to communities around NZ. If you're keen to be involved in presenting a lightning talk (or have suggestions for topics), read my previous post.

    I'm looking forward to it. Sign up now and I'll see you there!

    Kirk

    posted on Wednesday, August 13, 2008 5:32:46 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]