Selenium and C#

Applies to CrossBrowserTesting SaaS, last modified on October 07, 2021

Getting started with Selenium and C#

Selenium is a great tool to automate our functional tests on websites and web applications in our favorite language. With CrossBrowserTesting, you can use Selenium and C# to run automated browser tests on thousands of real mobile and desktop browsers in the cloud. To learn more about the Selenium API, we recommend you read Selenium documentation.

Note: You will need a Username and Authkey to run your tests on CrossBrowserTesting. To get yours, sign up for a free trial or purchase a plan.

Install Selenium

To get started let's make sure we have the necessary assembly references for our test script. If you copy the following script into Visual Studio, it should try to do this for you:

// Getting started: http://docs.seleniumhq.org/docs/03_webdriver.jsp
// API details: https://github.com/SeleniumHQ/selenium#selenium
// Quick start video tutorial using Visual Studio: https://www.youtube.com/watch?v=CxDkRJ1iHwE
// Step-by-step video turoial using Visual Studio: https://www.youtube.com/watch?v=uRJL0zu7U6k

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;

namespace BasicTest
{
    class BasicTest
    {
        // put your username and authkey here:
        public static string username = "YOUR_USERNAME";
        public static string authkey = "YOUR_AUTHKEY";

        static void Main(string[] args)
        {
            var cbtapi = new CBTApi();

            // Start by setting the capabilities
          var caps = new RemoteSessionSettings();

          caps.AddMetadataSetting("name", "C Sharp Test");
          caps.AddMetadataSetting("username", username);
          caps.AddMetadataSetting("password", authkey);
          caps.AddMetadataSetting("browserName", "Chrome");
          caps.AddMetadataSetting("version", "72");
          caps.AddMetadataSetting("platform", "Windows 10");
          caps.AddMetadataSetting("screen_resolution", "1024x768");
          caps.AddMetadataSetting("record_video", "true");



            // Start the remote webdriver
            RemoteWebDriver driver = new RemoteWebDriver(new Uri("http://hub.crossbrowsertesting.com:80/wd/hub"), caps, TimeSpan.FromSeconds(180));

            // wrap the rest of the test in a try-catch for error logging via the API
            try
            {
                // Maximize the window - DESKTOPS ONLY
                // driver.Manage().Window.Maximize();
                // Navigate to the URL
                driver.Navigate().GoToUrl("http://crossbrowsertesting.github.io/selenium_example_page.html");
                // Check the title
                Console.WriteLine(driver.Title);
                Assert.AreEqual(driver.Title, "Selenium Test Example Page");
                // Uncomment this line to see what happens when an assertion fails!
                // Assert.AreEqual(driver.Title, "Selenium Test Example Cage");
                cbtapi.setScore(driver.SessionId.ToString(), "pass");
                driver.Quit();
            }
            catch (AssertionException ex)
            {

                var snapshotHash = cbtapi.takeSnapshot(driver.SessionId.ToString());
                cbtapi.setDescription(driver.SessionId.ToString(), snapshotHash, ex.ToString());
                cbtapi.setScore(driver.SessionId.ToString(), "fail");
                Console.WriteLine("caught the exception : " + ex);
                driver.Quit();
                throw new AssertionException(ex.ToString());
            }
        }
    }

    public class CBTApi
    {

        public string BaseURL = "https://crossbrowsertesting.com/api/v3/selenium";

        public string username = BasicTest.username;
        public string authkey = BasicTest.authkey;

        public string takeSnapshot(string sessionId)
        {
            // returns the screenshot hash to be used in the setDescription method.
            // create the POST request object pointed at the snapshot endpoint
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "/" + sessionId + "/snapshots");
            Console.WriteLine(BaseURL + "/" + sessionId);
            request.Method = "POST";
            request.Credentials = new NetworkCredential(username, authkey);
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "HttpWebRequest";
            // Execute the request
            var response = (HttpWebResponse)request.GetResponse();
            // store the response
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            // parse out the snapshot Hash value
            var myregex = new Regex("(?<=\"hash\": \")((\\w|\\d)*)");
            var snapshotHash = myregex.Match(responseString).Value;
            Console.WriteLine(snapshotHash);
            return snapshotHash;
        }

        public void setDescription(string sessionId, string snapshotHash, string description)
        {
            // encode the data to be written
            ASCIIEncoding encoding = new ASCIIEncoding();
            var putData = encoding.GetBytes("description=" + description);
            // create the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseURL + "/" + sessionId + "/snapshots/" + snapshotHash);
            request.Method = "PUT";
            request.Credentials = new NetworkCredential(username, authkey);
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "HttpWebRequest";
            // write data to stream
            Stream newStream = request.GetRequestStream();
            newStream.Write(putData, 0, putData.Length);
            newStream.Close();
            WebResponse response = request.GetResponse();
        }

        public void setScore(string sessionId, string score)
        {
            string url = BaseURL + "/" + sessionId;
            // encode the data to be written
            ASCIIEncoding encoding = new ASCIIEncoding();
            string data = "action=set_score&score=" + score;
            byte[] putdata = encoding.GetBytes(data);
            // Create the request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            request.Credentials = new NetworkCredential(username, authkey);
            request.ContentLength = putdata.Length;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = "HttpWebRequest";
            // Write data to stream
            Stream newStream = request.GetRequestStream();
            newStream.Write(putdata, 0, putdata.Length);
            newStream.Close();
            WebResponse response = request.GetResponse();
        }
    }
}

Now, add references using Project > Add Reference. Selenium should be one of them. We will also be using NUnit to make assertions during our test.

Once you have all the necessary assembly references in place, we will run our first test. If you have the app open as well, navigate to the Selenium side of our app. As you can see we also create a CBTApi object that allows us to set the score, take a snapshot, and set the description.

Test capabilities

CrossBrowserTesting allows you to add certain capabilities to your test, like video recordings, naming structure and more.

Naming tests

Naming your tests can help organize your automated test cases for easier debugging. You can also mark Build number to denote releases.

caps.AddMetadataSetting("name", "Selenium Example");caps.AddMetadataSetting("build", "1.0");

Choose browsers

To choose your environment, you can select from Browsers, Operating System, Resolutions, and Devices. You can use our easy Selenium Wizard to select your configuration or hit our browser list endpoint.

Record videos

For superior debugging capabilities, CrossBrowserTesting offers the ability to record a video of your Selenium test session. You can find a copy of your test results here.

caps.AddMetadataSetting("record_video", "true");

Record network

To record the network packets during your test for performance debugging, set the following to "true".

caps.AddMetadataSetting("record_network", "true");

Run a local test

With our Local Tunnel, you can run a test on a local URL or behind your company's firewall. There are two different ways to connect the CrossBrowserTesting local tunnel: our Node.js client and our Chrome Extension.

To learm more about setting up, starting, and using your tunnel connection, see About Local Testing.

When a tunnel is open, any automated test can access websites locally, behind a firewall, or across a proxy. There is no need to set a capability during your test.

See Also

Selenium and Java
Selenium and Ruby
Use of DesiredCapabilities has been deprecated

Highlight search results