Friday, September 30, 2011

ASP.NET MVC: Performance tips

Although there are a lot of different ways to optimize your ASP.NET MVC web applications, some are cheaper then others. Here are some very simple tips that still can make a significant difference:
Run in Release mode
Always make sure that your application is compiled in Release mode and that your web.config file is configured with <compilation debug="false" />. Use the web.config transformations feature to automatically change this value in release mode.
Use only the View Engines that you need
As you probably know the MVC framework supports multiple view engines. This means that each time MVC is trying to find a view it’s searching through all these view engines. In MVC 3 two view engines are registered by default (WebForms and Razor). So if you use only one view engine, remove the ones you are not using:
protected void Application_Start() 
{ 
	ViewEngines.Engines.Clear(); 
	ViewEngines.Engines.Add(new RazorViewEngine()); 
}
Use the CachedDataAnnotationsModelMetadataProvider from ASP.NET MVC Futures
In the ASP.NET MVC 3 Futures you can find a little gem called the CachedDataAnnotationsModelMetadataProvider. For using this provider, just open global.asax file and add the following line in the Application_Start method, 


ModelMetadataProviders.Current = new CachedDataAnnotationsModelMetadataProvider();


Avoid passing null models to views
Don’t pass in a null model to a view that uses strongly-typed html helpers (such as Html.TextBoxFor). Strongly-typed html helpers such as Html.TextBoxFor(m => m.Name) will try to emit the value of the model using the provided expression. However when something along the expression chain is null a NullReferenceException will be thrown when the expression gets evaluated. MVC’s expression evaluator catches the exception but on a page with multiple such html helpers the cost of the exception adds up. You can avoid that cost by always passing an empty instance of the model to the view:


public ActionResult Insert() 
{ 
	return View(new Product()); 
}

Uninstall URL Rewrite if you don’t use it
When performing URL generation (for example via a method like Html.ActionLink) in some cases MVC checks to see if the currently requested URL has been rewritten by the URL Rewrite module. If that is the case the result is processed so that it correctly matches the URL requested by the client. The act of checking if a URL has been rewritten has a non-trivial cost (because it involves checking server variables). ASP.NET MVC 3 checks to see if URL Rewrite is turned off and can cache that fact thus avoiding the need to inspect server variables for each request. If URL Rewrite is turned on MVC will have to check server variables even if no rewriting happened for a particular request so if you are not using URL Rewrite you should turn it off.

Thursday, September 29, 2011

Writing Powershell scripts inside Visual Studio: PowerGUI Visual Studio Extension

You want to write Powershell scripts inside Visual Studio? Thanks to the  PowerGUI Visual Studio Extension this becomes very easy.

Here is the list of available features:

  • PowerGUI Console Tool Window
  • PowerShell Project Type
  • IntelliSense support through a custom PowerShell editor
  • Syntax highlighting and script analysis
  • Supports PowerGUI settings
  • Supports PowerGUI imported modules
  • Supports PowerGUI Snippets
  • PowerShell debugging
  • PowerGUI Console Tool Window
  • PowerShell Project Type

screenshot.png

Wednesday, September 28, 2011

JScript Editor Extensions for Visual Studio

While browsing through some Channel 9 videos, I discovered the following session:

Damian Edwards, a member of the ASP.NET team at Microsoft talks in this episode about the JScript Editor Extensions(Microsoft calls it JScript because Oracle owns the rights on the name JavaScript) and about what can be expected in Visual Studio vNext.

This JScript Editor Extensions bundles the following functionality:

  • Brace Matching

Adds support for automatically highlighting the matching opening or closing brace to the one currently at the cursor. Supports matching parenthesis: (), square brackets: [], and curly braces: {}. Braces in strings, comments and regular expression literals are ignored.

  • Outlining / Cold-folding

Adds support for automatically creating outlining regions for JScript blocks. Blocks are detected via opening and closing curly braces. Braces in strings, comments and regular expression literals are ignored.

  • Current Word Highlighting

Adds support for highlighting all instances of the word currently at the cursor.

  • IntelliSense Doc-Comments <para> Support

Adds support for the <para> element in JScript IntelliSense doc-comments to allow display of new lines in IntelliSense tooltips, e.g.

function hello(name) {
/// <summary>A great function
/// < para>Some info on a new line</para>
/// </summary>
/// <param name="name" type="String">The name to say hello to</param>
return "hello " + name;
}

