Sunday, May 02, 2010

Code snippets are a great time saver and they are pretty simple to create.  Any time you find yourself typing the same thing over and over again, you may want to consider creating your own code snippet to make life easier.

Here’s an example… I was recently working on a large refactor of some error handling code for a user interface.  Basically, I went from form to form, refactoring the way the error handling was implemented and then test it.  How did I test it?  By throwing exceptions in my code.  Doing so is pretty easy, just find the portion of code that needs to be tested and type “throw new Exception(“This is a test”);”  Plus, for good measure and safety I’d add this above it: “//TODO – Don’t forget remove this test code”

//TODO:  Don't forget to remove this test code:
throw new Exception("This is a test");

Sure, it is easy enough to type but it got old pretty quick and I decided to create a simple snippet.  Once I did, all I needed to type was “tne” (it stands for “Throw New Exception) and hit “tab” twice (hitting “Tab” twice tells Visual Studio to use the code snippet based on what you just typed).  Sounds cool huh?  Ok so here is how you create a simple code snippet…

Snippets are stored in XML files on your pc.  To create a new one, it is easiest to just start with an existing snippet and modify the xml to meet your needs.  Here is an example of the one I am using:

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Throw new Exception</Title>
      <Shortcut>tne</Shortcut>
      <Description>This will generate code to throw a new Exception</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Code Language="csharp">
        <![CDATA[    //TODO: Remove this test code:
        throw new Exception("An Exception has been thrown"); $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

If you want to use your own snippet, just change the Title, Shortcut, Description and Author elements.  And of course, you need to put your snippet inside of the CDATA area of the the Code Element.

Next, you just need to save this file in a place where Visual Studio will pick it up.  To tell VS2008 where to look for it, go to Tools > Code Snippets Manager.  Make sure you select the correct language in the drop down, otherwise Visual Studio can’t connect your snippet to the language you meant it for.  You’ll also notice the existing folders for snippets.  That may give you an idea of where you should store your own snippets ;).

You can also write more complex snippets that allows you to use the snippet and then type in values that get used within the snippet.  For instance, I do a lot of work with Silverlight and for databinding my public variables must implement INotifyPropertyChanged.  Instead of manually typing a property that does so, plus a backing variable, I use a snippet with the shortcut “npc”.  In the sample below, you will see the words TYPE, PROPERTY and FIELD highlighted in Green.  Those are placeholders and when I utilize the code snippet, VS will prompt me to replace those values.  So if I want to create a public property and backing variable for a string FirstName, I just type the following:  “npc” TAB TAB “string” TAB “FirstName” TAB “_firstName” (but don’t type the quotes!).  It may seem weird at first but makes coding much easier.

private TYPE FIELD; 

image

Here is the XML for my “NotifyPropertyChanged” snippet:

<?xml version="1.0" encoding="utf-8" ?>

<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Notify Property Changed Property</Title>
      <Shortcut>npc</Shortcut>
      <Description>Code snippet for creating a property with a backing variable that calls NotifyPropertyChanged</Description>
      <Author>Andy Schwam</Author>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>type</ID>
          <ToolTip>The Type for the Property</ToolTip>
          <Default>TYPE</Default>
        </Literal>
    <Literal>
          <ID>fieldname</ID>
          <ToolTip>The Type for the field</ToolTip>
          <Default>FIELD</Default>
        </Literal>
    <Literal>
          <ID>propertyname</ID>
          <ToolTip>Parameter name</ToolTip>
          <Default>PROPERTY</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
    public $type$ $propertyname$ {
    get { return $fieldname$; } 
    set 
    { 
    if ($fieldname$ != value) 
    { $fieldname$ = value; 
    NotifyPropertyChanged("$propertyname$");
    }
    }
    }
    private $type$ $fieldname$; 
    $end$]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

Unfortunately, there isn’t a Code Snippet Editor included in VS.  There is some kind of plug-in available for creating VB snippets but I’ve never used it.  I’m sure you can find it with your favorite search engine.  Still it is pretty easy to write these yourself.

Sunday, May 02, 2010 3:36:46 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, April 17, 2010

I’ve been working on continuous integration and automated builds/deployment lately.  I put together a MSBuild script that does a whole bunch of typical stuff including getting code from my repository, compiling, and running tests.  I also want to create a Tag in my Subversion repository so I know which code was deployed.  That wasn’t too hard to do either.  The tricky part was that I want my build to fail if I try to make a Tag that already exists!

I fumbled around with this for a while trying a wide variety of ideas.  In the end, it turned out to be pretty simple.  There may be better ways to accomplish this, but here is how I am doing it…

