# .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/)

Pre-requisite

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.

Now you can install Jenkins.

The install wizard will open the Jenkins web page.

#### 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”

###### 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”

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

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

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.

You now see the New Job configuration page.

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

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.

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.

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”.

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\

… Coming soon …

# Create a NuGet package for a C# library

In this article we discuss a simple way to create, configure and publish your first c# library through personal NuGet repository.

• Add environment variable path that refer the installed nuget.exe file
• Build your project in Release mode
• Get the “bin” folder path where you can retrieve the project assembly
• Move under your project bin/release folder and copy the generated *.ddl (pay attention: copy only your project assembly file and not all the dependencies) and paste in a new different folder
• In this folder create these two folders:
• lib – contains only the project dlls
• content – contains all the solution content after the build process (Release mode) without the “bin” and “obj” folders
• Open cmd with admin priviledges:
• move under the temp folder where you create the folder at the step above
• enter in the lib folder (> cd lib)
• run > nuget.exe spec MyAssembly.dll
• this creates a Nuspec file
• move the .nuspec file outside the lib folder
• you must now have this configuration inside the folder:
• content
• lib
• MyAssembly.nuspec
• edit the NuSpec file as needed (see the section below)
• then run > nuget.exe pack MyAssembly.nuspec
• a new MyAssembly.nupkg was created.

### Nuspec file configuration


<?xml version="1.0"?>
<package>
<id>MyAssembly</id>
<version>1.0.0</version>
<authors>Tier-1</authors>
<owners>Tier-1</owners>
<projectUrl>http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE</projectUrl>
<iconUrl>http://ICON_URL_HERE_OR_DELETE_THIS_LINE</iconUrl>
<description></description>
<releaseNotes>Summary of changes made in this release of the package.</releaseNotes>
<tags>Tag1 Tag2</tags>
<dependencies>
<dependency id="Newtonsoft.Json" version="7.0.1" />
<dependency id="NLog" version="4.2.1" />
<dependency id="NLog.Config" version="4.2.1" />
<dependency id="NLog.Schema" version="4.2.1" />
</dependencies>
</package>



In the .nuspec file you can configure all the dependencies that you dll requires. In this way the NuGet repository can download the dependencies when a client install your NuGet package.

Now you can provide this package and retrieve via Visual Studio as all the other libraries.

# Windows 10 critical error: Start menu and Cortana doesn’t work

In order to fix the “Start menu and Cortana” error you must do the following steps:

2. Click on File > Run new task
3. Write PowerShell
4. Write this command on PowerShell prompt: “Get-AppXPackage-AllUsers|Foreach{Add-AppxPackage-DisableDevelopmentMode-register”$($_InstallLocation.)\AppXManifest.xml”}”
5. Close the PowerShell window and restart the computer.

# Change SourceTree default editor

Run this command in order to switch the default SourceTree editor. In this case I use Notepad++:

git config –-global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""

# 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>
</appSettings>

# Change Read the Docs Theme

C:\> pip install sphinx_rtd_theme

In your conf.py file:

import sphinx_rtd_theme
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
After that your docs looks like this

# How to use Read the Docs over Windows

In order to configure and use Read the Docs in Windows environment you need to follow these steps:

#### Install Python

Follow the Windows installer for Python.

Complete the installation.

Pay Attention:

Now run the Command Prompt (with Admin privileges). After command prompt window appear, type python and Enter.

If the Python installation was successful, the installed Python version is printed, and you are greeted by the prompt >>>.

Type Ctrl+Z and Enter to quit.

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

Otherwise, if python command was not found you must insert manually these lines in the Environment Variables Path:

1. Right click on Computer > Click on Properties
2. Click on Advanced system settings on the left (see picture below)
3. Click on “Environment Variables”
4. Select the Path System Variables and add these two lines in the path C:\Python27\;C:\Python27\Scripts;

#### Install the pip command

To install pip, download https://bootstrap.pypa.io/get-pip.py and save it somewhere. After download, invoke the command prompt, go to the directory with get-pip.py and run this command:

C:\> python “<folder_path>\get-pip.py”

Now pip command is installed. From there we can go to the Sphinx install.

#### Installing Sphinx with pip

If you finished the installation of pip, type this line in the command prompt:

C:\> pip install sphinx

After installation, type sphinx-build on the command prompt. If everything worked fine, you will get a Sphinx version number and a list of options for this command.

#### Defining a new project documentation

The root directory of a Sphinx collection of reStructuredText document sources is called the source directory. This directory also contains the Sphinx configuration file conf.py, where you can configure all aspects of how Sphinx reads your sources and builds your documentation.

C:\> sphinx-quickstart

and answer its questions. (Be sure to say yes to the “autodoc” extension.)

Question #1:

> Root path for the documentation [.]: <Enter>

Question #2:

You have two options for placing the build directory for Sphinx output. Either, you use a directory “_build” within the root path, or you separate
“source” and “build” directories within the root path.
> Separate source and build directories (y/n) [n]: y

Question #3:

Inside the root directory, two more directories will be created; “_templates” for custom HTML templates and “_static” for custom stylesheets and other static files. You can enter another prefix (such as “.”) to replace the underscore.
> Name prefix for templates and static dir [_]: <Enter>

Question #4:

The project name will occur in several places in the built documentation.
> Project name: <project_name>

> Author name: <author_name>

Question #5:

Sphinx has the notion of a “version” and a “release” for the software. Each version can have multiple releases. For example, for Python the version is something like 2.5 or 3.0, while the release is something like 2.5.1 or 3.0a1.  If you don’t need this dual structure, just set both to the same value.
> Project version: 1.0

> Project release [1.0]: <Enter>

Question #6:

The file name suffix for source files. Commonly, this is either “.txt” or “.rst”.  Only files with this suffix are considered documents.
> Source file suffix [.rst]: <Enter>

Question #7:

One document is special in that it is considered the top node of the “contents tree”, that is, it is the root of the hierarchical structure of the documents. Normally, this is “index”, but if your “index” document is a custom template, you can also set this to another filename.
> Name of your master document (without suffix) [index]: <Enter>

Question #8:

Sphinx can also add configuration for epub output:
> Do you want to use the epub builder (y/n) [n]: y

Question #9:

Please indicate if you want to use one of the following Sphinx extensions:
> autodoc: automatically insert docstrings from modules (y/n) [n]: y

> doctest: automatically test code snippets in doctest blocks (y/n) [n]: y

> intersphinx: link between Sphinx documentation of different projects (y/n) [n]: y

> todo: write “todo” entries that can be shown or hidden on build (y/n) [n]: y

> coverage: checks for documentation coverage (y/n) [n]: y

> pngmath: include math, rendered as PNG images (y/n) [n]: y

> mathjax: include math, rendered in the browser by MathJax (y/n) [n]: y

> ifconfig: conditional inclusion of content based on config values (y/n) [n]: y

> viewcode: include links to the source code of documented Python objects (y/n) [n]: y

A Makefile and a Windows command file can be generated for you so that you only have to run e.g. `make html’ instead of invoking sphinx-build directly.
> Create Makefile? (y/n) [y]: y

> Create Windows command file? (y/n) [y]: y

Creating file .\source\conf.py.
Creating file .\source\index.rst.
Creating file .\Makefile.
Creating file .\make.bat.

Finished: An initial directory structure has been created.

You should now populate your master file .\source\index.rst and create other documentation
source files. Use the Makefile to build the docs, like so:
make builder
where “builder” is one of the supported builders, e.g. html, latex or linkcheck.

And now … Start the Docs 😉