How to backup your private repositories

GitHub Repository Backup Steps


Install git. 1

Use SSH key for communication with GitHub. 1 1

Generate SSH Key. 1

Generating a new SSH key. 1

Adding your SSH key to the ssh-agent. 2

Add the SSH key to your GitHub account or the organization. 2

Setup a default user name and email 4

Set your username for every repository on your computer: 4

Setting your email address for every repository on your computer. 4

Create an access token if you want to clone repositories without a username and password. 5

Ways to access the GitHub API with an access token. 6

Cloning repositories. 7

Sample git command: 7

Sample node.js tool 7

Usage. 7

Options: 7

Examples: 7

Exclude and Only options. 7

Install git

Use SSH key for communication with GitHub

Generate SSH Key

Generating a new SSH key

1. Open Git Bash.

2. Paste the text below, substituting in your GitHub email address.

3. ssh-keygen -t rsa -b 4096 -C ""

This creates a new ssh key, using the provided email as a label.

Generating public/private rsa key pair.

4. When you’re prompted to "Enter a file in which to save the key," press Enter. This accepts the default file location.

5. Enter a file in which to save the key (/Users/you/.ssh/id_rsa): [Press enter]

6. At the prompt, type a secure passphrase. For more information, see "Working with SSH key passphrases".

7. Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

Adding your SSH key to the ssh-agent

Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key.

If you have GitHub for Windows installed, you can use it to clone repositories and not deal with SSH keys. It also comes with the Git Bash tool, which is the preferred way of running git commands on Windows.

1. Ensure the ssh-agent is running:

o If you are using the Git Shell that’s installed with GitHub Desktop, the ssh-agent should be running.

o If you are using another terminal prompt, such as Git for Windows, you can use the "Auto-launching the ssh-agent" instructions in "Working with SSH key passphrases", or start it manually:

o # start the ssh-agent in the background
o eval $(ssh-agent -s)
o Agent pid 59566

2. Add your SSH key to the ssh-agent. If you used an existing SSH key rather than generating a new SSH key, you’ll need to replace id_rsa in the command with the name of your existing private key file.

3. $ ssh-add ~/.ssh/id_rsa

Add the SSH key to your GitHub account or the organization

For a single user

For organization

Copy the SSH key to your clipboard(use Git bash)

If your SSH key file has a different name than the example code, modify the filename to match your current setup. When copying your key, don’t add any newlines or whitespace.

$ clip < ~/.ssh/
# Copies the contents of the file to your clipboard

Tip: If clip isn’t working, you can locate the hidden .ssh folder, open the file in your favorite text editor, and copy it to your clipboard.

Notice that the .ssh folder is usually located at: C:Users{your account name}.ssh

Go to you Organization management windows and select from the left navigation: SSH and GPG keys

From this new view then press New SSH Key button

The type a title and copy the key from the clipboard

Setup a default user name and email

You can do this for a specific repository or globally. For this situation globally if preferable.

Set your username for every repository on your computer:

1. Navigate to your repository from a command-line prompt.

2. Set your username with the following command.

3. git config –global "Billy Everyteen"

4. Confirm that you have set your username correctly with the following command.

5. git config –global

Billy Everyteen

Setting your email address for every repository on your computer

1. Open Git Bash.

2. Set your email address with the following command:

3. git config --global ""

4. Confirm that you have set your email address correctly with the following command.

5. git config --global

Create an access token if you want to clone repositories without a username and password

This is also useful if you want to create your own application to use the GitHub API for something you want to be done.

For a single user

For the organization

Navigate to the Organization management and from the left navigation go to: Developer settings -> Personal access tokens

From this new view press the button: Generate new token

From the new view add a title to the access token then select the needed privileges to your organization. For repository backup you might need the following in the picture below.

IMPORTANT: After you have created the token remember to copy and store the key because this is the only time you will see it.

Ways to access the GitHub API with an access token

Cloning repositories

Sample git command:

git clone --bare

