1

Sql timeout – a trap for young players!

Posted in Asp.Net, Sql Server at December 22nd, 2006 by Gerrod / 1 Comment »

I was talking to one of the guys at work about Sql timeouts. He had a long running operation – about 40 seconds – so to compensate for this, he set the timeout on his connection string to one minute:


<connectionStrings>
  <add name="cs"
    connectionString="Data Source=localhost;Initial Catalog=MyDB;Connection Timeout=60;"
</connectionStrings>

Sure looks OK, but as it turns out, this wasn’t working for him. The reason is actually quite straightforward – the Connection Timeout property is used to specify how long the application will wait to establish a connection to the server before giving up and throwing an exception. In most cases (where connections are properly managed), the connection will be returned almost instantaneously, hence changing this value is usually not required.

Instead, the timeout that he needed to change was the CommandTimeout on the SqlCommand object which was being passed to the database.


  SqlCommand command = new SqlCommand();
  command.CommandTimeout = 60;

As the MSDN doco states, this property "Gets or sets the wait time before terminating the attempt to execute a command and generating an error". And sure enough, once he changed this value to 60, everything was dandy.

4

Best Visual Studio Shortcut

Posted in .Net, Daily Question, Uncategorized at December 22nd, 2006 by Ben / 4 Comments »

A work colleague and I were discussing what we thought the best Visual Studio keyboard shortcut was.
The shortcut had to be a VS one and not that of a third party (eg. Resharper).

We came to the conclusion that Alt-Shift-Enter to enter into and out of Full Screen mode took 1st prize.

The shortcut to save – ctrl-s – is pretty handy too, but we decided this was not unique to VS and was more of a windows common-look-and-feel item.

What’s your favourite VS keyboard shortcut?

Today, I spent some time trying to debug an error I was getting with some of my ASP .Net 2.0 pages.

All of sudden IIS wouldn’t load my pages saying that they did not extend System.Web.UI.Page, when on inspection of the codebehind file I was sure they did.

The problem was that I ran a Resharper 2.0 – Reformat Code (ctrl-alt-f) on my web application with the shorten references item checked. This changed the way in which the page directive worked on the aspx page.

Following is an example that illustrates what the file was originally defined as and what the reformat did to it to cause the application to blow up.

Original syntax


<%@ Page language="c#"
               Codebehind="default.aspx.cs"
               AutoEventWireup="True"
               Inherits="Com.CompanyName.Default"
               EnableSessionState="False"
               EnableViewState="False"%>


  
    Don't use reformat code with shorten references checked.
  
		


Resharper Reformat


Resharper Reformat Code Syntax


<%@ Page language="c#"
        Codebehind="default.aspx.cs"
        AutoEventWireup="True"
        Inherits="Default"
        EnableSessionState="False"
        EnableViewState="False"%>
<%@ Import namespace="System.Web.UI.WebControls"%>
<%@ Import namespace="Com.CompanyName"%>


  
    Don't use reformat code with shorten references checked.
  
				


The reformatted syntax takes the namespace of the Inherits attribute in the Page directive shortening it to “Default” from “Com.CompanyName.Default”. To do this, it has imported the “Com.CompanyName” namespace into the aspx page.

Now because .Net 2.0 defaults non-namespaced elements to the global namespace, the designer file, no longer belongs to the Com.CompanyName namespace however the codebehind page still does.

This causes the conflict throwing the error.

The error message

A trap for young players.

1

Deserialization mythbuster

Posted in .Net, C# at December 14th, 2006 by Gerrod / 1 Comment »

I had always thought that when an object got deserialized (using the default serialization support), the basic process was:

  1. A new object is created using the object’s default constructor
  2. The object’s properties are populated via reflection from the object’s serialized stream

Turns out that’s not true – the constructor is never called! This was a problem for me as I was initializing my NonSerialized variables in the constructor, but after the object was Deserialized and I tried to access them, I was getting a NullReferenceException:


[Serializable]
public class Person {
    private string name;
    [NonSerialized] private IList friends;

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public void AddFriend(string name) {
        friends.Add(name);    // throws NRE after deserialization
    }

    public Person() {
        friends = new List();
    }
}

