Archive

Author Archive

Joel Spolsky: Leaky Abstractions

November 1st, 2010

I came across a great Joel Spolsky article this morning concerning the dangers of relying too heavily upon abstractions: http://www.joelonsoftware.com/articles/LeakyAbstractions.html

“The law of leaky abstractions means that whenever somebody comes up with a wizzy new code-generation tool … you hear a lot of people saying "learn how to do it manually first, then use the wizzy tool to save time…”

“And all this means that paradoxically, even as we have higher and higher level programming tools with better and better abstractions, becoming a proficient programmer is getting harder and harder.”

It still pays to know the fundamentals.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Notifying Property Code Snippet

October 27th, 2010

Having worked in Silverlight for a little over a year now, I find that INotifyPropertyChanged and the corresponding PropertyChanged event are something I use pretty often. To manage that I created a base view model class that exposes the following wrapper method:

/// <summary>
/// Raised when a property changed notification is sent.
/// </summary>
/// <param name="propertyName" />
/// A <see cref="System.String" /> identifying the property that
/// changed.
/// </param>
protected void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
        PropertyChanged(
            this,
            new PropertyChangedEventArgs(propertyName));
}

This allows me to create properties that look like:

/// <summary>
/// Gets or sets the Name.
/// </summary>
/// <value>
/// A string that contains the Name.
/// </value>
public string Name
{
    get { return _name; }
    set
    {
        if (_name == value) return;
        _name = value;
        OnPropertyChanged("Name");
    }
}

