Wednesday, August 31, 2011

JavaScript: The good parts

If there is one book about JavaScript I recommend reading, it’s JavaScript: The good parts. It was a real eye opener for me and brought back the love for this misused but beautiful language.

cat[1]

I really like the book size, especially if you compare it with the full JavaScript reference book. It makes you wonder how much bad parts there are in JavaScript… Knipogende emoticon

Tuesday, August 30, 2011

Error message in IIS 7.5: HTTP Error 401.2 – Unauthorized

IIS is really great. But sometimes you get an error message without any clue how to fix it. When I was testing an ASP.NET MVC website on my Windows 7 64-bit machine, I got the following error:

HTTP Error 401.2 – Unauthorized

You are not authorized to view this page due to invalid authentication headers.

After trying to change almost every possible setting in IIS I finally found the root cause of the issue. My default installation of IIS was running without the Windows Authentication module installed. As my website was expecting windows authentication, it was not unexpected to see this error. After enabling this feature in the list Windows Features, everything worked!

image

Monday, August 29, 2011

Web.config transform for all config files

If you did some web development in .NET you probably know the web.config transform feature. This allows you to link config transforms to your web.config. For example if  you make a web.debug.config it can contain all the changes you want made specific for your debug environment. Unfortunately this feature is only supported for web.config files out-of-the-box.

So what if you want to transform your app.configs, or any XML file? Sayed Ibrahim Hashimi and Chuck England bring you the solution with this Visual Studio Extension called SlowCheetah XML Transforms.

An overview of the features:

  • Added tooling to desktop project to create XDT transforms
  • Ability to transform
    • app.config for desktop projects based on build configuration
    • any XML file to the output folder based on build configuration
  • Added tooling to enable previewing XDT transforms
  • For web projects you can easily transform other XML files during package/publish

You can find more information at the following places:

Friday, August 26, 2011

Windows Azure Pricing Update

Beginning October 1, 2011, Microsoft will make two pricing related updates to the Windows Azure Platform.

First, the price of extra small compute will be reduced by 20 percent. Additionally, the compute allocations for all of the offers will be simplified to small compute hours. Additionally, current Introductory Special offer customers and customers who sign up for this offer prior to October 1 will receive both 750 extra small compute hours and 750 small compute hours for the months of August and September.

Details about this pricing update can be found at http://blogs.msdn.com/b/windowsazure/archive/2011/08/15/announcing-simplified-data-transfer-billing-meters-and-swappable-compute-instancess.aspx and some extra comments at http://www.zdnet.com/blog/microsoft/microsoft-to-cut-its-low-end-windows-azure-cloud-pricing/10343.

Thursday, August 25, 2011

Validating your WCF messages

For a project I needed to validate incoming WCF messages against an XSD.  After a few minutes I discovered the following MSDN article about Message Inspectors containing exactly the information I needed: http://msdn.microsoft.com/en-us/library/aa717047.aspx.

It shows a sample implements a basic client and service message validation mechanism that validates incoming messages against a set of configurable XML Schema documents. This sample is part of the  Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4.

Wednesday, August 24, 2011

Free tools for .NET developers

As a developer, I’m always looking for tools that make my life easier and improve my productivity. Last week I discovered this list(135784_.NET_Free_Dev_Tools-table v6_080111_0) with over 50 free tools.

It contains a some of the most popular and useful free software development tools available. The vast majority of the tools listed in the table are geared toward .NET development, but there are a few others thrown in for those who are doing cross-platform development.

50 tools are listed in nine categories that represent a cross-section of the types of tools most widely available:

  • Code-generation/editing/templates
  • Content management systems (CMSs)
  • Controls/Components
  • Data access and Object-Relational Mapping (ORM)
  • Documentation & Project Management
  • Performance Analysis/Management
  • Software Configuration Management/Version Control
  • Testing and Debugging
  • Visual Studio add-ins

Tuesday, August 23, 2011

Fluent NHibernate Error

Last week I was spending some time comparing Fluent NHibernate with the new code mapping feature in NHibernate 3.2.

However, no matter what I tried, I always got the same error message. The error was happening in the CreateSessionFactory method and returned the following information:

An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
Could not compile the mapping document: (XmlDocument)
persistent class FluentNHibernate.Model.Product, FluentNHibernate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null not found
Could not load file or assembly 'FluentNHibernate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.

After losing almost all my hair, I finally discovered what caused the problem.  I had named the project FluentNHibernate and that was causing the mapping to fail. Renaming the assembly to something else fixed it.

