Saturday, December 06, 2008

The SQL PASS Community Connection event is kicking off about now in Porirua (20 mins from Wellington). I'm not able to make it today, but I do plan to head along tomorrow.

Wake up, get up, and head on over!

posted on Saturday, December 06, 2008 8:05:06 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Friday, December 05, 2008

I'm in Napier presenting my Visual Studio Tips and Tricks talk to the Hawkes Bay .NET Users Group.

I think we're on at 3:30pm at the Taradale EIT Campus, but email me if you're thinking of coming, and I'll get you the info.

Kirk

[Update 8 Dec 2008: Added details below]

The session is at 3:30pm on Tuesday 9 December, at the following location:

Room C117
C-block (Computing building)
EIT (Eastern Institute of Technology)
Taradale end of Gloucester Street
Taradale, Napier

posted on Friday, December 05, 2008 10:29:04 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Thursday, December 04, 2008

I spent some time browsing the Givealittle site while eating my lunch today, and I'm struck by how great an idea it is.

JD from Mindscape posted about how they built the site, which is of course how I ended up there :)

When I've donated money in the past, or wanted to give a gift of donation for a wedding, birthday or Christmas, I've always spent ages on Google trying to find the project that 'fit' with the recipient (Are they religious? Do they like animals? etc). Givealittle lets you browse a whole bunch of charities on one site, and even give vouchers which let people choose charities of their choosing.

There's other features of Givealittle which are good news for givers and charities too, reduced costs of transactions, transparency over where the money is spent, collation of all your receipts so that tax time is easier and more.

A fantastic idea, and a site that I plan to use this Christmas.

Kirk

posted on Thursday, December 04, 2008 1:04:26 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [2]
 Wednesday, December 03, 2008

I had fun presenting on ASP.NET security tonight at the .NET Users Group. It was a bit of a whirlwind tour through some common security issues that you might come across when developing and deploying an ASP.NET application.

I've already posted the slides to this talk from back when I presented at the Christchurch Code Camp: Overcoming your web insecurity

posted on Wednesday, December 03, 2008 9:14:41 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Tuesday, December 02, 2008

I spent the evening at the Summer of Code user group event, along with James Hippolite and Scott McKenzie who are also from the Wellington .NET Users Group.

Summer of Code helps place students into companies over their summer break. At Xero we have James Sullivan currently working on Xero Labs samples on our Xero developer site.

The event tonight was to put students in touch with user groups around Wellington. It was great to see the cool user groups that are up and running, from PHP and Linux to WellRailed and SuperHappyDevHouse. Hopefully those students that were there got to see that there's a lot of good support if you're interested in learning new topics, and support for people that want help.

Go Wellington!

Kirk

posted on Tuesday, December 02, 2008 9:57:52 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Monday, November 24, 2008

The Security Development Lifecycle website has been updated, and they have launched a cartoon:

http://www.bakingsecurityin.com/

image

You can follow the adventures of Kevin and how he transforms into Kevlarr (presumably while learning to write secure code).

They've got an RSS feed for the comics: RSS (although strip 2 didn't work in the RSS for me, so you might want to go to the site)

posted on Monday, November 24, 2008 7:46:04 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Saturday, November 15, 2008

Next Wednesday we've got Chaks introducing us to Microsoft .NET Services, which are a set of building blocks provided by Microsoft in the upcoming Azure platform that will help you build your cloud computing applications.

The meeting will be held at Xero, starting at 6pm (details below). Please RSVP to kirkj@paradise.net.nz so we can make sure there's enough pizza for all!

Title: Microsoft .NET Services
When: Wed 19 Nov 2008, 6pm
Where: Xero, Level 1, 98 Customhouse Quay, Wellington (above Xero)
Presented by: Chakkaradeep Chandran

Microsoft .Net Services is a part of the recently announced Microsoft Azure Platform.

What does Microsoft .Net Services provide?

Microsoft .Net Services consists of three main components:

  1. Service Bus
  2. Access Control
  3. Workflow Services

They provide a hosting platform where you can develop connected, peer to peer applications that can speak to each other without considering the other complexities such as firewall rules and NAT etc,.

Chaks will cover these three components of .NET Services, and how you can use them in your applications.

Pizza and beer provided. Please RSVP to kirkj@paradise.net.nz

 

User group meetings are open to anyone to attend. Hopefully we'll see you there!

Kirk