Sample node.js tool


 cloneorg [OPTIONS] [ORG]


 -p, --perpage NUMBER number of repos per page (Default is 100)
 -t, --type STRING can be one of: all, public, private, forks, sources,
 member (Default is all)
 -e, --exclude STRING Exclude passed repos, comma separated
 -o, --only STRING Only clone passed repos, comma separated
 -r, --regexp BOOLEAN If true, exclude or only option will be evaluated as a
 -u, --username STRING Username for basic authentication. Required to
 access github api
 --token STRING Token authentication. Required to access github api
 -a, --gitaccess Protocol to use in `git clone` command. Can be `ssh` (default), `https` or `git`
 -s, --gitsettings Additional parameters to pass to git clone command. Defaults to empty.
 --debug Show debug information
 -v, --version Display the current version
 -h, --help Display help and usage details


clones all github/twitter repositories, with HTTP basic authentication. A password will be required

cloneorg twitter -u GITHUB_USERNAME
cloneorg twitter --username=GITHUB_USERNAME

clones all github/twitter repositories, with an access token provided by Github

cloneorg twitter --token GITHUB_TOKEN

If an environment variable GITHUB_TOKEN is set, it will be used.


Add a -p or –perpage option to paginate response

cloneorg mozilla --token=GITHUB_TOKEN -p 10

Exclude and Only options

If you only need some repositories, you can pass -o or –only with their names

cloneorg angular --token=GITHUB_TOKEN -o angular

This can be an array to

cloneorg angular --token=GITHUB_TOKEN -o angular,material,bower-angular-i18n

This can also be an regular expression, with -r or –regexp option set to true.

cloneorg marionettejs --token=GITHUB_TOKEN -o ^backbone -r true

The same rules apply to exclude options

cloneorg jquery --token=GITHUB_TOKEN -e css-framework # simple
cloneorg emberjs --token=GITHUB_TOKEN -e website,examples # array
cloneorg gruntjs --token=GITHUB_TOKEN -e $-docs -r true # regexp
cloneorg gruntjs --token=GITHUB_TOKEN -e $-docs -r true --gitaccess=git # Clone using git protocol
# Clone using git protocol and pass --recurse to `git clone` to clone submodules also
cloneorg gruntjs --token=GITHUB_TOKEN -e $-docs -r true --gitaccess=git --gitsettings="--recurse"

Azure AD Integration

