Friday, December 22, 2006

Settling into my XNA Development Environment

Microsoft recently released the XNA toolkit for XBox 360 and PC games development.  The supported IDE for this is Visual C# Express

I am quite picky about my development environment, for instance: I like the Consolas 12pt font;  I like 2 tab spaces instead of 4;  I like virtual space in the editor; etc. etc.

Visual Studio Express does not give the option to change tab size and virtual space settings so I immediately jumped into regedit and edited the values.  Then I thought that maybe I could export my settings from Visual Studio 2005 Professional and import them into Express.

This worked, with the exception of some command bar stuff that isn't supported in Express.  The added bonus was that the Options screen now displays more settings that before:

Options screen before import:

Options screen after import:

Very nice.  It's just a shame that Express doesn't support plug-ins as I really miss ReSharper.

Tuesday, December 12, 2006

ReSharper 2.5 Released

The download links don't seem to work at the moment (they're still pointing to version 2.0.2).  The link to the direct download is http://download.jetbrains.com/resharper/ReSharper-2.5-setup.exe  (which I rather cleverly deduced from the existing broken link of http://download.jetbrains.com/resharper/ReSharper-2.0.2-setup.exe)

Remember though, this is Visual Studio 2005 only.

Thursday, November 30, 2006

In the name of science

What is the speed of meme?  People write in general (typically truimphant) terms about how swiftly a single voice can travel from one side of the internet to the other and back again, but how often does that actually happen?

If you have a blog, please read this and follow the instructions.  I'm supposed to beg you to do this, but the title of this post is "In the name of science" and not "In the name of science and commision" !

FAJAX - Fake AJAX!

AJAX is great for reducing page flicker when posting back to the same page (for instance, updating a listbox or a textbox), but a lot of a web-site navigation involves clicking around to different pages.

DHTML behaviour has been around a good few years allowing page developers to have page transitions (such as wipe, chequerboard etc.) when the page loads and unloads. None of these transitions were that great and a certain amount of flicker was still present.

I’ve seen a few sites recently that have a nice fade transition that is much smoother than DHTML behaviours. I’ve just discovered from this blog, how it’s done.

Tuesday, November 21, 2006

I Hate ClearCase Part II - When a text file isn't a text file!

Here's a question:  If you have a text file that contains a very long line of text (>8000 characters), is it still a text file?

I'd say Yes. But ComputerClearCase says No. Or at least hinted it meant No via several obscure error messages.

The file in question is a whole bunch of JavaScript code (part of the Microsoft AJAX release) that is not intended to be read by anyone viewing a web page, and hence is sensibly put on one line (albeit 69168 bytes in length). 

Firstly, I was getting a strange error when adding them to ClearCase.  Apparently, despite of the error, they were being added – I found them in a checked-out state.  Upon trying to check them in, I got:

Error checking in '...MicrosoftAjax.js'.  Type manager "text_file_delta" failed create_version operation.
Unable to check in '...MicrosoftAjax.js'

...followed by OK and Cancel buttons (quite how one can Cancel an operation that can't be done anyway is beyond me!)

I then thought I’d take a look at the file and did a ‘diff’ with the previous version.  I got this:

Error encountered doing compare operation.
"c:\temp\ccdm02327" is not a 'text file':  it contains a line exceeding 8000 bytes.
Use a different type manager (such as a compressed file).

So, according to ClearCase, a text file is not a text file if it has lines of over 8000 characters!

Anyway, the solution was to use the cleartool command line tool to add the file using a different 'type' - a compressed text file type.  Note that this doesn't actually change the contents of the file, nor the way it's handled (thankfully!).  Of course, once the solution was presented to me...

C:\folder\ScriptLibrary\Release>cleartool mkelem -nc -eltype compressed_text_file MicrosoftAjax.js

...everything became perfectly clear!

Monday, October 30, 2006

I Hate ClearCase - Part I

ClearCase isn't my favourite source control system.  I find the UI clunky and for the most part, it's way over engineered.

I've just tried deleting a file and I'm getting an error message that says:

Trigger "NO_RMNAME" has refused to let rmname proceed. 
Unable to remove "[file]".

WHAT DOES THIS MEAN AND HOW DO I DELETE A FILE?!

My 20+ years of working with software - coupled with my powers of deduction, have led me to "guess" that this means I don't have the permission to delete a file! (I could be wrong;  I'm waiting for the in-house ClearCase administrator to advise!)

