Exemplo n.º 1
0
        public void UIAutoEnterValueIntoOpenDialog(string value)
        {
            ICapabilities     capabilities    = ((RemoteWebDriver)WebContext.WebDriver).Capabilities;
            AutomationElement fileNameTextBox = OpenTheUploadDialog();

            if (fileNameTextBox != null)
            {
                fileNameTextBox.SetFocus();
                ValuePattern valuePatternA =
                    fileNameTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                valuePatternA.SetValue(value);
                SendKeys.SendWait("{Enter}");
            }
        }
Exemplo n.º 2
0
        public static void Value(AutomationElement ae, string value)
        {
            Debug.Assert(null != ae);

            try
            {
                ValuePattern valPattern = ae.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                valPattern.SetValue(value);
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 3
0
        public void ValueTest()
        {
            string       magicStr = "Hello, ValuePatternTest.ValueTest!";
            ValuePattern pattern  = (ValuePattern)textbox1Element.GetCurrentPattern(ValuePatternIdentifiers.Pattern);

            pattern.SetValue(magicStr);
            //We add following sleep to make sure the test passes, since
            //"pattern.SetValue (magicStr)" may execute in another thread.
            Thread.Sleep(500);
            string str1 = pattern.Current.Value;
            string str2 = (string)(textbox1Element.GetCurrentPropertyValue(ValuePatternIdentifiers.ValueProperty));

            Assert.AreEqual(magicStr, str1, "Check pattern.Current.Value.");
            Assert.AreEqual(magicStr, str2, "Check ValuePatternIdentifiers.ValueProperty.");
        }
Exemplo n.º 4
0
        /// <summary>
        /// Inserts supplied text into existing string beginning at the specified index
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <param name="text">Text to insert into to TextBox value</param>
        /// <param name="index">Index into string where to begin insertion</param>
        internal static void InsertValue(AutomationElement control, string text, int index)
        {
            ValuePattern pattern  = (ValuePattern)CommonUIAPatternHelpers.CheckPatternSupport(ValuePattern.Pattern, control);
            string       baseText = pattern.Current.Value;

            /* If index is out of range, defer to ProdErrorManager */
            if (baseText == null)
            {
                return;
            }
            string insString = baseText.Insert(index, text);

            pattern.SetValue(insString);
            //TODO: Find an insert text verification
        }
Exemplo n.º 5
0
        static void Say(string phrase)
        {
            // VOICEROID2のウィンドウを探す
            var root            = AutomationElement.RootElement;
            var titleConditions = new [] {
                new PropertyCondition(AutomationElement.NameProperty, "VOICEROID2"),
                new PropertyCondition(AutomationElement.NameProperty, "VOICEROID2*")
            };
            var form = root.FindFirst(TreeScope.Element | TreeScope.Children, new OrCondition(titleConditions));

            if (form == null)
            {
                Console.Error.WriteLine("VOICEROID2のウィンドウが見つかりません。VOICEROID2を起動してください");
                return;
            }

            // 喋らせたいフレーズをセットする
            var textEditView = form.FindFirst(
                TreeScope.Element | TreeScope.Children,
                new PropertyCondition(AutomationElement.ClassNameProperty, "TextEditView")
                );
            var textBoxElem = textEditView.FindFirst(
                TreeScope.Element | TreeScope.Children,
                new PropertyCondition(AutomationElement.ClassNameProperty, "TextBox")
                );
            ValuePattern editValue = textBoxElem.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

            editValue.SetValue(phrase);

            // 再生ボタンを探して押す
            // textEditViewの最初に出てくるボタンが再生ボタンなのでこれで動いているけど将来ずっと動くかは不明
            var playButton = textEditView.FindFirst(
                TreeScope.Element | TreeScope.Children,
                new PropertyCondition(AutomationElement.ClassNameProperty, "Button")
                );
            var playButtonControl = playButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;

            playButtonControl.Invoke();

            // 喋っている間はテキストボックスがreadonlyになっているので、喋りおわるまで待つ
            // Invokeしてすぐはreadonlyになっていなくて抜けてしまうので、do-whileにすることでうまく待つという戦略
            do
            {
                Thread.Sleep(100);
            } while (editValue.Current.IsReadOnly);
        }
Exemplo n.º 6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="strValue"></param>
 /// <param name="waitTime"></param>
 public void DoSetValue(string strValue, double waitTime = 0.1)
 {
     try { DoSetFocus(); }
     catch (Exception) { }
     try
     {
         ValuePattern tbTestBox = me.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
         tbTestBox.SetValue("");
         Thread.Sleep((int)(0.3 * 1000));
         //PublicClass.Sendkeys(strValue);
         Thread.Sleep((int)(waitTime * 1000));
     }
     catch (Exception ex)
     {
         throw new Exception("Set value error. " + ex.Message);
     }
 }
Exemplo n.º 7
0
        public static AutomationElement SetTextBox(this AutomationElement parent, string name, string value)
        {
            AutomationElement box = parent.FindFirstWithRetries(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, name));

            if (box == null)
            {
                throw new Exception("TextBox '" + name + "' not found");
            }
            if (!box.Current.IsEnabled)
            {
                throw new Exception("TextBox '" + name + "' is not enabled");
            }
            ValuePattern p = (ValuePattern)box.GetCurrentPattern(ValuePattern.Pattern);

            p.SetValue(value);
            return(box);
        }
Exemplo n.º 8
0
        public static void SetComboBoxText(this AutomationElement parent, string name, string value)
        {
            AutomationElement box = parent.FindFirstWithRetries(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, name));

            if (box == null)
            {
                throw new Exception("ComboBox '" + name + "' not found");
            }
            if (!box.Current.IsEnabled)
            {
                throw new Exception("ComboBox '" + name + "' is not enabled");
            }

            // editable combo boxes expose a ValuePattern.
            ValuePattern sip = (ValuePattern)box.GetCurrentPattern(ValuePattern.Pattern);

            sip.SetValue(value);
        }
