.Net Continuous Integration via Jenkins

This post show a simple and effective way to setup a continuous integration server and a way to update a test environment on each commit on a developer branch.

Our domain is a compositions of these elements:

  • .NET Solution (the project)
  • Git repository (Stash)

Target

We want to create e new continuous integration environment using Jenkins to build .NET solutions.

Agenda

  • Jenkins introduction and installation
  • Configure Jenkins
    • Install Plugins
  • Manage Jenkins settings
  • Create a new Job
    • Set Source Control
    • Build Triggers
    • Build: create a custom script in order to create a package that can be deployed
  • Automatically FTP Deploy via Jenkins
  • Automatically run a new “build and deploy” after a commit on the develop branch.

Jenkins introduction and installation

What is Jenkins?

Jenkins is an application that monitors executions of repeated jobs, such as building a software project or jobs run by cron. Among those things, current Jenkins focuses on the following two jobs:

  • Building/testing software projects continuously. In a nutshell, Jenkins provides an easy-to-use so-called continuous integration system, making it easier for developers to integrate changes to the project, and making it easier for users to obtain a fresh build. The automated, continuous build increases the productivity.
  • Monitoring executions of externally-run jobs, such as cron jobs and procmail jobs, even those that are run on a remote machine. For example, with cron, all you receive is regular e-mails that capture the output, and it is up to you to look at them diligently and notice when it broke. Jenkins keeps those outputs and makes it easy for you to notice when something is wrong.

