I had the pleasure of presenting at the SA Dev workshop on 27 July 2011.Thanks to everyone who attended and please continue to support the local communities.

My discussion was based on Web application UI testing with open source tools and Visual Studio Testing tools. More specific I was covering AutoTest.Net for C# unit testing, QUnit for JavaScript testing and Web Tests and Load Tests in Visual Studio 2010.

Here is the links to my slides and demo application:

Web UI Testing Slides

World of Football Demo Application

Any feedback is welcome and thanks again!

Cheerio!

I recently worked on a project where I developed an WCF web services that is exposed via  https and net.tcp. The web services does all the database calls and business logic. Here are some lessons or tips for developing in WCF with net.tcp.

When I use the net.tcp channel to communicate to the web service I often get the following error:

The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:01:00'.

This is the default error message that you will get from WCF if something went wrong but the WCF channel does not know exactly what error occurred.

What to do when you receive this message.

  1. Increase the ReceiveTimeout and SendTimeout on the binding that is used by your web service to 5 min. The other timeout properties default values are 99.9% always correct. The 5 min is very big and will usually eliminate actual timeout issues.
  2. The usual suspects for the error is MaxBufferSize, MaxBufferPoolSize, MaxReceivedMessageSize, MaxArrayLength default size (65536) is to small. Increase them by adding a 0 at the end (655360) to see if the error disappear. Then by small increments reduce the size to find the correct value.
  3. If your web service method returns an big message or generic array or list with a big items count and big object graph you have to increase the value of the property MaxItemsInObjectGraph in the dataContractSerializer element. You need to create a Service Behaviour (Service side) and Endpoint Behaviour (Client side) with the dataContractSerializer element. You will then see the MaxItemsInObjectGraph property.
  4. To increase your communication between service and client you can switch the TransferMode in the binding from Buffered to Streamed.
  5. When you call the web service from an .Net client please avoid calling your code inside a using statement. Rather use try-finally where you can call close on the client object and if the communication channel faulted you can call abort on the client object.

These lessons will hopefully make your net.tcp development experience easier. If you have any further tips or lessons please leave a comment.

Cheerio!

Here is my talk that I presented at Devs4Devs. Thanks to Microsoft for the opportunity and thanks to the guys who attended.

At the bottom is the links to my presentation and sample code. Before you can use the sample you need to setup Windows Server AppFabric Cache and use the AdventureWorks Database.

Another note that the web service gets deployed to IIS when you build the project.

Here the links:

AdventureWorks Database

http://msftdbprodsamples.codeplex.com/

Sample Application

http://dl.dropbox.com/u/4406115/Devs4Devs%202011/AdventureService.zip

Presentation Slides

http://dl.dropbox.com/u/4406115/Devs4Devs%202011/WCF%20AppFabric%20Cache.pptx

Any feedback or questions are welcomed. Until the next talk!

I was busy going through some SQL Adapter walkthroughs in BizTalk 2010 and something very strange happened.

I was setting up my SQL Adapter, not the WCF SQL Adapter, and I come to the wizard screen where I need to select between Select or Stored procedure options.

I happily decided on the Select option. In the next screen you get a text area to write your SQL statement. Mine was just a simple select from a small table. I click the Next button and bang the whole wizard dialog disappeared. No SQLService.xsd was generated. I was so confused and though I did something wrong. I went over the steps like a crazy man.

Finally I restarted Visual Studio 2010 IDE and try again. After the restart everything just worked. I still don’t know why this happens. I don’t know if it is Visual Studio IDE or the SQL Adapter Wizard issue.

Lessons Learned – If something goes wrong in Visual Studio IDE for no reason then just restart the IDE and try again!

Cheerio!

With all the controversy about Reflector going commercial. People had to start looking for other solutions. You know that RedGate tools are very expensive.

So, the first tool I want to show you is ILSpy from SharpDevelop. This is a new tool and that means development is in progress. It follow Reflector’s principle of keeping it simple. Here is a screenshot:

ILSpy

ILSpy Features

  • Assembly Browsing
  • IL Disassembly
  • Saving of resources
  • Search for types/methods/properties
  • Hyperlink-based type/method/property navigation
  • Base/Derived types navigation
  • Navigation History

