Tag Archives: .net

Prevent an Asp.Net Button from triggering a Postback

Sometimes, you want an Asp.net Button to not trigger a postback.

One solution is, don’t use an asp.net button, use an html input or link tag instead. However, you may want to use an asp:XXXButton for consistency with the rest of your page; or it may seem a simple way to make the text on the button localisable (although you can equally achieve that on a plain old html control if you give it an id, a runat=”server” and probably a meta:resourcekey); or you may have other stuff you want to do with it serverside.

To stop an asp.net button causing a postback, do it like this:

<asp:LinkButton id="btnX" OnClientClick="return false;" runat="server"/>

The more likely scenarios is, that you want to run clientside javascript. In that case, put “;return false;” after your javascript call:

<asp:LinkButton id="btnX" OnClientClick="functionToCall();return false;" runat="server"/>

Localising programmatically in asp.net code behind

The usual examples for asp.net localisation are for the aspx markup page, not for the code behind.

In fact localisation, accessing localisation resource files programmatically, in code behind is also dead simple. You use GetLocalResourceObject() like so:

ctrl.Text = (string)GetLocalResourceObject("myCtrlKey.Text");
ctrl.AnotherAttribute = (string)GetLocalResourceObject("myCtrlKey.AnotherAttribute");

Using LocalResource means that for a page called MyPage.aspx, you have created a resource file called MyPage.aspx.resx and/or MyPage.aspx.{culturename}.resx in the special directory App_LocalResource.

If you like GlobalResources instead of local, use the special directory App_GlobalResource
to hold a resource file called MyResourceFileName.resx and call:

ctrl.Text= (string)GetGlobalResourceObject("MyResourceFileName", "myGlobalKey");

as per http://msdn.microsoft.com/en-us/library/ms227982.aspx

For a bit more of an overview of asp.net localisation, the page at http://msdn.microsoft.com/en-us/library/ms227427.aspx should only take you a few minutes to scan.

Switching between Visual Studio .Net and Mono with MonoDevelop

For reasons best not examined too closely I switch between between Mac and PC which, since I earn my crust largely with .Net development, means switching between Visual Studio and MS.Net and MonoDevelop with Mono.

Mono is very impressive, it is not at all a half hearted effort, and it does some stuff that MS haven’t done. But when switching environments, there’s always the occasional gotcha. Here are some that have got me, and some solutions.

Gotcha: Linq Expressions don’t work on Mono

Solution: Add a reference to System.Core to your project.

Question: What version of NUnit is built in to mono?

As of Feb 2011, it’s nunit 2.4.8.

The Object Quote Pattern for Testability of Components with Dependencies

I hereby introduce a very simple no-configuration pattern for making components with dependencies unit testable. Object Quote competes with existing solutions for testability of components with dependencies and is intended to be the simplest possible solution. This will make most sense if you already understand the problem of unit testing components and classes with dependencies.

Existing Patterns for Unit Testability

  • Dependency Injection or Service Location use a DI Container or a Service Locator for runtime configurability. As a side effect, they also provides a solution, albeit rather heavyweight, for test-time mockability
  • The Humble Object Pattern is an approach for codebases built without DI or service locator. A class with dependencies is refactored into two classes, one of which sets up the dependencies on the other, which contains the meat (or logic) of the class. The class containing the logic is then testable.

Neither of these are cost-free. Dependency Injection requires a framework and is best considered as an application-wide architectural pattern that should be used when runtime configuration is required. In that sense it is overkill for most bespoke code where you don’t need to choose at runtime between multiple implementations for an interface, and all you want is test-time mockability.

The humble object is effectively a proposal to rewrite code, albeit minimally. So it has a significant cost to it; and the end result is slightly more complex than the original.

The Object Quote Pattern

is very simple. It requires no framework, and can be applied to existing code for virtually no startup cost.

  1. Merrily write (or read, if it’s already written) your code with hard coded dependencies.
  2. Uncouple the dependencies by quoting the hard-coded references with a “Soq” – a simple object quoter.
  3. In your unit tests, configure the Soq as a Moq Soq.

Behold. You now have decoupled, testable code. Thus:

public class MyClassThatDependsonSomething
	public SomeDependency  D1 { get; set; }

    public MyClassThatDependsonSomething()
        D1 = Soq.Quote( new SomeDependency() );

public class TestExampleCode
    public void Test_something_with_dependencies()
        SomeDependency dummy = new Mock<SomeDependency>().Object;

        var mockSoq = new Mock<Soq>();
        mockSoq.Setup(soq => soq.QuoteImplementation<SomeDependency>(It.IsAny<SomeDependency>()))

        // Act
        var myClass = new MyClassThatDependsonSomething();
        var result = myClass.D1;

        Assert.AreSame<SomeDependency>(dummy, result);

How it works

By default the Soq just returns the object given it.
But when configured for test, the Soq is implemented by your MoqSoq, which returns whatever you’ve configured it to.

Voila. Testable code with no framework needed and no extensive refactoring of existing codebase. You get started with TDD even on legacy code with minimal overhead.

Get the code and a couple of example tests from https://github.com/xcarroll/Soq. Or copy and paste the source — just 12 lines of actual code  — from below.

The Soq Class

On Github: https://github.com/xcarroll/Soq/blob/master/Soq.cs

using System;
public class Soq
        private static Soq instance = new Soq();

        public static T Quote<T>(T instantiatedDependency)
            return instance.QuoteImplementation<T>(instantiatedDependency);

        public virtual T QuoteImplementation<T>(T dependency)
            return dependency;

        public static void ConfigureForTest(Soq testSoq)
            if (!ConfigurationIsEnabled)
                throw new InvalidOperationException(
                 "Test configuration is not enabled.");
            instance = testSoq ?? new Soq();
        public static bool ConfigurationIsEnabled { get { return true; } }