This year I’ve been working a lot more with Azure. On of my tasks has been to integrate other application to each other using Azure AD. Here are some of my finding and good to know things in case someone else runs into them:

  • Create a new MVC Application in Visual Studio
  • When this is done, press the second mouse button on the project and go to “Add” > “Connected Services”. This will allow you to create an O365 connection.
  • Select Office 365 API Services.
  • In the new Window select or type in your domain.
  • Next, create new Azure AD application configuration or use an existing one by providing the GUID for the application.
    • Make sure you select the “Configure Single Sign-On using Azure AD” option
    • Make sure that your application is multi-tenant:
      • This works so that you register your app with you own Azure AD domain, then after that external Azure AD tenants and their users are registered through an “onboarding” process. The process will the user or admin user for privileges to use certain information from the AD or other resources. These are defined in the Azure AD application settings.
      • Notice you are using an application ID and key to connect to your own organization Azure AD then the users are only onboarding using the multi-tenant option in the Azure AD application configuration.
    • Next select what kind of privileges your application needs from the Azure AD and O365.
    • You need onboarding functionality from here:
    • In Global.asax.cs application_start function add the following: AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
      • If this is missing, then you claim will not work properly.
    • If you are using a SQL Server database and Entity Framework remember to update you model from the database and remember primary key connections. If the Entity Framework update does not work then removing and adding the database tables should force an update. Also remember to clean and build your project if nothing else helps.
    • If you get this error: Error: {“error”:”invalid_grant”,”error_description”:”AADSTS70002: Error validating credentials. AADSTS70000: The provided access grant is invalid or malformed…..
    • Doing a redirect the proper way in an MVC apllication using the following piece of code in your contoller: return Redirect(returnUrl);
      • If you use the normal way in ASP .NET: Response.Redirect(returnUrl); you will run into trouble. The error message might look something like this:
        • Server Cannot Append Header After HTTP headers have been sent Exception at @Html.AntiForgery
        • You could set the AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in the Application_start, but this will lower your security and not advisable.


MongoDB Magic a.k.a simple database operations


This is my little post on how to do simple database operations with MongoDB.

First let’s start with needed MongoDB needed functionalities. The simplest way is to open Visual Studio and manage your projects nugets packages. Add these four nuggets to your projects. Notice that you do not necessary need the mongocshaprdiver, it’s a legacy driver. Add it only if you need it.


Next to be able to use the classes for handling MongoDB database operation include the following namespaces:

using MongoDB.Bson;
using MongoDB.Driver;

BSON is: “BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB” More info here:

Driver is: “The official MongoDB C#/.NET Driver provides asynchronous interaction with MongoDB” More Info:

To code below will create a client connection to the MondoDB and will get a database in it.

var client = new MongoClient("mongodb://localhost:27017");
 var database = client.GetDatabase("databaseName");

To list all collections in a database:

foreach (var item in database.ListCollectionsAsync().Result.ToListAsync&lt;BsonDocument&gt;().Result)


To get the name of the collection:

var name = item.Elements.FirstOrDefault().Value.RawValue as String;

To access a collection and all of its documents:

var collection = database.GetCollection&lt;BsonDocument&gt;(name);
// This filter simply means that all data is retrieved
 var filter = new BsonDocument();

 var documents = collection.Find(filter);
 foreach (var document in documents.ToEnumerable())

To check if a document has elements(fields) with a certain data type:

var dateTimeFields = document.Elements.Where(o =&gt; o.Value.BsonType == BsonType.DateTime);
foreach (var dateTimeField in dateTimeFields)

To update a document with certain values:

var updateFilter = Builders&lt;BsonDocument&gt;.Filter.Eq("_id", document.Elements.FirstOrDefault().Value);
 var value = BsonTypeMapper.MapToDotNetValue(dateTimeField.Value);
 var updateDefiniotion = Builders&lt;BsonDocument&gt;.Update.Set(dateTimeField.Name, BsonTypeMapper.MapToBsonValue(((DateTime)value).AddDays(3)));

 var result = collection.UpdateOne(updateFilter, updateDefiniotion);
 if (result.ModifiedCount &gt; 0)
 // Success
 // No updates

Retrieving documents based on a filter and copying them into another collection + deleting from the original collection:

var timeEntriesIntoTheFuture = Builders&lt;BsonDocument&gt;.Filter.Gt(dateTimeField.Name, BsonTypeMapper.MapToBsonValue(DateTime.Now));
 var entries = sourceCollection.Find(timeEntriesIntoTheFuture);
if(entries.Count() &gt; 0)
 foreach(var entry in entries.ToEnumerable())

Checking if a collection exists:

public static bool DoesCollectionExist(IMongoDatabase database, String collectionName)
 bool collectionExists = false;

 foreach (var item in database.ListCollectionsAsync().Result.ToListAsync&lt;BsonDocument&gt;().Result)
 var name = item.Elements.FirstOrDefault().Value.AsString;
 if (name.Contains(collectionName))
 collectionExists = true;

 return collectionExists;

Updating an element at a certain position:

var updateDefiniotion = Builders&lt;BsonDocument&gt;.Update.Set(firstDocument.ElementAt(1).Name, BsonTypeMapper.MapToBsonValue(DateTime.Now));

Inserting a document in a manually defined manner:

var dateTimeStampeValue = new BsonDocument()
{ "ResetDate", BsonTypeMapper.MapToBsonValue(DateTime.Now) }

Upgrading/Migrating from an older SharePoint version to a newer SharePoint

This is my checklist for when I am upgrading content from an older SharePoint to a newer one. Like from SharePoint 2010 to SharePoint 2013.

  • Make sure that you disable the outgoing Email address from the Central Administration in the web applications own settings. This is if you have events or other functionality that is to send emails based on some logic. You do not want to send emails confusing end users about emails which should not be send.
  • Install you needed packages for the migration process. This is important. If you do not do this the content database upgrade will have multiple errors and you might not be able to retrieve them.
    1. Notice another important reason why this is important is that lists and libraries are feature dependent. If there is a missing feature your lists or libraries will show empty views or will not function. Even if there is an access point through a URL, SharePoint will not be able to show you the content.
  • Next take a database backup in SQL Server from your old environment. You do this by: Pressing the secondary mouse button on a database > Tasks > Back Up… . Make sure that you check the checkbox named “Copy-only backup”. This is important, if you do not do this this will cause problems for the current database being used by the old SharePoint farm.
  • Next start the process of upgrading the content. More details here:
    • For a SharePoint 2010 upgrade, you might need to create a classic authentication application. More details here:
    • Sample command: New-SPWebApplication -name “ClassicAuthApp2” -Port 100 -ApplicationPool “ClassicAuthAppPool” -ApplicationPoolAccount (Get-SPManagedAccount “<domainname>\<user>”)
    • Before you perform the actual upgrade test the database with the following command: Test-SPContentDatabase -Name DatabaseName -WebApplication URL > TestLog.txt
      1. This will output a log file in the same folder where you are in the SharePoint management shell. Look at the log file and fix the errors found. It may not be necessary to fix them all if the errors do not affect the content you need.
      2. Notice: The WebApplication URL is the same as the classic application URL created earlier if you created it.
    • The next step is to mount the database. This is the actual upgrade process.
      1. Sample Command: Mount-SPContentDatabase -Name DatabaseName -DatabaseServer ServerName -WebApplication URL
        1. Notice: If your SharePoint farm is using SQL Aliases then open the following program and see your SQL Server database name: C:\Windows\System32\cliconfg.exe
        2. Notice: The WebApplication URL is the same as the classic application URL created earlier if you created it.
      2. If you created the classic authentication application then the next step is to convert it to a claims application.
        1. Sample command: Convert-SPWebApplication -Identity <yourWebAppUrl> -To Claims -RetainPermissions [ -Force]
      3. Moving the needed content from one content database to the other. More details here:
        1. Create new a content database (or multiple ones if needed) and use the Move-SPSite command to move them from one location to the other. Notice: The new content database(s) must be in the same application for the command to work.
        2. Sample command: Move-SPSite <http://ServerName/Sites/SiteName> -DestinationDatabase <DestinationContentDb>
        3. When ready with the move operation of content, then detach your new content database(s) and attach it to the new location.
  • Check that if you have XSLT based list or library field customizations that they work. If not consider using JSLink functionality in webparts of by defining it in a field through a powershell script like the one below. There is also a sample how to do it in the JavaScript file
  • Check that you calculated columns are working in your new environment.
  • If you are having problems with you quick edit functionality try this script:
  • If you have different threshold definitions in the old environment check that your old content and functionality behaves correctly in the new environment.
  • Next step upgrade your SharePoint sites look. This is offered automatically by the new version of SharePoint but if not then:
    1. /_layouts/siteupgrade.aspx ja /_layouts/siteupgradestatus.aspx
  • Next configure your search:
    1. Make sure that your new content is in one of your content sources.
    2. Run a full crawl.
  • Feature installation problems:
    1. “Check that the feature has been installed. For example, if you are performing Update-SPSolution and a new feature has been added between solution deployments then the feature is not installed by default.
    2. To check do the following:-
    3. Run SharePoint 2010 Management Shell from one of the SharePoint servers Type Install-SPFeature -ScanForFeatures
      1. This will show you any features that are available in the SharePoint Root but have not been installed. You can install any missing features using the command :-
    4. Install-SPFeature -AllExistingFeatures
      1. See the following TechNet Article for more information:
    5. Get-SPFeature| Sort -Property Scope,DisplayName | FT -GroupBy Scope DisplayName,ID
  1. If you have problems with some of your views in a list or library while others views work, then a work around is to create the view using the problem view as the base view.
param (

[string]$SPSiteFilter = "app url"



if ((Get-PSSnapin 'Microsoft.SharePoint.PowerShell' -ErrorAction SilentlyContinue) -eq $null){Add-PSSnapin 'Microsoft.SharePoint.PowerShell'}




$spWebApp = Get-SPWebApplication $SPSiteFilter

foreach($site in $spWebApp.Sites)


$ddField = $site.rootweb.Fields["field name"]

Write-Host $site.Url

if($ddField -ne $null)



$ddField.JSLink = "~sitecollection/Style Library/JSLinkFix.js"


Write-Host "Updated"











Check the difference between two dates with a custom JavaScript implementation

This might be useful if you are having problems with different browsers and how they handle JavaScript and date + time data.

var duedateString = &quot;you due date time value here&quot;;

 var today = new Date();

 var ddYear = parseInt(duedateString.substring(0 ,4));
 var ddMonth = parseInt(duedateString.substring(4 ,6));
 var ddDay = parseInt(duedateString.substring(6 ,8));

 var yearDifference = ddYear - (today.getFullYear()) ;
 var monthDifference = ddMonth - (today.getMonth() +1);
 var dayDifference = ddDay - (today.getDate());
 var stringDueDateParsed = duedateString.substring(6 ,8) + &quot;.&quot; + duedateString.substring(4 ,6) + &quot;.&quot; + duedateString.substring(0 ,4);
 var dueDate = new Date((ddYear),(ddMonth),(ddDay));

 var totalDifference = 0;

 if(yearDifference &lt; 0)
 totalDifference = -1;
 } else if(yearDifference &gt; 0)
 totalDifference = 1;
 } else if(monthDifference &lt; 0)
 totalDifference = -1;
 } else if(monthDifference &gt; 0)
 totalDifference = 1;
 } else if(dayDifference &lt; 0)
 totalDifference = -1;
 } else if(dayDifference &gt; 0)
 totalDifference = 1;
 } else
 totalDifference = 0;

 // the dates are equal
 if(totalDifference === 0)
 // do something
 // The dueDate is greater than the current date, in the future
 else if(totalDifference &gt; 0)
 // do something
 // The dueDate is smaller than the current date, in the past
 else if(totalDifference &lt; 0)
 // do something