Download the extension here: http://visualstudiogallery.msdn.microsoft.com/872d27ee-38c7-4a97-98dc-0d8a431cc2ed?SRC=Home

And if you want to know more about the improvements in the Visual Studio 11 JavaScript editor: http://www.asp.net/vnext/whats-new#_Toc303354500

Tuesday, September 27, 2011

The type or namespace name 'Linq' does not exist in the namespace 'System.Data'

Last week I was creating a demo application to show some ASP.NET features when I kept getting the following error:

“The type or namespace name 'Linq' does not exist in the namespace 'System.Data'”

I had the System.Data.Linq DLL referenced in my application and verified through the Object Browser that this namespace was indeed part of this assembly. Although a very stupid error it took me some time to figure out why it wasn’t working….

I was finally able to solve the issue by adding the following line in my web.config:

<add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

Monday, September 26, 2011

JavaScript weirdness

Interested in some of the curiosities inside the JavaScript programming language? Have a look at Mike Taulty’s blog where he walks through a lot of (little known) JavaScript features.

  • JavaScript OMG! #1 to #5
    • OMG #1 – Optional Semi-Colons
    • OMG #2 – JavaScript Type System
    • OMG #3 – JavaScript and Underflow, Overflow, Div Zero
    • OMG #4 – JavaScript and RegExp
    • OMG #5 – Truthy and Falsy
  • JavaScript OMG! #6 to #10
    • OMG #6 – The Global Object
    • OMG #7 – “Expando Objects”
    • OMG #8 – Wrappers
    • OMG #9 – Type Conversions
    • OMG#10 – Object to Primitive Conversions
  • JavaScript OMG! #11 to #15
    • OMG #11 – Variable Scope and Hoisting
    • OMG #12 – Bitwise Operators
    • OMG #13 – Equality and Strict Equality
    • OMG #14 – “use strict”
    • OMG #15 – Magic of Short-Circuiting ANDs and Truthy/Falsy
  • JavaScript OMG!: #16 to #20
    • OMG#16 – Function Arguments
    • OMG #17 – Nested Functions
    • OMG #18 – Arrays versus Lists
    • OMG #19 – Function Invocation Context & Strict Mode
    • OMG #20 – Nested Functions & Invocation Context
  • JavaScript OMG #21 to #25
    • OMG #21 – Everything’s a Function
    • OMG #22 – array.sort() won’t sort numbers “correctly”
    • OMG #23 – parseInt() needs help
    • OMG #24 – Callbacks and Scope
    • OMG #25 – Function Literals Create Functions

Sunday, September 25, 2011

How to connect to tfspreview.com from Visual Studio 2010?

After registering an account on TFS Preview, I immediately wanted to add some code and start playing with it. However just entering [your account name].tfspreview.com  in Team Explorer had no effect.

So what do you need to do to get this working?

First you need Visual Studio 2010 with SP1 applied. Secondly you need to install KB2581206.

After installing the hotfix, a connection can be made through the “Add Team Foundation Server” dialogue in VS2010:

  • URL of Team Foundation Server = [your account name].tfspreview.com
  • Connection Details:
    • Path = tfs
    • Port = 443
    • Protocol = HTTPS

image

You’ll get a connection dialog to connect through Live Id:

image

That’s it!

image

Saturday, September 24, 2011

What after BUILD?

c056e72a-e7e6-4aa1-b2ad-4e2265933726[1]

