I have dusted off some old code with I know used to work but no longer appears to function.
Namely
var browserLogs = Driver.Manage().Logs.GetLog(LogType.Browser);
This used to return any console log entries but now I get the following
I last used this code about 2 years ago so my questions are:
What has changed in Chrome? What do I need to change on my code to get
this working again?
I am using Chrome 85.x etc with matching ChromeDriver, C# and Selenium. Driver is correctly initialised and a valid web page has rendered. Also I have this as in my driver options
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
Any ideas folks?
More code below
public static void BeforeFeature(int server, string title)
{
if (server == 1) ResetReportVariables(TestUrls.DomainLive, title);
if (server == 2) ResetReportVariables(TestUrls.Domain, title);
var options = new ChromeOptions();
options.AddArguments("disable-browser-side-navigation");
options.AddArguments("disable-infobars");
options.AddArgument("ignore-certificate-errors");
options.AddArgument("ignore-ssl-errors");
options.AddArgument("disable-popup-blocking");
options.AddArguments("start-maximized");
options.AddArguments("no-sandbox");
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
Driver = new ChromeDriver(options);
Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(TestValues.DelayShort);
Driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(TestValues.DelayShort);
Driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(TestValues.DelayShort);
Driver.Manage().Cookies.DeleteAllCookies();
}
Scenario Outline: Validate the following pages on live site
Given that I browse to "<url>" page on "1" server
Then no console errors were detected
Examples:
| url |
| / |
[Given(#"that I browse to ""(.*)"" page on ""(.*)"" server")]
public void GivenThatIBrowseToPageOnServer(string url, int server)
{
Visit(url, server);
}
[Then(#"no console errors were detected")]
public void ThenNoConsoleErrorsWereDetected()
{
ValidateTheConsoleResults();
}
protected void Visit(string ext, int server)
{
WriteToReport(GetTheCurrentMethod());
if (server == 1)
ThisUrl = LiveUrl;
else
ThisUrl = PageUrl;
WriteToReport("Load page " + ThisUrl);
Driver.Navigate().GoToUrl(ThisUrl + ext);
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.UrlContains(ThisUrl));
}
protected void ValidateTheConsoleResults()
{
WriteToReport(GetTheCurrentMethod());
Visit();
var errors = 0;
//now we check the logs for errors
var browserLogs = Driver.Manage().Logs.GetLog(LogType.Browser);
if (browserLogs.Count > 0)
{
foreach (var log in browserLogs)
{
if (log.Level.Equals(LogLevel.Warning))
{
WriteToReport("Logged Warning - " + log);
continue;
}
else
{
WriteToReport("Logged Error - " + log);
errors++;
}
}
}
if (errors != 0) AssertFalse(errors + " Console errors detected");
else AssertTrue("No console errors detected");
}
#JimEvans you are a star
That solved it, many thanks
Related
I have an app published in the Play and App store, now I am in the work of publishing a new version for the app to both Play (Android) and App stores (iOS). Now, I want all the users to update to the new version when they use the app and not allow them to continue using the older version of the app without updating to the newer version.
Can anyone suggest me on how to force the users to update the app to the latest version once it is released in Play and App stores?
I don't know whether it is professional way or not., but this is the idea which struck my mind.
Add a variable with that app's version in App.cs or Mainpage.cs and and API with the current version as response.
Now check with the app's version and current version and redirect to homepage / any other page.
var version = 1.0;
var currentversion = 2.0; /* from API */
if(version == currentversion)
{
Navigation.PushModalAsync(new HomePage());
}
else
{
Navigation.PushModalAsync(new UpdatePage());
}
We must stop the old versions in the Play and App store.
For the future to do not stop (if we have some host - we should have it :) ):
someway save the version in the server side
every time when needed check the current version: getPackageManager().getPackageInfo(getPackageName(), 0).versionCode with version from server and force to update if needed.
good luck
How I am doing it my app is, when app starting in MyActivity I have code below
private void CompareVersion()
{
double currentVersion = 0d;
double appStoreversion =Convert.ToDouble(CosntValues.PlayStoreValues);
bool IsUpdateRequired = false;
if (Context.PackageName != null)
{
PackageInfo info = Context.PackageManager.GetPackageInfo(Context.PackageName, PackageInfoFlags.Activities);
string currentVersionStrig = info.VersionName;
currentVersion = Convert.ToDouble(currentVersionStrig);
}
try
{
if (IsUpdateRequired == false)
{
if (CheckNetConnection.IsNetConnected())
{
using (var webClient = new System.Net.WebClient())
{
var task = new VersionChecker();
task.Execute();
if ((appStoreversion.ToString() != currentVersion.ToString() && (appStoreversion > currentVersion)))
{
IsUpdateRequired = true;
}
}
}
}
if (IsUpdateRequired)
{
Activity.RunOnUiThread(() =>
{
AlertDialog dialog = null;
var Alertdialog = new Android.App.AlertDialog.Builder(Context);
Alertdialog.SetTitle("Update Available");
Alertdialog.SetMessage($"A new version of [" + appStoreversion + "] is available. Please update to version [" + appStoreversion + "] now.");
Alertdialog.SetNegativeButton("Cancel", (sender, e) =>
{
if (dialog == null)
{
dialog = Alertdialog.Create();
}
dialog.Dismiss();
});
Alertdialog.SetPositiveButton("Update", async (sender, e) =>
{
string appPackage = string.Empty;
try
{
appPackage = Application.Context.PackageName;
await Utilities.Logout(this.Activity);
var ints = new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + appPackage));
ints.SetFlags(ActivityFlags.ClearTop);
ints.SetFlags(ActivityFlags.NoAnimation);
ints.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(ints);
//StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + "com.sisapp.in.sisapp")));
}
catch (ActivityNotFoundException)
{
var apppack = Application.Context.PackageName;
//Default to the the actual web page in case google play store app is not installed
//StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse("https://play.google.com/store/apps/details?id=" + "com.app.in.app")));
await Utilities.Logout(this.Activity);
var ints = new Intent(Intent.ActionView, Android.Net.Uri.Parse("market://details?id=" + appPackage));
ints.SetFlags(ActivityFlags.ClearTop);
ints.SetFlags(ActivityFlags.NoAnimation);
ints.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(ints);
}
//this kills the app
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
System.Environment.Exit(1);
});
if (dialog == null)
dialog = Alertdialog.Create();
dialog.Show();
});
}
}
catch (Exception ex)
{
var objLog = new LogService();
objLog.MobileLog(ex, SISConst.UserName);
}
}
Followed by two separate above used classes
public class VersionChecker : AsyncTask
{
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] #params)
{
var val1 = Jsoup.Connect("https://play.google.com/store/apps/details?id=" + "com.app.in.app" + "&hl=en")
.Timeout(30000).UserAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6").Referrer("http://www.google.com")
.Get();
var val2 = val1.Select(".htlgb");
var val3 = val2.Get(7).ToString();
//here mobile app version is of 3 values like 2.1, 4.2 etc
var version = val3.Substring(val3.IndexOf(">") + 1, 3); //fetching only 3 values ex 1.1
CosntValues.PlayStoreValues = version;
return version;
}
}
public static class CosntValues
{
public static string PlayStoreValues { get; set; }
}
Disclaimer: Use your app package name & above code is statically supporting for 3 digit version like 1.1, 1.2 etc.
Hope it help you
With this plugin I found a good solution and works perfectly in production. I strongly recommend this plugin. With this solution you can even give the user the possibility to go to the store right from your app
For example:
var isLatest = await CrossLatestVersion.Current.IsUsingLatestVersion();
if (!isLatest) //If the user does not have the last version
{
var update = await DisplayAlert("New version available", "There is a new version of our app. Would you like to download it?", "Yes", "No");
if (update)
{
//Open the store
await CrossLatestVersion.Current.OpenAppInStore();
}
}
I have the following code that is intended to find the users you are following, and the users that you have requested to follow. It then unfollows the one's that are not following you. However it never actually seem's to work, however the AuthenticatedUser_UnFollowUser returns true. Any ideas? Thanks.
private void AuthenticateUser()
{
CheckRateLimits();
Auth.SetUserCredentials(_consumerKey, _consumerSecret, _userAccessToken, _userAccessSecret);
authenticatedUser = User.GetAuthenticatedUser();
}
private void CheckRateLimits()
{
// Enable RateLimit Tracking
RateLimit.RateLimitTrackerMode = RateLimitTrackerMode.TrackAndAwait;
TweetinviEvents.QueryBeforeExecute += (sender, args) =>
{
var queryRateLimits = RateLimit.GetQueryRateLimit(args.QueryURL);
// Some methods are not RateLimited. Invoking such a method will result in the queryRateLimits to be null
if (queryRateLimits != null)
{
if (queryRateLimits.Remaining > 0)
{
AppendProgress("RateLimits Available : " + queryRateLimits.Remaining.ToString());
// We have enough resource to execute the query
return;
}
// Strategy #1 : Wait for RateLimits to be available
AppendProgress("Waiting for RateLimits until : " + queryRateLimits.ResetDateTime.ToLongTimeString() + "For " + queryRateLimits.ToString());
MessageBox.Show("Waiting for " + queryRateLimits.ResetDateTime.ToLongTimeString());
Thread.Sleep((int)queryRateLimits.ResetDateTimeInMilliseconds);
// Strategy #2 : Use different credentials
//var alternateCredentials = TwitterCredentials.CreateCredentials("", "", "", "");
//var twitterQuery = args.TwitterQuery;
//twitterQuery.OAuthCredentials = alternateCredentials;
// Strategy #3 : Cancel Query
//args.Cancel = true;
}
};
}
private void UnfollowUsersNotFollowingYou()
{
AuthenticateUser();
var toUnfollow = Examples.Friendship_GetUsersNotFollowingYou();
toUnfollow.ForEach(x =>
{
if (Examples.AuthenticatedUser_UnFollowUser(x.ScreenName))
{
AppendProgress("You have unfollowed " + x.ScreenName);
SaveUnfollowedUserIdToTextFile(x.ScreenName);
}
});
}
//From Examples Static Class
public static bool AuthenticatedUser_UnFollowUser(string userName)
{
var authenticatedUser = User.GetAuthenticatedUser();
var userToFollow = User.GetUserFromScreenName(userName);
bool unfollowed = authenticatedUser.UnFollowUser(userToFollow);
return unfollowed;
}
//Users Not Following You
public static IEnumerable<IUser> Friendship_GetUsersNotFollowingYou()
{
var currentuser = Examples.User_GetCurrentUserScreenname();
var followers = Examples.User_GetFriendIds(currentuser);
var following = Examples.Friendship_GetUsersYouRequestedToFollow();
var toUnfollow = following.Where(x => followers != x.FriendIds);
return toUnfollow;
}
I am the developer of Tweetinvi. I have just verified and unfollow like follow seems to work properly. Could you please verify that you are using the latest version of Tweetinvi (0.9.13.0)?
Also please note that Unfollow will return success even if the user was not followed. This is what Twitter is returning and there is nothing I can do about that.
EDIT :
The problem came from the fact that #david-beamont was not retrieving the users properly.
Here is the code to get the following users :
var authenticatedUser = User.GetAuthenticatedUser();
var friends = authenticatedUser.GetFriends();
Outline
I am trying to implement WNS for my app game. I currently send a notification upon creation of a new user with the following function which works:
public async void SendNotificationToTag(string tag, string content)
{
var wnsToast = "<toast><visual><binding template=\"ToastText01\">"
+ "<text id=\"1\">Breaking " +content + "An WNS News!"
+ "</text></binding></visual></toast>";
WindowsPushMessage wnsMessage = new WindowsPushMessage();
wnsMessage.XmlPayload = wnsToast;
await Services.Push.HubClient.SendWindowsNativeNotificationAsync(wnsToast, tag);
Services.Log.Info("WNS TEST - SendWindowsNativeNotificationAsync - done");
}
I get a notfication to each username, i.e. a personal notificaion. I then update the tags the user listens to, looking in the hub database this also seems to work:
-Usernamecph--gameID1151--gameID1152--gameID1153--gameID1154--gameID1155--gameID1156--gameID1157--gameID1158
-gameID1157--UsernameFyn--gameID1151--gameID1153--gameID1155--gameID1156-
This check to extract the tags from the hub is done using
foreach (Microsoft.ServiceBus.Notifications.RegistrationDescription t in a)
{
string tempstring = "";
foreach (string x in t.Tags)
tempstring += "-" + x + "-";
Services.Log.Info(tempstring + t.RegistrationId + t.ETag);
}
So far so good.
When I then try to send to one of the other tags than the usernames I do not receive any notification, and I do not receive any error in the log. Am I missing something?
Update - Half Solution
If I use the server Explorer and look at the notification HUB. I can see all the tags, and I can send to them by using the test send. But I cannot seem to do it in other function calls online.
Is it something like the function has to be set as post or get?
YES
So inserting [HttpPost] Seems to enable the push.
However when I look in the Server explorer shown here on the image:
The user seems to be deleted when I update the registrations (There should be three, and there is again when I start the app with the correct tag subscriptions). So Maybe the question is How to Update a registration in the hub correctly
The current update code:
public async void updateRegistration(RegistrationDescription registration, List<string> TAGS)
{
registration.Tags = new HashSet<string>(TAGS);
try
{
var x = await hub.CreateOrUpdateRegistrationAsync(registration);
// apiServices.Log.Info(x.ExpirationTime + " " + x.Tags);
}
catch (MessagingException e)
{
ReturnGoneIfHubResponseIsGone(e);
}
}
The code that calls the function:
private async Task<bool> RegisterHubTag(User user, string Tag)
{
List<string> sendTAGs = new List<string>();
Services.Log.Info("RegisterHubTag Function");
using (Db db = new Db())
{
List<DataObjects.NotificationTag> userTags = db.NotificationTags.Where(t => t.User.UserId == user.UserId).ToList<DataObjects.NotificationTag>();
if (userTags.Count < 1)
{
//Register
RegisterController.DeviceRegistration Reg = CreateDeviceRegistration(user.PushChannelUri, sendTAGs);
Microsoft.Azure.NotificationHubs.RegistrationDescription registration = null;
//Microsoft.ServiceBus.Notifications.RegistrationDescription registration = null;
Services.Log.Info(Reg.Handle);
Services.Log.Info(Reg.Platform);
IEnumerable<string> tagsToRegister;
List<string> test = new List<string>() { user.Username };
if(Tag != user.Username)
test.Add(Tag);
tagsToRegister = test.AsEnumerable<string>();
switch (Reg.Platform)
{
case "mpns":
registration = new MpnsRegistrationDescription(Reg.Handle);
break;
case "wns":
registration = new WindowsRegistrationDescription(Reg.Handle);
break;
case "apns":
registration = new AppleRegistrationDescription(Reg.Handle);
break;
case "gcm":
registration = new GcmRegistrationDescription(Reg.Handle);
break;
default:
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var regID = await hub.Post(Services);
registration.RegistrationId = regID;
db.NotificationTags.Add(new DataObjects.NotificationTag() { User = user, tag = user.Username, RegistrationID = registration.RegistrationId });
hub.updateRegistration(registration, test);
db.SaveChanges();
}
else
{
RegisterController.DeviceRegistration Reg = CreateDeviceRegistration(user.PushChannelUri, sendTAGs);
Microsoft.Azure.NotificationHubs.RegistrationDescription registration = null;
//Microsoft.ServiceBus.Notifications.RegistrationDescription registration = null;
switch (Reg.Platform)
{
case "mpns":
registration = new MpnsRegistrationDescription(Reg.Handle);
break;
case "wns":
registration = new WindowsRegistrationDescription(Reg.Handle);
break;
case "apns":
registration = new AppleRegistrationDescription(Reg.Handle);
break;
case "gcm":
registration = new GcmRegistrationDescription(Reg.Handle);
break;
default:
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
registration.RegistrationId = userTags[0].RegistrationID;
IEnumerable<string> tagsToRegister;
List<string> test = new List<string>();
foreach (DataObjects.NotificationTag t in userTags)
test.Add(t.tag);
test.Add(Tag);
tagsToRegister = test.AsEnumerable<string>();
hub.updateRegistration(registration, test);
}
}
return true;
}
private RegisterController.DeviceRegistration CreateDeviceRegistration(string channelUri, List<string> tags)
{
return new RegisterController.DeviceRegistration() { Platform = "wns", Handle = channelUri, Tags = tags.ToArray<string>() };
}
New image
I really do not understand it, sometimes I have three registrations, but then in the counter in the bottom is still only saying 2 ? How can this be?
(The view is from the server explorer in VS2013)
I have no idea.. why this occurs.
In debug mode it is running well .
however, now I am trying to run my project in IIS web server and
it doesn't runs well.
I can access the main page of my project. but when I try to access the local database, the following error shows up.
this is my log file and codes:
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine("아님여기?"+ex.Message);
file2.Close(); //디버깅 계속................
}
In this catch I have the following error:
provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server
I am sorry that I can not explain which line is generating this exception because there's no exception occurring in debug mode...
Here is the code for Page Load:
protected void Page_Load(object sender, EventArgs e)
{
this.Page.Form.Enctype = "multipart/form-data";
WA = Request.QueryString["WA"];
if (string.IsNullOrEmpty(WA)) WA = "off";
string qstr = null;
qstr = Request.QueryString["vCnt"]; //ㅇㅈ이파라메터 들은 어디서...??
if (qstr != null && qstr != "") vCnt = Int32.Parse(qstr);
if (!IsPostBack)
{
Keywords = Request.QueryString["keywords"]; //ㅇㅈ search main -> searh 버튼 클릭
VideoSearch = Request.QueryString["VideoSearch"];//ㅇㅈ ~^~^~
// 스마트폰에서 포스팅 되었을 때
if (Request.UserAgent.Contains("Android"))
{
if (Request.Cookies["VIDEOSEARCH"] != null && Request.Cookies["VIDEOSEARCH"].Value != "")
{
VideoSearch = Request.Cookies["VIDEOSEARCH"].Value;
MAM.Models.Utils.CookieManager("VIDEOSEARCH", "");
}
}
if (!String.IsNullOrEmpty(Keywords) && !Keywords.Contains("null")) SearchTextbox2.Text = Keywords;
Debug.WriteLine("search text is " + SearchTextbox2.Text);
Debug.Flush();
try
{
if (!string.IsNullOrEmpty(VideoSearch))
{
//ㅇㅈ DNA를 추출하여 유사 동영상을 돌려받음.
string results = RetrieveDNAfromVideo(System.Web.HttpUtility.UrlDecode(VideoSearch)/*video name*/);
string[] lines = results.Split(new string[] { "\r\n" }, StringSplitOptions.None);
vSearchResults = new List<VSearchResult>();
foreach (string line in lines)
{
string[] words = line.Split(',');
VSearchResult vSearchResult = new VSearchResult();
vSearchResult.VideoID = Int32.Parse(words[0]);
vSearchResult.idx = Int32.Parse(words[1]);
vSearchResult.RGBdifferce = Int32.Parse(words[2]);
vSearchResults.Add(vSearchResult);
} //ㅇㅈ vSearchResults : RetrieveDNAfromVideo가 알려준유사동영상정보
MAMDataContext db = new MAMDataContext();
List<int> VideoIDs = (List<int>)vSearchResults.Select(v => v.VideoID).ToList();
//vdo = (List<Video>)(from a in db.Video
// join b in vSearchResults
// on a.id equals b.VideoID
// orderby b.RGBdifferce
// select a).ToList();
vdo = (List<Video>)(from a in db.Videos
where VideoIDs.Contains(a.id)
select a).ToList(); //ㅇㅈ vdo는 결국, RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들
vSearchResults2 = new List<VSearchResult2>();
VSearchResult v1 = null;
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v1 = vSearchResults.Where(t => t.VideoID == v.id).OrderBy(t => t.RGBdifferce).FirstOrDefault();//ㅇㅈ ㅇㄱㅁㅇ
// ㅇㅈ RetrieveDNAfromVideo가 알려준유사동영상정보-> id가 같은동영상들[-> RGBdifferce가 가장작은 애] [] 무슨의미??
v2.idx = v1.idx;
v2.RGBdifferce = v1.RGBdifferce;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Serach done");
Debug.Flush();
}
if (!string.IsNullOrEmpty(Keywords))
{
string ret2 = null;
string str1 = null;
if (string.IsNullOrEmpty(Keywords))
{
Keywords = SearchTextbox2.Text;
}
if (string.IsNullOrEmpty(str1)) str1 = Keywords; //ㅇㅈ str1 은 질의의도??
string[] searchTextArray = str1.Split(' ');
int cnt1 = searchTextArray.Count();
string st1 = ""; string st2 = ""; string st3 = "";
if (cnt1 > 0) st1 = searchTextArray[0];
if (cnt1 > 1) st2 = searchTextArray[1];
if (cnt1 > 2) st3 = searchTextArray[2];
MAMDataContext db = new MAMDataContext();
vdo = (List<Video>)db.Videos.Where(v => v.overview.Contains(st1)
|| (cnt1 > 1 ? v.overview.Contains(st2) : false)
|| (cnt1 > 2 ? v.overview.Contains(st3) : false)).ToList();//ㅇㅈ 검색어를 overview에 가지고 있는 동영상 리스트
vSearchResults2 = new List<VSearchResult2>();
foreach (Video v in vdo)
{
VSearchResult2 v2 = new VSearchResult2();
v2.VideoID = v.id;
v2.overview = v.overview;
v2.title = v.title;
v2.filename720 = v.filename720;
v2.filename360 = v.filename360;
v2.idx = 0;
v2.RGBdifferce = 0;
vSearchResults2.Add(v2);
}
Debug.WriteLine("Video Search");
}
}
catch (Exception ex)
{
Debug.WriteLine("Error in integration: " + ex.Message);
Debug.Flush();
StreamWriter file2 = new StreamWriter("c:\\resources\\file.log", true);
file2.WriteLine(ex.Message);
file2.Close(); //디버깅 계속................
}
Debug.WriteLine("Search End");
}
if (fUpload.PostedFile != null) //ㅇㅈ
{
fileupload1();
}
else
{
}
}
this is a guess because you did not provide a key information: the connection string.
my guess is that the application is using integrated authentication hence while debugging the access to the database is done using your credentials: as the developer you are likely allowed to do almost everything on the db so the application works correctly.
when the application is deployed the login to the database is performed using the credentials of the application pool used to run the application itself.
as a test you can change the user of the application pool on the iis server to use an account enabled on the db and retry to login.
there are two solutions:
- configure the application pool to use a specific windows user that is allowed to interact with the db
- change the connection string to log onto the db as a sql user (allowed to interact with the db)
So here is the code using S.DS.P to get all users very quickly in pages of 500 at a time..
public List<AllAdStudentsCV> GetUsersDistinguishedNamePagedResults( string domain, string distinguishedName )
{
try
{
NetworkCredential credentials = new NetworkCredential( ConfigurationManager.AppSettings["AD_User"], ConfigurationManager.AppSettings["AD_Pass"] );
LdapDirectoryIdentifier directoryIdentifier = new LdapDirectoryIdentifier( domain + ":389" );
List<AllAdStudentsCV> users = new List<AllAdStudentsCV>();
using (LdapConnection connection = new LdapConnection(directoryIdentifier, credentials))
{
string filter = "(&(objectClass=user)(objectCategory=person))";
string baseDN = ConfigurationManager.AppSettings["AD_DistinguishedName"];
string[] attribArray = {"name", "sAMAccountName", "objectGUID", "telexNumber", "HomePhone"};
List<SearchResultEntry> srList = PerformPagedSearch(connection, baseDN, filter, attribArray);
if (srList.Count == 0) return null;
foreach (SearchResultEntry entry in srList)
{
<...snip a bunch of code to filter out bad users by CN...>
users.Add( user );
}
catch ( Exception ex )
{
throw;
}
}
}
}
return users;
}
catch ( Exception ex )
{
throw;
}
}
private List<SearchResultEntry> PerformPagedSearch( LdapConnection connection, string baseDN, string filter, string[] attribs )
{
List<SearchResultEntry> results = new List<SearchResultEntry>();
SearchRequest request = new SearchRequest(
baseDN,
filter,
System.DirectoryServices.Protocols.SearchScope.Subtree,
attribs
);
PageResultRequestControl prc = new PageResultRequestControl(500);
//add the paging control
request.Controls.Add(prc);
int pages = 0;
while (true)
{
pages++;
SearchResponse response = connection.SendRequest(request) as SearchResponse;
//find the returned page response control
foreach (DirectoryControl control in response.Controls)
{
if (control is PageResultResponseControl)
{
//update the cookie for next set
prc.Cookie = ((PageResultResponseControl) control).Cookie;
break;
}
}
//add them to our collection
foreach (SearchResultEntry sre in response.Entries)
{
results.Add(sre);
}
//our exit condition is when our cookie is empty
if ( prc.Cookie.Length == 0 )
{
Trace.WriteLine( "Warning GetAllAdSdsp exiting in paged search wtih cookie = zero and page count =" + pages + " and user count = " + results.Count );
break;
}
}
return results;
}
It works perfectly on DEV and on Prod, but suddenly stopped working on the QA webserver when it talks to the QA AD server. it only returnes one page and then stops.
If I point DEV to the QA AD server it works correctly...
It was working before Feb 2012, last time I tested in QA, and definitely was broken in place by March 7, 2012
Can anyone think of anything that would cause this behavior? perhaps a windows update? I've had one jack this product up before...
I'm reasonably convinced that it's not the code or the configuration...as it works on so many other combinations... it's netowrk/securiyt/os related.. but I can't figure out what changed.
Any Help is appreicated
Had the exact same issue where no pages were returned after the first one.
Here is what I found to fix the problem:
PageResultRequestControl pageRequestControl = new PageResultRequestControl(500);
SearchOptionsControl soc = new SearchOptionsControl(System.DirectoryServices.Protocols.SearchOption.DomainScope);
request.Controls.Add(pageRequestControl);
request.Controls.Add(soc);
No idea what the SearchOptionsControl does, but since I added this, AD returns all the expected objects.
This line solves the issue (connection is LdapConnection) ->
connection.SessionOptions.ReferralChasing = ReferralChasingOptions.None;
https://social.msdn.microsoft.com/Forums/vstudio/en-US/17957bb2-15b4-4d44-80fa-9b27eb6cb61f/pageresultrequestcontrol-cookie-always-zero?forum=csharpgeneral