I'm going to stop using the advanced features of this software and continue with the basics...

Tuesday, October 24, 2006

Cassini and assembly loading problems

Cassini is the Visual Studio development web server. Generally, Cassini is great;  you give it a port number and a path and off it goes - hosting ASP.NET pages in a similar fashion to ISS but much quicker.  Plus, it's unloaded when you stop debugging.

One issue I came across today was with Cassini and the loading of assemblies.  During development of .NET applications, I like to use project references rather than binary references (whether those references are in our out of the GAC).

The problem lies with the fact that Cassini occasinally switches app domains, forcing objects to be serialised across.  This serialisation was failing as one of our serialisable objects were in an assembly that wasn't in the GAC and wasn't available anywhere for the Cassini process to load.  The exact error was:

Type is not resolved for member 'Company.Product.Type,Company.Product.dll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=blah'

Investigation led to the suggestion to use DEVPATH.  Basically, this means adding the following entry to the ‘runtime’ section of the machine.config file:

<developmentMode developerInstallation="true"/>

… and setting the DEVPATH environment variable to the directory where your private copies of assemblies are located.  This is supposed to load a matching assembly regardless of version.  Unfortunately, this didn’t work and for whatever reason, a ComException was being thrown very early on when Cassini started.

Although this didn't work, there was a link in the page to another MSDN article describing a way to redirect assembly loading. This again used the runtime section of the machine.config file, but this time using:

<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Company.Product" publicKeyToken="blah" culture="neutral" /> <codeBase version="1.0.0.0" href="file://C:/Blah/Company.Product.dll"/> </dependentAssembly> </assemblyBinding>

This worked great and saved me having to use IIS or copying my assemblies all over the place so Cassini can load them.

I hope this post proves useful to anyone having a similar problem.  It will probably prove useful to me when I come across the problem again in the far future having forgotten how I got around it the first time!

Monday, October 23, 2006

What to expose in a framework

Scott Hanselman  blogged recently on reasons to make a class public in a framework.  One reason was that a developer may want the functionality offered by a particular class, either to be used as-is or to be extended.

Normally, frameworks are quite specific in what they do and what they provide.  If a whole 'chunk' (class) is required to be made public, then it may be the case that this functionality isn't in the realm of what the Framework was designed to offer. For example, should a class that lists the zipped files in a directory be exposed from a compression framework?  Or, should a regular expression helper class be exposed from a logging/tracing framework?

Opening up large chunks of code because someone wants the functionality can dilute the Framework and make the API harder to understand because it offers so much functionality. With this in mind, if the framework you've given them doesn't do what they want, then maybe rethink ways of incorporating the functionality into the Framework rather than opening up a chunk of code.

You might be thinking that it'd be difficult incorporating all the functionality of a particular class into other parts of the framework;  classes, whether internal or exposed, should be succint (following the Single Responsibility Principle) - so there shouldn't be too much to move around to give them the features they require.

When we start talking about frameworks and OO concepts such as SRP, it brings to mind a very valid point raised in the excellent Framework Design Guidelines book - something along the lines that OO should play a part in the implementation of a framework but not in the API of the framework (I think the example of Streams/TextReaders was used as a very good example).  The .NET Framework now seems to have more and more utility classes that help to flatten the heirarchy and (in my opinion) increase usability/memorability.

Some examples would be a good way of testing our arguments.  Perhaps examples based on the .NET Framework wouldn't be the best to use as this is a lot more generic than say, frameworks for logging/tracing or compression.

Sunday, October 22, 2006

Retrieve your Windows OS Product Keys

Today I needed to get the Windows XP Product Key but didn't have the neccessary information to hand. I did a search and found the MagicJellyBean utility.


This worked but I was curious how it worked. I read around a little bit and discovered a snippet of C# code from Willem's blog.


I then modified it a bit and created my own C# WinForm application.



The application lists the most common product keys (Windows XP and Office) and has a button to search for more keys that look like product ID's. It searches all keys in HKEY_LOCAL_MACHINE.