After 2 weeks of vacation I’m working myself through all the information that was released at the Microsoft BUILD conference. If you couldn’t be there(like most of us) certainly start with the 2 keynotes(Keynote #1 & Keynote #2). This will inspire you enough to browse through all the other sessions(http://channel9.msdn.com/Events/BUILD/BUILD2011). 

One nice thing I noticed is that if you have an HTML5 enabled browser, the videos are shown using the HTML 5 <video> tag giving you the option to change the play speed(most sessions are still watchable at 1.4x speed). Unfortunately a full screen option is not available(yet), but you can always switch back to the Silverlight player.

Continue your journey by downloading and experimenting with

Friday, September 9, 2011

Design Patterns: Null Object

‘If you have a hammer, everything looks like a nail’. My favorite pattern today is the Null object pattern, so I’m applying it everywhere Glimlach
But what’s this pattern exactly and why is it so useful? Let’s consider the following code :
class DiscountRepository
{
    public Discount GetDiscountFor(Order order)
    {
    }
}

public abstract class Discount
{   
   public abstract int Calculate(Order order);
}

We have an abstract class that represents our object and a repository.

Now what if you have an order for which there is no discount information available in the database. You always have to check for null and having this all over the place make the code less readable.

public void ProcessOrder(Order order)
{
    var discount=_repository.GetDiscountFor(order);
    if (discount != null)
        discount.Calculate(order);
}

I don’t like this code.  So let’s apply the Null Object pattern to make the above code prettier and less error-prone. All we need to do is to implement the abstract class(you can achieve the same result by using an interface) one more time but this time we will do it inside our Discount class like this :

public abstract class Discount
{
    public abstract int Calculate(Order order);
        
    public static readonly Discount NULL = new NullDiscount();
    private class NullDiscount : Discount
    {            
        public override int Calculate(Order order) { return 0; }
    }
}

Our ProcessOrder now looks like this :

public void ProcessOrder(Order order)
{
    var discount=_repository.GetDiscountFor(order);
    discount.Calculate(order);
}

And our GetDiscountFor method looks like this :

public Discount GetDiscountFor(Order order)
{
    if(/* Not Found */)
        return Discount.NULL;
    else
        /* The db record */
}

Thursday, September 8, 2011

Impress your colleagues with your knowledge about… private builds

One of the little known features of Team Foundation Server 2010 are private builds (a.k.a. “Buddy Builds”).A Private build is just like a Gated check-in build, but without the automatic check-in and enforcement.

It’s a way to manually queue a Gated check-in build and provide a Shelveset name. It provides another sanity check beyond F5. You specify a private build by selecting a Shelveset to merge with the latest source code when queuing a build.

PrivateBuild

You queue a private build if you want to build the changes that you have put into a shelveset. You can use a private build (also known as a "buddy build") to validate changes to your code before you check it in. By performing a private build of your changes before you check them in, you can reduce the chance that they will break any builds that your team runs regularly (such as the nightly build).

From the MSDN website:
How Private Builds Differ from Public Builds

The results of a completed private build differ from a completed public build in the following ways:

  • A private build resembles a gated check-in build in that you are building code that includes changes in a shelveset. However, your changes are not automatically checked in for you after a private build as they are after a gated check-in build.

  • The following build process parameters are presumed to be False and therefore have no effect, regardless of the setting specified in the build definition:

    • Label Sources

    • Create Work Item on Failure

    • Associate Changesets and Work Items

  • In Build Explorer, the completed build appears next to the following icon: ms181722.Icon_BldPrivateBuild(en-us,VS.100).gif

  • The completed build is named by using the format Build N where N is a unique integer value. This format differs from that of public builds, which you specify by using the Build Number Format parameter.

  • For each build definition, you specify a separate (and optionally different) retention policy to limit the number of completed private builds that are stored in the system.

Queue a Private Build
  1. In Team Explorer, click the appropriate team project.

  2. On the Build menu, click Queue New Build.

  3. In the Build definition list, select a build definition.

  4. In the What do you want to build? list, select Latest sources with shelveset.

  5. Perform one of the following steps:

    • If you already have a shelveset, type its name into the Shelveset name box, or click the ellipsis (…) button to search for the shelveset.

    • If you want to put some pending changes from your workspace into a shelveset and then build those changes, click Create.

  6. Click Queue.

Wednesday, September 7, 2011

Team Foundation Server Training Kit + TFS vNext

Microsoft released a new version of the Team Foundation Server Training Kit.

“The Introduction to Team Foundation Server 2010 Training Kit includes presentations, hands-on labs and demos designed to help you get acquainted with the features of Team Foundation Server (TFS) 2010. This Training Kit contains several demos and hands-on labs that require some additional setup. For instructions, please see the Setup document.”

Download available here: http://www.microsoft.com/download/en/details.aspx?id=27152.

And while you are looking at the current TFS features, also have a look at the following posts by Brian Harry about what’s coming in TFS vNext:

Tuesday, September 6, 2011

Unity: Interception Call Handler called multiple times

For a project we are using Unity 2.0 interception with policy injection to create and manage our NHibernate session. Therefore we created a custom ICallHandler in combination with a HandlerAttribute.
[AttributeUsage(AttributeTargets.Method)]
    public class NHibernateUnitOfWorkHandlerAttribute : HandlerAttribute
    {
        private bool _createTransaction;

        public NHibernateUnitOfWorkHandlerAttribute(bool createTransaction=false)
        {
            _createTransaction = createTransaction;
        }

        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new NHibernateUnitOfWorkHandler(Order,_createTransaction);
        }
    }


    public class NHibernateUnitOfWorkHandler : ICallHandler
    {
        public NHibernateUnitOfWorkHandler(int order,bool createTransaction)
        {
            this.Order = order;
            this.CreateTransaction = createTransaction;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            IMethodReturn result=null;

            try
            {
                using (var uow = DataFactory.CreateUnitOfWork(TransactionMode.Explicit))
                {
                    if (CreateTransaction)
                    {
                        using (var tx = uow.CreateTransaction())
                        {
                            result = getNext()(input, getNext);
                            if (result.Exception == null)
                                tx.Commit();
                            else
                                tx.Rollback();
                        }
                    }
                    else
                    {
                        result = getNext()(input, getNext);
                    }
                }
            }
            catch (Exception ex)
            {
                result = getNext()(input, getNext);
                result.Exception = ex;
            }
            return result;
        }

        public int Order { get; set; }
        public bool CreateTransaction { get; set; }
    }


