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 = "you due date time value here";

 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) + "." + duedateString.substring(4 ,6) + "." + duedateString.substring(0 ,4);
 var dueDate = new Date((ddYear),(ddMonth),(ddDay));

 var totalDifference = 0;

 if(yearDifference < 0)
 {
 totalDifference = -1;
 } else if(yearDifference > 0)
 {
 totalDifference = 1;
 } else if(monthDifference < 0)
 {
 totalDifference = -1;
 } else if(monthDifference > 0)
 {
 totalDifference = 1;
 } else if(dayDifference < 0)
 {
 totalDifference = -1;
 } else if(dayDifference > 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 > 0)
 {
 // do something
 }
 // The dueDate is smaller than the current date, in the past
 else if(totalDifference < 0)
 {
 // do something
 }

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

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

Contents

Contents

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.

Installation

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:

http://www.seleniumhq.org/download/

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.

http://docs.seleniumhq.org/projects/ide/

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()

{

try

{

driver.Quit();

}

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;);

driver.FindElement(By.Id(&quot;searchText&quot;)).Clear();

driver.FindElement(By.Id(&quot;searchText&quot;)).SendKeys(&quot;test&quot;);

}

private bool IsElementPresent(By by)

{

try

{

driver.FindElement(by);

return true;

}

catch (NoSuchElementException)

{

return false;

}

}

private bool IsAlertPresent()

{

try

{

driver.SwitchTo().Alert();

return true;

}

catch (NoAlertPresentException)

{

return false;

}

}

private string CloseAlertAndGetItsText()

{

try

{

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

string alertText = alert.Text;

if (acceptNextAlert)

{

alert.Accept();

}

else

{

alert.Dismiss();

}

return alertText;

}

finally

{

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;);

driver.FindElement(By.Id(&quot;searchText&quot;)).Clear();

driver.FindElement(By.Id(&quot;searchText&quot;)).SendKeys(&quot;test&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;);

System.Threading.Thread.Sleep(3000);

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

Actions action = new Actions(driver);

action.MoveToElement(element).Perform();

element.Click();

}

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.

System.Threading.Thread.Sleep(3000);

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:

http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

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.

codeduip3

Next open the “Coded UI Test Builder”:

codeduip4

It should look like this:

codeduip6.PNG

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

[TestMethod]
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);
control.WaitForControlReady();

Assert.AreEqual(true, control.Exists);
control.DrawHighlight();

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");
control2.WaitForControlReady();

Assert.AreEqual(true, control2.Exists);
control2.DrawHighlight();

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");
control3.WaitForControlReady();

Assert.AreEqual(true, control3.Exists);
//tunnit.DrawHighlight();
control3.SetFocus();
control3.SetProperty(HtmlEdit.PropertyNames.Text, "some text");
System.Threading.Thread.Sleep(1000);

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);

person.WaitForControlReady();
person.SetFocus();
Mouse.Click(person);

}

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

https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.uitesting.htmlcontrols.aspx

Coded UI – Have to know things

Requirements

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: https://www.visualstudio.com/en-us/products/compare-visual-studio-2015-products-vs.aspx

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.

codeduip1

To access the test explorer:

codeduip5

Debugging

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.

codeduip2

Browsers

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;

UIMap

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

codeduip8

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.

codeduip9

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:

codeduip7

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

codeduip8

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
{
get
{
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");
#endregion
}
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.

SharePoint site collection access 404 page not found error

If you encounter some of the errors below and especially when trying to access a page or the front page of a site collection or site then the problem might be related to missing page layout or master page references.

This may be due to the fact that you have migrated content from an older SharePoint version and the content database is referencing an older hive version.

So check that you solution packages are installed using compatibility mode:

install-spsolution -identity solution.wsp -webapplication “site url” -gacdeployment -CompatibilityLevel All

Relying on fallback logic in VghostPageManager::getGhostDocument() for document: ‘C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Template\SiteTemplates\somesite\default.aspx’

This collection already contains an address with scheme http. There can be at most one address per scheme in this collection.

Fix deleted AD users from SharePoint

This is a small PowerShell script that will fix issues with removed SharePoint users. You may encounter problems if you remove an AD user but the later re-create it with the same AD user login. If such cases this script might help you with possible SharePoint issues. If this does not help then try to remove the user profile and run a full user profile synchronization and run the script again.


$sites = Get-SPSite http://portal.spdev.com

foreach ($site in $sites) {
$groups = $site.RootWeb.sitegroups
foreach ($group in $groups) {
foreach ($user in $group.users) {
# Skip All Authenticated Users, General groups
if ($user.userlogin -eq "c:0(.s|true" -or $user.userlogin -eq "c:0!.s|windows") {
continue;
}
if ($user.IsDomainGroup) {
# Skip Security Groups
}
else {
# Get user login
$splitline = $user.userlogin.split("\");
$samid = $splitline[1];
if ($user.userlogin.contains("AD domain name"))
{
if ($user.userlogin.contains("part of your login name")) {
Write-Host "user Found" $user.userlogin
$group.removeuser($user);
$site.RootWeb.SiteUsers.Remove($user.userlogin);
}
else {
Write-Host $user.userlogin
}
}
}
}
}
}

How to Fix Quick Edit for SharePoint lists after migration from SharePoint 2010 to Sharepoint 2013

Once again with annoying problem in SharePoint. The problem will most likely occur after you have migrated a content database from SP2010 to SP2013. Thanks to the internet the solution is to make sure that list views have in ther JSLink property the following file in them: clienttemplates.js

Thanks to the following site for the tip on how to fix it:

http://www.rickvanrousselt.com/updating/

Here is a sample C# code that will fix the problem. Using powershell I was unable to get a hold of views in lists after the migration.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

using Microsoft.SharePoint;
namespace SP2013MigrationListFix
{
class Program
{
static void Main(string[] args)
{
using(var site = new SPSite(ConfigurationManager.AppSettings["site"]))
{
for (int siteCount = site.WebApplication.Sites.Count - 1; siteCount >= 0; siteCount--)
{
Console.WriteLine();
Console.WriteLine("----------------------------------------------------------------------");
SPSite innerSite = site.WebApplication.Sites[siteCount];
Console.Write("Site: " + innerSite.RootWeb.Title);
try
{
for (int webCount = innerSite.AllWebs.Count - 1; webCount >= 0; webCount--)
{

SPWeb web = innerSite.AllWebs[webCount];
Console.WriteLine();
Console.WriteLine("Web: " + web.Title);
try
{

for (int listCount = web.Lists.Count - 1; listCount >= 0; listCount--)
{
SPList list = web.Lists[listCount];
Console.WriteLine("Web: " + list.Title);
if (list != null)
{
Console.WriteLine("View count: " + list.Views.Count);
for (int x = list.Views.Count - 1; x >= 0; x--)
{
SPView view = list.Views[x];
Console.WriteLine("View name: " + view.Title);
Console.WriteLine("JSLink before fix: " + view.JSLink);
if (String.IsNullOrWhiteSpace(view.JSLink))
{
view.JSLink = "clienttemplates.js";
view.Update();
Console.WriteLine("JSLink after fix: " + view.JSLink);
}

}
}
else
{
Console.WriteLine("List not found");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + " " + ex.StackTrace);
}
finally
{
if (web != null)
web.Dispose();
}
}
}
finally
{
if (innerSite != null)
innerSite.Dispose();
}
}

}
Console.ReadLine();
}
}
}