示例#1
0
        private static void SavesToSpecifiedLocation(BrowserWindow browserWindow)
        {
            const string fileName = "screenshot-test-card.jpg";

            try
            {
                browserWindow.SaveScreenshot(fileName);
                Assert.That(File.Exists(fileName), "Expected screenshot saved to " + new FileInfo(fileName).FullName);
                using (var saved = Image.FromFile("screenshot-test-card.jpg"))
                {
                    var docWidth = float.Parse(browserWindow.ExecuteScript("return window.document.body.clientWidth;")
                                               .ToString());
                    var docHeight = float.Parse(browserWindow.ExecuteScript("return window.document.body.clientHeight;")
                                                .ToString());
                    Assert.That(saved.PhysicalDimension, Is.EqualTo(new SizeF(docWidth, docHeight)));
                }
            }
            finally
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
            }
        }
示例#2
0
        public void JavaScript_CodedUI()
        {
            BrowserWindow browserObj = BrowserWindow.Launch(@"https://www.gmail.com/");

            browserObj.ExecuteScript("alert('Hello')");
            var count = browserObj.ExecuteScript("var count = document.getElementsByTagName('Input').length; return count;");
        }
示例#3
0
        public static IEnumerable <HtmlControl> GetChildControls(this BrowserWindow window, string selector)
        {
            object obj  = window.ExecuteScript(string.Format("return jQuery('{0}').children()", selector));
            var    list = obj as List <object>;

            return(list != null ? list.OfType <HtmlControl>() : null);
        }
示例#4
0
        public static Dictionary <String, Object> extractData(String txnName, String url, BrowserWindow browser, int txnStatus)
        {
            log.Debug("Started extracting data for Transaction : " + txnName + " with status " + txnStatus);
            Dictionary <String, Object> rtnValue = new Dictionary <string, object>();

            try
            {
                //IJavaScriptExecutor jsExe = (IJavaScriptExecutor)browser;

                log.Debug("Check Browser Type");
                String userAgent = (String)browser.ExecuteScript("var nAgt = navigator.userAgent|| {}; return nAgt;");
                log.Debug("User Agent : " + userAgent);

                if (userAgent != null)
                {
                    CollectorConstants.setUserAgent(userAgent);
                    rtnValue = collateData(txnName, url, browser, txnStatus);
                }
                else
                {
                    /*Adding conditions to check if Client Config is null or User Agent is null*/
                    log.Debug("No performance data will be collected for " + txnName + " since UserAgent: " + userAgent + " is null");
                    rtnValue = null;
                }
            }
            catch (Exception e)
            {
                log.Error("Exception in extractData for " + txnName + " at " + e);
            }
            log.Debug("Completed extracting data for Transaction : " + txnName + " with status " + txnStatus);
            return(rtnValue);
        }
示例#5
0
        public static object FindControlBySelector(this BrowserWindow window, Type htmlType, string selector)
        {
            var obj  = window.ExecuteScript(string.Format("return $('{0}')", selector));
            var list = obj as List <object>;

            return(list != null ? Convert.ChangeType(list.First(), htmlType) : Convert.ChangeType(obj, htmlType));
        }
示例#6
0
        public static HtmlControl GetFirstChild(this BrowserWindow window, string selector)
        {
            object obj  = window.ExecuteScript(string.Format("return jQuery('{0}').children()", selector));
            var    list = obj as List <object>;

            return((HtmlControl)(list != null ? list.First() : null));
        }
示例#7
0
        public void CleanLogs()
        {
            string script =
                "jQuery('.log').each(function(index) {" +
                "   $( this ).text('')" +
                "});";

            BrowserWindow.ExecuteScript(script);
        }