posted on Saturday, November 15, 2008 9:04:15 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

Well that's good news: Server Core changes in Windows Server 2008 R2

Server Core will soon allow ASP.NET and PowerShell to be installed as options. They've partitioned the .NET framework and only install those parts that are needed (presumably to remove those parts that depend on the UI). I haven't seen any details, but I expect that things in the System.Drawing space may not be there either.

This is good news for people with a farm of web servers, and also for those that want better management of their server core installs.

Kirk

posted on Saturday, November 15, 2008 8:45:06 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Friday, November 14, 2008

I was pleasantly surprised by this.

I'm kind-of addicted to buying books from Fishpond. Part of it is because they're the best online bookstore in NZ that I've found, and part of it is all of these annoyingly good specials that they email me.

At the bottom of the latest shipping notification email (for my Framework Design Guidelines book, yay!), was this:

image

I was feeling happy at the book being shipped, so I thought I'd follow the link :)

At the end of the link was an extremely simple evaluation form:

Simple evaluation form

Only one click to answer, either Yes or No, no big survey.

Following that, this:

$5 coupon

A $5 voucher, for a single click. That's a good way to say thank-you for helping them improve their service, and really shows that they value the feedback.

Pleasantly surprised :)

Kirk

posted on Friday, November 14, 2008 5:46:00 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]

There's two handy Visual Studio features that you can't customise through the Tools -> Options settings.

Guidelines

This allows you to have a little dotted line that reminds you that your code is getting too long:

image 

Under [HKEY_CURRENT_USER]\Software\Microsoft\VisualStudio\9.0\Text Editor create a string value called Guides, and put a colour and the column position(s) that you want guides to appear at (e.g. Guides = RGB(128,0,0) 79, 119)

(from http://blogs.msdn.com/saraford/archive/2004/05/05/257953.aspx)

 

MRU Tab Ordering

Keep your most recent files at the left of your tab channel, rather than ordering them in the order that the files were opened in:

image

Under the HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0 key, you can create a DWORD UseMRUDocOrdering = 1.

(from http://blogs.msdn.com/saraford/archive/2008/10/09/did-you-know-you-can-keep-recently-used-files-from-falling-off-the-file-tab-channel-331.aspx)

 

Cheers,

Kirk

Previous tips:

posted on Friday, November 14, 2008 5:31:22 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Tuesday, November 11, 2008

I had fun doing the tips'n'tricks talk in Christchurch today. Most of the keyboard shortcuts I showed are in this post of mine from a few months ago, where I have compiled the C# and VB equivalents: Visual Studio Tips n Tricks

The free plugins to Visual Studio that I recommended were:

There's also a cool File Explorer plugin for Visual Studio by the guys from Mindscape: VS File Explorer

I also have a series of other Visual Studio tips on this blog, as well as some C# tips. Subscribe to my RSS to hear more!

Kirk

Previous tips:

posted on Tuesday, November 11, 2008 8:10:17 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [4]
 Saturday, November 08, 2008

We've gone offline for an upgrade, and put a webcam in the office so you can see us work:

image

A little bit of fun with Craig acting for the camera :)

Kirk

posted on Saturday, November 08, 2008 11:08:32 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Thursday, November 06, 2008

Hi,

Many thanks to those who came along to our PDC Fireworks session last night. I hope you had an interesting time hearing about what's coming on the horizon, and that your families enjoyed meeting your geek friends!
A huge thank you to our speakers who presented on such a wide range of topics in a limited time. If you want to find out more or watch any sessions from the PDC, you could visit the Channel 9 PDC site, or visit the blogs of the presenters:

Also, a big thanks to those who helped set up and tidy up the room. Great job!

The .NET user group meets once or twice monthly, usually on the first and third Wednesday of the month. If you'd like to go on my mailing list for upcoming user group presentations, please email me.

If you're interested in the Wellington Sharepoint User Group, or the Wellington SQL User Group, make sure you follow the links to sign up to them.

Upcoming Sessions:

There's a few events coming up in Wellington that are free to attend:

Wed 19 Nov, 6pm - Microsoft .NET Services with Chaks Chandran [.NET User Group]

Microsoft .Net Services is a part of the recently announced Microsoft Azure Platform. What does Microsoft .Net Services provide ?

Microsoft .Net Services consists of three main components:

  1. Service Bus
  2. Access Control
  3. Workflow Services

They provide a hosting platform where you can develop connected, peer to peer applications that can speak to each other without considering the other complexities such as firewall rules and NAT etc,.

Venue: Xero, Level 1, 98 Customhouse Quay, Wellington

Please RSVP to kirkj@paradise.net.nz

Thurs 13 Nov, 1:10-5pm - MSDN Unplugged [Microsoft]

This free half day event, organised by Microsoft, sees JD Trask and myself talking on WPF, Silverlight and Visual Studio. More info here.

Sat 6 & Sun 7 Dec - SQL Pass Community Connection [NZ User Groups]

A free, all day event focussed on SQL and related technologies. Overseas and NZ speakers. Find out more at the event website.

Wed 3 Dec, 6pm - Overcoming your web insecurity [.NET User Group]

In this hour-long session, I'll be introducing you to some of the threats your ASP.NET website will face, and give you ideas on how to protect your users, company and yourself. This applies to public facing and internal (intranet) applications.

RSVP details will be sent out to the announcement list closer to the date.

 

Thanks for reading this far!

Kirk

posted on Thursday, November 06, 2008 9:47:02 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Sunday, November 02, 2008

I got a chance to watch a few great presentations at Code Camp yesterday:

Ivan Towlson - Thinking in WPF:

I've seen Ivan's talk already at the Auckland Code Camp, but I got a few new nuggets of WPF goodness out of it. It was fun watching people get up on the stage and act out the named parts pattern :)