How to use Selenium + IDE with Visual Studio and C#

How to use Selenium + IDE with Visual Studio and C#



Installation. 0

Optional step – Selenium IDE for Firefox. 5

Converting Selenium IDE recorded Scripts to C# WebDriver code for Visual Studio. 6

Running tests. 8

Tips and Tricks with Selenium and C#. 9

Sample C# code generated with Selenium IDE. 9

Needed namespaces for tests. 11

Using a browser to performs test operations. 11

Using a test. 11

Imitating focus or hover over an element. 12

Waiting for the page to load or some operation. 12

Working with dynamic content/elements. 12



In this post I will cover the details about how to install Selenium + needed components to be able to test your web application.


The simplest way to use Selenium is to install the Selenium WebDriver nugget package to your Visual Studio project.

Open your Visual Studio create a project(of any kind). Then go to the References and select the “Manage Nugget Packages…”

Next search for the packages Selenium.WebDriver and Selenium.Support and install them.

You also need to install the “NUnit Framework”, so repeat the previous steps to install the NUnit framework package.

When you are ready your project references should look like this:

Next we need to install support for running test cases from the Visual Studio Test Explorer. Go to the top menu bar, from there select Tools and “Extension and Updates…”.

From the new window search online for NUnit Test adapter. Notice: Make sure that you have the right version. If you are using the latest Selenium version, then “NUnit 3 Test Adapter” is what you need.