Stupid mistake…

Monday, August 22, 2011

Building WIF enabled .NET 4 Web applications: Potentially dangerous request

When integrating Windows Identity Foundation in your web applications probably one of the first errors you will see is the following:

RequestError

In the description of the error is stated that you can solve the error by adding the following configuration to your web.config:

<httpRuntime requestValidationMode="2.0" />

This solves the issue indeed but reverts the validation mode back to the ASP.NET 2.0 version. A better solution is to create and register your own RequestValidator for WIF.

public class WIFRequestValidator : RequestValidator
{
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
validationFailureIndex = 0;

if (requestValidationSource == RequestValidationSource.Form && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal))
{
SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(context.Request) as SignInResponseMessage;

if (message != null)
{
return true;
}
}

return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}

}

You can then register the WIFRequestValidator in the web.config:

<httpRuntime requestValidationType="SampleApp.Security.WIFRequestValidator,SampleApp"/>

Sunday, August 21, 2011

Integrating ADFS and the Windows Azure Access Control Service

Integrating ADFS with the Windows Azure Control Service(ACS) is not that hard but requires a long list of steps and actions. While searching for some clues I found the following blog post: http://blogs.msdn.com/b/willpe/archive/2010/10/25/windows-authentication-adfs-and-the-access-control-service.aspx

It contains all the information you need to setup federation between your on-premise Active Directory domain and ACS. A must read!

Friday, August 19, 2011

Prevent jqGrid from autoloading

The default behaviour of the jqGrid control is that it starts loading your data if you open up your page. But what if you don’t want this? How can you prevent the jqGrid from autoloading?

We solved it by setting the datatype to 'local'.  To force the loading of data afterwards, you can change datatype to 'json' or 'xml'  by using  .jqGrid(‘setGridParam’,{datatype:’json’}) method and then call the trigger("reloadGrid") method.

Thursday, August 18, 2011

WCF: Get the operation name within a Message Inspector

For logging purposes I needed to get the operation name of the called WCF service and the content of the message.

How can you get this done?

Important to notice when you look at the code is that I created an attribute and implement both the IDispatchMessageInspector and IServiceBehavior interface. This allows me to register this message inspector by just adding the attribute on top of my WCF service class.

/// <summary>
/// When applying this attribute to a service contract,
/// the input and output messages will be logged.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MessageLoggingBehaviorAttribute : Attribute, IDispatchMessageInspector, IServiceBehavior
{
#region IDispatchMessageInspector Members

/// <summary>
/// Will be executed after a request is received.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="channel">The channel.</param>
/// <param name="instanceContext">The instance context.</param>
/// <returns></returns>
/// <exception cref="System.Configuration.ConfigurationErrorsException">Throws a configuration exception if the environments don't match.</exception>
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
LogMessage(ref request);
return null;
}

/// <summary>
/// Will be executed before the reply is send.
/// </summary>
/// <param name="reply">The reply.</param>
/// <param name="correlationState">State of the correlation.</param>
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
LogMessage(ref reply);
}

#endregion

#region IServiceBehavior Members

/// <summary>
/// Adds the binding parameters.
/// </summary>
/// <param name="serviceDescription">The service description.</param>
/// <param name="serviceHostBase">The service host base.</param>
/// <param name="endpoints">The endpoints.</param>
/// <param name="bindingParameters">The binding parameters.</param>
public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}

/// <summary>
/// Applies the dispatch behavior.
/// </summary>
/// <param name="serviceDescription">The service description.</param>
/// <param name="serviceHostBase">The service host base.</param>
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
{
foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
{
epDisp.DispatchRuntime.MessageInspectors.Add(new MessageLoggingBehaviorAttribute());
}
}
}

/// <summary>
/// Validates the specified service description.
/// </summary>
/// <param name="serviceDescription">The service description.</param>
/// <param name="serviceHostBase">The service host base.</param>
public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
{
}

#endregion
}

Inside the AfterReceiveRequest and BeforeSendReply methods I call the LogMessage method passing the message object as a reference. Inside the log message I extract the operation name from the incoming headers, do a little bit of service location to get an IMessageLogger instance and invoke the log method in a separate task.

private void LogMessage(ref Message message) 
{
var action = OperationContext.Current.IncomingMessageHeaders.Action;
var operationName = action.Substring(action.LastIndexOf("/")+1);

var messageLogger = IoC.Container.Resolve<IMessageLogger>();
var messageContent = message.ToString();
Task.Factory.StartNew(() => messageLogger.Log(operationName, new List<string> { messageContent })); 
}

