navigation
 Tuesday, February 23, 2010

I don’t like the diff/merge tool that comes with TFS. At all. It isn’t just that it’s feature-poor; it also isn’t good at the one thing it’s supposed to do. I’ve had a quite a few merge operations go horribly wrong, resulting in data loss and syntactically incorrect merge results. Today I found two excellent articles that described how to replace the default TFS diff/merge with an alternative one:

TFS: Using Alternative Diff/Merge Tools

diff/merge configuration in Team Foundation - common Command and Argument values

There are a lot of alternatives out there. I chose to use KDiff3 because it is both free and popular. Most of the other alternatives are either one (Beyond Compare is very popular but not free) or the other (SourceGear DiffMerge is free and looks very good but is not as well-known).

When choosing an alternative, make sure that you choose one that supports 3-way merges. They are much more accurate and reliable than 2-way merges. Of the options listed in the articles above, that means to rule out WinMerge and Beyond Compare prior to version 3.

posted on February 23, 2010  #    by Adam Anderson  Comments [1]
 Friday, December 18, 2009
Getting files from an outside source can cause Windows to Block project files. .NET 4 has changed the security settings so some examples downloaded from the internet, for example, might not work without unblocking these files.
posted on December 18, 2009  #    by Scott Frolich  Comments [0]
 Thursday, December 17, 2009

If you, like me, did not install C++, it is not there… see this article. Installing C++ fixed the problem. The C++ team must be getting desperate!

posted on December 17, 2009  #    by John Waters  Comments [0]
 Wednesday, September 16, 2009
Find out how to save time and space (not like Dr Who) by using Differencing Disks to configure variations of your core install in Virtual Machines under Hyper V.
posted on September 16, 2009  #    by John Waters  Comments [1]
 Monday, August 31, 2009

We are proud to announce that Falafel is a platinum sponsor of this year’s Silicon Valley Code Camp, along with Microsoft, LinkedIn, Oracle and Foothill College, and has several speakers registered for the event.

Lino Tadros will cover the following topics:

  • Dependency Properties in WPF & Silverlight
  • Silverlight 3 ins & outs
  • IPhone Development in C# with MonoTouch

John Waters will talk about:

  • Partially Connected Silverlight Applications
  • Parallel Programming with .NET

Steve Trefethen is speaking on:

  • Extending CruiseControl.NET
  • Tour of AutomatedQA's TestComplete 7

And Stephen Dempsey has a talk on:

  • Befriending Lambda Expressions

There is a long list of other renowned speakers, come see us and get up to speed on the latest trends and technology! Also, we are hiring, to stop by us after our talks if you are interested in a Senior ASP.NET or Silverlight Engineer position.

Cheers

The Falafel Team

posted on August 31, 2009  #    by Lino Tadros  Comments [1]
 Tuesday, June 09, 2009
If you are using conditional directives in your C# code, you know that you can't set a breakpoint on any code within the directives using Visual Studio. Thankfully, you can add a breakpoint programmatically:

#if MYSYMBOL
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
DoSomethingForMySymbol();
#else
#if DEBUG
System.Diagnostics.Debugger.Break();
#endif
DoSomethingForEverythingElse();
#endif

System.Diagnostics.Debugger.Break() can only be called in Debug mode, so make sure you wrap it in a #if DEBUG check first. Good luck!


posted on June 9, 2009  #    by Brad Divine  Comments [0]
 Friday, June 05, 2009
Here's a handy little tip for those of you using DataGrids or something similar, for instance, the Telerik RadGrid control. If you want to allow the user to double-click on a row to do something (edit the row, for example), implement the CellDoubleClick event handler for the grid and put your code in there. If you do this, then double-clicks in the column header will also fire the event; this can happen if a user clicks the header too quickly while trying to sort. To prevent this, add code to check e.RowIndex. If the user double-clicked on a header, e.RowIndex will = -1.
posted on June 5, 2009  #    by Brad Divine  Comments [0]
 Friday, May 29, 2009
If you're like me, you sometimes use AJAX controls in your web page. And, if you're like me, you find that when they fail to behave as expected, you as the user are not notified as to the reason. Instead, the page will just stare back at you blankly: no spinning globe, no twirling fox to indicate that it is processing your request. Of course, what's really happened is that your AJAX request caused an unhandled exception on the server and the request was canceled. If you're like me (and if you've read this far I am forced to conclude we must be twins) you'd like some visibility into that unhandled exception.

There is a quick and easy solution! Simply add the following to your ASPX code-behind and during your debugging session Visual Studio will report the exception being thrown, complete with the exception message and stack trace. If you'd like to report the exception to the user, you would wrap the inner call in a try/catch block and update your UI (or Logging) accordingly.

Good luck!

C#
protected override void RaisePostBackEvent(IPostBackEventHandler source, String eventArgument)
{
    base.RaisePostBackEvent(source, eventArgument);
}

VB.NET
Protected Overrides Sub RaisePostBackEvent(ByVal source As IPostBackEventHandler, ByVal eventArgument As String)
    MyBase.RaisePostBackEvent(source, eventArgument)
End Sub

posted on May 29, 2009  #    by Brad Divine  Comments [0]
 Saturday, May 02, 2009
How to delete TortoiseSVN Username/password cache for specific repositories in three easy steps!
posted on May 2, 2009  #    by Brad Divine  Comments [0]
 Tuesday, March 03, 2009
Today was the second day at the MVP Summit in Redmond and it was a lot of fun.  This is my 5th MVP summit and it is so nice to see all the faces that I don't get to see except at the MVP summit from all over the world.  We spent several hours with Anders Hejlsberg discussing futuristic features to the C# language and the evolving of this powerful powerful language inside of the Visual Studio IDE for the next few years.  Met so many friends that I usually see in Europe and Australia while speaking at conferences like Miguel Castro, Richard Campbell, Steve Forte, Todd Anglin, Neil Ford, Remi Caron and many others... It was so nice for us not to be speaking this time but actually attendees :)
These events are usually for us like taking kids to Disneyland :)
This time is so special though because it is the first time I took my wife with me to Microsoft to see what I do and meet these friends.  She was shocked on how childish we all are when we get together :)
    mvp
