Chuan Chuan Law

DevOps | Software Automation | Continuous Integration

Tag: C#

Testing API in C# – WebClient – How To Post A Request

Testing API in C# – WebClient – How To Get A Request

Below is how to Get a request using WebClient instead of HTTPClient


Testing API In C# – HttpClient – How To Get A Request

Back in days when I was working with Ruby on a MacBook Pro, I got Curl. However, now as I am using a PC in a .NET shop, I need to use compatible technology to test API – HttpClient is my solution.

Install the Web API Client Libraries via Package Manager Console

Install-Package Microsoft.AspNet.WebApi.Client

Sample code as below:

  • [Fact] is merely an XUnit notation indicating that this is a unit test
  • using creates an HttpClient instance which is only active within the scope
  • await suspends operation until the execution is completed
  • Method is declared as async as HttpClient methods perform I/O
  • ReadAsStringAsync() will read the output as string
  • JsonConvert.Deserializeobject<> will parse the string into the object model LanguageDictionary
  • You can use many methods from the HttpResponseMessage to verify the response from the API


Uploading Files in Windows Using Selenium C#

I have encountered a situation where I need to click on a button in order to upload a file.

I test this using Selenium C# by:

1. Entering the file path into the box


2. Calling the Javascript function to simulate what happens when “Upload” button is clicked

IJavaScriptExecutor js = driver as IJavaScriptExecutor;

string script = “__doPostBack(‘uploadFileButton’,”)”;


SpecFlow + C# – Read a row from database to check the value


 [Then(@”we verify that the (.*) row contains (.*) of (.*)”)]
        public void ThenWeVerifyThatTheFirstRowContainsLInstIDOf410(String row, String field, String value)
            SqlConnection ThisConnection = new SqlConnection(@”Server=;Database=pp5_410_LK;Trusted_Connection=True”);
            SqlCommand thisCommand = ThisConnection.CreateCommand();
            if (String.Compare(row,”first”)==0)
                thisCommand.CommandText = “select * from CostCentre where sCostCentreNo in (select MAX(sCostCentreNo) from CostCentre where lInstID=410) and lInstID=410”;
            if (String.Compare(row, “last”) == 0)
                thisCommand.CommandText = “select * from CostCentre where sCostCentreNo in (select MIN(sCostCentreNo) from CostCentre where lInstID=410) and lInstID=410”;
            SqlDataReader thisReader = thisCommand.ExecuteReader();
                while (thisReader.Read())
                    Assert.AreEqual(value, thisReader[field].ToString());
            catch (Exception e)

SpecFlow + C# – Execute a script and how to make step definitions reusable

//This is how we can make the step definitions reusable

[When(@”I run the (.*)”)]
            public void WhenIRunTheGenericImporter(String importer)
               if (String.Compare(importer,”GenericImporter”)==0)
                   StartInfo.FileName = @”C:\TrunkbinDebugWinExecutablesGenericImporter.exe”;
               if (String.Compare(importer,”PageUpImporter”)==0)
                   StartInfo.FileName = @”C:\TrunkbinDebugWinExecutablesPageUpImporter.exe”;
//Passing in argument to the command
                   StartInfo.Arguments = @”lk 410″;

               ProcessStartInfo StartInfo = new ProcessStartInfo();

               Process Process = new Process();
               StartInfo.RedirectStandardOutput = true;
               StartInfo.RedirectStandardError = true;
               StartInfo.UseShellExecute = false;
               StartInfo.CreateNoWindow = true;
               Process.StartInfo = StartInfo;

SpecFlow + C# – Connect to a SQL database


 [Given(@”we clean the database”)]
        public void GivenWeCleanTheDatabase()
           SqlConnection ThisConnection = new SqlConnection(@”Server=1.10.26;Database=410_LK;Trusted_Connection=True”);
            SqlCommand thisCommand = ThisConnection.CreateCommand();
            thisCommand.CommandText = “delete from costcentre where linstid = 410”;
            SqlDataReader thisReader = thisCommand.ExecuteReader();

Selenium – C#

This post contains the key commands for Selenium in C#

  • Initialise a new driver

IWebDriver driver = new FirefoxDriver();

  • Navigation


  • Clear a field


  • Entering a text

driver.FindElement(By.XPath(“//input[@name=’sName’]”).SendKeys(“Testing 123”);

  • Click on an element


  • Wait until an element is found

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

IWebElement employeeSearch = wait.Until((d) =>

{ return






  • Switch to other windows
ReadOnlyCollection handles = driver.WindowHandles;
  • Select an element
new SelectElement(driver.FindElement(By.XPath(“//select[@id=’test’]”))).SelectByIndex(2);
  • Sleep

  • Quit

© 2019 Chuan Chuan Law

Theme by Anders NorenUp ↑