Next step is to download Selenium driver support for different browsers. If you do not do this then you will not be able to run C# tests using Selenium.

First thing is to go and download the browser drivers which you want to use:

Scroll down to the Third Party drivers and download what you need. Then create a folder somewhere on your computer where you will put the browser drivers.

After this copy the full path to the folder and store it.

Go to the “Control Panel” > System > “Advanced Settings”

In the “System Properties” window, in the Advanced tab select the “Environmental Variables…”.

Next double click on the Path and press the New button. Then just paste in the path you stored to the browser drivers. This is used so that Visual Studio will know where to locate the needed browser drivers. If this is not done you will receive errors when trying to use the selenium tests.

After this restart your Visual Studio.

Optional step – Selenium IDE for Firefox

If you want to speed up making test case’s you can use Selenium IDE for firefox.

To install this simply open you Firefox browser, go to the Extensions and search for the Selenium IDE.

To open the IDE in Firefox go to Tools > “Selenium IDE”. If the menu bar is not visible try pressing the ALT button.

Converting Selenium IDE recorded Scripts to C# WebDriver code for Visual Studio

First make sure that the recorded steps are converted into C# code. Go to Options > Format > C# / NUnit / WebDriver.

NOTICE: If the Format category under Options does not display any options:

Then do the following: Go to Options > Options and check “Enable experimental features”