Problem is, that this policy injection call handler executed twice when we expect that it only executes once. It took us some time to figure out what caused the problem. The reason was that the InterceptionExtension was registered twice:
  • One time explicitly through registration by using the AddNewExtension<T> method on the Unity container.
     
  • One time implicitly by registering the EnterpriseLibraryCoreExtension which also adds the Interception extension.
After removing the explicit registration everything worked fine. To further improve the solution we started to use the AddNewExtensionIfNotPresent<T> extension method which is available in the Enterprise Library Shared Assembly.

Monday, September 5, 2011

Windows Workflow Foundation Activity Pack for Windows Azure

Last week Microsoft released the Workflow Foundation (WF) Activity Pack for Windows Azure. The package is also available via NuGet(Package name=WFAzureActivityPack) and through their CodePlex page.

“The WF Activity Pack for Windows Azure CTP 1 is the first community technology preview (CTP) release of Windows Azure activities implementation based on Windows Workflow Foundation in .NET Framework 4.0 (WF4) and Windows Azure SDK. The implementation contains a set of activities based on Windows Azure Storage Service and Windows Azure AppFabric Caching Service, which enables developers to easily access these Azure services within a workflow application.”

The current release includes the following Workflow activities:

For Windows Azure Storage Service - Blob

  • PutBlob creates a new block blob, or replace an existing block blob.
  • GetBlob downloads the binary content of a blob.
  • DeleteBlob deletes a blob if it exists.
  • CopyBlob copies a blob to a destination within the storage account.
  • ListBlobs enumerates the list of blobs under the specified container or a hierarchical blob folder.

For Windows Azure Storage Service - Table

  • InsertEntity<T> inserts a new entity into the specified table.
  • QueryEntities<T> queries entities in a table according to the specified query options.
  • UpdateEntity<T> updates an existing entity in a table.
  • DeleteEntity<T> deletes an existing entity in a table using the specified entity object.
  • DeleteEntity deletes an existing entity in a table using partition and row keys.

For Windows Azure AppFabric Caching Service

  • AddCacheItem adds an object to the cache, or updates an existing object in the cache.
  • GetCacheItem gets an object from the cache as well as its expiration time.
  • RemoveCacheItem removes an object from the cache.

Friday, September 2, 2011

TFS: Setting a default value for an iteration

Last week I was trying to change the work item type definition so it will set a default value in the iteration path.  But when I tried importing it back with the TFS Power Tools, I always got the following error:

Error importing work item type definition:

TF26062:Rule '<DEFAULT from ="value" value="283" />' is not supported for the field 'System.IterationId'.

It seems like it is not possible to set a default value for the area or iteration path. In the end I solved this by creating a Work Item Template(part of the TFS Power Tools) with a default value for Iteration Path. I really like this approach because I can change the value in the template when a new sprint starts.

image

More about Work Item Templates and their usage:

Thursday, September 1, 2011

JavaScript: Where to start?

JavaScript, you love it or hate it. It’s ubiquitous, useful, powerful and at the same time clunky and confusing. But … there is no way around it.  Sooner or later you’ll have to (re)learn this language. So you can better start today.

Where to get started?

Forget all those bad JavaScript samples out there, instead have a look at  JavaScript Garden, a site created by Ivo Wetzel and Zhang Yi Jiang.

JavaScript Garden is a growing collection of documentation about the most quirky parts of the JavaScript programming language. It gives advice to avoid common mistakes, subtle bugs, as well as performance issues and bad practices that non-expert JavaScript programmers may encounter on their endeavours into the depths of the language.

Add it to your bookmarks!