Exemplo n.º 9
0
        private void SetTextBox(string name, string databasePath)
        {
            AutomationElement box = window.FindFirstWithRetries(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, name));

            if (box == null)
            {
                throw new Exception("TextBox '" + name + "' not found");
            }
            try
            {
                ValuePattern value = (ValuePattern)box.GetCurrentPattern(ValuePattern.Pattern);
                value.SetValue(databasePath);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 10
0
        public void UploadFile(string filePath)
        {
            //Name file path by Developer
            AutomationElement OpenDialog    = null;
            AutomationElement EditElement   = null;
            AutomationElement SubmitElement = null;

            //Get opendialog element
            JWait.WaitUntil(() =>
            {
                AutomationElement Desktop    = AutomationElement.RootElement;
                Condition OpenDialogConditon = new AndCondition(
                    new PropertyCondition(AutomationElement.NameProperty, "打开"),
                    new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "对话框")
                    );
                OpenDialog = Desktop.FindFirst(TreeScope.Descendants, OpenDialogConditon);
                if (OpenDialog == null)
                {
                    throw new Exception();
                }
            }, 30);
            //Get Edit element an set value to input
            Condition EditConditon = new AndCondition(
                new PropertyCondition(AutomationElement.NameProperty, "文件名(N):"),
                new PropertyCondition(AutomationElement.ClassNameProperty, "Edit"),
                new PropertyCondition(AutomationElement.IsValuePatternAvailableProperty, true)
                );

            EditElement = OpenDialog.FindFirst(TreeScope.Descendants, EditConditon);
            ValuePattern EditAction = EditElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

            EditAction.SetValue(filePath);
            //Get submit element and click the button
            Condition SubmitConditon = new AndCondition(
                new PropertyCondition(AutomationElement.NameProperty, "打开(O)"),
                new PropertyCondition(AutomationElement.ClassNameProperty, "Button"),
                new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "按钮")
                );

            SubmitElement = OpenDialog.FindFirst(TreeScope.Children, SubmitConditon);
            InvokePattern SubmitAction = SubmitElement.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;

            SubmitAction.Invoke();
        }
Exemplo n.º 11
0
        // For Edit and Editor Class
        #region Editor and Editr class and methods
        public string Set(string value)
        {
            ClearAll();

            try
            {
                ValuePattern v = (ValuePattern)_condition.AutomationElement.GetCurrentPattern(ValuePattern.Pattern);
                v.SetValue(value);
                if (valuechecker(value))
                {
                    return(value);
                }
            }
            catch
            { }

            try
            {
                ClearAll();
                KeyInput.Sendkeys(value);
                if (valuechecker(value))
                {
                    return(value);
                }
            }
            catch
            { }

            try
            {
                ClearAll();
                KeyInput.SendKeys_A(_condition.AutomationElement.Current.NativeWindowHandle, value);
                if (valuechecker(value))
                {
                    return(value);
                }
            }
            catch
            { }

            return("");
        }
Exemplo n.º 12
0
 private void UploadFile()
 {
     try
     {
         Task.Factory.StartNew(() =>
         {
             System.Threading.Thread.Sleep(500);
             try
             {
                 AutomationElement vDesktopObject                 = AutomationElement.RootElement;
                 PropertyCondition vWebBrowserName                = new PropertyCondition(AutomationElement.NameProperty, WEBBROWSER_TITLE);
                 AutomationElement vWebBrowserWindow              = vDesktopObject.FindFirst(TreeScope.Children, vWebBrowserName);
                 PropertyCondition vUploadDialogName              = new PropertyCondition(AutomationElement.NameProperty, "Choose File to Upload");
                 AutomationElement vUploadDialogWindow            = vWebBrowserWindow.FindFirst(TreeScope.Children, vUploadDialogName);
                 AndCondition vUploadDialogFileNameFieldCondition = new AndCondition(
                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                     new PropertyCondition(AutomationElement.AutomationIdProperty, "1148")
                     );
                 AutomationElement vUploadDialogFileNameFieldElement = vUploadDialogWindow.FindFirst(TreeScope.Descendants, vUploadDialogFileNameFieldCondition);
                 ValuePattern vUploadDialogFileNameFieldValuePattern = vUploadDialogFileNameFieldElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                 vUploadDialogFileNameFieldValuePattern.SetValue(DEFAULT_ATTACHMENTS_FOLDER + "report_108370888.pdf");
                 AndCondition vUploadDialogOpenButtonCondition = new AndCondition(
                     new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
                     new PropertyCondition(AutomationElement.NameProperty, OPEN_BUTTON)
                     );
                 AutomationElement vUploadDialogOpenButtonElement = vWebBrowserWindow.FindFirst(TreeScope.Descendants, vUploadDialogOpenButtonCondition);
                 vUploadDialogOpenButtonElement.SetFocus();
                 SendKeys.SendWait(ENTER_KEY);
             }
             catch (Exception vE)
             {
                 throw vE;
             }
         });
         HtmlHelper.ClickElement(this.webBrowser.Document, "UCCargarDocAutorizacion1_flDocumento", true);
     }
     catch (Exception vE)
     {
         throw vE;
     }
 }