That’s still a lot of typing! More typing is less doing. To add these properties more efficiently I developed the following code snippet:

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>
                Notifying Property
            </Title>
            <Shortcut>
                propnotify
            </Shortcut>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <Type>System.Type</Type>
                    <ToolTip>The property type.</ToolTip>
                    <Default>type</Default>
                </Literal>
                <Literal>
                    <ID>propname</ID>
                    <ToolTip>The property name.</ToolTip>
                    <Default>propname</Default>
                </Literal>
                <Literal>
                    <ID>varname</ID>
                    <ToolTip>The variable name.</ToolTip>
                    <Default>varname</Default>
                </Literal>
            </Declarations>
            <Code Language="CSharp">
        <![CDATA[/// <summary>
        /// Gets or sets the $propname$.
        /// </summary>
        /// <value>
        /// A $type$ that contains the $propname$.
        /// </value>
        public $type$ $propname$
        {
            get { return $varname$; }
            set
            {
                if ($varname$ == value) return;
                $varname$ = value;
                OnPropertyChanged("$propname$");
            }
        }]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

Now I can just type propnotify and press Tab to get a template property snippet in my code. This saves a bunch of time when declaring the notifying bound properties within a view model.

propnotify  propnotify2

What interesting code snippets have you developed? Do you rely upon a third-party tool such as Resharper or CodeRush, or does the snippet system in Visual Studio 2010 meet your needs?

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Cuil Finally Dead

October 21st, 2010

After two years of giving bad search results, it looks like one of the world’s shorter lived and less well known search engines has finally called it quits. According to this article on Wikipedia, the company closed its doors on September 17th 2010. The idea behind Cuil seemed like a good one. Take the largest snapshot of the web that you can and let the natural relations of the items in that index create richer search results. The problem with that approach is one of accuracy, or in this case the lack thereof.

TechCrunch summed up the problem right away and it didn’t take a marketing genius to realize the problems of pairing images with articles from around the web. There were reports of pornographic images showing up next to entirely unrelated search results, and of competing brandings being associated together. Can you imagine the press release of the Windows 7 phone being paired with an Apple logo? If the service didn’t slowly die through lack of use, I could only imagine it was a matter of time before the lawsuits would do the job instead.

Bye bye, Cuil. Nice idea, but the web just isn’t ready yet.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

How to Insert a Picture Inline in Outlook Email

June 16th, 2010

First create an email with HTML formatting. In Outlook 2010 this is found in the Format section of the Format Text ribbon.

SelectHTMLFormatting

Then click the Picture button from the Illustrations section of the Insert ribbon. Browse to the picture and click Insert to insert the picture inline in the email.

InsertPicture

Now you can send picture replies to your boss inline instead of having to rely upon him/her to open the attachment.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Changing Visual Studio Registration Information

March 17th, 2010

This morning as I started Visual Studio it bugged me that the splash screen reported my registration information as “User” at “Microsoft”. My name isn’t “User” and I don’t work for “Microsoft”, at least not directly. This is something that has bothered me in the past but I’ve never dug into it far enough to figure out how to fix it.

This afternoon after a little research I was able to piece together the steps necessary to update the information. I found this question on Stack Overflow that had some useful information but not a complete solution. I also came across this post on John Robbins’ blog and between the two of them I was able to close the gap.

Updating Company Name and User for Windows
The first step is to open the registry editor and navigate to:

32 bit: HKLM\Software\Microsoft\Windows NT\CurrentVersion
64 bit: HKLM\Software\Wow6432Node\Microsoft\WindowsNT\CurrentVersion

Here you can edit the RegisteredOrganization and RegisteredOwner values.

CompanyNameKey

Updating Visual Studio User Registry Key
The next step is to update the user name for your Visual Studio registration. This is also a key in the registry at:

32 bit: HKLM\Software\Microsoft\VisualStudio\9.0\Registration
64 bit: HKLM\Software\Wow6432Node\Microsoft\VisualStudio\9.0\Registration

VisualStudioRegistrationKey

Getting Visual Studio to Use the New Information
Modifying the keys is the first step. However, it turns out that Visual Studio actually stores the information to be displayed in a SplashInfo key. The info is stored in binary data. Fortunately we do not need to modify the binary value in the registry. Instead simply run devenv /setup and the information will be updated automatically.

Run DevEnv Setup SplashInfoKey

Verifying the Information
To verify that the information was updated correctly you can either view the SplashInfo key in the registry or simply run Visual Studio. I’m now “Stuart Thompson” at “SoftSource Consulting”. Much better!

SplashScreen

Disclaimer
This process worked for me. Your mileage may vary. This information is provided as is without any implied warranty of fitness for any purpose. I am not responsible for corrupted Visual Studio installations or registry hives nor for any other problems that may arise as a result of using these steps. USE AT YOUR OWN RISK.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Tools ,

Serialize SQL parameters

March 15th, 2010

Convert a collection of SQL parameters into a name:value string suitable for writing to a log.

/// <summary>
/// Serializes a collection of
/// <see cref="System.Data.SqlClient.SqlParameter"/>s.
/// </summary>
/// <param name="parameters">
/// The collection of parameters to serialize.
/// </param>
/// <returns>
/// A <see cref="System.String"/> that contains the parameter values.
/// </returns>
public string SerializeSqlParameterCollection(
    SqlParameterCollection parameters)
{
    StringBuilder sb = new StringBuilder();
    foreach (SqlParameter parameter in parameters)
        sb.Append(
            String.Format("{0}:{1} ",
                parameter.ParameterName, parameter.Value));
    return sb.ToString();
}

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

.NET Framework, Programming, Snippets , , ,

What’s new in the .NET Framework 4?

March 12th, 2010

This article gives a great overview of the new features that are coming in the next version of the .NET framework.

http://msdn.microsoft.com/en-us/library/ms171868(v=VS.100).aspx#core_new_features_and_improvements

I’m very excited for April 12th 2010.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Uncategorized

Http Modules

February 18th, 2010

The .NET framework provides several mechanisms for extending the behaviors of web pages and other endpoints. One such technique is the http module. Modules are often either overlooked as a solution or are considered too heavyweight or scary for use. This is unfortunate as they are a powerful item in the ASP.NET development toolbox.

An http module is a single unit of code that is executed as part of the web request pipeline. When a web request is received, the list of registered modules are afforded the opportunity to inject themselves at several stages in the execution pipeline. Each module has the opportunity to inspect or modify parts of the request before or after it is processed. This makes them a powerful mechanism for attaching custom behaviors. Modules also have a flexible activation model as they can be attached or detached via configuration allowing them to be enabled or disabled at will without affecting a production site.

The full source code for this example can be found here.

How to Create an HttpModule
The ASP.NET Module type is in the Web category under the Add New Item dialog.

241@229_tmp6C6D

Remove the default sample code that is included in the template. The LogContext event handler is implemented in the template for demonstration purposes but is not used in this example. Your class should now look similar to the following:

using System;
using System.Web;

namespace ModuleWebApp
{

    ///

    /// Custom http module.
    /// 

    public class MyNewModule : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() {}

        ///

        /// Initializes the module.
        /// 

        /// <param name="context">The application context.</param>
        public void Init(HttpApplication context)
        {

        }

        #endregion

    }
}

