Sending Emails through SMTP in C#

Recently I was looking for some code for sending emails via SMTP in C#. Below are few links which I found with some reusable code. Overall it looks fine , but have to include multiple validations for error handling . https://gist.github.com/robertgreiner/1529127 https://gist.github.com/gzuri/2850914 https://gist.github.com/pranavq212/1cbecac15abb229d40f1ad0765aa4dce https://gist.github.com/TrailCoder502/6254bdfcfe71c4000600 In Nutshell, flow is as below Define a function to send email which accepts an input Email object Validate the email object to ensure all mandatory fields are present and correct Create a new MailMessage object and SMTPClient Object and send email Above gist links have some reusable code to achieve step 3 of above.

April 9, 2019

Find DotNet Version Using Powershell

I recently faced an issue where one utility tool created by me was not running properly on another machine which had different dot net version installed. During troubleshooting, I was looking for ways to identify the installed dotnet version. Most of the links in google suggested to look for release value in registry as specified here. Below powershell script will list down installed dotnet version on a machine. This is based on dotnet version listed on https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed. We may have to update below snippet as when new versions are released. Currently it supports upto dotnet 4.7.2 ...

October 3, 2018

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

Extracting Substring using Javascript

In previous blogs here , I have explained how we return a XML response using mountebank. However , most of the time, we will have to make some modification to the template response before returning a response. Say for example, we may have to replace details like timestamp, or use an input from request parameter and update that in response etc. One of the easiest way to do this without using other frameworks like xml2js etc is to extract the substring between the node values and replace it . Below is a code snippet which will help to achieve this ...

July 21, 2017

Zip and Extract zip files using Csharp

On corporate world, most of the times, the access required for installing applications and connecting to internet will be limited. There can be scenarios where access to install Mountebank using npm will not be available. In those circumstances, we can just unzip the zip file downloaded from self contained archive links in mbtest.org Below code snippet can be used for extracting the zip files on the fly , so that it can be used for running test cases on any machine. ...

April 20, 2017

Running Command Line from C#

Code Snippet private void RunCLIjobsOnLocal(string arguments, int WaitTimePerCommand) { var psi = new ProcessStartInfo(); psi.CreateNoWindow = true; //This hides the dos-style black window that the command prompt usually shows psi.FileName = @"cmd.exe"; psi.Arguments = "/C " + arguments; psi.RedirectStandardOutput = true; psi.RedirectStandardInput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; var sspw = new SecureString(); foreach (var c in password) { sspw.AppendChar(c); } psi.Domain = domain; psi.UserName = userName; psi.Password = sspw; psi.WorkingDirectory = @"C:\"; using (Process process = new Process()) { try { process.StartInfo = psi; process.Start(); var procId = process.Id; string owner = GetProcessOwner(procId); // Synchronously read the standard output of the spawned process. StreamReader reader = process.StandardOutput; string output = reader.ReadToEnd(); reader = process.StandardError; string error = reader.ReadToEnd(); if(error.Length >0) process.WaitForExit(); } catch (Exception e) { log.Error(e.Message + "\n" + e.StackTrace); } } } private string GetProcessOwner(int processId) { string query = "Select * From Win32_Process Where ProcessID = " + processId; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); foreach (ManagementObject obj in processList) { string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0) { return argList[1] + "\\" + argList[0]; } } return "NO OWNER"; }

September 8, 2016

Data Driven Framework - Excel

In previous blog post, I have explained about how use XML for making a data driven framework for automation testing . It can be found here. I have also written about how to use jxl library for reading from excel and writing into Excel. Below is another code snippet to read all values of a row and save it into a hash map for accessing later during automation test. public HashMap GetAllDataForARow (String sheet, int Row){ HashMap DataMap = new HashMap(); try { Workbook wrk1 = Workbook.getWorkbook(new File(dataPath)); //Obtain the reference to the first sheet in the workbook Sheet sheet1 = wrk1.getSheet(sheet); int x =0; Cell colArow1 , colArow2; do { colArow1 = sheet1.getCell(x,0); colArow2 = sheet1.getCell(x,Row); DataMap.put(colArow1.getContents(), colArow2.getContents()); x=x+1; }while (colArow1.getContents() != ""); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }catch (IndexOutOfBoundsException e){ } return DataMap; }

July 30, 2016