Exemplo n.º 13
0
        protected override void Execute()
        {
            Condition controlCondition = new PropertyCondition(AutomationElement.AutomationIdProperty, ControlId);
            var       element          = MainWindow.FindFirst(TreeScope.Children, controlCondition);

            if (element != null)
            {
                try
                {
                    object pattern = element.GetCurrentPattern(ValuePattern.Pattern);
                    if (pattern != null && pattern is ValuePattern)
                    {
                        ValuePattern valuePtr = pattern as ValuePattern;
                        valuePtr.SetValue(Value);
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Exemplo n.º 14
0
        internal static void talk(string tchar, string talkText)
        {
            IntPtr hWnd = GetVoiceroid2hWnd();

            if (hWnd == IntPtr.Zero)
            {
                return;
            }

            AutomationElement ae  = AutomationElement.FromHandle(hWnd);
            TreeScope         ts1 = TreeScope.Descendants | TreeScope.Element;
            TreeScope         ts2 = TreeScope.Descendants;
            TreeScope         ts3 = TreeScope.Descendants;

            AutomationElement editorWindow = ae.FindFirst(ts1, new PropertyCondition(AutomationElement.ClassNameProperty, "Window"));

            AutomationElement customC = ae.FindFirst(ts1, new PropertyCondition(AutomationElement.AutomationIdProperty, "c"));

            AutomationElement textBox = customC.FindFirst(ts2, new PropertyCondition(AutomationElement.AutomationIdProperty, "TextBox"));
            ValuePattern      elem1   = textBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

            elem1.SetValue(tchar + ">" + talkText);

            AutomationElementCollection buttons = customC.FindAll(ts2, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "ボタン"));
            InvokePattern elem2 = buttons[4].GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;

            elem2.Invoke();

            AutomationElementCollection buttons2 = customC.FindAll(ts3, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "ボタン"));

            while (true)
            {
                if ((bool)buttons2[9].GetCurrentPropertyValue(AutomationElement.IsEnabledProperty))
                {
                    break;
                }
            }
            Console.WriteLine("Sucsess");
        }
Exemplo n.º 15
0
        public new void Set(string value)
        {
            this.PrepareForReplay();
            try
            {
                RangeValuePattern v = (RangeValuePattern)this._condition.AutomationElement.GetCurrentPattern(RangeValuePattern.Pattern);
                v.SetValue(Convert.ToDouble(value));
            }
            catch
            {
            }

            try
            {
                ValuePattern v = (ValuePattern)this._condition.AutomationElement.GetCurrentPattern(ValuePattern.Pattern);
                v.SetValue(value);
            }
            catch
            {
                ControlSearcher.ThrowError(ErrorType.CannotPerformThisOperation);
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            try
            {
                AutomationElement rootElement = AutomationElement.RootElement;

                if (rootElement != null)
                {
                    AutomationElement appElement = null;

                    appElement = rootElement.FindFirst(TreeScope.Children,
                                                       new PropertyCondition(AutomationElement.NameProperty
                                                                             , args[1].ToLower().Trim('"')
                                                                             , PropertyConditionFlags.IgnoreCase));


                    string function = args[0].ToLower().Trim('"');

                    if (function.Equals("settext"))
                    {
                        AutomationElement txt = GetElementByName(appElement, args[2].Trim('"'));

                        if (txt != null)
                        {
                            ValuePattern pattern = txt.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

                            pattern.SetValue(args[3].Trim('"'));

                            TextPattern textPattern = txt.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

                            textPattern.GetVisibleRanges()[0].Select();
                        }
                    }
                }
            }
            catch
            {}
        }
Exemplo n.º 17
0
 /// <summary>
 /// Enter text in dailog Element.
 /// </summary>
 /// <param name="textToEnter">String : Text to enter.</param>
 public void EnterdataInDialog(string textToEnter)
 {
     try
     {
         AutomationElement dialogElement = waitAndGetElement();
         //Enter data to dailog edit fields.
         if (dialogElement != null)
         {
             if (dialogElement.Current.ControlType.Equals(ControlType.ComboBox) || dialogElement.Current.ControlType.Equals(ControlType.Edit))
             {
                 ValuePattern pattern = dialogElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                 if (pattern != null)
                 {
                     pattern.SetValue(textToEnter);
                 }
             }
         }
     }
     catch (TimeoutException)
     {
         throw new Exception(Utility.GetCommonMsgVariable("KRYPTONERRCODE0030"));
     }
 }
        /// <summary>
        /// works better with chrome dialogs
        /// </summary>
        /// <param name="element"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static bool InsertTextUsingUIAutomation2(AutomationElement element, string value)
        {
            try
            {
                //element.SetFocus();

                //ValuePattern etb = EditableTextBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                //etb.SetValue("test");

                //TextPattern tp = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);


                ValuePattern valueP = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                valueP.SetValue(value);

                return(true);
            }
            catch (Exception x)
            {
                XLogger.Error(x);
                return(false);
            }
        }
Exemplo n.º 19
0
        private static void VerifyValuePattern(AutomationElement element)
        {
            object patternObj;

            if (!element.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj))
            {
                return;
            }

            ValuePattern pattern = patternObj as ValuePattern;

            try {
                if (!pattern.Current.IsReadOnly)
                {
                    string oldValue = pattern.Current.Value;
                    pattern.SetValue("hello world!");
                    // This test fails and confirms that we should implement IValueProvider
                    // but return IsReadOnly = true
                    Assert.AreEqual("hello world!", pattern.Current.Value, "Value not set even when IsReadOnly is false");
                }
                // This is weird, it should not throw any excepiont but:
                // ElementNotEnabledException, ArgumentException or InvalidDataException
            } catch (System.Runtime.InteropServices.COMException) { }
        }
Exemplo n.º 20
0
        private void Automate()
        {
            LogMessage("Getting RootElement...");
            AutomationElement rootElement = AutomationElement.RootElement;

            if (rootElement != null)
            {
                LogMessage("OK." + Environment.NewLine);

                Automation.Condition condition = new PropertyCondition(AutomationElement.NameProperty, _WindowTestsViewModel.FirstOrDefault().WindowTitle);

                LogMessage("Searching for Test Window...");
                AutomationElement appElement = rootElement.FindFirst(TreeScope.Children, condition);

                if (appElement != null)
                {
                    LogMessage("OK " + Environment.NewLine);
                    LogMessage("Searching for TextBox A control...");
                    AutomationElement txtElementA = GetTextElement(appElement, "txtA");
                    if (txtElementA != null)
                    {
                        LogMessage("OK " + Environment.NewLine);
                        LogMessage("Setting TextBox A value...");
                        try
                        {
                            ValuePattern valuePatternA = txtElementA.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                            valuePatternA.SetValue("10");
                            LogMessage("OK " + Environment.NewLine);
                        }
                        catch
                        {
                            WriteLogError();
                        }
                    }
                    else
                    {
                        WriteLogError();
                    }

                    LogMessage("Searching for TextBox B control...");
                    AutomationElement txtElementB = GetTextElement(appElement, "txtB");
                    if (txtElementA != null)
                    {
                        LogMessage("OK " + Environment.NewLine);
                        LogMessage("Setting TextBox B value...");
                        try
                        {
                            ValuePattern valuePatternB = txtElementB.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                            valuePatternB.SetValue("5");
                            LogMessage("OK " + Environment.NewLine);
                        }
                        catch
                        {
                            WriteLogError();
                        }
                    }
                    else
                    {
                        WriteLogError();
                    }
                }
                else
                {
                    WriteLogError();
                }
            }
        }
Exemplo n.º 21
0
        public void HandleAuthenticationDialogForIE(string username, string password)
        {
            if (String.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException(username, "Must contain a value");
            }

            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentNullException(password, "Must contain a value");
            }

            System.OperatingSystem osInfo = System.Environment.OSVersion;

            // Check to make sure this is run on Windows 7 or Windows 8 only. I didn't test this code on any other OS.
            if ((osInfo.Version.Major != 6) || ((osInfo.Version.Major == 6) && (osInfo.Version.Minor == 0)))
            {
                throw new NotSupportedException("This code has only been tested on Windows 7 and Windows 8.");
            }

            // If the minor version is "2" then it's Windows 8. Else, it's Windows 7. See http://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx
            bool isWindows8 = osInfo.Version.Minor == 2;

            // Condition for finding all "pane" elements
            Condition paneCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Pane);

            // Conditions for finding windows with a class of type dialog that's labeled Windows Security
            Condition windowsSecurityCondition = new AndCondition(
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                new PropertyCondition(AutomationElement.ClassNameProperty, "#32770"),
                new PropertyCondition(AutomationElement.NameProperty, "Windows Security"));

            // Conditions for finding list elements with an AutomationId of "UserList"
            Condition userListCondition = new AndCondition(
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List),
                new PropertyCondition(AutomationElement.AutomationIdProperty, "UserList"));

            // Conditions for finding the account listitem element
            Condition userTileCondition;

            if (isWindows8)
            {
                userTileCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem),
                    new PropertyCondition(AutomationElement.ClassNameProperty, "CredProvUserTile"),
                    new PropertyCondition(AutomationElement.NameProperty, "Use another account"));
            }
            else
            {
                userTileCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem),
                    new PropertyCondition(AutomationElement.ClassNameProperty, "UserTile"),
                    new PropertyCondition(AutomationElement.NameProperty, "Use another account"));
            }


            // Conditions for finding the OK button
            Condition submitButtonCondition = new AndCondition(
                new PropertyCondition(AutomationElement.IsEnabledProperty, true),
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
                new PropertyCondition(AutomationElement.AutomationIdProperty, "SubmitButton"));

            // Conditions for finding the edit controls
            Condition editCondition = new AndCondition(
                new PropertyCondition(AutomationElement.IsEnabledProperty, true),
                new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));

            Console.Write("Looking for credentials dialog...");

            // Find all "pane" elements that are children of the desktop
            AutomationElementCollection panes = AutomationElement.RootElement.FindAll(TreeScope.Children, paneCondition);

            bool foundSecurityDialog = false;

            // Iterate through the collection of "panes"
            foreach (AutomationElement pane in panes)
            {
                // Check to see if the current pane is labeled as IE
                if (pane.Current.Name.Contains("Windows Internet Explorer"))
                {
                    // Ok, we found IE. Now find all children of the IE pane that meets the windowSecurityCondition defined above
                    AutomationElement windowsSecurityDialog = pane.FindFirst(TreeScope.Children, windowsSecurityCondition);

                    if (windowsSecurityDialog != null)
                    {
                        // Great, we found the dialog
                        Console.WriteLine("found security dialog");

                        foundSecurityDialog = true;

                        AutomationElement userTile;

                        if (isWindows8)
                        {
                            // Grab the first child of the dialog that is a UserList
                            AutomationElement userList = windowsSecurityDialog.FindFirst(TreeScope.Children, userListCondition);

                            // Grab the first child of the UserList that is a UserTile
                            userTile = userList.FindFirst(TreeScope.Children, userTileCondition);
                        }
                        else
                        {
                            // Grab the first child of the dialog that is a UserTile
                            userTile = windowsSecurityDialog.FindFirst(TreeScope.Children, userTileCondition);
                        }

                        // Make sure the UserTile has focus so that we can see the UserName and Password edit boxes
                        userTile.SetFocus();

                        // Get all children of the UserTile that are edit controls
                        AutomationElementCollection edits = userTile.FindAll(TreeScope.Children, editCondition);

                        // Iterate thru the edit controls
                        foreach (AutomationElement edit in edits)
                        {
                            if (edit.Current.Name == "User name")
                            {
                                // We found the username edit control. Let's set the contents of the box to the username.
                                Console.WriteLine("Entering username");
                                ValuePattern userNamePattern = (ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern);
                                userNamePattern.SetValue(username);
                            }
                            if (edit.Current.Name == "Password")
                            {
                                // We found the password edit control. Let's set the contents of the box to the password.
                                Console.WriteLine("Entering password");
                                ValuePattern userNamePattern = (ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern);
                                userNamePattern.SetValue(password);
                            }
                        }

                        // Find the first child of the security dialog that meets the submitButtonCondition defined above
                        AutomationElement submitButton = windowsSecurityDialog.FindFirst(TreeScope.Children, submitButtonCondition);

                        // Now press the button
                        InvokePattern buttonPattern = (InvokePattern)submitButton.GetCurrentPattern(InvokePattern.Pattern);
                        buttonPattern.Invoke();

                        break;
                    }
                }
            }

            if (!foundSecurityDialog)
            {
                Console.WriteLine("no security dialogs found.");
            }
        }