Initializing the Module

Modules perform work by registering handlers for events in the request execution pipeline such as BeginRequest and EndRequest. It is within the event handlers that they perform their task. In the example below, the Init method is used to register handlers for the BeginRequest and EndRequest events.

///

/// Raised when the module is initialized.
/// 

/// <param name="context">The application context.</param>
public void Init(HttpApplication context)
{
    context.BeginRequest += new EventHandler(context_BeginRequest);
    context.EndRequest += new EventHandler(context_EndRequest);
}

Implementing the Event Handlers and Finishing the Module

Next provide implementations for the event handlers. This example module is going to calculate and display the time it takes to execute a page within the application. The code example below is for the completed module class. It contains the following changes:

  • Declaration of a dictionary of stopwatches that stores the execution timers.
  • Implementation of the BeginRequest and EndRequest handlers to start and stop the timers.
  • Instantiation of the dictionary of timers in the Init method.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Web;

namespace ModuleWebApp
{

    /// <summary>
    /// A custom http module used to time request execution.
    /// </summary>
    public class RequestTimer : IHttpModule
    {

        #region IHttpModule Members

        public void Dispose() { }

        /// <summary>
        /// Raised when the module is initialized.
        /// </summary>
        /// <param name="context">The application context.</param>
        public void Init(HttpApplication context)
        {
            _timers = new Dictionary<Guid, Stopwatch>();

            context.BeginRequest += new EventHandler(context_BeginRequest);
            context.EndRequest += new EventHandler(context_EndRequest);
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Raised when the request begins.
        /// </summary>
        /// <param name="sender">The source of the event; the <see cref="System.Web.HttpApplication" />.</param>
        /// <param name="e">An <see cref="System.EventsArgs"/> that contains event data.</param>
        protected void context_BeginRequest(object sender, EventArgs e)
        {
            Guid timerId = Guid.NewGuid();
            Stopwatch timer = new Stopwatch();
            _timers.Add(timerId, timer);

            HttpContext.Current.Items.Add(EXECUTION_TIMER_KEY, timerId.ToString());

            timer.Start();
        }

        /// <summary>
        /// Raised when the request ends.
        /// </summary>
        /// <param name="sender">The source of the event; the <see cref="System.Web.HttpApplication" />.</param>
        /// <param name="e">An <see cref="System.EventsArgs"/> that contains event data.</param>
        protected void context_EndRequest(object sender, EventArgs e)
        {
            string timerId = HttpContext.Current.Items[EXECUTION_TIMER_KEY] as string;

            if (String.IsNullOrEmpty(timerId))
                return;

            Stopwatch timer = _timers[new Guid(timerId)];
            if (timer == null)
                return;

            timer.Stop();

            double elapsedSeconds = (timer.ElapsedMilliseconds) / (double)1000;

            HttpContext.Current.Response.Write(
                String.Format(
                    "Request executed in {0} seconds ({1} ticks).",
                    elapsedSeconds.ToString(),
                    timer.ElapsedTicks.ToString()));
        }

        #endregion

        #region Fields

        /// <summary>
        /// The collection of execution timers.
        /// </summary>
        private Dictionary<Guid, Stopwatch> _timers;

        #endregion

        #region Constants

        private const string EXECUTION_TIMER_KEY = "__ExecutionTimer_Id";

        #endregion

    }

}

Some of the concepts used here are beyond the scope of this discussion. Research the Stopwatch class for more information on how to use timers. See the HttpContext class to learn more about request and response objects.

Registering the Module

The final step is to register the module so that it is instantiated and executed on every request. This is done via the web.config file. The <system.web> section contains an <httpModules> section. The registration configuration line for the module should be added to the <httpModules> section as shown below:


	
	
		
		
    
	

That’s it! Running the web application should display the default.aspx page, which now shows the execution time in elapsed seconds (and ticks). This information is displayed at the end of every web request so it works on every page in the system. If you inspect the context_EndRequest handler you can see the following lines:

HttpContext.Current.Response.Write(
	String.Format(
		"Request executed in {0} seconds ({1} ticks).",
		elapsedSeconds.ToString(),
		timer.ElapsedTicks.ToString()));

The HttpContext class exposes the current Request and Response. These are the http request and response that are received from and sent to the client respectively. The execution time was displayed on the page because this handler wrote to the response object after the request had finished executing. The timer was started when the request started and stopped when the request ended. The time taken for the page to performing its processing and the request to finish is then displayed in the response. It is in this way that modules interact with all requests in the system and provide global level behaviors that are attached via configuration.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

.NET Framework, ASP.NET, Programming , ,

Android Emulator Problems in Eclipse

September 9th, 2009

I’ve recently been playing with the Android SDK using Eclipse 3.5 as a development environment.  I coded up the Hello World sample and all was progressing smoothly.  However, I then coded my own project and after a couple of runs the Android emulator simply refused to initialize.  I would always get the same error message about how the runtime had requested to terminate the emulator in an unexpected way.  A few short Googles later and it seemed as though I was not alone in experiencing this problem.

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application’s support team for more information.

I tried rebooting my machine but to no avail as well as completely cleaning out my project.  It seemed that several people had even tried uninstalling and reinstalling the Android SDK without success.  It was at this point that I remembered I’d switched some of the emulator settings right around the time that the failure started to occur.  A little investigation showed that I’d added support for an 8MB  SD card to my virtual device in an attempt to more closely emulate the G1 that I own.  I quickly adjusted the settings back to their defaults and the emulator started functioning again.  I’m hopeful that with more experience I’d have been able to diagnose the problem via logging output or a more detailed debug mode.  As it is right now I’m something of a newbie to Android development so I just figured that some temporary files for the emulator were borked.

Every so often I seem to need to do this sort of thing to remind myself of the age old truth.  If software starts to break without any clear indication of why, it’s most likely due to something seemingly innocuous that the developer intentionally changed.  Always question your own actions first. :)

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Android, Programming , , ,