Now to get you C# source code you need to tap the “Source” tab in the Selenium IDE main window.

Now you can create a new class in your Visual Studio project and copy & paste that code there and you are ready to run tests.

Running tests

To run tests all you need to do is open the “Test Explorer” in Visual Studio: In the menu bar Test > Window > “Test Explorer”

Now if you have a test and you have compiled your project then you should see your NUnit test with Selenium testing.

To run a test simply click the test with the second mouse button and run it from the options.

Tips and Tricks with Selenium and C#

Sample C# code generated with Selenium IDE

using System;

using System.Text;

using System.Text.RegularExpressions;

using System.Threading;

using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;

using OpenQA.Selenium.Support.UI;

namespace SeleniumTests


[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">TestFixture</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public class Untitled


private IWebDriver driver;

private StringBuilder verificationErrors;

private string baseURL;

private bool acceptNextAlert = true;

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">SetUp</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void SetupTest()


driver = new FirefoxDriver();

baseURL = &quot;<a href="http://localhost:4000/&quot;">http://localhost:4000/&quot;</a&gt;;

verificationErrors = new StringBuilder();


[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">TearDown</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TeardownTest()






catch (Exception)


// Ignore errors if unable to close the browser


Assert.AreEqual(&quot;&quot;, verificationErrors.ToString());


[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TheUntitledTest()


driver.Navigate().GoToUrl(baseURL + &quot;about:home&quot;);




private bool IsElementPresent(By by)





return true;


catch (NoSuchElementException)


return false;



private bool IsAlertPresent()





return true;


catch (NoAlertPresentException)


return false;



private string CloseAlertAndGetItsText()




IAlert alert = driver.SwitchTo().Alert();

string alertText = alert.Text;

if (acceptNextAlert)








return alertText;




acceptNextAlert = true;





Needed namespaces for tests

Basically what you need is the NUnit framework, Selenium itself, different browsers support, support for UI and UI interactions.

using NUnit.Framework;

using OpenQA.Selenium;

using OpenQA.Selenium.Firefox;

using OpenQA.Selenium.Chrome;

using OpenQA.Selenium.Support.UI;

using OpenQA.Selenium.Interactions;

using OpenQA.Selenium.Interactions.Internal;

Using a browser to performs test operations

What this means is that you have to choose a browser driver of which you will create an object instance. With selenium you can code against an interface to make things easier.

So first you define the driver interface then later in the setup phase you instantiate it.

private IWebDriver driver;

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">SetUp</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void SetupTest()


driver = new ChromeDriver();

baseURL = &quot;<a href="http://localhost:4000/&quot;">http://localhost:4000/&quot;</a&gt;;

verificationErrors = new StringBuilder();


Using a test

If you look at a sample code generated with the IDE you can see that a test function is defined with the Test attribute. Within this test function you can make things happen.

In the example below the test simply involved entering a search test in the Firefox main search engine.

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void TheUntitledTest()


driver.Navigate().GoToUrl(baseURL + &quot;about:home&quot;);




Imitating focus or hover over an element

There might be situation where you have some HTML element hidden and you want it to be displayed when the user goes over a certain location. Selenium will not now where the element is in this case and will throw an exception that the element was not found.

To fix this you need to simulate this hover over effect with the Actions class.

The example below will search for a div with a certain CSS class then using the Actions class and the MoveToElement function we simulate this step.

[</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:#2B91AF;">Test</span><span lang="EN-US" style="font-size:9.5pt;font-family:Consolas;color:black;">]

public void WorkEntryTest()


driver.Navigate().GoToUrl(baseURL + &quot;/&quot;);


var element = driver.FindElement(By.CssSelector(&quot;div.myClass &quot;));

Actions action = new Actions(driver);




Waiting for the page to load or some operation

Now there are different ways to do this but the simples way is to sleep the thread where your test is running.


Working with dynamic content/elements

This is a tricky one. I tried several approaches but wasn’t able to make them work. One of those approaches was to use XPath to find the elements in different ways:

· Absolute XPath

· Identify Element by starting Text

· Identify Element by containing Text

· Identify Element by Index

· Identify Element with reference of a closest stable element

· Identify Element by stable preceding Text

What worked for me was to use the WebDriverWait class. You are going to use the Until function with a condition to find that dynamic element:

The code below waits for a couple of seconds before searching for elements with a certain name attribute. Notice that in the example below I know that the needed element is the second one in the array returned by the Until function.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(3));

var selectElementWait = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath(&quot;//select[@name=’minutes]&quot;)));

new SelectElement(selectElementWait[1]).SelectByText(&quot;30&quot;);

How to use Coded UI in Visual Studio to create automated UI tests

To use the Coded UI for automated testing you need to know three things:

  1. You can use the recording function for Visual Studio to do most of the work
  2. You can do it manually but it requires time and patience.
  3. There are some details which you need to be aware of before you can use Coded UI for testing


Automated UI test recording

This is rather straight forward.

To be able to record a test the following must be true:

  • You application but not in debug mode while you are recording your UI test
  • You have to have a physical focus in a C# test file inside a test method where the recording will create a test call created by the recording process.
  • Before you can start recording you must have your application running.


Next open the “Coded UI Test Builder”:


It should look like this:


At this point open your application on the screen. Then press the red recording button to start recording.

After you are done with your application test steps creation you can add assertions to the test. This happens from the circle in the test builder.

When you are done press the blue arrow pointing to the right with lines below it(the last icon in the test builder). This will generate the test code.

After this, you can start your tests from the test explorer.

Manual UI tests creation

Manual testing can be harder and time-consuming but has the advantage of precision. The basic structure goes as:

  • Create a browser object pointing to a web application
  • Start searching for controls based on search and/or filter properties
  • Do something to the control
  • Do an assertion for the test

public void CodedUITestMethod2()

// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.
BrowserWindow browser = BrowserWindow.Launch("some your to your web application");
browser.Maximized = true;
UITestControl control = new UITestControl(browser);
control.TechnologyName = "Web";
control.SearchProperties.Add(HtmlHyperlink.PropertyNames.TagName, "A", HtmlHyperlink.PropertyNames.InnerText, "some text", HtmlHyperlink.PropertyNames.ControlType, ControlType.Hyperlink.Name);
control.SearchProperties.Add(HtmlHyperlink.PropertyNames.Href, "some partial URL", PropertyExpressionOperator.Contains);

Assert.AreEqual(true, control.Exists);

UITestControl control2 = new UITestControl(browser);
control2.TechnologyName = "Web";
control2.SearchProperties.Add(HtmlInputButton.PropertyNames.ControlType, ControlType.Button.Name, HtmlHyperlink.PropertyNames.ValueAttribute, "some text", HtmlHyperlink.PropertyNames.Class, "some css class");

Assert.AreEqual(true, control2.Exists);

UITestControl control3 = new UITestControl(browser);
control3.TechnologyName = "Web";
control3.SearchProperties.Add(HtmlHyperlink.PropertyNames.TagName, "input", HtmlEdit.PropertyNames.Name, "some name", HtmlHyperlink.PropertyNames.Id, "some ID");

Assert.AreEqual(true, control3.Exists);
control3.SetProperty(HtmlEdit.PropertyNames.Text, "some text");

UITestControl person = new UITestControl(browser);
person.TechnologyName = "Web";
person.SearchProperties.Add(HtmlCell.PropertyNames.TagName, "td");
person.SearchProperties.Add(HtmlCell.PropertyNames.ValueAttribute, "namefield");
person.SearchProperties.Add(HtmlCell.PropertyNames.InnerText, "some text", PropertyExpressionOperator.Contains);



For more info on the controls and ways of using go here:

Coded UI – Have to know things


To use the Coded UI you need some version of Visual Studio that supports Coded UI. Currently as of this blog post only Visual Studio Enterprise supports it:

Running tests

You can run tests with or without debug mode for the tests. Notice that Coded UI test debugging is different than debugging your application, meaning that you have to run the debugging for test specifically from the text explorer.


To access the test explorer:



You can’t have your application in debug mode when recording automated UI tests (this is true for Web application, not sure for windows applications). What you need to do is to run your application without debugging. For web apps what this does is that normally IIS Express is launched and the app will be running there. If you are running the app on a manual IIS site well then all you need to do is to start the app.



Coded UI requires Internet Explorer unless you configure it otherwise.

You can start a browser from your code using the following code:

BrowserWindow browser = BrowserWindow.Launch(“some URL”);
browser.Maximized = true;


This is a class inside your test project where the automated recorded tests are saved.


NOTICE: If you have the “Coded UI Test Builder” closed you can double click on the UIMap.uitest to get an overview of your recorded tests.


Dynamic controls or URLs

If you have dynamic controls or URLs then you need to remove the dynamic parts from the recorded code. This means that you have to inside the C# code to remove search properties of filter properties that define dynamic data. Notice that you have to make sure that the remaining properties are enough to find your controls or URLs

You can do this from your Coded UI test class by going to the declaration of the test function in the UIMap class:


Or by opening the UIMap.cs file and under it the UIMap.Designer.cs file.


Basically what you are looking for is something like the code example below. The commented out code is in this case, the dynamic data which changes. The code assumes that the rest of the properties will do the job in finding the control:

public HtmlCheckBox UI__listitem___id_5066CheckBox
if ((this.mUI__listitem___id_5066CheckBox == null))
this.mUI__listitem___id_5066CheckBox = new HtmlCheckBox(this);
#region Search Criteria
//this.mUI__listitem___id_5066CheckBox.SearchProperties[HtmlCheckBox.PropertyNames.Id] = "__id_50661";
//this.mUI__listitem___id_5066CheckBox.SearchProperties[HtmlCheckBox.PropertyNames.Name] = "__listitem___id_50660";
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.Value] = "some value";
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.LabeledBy] = null;
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.Title] = null;
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.Class] = "__checkbox";
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.ControlDefinition] = "name=\"__listitem___id_50660\" class=\"__ch";
this.mUI__listitem___id_5066CheckBox.FilterProperties[HtmlCheckBox.PropertyNames.TagInstance] = "27";
this.mUI__listitem___id_5066CheckBox.WindowTitles.Add("Some URL");
return this.mUI__listitem___id_5066CheckBox;

Search and Filter properties when searching for controls – What’s the difference?

The difference is that the search properties act as AND operators. While the filter properties act as OR operators.