Here's the source code and here's the binary. Note, the application depends on the .NET Framework 2.0. Also, save the binary before running it otherwise it'll run with restricted permissions and won't be able to probe the registry.

Saturday, October 21, 2006

Visual Studio Orphaned Project Items Finder

The name is a bit of a mouthful, but sums up what it's all about.  It finds orphaned items in a Visual Studio project.  Inspired by Clean Source Plus, this utility is a stand-alone application and also a right-click Explorer menu item.

Recently I came across several dozen projects that had been worked on by dozens of people for several years.  Inevitably, there were files present in the source tree that were not part of the project.

This is a tool to find those files.  Please feel free to download it from CodePlex.  There is an installer file and the source code is also available. If you'd like to contribute to the project, please let me know.

To use it is very simple.  Download it and run it, or right click a Visual Studio project in Explorer and 'Find Orphaned Items...'.

Warning!

I've tested this project on Visual Studio 2003 and 2005 projects.  I haven't tested this on Web Projects or Web Application Projects (in Visual Studio 2005).  I would recommend verifying what the application thinks are orhpaned items.  If it continually gets it right, you can trust it more and check it less.  If it continually gets it wrong, then please let me know!

Friday, October 20, 2006

Problems with Forms Authentication and ASP.NET Themes

It's sometimes the strangest (and seemingly irrelevant) combinations of technology that give you the most problems. For a good few hours I've been wondering why my web site, which uses Forms Authentication and Themes, was not displaying any formatting or images.

It turns out that the URLs specified in the authentication section in web.config are used for ALL resources. So, in my case, the page was trying to load a .css file but ASP.NET was redirecting the request to default.aspx, which of course, is not a style-sheet and has a different MIME type. Here's the section of my web.config file:

<authentication mode="Forms">
      <forms  loginUrl="Default.aspx"
        defaultUrl="Default.aspx"
        protection="All"
        timeout="30"
        path="/"
        requireSSL="false"
        slidingExpiration="true"
        cookieless="UseDeviceProfile"
        domain=""
        enableCrossAppRedirects="false"/>
    </authentication>

To fix this, I allow unauthenticated access to the resources, which was straight-forward. I added the following to the web.config file:

 <location path="App_Themes">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>

The tricky part in finding this was that the page's HTML looked fine, there were no errors, and saving the resulting HTML to a file and viewing it produced the right results.

Firefox's JavaScript Console proved incredibly helpful in finding the problem:

 
Once I saw this, it all fell into place!

Thursday, October 19, 2006

BackgroundWorker - automating this handy class

BackgroundWorker objects are an addition to .NET 2.0 to simplify asynchronous programming and are very useful in (but not restricted to) Windows Forms.

The basic idea is:

  • Create a BackgroundWorker object
  • Set-up various events on it, like DoWork, RunWorkerCompleted, and ProgressChanged
  • Set-up various properties, like WorkerReportsProgress and WorkerSupportCancellation
  • Call RunWorkerAysnc

...then, in your form you get notified of progress and can cancel the operation at any time.

I've created a ReSharper Live Template that will help you create and set-up the BackgroundWorker object. You can download it here. For instructions on importing the Live Template into ReSharper, see my previous post here.

Wednesday, October 18, 2006

Visual Studio Build Tip

By default, Visual Studio will build all of the projects in your solution regardless of any errors.

The problem with this is that if the first project it builds contains an error, the resulting binary will not get generated. If any other projects depend on this (which is normally the case, as it was the first to be built) then they'll fail too, and so on to the end of the project heirarchy.

Pointless; you'll spend ages sitting around in a locked IDE unable to edit the error until the build finishes.

You might as well stop at the first error. You could of press Ctrl+Break (several times) and hope that VS will eventually stop. But, there's a better way: get Visual Studio to stop automatically after an error.

  1. Go to Tools/Macros/Macro Explorer
  2. Expand MyMacros
  3. Double click Module1
  4. This will bring up the macro in a new window. In that window, double click the EnvironmentEvents entry.
  5. From the drop-down (currently 'General', select 'Build Events')
  6. Select 'OnBuildProjConfigDone' and paste this in:
If Success = False Then 'The build failed...cancel any further builds.
DTE.ExecuteCommand("Build.Cancel")
End If

The whole method should look like this:

Private Sub BuildEvents_OnBuildProjConfigDone( _  
ByVal Project As String, _ 
ByVal ProjectConfig As String, _ 
ByVal Platform As String, _ 
ByVal SolutionConfig As String, _ 
ByVal Success As Boolean) Handles BuildEvents.OnBuildProjConfigDone   
    If Success = False Then 'The build failed...cancel any further builds.     
        DTE.ExecuteCommand("Build.Cancel")   
    End If 
End Sub

Wednesday, October 04, 2006

ReSharper Live Templates for validating parameters of public C# methods.

ReSharper Live Templates are smart shortcuts you can type and have filled in automatically. For instance, typing 'foreach' and pressing tab produces:

      foreach ( object o in something )
      {
      }

I've created 3 Live Templates for validating arguments in public methods (C#). Here's a short video demonstration. I've blogged about these before for ReSharper 1.5 and said that there's no way to export/import the templates. But in ReSharper 2.0, there is! You can get them here. Go to ReSharper/Options/Templates/LiveTemplates and click the 'Import templates from file' button.

Friday, September 29, 2006

MbUnit and null parameters

I've recently moved from NUnit to MbUnit.  I like the extra features it offers, in particular, the RowTest feature.  This allows a single test to take different parameters - the parameters of which are specified in the attributes.  Here's an example:

 

class Test { internal Test( string s ) { if( string.IsNullOrEmpty( s ) ) throw new ArgumentNullException( ) ; } } [ RowTest ] [ Row( @"Hello World!" )] [ Row( @"Another string" )] public void Test1( string val ) { Test t = new Test( val ); }

 

Here, Test1 is being given the parameters from the attributes on the test.  Previously, say, in NUnit, I'd have written a couple of unit tests that create this Test object and give it different values.  Normally, I'd also write a couple that would try and create one with a null string and an empty string and assert that it throws an ArgumentNullException.

Now, in MbUnit, I went to write the test like so:

[ RowTest ] [ Row( null , ExpectedException = typeof( ArgumentNullException ) ) ] [ Row( @"Hello World!" )] public void Test1( string val ) { Test t = new Test( val ); }

Strangely, this caused an internal error in MbUnit.  Reading around, It looks like MbUnit is taking the first parameter of Row and treating it as an array rather than a single parameter.  The complete non-obvious way around this is to cast the null to a string:

 

[ RowTest ] [ Row( (string)null , ExpectedException = typeof( ArgumentNullException ) ) ] [ Row( @"Hello World!" )] public void Test1( string val ) { Test t = new Test( val ); }

This now works.  Which is nice!

Wednesday, September 06, 2006

.NET Memory usage - A restaurant analogy

Tess uses a great analogy of restaurant bookings to describe .NET memory usage.  The rest of the posts in this blog are also very interesting.  Thanks Tess.

Link to If broken it is, fix it you should : .NET Memory usage - A restaurant analogy

Thanks for the feedback on the CodeFormatter plugin

I'd like to thank everyone for their feedback on the CodeFormatter plugin.  I've had some great suggestions and fixed a few bugs.  Keep them coming!

Friday, August 25, 2006

ReSharper 2.0.1 Maintenance Release Now Available

 

ReSharper 2.0.1 Maintenance Release Now Available

JetBrains ReSharper version 2.0.1 is now available for download at http://www.jetbrains.com/resharper/download/.
This release fixes a number of bugs and usability issues, in addition to substantial performance improvements. For more information, please see online Release Notes.
The update is a free maintenance release for all licensed users of previous ReSharper versions. All current users are highly encouraged to upgrade, due to the transition of the ReSharper development project to a new issue tracking system. So, the new release automatically sends bugs and exceptions to this new system.
Keep developing with pleasure!

Source: JetBrains .NET Tools Blog » Blog Archive » ReSharper 2.0.1 Maintenance Release Now Available

Wednesday, August 23, 2006

Code Formatter Plugin now on Codeplex

Check it out on Codeplex.  Please leave feedback on anything you'd like see.  The source code is there if you want to look around.  Let me know if you'd like to contribute.