For more details (http://jenkins-ci.org/)

Download Jenkins

Pre-requisite

Before installing Jenkins you must download and install Git.

For the most part, you’ll select command-line setting, with the exception of Git command line stuff. In that case, select “use git from the Windows Command Prompt,” as shown below.

git-install

Now you can install Jenkins.

The install wizard will open the Jenkins web page.

jenkins-home

Configure Jenkins

Install Plugins

Without these required Plugins you will not be able to build and test .NET solutions. In order to add essentials plugins you must go to “Manage Jenkins” > “Manage Plugin”

jenkins-plugin

Required Plugins:
  • The Build Plugin we’ll be using is MSBuild this allows us to build a .NET solution.
  • The GIT Plugin – This plugin allows use of Git as a build SCM.
  • Testing plugin (You’ll need one of these depending on your chosen test framework)
    • MSTest Plugin – This plugin converts MSTest TRX test reports into JUnit XML reports so it can be integrated with Jenkins JUnit features.
    • NUnit Plugin – This plugin allows you to publish NUnit test results.
    • xUnit Plugin – This plugin makes it possible to publish the test results of an execution of a testing tool in Jenkins.
    • Gallio Plugin – This plugin makes it possible to publish Gallio/MbUnit test results.

Tick the check box next to each of the required Plugins and then click the ‘Download now and install after restart’ button.

Optoinal Plugins
  • Green Balls – Changes Hudson to use green balls instead of blue for successful builds. Who doesn’t want Green Balls!
  • Active Directory Plugin – With this plugin, you can configure Jenkins authenticates the username and the password through Active Directory.

Manage Jenkins settings

Go to “Manage Jenkins” > “Configure System”

jenkins-config

Enter and go to the Git section and set the fields with your current Git installation described above.

jenkins-config_git

After that you must config the “MSBuild installations …” (click to open)

jenkins-config_msbuild

jenkins-config_msbuild-config

Please select your own path for MSBuild.exe

Click Save.

Create a new Job

In Jenkins the definition of a build process is called a Job. Jobs are created using the main menu on the Jenkins home page. We’ll create a basic Job that will checkout our source and build the solution.

From the main Jenkins menu, Click the ‘New Item’ link.

jenkins-create-new-job

You now see the New Job configuration page.

Set your own name (Test in this case) and select “Freestyle Project” and select “Ok”

jenkins-new-job

Jenkins will now create the Job workspace on disk and redirect you to the job configuration page.

Next we’re going to checkout our solution from source control and build it. So we first need to give Jenkins details of our source control server.

Set Source Control

For the purpose of this demo we’ll use Git.

Lets setup our Job to grab the source code from this repository. This is done in the” Source Code Management” section of the configuration page.

jenkins-config-job-01

  1. Select the Git radio button.
  2. Provide the git project url ang give the right username/password entry in order to connect Jenkins to the repository.

If can create a new user by clicking the aside “Add” button to do this.

After taht you can change the “Branches to build”. We choose to check-out the develop branch.

Git is now configured and we can move onto Build Triggers.

Build Triggers

We want to trigger a build every time our source code changes; we achieve this by creating a “Build Trigger” which polls our source code repository. When a change is detected a new build is triggered and a new deployable package is generated.

Under the Build Triggers section, tick the Poll SCM checkbox.

jenkins-config-job-02

By clicking on (?) you will read more about the configuration instruction for the “Schedule” field. These are the instruction:

==================================================================================

This field follows the syntax of cron (with minor differences). Specifically, each line consists of 5 fields separated by TAB or whitespace:

MINUTE HOUR DOM MONTH DOW
MINUTE Minutes within the hour (0–59)
HOUR The hour of the day (0–23)
DOM The day of the month (1–31)
MONTH The month (1–12)
DOW The day of the week (0–7) where 0 and 7 are Sunday.

To specify multiple values for one field, the following operators are available. In the order of precedence,

  • * specifies all valid values
  • M-N specifies a range of values
  • M-N/X or */X steps by intervals of X through the specified range or whole valid range
  • A,B,...,Z enumerates multiple values

To allow periodically scheduled tasks to produce even load on the system, the symbol H (for “hash”) should be used wherever possible. For example, using 0 0 * * * for a dozen daily jobs will cause a large spike at midnight. In contrast, using H H * * * would still execute each job once a day, but not all at the same time, better using limited resources.

The H symbol can be used with a range. For example, H H(0-7) * * * means some time between 12:00 AM (midnight) to 7:59 AM. You can also use step intervals with H, with or without ranges.

The H symbol can be thought of as a random value over a range, but it actually is a hash of the job name, not a random function, so that the value remains stable for any given project.

Beware that for the day of month field, short cycles such as */3 or H/3 will not work consistently near the end of most months, due to variable month lengths. For example, */3 will run on the 1st, 4th, …31st days of a long month, then again the next day of the next month. Hashes are always chosen in the 1-28 range, so H/3 will produce a gap between runs of between 3 and 6 days at the end of a month. (Longer cycles will also have inconsistent lengths but the effect may be relatively less noticeable.)

Empty lines and lines that start with # will be ignored as comments.

In addition, @yearly, @annually, @monthly, @weekly, @daily, @midnight, and @hourly are supported as convenient aliases. These use the hash system for automatic balancing. For example, @hourly is the same as H * * * * and could mean at any time during the hour. @midnight actually means some time between 12:00 AM and 2:59 AM.

Examples:

# every fifteen minutes (perhaps at :07, :22, :37, :52) H/15 * * * * # every ten minutes in the first half of every hour (three times, perhaps at :04, :14, :24) H(0-29)/10 * * * * # once every two hours every weekday (perhaps at 10:38 AM, 12:38 PM, 2:38 PM, 4:38 PM) H 9-16/2 * * 1-5 # once a day on the 1st and 15th of every month except December H H 1,15 1-11 *
==================================================================================
Finally we just need to tell Jenkins how to build the solution when changes are detected. This is done via the “Add build step” button under the Build section.

Build: create a custom script in order to create a package that can be deployed

We want to reach this goal: provide a visual studio solution ==> generate a build ==> run tests* ==> create a publish package ==> deploy via ftp.

* not included yet in these guide.

In order to accomplish these steps we start from “Add build step” and in this instance select “Execute Windows batch command”.

jenkins-config-job-03

The publish.bat script in our case make these steps:

  • set path variables for project, destination foldert, etc.
  • build the .NET solution with a specific configuration (Test, Release, etc.)
  • copy the created package into a destination folder in order to be moved via FTP on a specific Test server.
set msBuildDir=C:\Program Files (x86)\MSBuild\12.0\Bin
set slnPath=C:\myProjectSolutionPath
set packagePath=C:\myProjectSolutionPath\Project.Web
set deployPath=C:\DEPLOYED_APPS\ProjectName

rd %deployPath%\CI_Release /S /Q
md %deployPath%\CI_Release

call %msBuildDir%\MSBuild.exe  %slnPath%\myProject.sln /p:Configuration=Release /l:FileLogger,Microsoft.Build.Engine;logfile=Manual_MSBuild_ReleaseVersion_LOG.log

XCOPY %packagePath%\obj\Release\Package\PackageTmp\* /S %deployPath%\CI_Release\

Automatically FTP Deploy via Jenkins

… Coming soon …

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for ‘jquery’. Please add a ScriptResourceMapping named jquery (case-sensitive)

Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

Type: UnobtrusiveValidationMode

Default value: None

Remarks: If this key value is set to “None” [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic. If this key value is set to“WebForms”, ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

 <appSettings>
     <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
 </appSettings>

Manage Session in Asp.Net application

This post illustrate the 3 main steps to manage session in Web Forms application. This is not the only one way to do this, but it’s easy and responsive to a better user experience.

Step 1

In the Global.asax.cs in the Session_Start event add this code:

// Code that runs when a new session is started
if (Context.Session != null)
{
    if (Context.Session.IsNewSession)//|| Context.Session.Count==0)
    {
        string sCookieHeader = Request.Headers["Cookie"];
        if ((null != sCookieHeader) && (sCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
        {
           //if (Request.IsAuthenticated)
           FormsAuthentication.SignOut();
           Response.Redirect(Utility.Costants.PAGES_SESSIONEXPIRED);
        }
    }
}

and also in the Session_End event

Session.Clear();

Step 2

Add this in the web.config

<sessionState
        mode="InProc"
        timeout="30">
      <providers>
        <clear/>
      </providers>
    </sessionState>

Step 3

Create a custom Logout page and add this snippet on the Page_Load

if (User.Identity.IsAuthenticated)
{
    Session.Clear();
    Session.Abandon();
    Request.Cookies.Clear();
    FormsAuthentication.SignOut();
}

Enjoy!

Use reCAPTCHA in ASP.NET

In this post we are going to explain how to use reCAPTCHA in an ASP.NET. application.

It is easy and intuitive to integrate Google’s reCAPTCHA  but you have to pay attention to some “validation” details that we are going to see in the course of the post.

First of all, you need to sign up to get 2 registration keys, a public one and a private one that will have to be used during the integration of this component within the APSX page.

You can download the DLL to be integrated within the site from here.

It is easy to Integrate the library and it can be done by following these steps:

1) Add the library Reference downloaded in VS.

2) Register the dll in the web.config file if you need to reuse the library in several pages

<pages>
   <controls>
      <add tagPrefix="recaptcha" assembly="Recaptcha" namespace="Recaptcha" />
   </controls>
</pages>

Or in the page in which you want to integrate the reCAPTCHA

<%@ Register TagPrefix="recaptcha" Namespace="Recaptcha" Assembly="Recaptcha" %>

3) Put the reCAPTCHA control in a tag <form runat=”server”>

<recaptcha:RecaptchaControl
    ID="recaptcha"
    runat="server"
    PublicKey="your_public_key"
    PrivateKey="your_private_key"
    />

This is what you need to integrate the control within the web application

Everything is fine up to now!

Now let’s see how to solve some problems like the validation of the page and of the reCAPTCHA and especially the hosting security problems.

First, let’s see how to solve the problems related to the hosting servers rights.

As you don’t have the rights in full trust, you can’t invoke the assembly.

The solution to the security problem

You can solve this problem by doing the following things:

  • Download the reCAPTCHA library sources for ASP.NET by checking out from here
  • Open the solution and change the rights in the AssemblyInfo.cs file, like this:
[assembly: AllowPartiallyTrustedCallers()]
  • Fill in and copy the new assembly in your solution ASP.NET.

The validation

To validate the reCAPTCHA control is very easy. Add this code to the button click event that submits the form.

protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
< processate il form >
}
else
{
< visualizzate un errore >
}
}

