Example #1
0
 /// <summary>
 /// Kill a pocess given the name of the process
 /// The process is killed if the pocess is longer than 3 seconds
 /// </summary>
 /// <param name="nameOfProcessToKill"></param>
 public static void killProcessByNames(string nameOfProcessToKill)
 {
     SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName(), nameOfProcessToKill);
     string[] nameOfProcessToKillList = nameOfProcessToKill.Split(',');
     foreach (string nameOfProcess in nameOfProcessToKillList)
     {
         try
         {
             foreach (Process proc in Process.GetProcessesByName(nameOfProcess))
             {
                 DateTime procStartTime = proc.StartTime;
                 DateTime dateNow       = DateTime.Now;
                 long     diff          = (long)(dateNow - procStartTime).TotalMilliseconds;
                 //Kill the process if longer than 3 secunds
                 if (diff > 3000 && !(proc.ProcessName.ToLower().Contains("excel")))
                 {
                     proc.Refresh();
                     proc.Kill();
                 }
                 if (proc.ProcessName.ToLower().Contains("excel") && diff < 3000)
                 {
                     proc.Refresh();
                     proc.Kill();
                 }
             }
         }
         catch (Exception e)
         {
             SAFINCALog.Warning("The process, " + nameOfProcessToKill + " could not be killed. See Exception: \n" + e);
         }
         Thread.Sleep(1000);
     }
 }
        public static long GetCurrentTimeMillis()
        {
            SAFINCALog.Debug(GetClassAndMethodName());
            DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return((long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds));
        }
        /**Execute the java script, scriptToExecute, on the site driver, e.g. to simulate an action that cannot be achieved by a webdriver action.
         * Such actions could be as forcing the browser to show hidden elements, get browser information, etc.
         * The java script execution should be used with caution since it not an exact simulation of the user behavior.
         * @param scriptToExecute
         * @return an object
         */
        public Object ExecuteJavaScript(string pageNameToSwitchTo, string frameNameToSwitchTo, string scriptToExecute, params IWebElement[] args)
        {
            SAFINCALog.Debug("scriptToExecute: " + scriptToExecute);
            Object obj           = null;
            long   maxTimeToWait = CommonUtilities.GetCurrentTimeMillis() + CommonUtilities.GLOBAL_TIMEOUT_TIME_IN_MSEC;

            while (obj == null && maxTimeToWait > CommonUtilities.GetCurrentTimeMillis())
            {
                try
                {
                    //driver = FindWebDriverElement.SwitchToFrameOrWindowByName(this.driver, pageNameToSwitchTo, frameNameToSwitchTo);
                    IJavaScriptExecutor iJavaScriptExecutor = (IJavaScriptExecutor)driver;

                    {
                        if (args != null && args.Length > 0)
                        {
                            obj = (Object)iJavaScriptExecutor.ExecuteScript(scriptToExecute, args[0]);
                            SAFINCALog.Debug("object: " + obj);
                            return(obj);
                        }
                        else
                        {
                            obj = (Object)iJavaScriptExecutor.ExecuteScript(scriptToExecute);
                            SAFINCALog.Debug("object: " + obj);
                            return(obj);
                        }
                    }
                }
                catch (Exception e)
                {
                }
            }
            return(obj);
        }
        public static string GetCurrentDate()
        {
            SAFINCALog.Debug(GetClassAndMethodName());
            DateTime dt   = DateTime.Now;
            string   date = dt.ToString("dd_MM_yyyy_HH_mm_ss");

            return(date);
        }
        /// <summary>
        /// Same as {@methodref executeJavaScript} but with a WaitForAjaxCallToFinish before executing the java script
        /// </summary>
        /// <param name="pageNameToSwitchTo"></param>
        /// <param name="frameNameToSwitchTo"></param>
        /// <param name="scriptToExecute"></param>
        /// <returns></returns>
        public Object executeJavaScriptWithWaitForAjaxCallToFinish(string pageNameToSwitchTo, string frameNameToSwitchTo, string scriptToExecute)
        {
            SAFINCALog.Debug("scriptToExecute: " + scriptToExecute);
            WaitForAjaxCallToFinish();
            Object obj = ExecuteJavaScript(pageNameToSwitchTo, frameNameToSwitchTo, scriptToExecute);

            WaitForAjaxCallToFinish();
            return(obj);
        }
        /// <summary>
        /// Return a list of web element using the javascript to find element
        /// </summary>
        /// <param name="pageNameToSwitchTo"></param>
        /// <param name="frameNameToSwitchTo"></param>
        /// <param name="scriptToExecute"></param>
        /// <returns></returns>
        public ReadOnlyCollection <IWebElement> ExecuteJavaScriptIWebElementList(string pageNameToSwitchTo, string frameNameToSwitchTo, string scriptToExecute)
        {
            SAFINCALog.Debug("scriptToExecute: " + scriptToExecute);
            driver = FindWebDriverElement.SwitchToFrameOrWindowByName(this.driver, pageNameToSwitchTo, frameNameToSwitchTo);
            IJavaScriptExecutor iJavaScriptExecutor          = (IJavaScriptExecutor)driver;
            ReadOnlyCollection <IWebElement> iWebElementList = (ReadOnlyCollection <IWebElement>)iJavaScriptExecutor.ExecuteScript(scriptToExecute);

            SAFINCALog.Debug("iWebElementList: " + iWebElementList);
            return(iWebElementList);
        }
        public static string CreateFolder(string folderPath)
        {
            SAFINCALog.Debug(GetClassAndMethodName());
            string fullDirectoryPath = GetProjectDirectory() + folderPath;

            if (!Directory.Exists(fullDirectoryPath))
            {
                Directory.CreateDirectory(fullDirectoryPath);
            }
            return(fullDirectoryPath);
        }
        public static string GetProjectDirectory()
        {
            SAFINCALog.Debug(GetClassAndMethodName());
            var    outPutDirectory = GetOutPutDirectory();
            int    startIndex      = outPutDirectory.IndexOf("\\") + 1;
            int    binIndex        = outPutDirectory.IndexOf("bin");
            int    length          = binIndex - startIndex;
            string projectDir      = outPutDirectory.Substring(startIndex, length);

            return(projectDir);
        }
 /// <summary>
 /// Used Only wiht JQuery based web runningApplication
 /// </summary>
 public void WaitForAjaxCallToFinish()
 {
     SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName());
     try
     {
         AjaxCallToFinish();
     }
     catch
     {
         SAFINCALog.Info(CommonUtilities.GetClassAndMethodName(), "CALLING THE JAVA SCRIPT THE FIST TIME FAILED. TRYING THE ONE MORE TIME");
         AjaxCallToFinish();
     }
 }