ILSpy Roadmap

  • Improve the decompiler
  • Assembly Lists
  • Find References
  • Improve search performance
  • Save Assembly as C# Project
  • Debugger
  • Bookmarks
  • Extensibility via addins
  • Find Usage (of type/method/property)

The only thing that is short coming is all those nice plugins that Reflector had. I believe the authors of those plug-ins will soon port them over to ILSpy. As soon as ILSpy provide the extensibility via addins. Please download the tool and provide feedback.

On another note if you are using Resharper. In Resharper 6 that is currently under development you will get a decompiler. Go and check out the following article on JetBrains site: Resharper 6 Bundles Decompiler, Free Standalone Tool to Follow

Cheerio!

I’m going tell you the perfect developer  laptop environment setup. Does not matter if you are a Linux or Windows developer. Maybe Mac user can also find this interesting.

I’m mainly a .Net developer. Sometimes I dabble in Node.js (So Cool!) on Ubuntu. I also use Ubuntu for using Git. My main technology focus for this year is ASP.Net MVC, SharePoint 2010 and Node.js. I sometimes use BizTalk as well.

Firstly let’s discuss my hardware requirements. I need the following laptop spec:

I’m going to use this laptop to setup the minimum Ubuntu OS with VMWare or Virtualbox on top. I’m going to create development VM images on the external hard-drive that will use that nice USB 3.0 performance.

Hardware in Detail

Intel Core i7 logo as of 2009

The Intel Core i7 CPU has great benefits such as 4 Cores with Hyper Threading. Including Intel Turbo Boost Technology and Intel HD Graphics. This CPU will provide enough horsepower to run multiple VMs.

The 12GB Ram is necessary for being able to run multiple VMs. As an example, SharePoint 2010 requires 8GB Ram to run and running Visual Studio for development can easily consume 4GB Ram.

The 32GB SSD Drive is the main hard drive on which Ubuntu and the virtual applications are running. SSD gives you very high IOPS. You don’t need allot of capacity to run the minimum installation of Ubuntu.

The 17” Screen resolution is just a personal choice that give you enough screen real estate for development.

The Nvidia Geforce 500M GPU provide some nice features where certain graphic intense application will benefit from. The virtual applications started to support 3D acceleration inside the VMs. A side interest for me is also the ability to develop with Nvidia Cuda and OpenCL. Nvidia also provide the Optimus technology that intelligently optimize the GPU for better battery life.

500GB plug & play

The Lacie 500GB USB 3.0 drive is where all my VMs will be saved. The drive run at 7200 rpm and can deliver a transfer rate of up to 110MB/s via the USB 3.0 interface. The 500GB size is more than enough. You can get an additional external 2TB drive to backup the VMs.

Minimum Ubuntu Installation

Firstly go and download the minimum Ubuntu installation CD ISO. You can install it via cd-rom or USB device. Install Ubuntu as required by following the installation guide. At the end of the installation you be given the command prompt inside Ubuntu. Make sure you are connected to the internet via a network cable. This is required to download the additional packages.

Now we want to enable some of the fancy Ubuntu features, because we don’t want to be in the command prompt for ever. So here is what we are going to install.

  • Minimal Gnome
  • Wireless Networking
  • Chrome Browser
  • Ubuntu Theme
  • VirtualBox
  • VMware Player

Type the following to install the minimal gnome. This will install a graphical environment.

sudo apt-get install gnome-panel gdm gnome-terminal

Type the following to install Wireless Networking. This will give you a battery monitor and a icon to configure wireless networking. Additionally you get the hibernate button on the shutdown menu.

sudo apt-get install network-manager network-manager-gnome gnome-power-manager hibernate

Let’s install the Chrome browser. Type the following.

sudo apt-get install chromium-browser flashplugin-installer

The default gnome theme looks ugly. Type the following to enable the Ubuntu theme.

sudo apt-get install ubuntu-artwork

After that I would recommend you run the following commands.

sudo apt-get update

sudo reboot

The laptop will firstly make sure it has all the updates and after that we reboot the laptop. After the reboot you will get the login dialog that you use to login to the desktop. Once you on the desktop open a terminal so that we can install Virtualbox or VMWare player. The virtualization technology that you choose is up to you. I will show both.

