Exemplo n.º 1
0
        // Find pattern as //a[@title="SHIFT <> Å"]
        public static String XPathEquals(String element, String attribute, String value)
        {
            String xPathEquals = "//" + element + "[@" + attribute + "=\"" + value + "\"]";

            SAFEBBALog.Debug("xPathEquals: " + xPathEquals);
            return(xPathEquals);
        }
Exemplo n.º 2
0
        /**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)
        {
            SAFEBBALog.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]);
                            SAFEBBALog.Debug("object: " + obj);
                            return(obj);
                        }
                        else
                        {
                            obj = (Object)iJavaScriptExecutor.ExecuteScript(scriptToExecute);
                            SAFEBBALog.Debug("object: " + obj);
                            return(obj);
                        }
                    }
                }
                catch (Exception e)
                {
                }
            }
            return(obj);
        }
Exemplo n.º 3
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)
 {
     SAFEBBALog.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)
         {
             SAFEBBALog.Warning("The process, " + nameOfProcessToKill + " could not be killed. See Exception: \n" + e);
         }
         Thread.Sleep(1000);
     }
 }
Exemplo n.º 4
0
        public static long GetCurrentTimeMillis()
        {
            SAFEBBALog.Debug(GetClassAndMethodName());
            DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return((long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds));
        }
Exemplo n.º 5
0
        public static string GetCurrentDate()
        {
            SAFEBBALog.Debug(GetClassAndMethodName());
            DateTime dt   = DateTime.Now;
            string   date = dt.ToString("dd_MM_yyyy_HH_mm_ss");

            return(date);
        }
Exemplo n.º 6
0
        /// <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)
        {
            SAFEBBALog.Debug("scriptToExecute: " + scriptToExecute);
            WaitForAjaxCallToFinish();
            Object obj = ExecuteJavaScript(pageNameToSwitchTo, frameNameToSwitchTo, scriptToExecute);

            WaitForAjaxCallToFinish();
            return(obj);
        }
Exemplo n.º 7
0
        /// <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)
        {
            SAFEBBALog.Debug("scriptToExecute: " + scriptToExecute);
            driver = FindWebDriverElement.SwitchToFrameOrWindowByName(this.driver, pageNameToSwitchTo, frameNameToSwitchTo);
            IJavaScriptExecutor iJavaScriptExecutor          = (IJavaScriptExecutor)driver;
            ReadOnlyCollection <IWebElement> iWebElementList = (ReadOnlyCollection <IWebElement>)iJavaScriptExecutor.ExecuteScript(scriptToExecute);

            SAFEBBALog.Debug("iWebElementList: " + iWebElementList);
            return(iWebElementList);
        }
Exemplo n.º 8
0
        public static string CreateFolder(string folderPath)
        {
            SAFEBBALog.Debug(GetClassAndMethodName());
            string fullDirectoryPath = GetProjectDirectory() + folderPath;

            if (!Directory.Exists(fullDirectoryPath))
            {
                Directory.CreateDirectory(fullDirectoryPath);
            }
            return(fullDirectoryPath);
        }
Exemplo n.º 9
0
        public static string GetProjectDirectory()
        {
            SAFEBBALog.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);
        }
Exemplo n.º 10
0
 /// <summary>
 /// Used Only wiht JQuery based web runningApplication
 /// </summary>
 public void WaitForAjaxCallToFinish()
 {
     SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName());
     try
     {
         AjaxCallToFinish();
     }
     catch
     {
         SAFEBBALog.Info(CommonUtilities.GetClassAndMethodName(), "CALLING THE JAVA SCRIPT THE FIST TIME FAILED. TRYING THE ONE MORE TIME");
         AjaxCallToFinish();
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Take a print screen and save the image as .png file.
        /// </summary>
        /// <param name="imageFullPathAndName"></param>
        public static void CreateAndSaveScreenShot(string imageFullPathAndName)
        {
            SAFEBBALog.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;

            SAFEBBALog.Info("The screenshot is saved: " + imageFullPathAndNameIncludeFile);
        }
Exemplo n.º 12
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
                {
                    SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName());
                    String scriptToExecute = "return document.readyState";
                    documentReadyState         = (string)driver.ExecuteScript(scriptToExecute);
                    documentReadyStateStripped = documentReadyState.Trim().ToLower();
                }
                catch
                {
                    SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName(), "JAVASCRIPT NOT READY YET");
                    Thread.Sleep(500);
                }
            }
        }
Exemplo n.º 13
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)
        {
            SAFEBBALog.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);
            }
        }
Exemplo n.º 14
0
        /// <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;

            SAFEBBALog.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)
                            {
                                SAFEBBALog.Warning("Tag name element: " + webElementFromList.TagName);
                                SAFEBBALog.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(" ", "");
                                SAFEBBALog.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);
        }
Exemplo n.º 15
0
        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;


                    safeebbalog = new SAFEBBALog();


                    GoToSite(ConfigParameters.WEB_APPLICATION_URL);
                    // driver.Manage().Window.Maximize();
                    //  }
                    // else
                    //  {
                    // SAFEBBALog.Debug("Browser type not specified in the config file...........");
                    //  }
                }
            }
            catch (Exception e)
            {
                SAFEBBALog.Debug("Error Starting Web Driver...........");
                Console.WriteLine(e.StackTrace);
            }
        }
Exemplo n.º 16
0
 /// <summary>
 /// Clear the cache for Inernet Explorer
 /// </summary>
 public static void ClearIECache()
 {
     SAFEBBALog.Debug(CommonUtilities.GetClassAndMethodName());
     // Clear the special cache folder
     ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)));
 }