posted on March 3, 2009  #    by Lino Tadros  Comments [0]
 Saturday, January 10, 2009
After installing a new version of VS.NET there are three environment settings I always change from the default settings to make things a little better and save me time using VS.NET 2008.
posted on January 10, 2009  #    by Gary Campbell  Comments [1]
 Tuesday, January 06, 2009
A recent project has had me spending a lot of time working with Telerik controls for WinForms, and sometimes learning some lesser-known tricks in the process. Whether by research on Telerik's support site, contact with the fine people at Telerik themselves, or just plain old experimentation, it's been fun to learn these little tidbits that can help turn a control, like the RadTabStrip from just functionally acceptable into something much more.
posted on January 6, 2009  #    by Rachel Hagerman  Comments [1]
 Wednesday, December 17, 2008
Have you ever been in the middle of large source file and you need to add a "DataTable" or something else, but you don't have the appropriate "using" directive at the top of your file? In VS.NET it is very simple to add the "using" directive with a few clicks saving us developers some valuable keystrokes.
posted on December 17, 2008  #    by Gary Campbell  Comments [1]
 Wednesday, November 26, 2008
There are times when you may want to create your own custom build configuration for a project in Visual Studio, such as to define compiler symbols or to set build options for different projects within your solution. Fortunately, Visual studio makes it very simple.
posted on November 26, 2008  #    by Rachel Hagerman  Comments [1]
 Tuesday, November 04, 2008
Use these simple settings to save time on Windows Forms with Accept and Cancel functionality.
posted on November 4, 2008  #    by Rachel Hagerman  Comments [0]
 Wednesday, August 27, 2008
I just learned some very interesting things about WPF, Splash screens and Visual Studio 2008 SP1...
posted on August 27, 2008  #    by John Waters  Comments [1]
 Thursday, July 17, 2008
For those of use whose first language is something other than XAML, the default control template styles generated in Expression Blend are pretty intimidating. There has got to be a simpler place to start. Well, there is! It's a handy little download you can get straight from your Visual Studio help called ControlTemplateExamples.
posted on July 17, 2008  #    by Rachel Hagerman  Comments [2]
 Monday, May 26, 2008
Read about a cool hack in Visual Studio 2008 SP1 that allows the designer to fall back on a hardcoded master page if it doesn't manage to locate the correct one.
posted on May 26, 2008  #    by John Waters  Comments [0]
 Friday, April 25, 2008
This week I needed a particular VisualStudio 2005 project template called "ASP.NET AJAX-enabled Web site" and I could not for the life of me get it to show up. Here are the steps I used to fix it.
posted on April 25, 2008  #    by Aaron Rhodes  Comments [1]
 Monday, April 21, 2008
You can't run MSI or CAB files "As Administrator" directly from the explorer in Vista, but there's a workaround.
posted on April 21, 2008  #    by Noel Rice  Comments [0]
 Tuesday, April 15, 2008
After a Vista upgrade none of my .NET 3.5 web applications would run! Visual Studio gives a "Child nodes not allowed" error for the web.config file, but there is a simple solution - once you find it.
posted on April 15, 2008  #    by Rachel Hagerman  Comments [3]
 Wednesday, April 09, 2008
How do you build a VisualStudio solution file without VisualStudio installed? Answer: MSBuild, but there is a gotchya.
posted on April 9, 2008  #    by Aaron Rhodes  Comments [2]
 Monday, April 07, 2008
My name is Angelo Martinez and I am new here at Falafel Software. I have known Lino Tadros for a long time and I can assure you that this is a great place to be! My hope is to start blogging on new ideas/tools/technologies that I discover along the way. With that in mind... I had a requirement to build a generic MRU (Most Recently Used) class based on a Key/Value pair. Among other things, the class contains methods such as Add(), Find() and a Count property that reports the number of items currently in the list. It would be nice to be able to build a set of unit tests to verify the functionality of the new class. For this, Visual Studio 2008 comes to the rescue!
posted on April 7, 2008  #    by Angelo Martinez  Comments [0]
 Saturday, January 19, 2008
One of the things I have come to love about Linq is how you can focus more on declarative programming: focusing on what you want to accomplish rather than how...
posted on January 19, 2008  #    by John Waters  Comments [1]
 Tuesday, November 20, 2007

Falafel is partnering with Microsoft to offer this free half day seminar at the beautiful Saint Claire hotel in downtown San Jose, CA to celebrate the release of Visual Studio 2008, LINQ, WPF, WCF, WF and other exciting technologies.

ActiveFocus Hosting

Please join us on December 10th from 9:00 AM to 1:00 PM
Register on the Microsoft event site ASAP as space is limited.

Charlie Calvert, the C# Community Project Manager will be there to talk about LINQ and Lino Tadros will present the usefulness of the new technologies.
Hope to see you there!
 |  |  |  |  |  |  |  |  |  | 
posted on November 20, 2007  #    by Lino Tadros  Comments [0]
 Wednesday, September 26, 2007

Wow!  I was told so many times that Visual Studio 2008 will ship in 2007, well it does not sound like that is a possibility anymore.