示例#8
0
        public static int StartTransaction(String txnName, BrowserWindow browser)
        {
            int rtnValue = 0;

            CollectorConstants.setScriptStartTime(Convert.ToInt64((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds));
            //IJavaScriptExecutor jsExe = (IJavaScriptExecutor)browser;
            browser.ExecuteScript(CollectorConstants.clearResourceTiming());
            LOGGER.Debug("Cleared Resource Timing API data");
            return(rtnValue);
        }
        public EditWorkItemPage EditDescription(string description)
        {
            var uiDescription = new HtmlTextArea(browser);

            uiDescription.SearchProperties.Add(HtmlControl.PropertyNames.Id, EditWorkItemPageConst.EDIT_DESCRIPTION_TEXTAREA_ID);
            uiDescription.Find();
            browser.ExecuteScript("CKEDITOR.instances['" + EditWorkItemPageConst.EDIT_DESCRIPTION_TEXTAREA_ID + "'].setData(\"" + description + "\")");

            return(this);
        }
示例#10
0
        public void Setup()
        {
            string script =
                "jQuery('#textArea').each(function(index) {" +
                "   $( this ).val('')" +
                "});";

            BrowserWindow.ExecuteScript(script);
            BasicTestPage.TextArea.Text.Should().BeNullOrEmpty("there shouldn't be any text in that text area");
        }
 private static void CloseWindow(BrowserWindow popUp)
 {
     try
     {
         popUp.ExecuteScript("self.close();");
     }
     catch (Exception InvalidCastException)
     {
         // IE permissions
     }
 }
示例#12
0
        private static void SavesToSpecifiedLocation(BrowserWindow browserWindow)
        {
            const string fileName = "screenshot-test-card.jpg";
            try
            {
                browserWindow.SaveScreenshot(fileName, ImageFormat.Jpeg);

                Assert.That(File.Exists(fileName), "Expected screenshot saved to " + new FileInfo(fileName).FullName);
                using (var saved = Image.FromFile("screenshot-test-card.jpg"))
                {
                    var docWidth = float.Parse(browserWindow.ExecuteScript("return window.document.body.clientWidth;"));
                    var docHeight = float.Parse(browserWindow.ExecuteScript("return window.document.body.clientHeight;"));
                    Assert.That(saved.PhysicalDimension, Is.EqualTo(new SizeF(docWidth, docHeight)));
                }
            }
            finally
            {
                if (File.Exists(fileName))
                    File.Delete(fileName);
            }
        }
示例#13
0
        public static bool CurrentlyExists <T>(this BrowserWindow window, EnhancedHtmlControl <T> control) where T : HtmlControl
        {
            object obj  = window.ExecuteScript(string.Format("return jQuery('{0}')", control.Selector));
            var    list = obj as List <object>;

            if (list != null)
            {
                return(list.Any());
            }
            else
            {
            }
            return(obj != null);
        }
示例#14
0
 private static void CloseWindow(BrowserWindow popUp)
 {
     try
     {
         popUp.ExecuteScript("self.close();");
     }
     catch (Exception InvalidCastException)
     {
         // IE permissions
     }
 }
示例#15
0
        public static IEnumerable <T> FindControlsBySelector <T>(this BrowserWindow window, string selector) where T : HtmlControl
        {
            var controlsBySelector = (IEnumerable <T>)window.ExecuteScript(string.Format("return $('{0}')", selector));

            return(controlsBySelector);
        }
示例#16
0
        public static T FindControlBySelector <T>(this BrowserWindow window, string selector) where T : HtmlControl
        {
            object obj = window.ExecuteScript(string.Format("return $('{0}')", selector));

            return(ExtractTypeFromReturn <T>(obj));
        }
示例#17
0
        public static Dictionary <String, Object> collateData(String txnName, String url, BrowserWindow jsExe, int txnStatus)
        {
            log.Debug("Started collate data for Transaction : " + txnName + " with status " + txnStatus);
            Dictionary <String, Object> rtnValue = new Dictionary <string, object>();
            long    currNavTime;
            long    totalTime  = 0;
            long    serverTime = 0;
            Boolean navType    = false;
            double  speedIndex = 0;

            Dictionary <String, Object> collectedData = new Dictionary <string, object>();

            try
            {
                Dictionary <string, object>         navigationDetails = new Dictionary <string, object>();
                Dictionary <string, object>         memoryDetails     = new Dictionary <string, object>();
                Dictionary <string, object>         browserDetails    = new Dictionary <string, object>();
                Dictionary <String, Object>         heapUsage         = new Dictionary <string, object>();
                List <Dictionary <String, Object> > resourceDetails   = null;
                List <Dictionary <String, Object> > markDetails       = null;

                Boolean       isNavigationAPIEnabled, isResourceAPIEnabled, isMemoryAPIEnabled, isMarkAPIEnabled;
                StringBuilder document = new StringBuilder();
                long          loadEventEnd, currentHeapUsage, msFirstPaint;
                long          startTime, endTime, duration;

                //Load Configuration from remote service

                ConfigurationLoader config = ConfigurationLoader.getInstance();
                if (config.clientConfig.Count > 0)
                {
                    log.Debug("Configuration Loading..");
                    collectedData = (from x in config.clientConfig select x).ToDictionary(x => x.Key, x => x.Value);
                    collectedData.Add("TxnName", txnName);
                    collectedData.Add("txnStatus", txnStatus);
                    collectedData.Add("Url", url);

                    isNavigationAPIEnabled = ((config.clientConfig.ContainsKey("isNavigationAPIEnabled")) ? Convert.ToBoolean(config.clientConfig["isNavigationAPIEnabled"]) : false);
                    isResourceAPIEnabled   = ((config.clientConfig.ContainsKey("isResourceAPIEnabled")) ? Convert.ToBoolean(config.clientConfig["isResourceAPIEnabled"]) : false);
                    isMemoryAPIEnabled     = ((config.clientConfig.ContainsKey("isMemoryAPIEnabled")) ? Convert.ToBoolean(config.clientConfig["isMemoryAPIEnabled"]) : false);
                    isMarkAPIEnabled       = ((config.clientConfig.ContainsKey("isMarkAPIEnabled")) ? Convert.ToBoolean(config.clientConfig["isMarkAPIEnabled"]) : false);

                    log.Debug("Configuration Loading completed");
                    log.Debug("Navigation API data collection started for " + txnName);

                    if (isNavigationAPIEnabled)
                    {
                        log.Debug("User Agent : " + CollectorConstants.getUserAgent());
                        if (CollectorConstants.getUserAgent().Contains("Trident"))
                        {
                            log.Debug("Processing IE logic");
                            startTime = getCurrentMilliSeconds();
                            do
                            {
                                loadEventEnd = Convert.ToInt64(jsExe.ExecuteScript(CollectorConstants.getLoadEventEndIE()).ToString());
                                endTime      = getCurrentMilliSeconds();
                                duration     = (endTime - startTime) / 1000;
                                if (duration > 180)
                                {
                                    break;
                                }
                            }while (loadEventEnd <= 0);

                            object strNavigationDetails = jsExe.ExecuteScript(CollectorConstants.getNavigationTimeIE());
                            navigationDetails = JSONUtils.JsonStringToMap(strNavigationDetails.ToString());
                        }
                        else
                        {
                            log.Debug("Processing other browser logic");
                            //Loop until loadEventEnd is non zero or 3 minutes to avoid infinite loop
                            startTime = getCurrentMilliSeconds();
                            do
                            {
                                //navigationDetails = (Map<String, Object>)jsExe.executeScript("var performance = window.performance || window.webkitPerformance || window.mozPerformance || window.msPerformance || {};var timings = performance.timing || {}; return timings.loadEventEnd;");
                                loadEventEnd = Convert.ToInt64(jsExe.ExecuteScript(CollectorConstants.getLoadEventEnd()).ToString());
                                endTime      = getCurrentMilliSeconds();
                                duration     = (endTime - startTime) / 1000;
                                if (duration > 180)
                                {
                                    break;
                                }
                            }while (loadEventEnd <= 0); //Adding the loop to avoid loadEventEnd = 0

                            navigationDetails = (Dictionary <String, Object>)jsExe.ExecuteScript(CollectorConstants.getNavigationTime());
                            if (CollectorConstants.getUserAgent().Contains("Chrome") && !CollectorConstants.getUserAgent().Contains("Edge"))
                            {
                                msFirstPaint = (long)jsExe.ExecuteScript(CollectorConstants.getFirstPaint());
                                if (msFirstPaint != -9999)
                                {
                                    collectedData.Add("msFirstPaint", msFirstPaint);
                                }
                                else
                                {
                                    collectedData.Add("msFirstPaint", navigationDetails["loadEventEnd"]);
                                }
                            }
                            else
                            {
                                //No first paint event available for firefox
                                if (!CollectorConstants.getUserAgent().Contains("Edge"))
                                {
                                    collectedData.Add("msFirstPaint", navigationDetails["loadEventEnd"]);
                                }
                            }
                        }

                        log.Debug("Collected Navigation API data " + navigationDetails.ToString() + " for Transaction : " + txnName);
                        //validate if this is a new transaction. If true persist data else break immediately

                        currNavTime = (long)navigationDetails["navigationStart"];

                        if (currNavTime > getPrevTxnStartTime())
                        {
                            setPrevTxnStartTime(currNavTime);
                            navType = true;
                            collectedData.Add("StartTime", currNavTime);
                            totalTime  = ((long)navigationDetails["loadEventEnd"] - (long)navigationDetails["navigationStart"]);
                            serverTime = ((long)navigationDetails["responseStart"] - (long)navigationDetails["requestStart"]);
                            log.Debug("Hard Navigation : {}" + txnName);
                            speedIndex = Convert.ToDouble(jsExe.ExecuteScript(CollectorConstants.getSpeedIndex()));
                            collectedData.Add("SpeedIndex", speedIndex);
                            log.Debug("SpeedIndex for Transaction:" + txnName + " is " + speedIndex);
                        }
                        else
                        {
                            navType = false;
                            collectedData.Add("StartTime", getCurrentMilliSeconds());
                            navigationDetails = null;
                            log.Debug("Soft Navigation : {}" + txnName);
                        }
                        collectedData.Add("NavigationTime", navigationDetails);
                        collectedData.Add("NavType", navType);
                    }
                    // Fetch Client-side Resource Details via Resource Timing API
                    if (isResourceAPIEnabled)
                    {
                        long beforeLength, afterLength = 0;

                        do
                        {
                            beforeLength = (long)jsExe.ExecuteScript(CollectorConstants.getResourceLength());
                            Thread.Sleep(CollectorConstants.getResourceSettleTime());
                            afterLength = (long)jsExe.ExecuteScript(CollectorConstants.getResourceLength());
                        } while (beforeLength < afterLength);

                        if (CollectorConstants.getUserAgent().Contains("Trident"))
                        {
                            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            resourceDetails = serializer.Deserialize <List <Dictionary <string, object> > >
                                                  (jsExe.ExecuteScript(CollectorConstants.getResourceTimeIE()).ToString());
                        }
                        else
                        {
                            resourceDetails = ((IReadOnlyCollection <Object>)jsExe.ExecuteScript(CollectorConstants.getResourceTime())).ToDictionaries();
                        }
                        jsExe.ExecuteScript(CollectorConstants.clearResourceTiming());
                        log.Debug("Collected Resource Timing API : " + resourceDetails.ToString());
                        collectedData.Add("ResourceTime", resourceDetails);
                    }

                    if (navigationDetails == null && resourceDetails.Count <= 0)
                    {
                        log.Info("The transaction " + txnName + " probably did not make a server request and hence will be ignored.");
                        return(rtnValue);
                    }

                    // Fetch Client-side Menory Details via Memory API

                    if (isMemoryAPIEnabled)
                    {
                        if (CollectorConstants.getUserAgent().Contains("Chrome"))
                        {
                            heapUsage = (Dictionary <String, Object>)jsExe.ExecuteScript(CollectorConstants.getHeapUsage());
                            log.Debug("Heap Usage : " + heapUsage.ToString());
                            if (heapUsage.ContainsKey("totalJSHeapSize"))
                            {
                                memoryDetails.Add("jsHeapSizeLimit", heapUsage["jsHeapSizeLimit"]);
                                memoryDetails.Add("totalJSHeapSize", heapUsage["totalJSHeapSize"]);
                                memoryDetails.Add("usedJSHeapSize", heapUsage["usedJSHeapSize"]);
                                if (getPrevTxnHeapSize() == 0)
                                {
                                    setPrevTxnHeapSize((long)heapUsage["usedJSHeapSize"]);
                                    memoryDetails.Add("currentPageUsage", getPrevTxnHeapSize());
                                }
                                else
                                {
                                    currentHeapUsage = ((long)heapUsage["usedJSHeapSize"] - getPrevTxnHeapSize());
                                    setPrevTxnHeapSize((long)heapUsage["usedJSHeapSize"]);
                                    memoryDetails.Add("currentPageUsage", currentHeapUsage);
                                }
                            }
                            else
                            {
                                memoryDetails.Add("jsHeapSizeLimit", 0);
                                memoryDetails.Add("totalJSHeapSize", 0);
                                memoryDetails.Add("usedJSHeapSize", 0);
                                memoryDetails.Add("currentPageUsage", 0);
                            }
                        }
                        else
                        {
                            memoryDetails.Add("jsHeapSizeLimit", 0);
                            memoryDetails.Add("totalJSHeapSize", 0);
                            memoryDetails.Add("usedJSHeapSize", 0);
                            memoryDetails.Add("currentPageUsage", 0);
                        }
                        log.Debug("Collected Memory Details : " + memoryDetails.ToString());
                        collectedData.Add("Memory", memoryDetails);
                    }

                    //Fetch dom element count
                    long domElements = (long)jsExe.ExecuteScript(CollectorConstants.getDomLength());
                    log.Debug("DOM Element Count :{} " + domElements);
                    collectedData.Add("DomElements", domElements);


                    //Fetch Browser Details
                    browserDetails.Add("UserAgent", CollectorConstants.getUserAgent());
                    collectedData.Add("Browser", browserDetails);


                    // Fetch Client-side details Details via ResourceTiming API
                    if (isMarkAPIEnabled)
                    {
                        Thread.Sleep(CollectorConstants.getMarkWaitTime());
                        if (CollectorConstants.getUserAgent().Contains("Trident"))
                        {
                            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                            markDetails = serializer.Deserialize <List <Dictionary <string, object> > >
                                              (jsExe.ExecuteScript(CollectorConstants.getMarkTimeIE()).ToString());
                        }
                        else
                        {
                            markDetails = ((IReadOnlyCollection <Object>)jsExe.ExecuteScript(CollectorConstants.getResourceTime())).ToDictionaries();
                        }


                        if (markDetails.Count > 0)
                        {
                            collectedData.Add("MarkTime", markDetails);
                        }
                        jsExe.ExecuteScript(CollectorConstants.clearMarkTiming());
                        log.Info("Collected mark details from Resource Timing API : " + markDetails.ToString());
                    }

                    //Store DOM if required for analysis
                    if (config.clientConfig.ContainsKey("isDOMNeeded") && Convert.ToBoolean(config.clientConfig["isDOMNeeded"].ToString()))
                    {
                        if (navType == true)
                        {
                            document = document.Append((jsExe.ExecuteScript(CollectorConstants.getDom())).ToString());
                        }
                        else
                        {
                            document = null;
                        }
                    }
                    else
                    {
                        document = null;
                    }

                    collectedData.Add("DOMContent", document);
                    log.Debug("DOM Element : {}" + document);


                    log.Debug("Calling data persist for " + txnName + " asynchronously");
                    AsyncpersistData(collectedData);
                    log.Debug("Completed calling data persist for " + txnName + " asynchronously");
                    rtnValue.Add("UploadStatus", "Success");
                    rtnValue.Add("RunID", config.clientConfig["RunID"]);
                    rtnValue.Add("totalTime", totalTime);
                    rtnValue.Add("serverTime", serverTime);
                    rtnValue.Add("txnName", txnName);
                    if (txnStatus == 1)
                    {
                        rtnValue.Add("txnStatus", "Pass");
                    }
                    else
                    {
                        rtnValue.Add("txnStatus", "Fail");
                    }
                }
                else
                {
                    log.Error("Exception in collateData for transaction " + txnName + " in getting configuration");
                }
            }
            catch (Exception e)
            {
                log.Error("Exception in collateData for transaction " + txnName + " at " + e);
            }
            log.Debug("Completed collating data for " + txnName);
            return(rtnValue);
        }
示例#18
0
        public static IEnumerable <object> FindControlsBySelector(this BrowserWindow window, Type htmlType, string selector)
        {
            var controls = (IEnumerable)window.ExecuteScript(string.Format("return $('{0}')", selector));

            return(controls.Cast <object>().Select(control => Convert.ChangeType(control, htmlType)));
        }
示例#19
0
 public static bool IsVisible(this BrowserWindow window, string selector)
 {
     return((bool)window.ExecuteScript(string.Format("return jQuery('{0}').is(':visible')", selector)));
 }
示例#20
0
 public static HtmlControl GetNextSibling(this BrowserWindow window, string selector)
 {
     return((HtmlControl)window.ExecuteScript(string.Format("return jQuery('{0}').next()", selector)));
 }