And as a last step I add this attribute to my service class.

[MessageLoggingBehavior]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class AanbiederService : IAanbiederService
{

Wednesday, August 17, 2011

Mapping a Dictionary in NHibernate

For one of my projects, our end-users went crazy and asked for a dynamic fields feature which allows them to add and remove some extra fields on every entity. This is actually quite easy to implement with NHibernate.

Let’s first have a look at the entity(this is a simplified version):

public class File
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IDictionary<string, string> Attributes { get; set; }
}

And the corresponding mapping file (didn’t had time to look at the code mapping yet):

<class name="File" table="Files">
<id name="Id">
<generator class="native"/>
</id>
<property name="Name"/>

<map name="Attributes" table="FileAttributes">
<key column="FileId"/>
<index column="AttributeName" type="System.String"/>
<element column="Attributevalue" type="System.String"/>
</map>
</class>

And that’s all you need to do. This will create  2 tables, one table(Files) with the File properties and one table(FileAttributes) with the extra values.

Anyone who knows how to do the same thing with Entity Framework?

Tuesday, August 16, 2011

Deploying a Windows Azure Project from TFS 2010

As a big believer of Continuous Integration and Continuous Deployment systems, I’m always looking at new ways to get my applications build and roll-out in an automated way. So the same thing is true for our cloud service projects. I wanted to make the deployment to Windows Azure a part of TFS build process.  I looked around on the Internet and found the following great library: http://deploytoazure.codeplex.com/