Exemplo n.º 22
0
        private void TextActionInvoker(AutomationElement ae, string inputString)
        {
            ValuePattern valuePattern = ae.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

            valuePattern.SetValue(inputString);
        }
Exemplo n.º 23
0
 public void SendKeys(string text)
 {
     _pattern.SetValue(text);
 }
Exemplo n.º 24
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("\nBegin WinForm UIAutomation test run\n");
                // launch Form1 application
                // get refernce to main Form control
                // get references to user controls
                // manipulate application
                // check resulting state and determine pass/fail

                Console.WriteLine("\nBegin WinForm UIAutomation test run\n");
                Console.WriteLine("Launching WinFormTest application");
                //启动被测试的程序
                Process p = Process.Start(@"E:\Project\WinFormTest\WinFormTest\bin\Debug\WinFormTest.exe");

                //自动化根元素
                AutomationElement aeDeskTop = AutomationElement.RootElement;

                Thread.Sleep(2000);
                AutomationElement aeForm = AutomationElement.FromHandle(p.MainWindowHandle);
                //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法一)
                //if (null == aeForm)
                //{
                //    Console.WriteLine("Can not find the WinFormTest from.");
                //}

                //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法二)
                int numWaits = 0;
                do
                {
                    Console.WriteLine("Looking for WinFormTest……");
                    //查找第一个自动化元素
                    aeForm = aeDeskTop.FindFirst(TreeScope.Children, new PropertyCondition(
                                                     AutomationElement.NameProperty, "Form1"));
                    ++numWaits;
                    Thread.Sleep(100);
                } while (null == aeForm && numWaits < 50);
                if (null == aeForm)
                {
                    throw new NullReferenceException("Failed to find WinFormTest.");
                }
                else
                {
                    Console.WriteLine("Found it!");
                }

                Console.WriteLine("Finding all user controls");
                //找到第一次出现的Button控件
                AutomationElement aeButton = aeForm.FindFirst(TreeScope.Children,
                                                              new PropertyCondition(AutomationElement.NameProperty, "button1"));

                //找到所有的TextBox控件
                AutomationElementCollection aeAllTextBoxes = aeForm.FindAll(TreeScope.Children,
                                                                            new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));

                // 控件初始化的顺序是先初始化后添加到控件
                // this.Controls.Add(this.textBox3);
                // this.Controls.Add(this.textBox2);
                // this.Controls.Add(this.textBox1);

                AutomationElement aeTextBox1 = aeAllTextBoxes[2];
                AutomationElement aeTextBox2 = aeAllTextBoxes[1];
                AutomationElement aeTextBox3 = aeAllTextBoxes[0];

                Console.WriteLine("Settiing input to '30'");
                //通过ValuePattern设置TextBox1的值
                ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern);
                vpTextBox1.SetValue("30");
                Console.WriteLine("Settiing input to '50'");
                //通过ValuePattern设置TextBox2的值
                ValuePattern vpTextBox2 = (ValuePattern)aeTextBox2.GetCurrentPattern(ValuePattern.Pattern);
                vpTextBox2.SetValue("50");
                Thread.Sleep(1500);
                Console.WriteLine("Clickinig on button1 Button.");
                //通过InvokePattern模拟点击按钮
                InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern);
                ipClickButton1.Invoke();
                Thread.Sleep(1500);

                //验证计算的结果与预期的结果是否相符合
                Console.WriteLine("Checking textBox3 for '80'");
                TextPattern tpTextBox3 = (TextPattern)aeTextBox3.GetCurrentPattern(TextPattern.Pattern);
                string      result     = tpTextBox3.DocumentRange.GetText(-1);//获取textbox3中的值
                //获取textbox3中的值
                //string result = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty);
                if ("80" == result)
                {
                    Console.WriteLine("Found it.");
                    Console.WriteLine("TTest scenario: *PASS*");
                }
                else
                {
                    Console.WriteLine("Did not find it.");
                    Console.WriteLine("Test scenario: *FAIL*");
                }

                Console.WriteLine("Close application in 5 seconds.");
                Thread.Sleep(5000);
                //实现关闭被测试程序
                WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern);
                wpCloseForm.Close();

                Console.WriteLine("\nEnd test run\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal error: " + ex.Message);
            }
        }