Example #10
0
        /// <summary>
        /// Take a print screen and save the image as .png file.
        /// </summary>
        /// <param name="imageFullPathAndName"></param>
        public static void CreateAndSaveScreenShot(string imageFullPathAndName)
        {
            SAFINCALog.Debug(GetClassAndMethodName());
            Screen   screen   = Screen.PrimaryScreen;
            Bitmap   bmp      = new Bitmap(screen.Bounds.Width, screen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(bmp);

            graphics.CopyFromScreen(0, 0, 0, 0, new Size(screen.Bounds.Width, screen.Bounds.Height));
            bmp.Save(imageFullPathAndName, ImageFormat.Png);
            string imageFullPathAndNameWithoutC    = imageFullPathAndName.Replace("C:", "").Replace("C:", "");
            string imageFullPathAndNameIncludeFile = "file://///" + System.Environment.MachineName + imageFullPathAndNameWithoutC;

            SAFINCALog.Info("The screenshot is saved: " + imageFullPathAndNameIncludeFile);
        }
Example #11
0
        /// <summary>
        /// Wait for a page to loaded on the screen
        /// </summary>
        private void AjaxCallToFinish()
        {
            string documentReadyState         = "";
            string documentReadyStateStripped = "";
            long   maxTimeToWait = CommonUtilities.GetCurrentTimeMillis() + CommonUtilities.GLOBAL_TIMEOUT_TIME_IN_MSEC;

            while (!documentReadyStateStripped.Equals("complete") && maxTimeToWait > CommonUtilities.GetCurrentTimeMillis())
            {
                try
                {
                    SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName());
                    String scriptToExecute = "return document.readyState";
                    documentReadyState         = (string)driver.ExecuteScript(scriptToExecute);
                    documentReadyStateStripped = documentReadyState.Trim().ToLower();
                }
                catch
                {
                    SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName(), "JAVASCRIPT NOT READY YET");
                    Thread.Sleep(500);
                }
            }
        }
