本文整理汇总了C#中System.DirectoryServices.Protocols.LdapConnection.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# LdapConnection.Dispose方法的具体用法?C# LdapConnection.Dispose怎么用?C# LdapConnection.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.DirectoryServices.Protocols.LdapConnection
的用法示例。
在下文中一共展示了LdapConnection.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: authenticateBoundary
public User authenticateBoundary(string email, string password)
{
ldapId = new LdapDirectoryIdentifier(HOST, PORT);
network = new NetworkCredential(DN.Replace("{0}", email), password);
using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
{
try
{
connection.SessionOptions.SecureSocketLayer = false;
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
connection.Dispose();
return queryLdap(email);
}
catch (LdapException ex)
{
throw new BusinessException(ex.Message);
}
catch (Exception e)
{
throw new PlatformException(e.Message);
}
}
}
示例2: autenticarUsuario
/// <summary>
/// Autentica a un usuario contra openLDAP y verifica su membresia en alguno de los grupos
/// </summary>
/// <param name="nombreUsuario">Nombre de usuario</param>
/// <param name="password">Contraseña del usuario</param>
/// <returns>El grupo al que pertenece el usuario o null en caso que no esté registrado.</returns>
public GrupoLDAP autenticarUsuario(string nombreUsuario, string password)
{
// Valida usuario y contraseña correctos
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential("uid=" + nombreUsuario + ",ou=people,dc=ic-itcr,dc=ac,dc=cr", password);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3;
try
{
openLdap.Bind();
}
catch (Exception e)
{
openLdap.Dispose();
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
return null;
}
// Buscar grupo al que pertenezca el usuario
foreach (GrupoLDAP grupo in _listadaGrupos.obtenerGruposLDAP())
{
SearchRequest searchRequest = new SearchRequest("cn=" + grupo.NombreGrupo + ",ou=group,dc=ic-itcr,dc=ac,dc=cr", "(memberUid=" + nombreUsuario + ")", System.DirectoryServices.Protocols.SearchScope.Subtree);
try
{
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest);
if (searchResponse.Entries.Count != 0)
{
openLdap.Dispose();
return grupo;
}
}
catch (Exception e)// En caso que algún grupo registrado en ListadoGruposLDAP.getGroupList() no exista.
{
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "Algún grupo registrado en ListadoGruposLDAP.getGroupList() no existe.");
continue;
}
}
openLdap.Dispose();
return null;
}
示例3: ValidateUserInternal
public bool ValidateUserInternal(string username, string password)
{
LdapConnection connection = new LdapConnection(Domain);
try
{
connection.Bind(new NetworkCredential(username, password));
}
catch
{
return false;
}
finally
{
connection.Dispose();
}
return true;
}
示例4: queryLdap
private User queryLdap(string email)
{
string ldapFilter = "(objectClass=person)";
string ldapTarget = DN.Replace("{0}", email);
User user = new User();
network = new NetworkCredential(ADMIN, ADMIN_PASS);
ldapId = new LdapDirectoryIdentifier(HOST, PORT);
using (LdapConnection connection = new LdapConnection(ldapId, network, AuthType.Basic))
{
try
{
connection.SessionOptions.SecureSocketLayer = false;
connection.SessionOptions.ProtocolVersion = 3;
connection.Bind();
SearchRequest searchRequest = new SearchRequest(ldapTarget, ldapFilter, SearchScope.Subtree, "*");
SearchResponse searchResponse = (SearchResponse)connection.SendRequest(searchRequest);
SearchResultEntry entry = searchResponse.Entries[0];
user.email = email;
user.userId = entry.Attributes["employeeNumber"][0].ToString();
user.userName = entry.Attributes["cn"][0].ToString();
user.lastName = entry.Attributes["sn"][0].ToString();
user.userGroup = entry.Attributes["departmentNumber"][0].ToString();
connection.Dispose();
return user;
}
catch (LdapException ex)
{
throw new BusinessException(ex.Message);
}
catch (Exception e)
{
throw new PlatformException(e.Message);
}
}
}
示例5: DirectoryInformation
//.........这里部分代码省略.........
DirectoryEntry containerEntry = new DirectoryEntry(GetADsPath(containerDN), GetUsername(), GetPassword(), authenticationType);
try
{
creationContainerDN = containerDN = (string) PropertyManager.GetPropertyValue(containerEntry, "distinguishedName");
}
catch (COMException ce)
{
if (ce.ErrorCode == unchecked((int) 0x80072030))
throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
else
throw;
}
}
//
// Check if the specified path(container) exists on the specified server/domain
// (NOTE: We need to do this using S.DS.Protocols rather than S.DS because we need to
// bypass the referral chasing which is automatic in S.DS)
//
LdapConnection tempConnection = new LdapConnection(new LdapDirectoryIdentifier(serverName + ":" + port), GetCredentialsWithDomain(credentials), ldapAuthType);
tempConnection.SessionOptions.ProtocolVersion = 3;
try
{
tempConnection.SessionOptions.ReferralChasing = System.DirectoryServices.Protocols.ReferralChasingOptions.None;
SetSessionOptionsForSecureConnection(tempConnection, false /*useConcurrentBind */);
tempConnection.Bind();
SearchRequest request = new SearchRequest();
request.DistinguishedName = containerDN;
request.Filter = "(objectClass=*)";
request.Scope = System.DirectoryServices.Protocols.SearchScope.Base;
request.Attributes.Add("distinguishedName");
request.Attributes.Add("objectClass");
if (ServerSearchTimeout != -1)
request.TimeLimit = new TimeSpan(0, ServerSearchTimeout, 0);
SearchResponse response;
try
{
response = (SearchResponse) tempConnection.SendRequest(request);
if (response.ResultCode == ResultCode.Referral || response.ResultCode == ResultCode.NoSuchObject)
throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
else if (response.ResultCode != ResultCode.Success)
throw new ProviderException(response.ErrorMessage);
}
catch (DirectoryOperationException oe)
{
SearchResponse errorResponse = (SearchResponse) oe.Response;
if (errorResponse.ResultCode == ResultCode.NoSuchObject)
throw new ProviderException(SR.GetString(SR.ADMembership_Container_does_not_exist));
else throw;
}
//
// check that the container is of an object type that can be a superior of a user object
//
DirectoryAttribute objectClass = response.Entries[0].Attributes["objectClass"];
if (!ContainerIsSuperiorOfUser(objectClass))
throw new ProviderException(SR.GetString(SR.ADMembership_Container_not_superior));
//
// Determine whether concurrent bind is supported
//
if ((connectionProtection == ActiveDirectoryConnectionProtection.None) || (connectionProtection == ActiveDirectoryConnectionProtection.Ssl))
{
this.concurrentBindSupported = IsConcurrentBindSupported(tempConnection);
}
}
finally
{
tempConnection.Dispose();
}
//
// if this is ADAM, get the partition DN
//
if (directoryType == DirectoryType.ADAM)
{
adamPartitionDN = GetADAMPartitionFromContainer();
}
else
{
if (enablePasswordReset)
{
// for AD, get the lockout duration for user account auto unlock
DirectoryEntry de = new DirectoryEntry(GetADsPath((string) PropertyManager.GetPropertyValue(rootdse, "defaultNamingContext")), GetUsername(), GetPassword(), AuthenticationTypes);
NativeComInterfaces.IAdsLargeInteger largeIntValue = (NativeComInterfaces.IAdsLargeInteger) PropertyManager.GetPropertyValue(de, "lockoutDuration");
Int64 int64Value = largeIntValue.HighPart * 0x100000000 + (uint) largeIntValue.LowPart;
// int64Value is the negative of the number of 100 nanoseconds interval that makes up the lockout duration
adLockoutDuration = new TimeSpan(-int64Value);
}
}
}
示例6: validateUserByBind
/// <summary>
/// Another way of validating a user is by performing a bind. In this case the server
/// queries its own database to validate the credentials. It is defined by the server
/// how a user is mapped to its directory.
/// </summary>
/// <param name="username">Username</param>
/// <param name="password">Password</param>
/// <returns>true if the credentials are valid, false otherwise</returns>
public bool validateUserByBind(string username, string password)
{
bool result = true;
var credentials = new NetworkCredential(username, password);
var serverId = new LdapDirectoryIdentifier(connection.SessionOptions.HostName);
var conn = new LdapConnection(serverId, credentials);
try
{
conn.Bind();
}
catch (Exception)
{
result = false;
}
conn.Dispose();
return result;
}
示例7: BindLdap
private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
{
LdapConnection item;
int lDAPSSLPORT;
bool flag;
int num;
bool flag1 = (ContextOptions.SecureSocketLayer & contextOptions) > 0;
if (this.contextType != ContextType.ApplicationDirectory)
{
CredentialValidator ldapDirectoryIdentifier = this;
string str = this.serverName;
if (flag1)
{
lDAPSSLPORT = LdapConstants.LDAP_SSL_PORT;
}
else
{
lDAPSSLPORT = LdapConstants.LDAP_PORT;
}
ldapDirectoryIdentifier.directoryIdent = new LdapDirectoryIdentifier(str, lDAPSSLPORT);
}
else
{
CredentialValidator credentialValidator = this;
string str1 = this.serverProperties.dnsHostName;
if (flag1)
{
num = this.serverProperties.portSSL;
}
else
{
num = this.serverProperties.portLDAP;
}
credentialValidator.directoryIdent = new LdapDirectoryIdentifier(str1, num);
}
if (!flag1)
{
flag = false;
}
else
{
flag = this.fastConcurrentSupported;
}
bool flag2 = flag;
int num1 = Convert.ToInt32(flag2) * 2 + Convert.ToInt32(flag1);
if (this.connCache.Contains(num1))
{
item = (LdapConnection)this.connCache[(object)num1];
}
else
{
lock (this.cacheLock)
{
if (this.connCache.Contains(num1))
{
item = (LdapConnection)this.connCache[(object)num1];
}
else
{
item = new LdapConnection(this.directoryIdent);
item.SessionOptions.SecureSocketLayer = flag1;
if (flag2)
{
try
{
item.SessionOptions.FastConcurrentBind();
}
catch (PlatformNotSupportedException platformNotSupportedException)
{
item.Dispose();
item = null;
this.fastConcurrentSupported = false;
num1 = Convert.ToInt32(flag1);
item = new LdapConnection(this.directoryIdent);
item.SessionOptions.SecureSocketLayer = flag1;
}
}
this.connCache.Add(num1, item);
}
}
}
if (!flag2 || !this.fastConcurrentSupported)
{
lock (this.cacheLock)
{
this.lockedLdapBind(item, creds, contextOptions);
}
}
else
{
this.lockedLdapBind(item, creds, contextOptions);
}
return true;
}
示例8: cambiarContrasena
/// <summary>
/// Método que cambia la contraseña de un usuario
/// </summary>
/// <param name="nombreUsuario">Nombre de usuario</param>
/// <param name="password">Contraseña nueva</param>
public void cambiarContrasena(string nombreUsuario, string password)
{
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); // Conectar
ModifyRequest increment = new ModifyRequest("uid=" + nombreUsuario + ",ou=people,dc=ic-itcr,dc=ac,dc=cr"
, DirectoryAttributeOperation.Replace, "userPassword", generarClaveSha(password));
openLdap.SendRequest(increment);
openLdap.Dispose();
}
示例9: BindLdap
private bool BindLdap(NetworkCredential creds, ContextOptions contextOptions)
{
LdapConnection current = null;
bool useSSL = (ContextOptions.SecureSocketLayer & contextOptions) > 0;
if (_contextType == ContextType.ApplicationDirectory)
{
_directoryIdent = new LdapDirectoryIdentifier(_serverProperties.dnsHostName, useSSL ? _serverProperties.portSSL : _serverProperties.portLDAP);
}
else
{
_directoryIdent = new LdapDirectoryIdentifier(_serverName, useSSL ? LdapConstants.LDAP_SSL_PORT : LdapConstants.LDAP_PORT);
}
bool attemptFastConcurrent = useSSL && _fastConcurrentSupported;
int index = Convert.ToInt32(attemptFastConcurrent) * 2 + Convert.ToInt32(useSSL);
if (!_connCache.Contains(index))
{
lock (_cacheLock)
{
if (!_connCache.Contains(index))
{
current = new LdapConnection(_directoryIdent);
// First attempt to turn on SSL
current.SessionOptions.SecureSocketLayer = useSSL;
if (attemptFastConcurrent)
{
try
{
current.SessionOptions.FastConcurrentBind();
}
catch (PlatformNotSupportedException)
{
current.Dispose();
current = null;
_fastConcurrentSupported = false;
index = Convert.ToInt32(useSSL);
current = new LdapConnection(_directoryIdent);
// We have fallen back to another connection so we need to set SSL again.
current.SessionOptions.SecureSocketLayer = useSSL;
}
}
_connCache.Add(index, current);
}
else
{
current = (LdapConnection)_connCache[index];
}
}
}
else
{
current = (LdapConnection)_connCache[index];
}
// If we are performing fastConcurrentBind there is no need to prevent multithreadaccess. FSB is thread safe and multi cred safe
// FSB also always has the same contextoptions so there is no need to lock the code that is modifying the current connection
if (attemptFastConcurrent && _fastConcurrentSupported)
{
lockedLdapBind(current, creds, contextOptions);
}
else
{
lock (_cacheLock)
{
lockedLdapBind(current, creds, contextOptions);
}
}
return true;
}
示例10: agregarGruposGenerales
/// <summary>
/// Método que agrega a un usuario a los grupos generales del LDAP
/// </summary>
/// <param name="nombreUsuario">Usuario al cual se tiene que agregar a los grupos</param>
private void agregarGruposGenerales(string nombreUsuario)
{
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);//Conexion
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); // Conectar
// Agregar a cada uno de los grupos generales
foreach (string grupo in Constantes.GROUPS)
{
openLdap.SendRequest(new ModifyRequest("cn=" + grupo + ",ou=group,dc=ic-itcr,dc=ac,dc=cr", DirectoryAttributeOperation.Add, "memberUid", nombreUsuario));
}
openLdap.Dispose();
}
示例11: agregarGrupo
/// <summary>
/// Método que se encarga de agregar un usuario a un grupo especifico
/// </summary>
/// <param name="nombreUsuario">Nombre de usuario</param>
/// <param name="grupo">Nombre del grupo al cual se desea agregar el usuario</param>
private void agregarGrupo(string nombreUsuario, string grupo)
{
// CONSULTAR ESTO ANTES DE PONERLO EN EJECUCIÓN
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);//Conexion
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); // Conectar
// Agregar el usuario al grupo especificado
openLdap.SendRequest(new ModifyRequest("cn=" + grupo + ",ou=group,dc=ic-itcr,dc=ac,dc=cr", DirectoryAttributeOperation.Add, "memberUid", nombreUsuario));
openLdap.Dispose();
}
示例12: verificarProfesor
public Boolean verificarProfesor(string clave)
{
String descripcion = String.Empty;
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); // Conectar
// El criterio seleccionado es "Login" true
// if (!tipoBusqueda)
// clave = buscarUsuarioPorCarnet(clave);
Boolean res = false;
string[] attributesToReturn = new string[] { "description" }; // Retornar solamente el login
SearchRequest searchRequest = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + clave + "*)",
System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar por carnet
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); // Respuesta del servidor
if (searchResponse.Entries.Count == 0)
return res;
//Cambiar a String cada atributo del usuario
if (attributesToReturn.Length > 0)
{
DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["description"];
if (atributo != null)
{
object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
descripcion = Encoding.ASCII.GetString((byte[])objeto[0]);
}
else
{
return res;
}
}
if (descripcion == "Profesor")
res = true;
openLdap.Dispose(); //Liberar recursos
return res;
}
示例13: obtenerNombrePersona
/// <summary>
/// Método que se encarga de obtener el nombre de una persona a partir de su nombre de usuario (login)
/// </summary>
/// <param name="nombreUsuario">Nombre de usuario (login)</param>
/// <returns>Nombre de la persona</returns>
public String obtenerNombrePersona(string nombreUsuario)
{
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
try
{
String nombrePersona;
// Crear conexion con LDAP
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); //Conectar
string[] attributesToReturn = new string[] { "displayName" }; // Atributos a retornar
// Buscar al usuario por su login
SearchRequest searchRequest = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + nombreUsuario + "*)",
System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn);
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); // Respuesta del servidor
DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["displayName"];
object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
nombrePersona = Encoding.ASCII.GetString((byte[])objeto[0]);
openLdap.Dispose(); // Liberar recursos
return nombrePersona;
}
catch (Exception e)
{
openLdap.Dispose();
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
return null;
}
}
示例14: obtenerListaSoporte
/// <summary>
/// Método que recupera del LDAP el nombre, login y correo de los miembros de la Oficina de TI.
/// </summary>
/// <returns>Lista de Usuarios</returns>
public List<Usuario> obtenerListaSoporte()
{
List<Usuario> _resultado = new List<Usuario>(); //Lista de usuarios con los datos de los miembros de la Oficina de TI
List<String> _logins = new List<String>(); //Lista con los logins de los miembros de la Oficina de TI
#region buscar login
//Busca los memberUid del grupo soporte
int _conta = 0;
// Crear conexion con LDAP
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); //Conectar
string[] attributesToReturn = new string[] { "memberUid" }; // Atributos a retornar
SearchRequest searchRequest = new SearchRequest("ou=group,dc=ic-itcr,dc=ac,dc=cr", "(cn=soporte)",
System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); //Filtro de busqueda.
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); // Respuesta del servidor
DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["memberUid"];
object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
foreach (object ob in objeto)
{
String _login = Encoding.ASCII.GetString((byte[])objeto[_conta]);
_logins.Add(_login);
_conta++;
}
#endregion
#region buscar nombre y correo
//Busca el displayName y el mail de cada soportista según el login en el LDAP
foreach (String login in _logins)
{
try
{
Usuario _usuario = new Usuario();
_usuario.UID = login;
string[] _datos = new string[] { "displayName", "mail" }; // Atributos a retornar
// Buscar al usuario por su login
SearchRequest _buqueda = new SearchRequest("ou=people,dc=ic-itcr,dc=ac,dc=cr", "(uid=" + login + "*)",
System.DirectoryServices.Protocols.SearchScope.Subtree, _datos);
SearchResponse _respuesta = (SearchResponse)openLdap.SendRequest(_buqueda); // Respuesta del servidor
DirectoryAttribute _atributo = _respuesta.Entries[0].Attributes["displayName"];
object[] _objeto = _atributo.GetValues(Type.GetType("System.Byte[]"));
_usuario.Nombre = Encoding.ASCII.GetString((byte[])_objeto[0]);
_atributo = _respuesta.Entries[0].Attributes["mail"];
_objeto = _atributo.GetValues(Type.GetType("System.Byte[]"));
_usuario.Correo = Encoding.ASCII.GetString((byte[])_objeto[0]);
_resultado.Add(_usuario);
}
catch (Exception e)
{
_conexionBD = new ManejoBD();
_conexionBD.insertarBitacoraError(e.ToString(), "");
//throw e;
}
}
#endregion
openLdap.Dispose(); // Liberar recursos
return _resultado;
}
示例15: obtenerNumeroUid
/// <summary>
/// Método que retorna el proximo identificador unico libre
/// </summary>
/// <returns>Identificador único libre</returns>
private String obtenerNumeroUid()
{
string uid = "";
LdapDirectoryIdentifier serverInfo = new LdapDirectoryIdentifier(Constantes.LDAP_SERVER);
LdapConnection openLdap = new LdapConnection(Constantes.LDAP_SERVER);
openLdap.Credential = new System.Net.NetworkCredential(Constantes.LDAP_USER, Constantes.LDAP_PASS);
openLdap.AuthType = AuthType.Basic;
openLdap.SessionOptions.ProtocolVersion = 3; // Hay que usar LDAPv3
openLdap.Bind(); // Conectar
string[] attributesToReturn = new string[] { "uidNumber" }; // Retornar solamente el uid number
SearchRequest searchRequest = new SearchRequest("dc=ic-itcr,dc=ac,dc=cr", "(cn=NextFreeUnixId)",
System.DirectoryServices.Protocols.SearchScope.Subtree, attributesToReturn); // Buscar al objeto NextFreeUnixId
SearchResponse searchResponse = (SearchResponse)openLdap.SendRequest(searchRequest); // Respuesta del servidor
// Manejar la respuesta
DirectoryAttribute atributo = searchResponse.Entries[0].Attributes["uidNumber"];
object[] objeto = atributo.GetValues(Type.GetType("System.Byte[]"));
uid = Encoding.ASCII.GetString((byte[])objeto[0]);
int siguienteuid = Int32.Parse(uid) + 1; // Actualizar el Unix Id libre
ModifyRequest incremento = new ModifyRequest("cn=NextFreeUnixId,dc=ic-itcr,dc=ac,dc=cr"
, DirectoryAttributeOperation.Replace, "uidNumber", siguienteuid.ToString()); // Modificar el NextFreeUnixId en el servidor
openLdap.SendRequest(incremento);
openLdap.Dispose();
return uid; // Retornar el uid
}