Exemplo n.º 25
0
        private void DownloadFile()
        {
            try
            {
                string vDownloadDialogTitle      = "File Download";
                string vDownloadDialogSaveButton = SAVE_BUTTON;

                string vSaveAsDialogTitle           = "Save As";
                string vSaveAsDialogSaveButton      = SAVE_BUTTON;
                string vSaveAsDialogFileNameFieldId = "1001";
                string vFileNameToDownload          = "RegistroPrevioInactivo_Detalles_DXCBtn0.pdf";

                string vIdentifierElement = "ctl00_MainContent_BuscadorFolios1_FichaFolio1_ASPxPopupControl1_RegistroPrevioInactivo_DetallesASPxGridView_DXCBtn0";

                // Se crea el task que se encargará de manejar el Dialog de subir adjuntos,
                // la cual se ejecutará 5 segundos despues de que se le de click a seleccionar archivo
                Task.Factory.StartNew(() =>
                {
                    System.Threading.Thread.Sleep(500);
                    try
                    {
                        AutomationElement vDesktopObject = AutomationElement.RootElement;

                        #region WebBrowserWindow
                        // Obtener la ventana del robot, por medio del titulo RPA
                        AutomationElement vWebBrowserWindow = vDesktopObject.FindFirst(TreeScope.Children, this.NameProperty(WEBBROWSER_TITLE));
                        #endregion

                        #region DownloadDialog
                        // Obtener el File Download Dialog por medio del título y la ventana que lo levantó
                        AutomationElement vDownloadDialogWindow            = vDesktopObject.FindFirst(TreeScope.Children, this.NameProperty(vDownloadDialogTitle));
                        AutomationElement vDownloadDialogSaveButtonElement = null;
                        foreach (AutomationElement vElement in vDownloadDialogWindow.FindAll(TreeScope.Children, Condition.TrueCondition))
                        {
                            // vDownloadDialogWindow: primer File Download Dialog (Getting File Information)
                            if (!string.IsNullOrWhiteSpace(vElement.Current.Name) && vElement.Current.Name.Equals(vDownloadDialogTitle))
                            {
                                // Si entra al if, es porqué se encontró el segundo File Download Dialog (Do you want to open or save this file?)
                                // Obtener el Save Button del segundo File Download Dialog
                                vDownloadDialogSaveButtonElement = this.FindButton(vElement, vDownloadDialogSaveButton);
                                if (vDownloadDialogSaveButtonElement != null)
                                {
                                    break;
                                }
                            }
                        }

                        if (vDownloadDialogSaveButtonElement != null)
                        {
                            // Hacer click al Save Button del segundo File Download Dialog
                            this.ClickUIElement(vDownloadDialogSaveButtonElement);
                        }
                        else
                        {
                            logger.Warn(DialogNotFound(vDownloadDialogTitle));
                        }
                        #endregion

                        #region SaveAsDialog
                        // Obtener el Save As Dialog por medio de la ventana que lo levantó (File Download Dialog)
                        AutomationElement vSaveAsDialogFileNameFieldElement = null;
                        AutomationElement vSaveAsDialogSaveButtonElement    = null;
                        foreach (AutomationElement vElement in vDownloadDialogWindow.FindAll(TreeScope.Children, this.NameProperty(vSaveAsDialogTitle)))
                        {
                            // Obtener el Save Button del Save As Dialog
                            vSaveAsDialogSaveButtonElement = this.FindButton(vElement, vSaveAsDialogSaveButton);
                            if (vSaveAsDialogSaveButtonElement != null)
                            {
                                // Si se obtuvo el Save Button, entonces también se debería poder obtener el File Name Field del Save As Dialog
                                // Obtener del Save As Dialog el File Name Field utilizando su ControlId, para esto se usa el Spy++ (Visual Studio 2013: Menú > Tools > Spy++)
                                vSaveAsDialogFileNameFieldElement = vElement.FindFirst(TreeScope.Descendants, this.ConditionFieldById(vSaveAsDialogFileNameFieldId));
                                break;
                            }
                        }

                        if (vSaveAsDialogSaveButtonElement != null)
                        {
                            if (vSaveAsDialogFileNameFieldElement != null)
                            {
                                ValuePattern vSaveAsDialogFileNameFieldValuePattern = vSaveAsDialogFileNameFieldElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                                // Establecer el directorio, nombre y extensión del archivo que se va a descargar
                                vSaveAsDialogFileNameFieldValuePattern.SetValue(DEFAULT_ATTACHMENTS_FOLDER + vFileNameToDownload);
                            }
                            else
                            {
                                logger.Warn(DialogNotFound(vSaveAsDialogTitle, "File Name Field"));
                            }

                            // Hacer click al Save Button del Save As Dialog
                            this.ClickUIElement(vSaveAsDialogSaveButtonElement);
                        }
                        else
                        {
                            logger.Warn(DialogNotFound(vSaveAsDialogTitle));
                        }
                        #endregion
                    }
                    catch (Exception vE)
                    {
                        logger.Error(vE);
                    }
                });

                // Hacer click al enlace para descargar el archivo
                HtmlHelper.ClickElement(this.webBrowser.Document, vIdentifierElement, true);
            }
            catch (Exception vE)
            {
                throw vE;
            }
        }
