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!

Today I’m going to show you how to upload documents to a document library in SharePoint 2010 and also to create folders via web services in the document library.

I configured a document library where I want to create folders and store documents. I named it “My Documents Library” located at “http://server/sites/personal/My Documents Library”

Let’s Create Folders

In your .Net project you have to add a service reference to http://server/sites/personal/_vti_bin/Dws.asmx. This is the Document Workspace service.

Here is the code to create a folder in the document library:

  1: // Title of Document Library
  2: string library = "My Documents Library";
  3: 
  4: DwsSoapClient client = new DwsSoapClient();
  5: if (client.ClientCredentials != null)
  6: {
  7:     client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
  8: }
  9: 
 10: try
 11: {
 12:     // Create First Folder
 13:     string createResult = client.CreateFolder(library + "/Folder One");
 14:     Trace.WriteLine("Create Folder Result: " + createResult);
 15: 
 16:     // Create subfolder
 17:     createResult = client.CreateFolder(library + "/Folder One/Folder Two");
 18:     Trace.WriteLine("Create Folder Result: " + createResult);
 19: }
 20: finally
 21: {
 22:     if (client.State == CommunicationState.Faulted)
 23:     {
 24:         client.Abort();
 25:     }
 26: 
 27:     if (client.State != CommunicationState.Closed)
 28:     {
 29:         client.Close();
 30:     }
 31: }

The first thing to watch out for is setting the client credentials on the client proxy. This tells the client to impersonate you to create the folders. You the client need to have the rights to create folders in the document library.


To create folders is very straight forward where you use the CreateFolder method. As you can see you specify the library title and forward slash with the new folder to create. I also show in the code to create subfolders.


Let’s Upload a Document


To upload a document we need to add another service reference to http://server/sites/personal/_vti_bin/copy.asmx. This is the Copy service.


Here is the code to upload a document to the document library:

  1: CopySoapClient client = new CopySoapClient();
  2:             
  3: if (client.ClientCredentials != null)
  4: {
  5:     client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
  6: }
  7: 
  8: try
  9: {
 10:     client.Open();
 11:     string url = "http://server/sites/personal/My Documents Library/Folder One/Folder Two/";
 12:     string fileName = "test.txt";
 13:     string[] destinationUrl = { url + fileName };
 14:     byte[] content = new byte[] { 1, 2, 3, 4 };
 15: 
 16:     // Description Information Field
 17:     FieldInformation descInfo = new FieldInformation
 18:                                     {
 19:                                         DisplayName = "Description",
 20:                                         Type = FieldType.Text,
 21:                                         Value = "Test file for upload"
 22:                                     };
 23: 
 24:     FieldInformation[] fileInfoArray = { descInfo };
 25: 
 26:     CopyResult[] arrayOfResults;
 27: 
 28:     uint result = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
 29:     Trace.WriteLine("Upload Result: " + result);
 30: 
 31:     // Check for Errors
 32:     foreach (CopyResult copyResult in arrayOfResults)
 33:     {
 34:         string msg = "====================================" +
 35:                      "SharePoint Error:" +
 36:                      "\nUrl: " + copyResult.DestinationUrl +
 37:                      "\nError Code: " + copyResult.ErrorCode +
 38:                      "\nMessage: " + copyResult.ErrorMessage +
 39:                      "====================================";
 40: 
 41:         Trace.WriteLine(msg);
 42:         _logFactory.ErrorMsg(msg);
 43:     }
 44: }
 45: finally
 46: {
 47:     if (client.State == CommunicationState.Faulted)
 48:     {
 49:         client.Abort();
 50:     }
 51: 
 52:     if (client.State != CommunicationState.Closed)
 53:     {
 54:         client.Close();
 55:     }
 56: }

Again I set the client credentials to be able to upload documents to the document library. I have to specify the full URL and folder structure on where I want to upload the document too. I also have to append the filename onto the URL to upload the document.


I create a byte[] to simulate document content that will be saved in the document library. The web method that we use to upload a document only accepts an byte[] for content. If you use streams for reading a local file to upload, then you have to convert it to a byte[].


We use the CopyIntoItem method to upload the file. Firstly have to define the filename, the destination URL, file information array and a array for results that is returned.


In the example code I use the fileInfoArray to add document meta data. In the example I just add Description meta data.


When you upload the file the method returns an array of results that you can check if any errors occurred on the server for the document upload.


Hope this helps you and any feedback is welcome!


Cheerio!

This blog entry will show you how to setup SharePoint 2010 on Windows 7. Unfortunately it is not just as simple as to download SharePoint 2010 and say install. You can use SharePoint 2010 Foundation, Full SharePoint 2010 editions and Search Server 2010 Express for the rest of this blog entry.

Step 1:

Download your desired SharePoint 2010 edition. For the rest of this blog I will use SharePoint 2010 Foundation.

Step 2:

If you try to run the SharePointFoundation.exe and select Install SharePoint Foundation you will get the following error:

Setup_Error

You need to enable Windows 7 support. Before doing that we have to extract the SharePoint 2010 setup file to a directory. Go to command prompt and type the following:

Extract_Command

Step 3:

To enable Win 7 support you have to go to C:\SharePointFiles\Files\Setup folder and open config.xml in a text editor. In the file you have to add this line <Setting Id="AllowWindowsClientInstall" Value="True" />. Your file should look like this:

Enable _Win7_Config

Step 4:

Before we run the setup you need to enable IIS on Windows 7. Go to Control Panel->Program and Features->Turn Windows features on or off.

Enable_IIS

The most important features that should be enabled is the Internet Information Services and Microsoft .NET Framework 3.5.1.

A quick solution is to run the following in command prompt: ( Take out the line-breaks for command prompt )

start /w pkgmgr /iu:IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;
IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;IIS-HttpErrors;
IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;
IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-HealthAndDiagnostics;
IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ManagementScriptingTools;
IIS-Security;IIS-BasicAuthentication;IIS-WindowsAuthentication;IIS-DigestAuthentication;
IIS-RequestFiltering;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;
IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-IIS6ManagementCompatibility;
IIS-Metabase;IIS-WMICompatibility;WAS-WindowsActivationService;WAS-ProcessModel;
WAS-NetFxEnvironment;WAS-ConfigurationAPI;WCF-HTTP-Activation;
WCF-NonHTTP-Activation

Step 5:


After IIS is installed we need to install some additional prerequisite packages that is required by SharePoint 2010. Under c:\SharePointFiles run PrerequisiteInstaller.exe.


Required Prerequisite Packages:



Step 6:


After the prerequisite packages are installed, it is recommended to run Windows Update to install the latest patches from Microsoft.


Step 7:


Ok, now you are ready to install SharePoint 2010. Under c:\SharePointFiles run setup.exe and select the option that suite you the best. Most of the time it should be the Standalone option that will install a stand-alone SharePoint 2010 installation with SQL Server Express.


SharePoint_Install_Options


Note: After installing SharePoint 2010 check for the latest patched from Windows Updates.


Step 8:


After successful installation, you are ready to use SharePoint 2010 on Windows 7. Here is the default site that is created with sample data:


Default_Site


The default is accessible via the URL http://machine-name/.  SharePoint takes over the default port 80 on IIS.


Another page that is available is the  SharePoint 2010 Central Administration. Accessible via URL http://machine-name:34078/ Just check in IIS on which port it runs. Otherwise you can all so go to the Start menu->All Programs –> Microsoft SharePoint 2010 Products –> SharePoint 2010 Central Administration.


Central_Admin


For Development you have to follow these additional steps.


Step 9:


Install the SharePoint 2010 SDK. I’m going on the assumption that Visual Studio 2010 is already installed on Windows 7 machine. The SDK provide conceptual overviews, programming tasks, code samples for SharePoint 2010.


Step 10:


Install SharePoint 2010 Guidance. This guidance provides a deep technical insight into the key concepts and issues for SharePoint 2010 solution developers.


Helpful Additional Tools for Development:



With these steps completed you are ready to start developing with SharePoint 2010.


Enjoy SharePoint 2010.


Cheerio!

If you are looking for some introduction material to Microsoft Workflow Foundation 4.0 then here are a couple of links and tips.

Overview:

Windows Workflow Foundation (WF) Overview Wiki
http://social.technet.microsoft.com/wiki/contents/articles/windows-workflow-foundation-wf-overview-wiki.aspx

Videos:

Windows Workflow Foundation (WF) Screencasts:
http://msdn.microsoft.com/en-us/netframework/wf-screencasts.aspx

Endpoint TV screen cast:
http://channel9.msdn.com/shows/Endpoint/

Blogs:

Blogs that I follow for updates and development tips on WF 4.0

Andrew Zhu Blog - http://xhinker.com/

Ron Jacobs - http://blogs.msdn.com/b/rjacobs/

Unit Testing:

WF 4.0 is much more Unit Testing friendly. Ron Jacobs created WF 4.0 Unit Testing Helper library that is available at http://code.msdn.microsoft.com/wfth/

Forum:

Microsoft WF 4.0 Forum - http://social.msdn.microsoft.com/Forums/en/wfprerelease/threads

Using WF 4.0 with WCF 4.0 is one of the greatest experiences I have so far and one powerful toolset to know. These details should get you started with WF 4.0.

After you understand WF 4.0, I suggest you start looking at Microsoft AppFabric technology stack.

Cheerio!

Disqus