Microsoft released a new date, February 27th 20008 to release Windows Server 2008, Visual Studio 2008 and SQL Server 2008

2008 Global Launch Wave
963
Days
Windows Server 2008 • Microsoft Visual Studio 2008 • Microsoft SQL Server 2008
posted on September 26, 2007  #    by Lino Tadros  Comments [0]
 Thursday, August 16, 2007

I have spent the last few days trying to install Visual Studio 2008 a.k.a. Orcas Beta 2. The download page is here.

The basic idea is that you download a virtual machine that has both the OS (Windows Server 2003) and Orcas preloaded. First, you download a base file called VSCTPBase.exe, which you unpack to get a virtual hard drive. Then, you download 7 RAR files. The first one is self extracting and extracts itself and the rest of them, and then builds a differencing disk which is added to the initial virtual hard drive to create the final virtual drive. At least, that was the theory!

As the whole setup uses a lot of space, and I am almost out of space (as usual) on my laptop, I borrowed a 300 Gb external disk from work to put the VPC on. I downloaded the files mentioned above onto that disk. I then unpacked the base image, and started unpacking the 7 RARS. Well - somewhere in the middle of the third one, I get an error message saying

"Write error in the file OrcasBeta2_VSTS.vhd. Probably the disk is full."

Not! I had about 250 Gb free on the disk. OrcasBeta2_VSTS.vhd is the differencing disk that was being merged from the RARS. So, I scratched my head, googled, couldn't find anyone else with the same problem, tried downloading the file again, rebooted, tried again, sacrificed a goat. No luck.

So I tried searching for the message above as "Write error in the file" and "Probably the disk is full." Now I got lots of hits, this seems to happen a lot to people. Finally, I stumbled across a post saying that there is a file size limit on FAT32 volumes, somewhere around 4Gb.

FAT32? I had forgotten about that evil stuff, along with win.ini, config.sys, thunking, himem, edlin, floppy disks and gorilla.bas! And sure enough, the 300Gb external drive was formatted as FAT32. Duh!

So, a quick command brought my external I: drive out of the bronze age:

convert I:/FS:NTFS 

And now the extraction worked.

Can you believe that? Poor Microsoft trying to get it's developers to beta test their latest and greatest development tools, and you run into FAT32! Talk about a blast from the past. Tonight I will dream nightmares about 640K memory limits and 16 bit operating systems... and the turbo button.

posted on August 16, 2007  #    by John Waters  Comments [1]
 Tuesday, July 24, 2007

While having some fun with the Visual Studio SDK I ran across a great example of a Navigation window by Gaston Milano.  It's a great sample to start with if you would like to dive into Visual Studio Package development.  One item of note that I found while using the navigation window on a very large project is that Visual Studio 2005 kept crashing everytime the window would be brought up.  I noticed that before VS crashed it had a difficult time drawing things. I immediately thought of a GDI leak.  I opened up Task Manager and checked the GDI objects and sure enough every time I openned the window the GDI object count would skyrocket upwards, never to return to a sane GDI count again.  VS crashed after reaching a count of about 10,000 GDI objects and I don't blame it for doing that either :) 

The offending routine, the getter for the HierarchyItem::Icon property in HierarchyItem.cs, calls a method NativeMethods.ImageList_GetIcon() which merely vectors off into the win32 version of ImageList_GetIcon().  Looking at the MSDN documentation for this routine you'll notice that the remarks at the end state

"It is the responsibility of the calling application to destroy the icon returned from this function using the DestroyIcon function"

Looking at the code you'll notice that DestroyIcon is never called on the temporary HICON returned from this call so every time this routine is called I noted 2 HICONs being leaked.  And on my large project, this really started adding up.

The fix?

Change the following code in HierarchyItem.cs:

      int handleIcon = NativeMethods.ImageList_GetIcon((int)imageList, (int)index, hbmMask);
      try {
          this.icon = (Icon)Icon.FromHandle((IntPtr)handleIcon).Clone();
      }
      catch (ArgumentException) {
      }
To:
int handleIcon = NativeMethods.ImageList_GetIcon((int)imageList, (int)index, hbmMask);
try {
     this.icon = (Icon)Icon.FromHandle((IntPtr)handleIcon).Clone();
     NativeMethods.DestroyIcon(handleIcon); // <== added to destroy the temp HICON
    } catch (ArgumentException) {
    }

And add a reference to DestroyIcon in the NativeMethods class like so:

        [DllImport("USER32")]
        public static extern int DestroyIcon(int HICON);
Hope that helps any of you running into similar problems.
posted on July 24, 2007  #    by Adam Markowitz  Comments [1]
 Friday, July 13, 2007

Like many developers, I have both VS2003 and VS2005 installed on my machine. I had also placed a shortcut to the Visual Studio  command prompt in my programs menu. A couple of days ago, I had the opportunity to write my first Windows service application. I got everything set the way I wanted, and it was time to install. So, I opened up the VS command prompt, and typed in the magic chant "installutil servicename.exe". And fairly promptly got the error "Exception occurred while initializing the installation: System.BadImageFormatException: the format of the file 'servicename.exe' is invalid...".

If you're encountering the same error, make sure that you're using the correct installer. For me, it turned out that I was using the VS2003 installer. As soon as I switched to the installer from VS2005 (using the correct command prompt), everything worked just fine. It took me a while to track this down - perhaps this will save you some time.

posted on July 13, 2007  #    by Rick Miller  Comments [2]
 Thursday, July 12, 2007