I’m using the SvnClient task (it’s part of the MSBuild.Community.Tasks download) and executing a command:  “ls $(SvnRepository)/tags/$(SvnTagName)”.  Of course, my MSBuild script already has the variables $(SvnRepository) which is the path to my repository and $(SvnTagName) which is the name of the Tag I hope to create.  You may have to tweak this stuff depending on the layout of your SVN repository.  The command “ls” will actually list the contents of my Tag.  Since I know my tag just has a few folders in it (it isn’t a recursive task), it isn’t too harmful if it succeeds.  If the Tag does not exist in my repository, the command actually fails.  Oddly, I actually want this task to fail!  Yes, in my case, I am hoping the task does not find the Tag with the specified name.  When the task is executed, it returns an ExitCode which is 0 for success or 1 for failure.  Next I just check the returned code and if it is successful I generate an error.  Sure this feels a bit odd.  I don’t love using this kind of logic, hoping for an error to occur. I’d much rather have some subversion command I could execute to see if the Tag exists but I couldn’t find anything like that.  Here is the actual xml from my Build file to check for the Tag:

<Target Name="CheckSvn">
  <Message Text="*** Checking to see if the tag already exists"/>
  <!-- this task will look up the tag supplied.  
    If it exists it will return a code of 0 
    Technically this is a success but for this instance, 
    it is a failure because we don't want to find it! -->
  <SvnClient Command="ls $(SvnRepository)/tags/$(SvnTagName)" 
             Username="xxx" password="xxx" ContinueOnError="true">
    <Output TaskParameter="ExitCode" PropertyName="CommandResult"/>
  </SvnClient>
  <Message Text="*** ExitCode = $(CommandResult)"/>
  <Error Condition="$(CommandResult)=='0'" Text="This Tag already exists!"/>
  <Message Text="*** Finished Checking to see if the tag already exists"/>
</Target>

Working with MSBuild is becoming a love/hate relationship for me.  I really love the power of what you can do to automate tasks.  But it can be a real pain to write, test, and debug these scripts.  I hope my sharing this code will make your life a little easier.

Saturday, April 17, 2010 1:49:50 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [3]  |  Trackback
 Thursday, April 15, 2010

You’ve heard about LINQ to SQL, LINQ to Objects and LINQ to XML right?  Well how about LINQ to String?  Well technically there is no such thing.  But you use LINQ on a string!  You may not have realized this before but it works.  LINQ can be used to query IEnumerable<T> and a string is actually a collection of chars.  So yup, you can actually query the string itself.  Here are a few simple examples but you certainly do a lot more than this…

public void LinqToStringSample()
{
    string letters = "keuiwierqewefqwfwefcjlkjkl";

    //count all 'e'
    int count = letters.Count(l => l == 'e');

    //order
    var ordered = letters.OrderBy(l => l);
    
}
 | 
Thursday, April 15, 2010 8:53:45 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback

I recently gave an “Introduction To LINQ” presentation at the Microsoft event:  Data Access Firestarter.  That session was recorded and posted on MSDN’s Channel 9.  Here is the link so you can check it out.  If you want the content, you can get it from this post.  I’m really excited to be on Channel 9, it is such a great source of content!

I also gave the same talk at Philly.Net Code Camp this past Saturday.  That talk was also recorded and is available via Live Meeting replay.  I think it will be on Channel 9 too.  Both sessions went pretty well. 

I do feel the need to make a correction though!  In the presentation at Code Camp I answered a question incorrectly.  It was a subtle error, but one just the same.  The question was “Can you use LINQ to SQL against other databases?”.  I’m not really sure why I gave the wrong answer because I have been doing this stuff for a long time and I really do know the right answer.  My incorrect answer was that you can do LINQ to SQL as long as you have a provider to the other database.  This is completely wrong!  You can certainly do LINQ to a wide variety of data sources, including Oracle, but that isn’t “LINQ to SQL”.  LINQ to SQL is specifically an implementation of LINQ to a SQL Server Database.  I hope that makes sense.

Thursday, April 15, 2010 8:22:16 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, March 27, 2010

