Running Command Line in Remote Machine Using WMI

Recently I had to find a way for running a command line process in server. I had to spend fair bit of time googling for various approaches of doing it. Most of them are by using PSExec. However there is another approach of using WMI (Windows Management Instrumentation) . Below is one of the approach , which I found at msdn blog. Below method can be accessed anywhere by ProcessWMI p = new ProcessWMI(); p.ExecuteRemoteProcessWMI(remoteMachine, sBatFile, timeout); The solution has multiple parts as follows ...

September 8, 2018

Running Powershell Remotely

Code snippet for running power shell on a remote machine. Loosely based on blog post here and here Code below is based on the sample code given in above two links Add reference to System.Management.Automation using System.Management.Automation; using System.Management.Automation.Runspaces; internal void runPowershellRemotely(string location, string scriptToBeRun) { string userName = ConfigurationManager.AppSettings["RemoteMachineLogonUser"]; string password = ConfigurationManager.AppSettings["RemoteMachineUserPassword"]; var securestring = new SecureString(); foreach (Char c in password){ securestring.AppendChar(c); } PSCredential creds = new PSCredential(userName, securestring); // Remove logging if not needed log.Info(String.Format("\tPOWERSHEL : Running Powershell {0} at location {1}", scriptToBeRun, location)); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); connectionInfo.ComputerName = ConfigurationManager.AppSettings["RemoteMachine"]; connectionInfo.Credential = creds; Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo); runspace.Open(); using (PowerShell ps = PowerShell.Create()) { ps.Runspace = runspace; ps.AddScript(@"cd "+ location); ps.AddScript(scriptToBeRun); try { var results = ps.Invoke(); log.Info("\tPOWERSHEL : Results from Powershell Script is ---------------------------"); foreach(var x in results) { log.Info(x.ToString()); } log.Info("\tPOWERSHEL : End of results--------------------------------- ---------------------------"); } catch (Exception e) { log.Error("\tPOWERSHEL : Exception from running Powershell Script is" + e.ToString()); } } runspace.Close(); }

September 5, 2018

Working With Windows Services

Below is code snippet for working with windows service. It helps to find status of service, start , stop and restart as required. We need to pass in details of windows services name ( as shown i services.msc ) and machine name(should be in same network). using System.ServiceProcess; internal string FindStatus(string service, string server) { var myService = new ServiceController(service, server); log.Info(String.Format("\tStatus of {0} service in {1} is {2}", service, server, myService.Status.ToString())); return myService.Status.ToString(); } internal string StopService(string service, string server) { var myService = new ServiceController(service, server); if (myService.Status == ServiceControllerStatus.Running) { myService.Stop(); myService.WaitForStatus(ServiceControllerStatus.Stopped); log.Info(String.Format("\t{0} service Stopped in {1}. Current Status is {2}", service, server, myService.Status.ToString())); } return myService.Status.ToString(); } internal string StartService(string service, string server) { var myService = new ServiceController(service, server); if (myService.Status == ServiceControllerStatus.Stopped) { myService.Start(); myService.WaitForStatus(ServiceControllerStatus.Running); log.Info(String.Format("\t{0} service Started in {1}. Current Status is {2}", service, server, myService.Status.ToString())); } return myService.Status.ToString(); }

September 3, 2018

Comparing XML file Structure without XSD

Code snippet for comparing two xml files without using xsd for validating their structure is same ( nodes and arguments should be same. Values of each node/argument can be different). internal void VerifyMessageHaveSimilarStructureOfTemplate(string inputXml, string templateXml) { var docA = new XmlDocument(); var docB = new XmlDocument(); docA.LoadXml(inputXml); docB.LoadXml(templateXml); var isDifferent = DoTheyHaveDiferentStructure(docA.ChildNodes, docB.ChildNodes); log.Info("Result of Checking for difference of Input xml with template is : " + isDifferent.ToString()); } private bool DoTheyHaveDiferentStructure(XmlNodeList xmlNodeListA, XmlNodeList xmlNodeListB) { if (xmlNodeListA.Count != xmlNodeListB.Count) return true; for (var i = 0; i < xmlNodeListA.Count; i++) { var nodeA = xmlNodeListA[i]; var nodeB = xmlNodeListB[i]; if (nodeA.Attributes == null) { if (nodeB.Attributes != null) return true; else continue; } if (nodeA.Attributes.Count != nodeB.Attributes.Count || nodeA.Name != nodeB.Name) return true; List<string> AttributeNameA = new List<string>(); List<string> AttributeNameB = new List<string>(); for (var j = 0; j < nodeA.Attributes.Count; j++) { AttributeNameA.Add(nodeA.Attributes[j].Name); AttributeNameB.Add(nodeB.Attributes[j].Name); // -- If attribute position should be same, then include below as well //var attrA = nodeA.Attributes[j]; //var attrB = nodeB.Attributes[j]; //if (attrA.Name != attrB.Name) return true; } AttributeNameA.Sort(); AttributeNameB.Sort(); if(! AttributeNameA.SequenceEqual(AttributeNameB)) return true; if (nodeA.HasChildNodes && nodeB.HasChildNodes) { return HaveDiferentStructure(nodeA.ChildNodes, nodeB.ChildNodes); } else { return true; } } return false; }

September 1, 2018

Converting Datatable to List of Objects in CSharp

There are many cases where we will have to convert Dataset into list of objects. Below is a generic method using reflection to achieve that. Below will work only if datatable column name and class property name are same and they match exactly. using System.Reflection internal static List<T> ConvertDataTableToList<T>(DataTable dt) { List<T> data = new List<T>(); foreach (DataRow row in dt.Rows) { T item = GetItem<T>(row); data.Add(item); } return data; } internal static T GetItem<T>(DataRow dr) { Type temp = typeof(T); T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in dr.Table.Columns) { foreach (PropertyInfo pro in temp.GetProperties()) { if (pro.Name == column.ColumnName) pro.SetValue(obj, dr[column.ColumnName], null); else continue; } } return obj; } Usage of this will be like below ...

August 10, 2018

Running API Test using Cypress

Cypress is not just UI automation tool . It can be used for testing APIs as well . Even though we have other tools like Postman, Newman, Rest Assured, SOAP UI etc for testing APIs, I believe cypress is a good alternative for testing API. It will help to use same tool for both UI and API test automation. Demo Let us look at a sample API test case. In below example, we trigger a API call to http://services.groupkt.com/country/get/iso2code/AU and validate below in the response. ...

May 27, 2018

UI Automation with cypress

When we talk about UI automation for browsers, the default tool which comes to mind is Selenium. There are different wrappers around selenium like protractor, Nightwatch , selenium webdriver etc. All of them are build on top of selenium and have all advantages /disadvantages of selenium. All of the control browser by executing remote commands through Network. We will most probably need additional libraries, framework etc to make full use of selenium. ...

May 11, 2018

Writing Tests in Postman

In previous blog post, we saw how to use BDD format for writing test cases in postman. Most important part of writing tests in postman is understanding various features available. Let us explore various options available . The examples specified in postman documentation, have lot of information about how to setup postman bdd, use chai http assertions, create custom assertions and use before and after hooks. Please import them into postman and try that by yourself to familiarise with postman BDD. Below is only few examples from them. ...

May 3, 2018

Postman BDD

In Previous blog post,we discussed about how to use postman and how to use collections using newman and data file. If you haven’t read that , please have a read through first . In previous examples, we discussed about writing tests/assertions in postman. We followed normal Javascript syntax for writing test cases including asserting various factors of response ( like content , status code etc). Eventhough this is a straightforward way of writing, many people would like to use existing javascript test library like Mocha. They can use postman - bdd libraries. ...

April 28, 2018

Gulp Task For Running Automated Test

Gulp is a toolkit for automating painful or time-consuming task in your development workflow, so you can stop messing around and build something. Gulp can be used for creating a simple task to run automated test cases. Firstly, we will create package.json file for this project. This can be done by below command from project folder. It will prompt you to enter a list of information required for creating package.json file ...

March 20, 2018