While working with Visual Studio and wishing that feature X existed, I decided to delve into the Visual Studio Extensibility layer and see what it can do.  There are 3 main ways to extend the VSIDE which are Macros, Plugins, and Packages so I opted to play with managed packages (I like C# and wanted full integration into the IDE).

After downloading the Visual Studio 2005 SDK and completing development of my package I needed to deploy it.  I ran into a number of issues deploying my package, mostly related to issues with the Package Load Key.  Following are the steps that I came up with for deploying a package.

  1. Create a new VSIP membership account if you do not already have one (go to the VSIP affiliate site to sign up if you are not a member yet)
  2. Login using your passport account at the vsip members
  3. Once logged in, you must Create a new product
    1. Click on the Products link
    2. Click on the Create New Product link and fill out the information for your package
  4. After your product is created, click on the View/Request PLK link
  5. Fill in the information as it appears in your VSPackage and click the Request PLK button
  6. Microsoft will review your product and notify you that the PLK has been approved or denied
  7. If the PLK has been approved, log back into your VSIP member account, click on Products and then View/Request PLK
  8. Add a new numbered resource to your package with the PLK as its value
  9. Modify the ProvideLoadKey attribute in your package source to reference the resource number for your PLK

Microsoft requires that each deployed Package be given a key generated by and registered with Microsoft.  The generated key is called a Visual Studio Package Load Key, or PLK and must be requested from your VSIP, or Visual Studio Industry Partner, account (Note that if you are not a VSIP member you must sign up).  The PLK is a digest based on information specific to the Package that you have created (Package GUID, Package Name, Product Name, Company Name) allowing for a higher probability of unique values between packages.  The PLK also allows Microsoft to keep track of all released 3rd-party packages via their signature.  Be aware that PLKs are finicky so you must be sure to use the EXACT same information for both the Package and what was used to generated a PLK.

    Here are some useful links I came across regarding PLKs when I was getting my package ready for deployment:
    posted on July 12, 2007  #    by Adam Markowitz  Comments [0]
     Wednesday, June 20, 2007

    Today I worked on an AJAX application that uses JSON over xmlhttp to provide a quick search feature in our product ActiveFocus. Here you can see it in action: as you type in the searchbox, each time a key is pressed, the search string is sent to the server, a freetext search is done against the database, the results are returned in a JSON array, and then rendered as a HTML table:

    Originally, this was hand coded in JavaScript at a very low level, using an ASP.Net 2.0 page on the server side to create and return the JSON object. The task at hand was to convert this to a more high level approach using Teleriks RadServiceManager to call a ASP.Net 2.0 Web Service, which returns a standard .NET type that is automatically converted to a JSON object.

    In my Search Web Service, I return an array of SearchResultRows:

    public struct SearchResultRow
    {
      public int ID;
      public string ArtifactType;
      // ...
    }

    [WebMethod(EnableSession = true)]
    public SearchResultRow[] ArtifactSearch( string searchKey)
    {
      //…

    This was amazingly straight forward. On the client side, when the callback returns, you can access the array through JSON indexing, something like this:

    function CallSearch( searchKey )
    {
      Search.ArtifactSearch(
        searchKey,
        SearchServiceCompleteCallback, SearchErrorCallback);
    }


    function SearchServiceCompleteCallback(ResponseAsJSON, ResponseAsXml, ResponseAsText)
    {
      var Results = ResponseAsJSON;
      for( i=0; i < Results.length; i++)
      {
        // …
     

    After debugging it in FireFox/FireBug (highly recommended! See article by my colleague Noel), I switched back to Internet Explorer 7.0 to test it there, confident that all was well. At first, the search behaved just like it should. But when I typed a search phrase that narrowed the search down to just one record in the returned array, I suddenly found that the table of results did not get displayed at all. It would display two or more results, but not one!

    Intrigued, I switched back to FireBug to debug the mystery. But in FireFox, a one row array worked just fine. I could inspect the value of Results and see the JSON encoding, and verify that it was correct. So, I switched back to IE, this time using the VS 2005 IDE Script Debugger, which is pretty primitive compared to FireBug, but I had no choice.

    Now, when I went to inspect Results, I found something very strange. When two or more records were returned, the JSON looked just like the FireFox version:

    But when the call only returned one row, the JSON object had a different layout! Instead of a JSON  array of SearhResultRow records, there was an inner object named the same thing as the type of the array elements (SearchResultRow), which contained the field values for that one record!

    Go figure!

    At this point I had spent way too much time debugging and needed to get the job done, so I just added a check to see if the singleton format was present and handled the two different cases in seprate branches of the if statement, which did the trick.

    However, I am curious as to whether this is a bug or not. Clearly, it is the same code running both server side and client side, yet in the two main browser versions, the JSON objects differ for one record arrays.

    Let me know if you have any input! If not, maybe at least this blog will save you some debugging time…

    posted on June 20, 2007  #    by John Waters  Comments [0]
     Wednesday, May 23, 2007

    Visual Studio comes with some handy (and some not-so-handy) code snippets, but for some reason there isn't one for declaring a method. It isn't that big of a deal, but after a while you might start resenting finishing your method header, then having to type Enter, {, Enter, }, Up, Enter to start the method body. Here's a snippet that will automatically put an open and closing brace after your method declaration, with the cursor ready to go in between:

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>method</Title>
          <Shortcut>m</Shortcut>
          <Description>Code snippet for methods</Description>
          <Author>Adam Anderson</Author>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
        </Header>
        <Snippet>
          <Declarations>
            <Literal>
              <ID>method-modifiers</ID>
              <ToolTip>Method modifiers</ToolTip>
              <Default>public</Default>
            </Literal>
            <Literal>
              <ID>return-type</ID>
              <ToolTip>Return type</ToolTip>
              <Default>void</Default>
            </Literal>
            <Literal>
              <ID>member-name</ID>
              <ToolTip>Method name</ToolTip>
              <Default>Name</Default>
            </Literal>
            <Literal>
              <ID>param-list</ID>
              <ToolTip>Parameter list</ToolTip>
              </Default>
            </Literal>
          </Declarations>
          <Code Language="csharp">
            <![CDATA[$method-modifiers$ $return-type$ $member-name$( $param-list$ )
    {
    $end$
    }]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>

    posted on May 23, 2007  #    by Adam Anderson  Comments [0]
     Tuesday, May 15, 2007

    There's a fascinating little article "Create Advanced Web Applications With Object-Oriented Techniques" by Ray Djajadinata that delves into how JavaScript implements objects, inheritance, anonymous methods, and even a bit about simulating private properties and namespaces.  This may be relevant if you want greater depth in AJAX, particularly the Microsoft flavor ASP.NET AJAX.  There's a sidebar (by Bertrand Le Roy) about the ASP.NET AJAX OOPS implementation and use of JavaScript to add reflection and other .NET familar constructs including properties, events, enumerations and interfaces.

    posted on May 15, 2007  #    by Noel Rice  Comments [0]
     Monday, May 14, 2007

    This is one of those little things I'm looking forward to getting out of C# 3.0: inferred types. I've always throught to myself, "I just declared the variable to be that type, can't you figure it out without me spelling it out for you, C# compiler?" Well, the compiler can't figure it out yet, but here's a little snippet I cooked up so at least I don't have to type the type name twice:

    <?xml version="1.0" encoding="utf-8" ?>
    <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
      <CodeSnippet Format="1.0.0">
        <Header>
          <Title>var</Title>
          <Shortcut>var</Shortcut>
          <Description>Code snippet for declaring and initializing a variable with a type cast</Description>
          <Author>Adam Anderson</Author>
          <SnippetTypes>
            <SnippetType>Expansion</SnippetType>
          </SnippetTypes>
        </Header>
        <Snippet>
          <Declarations>
            <Literal>
              <ID>type</ID>
              <ToolTip>Variable type</ToolTip>
              <Default>Type</Default>
            </Literal>
            <Literal>
              <ID>name</ID>
              <ToolTip>Variable name</ToolTip>
              <Default>Name</Default>
            </Literal>
            <Object>
              <ID>value</ID>
              <ToolTip>Initial value</ToolTip>
              <Default>Value</Default>
              <Type>System.Object</Type>
            </Object>
          </Declarations>
          <Code Language="csharp">
            <![CDATA[$type$ $name$ = ($type$) $value$;
            $end$]]>
          </Code>
        </Snippet>
      </CodeSnippet>
    </CodeSnippets>

    To install, copy and paste the above XML into a file and save it with a .snippet extension to your code snippets directory (My Documents\Visual Studio 2005\Code Snippets\Visual C#\My Code Snippets). To use, simply type "var" and press Tab.

    Now as you type the type name, it will be duplicated for you in the type cast.

    Every little annoyance eliminated is productivity gained. Enjoy!

    posted on May 14, 2007  #    by Adam Anderson  Comments [1]
     Tuesday, April 17, 2007

    You might overlook the JavaScript debugging utility that's already built in to Visual Studio 2005: the Script Explorer window.  The Script Explorer can take care of the usual debugging tasks like stepping through code, adding watches and evaluating variables. 

    To use the debugger in Internet Explorer navigate to the browser Tools | Internet Options | Advanced tab and make sure that "Disable script debugging" is turned off. 

    Run your web application in Visual Studio 2005.  Then select the menu option for Debug | Windows | Script Explorer.  Notice in the background the tags for telerik RadEditor controls...

    The first thing you notice in the Script Explorer window is a series of JavaScript and resource files that are currently loaded.  Double click on the aspx file you're currently working with and you will see the evaluated HTML returned from the server.  The RadEditor control now shows as its computed HTML, CSS and JavaScript that will actually be functioning in the browser. 

    You can also navigate up to the script for the page and set breakpoints and watches.  When the JavaScript executes and hits your breakpoint you get all the usual Visual Studio debugging capabilities for free.

    Next blog I'll show the excellent "Firebug" debugging utility for Firefox.  Firebug doesn't stop at just JavaScript but works with the entire stack of AJAX related technologies (and has a high cool-factor).

    posted on April 17, 2007  #    by Noel Rice  Comments [0]
     Friday, March 02, 2007

    I was doing some work the other day, and found that I had the need to implement a template programatically (rather than creating it at design time). I love the internet search engines, and the (sometimes overwhelming) amount of information you can usually find on any subject, but there wasn't a whole lot on this subject. To make matters worse, the articles I did find hinted around the edges of what I was looking for, but none seemed to describe what I needed to do very closely - they all addressed the aspect of the problem that they were interested in solving. So, at the risk of introducing one more post that addresses the issue that I was trying to solve, perhaps this post will help you.

    The basic idea behind using a template is that you can place controls into it that are bound to data at run-time. In a very general sense, that's what a grid control does - you provide a list of columns you're interested in, hook the grid up to a datasource, issue a databind command, and the data gets displayed where you want it to be. The next step is to take your own asp.net controls of choice and put them into the itemtemplate or edittemplate for a column. If you know what column you're binding to at run-time, the task is fairly straightforward, and we've all done it countless times.

    The problem I was trying to solve was that I had a control (the radRotator control by telerik) that I needed to place an unknown number of copies (at design time) onto a web page, each of which would dind to a differently-named column in the data table it was attaching to. Yes, I probably could have created a bunch of different controls, and altered the "visible" property, but that wasn't how I wanted to skin this cat. Doing it the way I wanted to, however, required that I instantiate the controls dynamically at run time, and populate the control's template with the controls I wanted to use in the display, which would themselves bind to data columns that varied from instance to instance.

    The first step is to create a helper class that creates your template. The template in this case is a very simple one, containing only a label control which will take as its text the name of a color, and change the background color of the label to that same color. The class looks like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    class RotatorTemplate : ITemplate
    {
    string columnName;
    public RotatorTemplate(string column)
    {
    columnName = column;
    }

    public void InstantiateIn(Control c)
    {
    Label lbl = new Label();
    lbl.DataBinding += new EventHandler(OnDisplayDataBinding);
    c.Controls.Add(lbl);
    }

    void OnDisplayDataBinding(object sender, EventArgs e)
    {
    Label lbl = (Label)sender;
    RadRotatorFrame iContainer = (RadRotatorFrame)lbl.NamingContainer;
    DataRowView drv = ((DataRowView) iContainer.DataItem);
    lbl.Text = drv[columnName].ToString();
    lbl.BackColor = System.Drawing.Color.FromName(lbl.Text);
    }
    }

    What's going on here is that when the constructor is called, the name of the column that we're going to bind to is passed in to the constructor, and stored in the local variable "columnName" at line 6. The InstantiateIn method is called by the control wrapping the template each time it needs a new copy of the template contents. In our example, we create a new label, hook up the OnDisplayDataBinding event handler. Note that there's no magic in the name internal to the helper class - I named it that because it's descriptive of what the routine does. The only important piece here is that the "lbl.DataBinding" event be specified properly. You should also realize that you could create and add any number of controls of different types here, you're not limited to a single control. Finally, we add the control to the controls collection of whatever control requested the new template instance.

    The most interesting part is the event handler. I don't see how this helper class can avoid having a lot of knowledge about the environment it's working in, because of the code on line 17 that typecasts the naming container to be of type RadRotatorFrame - though I suspect that the RotatorFrame descends from a more generic class that still has  a dataitem property; in any event, this solved my immediate problem, I'll look for the generic class later, and you should just be aware that you'd substitute your own naming container in the typecast.

    The real breakthrough for me was the realization that the DataItem was available to be cast into a dataRowView, which I could then extract the desired data from, and set the text of the control. Because I was writing this for a very specific application, I knew I'd always be getting a color name, so I also took the opportunity to set the label's background color. As a general rule, you'd want to do better data checking before making the assignment on line 20, though it turns out that an attempt to convert a non-color into a color fails gracefully, and returns white.. Also, if you're adding more that one control in the InstantiateIn event, you'll want to name them when you create them, so that you can find them in the databinding event.

    That's the helper class. After that, the rest of the process is trivial. As an example, say you wanted to hook up a table that contains proverbs. You could do it like this (and here, I'm populating the template of a radRotator control, but the containing control could be anything that would take a template):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    protected void Page_Load(object sender, EventArgs e)
    {
    DataTable proverbsTable = new DataTable();
    proverbsTable.Columns.Add("proverb");

    proverbsTable.Rows.Add("A stitch in time saves nine");
    proverbsTable.Rows.Add("A rolling stone gathers no moss");
    proverbsTable.Rows.Add("The early bird catches the worm");
    proverbsTable.Rows.Add("A penny saved is virtually worthless");

    RadRotator rotator1 = new RadRotator();
    rotator1.ID = "rotator1";
    rotator1.DataSource = proverbsTable;

    rotator1.FrameTemplate = new RotatorTemplate("proverb");
    rotator1.TransitionType = RadRotator.RotatorTransitionType.Slideshow;
    rotator1.TransitionEffect = RadRotator.RotatorTransitionEffect.GradientWipe;
    rotator1.Width = 500;
    rotator1.Height = 50;
    rotator1.AutoPostBack = true;
    PlaceHolder1.Controls.Add(rotator1);

    rotator1.DataBind();
    }

    The only really interesting thing here is the creation of the RotatorTemplate on line 12 - here's where you pass the variable information (in this case, the name of the data column you're going to use to populate the label text).

    That's it for ITemplate Instantiation. I hope it saves you some time and sheds a little light on your own problem.

    posted on March 2, 2007  #    by Rick Miller  Comments [2]
     Wednesday, February 07, 2007

    This morning I discovered I could enter code to VS but couldn't backspace over it.  This would require me to code perfectly the first time, and for me that's a non-starter.  It turns out that none of the command buttons work.  The short story on the fix for this oddity is to either disable Auto-Hide or open one of the hidden windows, then click the X to close.  More info at the msdn blog site: Tabs, Backspace, Delete and other commands not working in the editor.

    posted on February 7, 2007  #    by Noel Rice  Comments [0]
     Monday, January 29, 2007

    I have been developing ASP.net Web Applications with Visual Studio 2005 on Windows Vista for a month or so now, and it kind of works. But I have been looking forward to the Visual Studio 2005 SP1, so I was excited to see that Windows Update had tried to install it last night. The install failed, but I set out to figure out what it would take to get it to work on Vista...

    The Service Pack can be downloaded manually here. I fetched it and ran it to see what the problem was. It ended up showing me an error box, saying that if I had installed support for Web Application Projects, then I needed to uninstall it before installing the Service Pack, as Web Application Projects are now an integral part of VS 2005 development. I had indeed done that, so I went to the control panel, uninstalled Web Application Projects, and then tried again. Bingo! This time it installed.

    Next, I fired up Visual Studio to see if my Web Application Projects would still work. However, I didn't get far - Visual Studio immediately informed me that I needed to get the Visual Studio 2005 Vista SP1. Here is how it is described on the page where you download the regular SP:

    "For developers using Visual Studio 2005 on Windows Vista, Microsoft is in current development on an update to Service Pack 1 called the ‘Visual Studio 2005 SP1 Vista Refresh Beta’. This update builds on the improvements made in SP1 and delivers a first class experience for developers wanting to take advantages of the new features in Windows Vista. The Visual Studio 2005 SP1 Update for Windows Vista is expected to ship after the consumer availability of Windows Vista in Q1 of 2007 and is now available in beta."

    Wel, I dont have the patience to wait for this to RTM, so I figured I would install the beta. You can get it here.

    I went ahead and downloaded the beta. The installation instructions state "On Vista, ensure UAC is turned on". I have turned UAC off, it is the most annoying thing Microsoft created since the Office Paper Clip. But I didnt want to mess up the install, so I turned it back on (which requires a reboot), and then installed the beta (you need to run it as Administrator). That went smoothly, so I turned UAC off again, rebooted, and then started Visual Studio. Cool! No warning messages this time!

    Now it was time to see if I could still load my Web Application Projects, so I selected a solution to open and.... it didnt work! Visual Studio told me that I had to install something called "IIS 6 Metabase and IIS 6 Configuration Compatibility". I googled that phrase and ended up on this page. It is a good resource that tells you all the steps needed to run Web Application Projects with IIS (not the built in Development Web Server). One of the steps is to turn on the above mentioned compatibility setting, which you do from the Control Panel, the procedure is well described in the page mentioned above. So, I turned on the compatibilty and tried again!

    Lo and behold, this time it worked! As of now, I am back to developing, running and debugging Web Application Projects in Visual Studio against my local IIS, but now with SP1 and the Vista SP1 beta...

    posted on January 29, 2007  #    by John Waters  Comments [0]
     Friday, March 17, 2006

    I'm still playing around with that MakeRegion macro that Philip first posted. Today I added a regular expression to parse the first line of code and extract only the member name instead of the entire line.

    For instructions on how to install, see The Blog That Started It All.

    Imports EnvDTE
    Imports EnvDTE80
    Imports System.Diagnostics
    Imports System.Text.RegularExpressions

    Public Module Regions

      Sub MakeRegion()
        Regions.MakeRegion()
      End Sub

      Public Class Regions
        ' MakeRegion inserts #region and #endregion tags
        ' around selected text in the VS editor.
        Shared Sub MakeRegion()
          Dim rName As String = ""
          Dim pad As String = ""
          Dim junk As String
          Dim count, i As Integer
          Dim startpoint, endpoint, tmppoint As EditPoint

          With DTE.ActiveDocument.Selection
            startpoint = .TopPoint.CreateEditPoint()
            endpoint = .BottomPoint.CreateEditPoint
          End With

          If startpoint.EqualTo(endpoint) Then
            Exit Sub
          End If

          'ELR: ADDED THIS, to move the startpoint to the start of the line()
          'so that the Pad function works correctly
          If Not startpoint.AtStartOfLine Then
            startpoint.StartOfLine()
          End If

          Dim DefaultResponse = GetDesc(DTE.ActiveDocument.Selection.TopPoint.CreateEditPoint())
          Dim re As Regex = New Regex("\s(\w+)\s*(?:\(|\:|$)")
          DefaultResponse = re.Match(DefaultResponse).Groups(1).Value

          'IV 2004-12-13: rName = InputBox("Region Name:")
          rName = InputBox("Type the name you want to give to the region, which will appear in the Visual Studio Code Editor.", "Make Region", _
          DefaultResponse)

          rName = rName.Trim()

          If rName.Length = 0 Then
            Exit Sub
          End If

          DTE.UndoContext.Open("Insert A Region")
          Try
            junk = startpoint.GetText(startpoint.LineLength)

            pad = String.Empty
            For count = 0 To junk.Length - 1
              If junk.Substring(count, 1).Equals(" ") _
              Or junk.Substring(count, 1).Equals(vbTab) Then
                pad += junk.Substring(count, 1)
              Else
                Exit For
              End If
            Next

            'ELR: ADDED Test for Languages
            If DTE.ActiveDocument.Language = "CSharp" Then
              ' C Sharp Code
              startpoint.Insert(String.Format("{0}#region {1}{2}", _
               pad, rName, vbCrLf))
              If endpoint.LineLength = 0 Then
                endpoint.Insert(String.Format("{0}#endregion {1}{2}", _
                 pad, rName, vbCrLf))
              Else
                endpoint.Insert(String.Format("{0}#endregion {1}", _
                 vbCrLf & pad, rName))
              End If
            Else
              ' VB Code
              startpoint.Insert(String.Format("{0}#Region {1}{2}", _
               pad, rName, vbCrLf))
              If endpoint.LineLength = 0 Then
                endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
                 pad, rName, vbCrLf))
              Else
                endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
                 vbCrLf & pad, rName, vbCrLf))
              End If
            End If
          Finally
            DTE.UndoContext.Close()
          End Try
        End Sub

        ' IV: Get the description from the 1st line of code in the region
        ' i.e. ignore c# comment tags (///) or take 1st line of the comments (//)
        ' Requires adjustments for VB and other langs
        Private Shared Function GetDesc(ByVal startpoint As EditPoint) As String
          Dim line As String = ""
          Dim tmppoint As EditPoint

          line = startpoint.GetText(startpoint.LineLength)
          If (line.Length > 0) Then
            line = line.TrimStart(" ", vbTab)
            If DTE.ActiveDocument.Language = "CSharp" Then
              If (line.StartsWith("///")) Or (line.StartsWith("[")) Then
                tmppoint = startpoint
                tmppoint.LineDown()
                line = GetDesc(tmppoint)
              ElseIf (line.StartsWith("//")) Then
                line = line.TrimStart("//", " ")
              End If
              line = line.Replace("{", String.Empty)
            End If
            line = line.TrimEnd(" ", vbTab)
          End If
          Return line
        End Function
      End Class

    End Module

    posted on March 17, 2006  #    by Adam Anderson  Comments [1]
     Tuesday, March 14, 2006

    Sometimes you need to comment out blocks of code, but you don't necessarily want to comment out each entire line. As I was performing this very chore today, I thought to myself, "Hey, wouldn't it be nice if there was a keyboard shortcut I could use to comment a selected block of text using comment delimiters?" Then I thought to myself, "I already know how to create macros thanks to Philip's great blogs on macros. Why don't I try writing my own?" So I did. Source code within.

    See Philip's great blogs for instructions on how to install macros.

    Imports System
    Imports EnvDTE
    Imports EnvDTE80
    Imports System.Diagnostics

    Public Module SolutionExplorer

      Sub CollapseNodes()
        ' Get the the Solution Explorer tree
        Dim UIHSolutionExplorer As UIHierarchy
        UIHSolutionExplorer = DTE.Windows.Item( _
         Constants.vsext_wk_SProjectWindow).Object()

        ' Check if there is any open solution
        If (UIHSolutionExplorer.UIHierarchyItems.Count = 0) Then
          Return
        End If

        ' Get the top node (the name of the solution)
        Dim UIHSolutionRootNode As UIHierarchyItem
        UIHSolutionRootNode = UIHSolutionExplorer.UIHierarchyItems.Item(1)

        ' Collapse each project node
        Dim UIHItem As UIHierarchyItem
        For Each UIHItem In UIHSolutionRootNode.UIHierarchyItems
          UIHItem.UIHierarchyItems.Expanded = False
        Next

        ' Select the solution node, or else when you click
        ' on the solution windows scrollbar, it will synchronize the open document
        ' with the tree and pop out the corresponding node which is probably not
        ' what you want.
        UIHSolutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
      End Sub

      Sub ExpandNodes()
        ' Get the the Solution Explorer tree
        Dim UIHSolutionExplorer As UIHierarchy
        UIHSolutionExplorer = DTE.Windows.Item( _
         Constants.vsext_wk_SProjectWindow).Object()

        ' Check if there is any open solution
        If (UIHSolutionExplorer.UIHierarchyItems.Count = 0) Then
          Return
        End If

        ' Get the top node (the name of the solution)
        Dim UIHSolutionRootNode As UIHierarchyItem
        UIHSolutionRootNode = UIHSolutionExplorer.UIHierarchyItems.Item(1)

        ' Collapse each project node
        Dim UIHItem As UIHierarchyItem
        For Each UIHItem In UIHSolutionRootNode.UIHierarchyItems
          UIHItem.UIHierarchyItems.Expanded = True
        Next

        ' Select the solution node, or else when you click
        ' on the solution windows scrollbar, it will synchronize the open document
        ' with the tree and pop out the corresponding node which is probably not
        ' what you want.
        UIHSolutionRootNode.Select(vsUISelectionType.vsUISelectionTypeSelect)
      End Sub

    End Module

    posted on March 14, 2006  #    by Adam Anderson  Comments [0]
     Monday, January 16, 2006
    DPack is a collection of free tools that extend the VS IDE. I originally got it because of the Delphi keyboard shortcut scheme, but I've come to appreciate for many of its other features, especially Surround With, which surrounds selected code with many different kinds of code constructs, and the Code Browser, which incrementally searches code for members matching a filter expression. Get it at http://www.usysware.com/dpack/
    posted on January 16, 2006  #    by Adam Anderson  Comments [1]
     Friday, January 06, 2006

    Add vertical guidelines to Visual Studio by adding a simple registry key to this location:

    [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\7.1\Text Editor]

    Now, add a string value named "Guides".

    Set its value to something like RGB(128,0,0) 80, 100

    The setting above will draw a Red guideline in Visual Studio at column 80 and 100. You can  have up to 13 guidelines. Adjust the values as you see fit.

    Giving credit where credit is due, I believe Sara Ford first blogged about this about a year ago.

    posted on January 6, 2006  #    by Mike Dugan  Comments [1]
     Friday, November 12, 2004

    Build events are handy ways to perform tasks that need to be done every time a project is rebuilt. The Visual Studio IDE exposes these events through the project properties dialog for windows applications, but not for web applications. However, the IDE can be coerced into supporting build events for web applications, and it's surprisingly easy to do. Simply open your web project's .csproj file and look under the settings element for the following elements:

    <VISUALSTUDIOPROJECT>
      <CSHARP>
        <BUILD>
          <SETTINGS>
            <!-- Your Build Events Here -->
            PreBuildEvent = ""
            PostBuildEvent = ""
            <!-- RunPostBuildEvent = "Always" | "OnBuildSuccess" | "OnOutputUpdated" -->
            RunPostBuildEvent = "OnBuildSuccess"
          </SETTINGS>
        </BUILD>
      </CSHARP>
    </VISUALSTUDIOPROJECT>

    Simply enter your command-line actions to PreBuildEvent and/or PostBuildEvent and enter the string describing the desired condition in RunPostBuildEvent. Save the file, and you're good to go.

    posted on November 12, 2004  #    by Adam Anderson  Comments [1]