//
// Copyright © 2018 Ranorex All rights reserved
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Ranorex.Core.Testing;
namespace Ranorex.AutomationHelpers.UserCodeCollections
{
///
/// A collection of useful general helper methods.
///
[UserCodeCollection]
public static class SystemLibrary
{
private const string libraryName = "SystemLibrary";
private static readonly Dictionary timers = new Dictionary();
///
/// Kills a process.
///
/// Name of the process to kill
[UserCodeMethod]
public static void KillProcess(string processname)
{
Process[] processes = Process.GetProcessesByName(processname);
if (processes.Length == 0)
{
Report.Error(string.Format("Process '{0}' not found.", processname));
}
foreach (Process p in processes)
{
try
{
p.Kill();
Report.Info("Process killed: " + p.ProcessName);
}
catch (Exception ex)
{
Utils.ReportException(ex, libraryName);
}
}
}
///
/// Starts a new timer.
///
/// Name of the timer
[UserCodeMethod]
public static void StartTimer(string timerName)
{
if (timers.ContainsKey(timerName))
{
throw new ArgumentException(string.Format("Timer with name '{0}' already exists", timerName));
}
timers.Add(timerName, System.DateTime.Now);
Report.Log(ReportLevel.Info, "Timer", "Started: '" + timerName + "'");
}
///
/// Stops a timer.
///
/// Name of the timer to stop
[UserCodeMethod]
public static TimeSpan StopTimer(string timerName)
{
if (timers.ContainsKey(timerName))
{
System.DateTime end = System.DateTime.Now;
System.DateTime start = timers[timerName];
TimeSpan duration = end - start;
timers.Remove(timerName);
Report.Log(
level: ReportLevel.Info,
category: "Timer",
message: string.Format("Stopped: '{0}' (duration: {1} seconds)", timerName, duration.TotalMilliseconds / 1000));
return duration;
}
throw new Exception(string.Format("Timer '{0}' does not exist.", timerName));
}
///
/// Returns the current time and date as a string in the specified format.
///
/// The format the time and date are returned in. Default = dd.MM.yyyy
/// The current time and date as a string.
[UserCodeMethod]
public static string GetDateTimeAsString(string expectedFormat = "dd.MM.yyyy")
{
return System.DateTime.Now.ToString(expectedFormat);
}
}
}