I remember a conversation with a client about certain coding practices.  We were discussing things like code reviews, paired programming and similar concepts.  These were concepts that we both believed in but yet at certain times in the project we scrapped these ideas.  Why?  Why else, we were behind schedule and we didn’t have time.  Thinking about it, I said to him that this was precisely the time we should NOT ignore these practices.  Why is this?  Because when you are close to a deadline and running out of time, you don’t have time for mistakes.  And paired programming is a great way to minimize mistakes.  I’m not trying to say here that Pairing is the only way to prevent issues.  The point is that we shouldn’t rush our work when we have limited time.  I know that while we were in our frantic pace to the finish we made some mistakes.  We then had to fix those mistakes before we released anyway.  If we had taken our time a bit more, we would have saved resources in the long run because it is faster to write better code than fix bugs. 

I thought of this conversation today.  I was listening to Studio 360 on NPR and heard a great quote.  The show had guest host Alec Baldwin interviewing actress Laura Linney. Laura Linney was recalling a quote by some other woman, I don’t recall her name, who was a Broadway director, if I recall correctly.  In any case, this woman used a phrase all the time that really expresses my thoughts from above.  She used to say “Ok people, we are almost out of time, we better slow down”.  Isn’t that perfect?  I’m not positive that I’m quoting it correctly, word for word, but I am close enough and the point is clear.

I hope to remember this quote and repeat it a lot.

Saturday, March 27, 2010 12:58:20 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Friday, March 26, 2010

Tomorrow I’m presenting “Introduction to LINQ” at the Microsoft Event: Data Access Firestarter.  I’m trying to be proactive and actually post my samples and slides in advance!  This way, they’ll be there if anyone wants to take a look.  I’ll be doing the same demo at Philly.Net Code Camp on April 10 too.

Click here to download the samples: Demo and Slides 

If you attended the Firestarter, I hope you enjoyed my talk.  If not, I hope to see you at Code Camp.  And if you just happened along and are interested in learning LINQ, enjoy the samples.  Email me if you have any questions.

Friday, March 26, 2010 7:08:01 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Tuesday, March 16, 2010

I’m pretty excited about two upcoming events coming to our community and I have an active role in both of them. 

First, I’ll be presenting at the .Net Data Access Firestarter on March 17, 2010.  This event, hosted at the Microsoft Office in Malvern, PA covers a variety of .Net data access strategies including LINQ to SQL, WCF Data Services and OData, Entity Framework, and even Azure Data Storage.  It’s a pretty good variety of information.  I’ll be doing one of the earliest sessions on the day, my topic is “Introduction To LINQ”.  I’m excited about this because LINQ is such an important part of the .Net Framework now.  While it isn’t really a data access technology, most of the data access technologies use LINQ!  It should be a lot of fun and I am honored to be a part of the event.  Also, if you can’t make it out to the event, you can watch it online too!

Here is a link to more information.

Second is of course, Philly.Net Code Camp.  Our next Code Camp is April 10, 2010.  Once again we are back at DeVry University.  These Code Camps just continue to get better and better.  Once again, we 60 sessions in a variety of technologies.  In addition, we are broadcasting a portion of the content via Live Meeting and they’ll also be available for download later.  That alone makes this an exciting event.  This year, we’ve also invited some folks from Alex’s Lemonade Stand to come by.  At the end of the day, we’ll be presenting them with a donation to their worthwhile organization.  How are we raising the money?  This year we are offering two kinds of tickets to Code Camp.  The first is the standard, free ticket.  Anyone is welcome to come to Code Camp for free and enjoy the day (and breakfast and lunch are included as always).  But we have added a Booster ticket this year for $25.  If attendees choose to donate this small amount, they get a few benefits:

  • $5 of the each Booster ticket goes to Alex’s Lemonade Stand
  • Boosters are included in some premium raffles
  • Boosters are included in the post Code Camp party
  • Booster money will help sustain Philly.Net throughout the year.
  • Other benefits are included as well.

This is sort of an experiment.  The leadership, of which I am a member, doesn’t know how this will turn out.  It seems to me that $25 is a small price to pay for a ton of content at Code Camp, not to mention the fact that we provide breakfast and lunch.  And we hope that people won’t mind donating to our efforts, it takes a lot of money to run the organization and all of the events year round.  Plus, we are donating a portion to charity.  On the other hand, I always liked these events being free.  People donate their time so that others can come and learn for free.  It’s a great concept!  But times are changing and we need money to run our organization year round.

In any case, whether you choose to donate or attend for free, I hope to see you at Code Camp.

Tuesday, March 16, 2010 10:21:58 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Saturday, September 12, 2009

With a day off and nothing to do, I was excited to migrate my home PC to Windows 7.  I’ve used the beta and RC for a while on my laptop but my home PC is a different story.  This is my “main” computer in the house and I need it for lots of stuff. I wasn’t worried about Windows 7 but I also decided to go 64 bit!  Plus I have a lot of software to install and licenses to find, so that always makes me nervous.  All (hopefully) of my data is on different drives than my OS so that makes life easy.