Tuesday, August 22, 2006

Resharper 2.0.1 RC2 is now available.

One of the best tools ever just keeps getting better and better! Get RC2 here.

New version of the Code Formatter plugin for Windows Live Writer now available.

The new binaries are here. One small bug fixed in the form where you edit the code: pressing return caused the OK button to fire. Doh! Thanks to JTB World for spotting it.

Windows Live Writer - Bug

When content in a smart plugin exceeds the height of the canvas area, dragging on the size points on the surrounding rectangle causes strange behaviour.  Is anyone else seeing this or is it just me?

Windows Live Writer - Additions to API

Maybe this already exists, but it's not immediately obviose.  When developing a plugin, the component that sits along the right side of the screen is the Content Editor.  WLW has its own color scheme and to intermingle* nicely with it, it'd be nice if the color(s) used were available.

*is that a word?!

Sunday, August 20, 2006

Code Formatter Plugin for Windows Live Writer

I'm quite new to blogging and have recently discovered Windows Live Writer. I've downloaded various plugins for code formatting but none provided me with what I wanted:

  • The ability to format the code 'live'
  • The ability to wrap lines
  • The ability to change the background color
  • The ability to just quickly paste what's in the clipboard as code

The plugin I implemented formats and highlights code and also does all the above. Here's a screen shot of it in use:



Here you can see that the content editor on the right can change the tab width, background color, language, and line numbers.

Below are some sample of code used with the plugin.

Here's some C# code:

public int TabWidth

{

get

{

return _content.Properties.GetInt( @"TabWidth", 4 );

}

set

{

_content.Properties.SetInt(
@"TabWidth", value );

}

}






and some XML markup...


<Triggers>

<KeyPressTrigger Key="PropertyListTrigger" Character=" ">

<KeyPressTriggerValidStates>

<KeyPressTriggerValidState State="PropertyState" />

</KeyPressTriggerValidStates>

</KeyPressTrigger>

<KeyPressTrigger Key="ValueListTrigger" Character=" ">

<KeyPressTriggerValidStates>

<KeyPressTriggerValidState State="ValueState" />

</KeyPressTriggerValidStates>

</KeyPressTrigger>

</Triggers>






I've made available the source and the binaries for this plugin.



To use it, extract the binaries to \Windows Live Writer\Plugins and run WLW. The source is in C# 2.0 and comes with a Visual Studio 2005 solution.



Note that the .NET 2.0 Framework must be installed before this plugin will work.



Going forward



I plan to put this plugin onto CodePlex (if they let me!). I also plan on making a few additions to the defaults via the Options screen. New languages can easily be added too thanks to the great ActiPro Code Highlighter. I'd also like to thank Christophe De Baene for his syntax highlighting tool. It's a great plugin and also helped me understand how to use the ActiPro control.



Please let me know if you'd like to contribute on CodePlex or if there are any features you'd like to see at steve at dunnhq d.o.t. com

Friday, August 18, 2006

Converting System.Drawing.Color to HTML color (and vice-versa)

 

This is something I need very rarely.  So rare in fact that in-between uses it is completely removed from my memory, leaving just the fact that I know I've searched for it before!

To convert a .NET Color object to an HTML RGB or named color, use

 

string colorAsString = ColorTranslator.ToHtml( _backgroundColor ) ;

and vice-versa

 

Color c= ColorTranslator.FromHtml( @"#RRGGBB" ) ;

Wednesday, August 16, 2006

Reshaper Live Templates for validating arguments

I strongly agree with the 'contract' mataphor in API design, hence my interest in Spec# (that I've blogged about before).  

To assist in this and to eliminate the tedium of writing argument checks, I've created 3 Resharper Live Templates.  These check for

  • null parameters for any object passed
  • invalid parameters for any object passed
  • null or empty check for any String passed. 

These templates are called 'arg', 'argnull' and 'argempty' respectivly.

Resharper 1.5 doesn't allow importing or exporting of Live Templates from the GUI.  They are however stored in an XML file at %userprofile%\Application Data\JetBrains\ReSharper\UserSettings.xml.   Below is a chunk of XML that must be placed under the TemplateManager\Templates node.  If you have any others, please let me know!

 