DeployToAzure allows automating deployment of Windows Azure project and making it a part of TFS 2010 build process without using PowerShell and Azure Management CmdLets.
Solution includes:

  • a set of custom workflow actions wrapping Azure Management API operations such as GetDeployment, GetOperationStatus, NewDeployment, RemoveDeployment and SetDeploymentStatus;
  • helper actions such as FindPackageAndConfigurationFiles, LoadCertificate and WaitForOperationToComplete;
  • designer activity DeployToAzure implementing deployment logic ;
  • reusable build definition template.

    Build Definition Template

    There are some extra steps required on your build server to get the activity up and running. I recommend the following article for a step-by-step guide: http://www.koltovich.com/blog/DeployingAzureProjectFromTFS2010BuildServer.aspx.

    Friday, August 12, 2011

    ASP.NET MVC JSON strings

    Although JSON is a great and simple format, I’m not a big fan of the way dates are represented.  If you have a look at a JSONResult in ASP.NET MVC you’ll probably see some data like this:

    {“result”:[{"ProductId":"21329023","OrderDate":"\/Date(1296824894700”}]}

    You’ll see that the Date is:

    \/Date(1296824894700)\/

    Not very JavaScript friendly. We tried a lot of different approaches in getting something more useful back from our action results(including just using strings instead of datetimes). In the end we decided to use the  jQuery’s dataFilter property. The dataFilter function is used to sanitize a response from a web server.  We ended up with the following small jQuery code:

    $.ajaxSettings.dataFilter = function (data, type) {
    if (type === 'json') {
    data = data.replace(/\/Date\((.*?)\)\//gi,
    function (fullMatch, $1, $2, $3) {
    try {
    return $1 + new Date(parseInt($2.substr(6))).toUTCString() + $3;
    }
    catch (e) { }
    return $1 + $2 + $3;
    });
    }
    return data;
    };


    This method uses a regular expression to look for the various elements that represent a Date in Microsoft JSON serialization format. The resulting date is reformatted to a human readable string. This format can be understood by other JavaScript components like for example the jQuery jqGrid.



    Anyone with a better alternative?

    Thursday, August 11, 2011

    ASP.NET MVC 3 ModelBinding Localization: incorrect date

    One of the great features of ASP.NET MVC is modelbinding. It automatically converts data coming from your form, route data, query string parameters etc… into parameters on your action methods. However we noticed one problem. Imagine you have the following action method

    public ActionResult PlaceOrder(DateTime orderDate) 
    { 
    ... 
    }

    The problem that we noticed is that  MVC is converting our datetime to MM/dd/yyyy although our users are setting dates through the date format dd/MM/yyyy. For example, submitting a call to the action with a string '03/02/2011' results in a DateTime of  '02/03/2011'.

    We were able to solve this issue by adding a globalization section to our web.config. The modelbinder picks this up and uses the correct date format.


    <system.web>    
    <globalization uiCulture="nl-BE" culture="nl-BE" />
    </system.web>

    Wednesday, August 10, 2011

    Windows Azure Platform Training Kit - August Update

    And to complete the list of updates, Microsoft published an update of the Windows Azure Platform Training Kit.

    August 2011 Update
    The August 2011 update of the training kit includes the following updates:

    • [Updated] Labs and Demos to leverage the August 2011 release of the Windows Azure Tools for Microsoft Visual Studio 2010
    • [Updated] Windows Azure Deployment to use the latest version of the Azure Management Cmdlets
    • [Updated] Exploring Windows Azure Storage to support deleting snapshots
    • Applied several minor fixes in content

    Tuesday, August 9, 2011

    Windows Azure Tools for Visual Studio 2010 - August 2011 Upgrade

    Last week the Windows Azure time did not only announced the availability of the Windows Azure Storage Analytics feature but also released Windows Azure Tools for Visual Studio 2010 - August 2011 Upgrade.

    Some features that are included are:

    • Profiling the application running in Windows Azure.
    • New ASP.NET MVC 3 web role template.
    • Multi-configuration files in one cloud project.
    • More validation in the service package and deployment phase.
    Download and Install

    The easiest way to install the upgrade is by using the Web Platform Installer which can be found here. The WebPI will download some dependency packages besides, such as the latest Windows Azure SDK, ASP.NET MVC 3 for Windows Azure, etc.

    ASP.NET MVC 3 Web Role

    When creating a new cloud project you now have a  new ASP.NET MVC 3 Web Role template available. This template already added all the required  assemblies related to MVC3 and set the Copy Local = True by default.

    Multiple Service Configurations

    Under the cloud project we can find that there are two service configuration files (CSCFG) which are:

    • ServiceConfiguration.Cloud.cscfg
    • ServiceConfiguration.Local.cscfg

    The Multiple Service Configurations feature makes it easier to switch between the local emulator and the real cloud environment. With two configuration files enabled, we can choose which one will be the service configuration file when locally debugging, packaging and deploying. 

    New Package and Publish Window

    Previously we choose to package or publish our windows azure project by selecting the radio button in the Publish window. In this upgrade the package and publish had been totally separated. In the context menu of the windows azure project we can create a package by using the Package menu, and use the Publish menu to deploy the application directly to the cloud.

    More Validation

    Because of the differences between the local emulator and the real cloud environment, deploying a Windows Azure project can be a trial-and-error process.  With the new tools update, Visual Studio helps us to validate our project and detect some common mistakes(like not setting Copy Local=True, connection to a local database, etc…).

    Powered by ASP.NET Universal Providers

    The ASP.NET Universal Providers extends the Session, Membership, Roles and Profile support to SQL Compact Edition and SQL Azure, which means as a developer, we can implement the business logic regardless which backend database we are using. More information in Scott’s blog post.

    Go try it out yourself!

    Monday, August 8, 2011

    Microsoft announced Windows Azure Storage Analytics

    Last week Microsoft released  Windows Azure Storage Analytics. This feature offers developers and operations the ability to track, analyze, and debug usage of Windows Azure Storage (Blobs, Tables and Queues). You can use this data to analyze storage usage to improve the design of your applications and their access patterns to Windows Azure Storage. Analytics data consists of:

    • Logs
      • Provide trace of executed requests for Blobs, Tables and Queues
    • Metrics
      • Provide summary of key capacity and request statistics for Blobs, Tables and Queues

    The official announcement can be found here: http://blogs.msdn.com/b/windowsazure/archive/2011/08/03/announcing-windows-azure-storage-analytics.aspx and Steve Marx talked about some of the new features here:http://blog.smarx.com/posts/playing-with-the-new-windows-azure-storage-analytics-features and even created a sample application: http://storageanalytics.cloudapp.net.

    Friday, August 5, 2011

    Improve your Daily Scrum meetings

    Normally when you are doing  Scrum, you have a Daily Scrum meeting. The idea is that you have a daily meeting where you basically determine how the work is progressing and if divine intervention is required to keep things progressing.

    The goal is to provide a transparency where anyone can see what exactly the team is up to.

    The basic format of a scrum meeting is pretty simple. Each person on the team says three things:

    1. What did I do since our last meeting
    2. What am I doing until our next meeting
    3. What is impeding me

    Last week I was reading this post by John Sonmez about how these questions are too vague and can easily evolve to the following conversion:

    “I continued to work on backlog X, I’ll continue to work on backlog X today.”

    This is of course not very useful and a pure waste of time. I noticed that our own Scrum meetings were also evolving in this direction, so I took John Sonmez advice and tried replacing the 3 topics in a Scrum report with these:

    1. What did I commit to doing yesterday and did I or did I not meet that commitment. If not, why not.
    2. What will I commit to getting done today.
    3. What is impeding me that can be improved by bringing it up in this meeting.

    This immediately changes the whole conversation and forces us to commit every day over and over again AND be truthful to ourselves realizing that we sometimes didn’t succeed in fulfilling these commitments.

    Thursday, August 4, 2011

    Visual Studio Database Project Error: User has an unresolved reference to Login

    After creating a Database Project in Visual Studio and importing all database objects, we got one error:

    “SQL03006: User: [x] has an unresolved reference to Login [X]”

    If I double click on the error, it takes me to a CREATE USER statement in one of the files. The problem is that the LOGIN that it's referencing is a SERVER object, not a DATABASE object and your can't run server based SQL commands in a database project type.

    How can you solve this?
    • Right click on your solution and choose Add -> New Project. For the project type select "SQL Server 2008 Server Project."
    • Do a schema compare against the server project and get it all synchronized.
    • Go back do your database project and right click on References and "Add Database Reference" and select your server project.
    • That’s it!

    What you can also do is turn off schema checking (Tools->Options->Database Tools->Schema Compare->SQL Server, then the Object Type tab) for anything user or security related since that is usually done by a DBA.

    Wednesday, August 3, 2011

    CleanProject: Share your .NET code in a clean way

    How many times have you wanted to send a project to a friend or upload it to a web site like MSDN Code Gallery only to find that your zip file has lots of stuff that you don't need to send in it making the file larger than it needs to be.


    And then if you forget about removing Source Control bindings whoever gets your project will be prompted with errors about Source Control. This is no longer a problem, thanks to CleanProject.

    Clean Project is a utility that cleans Visual Studio project directories so you can quickly upload or email a zip file with your solution.

    More info at http://blogs.msdn.com/b/rjacobs/archive/2011/07/24/clean-project-cleans-visual-studio-solutions-for-uploading-or-email.aspx

    Tuesday, August 2, 2011

    WCF: Keyset does not exist exception

    When testing a newly developed WCF Service, the webservice call fails with a  CryptographicException including the following message:

    "Keyset does not exist"

    This is not the most helpful error but some googling around revealed that issue was caused because the IIS user didn’t had access to the private key for the webservice certificate.

    You can solve this by following these steps...

    1. Start -> Run -> MMC
    2. File -> Add/Remove Snapin
    3. Add the Certificates Snap In
    4. Select Computer Account, then hit next
    5. Select Local Computer (the default), then click Finish
    6. On the left panel from Console Root, navigate to Certificates (Local Computer) -> Personal -> Certificates
    7. Right click on your certificate -> All Tasks -> Manage Private Keys
    8. Change the private key security settings.

    Monday, August 1, 2011

    Tools for the paranoia

    The moment you start diving deep into web security, your live will change forever. Possible vulnerabilities appear everywhere in your web application and you don’t know where to start.

    So here are some free security tools/sites that help you on the right track:

    The Open Web Application Security Project (OWASP) is a 501c3 not-for-profit worldwide
    charitable organization focused on improving the security of application
    software. In their web site, you almost could find every piece of information
    regarding security.

    A practical process we could follow to make our software more secure.

    Burp Suite is an integrated platform for performing security testing of web applications. Its
    various tools work seamlessly together to support the entire testing process,
    from initial mapping and analysis of an application's attack surface, through
    to finding and exploiting security vulnerabilities.

    DOMinator is a Firefox based software for analysis and identification of DOM Based Cross Site
    Scripting issues
    (DOMXss).

    Dom Snitch is a Chrome based software for analysis and identification of DOM Based Cross Site
    Scripting issues
    (DOMXss).

    Web Application Configuration Analyzer (WACA) analyzes server configuration for security best practices
    related to General Windows, IIS, ASP.net and SQL server settings.

    CAT.net is a binary code analysis tool that
    helps identify common variants of certain prevailing vulnerabilities that can
    give rise to common attack vectors such as Cross-Site Scripting (XSS), SQL
    Injection and XPath Injection