Turns out that the correct way of doing something like this is to use the OnDeserialized attribute on an initialization method. The attribute requires that the method signature takes a single parameter – a StreamingContext:


[Serializable]
public class Person {
    private string name;
    [NonSerialized] private IList friends;

    public string Name {
        get { return name; }
        set { name = value; }
    }

    public void AddFriend(string name) {
        friends.Add(name);    // no more NRE after deserialization
    }

    [OnDeserialized]
    private void Init(StreamingContext context) {
        friends = new List();
    }

    public Person() {
        Init(new StreamingContext());
    }
}

I’m not sure if this is technically the best way of achieving this, but it works, and besides creating an empty StreamingContext in the constructor (StreamingContext is a struct so you can’t use null), it feels ok to me. Any thoughts?

Sometimes it’s necessary to access a method/property on a Page from the UserControl code.

Eg.

We have a Page that has a label on it. A UserControl is embedded in that page. The UserControl has a DropDownList of values. When the value in the DropDownList is changed, we want the UserControl to change the value of Page’s label to reflect the selected value of the drop down list.

Now because the UserControl is associated with the Page using aggregation and there is no reference back to the Page instance it becomes a little tricky to do this.

We could pass a reference to the label in the UserControl but once we do that, we are creating a tighter coupling between the Page and UserControl thus making it difficult to re-use the UserControl for Pages that don’t have a label that needs modification.

Don’t worry though! The Event Handler (or Observer) pattern is very handy and comes into play to enable a communication mechanism that gets around the coupling problem.

In the UserControl declare a public property that accepts and returns an EventHandler delegate.

Eg.



public class ExampleUserControl : UserControl {

	protected DropDownList automobileTypes;
	private EventHandler automobileChangeHandler;

	public EventHandler AutomobileChangeHandler {
		get { return automobileChangeHandler; }
		set { automobileChangeHandler = value; }
	}

Now call the declared EventHandler at the appropriate execution point.

Eg.



	...
        ...

	private void InitializeComponent() {
 	     this.Load += new System.EventHandler(this.Page_Load);
             automobileTypes.SelectedIndexChanged += new EventHandler(automobileTypes_SelectedIndexChanged);
	}

	private void automobileTypes_SelectedIndexChanged(object sender, EventArgs e) {
		if (AutomobileChangeHandler != null) {
			AutomobileChangeHandler(automobileTypes.SelectedValue, e);
		}

	}

In the Page class create a method to be executed by the UserControl’s event handler. Define the logic that the UserControl’s event is to trigger on the Page object.

Eg.



public class ExamplePage : Page {

	protected Label name;
	protected ExampleUserControl euc; 

	private void ExampleUserControl_Changed(object sender, EventArgs e) {
		name.Text = String.Format("You have selected - {0}", sender as string);
	}

        override protected void OnInit(EventArgs e) {
		InitializeComponent();
		base.OnInit(e);
	}

	private void InitializeComponent() {
		this.Load += new System.EventHandler(this.Page_Load);
		euc.AutomobileChangeHandler += new EventHandler(ExampleUserControl_Changed);
	}