<Template text="if( $TYPE$$EXPRESSION$ )&#xA; throw new ArgumentException( @&quot;Cannot $ACTION$ as the value passed was invalid. Please provide a valid value.&quot;, @&quot;$TYPE$&quot; ) ;&#xA;" shortcut="arg" description="Throws an ArgumentException" kind="livetemplate" reformat="false" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1723695683">

<Variables>

<Variable name="TYPE" expression="variableOfType(&quot;System.Object&quot;)" initialRange="0" />

<Variable name="EXPRESSION" expression="constant(&quot; != 1&quot;)" initialRange="0" />

<Variable name="ACTION" expression="constant(&quot;PERFORM AN ACTION&quot;)" initialRange="0" />

</Variables>

</Template>

<Template text="if( $TYPE$ == null || $TYPE$.Length == 0 )&#xA;throw new ArgumentNullException( @&quot;$TYPE$&quot;, @&quot;Cannot $ACTION$ as the value passed was null or empty. Please provide a valid non null value.&quot; ) ;&#xA;" shortcut="argempty" description="Throws an ArgumentNullException when a string is null or empty" kind="livetemplate" reformat="true" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1705884294">

<Variables>

<Variable name="TYPE" expression="variableOfType(&quot;System.String&quot;)" initialRange="0" />

<Variable name="ACTION" expression="constant(&quot;PERFORM AN ACTION&quot;)" initialRange="0" />

</Variables>

</Template>

<Template text="if( $TYPE$ == null )&#xA;throw new ArgumentNullException( @&quot;$TYPE$&quot;, @&quot;Cannot $ACTION$ as the value passed was null. Please provide a valid non-null value.&quot; ) ;&#xA;" shortcut="argnull" description="Throws an ArgumentNullException" kind="livetemplate" reformat="true" fileMask="" context="Everywhere" fileContext="CSharp" enabled="False" id="1497171628">

<Variables>

<Variable name="TYPE" expression="variableOfType(&quot;System.Object&quot;)" initialRange="0" />

<Variable name="ACTION" expression="constant(&quot;PERFORM AN ACTION&quot;)" initialRange="0" />

</Variables>

</Template>

Spec#

Spec# is an addition to C# to allow specifications to be explicitly added to methods. Specifications can state that a method takes a string (which must be non-nul), an integer (which must be between 0 and n), or an array (of which all entries must be non null).  Previously in C#, this would have meant a fair few lines of code that manually checked parameters and threw the respective exceptions.  Furthermore, without specifications, you cannot force any over-ridden method to comply to the same specification.

Spec# is currently a research project and can be downloaded at http://research.microsoft.com/specsharp/

It can be installed to run in Visual Studio 2003 and 2005.  For both systems, it requires an application called Simplify.  This is a java application that can be downloaded at HP Labs Java Programming Toolkit page.  The zipped file that contains Simplify.exe can be found at http://www.hpl.hp.com/downloads/crl/jtk/download-escjava.html, but don't forget to first read the licence at http://www.hpl.hp.com/downloads/crl/jtk/agreement.html ;)

Quicky StringBuilder Tip

StringBuilder has an Append method that returns a reference to itself. This is useful for when you want to append several items in one go. The following code is an example. Obviously, you'll get more benefit the more items you add:

      StringBuilder sb = new StringBuilder( ) ;
      string s = sb.Append( @"Hello " )
        .Append( @"World" )
        .ToString( ) ;

If you've been forced into programming in VB, then check out the original text of this tip at devx.com:

http://www.devx.com/tips/Tip/28152

Quicker loading of the Visual Studio .NET IDE

A handy tip from the Bug Slayer MSDN column:

Tip 57 - To hasten the startup of the Visual Studio .NET IDE, get rid of the Start Page. Because the Start Page requires all Web-browsing components to be loaded, you can chop off a considerable amount of startup time by skipping it. To turn off the Start Page, select Options from the Tools menu to bring up the Options dialog. In the Environment/General property page, select "Show empty environment" in the "at Startup" combobox.

Of course, with Resharper installed, this causes the the IDE's start-up time to become terribly slow.  But it's worth it!