Selenium throws timeout after locating the element - c#

Has anyone experienced the problem when the webdriver locates the needed element, types the text into it, and then throws WebDriverTimeout exception saying that it takes too much time to find the exact same element that it has just sent text into?
If I wrap this block of code in try-catch which catches the timeout exception, the test goes on successfully, but it doesn't seem to be the healthy way of doing this.
I am using the c# selenium and chromedriver 2.44
Update:
The initial wait configuration and the action itself:
var driver = new ChromeDriver();
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(20);
driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(3);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(2);
...
var searchLocator = By.Id("searchByName");
driver.GetElement(searchLocator, 20, element => element.Displayed).SendKeys("test");
GetElement extension:
public static IWebElement GetElement(this IWebDriver driver, By locator, double timeout, Func<IWebElement, bool> condition)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeout));
wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException));
wait.Until(drv =>
{
var element = driver.FindElement(locator);
return condition(element);
});
return driver.FindElement(locator);
}
StackTrace:
Result StackTrace:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebElement.Execute(String commandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebElement.SendKeys(String text)
at Tests.Steps.SearchSteps.WhenTheUserFillsTheSearchFieldWith(String searchFieldName, String data) in C:\...Tests\Steps\SearchSteps.cs:line 64
at lambda_method(Closure , IContextManager , String , String )
at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(IContextManager contextManager, StepInstance stepInstance)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
at TechTalk.SpecFlow.TestRunner.CollectScenarioErrors()
at Tests.Features.SearchFeature.ScenarioCleanup()
at Tests.Features.SearchFeature.CheckSearch() in C:\...Tests\Features\Search.feature:line 167
Result Message:
OpenQA.Selenium.WebDriverTimeoutException : timeout
(Session info: chrome=70.0.3538.110)
(Driver info: chromedriver=2.44.609538
(b655c5a60b0b544917107a59d4153d4bf78e1b90),platform=Windows NT 6.3.9600 x86_64)

You should be able to set various timeout spans using the manage method on the driver. One of these should do the trick:
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
Also you are able to specify timeout in the ctor like:
var driver = new ChromeDriver (pathToDriver, TimeSpan.FromSeconds (30))
In the constructor case, the timeout is the command timeout that . Not sure which one is appropriate for you. Probably what you need is the implicitwait tho.

Related

StaleElementReferenceException thrown ONLY in the pipeline

I have a test running in our azure pipeline that fails every time it is run(it turns out it's about half the time), with a StaleElementReferenceException. Whenever the test is run locally (headless or otherwise) the test will pass.
Interestingly, it's failing while running a method that is used in multiple other tests that will not hit this issue.
I have a callstack, but I'm really not sure how to go about debugging this one! Any advice please?!
at OpenQA.Selenium.WebDriver.UnpackAndThrowOnError(Response errorResponse, String commandToExecute)
at OpenQA.Selenium.WebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebDriver.InternalExecute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebElement.Execute(String commandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.WebElement.get_Displayed()
at SeleniumExtras.WaitHelpers.ExpectedConditions.<>c__DisplayClass6_0.<ElementToBeClickable>b__0(IWebDriver driver)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition, CancellationToken token)
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at GembaCloud.Tests.Pages.BasePage.BasePageActions.WaitForElementToBeClickable(By element) in C:\agent\_work\53\s\GembaCloud.Tests\Pages\BasePage.cs:line 205
at GembaCloud.Tests.Pages.BasePage.BasePageActions.GetTable(By byTable, Int32 firstDataRowIndex) in C:\agent\_work\53\s\GembaCloud.Tests\Pages\BasePage.cs:line 259
at GembaCloud.Tests.Pages.GembaIntelligencePage.GembaIntelligencePageActions.GetGembaIntelligenceTable() in C:\agent\_work\53\s\GembaCloud.Tests\Pages\Home\GembaIntelligencePage.cs:line 52
at GembaCloud.Tests.Pages.GembaIntelligencePage.GembaIntelligencePageActions.ExpandGembaIntelligenceTableRow(Int32 rowNumber) in C:\agent\_work\53\s\GembaCloud.Tests\Pages\Home\GembaIntelligencePage.cs:line 79
at GembaCloud.Tests.TestClasses.UserRolePageElementAuthorisationTests.reporting_user_should_not_have_access_to_intelligence_dropdown_create_action_button() in C:\agent\_work\53\s\GembaCloud.Tests\TestClasses\UserRolePageElementAuthorisationTests.cs:line 115
Is there something obviously wrong here? Thanks!
Here's the code of the items in the callstack. GembaIntelligencePage class first:
public void ExpandGembaIntelligenceTableRow(int rowNumber)
{
this.ExpandTableRow(this.GetGembaIntelligenceTable(), rowNumber);
}
public IList<IWebElement> GetGembaIntelligenceTable()
{
return this.GetTable(_elements.byGembaIntelligenceTable, 1);
}
BasePage class second:
protected IList<IWebElement> GetTable(By byTable, int firstDataRowIndex)
{
//firstDataRowIndex is so we only return the table rows that we need
this.WaitForElementToBeClickable(byTable);
IWebElement table = _driver.FindElement(byTable);
IList<IWebElement> listOfDataTableRows = table.FindElements(By.CssSelector("tr")).Skip(firstDataRowIndex -1).ToList();
return listOfDataTableRows;
}
protected void WaitForElementToBeClickable(By element)
{
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(element));
}
Change the Timeout value to a higher value (for example from 10 change it to 30) and tell us if it works:
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30));