Example #12
0
        /// <summary>
        /// Deletes all the files within the specified folder
        /// </summary>
        /// <param name="folder">The folder from which we wish to delete all of the files</param>
        public static void ClearFolder(DirectoryInfo folder)
        {
            SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName(), folder.FullName);
            // Iterate each file
            foreach (FileInfo file in folder.GetFiles())
            {
                try
                {
                    // Delete the file, ignoring any exceptions
                    file.Delete();
                }
                catch (Exception)
                {
                }
            }

            // For each folder in the specified folder
            foreach (DirectoryInfo subfolder in folder.GetDirectories())
            {
                // Clear all the files in the folder
                ClearFolder(subfolder);
            }
        }
Example #13
0
 /// <summary>
 /// Clear the cache for Inernet Explorer
 /// </summary>
 public static void ClearIECache()
 {
     SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName());
     // Clear the special cache folder
     ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)));
 }
        /// <summary>
        /// Get the web element according to a given page name, frame name and location(identification method for the element)
        ///
        /// </summary>
        /// <param name="pageNameToSwitchTo"></param>
        /// <param name="frameNameToSwitchTo"></param>
        /// <param name="by"></param>
        /// <returns></returns>
        private IWebElement waitAndGetElement(string pageNameToSwitchTo, string frameNameToSwitchTo, params By[] by)
        {
            Exception exception = null;

            SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName());
            String      errorMessage = "No Element Was Found by: " + by[0] + "\n EXCEPTION THROWN: ";
            IWebElement webElement   = null;

            if (waitForAjax)
            {
                //Check the status of the page by executing the javascipt, document.status, to see if the page is fully loaded
                //This check makes the system slower but minimize the risk of failure
                javaScriptCalls.WaitForAjaxCallToFinish();
            }
            //Max time to wait for an element
            long maxTimeToWait = CommonUtilities.GetCurrentTimeMillis() + CommonUtilities.GLOBAL_TIMEOUT_TIME_IN_MSEC;

            while (webElement == null && maxTimeToWait > CommonUtilities.GetCurrentTimeMillis())
            {
                try
                {
                    //Modify the diver by switching page and frame if needed
                    // driver = SwitchToFrameOrWindowByName(driver, pageNameToSwitchTo, frameNameToSwitchTo);

                    if (by.Length == 1)
                    {
                        var webElementList    = driver.FindElements(by[0]);
                        int nrOfFoundElements = webElementList.Count;
                        if (nrOfFoundElements > 1)
                        {
                            foreach (IWebElement webElementFromList in webElementList)
                            {
                                SAFINCALog.Warning("Tag name element: " + webElementFromList.TagName);
                                SAFINCALog.Warning("Text element: " + webElementFromList.Text);
                            }

                            errorMessage = "TOO MANY Elements Was Found by: " + by + "\n EXCEPTION THROWN: ";
                            //throw new Exception();
                        }
                        //Create a WebDriver wait to wait for the element to show on the page
                        var webDriverWait = new WebDriverWait(new SystemClock(), driver, TimeSpan.FromSeconds(CommonUtilities.GLOBAL_TIMEOUT_TIME_IN_MSEC / 1000), TimeSpan.FromMilliseconds(500));
                        webElement = webDriverWait.Until(ExpectedConditions.ElementExists(by[0]));
                    }
                    else
                    {
                        var    webElementList = driver.FindElements(by[0]);
                        string byLocator      = by[1].ToString().ToLower().Replace(" ", "");

                        if (byLocator.Contains("by.tagname"))
                        {
                            foreach (IWebElement webElementFromList in webElementList)
                            {
                                string webElementTagName = "by.tagname:" + webElementFromList.TagName.ToLower().Replace(" ", "");
                                SAFINCALog.Debug(CommonUtilities.GetClassAndMethodName(), "webElementTagName: " + webElementTagName, "byLocator: " + byLocator);
                                if (byLocator.Contains(webElementTagName))
                                {
                                    webElement = webElementFromList;
                                    break;
                                }
                            }
                        }
                        else if (byLocator.Contains("##"))
                        {
                            int    startIndex   = by[1].ToString().IndexOf("#") + 1;
                            int    endIndex     = by[1].ToString().IndexOf("##") - startIndex;
                            string s            = by[1].ToString().Substring(startIndex, endIndex);
                            int    elementIndex = int.Parse(by[1].ToString().Substring(startIndex, endIndex));
                            webElement = webElementList[elementIndex];
                        }
                    }
                }


                catch (Exception e)
                {
                    exception = e;
                    Thread.Sleep(500);
                }
            }

            if (webElement == null)
            {
                throw new DriverServiceNotFoundException(errorMessage + (exception == null? "":exception.ToString()));
            }
            return(webElement);
        }
        public void SeleniumSetup()
        {
            try
            {
                Console.WriteLine("Starting Driver...........");

                String browser = ConfigurationManager.AppSettings["WEB_BROWSER_TO_RUN"];

                var options = new InternetExplorerOptions
                {
                    IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                    EnsureCleanSession = true,
                    //ForceCreateProcessApi=true
                    EnableNativeEvents = false,
                    RequireWindowFocus = false,
                    IgnoreZoomLevel    = true
                };

                ChromeOptions chromeOptions = new ChromeOptions();

                chromeOptions.AddArgument("--test-type");
                chromeOptions.AddArguments("chrome.switches", "--disable-extensions");

                chromeOptions.AddArgument("start-maximized");
                chromeOptions.AddArgument("--enable-automation");
                chromeOptions.AddArgument("test-type=browser");
                chromeOptions.AddArgument("disable-infobars");

                if (browser.Contains("Internet"))
                {
                    driver = new InternetExplorerDriver(TestContext.DeploymentDirectory, options);
                }
                else if (browser.Contains("Chrome"))
                {
                    driver = new ChromeDriver(chromeOptions);
                }

                // driver = new ChromeDriver();
                else
                {
                    driver = null;
                }


                if (driver != null)
                {
                    // Javascript Class
                    javaScriptCalls        = new JavaScriptCalls();
                    javaScriptCalls.Driver = driver;

                    //Find Web Driver
                    findWebDriverElement                 = new FindWebDriverElement();
                    findWebDriverElement.Driver          = driver;
                    findWebDriverElement.JavaScriptCalls = javaScriptCalls;

                    //Operate Web Element
                    operateOnWebDriverElement = new OperateOnWebDriverElement();
                    operateOnWebDriverElement.FindWebDriverElement = findWebDriverElement;
                    operateOnWebDriverElement.JavaScriptCalls      = javaScriptCalls;

                    SVLGridOperation = new SVLGridOperation();
                    safeebbalog      = new SAFINCALog();
                    switcher         = new IframeSwitcher();
                    incaFunction     = new IncaGenericFunction();

                    GoToSite(ConfigParameters.WEB_APPLICATION_URL);
                    // driver.Manage().Window.Maximize();
                    //  }
                    // else
                    //  {
                    // SAFINCALog.Debug("Browser type not specified in the config file...........");
                    //  }
                }
            }
            catch (Exception e)
            {
                SAFINCALog.Debug("Error Starting Web Driver...........");
                Console.WriteLine(e.StackTrace);
            }
        }