Anyway, I installed Windows 7 64 bit with no issues, so I thought.  Afterwards I even started installing additional software.  It wasn’t until I rebooted my PC without the Windows 7 install DVD in the drive that I realized I had a problem!  On boot up, I got the following doosy of an error:

Disk Boot Failure, Insert System Disk and Press Enter

That is one of those errors that really makes you pause.  It really makes you feel like you are in big trouble.  Figuring maybe there was some piece of installation that wasn’t yet complete, I put the Windows 7 install DVD back in and it booted just fine!  But of course, I still couldn’t boot without the DVD.  This had me bewildered for a while, I tried various combinations of rebooting, and then searched the internet for answers.  All the while, this seemed strangely familiar – I’ve had this happen to me before, but I can’t remember when and why (don’t you hate that?).  I did a reinstallation of Windows 7 but that didn’t fix anything.  I was reading articles about bootmgr and active drives and all kinds of stuff.  From my research, I started to figure out that (I may explain this wrong) when you install Windows, some information about how to boot up goes on your hard drive but it isn’t necessarily the same hard drive (or partition) that Windows gets installed on.  I mentioned early that I had a separate data drive.  As a matter of fact, I have 4 hard drives in my PC.  So now I had an idea of the problem (just an idea at this point) – my PC was probably reading hard drives in the wrong order and couldn’t figure out how to boot up.  I wasn’t sure how to fix it.  Then the answer came to me, it was really quite simple.  Here is how to solve the problem:

When installing Windows 7 (or any Windows version, I’d guess), disconnect all additional hard drives except for the C drive!  Then you know all of the right information goes on the drive that you want to boot off of.

I did just that.  I left just the one HDD connected in my pc and reinstalled Windows 7.  I’m sure there are exceptions to this and reasons why you shouldn’t do this.  I’m not an IT Pro, just a software developer who’s done installations more than a few times.  But this worked for me!  After installation, I just hooked up my additional drives and everything worked perfectly! 

I hope this helps and good luck.  By the way, if you have additional questions related to installation problems, I am probably NOT the guy to ask.  I just got lucky on this one.

 

Saturday, September 12, 2009 10:08:35 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [1]  |  Trackback
 Saturday, June 13, 2009

It's been a busy few months since my last post.  Ben's building his vocabulary and knows a bunch of words.  He's also working on his "animal sounds".  He knows that a cow says "moo" and a bunch of others.  If you ask him what a pig says, he makes a sort of coughing sound.  I figured out he is saying the end of the word "oinK".  Ben was a little late to the game for walking. But he really got the hang of it and was very proud to be walking around.  But then he had a bit of an accident and broke his leg!  It sounds pretty crazy but the doctor says it is really quite common.  The specific break is actually called a "toddler's fracture"  To be clear, we aren't talking about one of those nasty "dangling limb" breaks.  Just a crack.  It still sucks for a 15 month old kid.  So poor Benny has a cast on his leg and that put an end to walking for a while. 