System.ComponentModel.Win32Exception: 'Access is denied' error while Automating a WPF app using FlaUI+SpecFlow

I have landed up in a problem that doesn't occur very frequently. I am trying to automate the UI testing using FlaUI and SpecFlow. I am trying to launch the app exe.The app runs for sometime and then throws the error. I am getting the error below.
System.ComponentModel.Win32Exception: 'Access is denied'
Code:
public void Start()
{
try
{
_logger.Info("Synergy TestHub starting up in memory");
_testHub = new SynergyTestHub(locator =>
{
locator.RegisterFeatureService(Substitute.For<ISynergyLogger>());
locator.RegisterFeatureService(Substitute.For<ISynergyClientConfigService>());
}, Config.SynergyEnvironment);
// Run the Synergy Test Hub In Memory
AsyncBlockingDeadlockAvoidanceHack.SafeWait(
async () => await _testHub.RunUiApplicationAsync(
_pathBuilder.ShipTrackerExePath,
600,
false));
_controlAction.WaitFor(new TimeSpan(0, 0, 0, 50)); // Average time for ref data to load
var process = Process.GetProcessesByName(Config.ShipTrackerFileName)[0];
process.WaitForInputIdle();
Application = Application.Attach(process.Id);
ShipTrackerWindow = GetMainWindow();
}
catch (Exception exception)
{
_logger.Error($"Error Starting up Synergy TestHub in Memory. {exception.Message}");
_logger.Warning("Killing processes that could be hanging around .. please try to run the test again");
_processTerminator.KillProcess(new List<string>
{
Config.ShipTrackerFileName, Config.SynergyHubAppName
});
throw;
}
}
The StackTrace is
Stack Trace:
ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
Process.GetProcessHandle(Int32 access, Boolean throwIfExited)
Process.WaitForInputIdle(Int32 milliseconds)
Process.WaitForInputIdle()
ApplicationDriver.Start() line 79
Hooks.BeforeScenario() line 133
lambda_method(Closure , IContextManager )
BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration) line 69
TestExecutionEngine.InvokeHook(IBindingInvoker invoker, IHookBinding hookBinding, HookType hookType) line 351
TestExecutionEngine.FireEvents(HookType hookType) line 340
TestExecutionEngine.FireScenarioEvents(HookType bindingEvent) line 321
TestExecutionEngine.OnScenarioStart() line 198
TestRunner.OnScenarioStart() line 54
RefreshTheViewsFeature.ScenarioStart()
RefreshTheViewsFeature.AutomationOfRefreshInManualPublishMode() line 34
The line process.WaitForInputIdle(); throws the above mentioned error.
You dont have permission to read all the process in your device, try to run as administrator mode

Selenium C# waiting for page to load - UnexpectedJavaScriptError

