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

Creating utility tool as portable EXE

Recently one of my colleague approached me asking to help on creating a utility tool using selenium web driver. The requirement was simple which includes accepting few arguments from the command line and then open a browser and complete some actions on browser based on inputs provided. Having worked on selenium web driver for a few years, I thought this is relatively simple and can be done quickly. It is implemented as a C# console app which had reference to selenium web driver. It accepts few arguments from command line and based on the values it opens up chrome browser and completes the action. The initial version was already there on which I made some modifications. We gave a demo to the user and thought it is all done. ...

October 3, 2018

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

Deploying Octopress to AWS S3 and CloudFront

I was hosting my blog on github pages for past one year. Last week I decided to move hosting of my blog to AWS S3. There are obvious advantages of hosting a static site on S3. Moreover the cost of hosting is also minimal. There are many blogs in internet which explains the steps for hosting an octopress blog on S3. Since this is my first exposure to AWS world, I did had a learning curve to get this done. Below are highlevel steps involved in hosting in S3. ...

September 23, 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

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