It's actually quite interesting to see Ben respond to this situation.  When the accident happened he was really unhappy and scared.  I don't think he was in a terrible amount of pain if he kept still.  But he was really scared, he knew something was not right in a serious way.  It took a while in the hospital and he did not like it when they splinted and wrapped his leg (the cast would get put on the next day at the Orthopedist's office).  However, as soon as his leg was immobilized he was out of pain and started turning back to normal, even playing a bit.  I expected him to play with the splint or try and take it off.  But he just ignored it.  I think somehow he actually understood that it was helping him.  Even when the cast got put on, he never pulled at it or anything.  He just accepted the situation - "now I have a cast on my leg, what's next?" He was back to crawling full time but didn't seem to care about the broken leg at all.  He eventually started to stand on it (leaning  on furniture) and now even takes as many as 8-10 steps on it!  He's not really supposed to but it isn't so easy to keep him off it.  The worst part of the whole thing is 6 weeks with no baths (not real ones, anyway), sand, swimming, dirt etc.  Anyway, in 2 weeks the cast is coming off.  My expectation is he'll quickly adjust back, start walking and that will be the end of that story.

We've also joined the Philadelphia Zoo.  This is a great idea for any family and we are really liking it, with 2 trips in so far this summer.  Benny loves it and points and yells at the animals.  We've also seen a lot of family lately including a visit to the park with Grandma and Longstreet Farm with his cousins. 

The last new thing is that we've been taking Ben for bike rides (he hangs out in a trailer), it's fun for the whole family.  Wow, so much to talk about, I really need to post these things more often!  Here's a bunch of photos:

  • Craft Time for Ben, Mommy and cousin Fiona!

DSC04082 DSC04084

  • With Grandma on Passover.  A classic "how big is Benny?" photo!

 DSC04093

 DSC04104 DSC04110 DSC04120 DSC04121 DSC04137

  • Here's a shot of Ben with his cast.

DSC04142

  • Benny's catching a free ride with Uncle Dennis, and posing with cousins Kaycie, Allie, Sami and Jake at Longstreet Farm.  Also Benny is his bike trailer - and looking cool too!

 DSC04146 DSC04154 DSC04167

 | 
Saturday, June 13, 2009 2:01:10 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [0]  |  Trackback
 Monday, May 04, 2009

Lot's of bloggers have written a post just like this.  It's almost a staple for the tech-blogger.  I've avoided it until now because there are lots of posts like it out there already.  Wow, really makes you want to read on, huh?  Well since I am in the process of installing Windows 7 RC on my laptop, I couldn't help but notice my list of favorite utility programs. So here they are in no particular order.  Check em out!

Disclaimer/Note - I am not affiliated with any of these products in any way, I just like them. 

Virtual Clone Drive:  This tool is great because it allows you to take an ISO image and treat it like it is a drive on your computer.  So if you download an install CD/DVD image, you don't need to burn it onto a disk in order to install it.  Just use Virtual Clone Drive and you can click on it like any other drive on your computer and browse or run files.  Very Cool!  Plus, they've got one of the coolest logos around.

Paint.Net:  I'm a developer, not a professional designer.  Paint.Net is similar to programs like PhotoShop but it is free.  It certainly doesn't have as many features as PhotoShop but most of the time, for me, it gets the job done.  I've been using this tool a lot for years!  And it is FREE! If you think you need photoshop, but just for casual use, check out Paint.Net.

Visual Color Picker:  This is a great tool to use if you need to figure out what color something is on your computer.  Just open a web page, application, or whatever you want to investigate and use Visual Color Picker to "pick" the color with it's dropper tool.  Piece of cake.  Then just copy the color name or code into the application you are working on and you are all set.  Off all the tools on my list, this one seems to be the "best kept secret".  You should really try this out, it is awesome.

BurnCDCC:  I just learned about this one from an old post Scott Hanselman's blog.  (If I ever need a cool tool, I search his blog!)  Burn CDCC lets you put an ISO image on DVD as a true image, not just data.  This is important when you download a cd/dvd and need it to actually run off of disk (such as to install some software).

Zoomit:  This is a great little app for when you are doing presentations.  It allows you to easily zoom in on a portion of your screen, and scribble on it too!  This one is written by Mark Russinovich but available for free from Microsoft.

Lastly, an Honorable Mention...

Windows Snipping Tool:  Honorable mention, because it is already included on most computers with Vista or Windows 7.  If you need to highlight and clip just a portion of a screen shot and paste it somewhere (like into a Word doc or a blog post) Snipping Tool makes it easy.  Like some of the other tools listed above, there are some great products available out there for purchase.  In this case, Snipping Tool is similar to SnagIt, which is a cooler, better product.  And actually, SnagIt isn't priced too highly.  But Snipping Tool makes for a decent, free version.  Oddly, up until a few weeks ago, I didn't even know I had it!  And In 1 week, two different people told me about it.  Turns out, in an effort to enhance the performance of my computer while using the processor/memory hog Vista, I shut down a lot of things, including the Tablet PC Features in Vista.  For some reason, Snipping Tool is included in that package.  So for all this time, I didn't have access to a really neat little feature.  Oh well.  Now I've got it, and I use it all the time!

 

While I'm at it, I may as well list the software getting installed on my laptop too.

Things I can't do without:

Firefox (with Firebug, WaveToolbar, and YSlow addons), Live Writer (for composing blog posts like this one!), Digsby (for Instant Messaging), Twirl (twitter client), Live Mesh

And then:

Office 2007 and Outlook, SQL Server, Visual Studio 2008, ReSharper (my favorite VS Add on!), Bit Defender (Anti Virus), Tortoise SVN (source control) and more...

Something tells me that after I publish this, I'll think of a bunch of stuff that I left off the list

 

Technorati Tags: ,
Monday, May 04, 2009 9:35:41 PM (Eastern Standard Time, UTC-05:00)  #    Disclaimer  |  Comments [1]  |  Trackback