John Rusk - Linq to SQL:

This was a really interesting dive into the good and bad of LINQ to SQL, and some of the stuff John and his co-workers have had to do to work around and extend it, including checking that the model matches the database, in memory save points and model inspection.

It sounds like they've got some really cool code that can be re-used by others -- now we just need to convince them to release it!

Jeremy Straub - IIS 7 Extensibility:

Jeremy gave a short talk about how easy it is to automate IIS administrative tasks, such as creating websites and setting properties, and showed how to do so from within C# and PowerShell. It's really nice how much you can do programmatically against IIS7.

Baroon Anand - Team Foundation Server:

Baroon's talk introduced TFS, and went through some of Intergen's customisation and uses of TFS within their business process and projects. A good overview with some interesting nuggets on running projects through TFS.

Lightning Talks:

I was being the dastardly timekeeper for the lightning talks which was a fun task. There were about 7 lightning talks @ 5 minutes each, on a variety of topics from C# to paper prototyping, solving real-world problems and PDC / Azure announcements. Well done to everyone who presented, there's at least an hour of content from each of that I'd love to hear!

Matt Smith - Productive Sharepoint Development:

Matt is a great presenter, I really enjoyed his talk. It was similar to his TechEd talk (which I didn't go to), so the above link will help you out if you want some tips on how to be a productive developer using Sharepoint (summary: ask your boss for a fast PC, and make your build/deploy as quick as possible).

A bunch of cool tools and tips punctuated by good humour :)

Kirk Jackson - Overcoming your web insecurity:

I can't really comment much on this talk, except to say that there's more stuff in the slides if you're interested :)

David Bales - Scrum Game:

This was a lot of fun. Rather than teaching Scrum via PowerPoint, David had us organised into groups trying to complete tasks by running a series of sprints. I think everyone in the room had a better understanding of the Scrum process and a little idea about the challenges you come across by the end of it.

Clarus is running a Scrum course in December.

 

Of course, there were other presentations through the day (there were two streams), so I didn't get along to all of the great Code Camp presentations. Well done to all of the speakers for great content, and to the organisers for a really interesting day!

Kirk

posted on Sunday, November 02, 2008 10:35:26 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

I had a fun time presenting my talk at the Christchurch Code Camp yesterday. I only fell off the stage once!

A collection of urls:

Here's the sanitised version of my slides:

posted on Sunday, November 02, 2008 7:55:50 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Saturday, November 01, 2008

I've arrived at the Christchurch Code Camp. Currently Ivan is presenting his kick-ass WPF talk "Thinking in WPF".

Today I'm doing a presentation on ASP.NET security, covering the basic threats and giving some of the quick wins that you can do to protect your application and users. I'll post the code up here shortly.

Looking forward to an information-packed day!

Kirk

posted on Saturday, November 01, 2008 8:50:03 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Friday, October 31, 2008

Ponoko is a pretty unique concept - an online shop for individualised goods, where you search a market place or upload designs to have something manufactured just for you.