	#endregion
}

Thus allowing a UserControl to trigger events in the page object, without explicitly knowing about the class in which the UserControl resides.

1

Javascript – Inheritance

Posted in Development, Javascript at December 5th, 2006 by Ben / 1 Comment »

There are many ways to perform inheritance using objects in javascript. I recommend reading chapter 3 and 4 from Professional Javascript for Web Developers” to get a full understanding of how the language can be utilized for inheritance.

Below I have listed a hybrid method that incorporates using the call() method and prototype chaining to simulate inheritance that matches closely to how you would use it in a typed language like Java or C#.



function File(name, path) {
	this.name = name;
	this.path = path;
}

File.prototype.getName = function() { return this.name; }
File.prototype.setName = function(name) { this.name = name; }

File.prototype.getPath = function() { return this.path; }
File.prototype.setPath = function(path) { this.path = path; }


Using the prototype keyword, means that the method is assigned to the File class. Without it, the function would be a new instance for every instantiated File object.

The following subclass utilizes the call() method which in this case is analogous to the super keyword in java or the base keyword in C#.

It then uses prototype chaining to assign/copy all the prototype functions of File to itself, before defining further functions that relate specifically to itself.


function ExcelFile(name, path, numberOfWorksheets) {
	File.call(this, name, path); // equivalent to calling base(name, path)
        this.numberOfWorksheets = numberOfWorksheets;
}

// this is how you inherit all the prototype values of the base class.
// ensure to place this before defining new functions as this will blat out
// all prototype functions currently declared for the class.
ExcelFile.prototype = new File(); 

ExcelFile.prototype.getNumberOfWorksheets =
	function() { return this.numberOfWorksheets; }

ExcelFile.prototype.setNumberOfWorksheets =
	function(numberOfWorksheets) { this.numberOfWorksheets =
							numberOfWorksheets; }


The following shows how you would instantiate your classes and prove that the inheritance worked.


var file = new File("RecipeDetails.txt", "c:/temp");
var excelFile = new ExcelFile("Business.xls", "c:/temp", 6);

alert(excelFile instanceof File);
alert(excelFile instanceof ExcelFile);
0

Retrieving documents from the web in .NET

Posted in .Net at December 1st, 2006 by Gerrod / No Comments »

My current project requires me to fetch pages from the web and analyse their contents. I’ll be the first one to admit that I didn’t have a clue how to do this – it’s not exactly your everyday type of operation, after all.

Still, I knew that the XmlReader class allows you to plug in a URL at construction time, so I figured that it must be doing exactly this type of operation. Trolling through MSDN for a while proved fruitless, so instead I decided to just look at the code using Reflector. Bingo!

Actually it turns out to be very easy – the key class is XmlUrlResolver. Once you’ve got that figured out, it’s all pretty self explanatory. For example, here’s a chunk of code that will pull whatever document is at the nominated URL, and return it as a string:


/// <summary>
/// Retrieve the content as a string, from the nominated url
/// </summary>
/// <param name="url">Url to retrieve the content from</param>
/// <returns>String value of the content located at the url</returns>
static private string Get(string url) {
    XmlUrlResolver resolver = new XmlUrlResolver();
    Uri uri = resolver.ResolveUri(null, url);
    using (Stream urlContentStream = (Stream) resolver.GetEntity(uri, String.Empty, typeof(Stream))) {
        using (StreamReader reader = new StreamReader(new BufferedStream(urlContentStream))) {
            return reader.ReadToEnd();
        }
    }
}
1

SQL Compare

Posted in Sql Server at December 1st, 2006 by Gerrod / 1 Comment »

Recently I made the unfortunate mistake of developing against an SQL Server 2005 database server, which I mistakenly thought was an SQL Server 2000 server. I know what you’re thinking, “how could you get that wrong?!” – but the reason was that the server was previously running 2000, and I had forgotten that it was upgraded.

Anyway, this wasn’t really a problem (since I had compatibility level set to 8) – until it came to deploying the updated database. Turns out you can’t export a 2005 backup and restore it onto 2000 – no real surprises there! So my next option was to generate scripts to recreate the database on a SQL Server 2000 server, but guess what – the Generate Scripts tool in 2005 does NOT generate scripts compatible with 2000. Now that was a surprise, given that one of the options actually allows you to specify that the scripts are for Sql Server 2000!

After searching around the net for a solution, I concluded that my best option was to restore an old database backup, and then manually go through and make the changes. Clearly not a good option, since it was very likely that I’d be missing things left right and centre, but what choice did I have?

Lucky for me, a colleague happened to pay me a visit just as I was about to start, and told me that he had had my exact same problem only a few weeks ago. Better still, he had a tool which was effectively a diff/merge tool which worked across database versions. Sweet!

So I checked it out – RedGate’s SQL Compare – and found it an absolute delight to use. It was able to update about 95% of the changes without manual intervention. The other 5% was also a simple change – since SQL Compare had generated a script to do the upgrades, all I had to do was make a few minor tweaks.

My only complaint with SQL Compare is that you can’t tell it not to synchronize/compare extended properties of objects. (Extended properties define stuff like layouts of diagrams, etc). If I could have turned this off, it would have been able to do the entire upgrade without any intervention from me. Still, overall, this is an awesome piece of software, and it gets my highest recommendation.