public string FindUser(string userName) { string rvUserName = null; using (var localDirectory = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries users = localDirectory.Children; try { using (DirectoryEntry user = users.Find(userName)) { if (user != null) { rvUserName = user.Name; } } } catch (COMException ex) { // Exception indicates the requested item could not be found, in which case we should return the default value if ((uint)ex.ErrorCode != COM_EXCEPT_UNKNOWN_DIRECTORY_OBJECT) { throw; } } } return(rvUserName); }
// Ref http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentries.remove(v=vs.110).aspx private static bool RemoveAutoUserFromCM(string usernametoremove, string machineName) { // Split out the userName var userName = usernametoremove.Split('_')[1]; DirectoryEntry AD = new DirectoryEntry("WinNT://" + machineName + ",computer"); DirectoryEntries daChildren = AD.Children; var userToRemove = daChildren.Find(userName, "User"); try { daChildren.Remove(userToRemove); //Do Something with --> ex.Message.ToString(); Log.Success(string.Format("User {0} removed successfully.", userName)); return(true); } catch (System.DirectoryServices.DirectoryServicesCOMException ex) { //Do Something with --> ex.Message.ToString(); Log.Error(string.Format("Unable to remove \"{0}\" from CM, Error:{1}", userName, ex.Message)); return(false); } finally { if (null != AD) { AD.Dispose(); } } }
static void Main() { try { String strPath = "IIS://localhost/W3SVC/1/Root"; String strName = ""; // Create a new 'DirectoryEntry' with the given path. DirectoryEntry myDE = new DirectoryEntry(strPath); DirectoryEntries myEntries = myDE.Children; // Create a new entry 'Sample' in the container. DirectoryEntry myDirectoryEntry = myEntries.Add("Sample", myDE.SchemaClassName); // Save changes of entry in the 'Active Directory'. myDirectoryEntry.CommitChanges(); Console.WriteLine(myDirectoryEntry.Name + " entry is created in container."); // Find 'Sample' entry in container. myDirectoryEntry = myEntries.Find("Sample", myDE.SchemaClassName); Console.WriteLine(myDirectoryEntry.Name + " found in container."); // Remove 'Sample' entry from container. strName = myDirectoryEntry.Name; myEntries.Remove(myDirectoryEntry); Console.WriteLine(strName + " entry is removed from container."); } catch (Exception e) { Console.WriteLine("The following exception was raised : {0}", e.Message); } }
/// <summary> /// 添加一个用户 /// </summary> /// <param name="userName"></param> /// <param name="password"></param> public bool NewSysUser(string userName, string password) { string EntryPath = String.Format("WinNT://{0}", this.HOSTNAME); DirectoryEntry obDirEntry = this.GetDirectoryEntry(EntryPath); DirectoryEntries users = obDirEntry.Children; try { DirectoryEntry user = users.Add(userName, "user"); user.Invoke("Put", new string[] { "Description", "IIS网站独立用户" }); user.Invoke("Put", "UserFlags", 66049); //密码永不过期 //user.Invoke("Put", "PasswordExpired", -1); //密码永不过期 user.CommitChanges(); user.Invoke("SetPassword", password); DirectoryEntry grp = users.Find("Users", "group"); if (grp.Name != "") { //grp.Invoke("Add", user.Path);//将用户添加到某组 } return(true); } catch (Exception ex) { return(false); } }
public void CreateLocalGroup(string groupName) { using (var localDirectory = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries children = localDirectory.Children; try { using (DirectoryEntry group = children.Find(groupName, "group")) { if (group != null) { return; } } } catch (COMException) { // Couldn't find group. } var newGroup = children.Add(groupName, "group"); newGroup.CommitChanges(); } }
/// <summary> /// Creates a local machine account. The account is not created if it already exists. /// </summary> /// /// <param name="loginName">The login name, e.g. "SlkLearner123". The name may start with /// ".\", indicating that it's a local machine account.</param> /// /// <param name="fullName">The full name, e.g. "SLK Sample Learner 123". Not used if the /// account already exists.</param> /// /// <param name="password">The password for the new account. Not used if the account already /// exists.</param> /// static void CreateUser(string loginName, string fullName, string password) { // add the user as a local user of this computer; set <existed> to true if the user // already existed Console.WriteLine("Finding or creating user account \"{0}\"", loginName); if (loginName.StartsWith(@".\")) { loginName = loginName.Substring(2); } DirectoryEntry user; bool existed; try { user = s_computerChildren.Find(loginName, "user"); existed = true; Console.WriteLine("...exists already"); } catch (COMException) { user = s_computerChildren.Add(loginName, "user"); existed = false; } using (user) { // if the user didn't exist, set up their account if (!existed) { // set properties of the user user.Invoke("SetPassword", new object[] { password }); user.Invoke("Put", new object[] { "FullName", fullName }); user.Invoke("Put", new object[] { "Description", "* Created by SharePoint Learning Kit sample code *" }); user.CommitChanges(); // add the user to the Guests group try { s_guests.Invoke("Add", new object[] { user.Path }); } catch (TargetInvocationException) { // probably the user is already a member of the group } } #if false // add the user to SharePoint string domainName = String.Format(@"{0}\{1}", s_parentWeb.Site.HostName, loginName); s_parentWeb.SiteUsers.Add(domainName, String.Empty, fullName, String.Empty); #endif } if (!existed) { Console.WriteLine("...created"); } }
static void SetNewPassword(string User, string NewPassword) { DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString()); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(User); user.Invoke("SetPassword", NewPassword); }
public static void ChangePassword(string passedName, string pass) { DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(passedName); user.Password = pass; }
public static void DeleteUser(string passedName) { DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(passedName); users.Remove(user); }
static void Main(string[] args) { int delcount = 0; Boolean ignore = false; Boolean sys = false; string name = null; string[] ignoreList = { "guest", "wdagutilityaccount" }; string sPath = "WinNT://" + Environment.MachineName + ",computer"; DirectoryEntry localDirectory = new DirectoryEntry(sPath); using (var computerEntry = localDirectory) foreach (DirectoryEntry childEntry in computerEntry.Children) { if (childEntry.SchemaClassName == "User") { name = childEntry.Name; ignore = false; sys = false; for (int i = 0; i < ignoreList.Length; i++) { if (name.ToLower().Equals(ignoreList[i])) { ignore = true; i = ignoreList.Length + 5; } } if (!ignore) { object obGroups = childEntry.Invoke("Groups"); foreach (object ob in (System.Collections.IEnumerable)obGroups) { DirectoryEntry obGpEntry = new DirectoryEntry(ob); if (obGpEntry.Name.ToLower().Equals("administrators") || obGpEntry.Name.ToLower().Equals("system managed accounts group")) { sys = true; } obGpEntry.Close(); } if (!sys) { try { DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(name); users.Remove(user); delcount++; } catch (Exception err) { Console.WriteLine(err.ToString()); } } } } } Console.WriteLine("\t " + delcount + "Users Deleted"); }
/// <summary> /// Change a local user password /// </summary> /// <param name="username">The target user</param> /// <param name="newPassword">The new password</param> public static void ChangeUserPassword(string username, string newPassword) { var path = $"WinNT://{Environment.MachineName},computer"; DirectoryEntry localDirectory = new DirectoryEntry(path); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(username); user.Invoke("SetPassword", newPassword); }
/// <summary> /// Creates a local machine account with a randomly-assigned password. The account is not /// created if it already exists. /// </summary> /// /// <param name="loginName">The login name, e.g. "SlkLearner123".</param> /// /// <param name="fullName">The full name, e.g. "SLK Sample Learner 123".</param> /// static void CreateUser(string loginName, string fullName) { // add the user as a local user of this computer; set <existed> to true if the user // already existed Console.WriteLine("Finding or creating user account: {0}", loginName); DirectoryEntry user; bool existed; try { user = s_computerChildren.Find(loginName, "user"); existed = true; Console.WriteLine("...exists already"); } catch (COMException) { user = s_computerChildren.Add(loginName, "user"); existed = false; } using (user) { // if the user didn't exist, set up their account if (!existed) { // set properties of the user byte[] passwordBytes = new byte[30]; s_secureRandomNumberGenerator.GetNonZeroBytes(passwordBytes); string password = Convert.ToBase64String(passwordBytes); user.Invoke("SetPassword", new object[] { password }); user.Invoke("Put", new object[] { "FullName", fullName }); user.Invoke("Put", new object[] { "Description", "* Created by SharePoint Learning Kit sample code *" }); user.CommitChanges(); // add the user to the Guests group try { s_guests.Invoke("Add", new object[] { user.Path }); } catch (TargetInvocationException) { // probably the user is already a member of the group } } // add the user to SharePoint string domainName = String.Format(@"{0}\{1}", s_parentWeb.Site.HostName, loginName); s_parentWeb.SiteUsers.Add(domainName, String.Empty, fullName, String.Empty); } if (!existed) { Console.WriteLine("...created"); } }
private static void RemoveLocalUser(string username) { string dir = $"C:\\Users\\{username}"; DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString()); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find($"{username}"); users.Remove(user); //remove the user account from the pc DelDir(dir); }
/// <summary> /// Deletes the group. /// </summary> /// <param name="groupName">Name of the group.</param> public static void DeleteGroup(string groupName) { using (DirectoryEntry localEntry = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries localChildren = localEntry.Children; using (DirectoryEntry groupEntry = localChildren.Find(groupName, "Group")) { localChildren.Remove(groupEntry); } } }
/// <summary> /// Deletes a windows user based on an Id. /// </summary> /// <param name="id">The id that was used to create the user.</param> public static void DeleteUser(string id) { string decoratedUsername = DecorateUser(id); using (DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString())) { DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find(decoratedUsername); users.Remove(user); } }
/// <summary> /// Deletes the user. /// </summary> /// <param name="userName">Name of the user.</param> public static void DeleteUser(string userName) { using (DirectoryEntry localEntry = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries localChildren = localEntry.Children; using (DirectoryEntry userEntry = localChildren.Find(userName, "User")) { localChildren.Remove(userEntry); } } }
public void DeleteUser(string userName) { using (var localDirectory = new DirectoryEntry(directoryPath)) { DirectoryEntries users = localDirectory.Children; using (DirectoryEntry user = users.Find(userName)) { users.Remove(user); } } }
public void DeleteLocalGroup(string groupName) { using (var localDirectory = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries children = localDirectory.Children; using (DirectoryEntry group = children.Find(groupName, "group")) { children.Remove(group); } } }
public static void Main() { DirectoryEntry de = new DirectoryEntry( "LDAP://192.168.1.100/ou=auditing, ou=accounting, dc=ispnet1, dc=net", "cn=Administrator, dc=ispnet1, dc=net", "password", AuthenticationTypes.ServerBind); DirectoryEntries des = de.Children; DirectoryEntry badObject = des.Find("cn=test"); badObject.Rename("cn=testing"); de.CommitChanges(); de.Close(); }
public string FindUser(string userName) { string rvUserName = null; using (var localDirectory = new DirectoryEntry(directoryPath)) { DirectoryEntries users = localDirectory.Children; using (DirectoryEntry user = users.Find(userName)) { if (user != null) { rvUserName = user.Name; } } } return(rvUserName); }
public void Execute(IActivityRequest request, IActivityResponse response) { String userName = String.Empty; String computerName = String.Empty; userName = request.Inputs["User Name"].AsString(); computerName = request.Inputs["Computer Name"].AsString(); String aUserName = String.Empty; String aUserDomain = String.Empty; String aUserPassword = String.Empty; if (request.Inputs.Contains("Alternate Connection Username")) { aUserName = request.Inputs["Alternate Connection Username"].AsString(); } if (request.Inputs.Contains("Alternate Connection User Domain")) { aUserDomain = request.Inputs["Alternate Connection User Domain"].AsString(); } if (request.Inputs.Contains("Alternate Connection Password")) { aUserPassword = request.Inputs["Alternate Connection Password"].AsString(); } DirectoryEntry machine; if (aUserName.Equals(String.Empty) || aUserDomain.Equals(String.Empty) || aUserPassword.Equals(String.Empty)) { machine = new DirectoryEntry("WinNT://" + computerName); } else { machine = new DirectoryEntry("WinNT://" + computerName, string.Format("{0}@{1}", aUserName, aUserDomain), aUserPassword); } DirectoryEntries entries = machine.Children; DirectoryEntry user = entries.Find(userName); entries.Remove(user); machine.Close(); response.Publish("User Name", userName); }
/// <summary>查找某个组织单位下面的所有人员</summary> /// <param name="fullName">组织单位的显名,例如:OU=微软创新中心,OU=合作伙伴,OU=组织结构</param> /// <returns></returns> public SearchResultCollection FindAll(string fullName) { if (this.integratedMode == "OFF") { return(null); } DirectoryEntries nodes = this.directoryEntry.Children; directorySearcher.SearchRoot = nodes.Find(fullName); directorySearcher.PageSize = int.MaxValue; // 此参数可以任意设置,但不能不设置,如不设置读取AD数据为0-999条数据,设置后可以读取大于1000条数据. //directorySearcher.SizeLimit = 10000; directorySearcher.Filter = "(objectClass=user)"; directorySearcher.SearchScope = SearchScope.Subtree; directorySearcher.Sort = new SortOption("sAMAccountName", SortDirection.Ascending); return(directorySearcher.FindAll()); }
private static string DeleteUser(string userName) { DirectoryEntry user; DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries users = localMachine.Children; try { user = users.Find(userName); } catch (Exception erMess) { return("User not found!"); } users.Remove(user); return("User Delete!"); }
public void removeLocalUser(string name) { try { string user_name = name; DirectoryEntry local_computer_path = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries users = local_computer_path.Children; DirectoryEntry existing_user = users.Find(user_name); users.Remove(existing_user); Console.WriteLine("\nUSER REMOVED SUCCESSFULLY"); } catch (Exception exception_log) { Console.Clear(); Console.Write("=======================================================================================================================\n"); Console.WriteLine(exception_log.ToString() + "\n"); Console.Write("=======================================================================================================================\n"); Console.WriteLine("USER DOES NOT EXIST - OPERATION FAILED"); Thread.Sleep(5000); } }
private void button3_Click(object sender, EventArgs e) { try { if (lstUsers.SelectedItem == null) { return; } string username = lstUsers.SelectedItem.ToString(); DirectoryEntry host = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries entries = host.Children; DirectoryEntry user = entries.Find(username); entries.Remove(user); MessageBox.Show("User deleted"); button1.PerformClick(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public static void Main() { DirectoryEntry de = new DirectoryEntry( "LDAP://192.168.1.100/ou=accounting, dc=ispnet1, dc=net", "cn=Administrator, dc=ispnet1, dc=net", "password", AuthenticationTypes.ServerBind); DirectoryEntries children = de.Children; try { DirectoryEntry badObject = children.Find("ou=auditing"); badObject.DeleteTree(); de.CommitChanges(); Console.WriteLine("the object has been deleted"); } catch (Exception e) { Console.WriteLine("the object was not found or deleted:"); Console.WriteLine(e.ToString()); } }
private void AssertUserInGroup(string groupName, string userName) { using (var localDirectory = new DirectoryEntry("WinNT://.,Computer")) { DirectoryEntries children = localDirectory.Children; DirectoryEntry group = children.Find(groupName); var groupChildren = group.Invoke("Members", null) as IEnumerable; DirectoryEntry user = null; foreach (var child in groupChildren) { DirectoryEntry de = new DirectoryEntry(child); if (de.Name == userName) { user = de; } } Assert.NotNull(user); } }
public void ChangeD2UserPassword() { //Generating new password string newPassword = Guid.NewGuid().ToString(); newPassword = newPassword.Replace("-", ""); Random random = new Random(DateTime.Now.Millisecond); newPassword = newPassword.Remove(random.Next(8, 31)); //Creating temporary Lgn string fileName = (new D2PathHelper()).GetD2Path() + @"_Lgn" + IpAddress + ".dat"; try { int retCode = CreateLgnFile(fileName, newPassword); if (retCode != 0) { Logger?.LogTextMessage("CreateLgnFile returns " + retCode); } } catch (Exception exception) { Logger?.LogTextMessage("Exception while calling CreateLgnFile: " + exception.Message); return; } //Change password for D2_User in Windows try { DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries users = localDirectory.Children; DirectoryEntry user = users.Find("D2_User"); user.Invoke("SetPassword", newPassword); } catch (Exception exception) { Logger?.LogTextMessage("Exception while invoking SetPassword: "******"\nStack:" + exception.StackTrace); return; } //Renaming file if password changed successfully string newFileName = (new D2PathHelper()).GetD2Path() + @"Lgn" + IpAddress + ".dat"; try { if (File.Exists(newFileName)) { File.Delete(newFileName); } File.Move(fileName, newFileName); } catch (Exception exception) { Logger?.LogTextMessage("Exception while renaming Lgn-file: " + exception.Message); return; } //Notifying clients D2UserService.NotifyAllSubscribers(); }
static void Main(string[] args) { Console.WriteLine("----------FIREWALL-----------"); #region firewall SetFirewallRule("Remote Assistance (DCOM-In)", false); SetFirewallRule("Remote Assistance (PNRP-In)", false); SetFirewallRule("Remote Assistance (RA Server TCP-In)", false); SetFirewallRule("Remote Assistance (SSDP TCP-In)", false); SetFirewallRule("Remote Assistance (SSDP UDP-In)", false); SetFirewallRule("Remote Assistance (TCP-In)", false); SetFirewallRule("Telnet Server", false); SetFirewallRule("netcat", false); #endregion Console.WriteLine("----------REGISTRIES-----------"); #region reg { string[] lines = File.ReadAllLines(@"regkeys.txt"); foreach (var line in lines) { string[] words = Regex.Split(line, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)"); SetRegistry(words[0].Replace("\"", ""), words[1], words[2], words[3]); } } #endregion #region features { string[] lines = File.ReadAllLines(@"features.txt"); foreach (var line in lines) { Console.WriteLine("Disabling " + line); //ExecuteCommand("dism /online /disable-feature /featurename:" + line); } } #endregion Console.WriteLine("flushing dns"); ExecuteCommand("ipconfig /flushdns"); Console.WriteLine("setting password age"); ExecuteCommand("net accounts /minpwlen:10"); ExecuteCommand("net accounts /minpwage:5"); ExecuteCommand("net accounts /maxpwage:30"); Console.WriteLine(@"Deleting media files in C:\Users"); Console.WriteLine("OWNING COMPUTER"); ExecuteCommand("icacls " + @"C:\Users" + " /setowner \"Administrators\" /T /C"); #region users { string[] admins = File.ReadAllLines(@"admins.txt"); string[] standards = File.ReadAllLines(@"standards.txt"); string[] combined = admins.Concat(standards).ToArray(); DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString()); DirectoryEntries users = localDirectory.Children; List <string> unauthorizedUsers = GetComputerUsers(); foreach (var userName in combined) { Console.WriteLine($"Found authorized user {userName}"); unauthorizedUsers.Remove(userName); } foreach (var unauthorizedUser in unauthorizedUsers) { try { Console.WriteLine($"Press enter to remove unauthorized user {unauthorizedUser}"); Console.ReadKey(); DirectoryEntry user = users.Find(unauthorizedUser); users.Remove(user); Console.WriteLine($"Removed unauthorized user {unauthorizedUser}"); } catch (Exception e) { Console.WriteLine($"failed to remove unauthorized user {unauthorizedUser}"); Console.WriteLine(e.ToString()); } } foreach (var userName in admins) { try { DirectoryEntry user = users.Find(userName); Console.WriteLine($"Found admin {userName}"); } catch { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add(userName, "user"); NewUser.Invoke("SetPassword", new object[] { "Exploratory123$" }); NewUser.Invoke("Put", new object[] { "Description", "admin user added by script" }); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Administrators", "group"); if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } Console.WriteLine($"Admin account {userName} Created Successfully"); Console.WriteLine($"Password: Exploratory123$"); } } foreach (var userName in standards) { try { DirectoryEntry user = users.Find(userName); Console.WriteLine($"Found standard user {userName}"); } catch { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add(userName, "user"); NewUser.Invoke("SetPassword", new object[] { "Exploratory123$" }); NewUser.Invoke("Put", new object[] { "Description", "standard user added by script" }); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Users", "group"); if (grp != null) { grp.Invoke("Add", new object[] { NewUser.Path.ToString() }); } Console.WriteLine($"Standard account {userName} Created Successfully"); Console.WriteLine($"Password: Exploratory123$"); } } } #endregion Console.ReadKey(); }
private void Grabar() { bool bErrorControlado = false; ArrayList aListCorreo = new ArrayList(); string sAsunto = ""; string sTexto = ""; string sTO = ""; string strFecIniOld = ""; string strFecFinOld = ""; string strInteresadoOld = ""; string strEmpresaOld = ""; string sUsuario = "", sPassword = ""; if (this.hdnIDReserva.Text != "") { //Si se trata de una reserva existente, se obtienen sus datos //para luego comunicar las modificaciones realizadas. WIFI oWifi = WIFI.Obtener(null, int.Parse(this.hdnIDReserva.Text)); strFecIniOld = oWifi.t085_fechoraini.ToString(); strFecFinOld = oWifi.t085_fechorafin.ToString(); strInteresadoOld = oWifi.t085_interesado; strEmpresaOld = oWifi.t085_empresa; if (strFecIniOld.Length == 19) { strFecIniOld = strFecIniOld.Substring(0, 16); } else { strFecIniOld = strFecIniOld.Substring(0, 15); } if (strFecFinOld.Length == 19) { strFecFinOld = strFecFinOld.Substring(0, 16); } else { strFecFinOld = strFecFinOld.Substring(0, 15); } } SqlConnection oConn = Conexion.Abrir(); SqlTransaction tr = Conexion.AbrirTransaccion(oConn); DateTime dInicio = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue); DateTime dFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue); DateTime dNow = DateTime.Now; try { if (this.hdnIDReserva.Text == "") //insert { #region Código Insert sEsInsert = "true"; string sTicks = DateTime.Now.Ticks.ToString(); //string sTicksReducida = sTicks.Substring(10, 8); //sUsuario = "IB" + EncodeTo64(sTicksReducida).Substring(0, 6).ToUpper(); //sPassword = EncodeTo64((int.Parse(sTicksReducida) + ((int)Session["CR2I_IDFICEPI"] * int.Parse(sTicksReducida))).ToString()); //sPassword = sPassword.Substring(sPassword.Length - 10, 8); sPassword = sTicks.Substring(sTicks.Length - 4, 4); //sUsuario = "ib" + sTicksReducida; //sPassword = (int.Parse(sTicks.Substring(0, 8)) * (int)Session["CR2I_IDFICEPI"]).ToString().Substring(0, 8); //sPassword = (long.Parse(sTicks.Substring(sTicks.Length - 8, 8)) * long.Parse(Session["CR2I_IDFICEPI"].ToString())).ToString(); //sPassword = sPassword.Substring(sPassword.Length-8, 8); //Datos de la reserva byte nEstado = 1; if (dInicio < dNow && dFin > dNow) { nEstado = 2; } int nResul = WIFI.Insert(tr, (int)Session["CR2I_IDFICEPI"], txtInteresado.Text, txtEmpresa.Text, dInicio, dFin, txtObservaciones.Text, nEstado, sPassword); sUsuario = "ib" + nResul.ToString().Substring(nResul.ToString().Length - 4, 4); txtUsuario.Text = sUsuario; txtPwd.Text = sPassword; try { if (dInicio < dNow && dFin > dNow) {//hay que crear la reserva directamente en el LDAP DirectoryEntry de = new DirectoryEntry("LDAP://172.20.254.150:389/ou=people,dc=visitas,dc=ib", "cn=vadmin,dc=visitas,dc=ib", "PruebaLDAP", AuthenticationTypes.FastBind); DirectoryEntries entries = de.Children; DirectoryEntry oUser = entries.Add("cn=" + sUsuario, "inetOrgPerson"); //oUser.Properties["dn"].Add("cn=" + sUsuario + ",ou=people,dc=visitas,dc=ib"); oUser.Properties["objectClass"].Add("inetOrgPerson"); oUser.Properties["cn"].Add(sUsuario); oUser.Properties["sn"].Add(sUsuario); oUser.Properties["uid"].Add(sUsuario); oUser.Properties["userpassword"].Add(sPassword); oUser.Properties["ou"].Add("Visitas"); oUser.CommitChanges(); //DirectoryEntry oUserDelete = entries.Find("cn=" + sUsuario, "inetOrgPerson"); //entries.Remove(oUserDelete); //generar error //DirectoryEntry oUserDeletex = entries.Find("cn=x" + sUsuario, "inetOrgPerson"); } } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } catch (Exception ex) { sErrores = "Error : " + ex.Message; } hdnIDReserva.Text = nResul.ToString(); sTO = Session["CR2I_IDRED"].ToString(); sAsunto = "Reserva WIFI"; string sFecIni = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue).ToString(); if (sFecIni.Length == 19) { sFecIni = sFecIni.Substring(0, 16); } else { sFecIni = sFecIni.Substring(0, 15); } string sFecFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue).ToString(); if (sFecFin.Length == 19) { sFecFin = sFecFin.Substring(0, 16); } else { sFecFin = sFecFin.Substring(0, 15); } sTexto = "<p style='font-size:12px'>" + this.txtSolicitante.Text + @" ha solicitado una reserva WIFI para <b>" + this.txtInteresado.Text + @"</b><br /><br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + sFecIni + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + sFecFin + @"<br /><br /> <span style='width:150px'><b>Usuario:</b></span> " + txtUsuario.Text + @"<br /> <span style='width:150px'><b>Contraseña:</b></span> " + txtPwd.Text + @"<br /><br /> <span style='width:150px'><b>Observaciones:</b></span> " + txtObservaciones.Text.Replace(((char)10).ToString(), "<br />") + @"<br /><br /><br /><br /></p>"; string[] aMail = { sAsunto, sTexto, sTO, "", "I", "" }; aListCorreo.Add(aMail); #endregion } else //update { #region Código Update //Datos de la reserva WIFI oWifi = WIFI.Obtener(tr, int.Parse(hdnIDReserva.Text)); byte nEstado = oWifi.t085_estado; if (dInicio < dNow && dFin > dNow) { nEstado = 2; } WIFI.Actualizar(tr, int.Parse(hdnIDReserva.Text), (int)Session["CR2I_IDFICEPI"], txtInteresado.Text, txtEmpresa.Text, dInicio, dFin, txtObservaciones.Text, nEstado, txtPwd.Text); try { if (dInicio < dNow && dFin > dNow) { DirectoryEntry de = new DirectoryEntry("LDAP://172.20.254.150:389/ou=people,dc=visitas,dc=ib", "cn=vadmin,dc=visitas,dc=ib", "PruebaLDAP", AuthenticationTypes.FastBind); DirectoryEntries entries = de.Children; //1º Borrar la reserva WIFI que pudiera existir. try { DirectoryEntry oUserDelete = entries.Find("cn=" + txtUsuario.Text, "inetOrgPerson"); entries.Remove(oUserDelete); } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } //2º Hay que crear la reserva directamente en el LDAP DirectoryEntry oUser = entries.Add("cn=" + txtUsuario.Text, "inetOrgPerson"); //oUser.Properties["dn"].Add("cn=" + sUsuario + ",ou=people,dc=visitas,dc=ib"); oUser.Properties["objectClass"].Add("inetOrgPerson"); oUser.Properties["cn"].Add(txtUsuario.Text); oUser.Properties["sn"].Add(txtUsuario.Text); oUser.Properties["uid"].Add(txtUsuario.Text); oUser.Properties["userpassword"].Add(txtPwd.Text); oUser.Properties["ou"].Add("Visitas"); oUser.CommitChanges(); } } catch (System.Runtime.InteropServices.COMException) { //string s = ""; //No existe o no se ha encontrado el usuario } catch (Exception ex) { sErrores = "Error : " + ex.Message; } sTO = Session["CR2I_IDRED"].ToString(); sAsunto = "Modificación reserva WIFI."; string sFecIni = Fechas.crearDateTime(this.txtFechaIni.Text, this.cboHoraIni.SelectedValue).ToString(); if (sFecIni.Length == 19) { sFecIni = sFecIni.Substring(0, 16); } else { sFecIni = sFecIni.Substring(0, 15); } string sFecFin = Fechas.crearDateTime(this.txtFechaFin.Text, this.cboHoraFin.SelectedValue).ToString(); if (sFecFin.Length == 19) { sFecFin = sFecFin.Substring(0, 16); } else { sFecFin = sFecFin.Substring(0, 15); } sTexto = @"<p style='font-size:12px'>La reserva WIFI <br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + strFecIniOld + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + strFecFinOld + @"<br /><br /> <span style='width:150px'><b>Interesado:</b></span> " + strInteresadoOld + @"<br /> <br />Ha sido modificada por " + Session["CR2I_APELLIDO1"].ToString() + @" " + Session["CR2I_APELLIDO2"].ToString() + @", " + Session["CR2I_NOMBRE"].ToString() + @" y se reservará <br /><br /> <span style='width:150px'><b>Inicio:</b></span> " + sFecIni + @"<br /> <span style='width:150px'><b>Fin:</b></span> " + sFecFin + @"<br /><br /> <span style='width:150px'><b>Interesado:</b></span> " + txtInteresado.Text + @"<br /><br /> <span style='width:150px'><b>Usuario:</b></span> " + txtUsuario.Text + @"<br /> <span style='width:150px'><b>Contraseña:</b></span> " + txtPwd.Text + @"<br /><br /><br /><br /></p>"; string[] aMail = { sAsunto, sTexto, sTO, "", "I", "" }; aListCorreo.Add(aMail); #endregion } Conexion.CommitTransaccion(tr); sResultadoGrabacion = "OK"; } catch (Exception ex) { if (!bErrorControlado) { sErrores += Errores.mostrarError("Error al realizar la reserva:", ex); } else { sErrores = ex.Message; } Conexion.CerrarTransaccion(tr); } finally { Conexion.Cerrar(oConn); } try { Correo.EnviarCorreos(aListCorreo); } catch (Exception ex) { sErrores += Errores.mostrarError("Error al enviar los mails de convocatoria:", ex); } }