It's pretty cool for geeks - you can create line art of where you want the laser to cut or etch, and they will cut your design from flat sheets of wood, acrylic or other materials. I have made a one-of-a-kind picture frame for my daughter, and toyed around with a bunch of interesting ideas that I haven't yet followed through with.

If you want a more free-style approach, you can even get them to cut based on your hand drawn sketch - all automatically (Photomake).

Anyway... the interesting news today is that they have broadened their set of materials to include bamboo, felt and plain old cardboard, which should lead to some more variety in the products people can make.

Materials gallery

Kirk

posted on Friday, October 31, 2008 8:23:04 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

Now that's cool.

Miguel demoed Mono running on the IPhone at PDC. He wrote about it a few months ago.

I guess the video will wind it's way up here on Channel9.

image

Kirk

posted on Friday, October 31, 2008 1:25:35 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

Reading about how dynamic is implemented in C# 4.0 over on Sam Ng's blog: Dynamic in C#

How did they implement the new dynamic 'keyword' in C# 4.0? Using the DLR, of course!

Very cool to see that the C# version of dynamic dispatch is implemented over the same mechanisms for call actions, dynamic objects and binders to generate expression trees, with some C# specifics in the binder to implement C#'s rules for dispatch etc.

It's interesting to see the flow-on effects of using a dynamic type in an expression and how the 'dynamism' then flows on to subsequent expressions or invocations involving the resulting object.

Quite a nice bit of work, and well explained by Sam. He's going to post more in the series, so worth subscribing to his blog.

Kirk

posted on Friday, October 31, 2008 12:06:10 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]
 Wednesday, October 29, 2008

The PDC session videos are up on Channel 9: Breakout sessions

They don't seem to have download links for the WMV's (or at least, not for me), so if you want to download the video files you've got to view the source of the page and copy the wmv url into your browser.

For example, Ander's C# talk is available at:

http://mschnlnine.vo.llnwd.net/d1/pdc08/WMV-HQ/TL16.wmv

Basically, replace TL16 in the above url for the session code to download other sessions.

Cheers,

Kirk

posted on Wednesday, October 29, 2008 9:38:50 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [2]
 Tuesday, October 28, 2008

As linked to by the C# Futures site, here are the four main groups of C# 4.0 proposed features:

Dynamic lookup

Dynamic lookup allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.

Named and optional parameters

Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.

COM specific interop features

Dynamic lookup as well as named and optional parameters both help making programming against COM less painful than today. On top of that, however, we are adding a number of other small features that further improve the interop experience.

Variance

It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance” and common BCL types are updated to take advantage of that.

Most of these features are similar in spirit to what was shown at the Lang.NET symposium, but with a few details worked out.

The Dynamic features are going to be great when dealing with objects from DLR languages or COM. Named parameters sounds kind-of nice, but not world-changing. Variance support when assigning collections is going to be very handy, so is probably my favourite of the four feature groups.

Read more at the C# Futures site.

Kirk

posted on Tuesday, October 28, 2008 2:41:46 PM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

As promised, here's more information on what's happening on Guy Fawkes day in Wellington:

Fireworks

We've just heard some of the cool stuff coming out of the Professional Developers Conference, and we've got our spies deployed in the audience -- so come along to our special user group event next Wednesday in Wellington to hear all about it!

Print out the above PDF, or forward this post along to all of your workmates. It's going to be a great 2 hour session, and we'll have stuff to give away to a few lucky attendees.

At 7:30pm we're welcoming families and partners along for pizza and subway -- so if you're planning on catching the fireworks, this is a great way to have some food before the explosions begin.

RSVP to kirkj@paradise.net.nz to reserve your (and your families) place.

Kirk

posted on Tuesday, October 28, 2008 10:37:10 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

Well it was like the calm before the storm this weekend, with just one early blog post with leaked information to whet my appetite.

Now we're hearing all about Azure:

I'm looking forward to hearing about Azure. As JB said, we knew something was coming, now it's good to find out what it is :)

Kirk

posted on Tuesday, October 28, 2008 10:15:36 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

James Newton-King is busting out a beta version of JSON.NET 3.5, and has made some pretty good improvements of up to 400% when serializing / deserialising:

image

(Second set of columns are the improved Json.NET)

Well done James!

Kirk

posted on Tuesday, October 28, 2008 10:03:01 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [1]
 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:45:38 AM (New Zealand Standard Time, UTC+12:00)  #    Comments [0]

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]