Mathematical Notation on the Web

August 27th, 2009

I’ve recently been researching ways of displaying math equations online. To my surprise I have found that the packaged options for doing this are quite limited, especially on the Microsoft technology stack. There is fairly good coverage for Java and in the form of php and perl scripts, but very little natively for the .NET framework. As usual there are several formats for storing equations, including OMML from Microsoft, a recommendation from W3C called MathML and what is best described as the lingua franca in the form of LaTeX.

image001

Native Browser Support
Several google searches showed that I was not alone in this search. However, most of the solutions I found came with caveats about which browsers they would work with and required the installation of additional software on client machines in order to work. Installing additional software on client machines defeats the purpose of providing a browser-based experience and in some environments isn’t even an option. I needed to find something that would work all modern browsers without requiring changes on the client.

Internet Explorer – MathPlayer
Design Science (who originally created the Equation Editor that is now part of Microsoft Office) offer a product called Math Player. Math Player is an ActiveX control that renders MathML equations within Internet Explorer. It provides good accessibility support, is free for non-commercial uses, and as ActiveX controls go it was a painless installation. However, because it is an ActiveX control is requires a client installation and only works in IE. Furthermore, the player only seemed to work for pages with the .xhtml extension that declared that XHTML doctype and exhibited some strange visual artifacts if either the MathML or containing page were not formatted correctly.

FireFox MathML Support
FireFox has made some good progress towards natively supporting MathML. However, at present it does not contain a full solution and instead requires downloading the latest nightly build and the installation of several fonts.

Chrome MathML Support
Despite being widely requested, Chrome does not natively support MathML. I could not find conclusive information either way as to whether MathML support is on the Chrome development roadmap.

For the next part of my research I’m going to look into LaTeX as it really seems to be the de facto standard from a tools and community support perspective. I have seen several examples, including WikiPedia that stores equations and diagrams in LaTeX format and then renders them to images on the fly as part of the page. That sounds like it could be a good way to go.

Post to Twitter Post to Yahoo Buzz Post to Delicious Post to Digg Post to Facebook Post to Reddit Post to StumbleUpon

Internet , , , , , , ,