Я недавно обновил к Windows 7, VS2010 и IE8. У нас есть комплект автоматизации, запускающий тесты против использования IE WatiN. Эти тесты требуют, чтобы обработчик диалоговых окон входа в систему использовался, для входа различных AD Пользователей в Браузер IE.
Это работает отлично при использовании Windows XP, и IE8, но теперь с помощью Windows 7 привел к диалоговому окну безопасности Windows, больше не распознаваемому, диалоговое окно просто игнорируется. Это - метод, используемый для запущения браузера:
public static Browser StartBrowser(string url, string username, string password)
{
Browser browser = new IE();
WatiN.Core.DialogHandlers.LogonDialogHandler ldh = new WatiN.Core.DialogHandlers.LogonDialogHandler(username, password);
browser.DialogWatcher.Add(ldh);
browser.GoTo(url);
return browser;
}
любые предложения или справка значительно ценились бы...
Поскольку никто не ответил на ваш вопрос, я отвечу, но, к сожалению, без готового решения.
На данный момент у меня нет Windows 7, но похоже, что WatiN LogonDialogHandler
несовместим с Windows 7, поэтому вам придется написать свой собственный DialogHandler
. Самый простой способ - унаследовать от BaseDialogHandler
. Вы можете посмотреть исходный код существующих обработчиков диалогов в WatiN. Я сделал себя очень простым и не универсальным для работы с диалоговым окном сертификата . WinSpy ++ может быть очень полезен во время реализации.
В конце концов мы решили эту проблему, используя Windows Automation 3.0 API, чтобы открыть диалоговое окно и обработать вход в систему. Это было сделано следующим образом:
После аутентификации браузера мы присоединяем его к объекту браузера WatiN IE. Код ниже:
public static Browser LoginToBrowser(string UserName, string Password, string URL)
{
AutomationElement element = StartApplication("IEXPLORE.EXE", URL);
Thread.Sleep(2000);
string t = element.Current.ClassName.ToString();
Condition conditions = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window));
Condition List_condition = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem));
Condition Edit_condition = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
Condition button_conditions = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
AutomationElementCollection c = element.FindAll(TreeScope.Children, conditions);
foreach (AutomationElement child in c)
{
if (child.Current.ClassName.ToString() == "#32770")
{
//find the list
AutomationElementCollection lists = child.FindAll(TreeScope.Children, List_condition);
// find the buttons
AutomationElementCollection buttons = child.FindAll(TreeScope.Children, button_conditions);
foreach (AutomationElement list in lists)
{
if (list.Current.ClassName.ToString() == "UserTile")
{
AutomationElementCollection edits = list.FindAll(TreeScope.Children, Edit_condition);
foreach (AutomationElement edit in edits)
{
if (edit.Current.Name.Contains("User name"))
{
edit.SetFocus();
//send the user name
}
if (edit.Current.Name.Contains("Password"))
{
edit.SetFocus();
//send the password
}
}
}
}
foreach (AutomationElement button in buttons)
{
if (button.Current.AutomationId == "SubmitButton")
{
//click the button
break;
}
}
}
}
return IE.AttachToIE(Find.By("hwnd", element.Current.NativeWindowHandle.ToString()), 30) ;
}
Мы действительно использовали инструмент под названием UI Spy для изучения пользовательского интерфейса Windows. Если вы запустите его против XP и Win7, вы можете ясно увидеть, как изменилась структура диалогового окна безопасности Windows между двумя ОС.
Если в Windows 7 установить для процесса, запускающего ватин, режим запуска от имени администратора, то DialogHandlers работают отлично.
По какой-то причине код, опубликованный Клинтом, содержит комментарии вместо ввода имени пользователя, пароля и отправки, и ссылается на неопределенный метод, но в остальном все в порядке. Вот завершенный (и работающий) код:
public static Browser Win7Login(string username, string password, string URL) {
Process ieProcess = Process.Start("iexplore.exe", URL);
ieProcess.WaitForInputIdle();
Thread.Sleep(2000);
AutomationElement ieWindow = AutomationElement.FromHandle(ieProcess.MainWindowHandle);
string t = ieWindow.Current.ClassName.ToString();
Condition conditions = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window));
Condition List_condition = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem));
Condition Edit_condition = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
Condition button_conditions = new AndCondition(new PropertyCondition(AutomationElement.IsEnabledProperty, true),
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));
AutomationElementCollection c = ieWindow.FindAll(TreeScope.Children, conditions);
foreach (AutomationElement child in c) {
if (child.Current.ClassName.ToString() == "#32770") {
// find the list
AutomationElementCollection lists = child.FindAll(TreeScope.Children, List_condition);
// find the buttons
AutomationElementCollection buttons = child.FindAll(TreeScope.Children, button_conditions);
foreach (AutomationElement list in lists) {
if (list.Current.ClassName.ToString() == "UserTile") {
AutomationElementCollection edits = list.FindAll(TreeScope.Children, Edit_condition);
foreach (AutomationElement edit in edits) {
if (edit.Current.Name.Contains("User name")) {
edit.SetFocus();
ValuePattern usernamePattern = edit.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
usernamePattern.SetValue(username);
}
if (edit.Current.Name.Contains("Password")) {
edit.SetFocus();
ValuePattern passwordPattern = edit.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
passwordPattern.SetValue(password);
}
}
}
}
foreach (AutomationElement button in buttons) {
if (button.Current.AutomationId == "SubmitButton") {
InvokePattern submitPattern = button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
submitPattern.Invoke();
break;
}
}
}
}
return IE.AttachTo<IE>(Find.By("hwnd", ieWindow.Current.NativeWindowHandle.ToString()), 30);
}