Firstly I will recommend that you install the Build Essentials on Ubuntu. Some packages require that the build essentials are install before the packages can install.

sudo apt-get install gcc build-essentials

Lets Virtualize – VirtualBox

VirtualBox

Type the following to install VirtualBox. In the terminal type:

sudo gedit /etc/apt/source.list

Add the following VirtualBox repository

deb http://download.virtualbox.org/virtualbox/debian maverick contrib

Now let’s add the public key of VirtualBox to the system.

wget –q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc –O- | sudo apt-key add -

Update the package database.

sudo aptitude update

Now to install VirtualBox type the following magic command.

sudo apt-get install virtualbox-4.0

After VirtualBox has installed you might want to install the dkms package.

sudo apt-get install dkms

Lets Virtualize – VMware Player

Image representing VMware as depicted in Crunc...Lets start installing VMWare Player. Go to the VMware player download page and download the binaries. Now we need to give the VMWare bundle executable privileges. Type the following in terminal where the VMware bundle exist.

chmod +x VMware-Player*.bundle

gksudo bash ./VMware-Player*.bundle

After these commands a installer window will pop up. Just follow the wizard guide. This was now quick and easy.

Installation Summary

At this stage all the required software is installed for you to get started with creating VMs. Here is a list of some additional software you might want to install on Ubuntu.

  • 7-zip
  • Blowfish
  • VLC-Player

Just remember that you want to keep your Host OS as small as possible and to use as little possible memory. I would recommend that you format the external drive to ext 4 file system. It provides very nice performance for the VMs.

I hope you see the benefits of using VMs for your development environments. With this setup you can go crazy with creating VMs and you can easily backup your VMs en data. If you have any suggestions to improve this setup, please let me know.

Cheerio!

Enhanced by Zemanta

Today I want to show you how to develop an authentication system with JSON using ASP .Net MVC 3.0 and WCF.
Firstly I want to discuss the system design. I’m using Asp .Net MVC 3.0 framework to publish Html views to the client browser and for defining pretty URLs in the project. There is no business logic in the MVC framework. I define all my business rules in an WCF Service that only respond to JSON requests.  I’m using JQuery from my Html pages to query the web services for my business data.
Asp MVC WCF Json Design
You might ask yourself why I would decide on this design?
Benefits:
  • Clear separation of concern.
  • Smaller request and response data transfers.
  • Very Scalable  System ( Quickly move web services to Windows Azure ).
  • Dynamic Html Views Design.
Negatives:
  • JSON data is plain text.
  • Require SSL for secure and encrypted data transfer.
I hope you understand the benefits and negatives. There are more benefits and negatives that can be added. SSL is very important to be enabled when using this approach for authentication. Otherwise the user’s password will be available when transferred to the server.
Authentication Code Example:
Download the code to follow: JQueryLogin.zip
I created the default Asp .Net MVC 3.0 project with unit test project included. For this blog I did not do any unit testing. A nice challenge for you! In the solution there are three projects. JqueryLogin project, is the MVC web project. JqueryLogin.WebService project, is the WCF service that will handle JSON requests and business logic. JqueryLogin.Contracts project, is the WCF contracts that is defined for each request and response.
In the MVC web project I use the Razor View Engine. I also clean-up the code to just provide Views with no logic in the controllers. Especially go and look at the AccountController. I did not touch any views that is created by the template. Also I added the necessary JavaScript files that is required to do Ajax requests and create dynamic Html views.
In the _Layout.cshtml I added a bit of special JavaScript resolve function to help resolve URLs in my other JavaScript files. I got the original code from another blog (Forgot where?) but fixed it for MVC 3.0.
<script type="text/javascript">
    Url = function () { }

    Url.prototype =
        {
            _relativeRoot: "@Url.Content("~/")",

            resolve: function (relative) {
                var resolved = relative;
                if (relative.charAt(0) == '~') resolved = this._relativeRoot + relative.substring(2);
                return resolved;
            }
        }

    $Url = new Url();
</script>

With this function I will be able to resolve URLs like this in JavaScript:
window.location.href = $Url.resolve("~/Home/Index");

