/// <summary> /// Updates the entry in the directory and returns the updated version from the directory. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="entry">The entry to update.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="controls">Any <see cref="DirectoryControl"/>s to be sent with the request</param> /// <param name="listeners">The event listeners to be notified.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <returns></returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="entry"/> is null. /// </exception> /// <exception cref="DirectoryOperationException">Thrown if the operation fails</exception> /// <exception cref="LdapException">Thrown if the operation fails</exception> public static async Task <IDirectoryAttributes> UpdateAndGetAsync(this LdapConnection connection, IDirectoryAttributes entry, ILinqToLdapLogger log = null, DirectoryControl[] controls = null, IEnumerable <IUpdateEventListener> listeners = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { await UpdateAsync(connection, entry, log, controls, listeners, resultProcessing).ConfigureAwait(false); return(await GetByDNAsync(connection, entry.DistinguishedName, log, null, resultProcessing).ConfigureAwait(false)); }
protected override Expression VisitConstant(ConstantExpression c) { var q = c.Value as IQueryable; if (q != null) { } else if (c.Value == null || string.Empty.Equals(c.Value)) { _sb.Append(_dnFilter ? "" : "*"); } else if (c.Value is Expression) { Visit(c.Value as Expression); } else if (_dnFilter) { _sb.Append(_shouldCleanFilter ? (c.Value as string).CleanFilterValue() : (c.Value as string)); } else if (c.Type == typeof(PartialResultProcessing)) { _asyncProcessing = (PartialResultProcessing)c.Value; } else if (_currentProperty != null) { var str = _currentProperty.FormatValueToFilter(c.Value); if (str.IsNullOrEmpty()) { throw new FilterException("Cannot use white spaces for a value in a filter."); } _sb.Append(str); } else if (!_binaryExpression && false.Equals(c.Value)) { _falseEncountered = true; } return(c); }
/// <summary> /// List server information from RootDSE. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="attributes"> /// Specify specific attributes to load. Some LDAP servers require an explicit request for certain attributes. /// </param> /// <param name="resultProcessing">How the async results are processed</param> /// <returns></returns> public static async Task <IDirectoryAttributes> ListServerAttributesAsync(this LdapConnection connection, string[] attributes = null, ILinqToLdapLogger log = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { try { if (connection == null) { throw new ArgumentNullException("connection"); } using (var provider = new DirectoryQueryProvider( connection, SearchScope.Base, new ServerObjectMapping(), false) { Log = log, IsDynamic = true }) { var directoryQuery = new DirectoryQuery <IDirectoryAttributes>(provider); var query = directoryQuery .FilterWith("(objectClass=*)"); if (attributes?.Length > 0) { query = query.Select(attributes); } var results = await QueryableAsyncExtensions.FirstOrDefaultAsync(query, resultProcessing).ConfigureAwait(false); return(results ?? new DirectoryAttributes()); } } catch (Exception ex) { if (log != null) { log.Error(ex); } throw; } }
/// <summary> /// Retrieves the attributes from the directory using the distinguished name. <see cref="SearchScope.Base"/> is used. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="distinguishedName">The distinguished name to look for.</param> /// <param name="attributes">The attributes to load.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <returns></returns> public static async Task <IDirectoryAttributes> GetByDNAsync(this LdapConnection connection, string distinguishedName, ILinqToLdapLogger log = null, string[] attributes = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { try { if (connection == null) { throw new ArgumentNullException("connection"); } var request = new SearchRequest { DistinguishedName = distinguishedName, Scope = SearchScope.Base }; if (attributes != null) { request.Attributes.AddRange(attributes); } var transformer = new DynamicResultTransformer(); if (log != null && log.TraceEnabled) { log.Trace(request.ToLogString()); } #if NET45 return(await System.Threading.Tasks.Task.Factory.FromAsync( (callback, state) => { return connection.BeginSendRequest(request, resultProcessing, callback, state); }, (asyncresult) => { var response = connection.EndSendRequest(asyncresult) as SearchResponse; response.AssertSuccess(); return (response.Entries.Count == 0 ? transformer.Default() : transformer.Transform(response.Entries[0])) as IDirectoryAttributes; }, null ).ConfigureAwait(false)); #else var response = await Task.Run(() => connection.SendRequest(request) as SearchResponse).ConfigureAwait(false); response.AssertSuccess(); return((response.Entries.Count == 0 ? transformer.Default() : transformer.Transform(response.Entries[0])) as IDirectoryAttributes); #endif } catch (Exception ex) { if (log != null) { log.Error(ex, string.Format("An error occurred while trying to retrieve '{0}'.", distinguishedName)); } throw; } }
/// <summary> /// Adds the entry to the directory. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="entry">The entry to add.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="controls">Any <see cref="DirectoryControl"/>s to be sent with the request</param> /// <param name="listeners">The event listeners to be notified.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <returns></returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="connection"/> or <paramref name="entry"/>> is null. /// </exception> /// <exception cref="DirectoryOperationException">Thrown if the add was not successful.</exception> /// <exception cref="LdapException">Thrown if the operation fails.</exception> public static async Task AddAsync(this LdapConnection connection, IDirectoryAttributes entry, ILinqToLdapLogger log = null, DirectoryControl[] controls = null, IEnumerable <IAddEventListener> listeners = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { string distinguishedName = null; try { if (connection == null) { throw new ArgumentNullException("connection"); } if (entry == null) { throw new ArgumentNullException("entry"); } distinguishedName = entry.DistinguishedName; if (distinguishedName.IsNullOrEmpty()) { throw new ArgumentException("entry.DistinguishedName is invalid."); } var request = new AddRequest(distinguishedName, entry.GetChangedAttributes().Where(da => da.Count > 0).ToArray()); if (controls != null) { request.Controls.AddRange(controls); } if (listeners != null) { var args = new ListenerPreArgs <object, AddRequest>(entry, request, connection); foreach (var eventListener in listeners.OfType <IPreAddEventListener>()) { eventListener.Notify(args); } } if (log != null && log.TraceEnabled) { log.Trace(request.ToLogString()); } AddResponse response = null; #if NET45 await Task.Factory.FromAsync( (callback, state) => { return(connection.BeginSendRequest(request, resultProcessing, callback, state)); }, (asyncresult) => { response = (AddResponse)connection.EndSendRequest(asyncresult); response.AssertSuccess(); }, null ).ConfigureAwait(false); #else response = await Task.Run(() => connection.SendRequest(request) as AddResponse).ConfigureAwait(false); response.AssertSuccess(); #endif if (listeners != null) { var args = new ListenerPostArgs <object, AddRequest, AddResponse>(entry, request, response, connection); foreach (var eventListener in listeners.OfType <IPostAddEventListener>()) { eventListener.Notify(args); } } } catch (Exception ex) { if (log != null) { log.Error(ex, string.Format("An error occurred while trying to add '{0}'.", distinguishedName)); } throw; } }
/// <summary> /// Pages through all the results and returns them in a <see cref="List{T}"/>. /// </summary> /// <param name="source">The query</param> /// <param name="pageSize">The size of each page</param> /// <param name="resultProcessing">How the async results are processed</param> /// <typeparam name="TSource">The type to query against</typeparam> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="source"/> is null. /// </exception> /// <exception cref="ArgumentException">Thrown if <paramref name="pageSize"/> is not greater than 0</exception> /// <returns></returns> public static async Task <List <TSource> > InPagesOfAsync <TSource>(this IQueryable <TSource> source, int pageSize, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { if (source == null) { throw new ArgumentNullException("source"); } if (pageSize < 1) { throw new ArgumentException("pageSize must be greater than 0"); } if (source.Provider is IAsyncQueryProvider asyncProvider) { return(await asyncProvider.ExecuteAsync <List <TSource> >( Expression.Call(null, InPagesOfAsyncMethod.MakeGenericMethod( new[] { typeof(TSource) }), new[] { source.Expression, Expression.Constant(pageSize), Expression.Constant(resultProcessing) })).ConfigureAwait(false)); } return(source.InPagesOf(pageSize)); }
public void BeginSendRequest_InvalidPartialMode_ThrowsInvalidEnumArgumentException(PartialResultProcessing partialMode) { var connection = new LdapConnection("server"); AssertExtensions.Throws <InvalidEnumArgumentException>("partialMode", () => connection.BeginSendRequest(new AddRequest(), partialMode, null, null)); }
public IAsyncResult BeginSendRequest(DirectoryRequest request, PartialResultProcessing partialMode, AsyncCallback callback, object state) { return BeginSendRequest(request, connectionTimeOut, partialMode, callback, state); }
private static async Task <ModifyDNResponse> SendModifyDnRequestAsync(LdapConnection connection, string dn, string parentDn, string newName, bool?deleteOldRDN, DirectoryControl[] controls, ILinqToLdapLogger log = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { var request = new ModifyDNRequest { DistinguishedName = dn, NewParentDistinguishedName = parentDn, NewName = newName, }; if (deleteOldRDN.HasValue) { request.DeleteOldRdn = deleteOldRDN.Value; } if (controls != null) { request.Controls.AddRange(controls); } if (log != null && log.TraceEnabled) { log.Trace(request.ToLogString()); } #if NET45 return(await Task.Factory.FromAsync( (callback, state) => { return connection.BeginSendRequest(request, resultProcessing, callback, state); }, (asyncresult) => { return connection.EndSendRequest(asyncresult) as ModifyDNResponse; }, null ).ConfigureAwait(false)); #else return(await Task.Run(() => connection.SendRequest(request) as ModifyDNResponse).ConfigureAwait(false)); #endif }
public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { throw new NotImplementedException(); }
public IAsyncResult BeginSendRequest (DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { throw new NotImplementedException (); }
public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { int messageID = 0; int error = 0; if (this.disposed) { throw new ObjectDisposedException(base.GetType().Name); } if (request == null) { throw new ArgumentNullException("request"); } if ((partialMode < PartialResultProcessing.NoPartialResultSupport) || (partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback)) { throw new InvalidEnumArgumentException("partialMode", (int) partialMode, typeof(PartialResultProcessing)); } if ((partialMode != PartialResultProcessing.NoPartialResultSupport) && !(request is SearchRequest)) { throw new NotSupportedException(System.DirectoryServices.Protocols.Res.GetString("PartialResultsNotSupported")); } if ((partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) && (callback == null)) { throw new ArgumentException(System.DirectoryServices.Protocols.Res.GetString("CallBackIsNull"), "callback"); } error = this.SendRequestHelper(request, ref messageID); LdapOperation ldapSearch = LdapOperation.LdapSearch; if (request is DeleteRequest) { ldapSearch = LdapOperation.LdapDelete; } else if (request is AddRequest) { ldapSearch = LdapOperation.LdapAdd; } else if (request is ModifyRequest) { ldapSearch = LdapOperation.LdapModify; } else if (request is SearchRequest) { ldapSearch = LdapOperation.LdapSearch; } else if (request is ModifyDNRequest) { ldapSearch = LdapOperation.LdapModifyDn; } else if (request is CompareRequest) { ldapSearch = LdapOperation.LdapCompare; } else if (request is ExtendedRequest) { ldapSearch = LdapOperation.LdapExtendedRequest; } if ((error == 0) && (messageID != -1)) { if (partialMode == PartialResultProcessing.NoPartialResultSupport) { LdapRequestState state2 = new LdapRequestState(); LdapAsyncResult key = new LdapAsyncResult(callback, state, false); state2.ldapAsync = key; key.resultObject = state2; asyncResultTable.Add(key, messageID); this.fd.BeginInvoke(messageID, ldapSearch, ResultAll.LDAP_MSG_ALL, requestTimeout, true, new AsyncCallback(this.ResponseCallback), state2); return key; } bool partialCallback = false; if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { partialCallback = true; } LdapPartialAsyncResult asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout); partialResultsProcessor.Add(asyncResult); return asyncResult; } if (error == 0) { error = Wldap32.LdapGetLastError(); } throw this.ConstructException(error, ldapSearch); }
/// <summary> /// Executes <see cref="QueryableExtensions.ToList{TSource}"/> on <paramref name="source"/> in a <see cref="Task"/>. /// </summary> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The query.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <returns></returns> public static async Task <List <TSource> > ToListAsync <TSource>(this IQueryable <TSource> source, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { if (source.Provider is IAsyncQueryProvider asyncProvider) { return(await asyncProvider.ExecuteAsync <List <TSource> >( Expression.Call(null, ToListAsyncMethod.MakeGenericMethod( new[] { typeof(TSource) }), new[] { source.Expression, Expression.Constant(resultProcessing) })).ConfigureAwait(false)); } return(source.ToList()); }
/// <summary> /// Executes Any on <paramref name="source"/> in a <see cref="Task"/>. /// </summary> /// <param name="source">The query.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <param name="predicate">A function to test each element for a condition.</param> /// <typeparam name="TSource">The element type to return.</typeparam> /// <returns></returns> public static async Task <bool> AnyAsync <TSource>(this IQueryable <TSource> source, Expression <Func <TSource, bool> > predicate, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { if (source.Provider is IAsyncQueryProvider asyncProvider) { return(await asyncProvider.ExecuteAsync <bool>( Expression.Call(null, AnyPredicateAsyncMethod.MakeGenericMethod( new[] { typeof(TSource) }), new[] { source.Expression, predicate, Expression.Constant(resultProcessing) })).ConfigureAwait(false)); } return(source.Any(predicate)); }
/// <summary> /// Renames the entry within the same container. The <paramref name="newName"/> can be in the format /// XX=New Name or just New Name. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="currentDistinguishedName">The entry's current distinguished name</param> /// <param name="newName">The new name of the entry</param> /// <param name="deleteOldRDN">Maps to <see cref="P:System.DirectoryServices.Protocols.ModifyDNRequest.DeleteOldRdn"/>. Defaults to null to use default behavior</param> /// <param name="controls">Any <see cref="DirectoryControl"/>s to be sent with the request</param> /// <param name="resultProcessing">How the async results are processed</param> /// <exception cref="ArgumentException"> /// Thrown if <paramref name="currentDistinguishedName"/> has an invalid format. /// </exception> /// <exception cref="ArgumentNullException">Thrown if <paramref name="currentDistinguishedName"/> /// or <paramref name="newName"/> are null, empty or white space. /// </exception> /// <exception cref="DirectoryOperationException">Thrown if the operation fails.</exception> /// <exception cref="LdapConnection">Thrown if the operation fails.</exception> public static async Task <string> RenameEntryAsync(this LdapConnection connection, string currentDistinguishedName, string newName, ILinqToLdapLogger log = null, bool?deleteOldRDN = null, DirectoryControl[] controls = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { try { if (connection == null) { throw new ArgumentNullException("connection"); } if (currentDistinguishedName.IsNullOrEmpty()) { throw new ArgumentNullException("currentDistinguishedName"); } if (newName.IsNullOrEmpty()) { throw new ArgumentNullException("newName"); } newName = DnParser.FormatName(newName, currentDistinguishedName); var container = DnParser.GetEntryContainer(currentDistinguishedName); var response = await SendModifyDnRequestAsync(connection, currentDistinguishedName, container, newName, deleteOldRDN, controls, log, resultProcessing).ConfigureAwait(false); response.AssertSuccess(); return(string.Format("{0},{1}", newName, container)); } catch (Exception ex) { if (log != null) { log.Error(ex, string.Format("An error occurred while trying to rename entry '{0}' to '{1}'.", currentDistinguishedName, newName)); } throw; } }
/// <summary> /// Uses range retrieval to get all values for <paramref name="attributeName"/> on <paramref name="distinguishedName"/>. /// </summary> /// <typeparam name="TValue">The type of the attribute. Must be <see cref="string"/> or <see cref="Array"/> of <see cref="byte"/>.</typeparam> /// <param name="connection">The connection to the directory.</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="distinguishedName">The distinguished name of the entry.</param> /// <param name="attributeName">The attribute to load.</param> /// <param name="start">The starting point for the range. Defaults to 0.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="distinguishedName"/> or <paramref name="attributeName"/> is null, empty or white space. /// </exception> /// <returns></returns> public static async Task <IList <TValue> > RetrieveRangesAsync <TValue>(this LdapConnection connection, string distinguishedName, string attributeName, int start = 0, ILinqToLdapLogger log = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { int idx = start; int step = 0; string currentRange = null; try { if (connection == null) { throw new ArgumentNullException("connection"); } if (distinguishedName.IsNullOrEmpty()) { throw new ArgumentNullException("distinguishedName"); } if (attributeName.IsNullOrEmpty()) { throw new ArgumentNullException("attributeName"); } //Code pulled from http://dunnry.com/blog/2007/08/10/RangeRetrievalUsingSystemDirectoryServicesProtocols.aspx var list = new List <TValue>(); var range = string.Format("{0};range={{0}}-{{1}}", attributeName); currentRange = string.Format(range, idx, "*"); var request = new SearchRequest { DistinguishedName = distinguishedName, Filter = string.Format("({0}=*)", attributeName), Scope = SearchScope.Base }; request.Attributes.Add(currentRange); bool lastSearch = false; while (true) { SearchResponse response = null; #if NET45 await System.Threading.Tasks.Task.Factory.FromAsync( (callback, state) => { return(connection.BeginSendRequest(request, resultProcessing, callback, state)); }, (asyncresult) => { response = connection.EndSendRequest(asyncresult) as SearchResponse; }, null ).ConfigureAwait(false); #else response = await Task.Run(() => connection.SendRequest(request) as SearchResponse).ConfigureAwait(false); #endif response.AssertSuccess(); if (response.Entries.Count != 1) { break; } SearchResultEntry entry = response.Entries[0]; foreach (string attrib in entry.Attributes.AttributeNames) { currentRange = attrib; lastSearch = currentRange.IndexOf("*", 0, StringComparison.Ordinal) > 0; step = entry.Attributes[currentRange].Count; } foreach (TValue member in entry.Attributes[currentRange].GetValues(typeof(TValue))) { list.Add(member); idx++; } if (lastSearch) { break; } currentRange = string.Format(range, idx, (idx + step)); request.Attributes.Clear(); request.Attributes.Add(currentRange); } return(list); } catch (Exception ex) { if (log != null) { log.Error(ex, string.Format("An error occurred while trying to retrieve ranges of type '{0}' for range '{1}'.", typeof(TValue).FullName, currentRange)); } throw; } }
public System.IAsyncResult BeginSendRequest(DirectoryRequest request, System.TimeSpan requestTimeout, PartialResultProcessing partialMode, System.AsyncCallback callback, object state) { }
public System.IAsyncResult BeginSendRequest(DirectoryRequest request, System.TimeSpan requestTimeout, PartialResultProcessing partialMode, System.AsyncCallback callback, object state) {}
public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { int num = 0; if (!this.disposed) { if (request != null) { if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { throw new InvalidEnumArgumentException("partialMode", (int)partialMode, typeof(PartialResultProcessing)); } else { if (partialMode == PartialResultProcessing.NoPartialResultSupport || request as SearchRequest != null) { if (partialMode != PartialResultProcessing.ReturnPartialResultsAndNotifyCallback || callback != null) { int num1 = this.SendRequestHelper(request, ref num); LdapOperation ldapOperation = LdapOperation.LdapSearch; if (request as DeleteRequest == null) { if (request as AddRequest == null) { if (request as ModifyRequest == null) { if (request as SearchRequest == null) { if (request as ModifyDNRequest == null) { if (request as CompareRequest == null) { if (request as ExtendedRequest != null) { ldapOperation = LdapOperation.LdapExtendedRequest; } } else { ldapOperation = LdapOperation.LdapCompare; } } else { ldapOperation = LdapOperation.LdapModifyDn; } } else { ldapOperation = LdapOperation.LdapSearch; } } else { ldapOperation = LdapOperation.LdapModify; } } else { ldapOperation = LdapOperation.LdapAdd; } } else { ldapOperation = LdapOperation.LdapDelete; } if (num1 != 0 || num == -1) { if (num1 == 0) { num1 = Wldap32.LdapGetLastError(); } throw this.ConstructException(num1, ldapOperation); } else { if (partialMode != PartialResultProcessing.NoPartialResultSupport) { bool flag = false; if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) { flag = true; } LdapPartialAsyncResult ldapPartialAsyncResult = new LdapPartialAsyncResult(num, callback, state, true, this, flag, requestTimeout); LdapConnection.partialResultsProcessor.Add(ldapPartialAsyncResult); return ldapPartialAsyncResult; } else { LdapRequestState ldapRequestState = new LdapRequestState(); LdapAsyncResult ldapAsyncResult = new LdapAsyncResult(callback, state, false); ldapRequestState.ldapAsync = ldapAsyncResult; ldapAsyncResult.resultObject = ldapRequestState; LdapConnection.asyncResultTable.Add(ldapAsyncResult, num); this.fd.BeginInvoke(num, ldapOperation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, new AsyncCallback(this.ResponseCallback), ldapRequestState); return ldapAsyncResult; } } } else { throw new ArgumentException(Res.GetString("CallBackIsNull"), "callback"); } } else { throw new NotSupportedException(Res.GetString("PartialResultsNotSupported")); } } } else { throw new ArgumentNullException("request"); } } else { throw new ObjectDisposedException(base.GetType().Name); } }
public IAsyncResult BeginSendRequest(DirectoryRequest request, TimeSpan requestTimeout, PartialResultProcessing partialMode, AsyncCallback callback, object state) { int messageID = 0; int error = 0; if (this.disposed) throw new ObjectDisposedException(GetType().Name); // parameter validation if (request == null) throw new ArgumentNullException("request"); if (partialMode < PartialResultProcessing.NoPartialResultSupport || partialMode > PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) throw new InvalidEnumArgumentException("partialMode", (int)partialMode, typeof(PartialResultProcessing)); if (partialMode != PartialResultProcessing.NoPartialResultSupport && !(request is SearchRequest)) throw new NotSupportedException(Res.GetString(Res.PartialResultsNotSupported)); if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback && (callback == null)) throw new ArgumentException(Res.GetString(Res.CallBackIsNull), "callback"); error = SendRequestHelper(request, ref messageID); LdapOperation operation = LdapOperation.LdapSearch; if (request is DeleteRequest) operation = LdapOperation.LdapDelete; else if (request is AddRequest) operation = LdapOperation.LdapAdd; else if (request is ModifyRequest) operation = LdapOperation.LdapModify; else if (request is SearchRequest) operation = LdapOperation.LdapSearch; else if (request is ModifyDNRequest) operation = LdapOperation.LdapModifyDn; else if (request is CompareRequest) operation = LdapOperation.LdapCompare; else if (request is ExtendedRequest) operation = LdapOperation.LdapExtendedRequest; if (error == 0 && messageID != -1) { if (partialMode == PartialResultProcessing.NoPartialResultSupport) { LdapRequestState rs = new LdapRequestState(); LdapAsyncResult asyncResult = new LdapAsyncResult(callback, state, false); rs.ldapAsync = asyncResult; asyncResult.resultObject = rs; s_asyncResultTable.Add(asyncResult, messageID); _fd.BeginInvoke(messageID, operation, ResultAll.LDAP_MSG_ALL, requestTimeout, true, new AsyncCallback(ResponseCallback), rs); return (IAsyncResult)asyncResult; } else { // the user registers to retrieve partial results bool partialCallback = false; if (partialMode == PartialResultProcessing.ReturnPartialResultsAndNotifyCallback) partialCallback = true; LdapPartialAsyncResult asyncResult = new LdapPartialAsyncResult(messageID, callback, state, true, this, partialCallback, requestTimeout); s_partialResultsProcessor.Add(asyncResult); return (IAsyncResult)asyncResult; } } else { if (error == 0) { // success code but message is -1, unexpected error = Wldap32.LdapGetLastError(); } throw ConstructException(error, operation); } }
/// <summary> /// Deletes an entry from the directory. /// </summary> /// <param name="connection">The connection to the directory.</param> /// <param name="distinguishedName">The distinguished name of the entry /// </param><param name="controls">Any <see cref="DirectoryControl"/>s to be sent with the request</param> /// <param name="log">The log for query information. Defaults to null.</param> /// <param name="listeners">The event listeners to be notified.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="distinguishedName"/> is null, empty or white space.</exception> /// <exception cref="DirectoryOperationException">Thrown if the operation fails.</exception> /// <exception cref="LdapException">Thrown if the operation fails.</exception> public static async Task DeleteAsync(this LdapConnection connection, string distinguishedName, ILinqToLdapLogger log = null, DirectoryControl[] controls = null, IEnumerable <IDeleteEventListener> listeners = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { try { if (connection == null) { throw new ArgumentNullException("connection"); } if (distinguishedName.IsNullOrEmpty()) { throw new ArgumentNullException("distinguishedName"); } var request = new DeleteRequest(distinguishedName); if (controls != null) { request.Controls.AddRange(controls); } if (listeners != null) { var args = new ListenerPreArgs <string, DeleteRequest>(distinguishedName, request, connection); foreach (var eventListener in listeners.OfType <IPreDeleteEventListener>()) { eventListener.Notify(args); } } if (log != null && log.TraceEnabled) { log.Trace(request.ToLogString()); } DeleteResponse response = null; #if NET45 await Task.Factory.FromAsync( (callback, state) => { return(connection.BeginSendRequest(request, resultProcessing, callback, state)); }, (asyncresult) => { response = (DeleteResponse)connection.EndSendRequest(asyncresult); response.AssertSuccess(); }, null ).ConfigureAwait(false); #else response = await Task.Run(() => connection.SendRequest(request) as DeleteResponse).ConfigureAwait(false); response.AssertSuccess(); #endif if (listeners != null) { var args = new ListenerPostArgs <string, DeleteRequest, DeleteResponse>(distinguishedName, request, response, connection); foreach (var eventListener in listeners.OfType <IPostDeleteEventListener>()) { eventListener.Notify(args); } } } catch (Exception ex) { string message = string.Format("An error occurred while trying to delete '{0}'.", distinguishedName); if (log != null) { log.Error(ex, message); } throw; } }
public void BeginSendRequest_ReturnModeAndSearchRequest_ThrowsInvalidNotSupportedException(PartialResultProcessing partialMode) { var connection = new LdapConnection("server"); Assert.Throws <NotSupportedException>(() => connection.BeginSendRequest(new AddRequest(), partialMode, null, null)); }
/// <summary> /// Executes <see cref="QueryableExtensions.ListAttributes{TSource}"/> on <paramref name="source"/> in a <see cref="Task"/>. /// </summary> /// <typeparam name="TSource">The type of the elements of <paramref name="source"/>.</typeparam> /// <param name="source">The query.</param> /// <param name="resultProcessing">How the async results are processed</param> /// <param name="attributes">The attributes to load.</param> /// <returns></returns> public static async Task <IEnumerable <KeyValuePair <string, IEnumerable <KeyValuePair <string, object> > > > > ListAttributesAsync <TSource>(this IQueryable <TSource> source, string[] attributes = null, PartialResultProcessing resultProcessing = LdapConfiguration.DefaultAsyncResultProcessing) { if (source.Provider is IAsyncQueryProvider asyncProvider) { return(await asyncProvider.ExecuteAsync <IEnumerable <KeyValuePair <string, IEnumerable <KeyValuePair <string, object> > > > >( Expression.Call(null, ListAttributesAsyncMethod.MakeGenericMethod( new[] { typeof(TSource) }), new[] { source.Expression, Expression.Constant(attributes ?? new string[0]), Expression.Constant(resultProcessing) })).ConfigureAwait(false)); } return(source.ListAttributes()); }