Exemplo n.º 26
0
        public static void NavigateIEWindow(AutomationElement ieWindow, Uri UriToNavigate)
        {
            // Get a reference the address bar...
            GlobalLog.LogDebug("Finding the IE address bar");

            AndCondition isAddrBar = new AndCondition(new PropertyCondition(ValuePattern.ValueProperty, "about:NavigateIE"),
                                                      new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
            AutomationElement addressBar = null;

            try
            {
                addressBar = ieWindow.FindFirst(TreeScope.Descendants, isAddrBar);
            }
            catch // Any exception type... can be one of several
            // Retry this a few times in a loop before we go the "old" route.
            {
                for (int countdown = 15; countdown > 0; countdown--)
                {
                    try
                    {
                        Thread.Sleep(150);
                        addressBar = ieWindow.FindFirst(TreeScope.Descendants, isAddrBar);
                        countdown--;
                    }
                    catch { } // Still failing :(

                    // Success!
                    if (addressBar != null)
                    {
                        break;
                    }
                }
            }

            // Type the URI and press return
            GlobalLog.LogDebug("Typing " + UriToNavigate.ToString() + " into the address bar");

            if (addressBar != null)
            {
                // Don't focus the element because some OS'es will throw an InvalidOperationException
                // and this is unnecessary for ValuePattern.
                ValuePattern vp = addressBar.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                if (vp == null)
                {
                    throw new System.Exception("Couldn't get the valuePattern for the IE address bar! Please contact Microsoft to fix this.");
                }
                vp.SetValue(UriToNavigate.ToString());
            }
            else
            {
                GlobalLog.LogEvidence("Could not set focus to address bar.  Attempting to continue...");
                //Sleep a few seconds to make sure that the address bar has focus
                Thread.Sleep(3500);
                // This section should only work as a backup, since this is unreliable in Japanese (possibly other) languages.
                // But if we fail to get the address bar or its valuepattern, it's better to try to continue.
                MTI.Input.SendUnicodeString(UriToNavigate.ToString(), 1, 15);
            }

            // Wait a second then send a 2nd Enter to the address bar if we're Japanese, as IME is on by default and requires this.
            // If this UIHandler fails for other languages, add their LCID's to the if statement.

            int tryCount = 10;

            Thread.Sleep(1500);

            AndCondition didNavigate = new AndCondition(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text),
                                                        new PropertyCondition(AutomationElement.NameProperty, "NavigateIE"));
            AutomationElement navigationSuccessElement = null;

            do
            {
                tryCount--;
                // Can't trust setfocus to work, so instead click on the address bar...
                try
                {
                    MTI.Input.MoveToAndClick(addressBar);
                }
                catch
                {
                    // Do nothing... we'll try again in a little bit hoping this has fixed itself.
                }
                // Should disable IME.  For most OS'es this is a no-op.  For east asian, this will preclude the need to hit enter twice
                // (this is unreliable to do by culture)
                // This is broken by DD bugs 201197 - Invariant Assert in TextServicesLoader.Load() when setting IME State
                // If IME is enabled and it matters, we're out of luck since this Asserts.
                // Renable (InputMethod.Current.ImeState = InputMethodState.Off) if this is ever fixed

                MTI.Input.SendKeyboardInput(Key.Enter, true);
                MTI.Input.SendKeyboardInput(Key.Enter, false);

                Thread.Sleep(2000);
                try
                {
                    navigationSuccessElement = ieWindow.FindFirst(TreeScope.Descendants, didNavigate);
                }
                catch // Any exception type... can be one of several
                {
                    // Do nothing.  Sometimes this happens when this handler is running while IE is shutting down.
                }
            }
            // Don't loop this in Vista... we'll take our chances.
            // LUA causes this to fail since some navigations launch new IE windows.
            while ((navigationSuccessElement != null) && tryCount > 0 && Environment.OSVersion.Version.Major != 6 &&
                   !UriToNavigate.ToString().EndsWith(ApplicationDeploymentHelper.STANDALONE_APPLICATION_EXTENSION));
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            for (int i = 0; i < Convert.ToInt32(args[1]); i++)
            {
                //
                // Description: This is sample source code to automatically sign-in Chat with valid user account,
                // then add other contact to Deck, send "Hello!! Nice to meet you!!" to that contact, and start Video Chat with him.
                //
                StreamWriter file2     = new StreamWriter(@"e:\RunningTimeAutoUILogin.txt", true);
                Stopwatch    stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch

                // Launch Chat application
                Directory.SetCurrentDirectory("C:\\Users\\pth\\AppData\\Local\\Personify\\Omni\\");
                Console.WriteLine("\n Begin Automation test chat");
                Process chat = Process.Start("C:\\Users\\pth\\AppData\\Local\\Personify\\Omni\\Personify.exe");

                // Waiting for Chat Login dialog display.
                AutomationElement aeDesktop   = AutomationElement.RootElement;
                AutomationElement aeChatLogin = null;
                int numWaits = 0;
                do
                {
                    Console.WriteLine("\n Looking for Chat application...");
                    aeChatLogin = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Personify"));
                    ++numWaits;
                    Thread.Sleep(100);
                }while (aeChatLogin == null && numWaits < 50);

                Assert.IsNotNull(aeChatLogin);

                // Get all edit boxes from Chat login dialog.
                aeDesktop = AutomationElement.RootElement;
                AutomationElement aeEditUserName = aeChatLogin.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "Username"));
                AutomationElement aeEditPassword = aeChatLogin.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "Password"));
                if (aeEditUserName == null || aeEditPassword == null)
                {
                    Assert.Fail("!!Can not find any textbox");
                }


                // Input valid nxchattest1 user account to sign in.
                AutomationElement aeTemp         = TreeWalker.ControlViewWalker.GetNextSibling(aeEditPassword);
                AutomationElement aeSignInButton = TreeWalker.ControlViewWalker.GetNextSibling(aeTemp);
                ValuePattern      vpEditUserName = (ValuePattern)aeEditUserName.GetCurrentPattern(ValuePattern.Pattern);
                vpEditUserName.SetValue("");
                ValuePattern vpEditPassword = (ValuePattern)aeEditPassword.GetCurrentPattern(ValuePattern.Pattern);
                vpEditPassword.SetValue("");
                InvokePattern ipClickLogin = (InvokePattern)aeSignInButton.GetCurrentPattern(InvokePattern.Pattern);
                ipClickLogin.Invoke();
                Thread.Sleep(1000);
                vpEditUserName.SetValue("*****@*****.**");
                vpEditPassword.SetValue("123456");
                ipClickLogin.Invoke();
                Thread.Sleep(2000);
                // Waiting for Chat Deck Window display
                AutomationElement aeDeckWindow = null;
                numWaits = 0;
                do
                {
                    Console.WriteLine("\n Looking for Chat Deck...");
                    aeDeckWindow = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Home"));
                    ++numWaits;
                    Thread.Sleep(100);
                }while (aeDeckWindow == null && numWaits < 50);
                AutomationElement aeTexttemp  = aeDeckWindow.FindFirst(TreeScope.Children, new AndCondition(new PropertyCondition(AutomationElement.NameProperty, "Create an immersive recording with your persona and content on screen."), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)));
                AutomationElement menu        = TreeWalker.ControlViewWalker.GetNextSibling(aeTexttemp);
                TogglePattern     toogleclick = (TogglePattern)menu.GetCurrentPattern(TogglePattern.Pattern);
                //ipClickLogin = (InvokePattern)menu.GetCurrentPattern(InvokePattern.Pattern);
                toogleclick.Toggle();
                AutomationElement aeSignout = aeDeckWindow.FindFirst(TreeScope.Descendants, new AndCondition(new PropertyCondition(AutomationElement.NameProperty, "Sign out"), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.MenuItem)));
                ipClickLogin = (InvokePattern)aeSignout.GetCurrentPattern(InvokePattern.Pattern);
                ipClickLogin.Invoke();
                chat.Kill();
                stopwatch.Stop();
                file2.WriteLine(stopwatch.ElapsedMilliseconds + " miliseconds");
                file2.Close();
            }
        }
Exemplo n.º 28
0
        public void NotEnabledTest()
        {
            ValuePattern pattern = (ValuePattern)textbox2Element.GetCurrentPattern(ValuePatternIdentifiers.Pattern);

            pattern.SetValue("123");
        }
Exemplo n.º 29
0
        private static void SetTextBoxValue(AutomationElement element, string value)
        {
            ValuePattern valuePattern = element.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;

            valuePattern.SetValue(value);
        }
        /// <summary>
        /// 输入字符串
        /// </summary>
        /// <param name="automationElement">UI自动化元素</param>
        /// <param name="str">字符串</param>
        public static void InputString(this AutomationElement automationElement, string str)
        {
            ValuePattern valuePattern = (ValuePattern)automationElement.GetCurrentPattern(ValuePattern.Pattern);

            valuePattern.SetValue(str);
        }