internal void SetError(string errorMsg) { ErrorMSG = "ERROR " + errorMsg; HasError = true; GlobalEventHandler.RaiseErrorOccured(ErrorMSG); }
private void SendPath(bool selectPath = true, bool queryGui = false) { IsHidden = false; string path = this.tvLdap.SelectedNode.Name; switch (Caller) { case CALLING_CONTROL.GUI_BASE: ADObjectInfo objectinfo = (ADObjectInfo)this.tvLdap.SelectedNode.Tag; GlobalEventHandler.RaiseGuiBaseObjectSelected(objectinfo, queryGui); break; case CALLING_CONTROL.GUI_ASQ: GlobalEventHandler.RaiseGuiAsqPathSelected(path); break; case CALLING_CONTROL.WIZARD: GlobalEventHandler.RaiseWizardPathSelected(path); break; default: break; } if (selectPath) { IsHidden = true; this.Hide(); } }
public string DecodeSID(SecurityIdentifier trustee, bool translateSid = true) { string ret = null; if (!translateSid) { ret = trustee.ToString() + " (must not resolve)"; } else { try { ret = ForestBase.SidCache.GetValueSafe <SecurityIdentifier, string>(trustee); if (ret == null) { ret = trustee.Translate(typeof(NTAccount)).Value; } } catch (Exception ex) { ret = trustee.ToString() + " (could not resolve)";; GlobalEventHandler.RaiseErrorOccured("ERROR resolving " + trustee.ToString()); ex.ToDummy(); } ForestBase.SidCache.AddSafe <SecurityIdentifier, string>(trustee, ret); } return(ret); }
private void GetSingleObjectPaths(string dc, string searchBase, string ldapFilter, string[] propertiesToLoad, SearchScope scope, ReferralChasingOptions referralChasing, QueryControl queryInfo) { GlobalEventHandler.RaiseErrorOccured(String.Format("Attribute list contains (a) constructed attribute(s) {0}\t-> changing to single object path base query", Environment.NewLine)); if ((queryInfo.PhantomRoot) && (propertiesToLoad.ContainsSubString("tokengroups", MATCH_POSITION.STARTSWITH))) { GlobalEventHandler.RaiseErrorOccured(String.Format("Turning off PhantomRoot {0}\t-> attribute(s) contain tokenGroups*", Environment.NewLine)); queryInfo.PhantomRoot = false; } GlobalEventHandler.QueryCompleted += QuerySingleObjectPaths; string[] attribs = new string[] { "cn" }; Query(dc, searchBase, ldapFilter, attribs, scope, referralChasing, queryInfo, propertiesToLoad); }
private void PagedAsyncQuery() { bool success = false; try { base.AsyncCalls++; IAsyncResult asResult = base.AsyncConnection.BeginSendRequest(ForestBase.CurrentRequestExtender.Request, PartialResultProcessing.ReturnPartialResultsAndNotifyCallback, PagedAsyncQueryCallBackPartial, null); success = true; } catch (LdapException ldapEx) { ForestBase.CurrentRequestExtender.HasError = true; ForestBase.CurrentRequestExtender.ErrorMSG = ldapEx.Message; } catch (Exception ex) { ForestBase.CurrentRequestExtender.HasError = true; ForestBase.CurrentRequestExtender.ErrorMSG = ex.Message; } if (!success) { GlobalEventHandler.RaiseAsyncPartialResult(null, true); } }
private void ConnectThis() { string pwd = this.txtPwd.Text; Credentials creds = null; if ((this.txtUser.Text.Length != 0) && (pwd.Length != 0)) { creds = new Credentials(this.txtForest.Text, this.txtDomain.Text, this.txtUser.Text, ref pwd); if (creds.HasError) { DialogResult ret = MessageBox.Show("Credential error", creds.ErrorMsg, MessageBoxButtons.RetryCancel); if (ret == DialogResult.Cancel) { Unload(); } } } else { creds = new Credentials(this.txtForest.Text, this.txtDomain.Text, this.txtUser.Text, ref pwd); } GlobalEventHandler.RaiseConnectionSignaled(creds); }
protected void StatsCookie() { if (QueryInfo.ExecStatsQuery) { if (QueryInfo.RootDse) { GlobalEventHandler.RaiseErrorOccured("Retreiving statistics from a rootDSE query cannot be done", true); } else if (QueryInfo.MustGetSingleObjectPath) { GlobalEventHandler.RaiseErrorOccured(String.Format("Switched to single object path base query {0}\t-> retreiving staistics doesn't make sense", Environment.NewLine), true); } else { RetreiveStatistics = QueryInfo.ExecStatsQuery; byte[] controlvalue = BerConverter.Encode("{i}", new object[] { 0x1 }); controlvalue = null; Request.Controls.Add(new DirectoryControl(STATISTCS_CONTROL_OID, controlvalue, false, true)); } } }
private TOKEN_GROUPS_AND_PRIILEGES GetTokenGroupsAndPrivileges(WindowsIdentity secp) { TOKEN_GROUPS_AND_PRIILEGES ret = default(TOKEN_GROUPS_AND_PRIILEGES); int tlength = 0; this.TokenHandle = IntPtr.Zero; this.Success = Advapi32.GetTokenInformation(secp.Token, TOKEN_INFORMATION_CLASS.TokenGroupsAndPrivileges, this.TokenHandle, tlength, out tlength); this.TokenHandle = Marshal.AllocHGlobal(tlength); this.Success = Advapi32.GetTokenInformation(secp.Token, TOKEN_INFORMATION_CLASS.TokenGroupsAndPrivileges, this.TokenHandle, tlength, out tlength); if (this.Success) { ret = (TOKEN_GROUPS_AND_PRIILEGES)Marshal.PtrToStructure(TokenHandle, typeof(TOKEN_GROUPS_AND_PRIILEGES)); } else { GlobalEventHandler.RaiseDebugInfoOccured("Failed on GetTokenInformation"); } return(ret); }
private void AuthGUI_FormClosing(object sender, FormClosingEventArgs e) { if (!CredsSent) { GlobalEventHandler.RaiseCredentialsSignaled(null); } }
private void RaiseCreds(Credentials creds) { CredsSent = true; GlobalEventHandler.RaiseCredentialsSignaled(creds); this.Close(); }
private bool LoadCurrentDomain(string domainDNS) { bool ret = false; DateTime starttime = DateTime.Now; ForestBase.DefaultDC = GetDC(domainDNS); ForestBase.DefaultDC.Load(DomainControllerHelper.UDPAttributes); ret = ForestBase.DefaultDC.Success; if (ret) { GlobalEventHandler.RaiseUDPPingProceeded((long)DateTime.Now.Subtract(starttime).TotalMilliseconds, (long)DateTime.Now.Subtract(base.UpdateStarted).TotalMilliseconds); starttime = DateTime.Now; ForestBase.RootDomainNamingContext = ForestBase.DefaultDC.RootDomainNamingContext; ForestBase.SchemaNamingContext = ForestBase.DefaultDC.SchemaNamingContext; ForestBase.ConfigurationNamingContext = ForestBase.DefaultDC.ConfigurationNamingContext; ForestBase.CurrentDomain = ForestBase.DefaultDC.DefaultNamingContext; ForestBase.CurrentDC = ForestBase.DefaultDC.Name; ret = LoadConfig(); if (ret) { ret = LoadForestName(); } if (ret) { ForestBase.DefaultDC.GetQueryPolicy(); StoreDC(ForestBase.DefaultDC, ForestBase.DefaultDC.DefaultNamingContext); GlobalEventHandler.RaiseDiscoveredCurrentDomain((long)DateTime.Now.Subtract(starttime).TotalMilliseconds, (long)DateTime.Now.Subtract(base.UpdateStarted).TotalMilliseconds); GlobalEventHandler.RaiseDiscoveredCurrentDomainNCs((long)0, (long)DateTime.Now.Subtract(base.UpdateStarted).TotalMilliseconds); } } else { if (domainDNS == null) { domainDNS = "current domain"; } base.SetError(String.Format("LoadCurrentDomain: Could not detect a DC in {0}", domainDNS)); GlobalEventHandler.RaiseFinishedDiscovering(); } return(ret); }
private void GetMachineSid() { this.MachineSid = GetAccountSid(MachineName); if (!this.Success) { GlobalEventHandler.RaiseDebugInfoOccured("Failed to resolve machine sid!"); } }
private void Apply() { cmdCloseAllGroups_Click(null, null); GlobalEventHandler.RaiseFilterSignaled(this.txtFilter.Text, false); cmdClearFilter_Click(null, null); this.Hide(); }
private void LoadInternal(string userName) { this.SidList = new List <string> { }; this.Groups = new List <SidInfo> { }; this.PrivilegesStringList = new List <string> { }; this.Privileges = new List <PrivilegeInfo> { }; this.CallingIdentity = GlobalUserStore.Name; this.CurrentIdentity = GlobalUserStore.Name; this.Sid = GlobalUserStore.SDDLSid; this.IsElevated = GlobalUserStore.IsElevated; if (!String.IsNullOrEmpty(userName)) { this.Success = false; try { using (WindowsIdentity secp = new WindowsIdentity(userName)) { if (GlobalUserStore.UPN.ToLowerInvariant() != userName) { this.CurrentIdentity = secp.Name; this.Sid = secp.User.Value; } this.TGP = GetTokenGroupsAndPrivileges(secp); } this.Success = true; } catch (Exception ex) { GlobalEventHandler.RaiseDebugInfoOccured("Failed to get target identity {0} {1} ({2})", userName, ex.Message, ex.GetType()); } } if (this.Success) { DecodeGroups(); DecodePrivileges(); } }
private void WalkNesting() { foreach (GroupInfo group in this.Groups) { foreach (GroupInfo checkgroup in this.Groups) { if (group.Sid != checkgroup.Sid) { if (checkgroup.SidList.Contains(group.Sid)) { GlobalEventHandler.RaiseNestingFound(checkgroup.Sid, (SidInfo)group); } } } } }
public void AsyncQuery(string dc, string searchBase, string ldapFilter, string[] propertiesToLoad, SearchScope scope, ReferralChasingOptions referralChasing, QueryControl queryInfo, bool performASQ = false) { CancelToken = false; GlobalEventHandler.ClearSearchCancelled(); GlobalEventHandler.SearchCancelled += ReceivedCancellation; byte[] pagingCookie = null; ForestBase.CurrentPorts.SelectedPort = queryInfo.Port; Connect(dc, referralChasing, true, connectionLess: (searchBase.Length == 0)); if (propertiesToLoad.Length == 0) { propertiesToLoad = null; } else if ((propertiesToLoad.Length == 1) && (propertiesToLoad[0] == "*")) { propertiesToLoad = null; } ForestBase.CurrentRequestExtender = new SearchRequestExtender(searchBase, ldapFilter, propertiesToLoad, scope, pagingCookie, queryInfo); base.AsyncComplete = false; base.AsyncCalls = 0; GlobalEventHandler.AsyncQureyIsCompleted += AsyncSearchComplete; PagedAsyncQuery(); }
public bool Load(string domainDNS = null, Credentials userCreds = null, DateTime startUpdate = default(DateTime)) { bool ret = false; base.UpdateStarted = startUpdate; ForestBase.Loading = true; ForestBase.CurrentDomain = domainDNS; ForestBase.GivenCreds = userCreds; PreLoad(); ret = LoadCurrentDomain(domainDNS); if (ret) { (new Thread(TrustThread)).Start(); (new Thread(SchemaThread)).Start(); (new Thread(DomainsThread)).Start(); int fincnt = 0; while (!base.HasError) { WaitHandle.WaitAny(base.Signaler); fincnt++; if (fincnt > 1) { break; } } } PostLoad(); GlobalEventHandler.RaiseFinishedDiscovering(); return(ret); }
protected List <SidInfo> GetTokenGroups(string targetDC, string sddlSid) { List <SidInfo> ret = new List <SidInfo> { }; LDAPHelper ldap = new LDAPHelper(); List <SearchResultEntry> res = ldap.Query(targetDC, String.Format("<SID={0}>", sddlSid), "(objectClass=*)", new string[] { "tokenGroups", "userPrincipalName" }, SearchScope.Base, ReferralChasingOptions.None, new QueryControl() { CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.FROM_DECODING }, returnResults: true); if (res.Count > 0) { foreach (byte[] bsid in res[0].Attributes["tokenGroups"].GetValues(typeof(byte[]))) { SecurityIdentifier sid = new SecurityIdentifier(bsid, 0); SidInfo sinfo = new SidInfo(bsid); ret.Add(sinfo); } foreach (string upn in res[0].Attributes["userPrincipalName"].GetValues(typeof(string))) { GlobalUserStore.UPN = upn; } } else { Info.AddFormatted("Failed on TokenGroups for {0}", sddlSid); GlobalEventHandler.RaiseDebugInfoOccured("Failed on TokenGroups for {0}", sddlSid); } return(ret); }
private void SchemaThread() { if (base.HasError) { return; } Stopwatch stp = new Stopwatch(); stp.Start(); GetAggregateSchema(ForestBase.DefaultDC.Name); stp.Stop(); base.Signaler[0].Set(); GlobalEventHandler.RaiseDiscoveredSchema(stp.ElapsedMilliseconds, (long)DateTime.Now.Subtract(base.UpdateStarted).TotalMilliseconds); }
private void QuerySingleObjectPaths(object infoStore, GlobalEventArgs args) { if ((args.ResultEventType & QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) != QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) { return; } if ((args.ResultEventType & QUERY_RESULT_EVENT_TYPE.IS_COMPLETED) == QUERY_RESULT_EVENT_TYPE.IS_COMPLETED) { GlobalEventHandler.QueryCompleted -= QuerySingleObjectPaths; } SearchRequestExtender reqstore = (SearchRequestExtender)infoStore; if (!reqstore.HasError) { GlobalEventHandler.RaiseErrorOccured(String.Format("Found {0} paths to handle", args.Entries.Count)); } reqstore.QueryInfo.CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.IS_PARTIAL; int cnt = 0; foreach (SearchResultEntry entry in args.Entries) { cnt++; if ((cnt == args.Entries.Count) && (!reqstore.MoreData)) { reqstore.QueryInfo.CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.NONE; } Query(reqstore.DC, entry.DistinguishedName, reqstore.LdapFilter, reqstore.Attributes, SearchScope.Base, reqstore.ReferralChasing, reqstore.QueryInfo); GlobalEventHandler.RaiseErrorOccured(String.Format("Subsequent query: #{0}", cnt)); } }
private void DomainsThread() { if (base.HasError) { return; } Stopwatch stp = new Stopwatch(); stp.Start(); LoadDomains(); stp.Stop();; base.Signaler[1].Set(); GlobalEventHandler.RaiseDiscoveredForest(stp.ElapsedMilliseconds, (long)DateTime.Now.Subtract(base.UpdateStarted).TotalMilliseconds); //GlobalEventHandler.RaiseDomainsUpdated(stp.ElapsedMilliseconds, (long)DateTime.Now.Subtract(UpdateStarted).TotalMilliseconds); }
private void HandleNesting(object sender, GlobalEventArgs args) { EventValue gval = args.Values.GetValueSafe("Group"); string groupsid = gval.GetTypedValue <string>(); EventValue mval = args.Values.GetValueSafe("Member"); SidInfo member = (SidInfo)mval.GetTypedValue <object>(); if (!this.SidList.Contains(groupsid)) { this.Members.Add(member); this.SidList.Add(member.Sid); GlobalEventHandler.RaiseNestingFound(this.Sid, member); } }
private void InternalStartWatching() { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Thread stat = new Thread(new ThreadStart(InternalStartWatching)); stat.SetApartmentState(ApartmentState.STA); stat.Start(); } else { while (!StopWatch) { try { bool ret = Clipboard.ContainsText(); if (ret) { ret = false; Int32 temp = Clipboard.GetText().GetHashCode(); if (Hash != temp) { Hash = temp; ret = true; } } GlobalEventHandler.RaiseClipBoardChanged(ret); } catch (Exception ex) { ex.ToDummy(); } Thread.Sleep(100); } } }
protected override bool ProcessCmdKey(ref Message keyMessage, Keys keyCode) { bool ret = false; bool suppress = false; if (keyCode == Searchkey) { GlobalEventHandler.RaiseStartSearch(); } else if (keyCode == ContinueSearchKey) { GlobalEventHandler.RaiseContinueSearch(); } if ((keyMessage.Msg == WM_KEYDOWN) || (keyMessage.Msg == WM_SYSKEYDOWN)) { if (SuppressTab) { if (keyCode == Keys.Tab) { suppress = true; ret = true; keyMessage.WParam = (IntPtr)13; } } } if (!suppress) { ret = base.ProcessCmdKey(ref keyMessage, keyCode); } return(ret); }
protected void GetAggregateSchema(string dcName) { DateTime modified = DateTime.MinValue; string[] attribs = new string[] { "modifyTimeStamp", "schemaInfo" }; List <SearchResultEntry> schemainfo = Query(dcName, ForestBase.SchemaNamingContext, "(objectClass=*)", attribs, SearchScope.Base, ReferralChasingOptions.None, new QueryControl() { CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.FROM_SCHEMA }, returnResults: true); Int32 updatever = 0; if (base.HasError) { base.SetError("Get Schema: " + base.ErrorMSG); } else { if (schemainfo[0].Attributes.Contains("schemaInfo")) { DirectoryAttribute dainfo = schemainfo[0].Attributes["schemaInfo"]; DecodeSchemaInfo(dainfo, out updatever); } //DirectoryAttribute dastamp = schemainfo[0].Attributes["modifyTimeStamp"]; //bool temp = false; //string plaind = null; //DecodeInt64Data(dastamp, ActiveDirectorySyntax.GeneralizedTime, out temp, out plaind); //DateTime.TryParse(plaind, out modified); } LoadCacheFromXML(ForestBase.ForestName, updatever); if (base.MustLoadSchemaFromAD) { GlobalEventHandler.RaiseLoadingSchema(); string[] attributes = new string[] { "attributeSecurityGUID", "schemaIDGUID", "lDAPDisplayName", "attributeSyntax", "oMSyntax", "isDefunct", "systemFlags", "linkID" }; List <SearchResultEntry> attributeSchema = Query(dcName, ForestBase.SchemaNamingContext, "(objectClass=attributeSchema)", attributes, SearchScope.Subtree, ReferralChasingOptions.None, new QueryControl() { AutoPage = true, CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.FROM_SCHEMA }, returnResults: true); attributes = new string[] { "systemMustContain", "systemMayContain", "systemAuxiliaryClass", "subClassOf", "mustContain", "mayContain", "lDAPDisplayName", "auxiliaryClass", "isDefunct", "schemaIDGUID" }; List <SearchResultEntry> classschema = Query(dcName, ForestBase.SchemaNamingContext, "(objectClass=classSchema)", attributes, SearchScope.Subtree, ReferralChasingOptions.None, new QueryControl() { AutoPage = true, CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.FROM_SCHEMA }, returnResults: true); string[] attribs1 = new string[] { "displayName", "rightsGuid" }; List <SearchResultEntry> extendedrights = Query(dcName, ForestBase.ConfigurationNamingContext, "(objectClass=controlAccessRight)", attribs1, SearchScope.Subtree, ReferralChasingOptions.None, new QueryControl() { AutoPage = true, CurrentResultEventType = QUERY_RESULT_EVENT_TYPE.FROM_SCHEMA }, returnResults: true); DownloadSchemaCache(attributeSchema, classschema, extendedrights, updatever); //DownloadSchemaCache(attributeSchema, classschema, extendedrights, modified); } LoadSchemaFomCache(); ForestBase.SchemaLoaded = true; ForestBase.AttributesLoaded = true; }
private void Connection_FormClosing(object sender, FormClosingEventArgs e) { GlobalEventHandler.RaiseConnectionSignaled(null); }
public List <string> TryCustomDecoding(DirectoryAttribute attrib, SearchResultEntry entry, ref bool match, ref bool exclusive, ActiveDirectorySyntax aSyntax = ActiveDirectorySyntax.CaseIgnoreString) { exclusive = false; match = true; List <string> ret = new List <string>(); bool isbad = false; #region userparamters if (attrib.Name.ToLowerInvariant() == "userparameters") { if (MainBase.UserSettings.DecodeUserParameters) { DirectoryAttribute desam = entry.Attributes["sAMAccountName"]; string sam = DecodeStringData(desam, ActiveDirectorySyntax.CaseIgnoreString, out isbad, true)[0]; DateTime start = DateTime.Now; WtsApi userparams = new WtsApi(ForestBase.CurrentDC, sam); GlobalEventHandler.RaiseSubsequentQuery((long)DateTime.Now.Subtract(start).TotalMilliseconds); ret = userparams.Print(); if (!userparams.HasError) { exclusive = true; } } } #endregion #region memberof else if (attrib.Name.ToLowerInvariant() == "memberof") { if (MainBase.UserSettings.DecodePrimaryGroupID) { try { DirectoryAttribute deprid = entry.Attributes["primaryGroupID"]; string pgid = DecodePrimaryGroupId(deprid, true); ret.Add(pgid.Replace("<", "<(primaryGroupID) ")); } catch (Exception ex) { ex.ToDummy(); } } } #endregion #region primarygroupid else if (attrib.Name.ToLowerInvariant() == "primarygroupid") { try { DirectoryAttribute deprid = entry.Attributes["primaryGroupID"]; string pgid = DecodePrimaryGroupId(deprid, MainBase.UserSettings.DecodePrimaryGroupID); ret.Add(pgid); exclusive = true; } catch (Exception ex) { ex.ToDummy(); } } else if (attrib.Name.ToLowerInvariant() == "defaultsecuritydescriptor") { DirectoryAttribute deprid = entry.Attributes["defaultsecuritydescriptor"]; ret = DecodeDefaultSD(deprid, MainBase.UserSettings.DecodeDefaultSD); exclusive = true; } #endregion #region logonhours else if (attrib.Name.ToLowerInvariant() == "logonhours") { try { ret = DecodeLogonHours(attrib); exclusive = true; } catch (Exception ex) { ex.ToDummy(); } } #endregion #region dSaSignature else if (attrib.Name.ToLowerInvariant() == "dsasignature") { try { ret = DecodeDsaSignature(attrib); exclusive = true; } catch (Exception ex) { ex.ToDummy(); } } else if (attrib.Name.ToLowerInvariant() == "schemainfo") { try { Int32 uver = 0; ret = DecodeSchemaInfo(attrib, out uver); exclusive = true; } catch (Exception ex) { ex.ToDummy(); } } #endregion #region tokenGroups tokenGroupsGlobalAndUniversal tokenGroupsNoGCAcceptable else if ((attrib.Name.ToLowerInvariant() == "tokengroups") || (attrib.Name.ToLowerInvariant() == "tokengroupsglobalanduniversal") || (attrib.Name.ToLowerInvariant() == "tokengroupsglobalanduniversal")) { if (MainBase.UserSettings.ResolveSids) { ret.AddRange(DecodeByteData(attrib, ActiveDirectorySyntax.Sid, out isbad, true)); exclusive = true; } } #endregion #region trust else if (attrib.Name.ToLowerInvariant() == "msds-trustforesttrustinfo") { foreach (byte[] value in attrib.GetValues(typeof(byte[]))) { ret.AddRange(new ForestTrustInfoDecoder(value).ToString()); exclusive = true; } } #endregion #region replication else if (attrib.Name.ToLowerInvariant() == "repluptodatevector") { foreach (byte[] value in attrib.GetValues(typeof(byte[]))) { ret.AddRange(new ReplUpToDateVector().Decode(value)); exclusive = true; } } else if (attrib.Name.ToLowerInvariant() == "replpropertymetadata") { //ActiveDirectoryReplicationMetadata metadata = CurrentDC } else if (aSyntax == ActiveDirectorySyntax.ReplicaLink) { } #endregion else { match = false; } return(ret); }
private void PagedAsyncQueryCallBackPartial(IAsyncResult Result) { PartialResultsCollection pResults = null; SearchResultEntry[] temp = new SearchResultEntry[0]; if (!Result.IsCompleted) { pResults = base.Connection.GetPartialResults(Result); if (pResults != null) { temp = new SearchResultEntry[pResults.Count]; pResults.CopyTo(temp, 0); } } else { SearchResponse sresponse = null; try { sresponse = (SearchResponse)base.AsyncConnection.EndSendRequest(Result); } catch (DirectoryOperationException direx) { if (direx.Response != null) { if (direx.Response.ResultCode == ResultCode.SizeLimitExceeded) { if (ForestBase.CurrentRequestExtender.QueryInfo.AutoPage) { GlobalEventHandler.RaiseErrorOccured(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); ForestBase.CurrentRequestExtender.AddMessage(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); ForestBase.CurrentRequestExtender.PageCookie(((SearchResponse)direx.Response).Entries.Count); ForestBase.CurrentRequestExtender.MoreData = true; PagedAsyncQuery(); } } } } catch (Exception ex) { string x = ex.Message; } temp = new SearchResultEntry[sresponse.Entries.Count]; sresponse.Entries.CopyTo(temp, 0); if (ForestBase.CurrentRequestExtender.RetreiveStatistics) { DirectoryControl dcStats = GetControl(sresponse.Controls, SearchRequestExtender.STATISTCS_CONTROL_OID); if (dcStats != null) { ForestBase.CurrentRequestExtender.Statistics.Add(new StatsData(dcStats.GetValue())); } else { GlobalEventHandler.RaiseErrorOccured("WARNING: No Query Statistics data returned"); } } DirectoryControl pageRespControl = GetControl(sresponse.Controls, ForestBase.CurrentRequestExtender.PageControl.Type); ForestBase.CurrentRequestExtender.UpdatePagingCookie(pageRespControl, sresponse.Entries.Count); base.AsyncCalls--; base.ParallelRuns--; } GlobalEventHandler.RaiseAsyncPartialResult(temp.ToList(), !ForestBase.CurrentRequestExtender.MoreData); if (!CancelToken) { if (ForestBase.CurrentRequestExtender.MoreData) { PagedAsyncQuery(); } else if (base.ParallelRuns < 1) { GlobalEventHandler.RaiseParallelQueriesCompleted(); } } else { GlobalEventHandler.RaiseParallelQueriesCompleted(); } }
public List <SearchResultEntry> Query(string dc, string searchBase, string ldapFilter, string[] propertiesToLoad, SearchScope scope, ReferralChasingOptions referralChasing, QueryControl queryInfo, string[] attributesRemebered = null, bool returnResults = false) { CancelToken = false; GlobalEventHandler.ClearSearchCancelled(); GlobalEventHandler.SearchCancelled += ReceivedCancellation; List <SearchResultEntry> ret = new List <SearchResultEntry> { }; List <SearchResultEntry> fire = new List <SearchResultEntry> { }; QueryHasConstructedAttribute(propertiesToLoad, scope, ref queryInfo); if (queryInfo.MustGetSingleObjectPath) { GetSingleObjectPaths(dc, searchBase, ldapFilter, propertiesToLoad, scope, referralChasing, queryInfo); return(ret); } ForestBase.CurrentPorts.SelectedPort = queryInfo.Port; byte[] pagingCookie = null; SearchRequestExtender reqstore = new SearchRequestExtender(searchBase, ldapFilter, propertiesToLoad, scope, pagingCookie, queryInfo); reqstore.DC = dc; reqstore.ReferralChasing = referralChasing; propertiesToLoad = reqstore.Attributes; while (true) { if (!reqstore.HasError) { reqstore.PageCount++; } SearchResultEntryCollection colresult = null; if (!CancelToken) { if (!queryInfo.PerformDirSync) { DateTime starttime = DateTime.Now; colresult = PagedQuery(ref reqstore); if (reqstore.CurrentPageSize > 0) { GlobalEventHandler.RaiseMessageOccured(String.Format("Page: {0} ({1}) [{2}] ms]", reqstore.PageCount, reqstore.CurrentPageSize, DateTime.Now.Subtract(starttime).TotalMilliseconds)); } } else { colresult = DirSyncQuery(ref reqstore); } } else { break; } if (reqstore.HasError) { break; } if ((colresult != null) && (colresult.Count > 0) && ((colresult[0].DistinguishedName.Length != 0) || (searchBase == ""))) { SearchResultEntry[] temp = new SearchResultEntry[colresult.Count]; colresult.CopyTo(temp, 0); fire = temp.ToList(); if (returnResults) { ret.AddRange(fire); } } if ((queryInfo.CurrentResultEventType == QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) && (attributesRemebered != null)) { reqstore.HandleAttributes(attributesRemebered); } if (reqstore.MoreData) { if ((fire.Count > 0) && !returnResults) { GlobalEventHandler.RaiseQueryCompleted(fire, reqstore, QUERY_RESULT_EVENT_TYPE.IS_PARTIAL | queryInfo.CurrentResultEventType); } if ((queryInfo.CurrentResultEventType == QUERY_RESULT_EVENT_TYPE.FROM_SINGLE_OBJECT_PATH) && (attributesRemebered != null)) { reqstore.HandleAttributes(propertiesToLoad); } } else { break; } } if (reqstore.DoPaging) { reqstore.AddMessage(String.Format("PageSize: {0}", reqstore.CurrentPageSize)); reqstore.AddMessage(String.Format("Pages: {0}", reqstore.PageCount)); } if (!returnResults) { GlobalEventHandler.RaiseQueryCompleted(fire, reqstore, QUERY_RESULT_EVENT_TYPE.IS_COMPLETED | queryInfo.CurrentResultEventType); } Disconnect(); return(ret); }
private SearchResultEntryCollection PagedQuery(ref SearchRequestExtender reqStore) { SearchResultEntryCollection ret = null; SearchResponse sresponse = null; bool goon = false; try { if ((base.IsConnected == false) || (base.Connection == null)) { Connect(reqStore.DC, reqStore.ReferralChasing, connectionLess: reqStore.QueryInfo.RootDse); } sresponse = (SearchResponse)base.Connection.SendRequest(reqStore.Request); goon = true; } catch (LdapException ldapEx) { base.SetError(ldapEx.Message); reqStore.HasError = true; reqStore.ErrorMSG = ldapEx.Message; return(null); } catch (DirectoryOperationException direx) { if (direx.Response != null) { if (direx.Response.ResultCode == ResultCode.SizeLimitExceeded) { if (reqStore.QueryInfo.AutoPage) { GlobalEventHandler.RaiseErrorOccured(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); reqStore.AddMessage(String.Format("Non-PagedQuery: {0} - switched to PagedQuery", direx.Response.ResultCode.ToString())); reqStore.PageCookie(((SearchResponse)direx.Response).Entries.Count); reqStore.MoreData = true; } else { sresponse = (SearchResponse)direx.Response; GlobalEventHandler.RaiseErrorOccured(String.Format("\tNon-PagedQuery: {0} - returned first {1} entries", direx.Response.ResultCode.ToString(), sresponse.Entries.Count)); reqStore.AddMessage(String.Format("Non-PagedQuery: {0} - returned first {1} entries", direx.Response.ResultCode.ToString(), sresponse.Entries.Count)); } goon = true; } else if ((direx.Response.ResultCode == ResultCode.UnavailableCriticalExtension) && direx.Response.ErrorMessage.StartsWith("00002040") && (reqStore.PageControl != null) && (reqStore.ReferralChasing != ReferralChasingOptions.None)) { reqStore.PageCount--; string msg = "Multiple page cookies from referrals."; msg = String.Format("{0} ({1})", msg, direx.Message); if (direx.Response.ErrorMessage != null) { msg = String.Format("{0}: ({1})", msg, direx.Response.ErrorMessage); } base.SetError(msg); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; //goon = true; } else { string msg = direx.Message; if (direx.Response.ErrorMessage != null) { msg = String.Format("{0}: ({1})", msg, direx.Response.ErrorMessage); } base.SetError(msg); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; } } else // if (!goon) { base.SetError(direx.Message); reqStore.HasError = true; reqStore.ErrorMSG = base.ErrorMSG; } } catch (Exception ex) { base.SetError(ex.Message); reqStore.HasError = true; reqStore.ErrorMSG = ex.Message; return(null); } if (goon) { if (sresponse != null) { if (reqStore.RetreiveStatistics) { DirectoryControl dcStats = GetControl(sresponse.Controls, SearchRequestExtender.STATISTCS_CONTROL_OID); if (dcStats != null) { reqStore.Statistics.Add(new StatsData(dcStats.GetValue())); } else { GlobalEventHandler.RaiseErrorOccured("WARNING: No Query Statistics data returned"); } } if (reqStore.PageControl != null) { DirectoryControl pageRespControl = GetControl(sresponse.Controls, reqStore.PageControl.Type); reqStore.UpdatePagingCookie(pageRespControl, sresponse.Entries.Count); } ret = sresponse.Entries; } } return(ret); }