This code works perfectly if you don’t have validations on other controls.

To overcome the following problem, you have to validate the control Recaptcha in a different way.

Within the same method as above, you have to include this type of validation in order to have the coexistence of the traditional validation on asp.net controls and the recapcha control.

recaptcha.Validate();
if (recaptcha.IsValid)
{
< processate il form >
}
else
{
< visualizzate un errore >
}

And this is it!

Forward parameters from Silverlight Web project to Silverlight project

In “real-world” is really common that your Silverlight application needs some parameters from the relatieve Web project.
If you have the necessity to pass some parameters, never mind.
You can use this trick.
For istance, you need to pass the HttpContex from the Silverlight Web to the relatieve Silverlight project.
You can add in default.aspx page in SL Web this tag:

<param name="initParams" value="username=<%=HttpContext.Current.User.Identity.Name%>" />

Then, you need to add in App.xaml.vb page (inside the constructor) this code

If Not e.InitParams Is Nothing Then
      For Each data As Object In e.InitParams
          Me.Resources.Add(data.Key, data.Value)
      Next
End If

In this way you add this resources to the Resources dictionary in SL project.
Then, at the end, you can retrieve the resource key property to obtain the relatieve value

Dim user As String = App.Current.Resources("username").ToString()

If you need to pass more than one parameter, add in the same tag “initParams” all the parameters you need and separate them with commas.
For example,

<param name="initParams" value="param1=value1,param2=value2" />