Now lets look at the other JavaScript files. The file ajax.js has some infrastructure and setup code that will help me with the requests to the web service. The User.js file is where the main logic is to register, sign-in and sign-out users to the web application. 

At the top of the file I define two object Register and SignIn with properties that match the same properties as the RegisterRequest Contract and SignInRequest Contract. The code that follow is where I define where the web service is that needs to be called. The web service methods are called after the Html form pass validation on the submit. Here is the code for sign-in and sign-out of the user:
/// <reference path="jquery-1.4.1.js" />
/// <reference path="jquery.validate.min.js" />
/// <reference path="ajax.js" />

var SignIn = {
    UserName : '',
    Password : '',
    RememberMe: ''
};

var UserServiceURL = "../WebService/UserService.svc/";
var UserServiceProxy = new serviceProxy(UserServiceURL);

$(document).ready(function () {
    $("#loginForm").validate({ submitHandler: function (form) {
        SignInUser();
    }
    });

    $('a[href="/Account/LogOff"]').click(function () {
        SignOutUser();

        return false;
    });

});

function SignInUser() {
    blockDisplay();
    var request = BuildSignInRequest();

    UserServiceProxy.invoke({
        serviceMethod: "SignIn",
        data: { request: request },
        callback: function (response) {
            $('#status').empty().html("<strong>Success: " + response.Message + "</strong>");

            $.unblockUI();
            window.location.href = $Url.resolve("~/Home/Index");       
        },
        error: function (xhr, errorMsg, thrown) {
            OnPageError(xhr, errorMsg, thrown);

            $.unblockUI();
        }
    });

    return false;
}

function SignOutUser() {
    blockDisplay();

    UserServiceProxy.invoke({
        serviceMethod: "SignOut",
        data: null,
        callback: function (response) {
            $('#status').empty().html("<strong>Success: " + response.Message + "</strong>");

            $.unblockUI();
            window.location.href = $Url.resolve("~/Home/Index");       
        },
        error: function (xhr, errorMsg, thrown) {
            OnPageError(xhr, errorMsg, thrown);

            $.unblockUI();
        }
    });

    return false;
}

function BuildSignInRequest() {
    SignIn.UserName = $('input[name="UserName"]').val();
    SignIn.Password = $('input[name="Password"]').val();
    SignIn.RememberMe = $('input[name="RememberMe"]').val();

    if (SignIn.RememberMe === "on") {
        SignIn.RememberMe = true;
    }
    else {
        SignIn.RememberMe = false;
    }

    return SignIn;
}

WCF Web Service Setup

Now let look at the web service to get all of this working. Firstly you define you web service in an interface file like IUserService.cs. In the UserService.svc mark up you have to change the factory to be able to handle JSON requests and responses.
<%@ ServiceHost Language="C#" Service="JqueryLogin.WebService.Service.UserService" Factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" %>

In the UserService implementation you have to set AspNetCompatibilityRequirements attribute. This will allow for cookies to be set for when the user is authenticated.
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class UserService : IUserService
{
    // Implementation Code
}

The implementation of the user authentication can be found in the AccountMembershipManager class and the FormsAuthenticationManager class.  The last part that is required for the service is the service binding. For this service I use wsHttpBinding.
<services>
  <service behaviorConfiguration="DefaultBehavior" name="UserService">
    <endpoint binding="wsHttpBinding" contract="JqueryLogin.WebService.IUserService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
  </service>
</services>

Show Some Results

I use Chrome Browser for debugging. I will show you the traced request and response output for Sign-in and Sign-out of user. I underline in red in the images the important details to notice.

SignIn Request – Click to Enlarge

SignInRequest

SignIn Response – Click to Enlarge

SignInResponseContent


SignOut Request – Click to Enlarge

SignOutRequest

SignOut Response – Click to Enlarge

SignOutResponseContent

Summary

The original idea of using JSON and WCF for creating a responsive website came when I read Chris Love blog entries “Creating a WCF Service for JSON” and “WCF and JQuery Using JSON”. The original JavaScript infrastructure come from him. As you can see that JSON allow for speedy web development and responsive web pages. JQuery just make it so easy to create Ajax calls.

Hope you enjoy this entry and any feedback or questions are welcome.

Cheerio!

Disqus