I am using selenium, IEDriver, and C# and I would like to wait for the page to load. I have this code:
/// <summary>
/// Ceka dokud neni stranka nastena
/// </summary>
public static void WaitForPageToLoad()
{
try
{
Thread.Sleep(500);
Log.Trace("Browser.WaitForPageToLoad() - Ceka dokud neni stranka nactena ...");
new WebDriverWait(Browser.Driver, new TimeSpan(0, 0, 360)).Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete"));
Thread.Sleep(1000);
}
catch (Exception ex)
{
Log.Error(ex);
throw;
}
}
but it will crash on this:
2018-01-04 15:39:27.2266 - ERROR: System.InvalidOperationException: JavaScript error (UnexpectedJavaScriptError)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
at BaseFramework.Browser.<>c.<WaitForPageToLoad>b__10_0(IWebDriver d) in C:\TFS\PRIVPMT\Selenium\BaseFramework\Browser.cs:line 97
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at BaseFramework.Browser.WaitForPageToLoad() in C:\TFS\PRIVPMT\Selenium\BaseFramework\Browser.cs:line 97
EXCEPTION: System.InvalidOperationException: JavaScript error (UnexpectedJavaScriptError)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object[] args)
at BaseFramework.Browser.<>c.<WaitForPageToLoad>b__10_0(IWebDriver d) in C:\TFS\PRIVPMT\Selenium\BaseFramework\Browser.cs:line 97
at OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)
at BaseFramework.Browser.WaitForPageToLoad() in C:\TFS\PRIVPMT\Selenium\BaseFramework\Browser.cs:line 103
at Gamma.Tests.GammaICRM.AT82688_ICRM_SMOKE() in C:\TFS\PRIVPMT\Selenium\Gamma.UI.Tests\Gamma.Tests\GammaICRM.cs:line 72
at Gamma.Tests.GammaICRM.AT82688_ICRM_SMOKE_PerformTest() in C:\TFS\PRIVPMT\Selenium\Gamma.UI.Tests\Gamma.Tests\GammaICRM.cs:line 23
most of the time it works, but from time to time it will crash on this
next method is this:
public static void LeftClick(this IWebElement element)
{
//pockame dokud nelze na element kliknout
new WebDriverWait(Browser.Driver, new TimeSpan(0, 0, 120)).Until(ExpectedConditions.ElementToBeClickable(element));
Actions actions = new Actions(Browser.Driver);
//posuneme cursor na element
actions.MoveToElement(element).Perform();
//klikeneme na element
actions.Click().Build().Perform();
}
passed webElement is founded by XPath (webElement is always correct)
You could try calling the WebDriverWait class. You can use this to wait for an element to show up on the page (i.e the page loads if this object exists)
public static IWebElement WaitUntilElementExists(By elementLocator, int timeout = 10)
{
try
{
var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeout));
return wait.Until(ExpectedConditions.ElementExists(elementLocator));
}
catch (NoSuchElementException)
{
Console.WriteLine("Element with locator: '" + elementLocator + "' was not found in current context page.");
throw;
}
}
In this code the method returns wait.until then the elementexists condition on an element that is supposed to be on the page. Just have it try to find an element on the page which is supposed to be there when the page loads. If it doesn't exist for a certain amount of time it will give the NoSuchElementException (so a timeout). Catch this and give your own output
source: How to get webDriver to wait for page to load (C# Selenium project)
hope this helps at all
I've faced the same issue and the problem was that I was inside of a frame. Switching back to default content before executing this javascript resolved the error.
Hope it'll help if the problem is still valid for you.
In one word, just before calling WaitForPageToLoad() I've used _driver.SwitchTo().DefaultContent();

Invalid Operation Exception in C# Unit Test using Protractor

I have a simple test class like this:
public class MyTest
{
const string URL = "https://example.com/content/mypage.aspx";
IWebDriver driver;
NgWebDriver ngDriver;
[SetUp]
public void Setup()
{
driver = new ChromeDriver();
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
ngDriver = new NgWebDriver(driver);
}
[TearDown]
public void Teardown()
{
ngDriver.Quit();
}
[Test]
public void Basic()
{
ngDriver.Url = URL;
Assert.IsTrue(ngDriver.FindElement(By.CssSelector("#my")).Displayed);
}
}
and here's the HTML snippet:
<kendo-button id="my" ng-click="myCtrl.doSomething()">Do Something</kendo-button>
I'm getting the following error on the Assert.IsTrue line:
javascript error: [ng:test] http://errors.angularjs.org/1.3.15/ng/test
JavaScript stack:
Error: [ng:test] http://errors.angularjs.org/1.3.15/ng/test
at Error (native)
at https://example.com/AngularJS/1.3.15/angular.min.js:6:417
at Object.Ld [as getTestability] (https://example.com/AngularJS/1.3.15/angular.min.js:18:468)
at eval (eval at executeAsyncScript (unknown source), <anonymous>:10:13)
at eval (eval at executeAsyncScript (unknown source), <anonymous>:18:5)
at executeAsyncScript (<anonymous>:329:26)
at <anonymous>:345:29
at callFunction (<anonymous>:237:33)
at <anonymous>:247:23
at <anonymous>:248:3
(Session info: chrome=49.0.2623.87)
(Driver info: chromedriver=2.21.371459 (36d3d07f660ff2bc1bf28a75d1cdabed0983e7c4),platform=Windows NT 6.1 SP1 x86_64) (UnexpectedJavaScriptError)
and the stack trace is:
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptCommand(String script, String commandName, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteAsyncScript(String script, Object[] args)
at Protractor.NgWebDriver.WaitForAngular() in c:\Users\Bruno\Projets\GitHub\bbaia\protractor-net\src\Protractor\NgWebDriver.cs:line 315
at Protractor.NgWebDriver.FindElement(By by) in c:\Users\Bruno\Projets\GitHub\bbaia\protractor-net\src\Protractor\NgWebDriver.cs:line 262
I only got the Protractor and Selenium WebDriver Nuget package. Is there something else I need to install or this is actually a code problem?
You're not actually navigating to the URL before the Assert?
Try -
[Test]
public void Basic()
{
NgDriver.Navigate().GoToUrl(URL);
Assert.IsTrue(ngDriver.FindElement(By.CssSelector("#my")).Displayed);
}
Building on what I shared below, I found that my problem was not specifying the root to the document. In my tag, I had
data-ng-app='myApp'
The code to create my protractor driver was:
ngDriver = new NgWebDriver(driver, "[ng-data='myApp']"
Protractor-net doesn't modify this direct CSS search criteria, so what worked was:
ngDriver = new NgWebDriver(driver, "[data-ng-app='myApp']"
Not an answer, but I don't have the ability to comment.
I'm seeing the same issue. Further investigation reveals that there is an exception being thrown when the NgWebDriver is instantiated. Inspecting the object shows the Location, PageSource, Title and Url members of the object created all "threw an exception of type 'System.InvalidOperationException' string {System.InvalidOperationException}". The exception only gets thrown up to the test when attempting to find an element.
My code looks like:
public DefaultPOM(IWebDriver webDriver, string baseURL)
{
driver = webDriver;
this.baseURL = baseURL;
driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(10));
driver.Navigate().GoToUrl(baseURL);
ngDriver = new NgWebDriver(driver, "[ng-app='myApp']");
ngDriver.Manage().Window.Maximize();
ngDriver.Navigate().GoToUrl(baseURL);
}
The inspecting the ngDriver object right after it is created shows the exceptions.
If I turn off synchronization before navigating, the only member of the driver object recording the exception is the Location.
ngDriver = new NgWebDriver(driver, "[ng-app='NCTWebPortal']");
ngDriver.IgnoreSynchronization=true;
ngDriver.Manage().Window.Maximize();
ngDriver.Navigate().GoToUrl(baseURL);
ngDriver.IgnoreSynchronization = false;

LdapConnection SearchRequest throws exception for "The size limit was exceeded"

Because of the fact that we are required to connect to an LDAP server using LDAPS we must use LdapConnection instead of DirectoryEntry.
Here is the source code:
SearchResponse response;
using (LdapConnection con = new LdapConnection(new LdapDirectoryIdentifier(Host, Port)))
{
if (IsSSL)
{
con.SessionOptions.SecureSocketLayer = true;
con.SessionOptions.VerifyServerCertificate =
(connection, certificate)
=> true;
}
con.Credential = new NetworkCredential(_username, _password);
con.AuthType = AuthType.Basic;
con.Bind();
if (logMessage != null)
logMessage("Connected to LDAP");
string sFilter = String.Format(
"(&(objectcategory=person)(objectclass=user){0}(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
filter
);
SearchRequest request = new SearchRequest("OU=Corp,DC=mydc,DC=com", sFilter, SearchScope.Subtree);
request.Attributes.Add(Resources.objectguid);
request.Attributes.Add(Resources.givenname);
request.Attributes.Add(Resources.sn);
request.Attributes.Add(Resources.initials);
request.Attributes.Add(Resources.samaccountname);
request.Attributes.Add(Resources.userprincipalname);
request.Attributes.Add(Resources.mail);
request.Attributes.Add(Resources.objectsid);
request.Attributes.Add(Resources.department);
request.Attributes.Add(Resources.company);
request.SizeLimit = 10;
response = (SearchResponse) con.SendRequest(request);
}
Upon execution of the source code (we have verified credentials, host, port, etc - using an external 3rd party software) we get the following exception:
The size limit was exceeded
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.DirectoryServices.Protocols.DirectoryOperationException: The size limit was exceeded
Source Error:
response = (SearchResponse) con.SendRequest(request);
[DirectoryOperationException: The size limit was exceeded]
System.DirectoryServices.Protocols.LdapConnection.ConstructResponse(Int32
messageId, LdapOperation operation, ResultAll resultType, TimeSpan
requestTimeOut, Boolean exceptionOnTimeOut) +2385
System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest
request, TimeSpan requestTimeout) +499
System.DirectoryServices.Protocols.LdapConnection.SendRequest(DirectoryRequest
request) +50
UserSearchProvider.ADUserSearchProvider.QueryStore(UserSearchCriteriaCollection
criterias, Action1 logMessage) in c:\Users\stemarie\Documents\Visual
Studio
2012\Projects\Idealink.Modules\UserSearchProvider\UserSearchProvider\ADUserSearchProvider.cs:298
UserSearchProvider.UserSearchProvider.QueryAndSort(UserSearchCriteriaCollection
criterias, Action1 logMessage) in c:\Users\stemarie\Documents\Visual
Studio
2012\Projects\Idealink.Modules\UserSearchProvider\UserSearchProvider\UserSearchProvider.cs:77
UserSearchProvider.UserSearchProvider.Search(UserSearchCriteriaCollection
criterias, Action1 logMessage) in c:\Users\stemarie\Documents\Visual
Studio
2012\Projects\Idealink.Modules\UserSearchProvider\UserSearchProvider\UserSearchProvider.cs:33
UserSearchProvider.UserSearchService.Search(UserSearchCriteriaCollection
criterias, Action1 logMessage) in c:\Users\stemarie\Documents\Visual
Studio
2012\Projects\Idealink.Modules\UserSearchProvider\UserSearchProvider\UserSearchService.cs:44
UserSearchProviderTest._Default.Page_Load(Object sender, EventArgs e) in c:\Users\stemarie\Documents\Visual Studio
2012\Projects\Idealink.Modules\UserSearchProvider\UserSearchProviderTest\Default.aspx.cs:28
The part that confuses me is that we did specify the maximum size limit, we don't want more than 100 entries - we want to limit it. But yet the library consistently throws the error even if we specify a SizeLimit of 1.
Does anyone have any insights/suggestions regarding this issue? We are very close to getting this working and just need to resolve this last problem.
You should use cookies in a function similar to this.
The function returns a collection of SearchResponse objects, which the caller should loop though.
private List<SearchResponse> SearchDirectory(string distinguishedName, string searchFilter, System.DirectoryServices.Protocols.SearchScope searchScope, params string[] attributeList)
{
List<SearchResponse> result = new List<SearchResponse>();
SearchResponse response = null;
int maxResultsToRequest = 100;
try
{
PageResultRequestControl pageRequestControl = new PageResultRequestControl(maxResultsToRequest);
// used to retrieve the cookie to send for the subsequent request
PageResultResponseControl pageResponseControl;
SearchRequest searchRequest = new SearchRequest(distinguishedName, searchFilter, searchScope, attributeList);
searchRequest.Controls.Add(pageRequestControl);
while (true)
{
response = (SearchResponse)connection.SendRequest(searchRequest);
result.Add(response);
pageResponseControl = (PageResultResponseControl)response.Controls[0];
if (pageResponseControl.Cookie.Length == 0)
break;
pageRequestControl.Cookie = pageResponseControl.Cookie;
}
}
catch (Exception e)
{
// do something with the error
}
return result;
}
As it turns out, this works:
try
{
response = (SearchResponse)con.SendRequest(request);
return response.Entries.Cast<SearchResultEntry>()
.Select(entry => entry.Attributes)
.Select(x => GetADUserSearchItemFromADProperties(x, logMessage))
.Where(user => user.HasName)
.Cast<IUserSearchItem>();
}
catch (DirectoryOperationException ex)
{
response = (SearchResponse) ex.Response;
return response.Entries.Cast<SearchResultEntry>()
.Select(entry => entry.Attributes)
.Select(x => GetADUserSearchItemFromADProperties(x, logMessage))
.Where(user => user.HasName)
.Cast<IUserSearchItem>();
}
The MSDN documentation states that you get a DirectoryResponse class as the DirectoryOperationException.Response property. You can however cast this property to a SearchResponse type and then use the SearchResponse.Entries property to get the entries that you have received prior to hitting the specified SizeLimit.
I have tried this and I get the expected results, I'm just a bit upset that I have to work with an exception in order to perform the operation.

Categories

Resources