/// <summary> /// Creates a new user account /// </summary> /// <param name="name">User login name</param> /// <param name="password">User password</param> /// <param name="fullName">User full name</param> /// <param name="isAdmin">flag as admin</param> /// <returns>returns true when user is successfully created</returns> public static bool Create(string name, string password, string fullName = "", bool isAdmin = false) { try { var dirEntry = new DirectoryEntry("WinNT://localhost"); DirectoryEntries entries = dirEntry.Children; DirectoryEntry newUser = entries.Add(name, "user"); newUser.Properties["FullName"].Add(fullName); newUser.Invoke("SetPassword", password); newUser.CommitChanges(); // Remove the if condition along with the else to create user account in "user" group. DirectoryEntry grp; grp = dirEntry.Children.Find(UserGroup, "group"); grp.Invoke("Add", new object[] { newUser.Path }); if (isAdmin) { grp = dirEntry.Children.Find(AdminGroup, "group"); grp.Invoke("Add", new object[] { newUser.Path }); } } catch (Exception ex) { Logger.Instance.WriteGlobal("Failed to add new user: {0}", name); DebugHelper.Exception(ex); return(false); } return((isAdmin && ExistsAsAdmin(name)) || (Exists(name))); }
private static void CreateVirtualDirectoryIfAny(string metabasePath, string vDirName, string physicalPath) { try { DirectoryEntry service = new DirectoryEntry(metabasePath); // Check if the virtual directory already exists DirectoryEntry matchingVDir = service.Children.Cast <DirectoryEntry>().Where(v => v.Name == vDirName).SingleOrDefault(); if (matchingVDir != null) { return; } string scName = service.SchemaClassName; if (scName.EndsWith(DirectoryService.ADDS_NODETYPE_SERVER) || scName.EndsWith(DirectoryService.ADDS_NODETYPE_COMPUTER) || scName.EndsWith(DirectoryService.ADDS_NODETYPE_VIRTUALDIR)) { DirectoryEntries vDirs = service.Children; DirectoryEntry vDir = vDirs.Add(vDirName, DirectoryService.ADDS_SCHEMA_IISWEBVIRTUALDIR); vDir.Properties["Path"][0] = physicalPath; vDir.Properties["AppFriendlyName"][0] = vDirName; vDir.Properties["EnableDirBrowsing"][0] = false; vDir.Properties["AccessRead"][0] = true; vDir.Properties["AccessWrite"][0] = false; vDir.Properties["AccessScript"][0] = true; vDir.Properties["AppIsolated"][0] = "1"; vDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", DirectoryService.ADDS_PROTOCOL_IIS.Length)); vDir.CommitChanges(); vDir.Invoke("AppCreate", 1); } } catch (Exception ex) { throw new DsUpdateException(ex.Message + "\nmetabasePath: " + metabasePath + ", Virtual Dir: " + vDirName + ", physical Path: " + physicalPath, ex); } }
/* * SetPassword' requires admin rights to execute - which is not something you probably want to do. * 'ChangePassword' does not and can be used by the end user themselves. * It takes the old password and new password as arguments (do a search in this forum for 'ChangePassword' to see examples). * This would be the preferred way of executing this and it would also verify their identity for you without a database * lookup (or at least verify that the user knows their old password). */ public void CreateUserAccount(string login, string password, string fullName, bool isAdmin) { try { DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries entries = dirEntry.Children; DirectoryEntry newUser = entries.Add(login, "user"); newUser.Properties["FullName"].Add(fullName); newUser.Invoke("SetPassword", password); newUser.CommitChanges(); // Remove the if condition along with the else to create user account in "user" group. DirectoryEntry grp; if (isAdmin) { grp = dirEntry.Children.Find("Administrators", "group"); if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); } } else { grp = dirEntry.Children.Find("Guests", "group"); if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
/* * SetPassword' requires admin rights to execute - which is not something you probably want to do. * 'ChangePassword' does not and can be used by the end user themselves. * It takes the old password and new password as arguments (do a search in this forum for 'ChangePassword' to see examples). * This would be the preferred way of executing this and it would also verify their identity for you without a database * lookup (or at least verify that the user knows their old password). */ public static void CreateUserAccount(string login, string password, string fullName, string groupName, string description) { DirectoryEntry dirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName); DirectoryEntries entries = dirEntry.Children; DirectoryEntry newUser = entries.Add(login, "user"); newUser.Properties["FullName"].Add(fullName); if (description != null) { newUser.Properties["Description"].Add(description); } newUser.Invoke("SetPassword", password); newUser.CommitChanges(); if (groupName == null) { groupName = "Guests"; } DirectoryEntry grp = dirEntry.Children.Find(groupName, "group"); //DirectoryEntry grp = new DirectoryEntry("WinNT://" + Environment.MachineName + "/" + groupName); if (grp != null) { grp.Invoke("Add", new object[] { newUser.Path.ToString() }); } grp.CommitChanges(); }
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(); } }
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); } }
private DirectoryEntry AddGroup(string Name, string DisplayName, string DistinguishedName, string Description) { string RootDSE; System.DirectoryServices.DirectorySearcher DSESearcher = new System.DirectoryServices.DirectorySearcher(); try { RootDSE = DSESearcher.SearchRoot.Path; RootDSE = RootDSE.Insert(7, Utility.ADUsersPath); System.DirectoryServices.DirectoryEntry myDE = new DirectoryEntry(RootDSE); DirectoryEntries myEntries = myDE.Children; System.DirectoryServices.DirectoryEntry myDirectoryEntry = myEntries.Add("CN=" + Name, "Group"); Utility.SetProperty(myDirectoryEntry, "cn", Name); Utility.SetProperty(myDirectoryEntry, "DisplayName", DisplayName); Utility.SetProperty(myDirectoryEntry, "Description", Description); Utility.SetProperty(myDirectoryEntry, "sAMAccountName", Name); Utility.SetProperty(myDirectoryEntry, "groupType", System.Convert.ToString(Utility.GroupScope.ADS_GROUP_TYPE_GLOBAL_GROUP)); myDirectoryEntry.CommitChanges(); myDirectoryEntry = Utility.GetGroup(Name); return(myDirectoryEntry); } catch (Exception ex) { throw (ex); } }
public static void CreateVDir(string metabasePath, string vDirName, string physicalPath) { // metabasePath is of the form "IIS://<servername>/<service>/<siteID>/Root[/<vdir>]" // for example "IIS://localhost/W3SVC/1/Root" // vDirName is of the form "<name>", for example, "MyNewVDir" // physicalPath is of the form "<drive>:\<path>", for example, "C:\Inetpub\Wwwroot" DirectoryEntry site = new DirectoryEntry(metabasePath); string className = site.SchemaClassName.ToString(); if ((className.EndsWith("Server", StringComparison.OrdinalIgnoreCase)) || (className.EndsWith("VirtualDir", StringComparison.OrdinalIgnoreCase))) { DirectoryEntries vdirs = site.Children; DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir"))); newVDir.Properties["Path"][0] = physicalPath; newVDir.Properties["AccessScript"][0] = true; // These properties are necessary for an application to be created. newVDir.Properties["AppFriendlyName"][0] = vDirName; newVDir.Properties["AppIsolated"][0] = "1"; newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length))); newVDir.CommitChanges(); } else { throw new Exception(" Failed. A virtual directory can only be created in a site or virtual directory node."); } }
public bool CreateSubVirtualDir(string vDirName, string physicalPath) { try { string metabase = "IIS://" + _serverName + "/w3svc/" + GetWebSiteId() + "/root"; using (DirectoryEntry site = new DirectoryEntry(metabase)) { string className = site.SchemaClassName.ToString(); if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir"))) { DirectoryEntries vdirs = site.Children; DirectoryEntry newVDir = vdirs.Add(vDirName, (className.Replace("Service", "VirtualDir"))); newVDir.Properties["Path"][0] = physicalPath; newVDir.Properties["AccessScript"][0] = true; // These properties are necessary for an application to be created. newVDir.Properties["AppFriendlyName"][0] = vDirName; newVDir.Properties["AppIsolated"][0] = "1"; newVDir.Properties["AppRoot"][0] = "/LM" + metabase.Substring(metabase.IndexOf("/", ("IIS://".Length))); newVDir.CommitChanges(); return(true); } else { return(false); } } } catch (Exception ex) { return(false); } }
/// <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"); } }
/// <summary> /// Gets the distinguishedName (LDAP notation locator) of the specified user. /// </summary> /// <param name="samAccountName">The sam account name of the user to retrieve the distinguishedName for. Exclude the domain.</param> /// <param name="reload">If set to <c>true</c> reload the properties of the specified user.</param> /// <param name="throwIfNotFound">If set to <c>true</c> throw an InvalidOperationException if the specified user is not found.</param> /// <param name="entry"></param> /// <returns></returns> /// <exception cref="System.InvalidOperationException"></exception> public string GetDistinguishedName(string samAccountName, out DirectoryEntry entry, bool reload = false, bool throwIfNotFound = false) { entry = null; if (!SearchResults.ContainsKey(samAccountName)) { SearchResults.Add(samAccountName, new Dictionary <string, string>()); DirectoryEntries.Add(samAccountName, null); } if (!SearchResults[samAccountName].ContainsKey(DistinguishedName) || reload) { using (DirectorySearcher searcher = GetDirectoryRootSearcher()) { searcher.Filter = $"(sAMAccountName={samAccountName})"; SearchResult result = searcher.FindOne(); Dictionary <string, string> properties = new Dictionary <string, string>(); if (result != null) { entry = result.GetDirectoryEntry(); DirectoryEntries[samAccountName] = entry; FireEvent(UserFound, new ActiveDirectoryEventArgs { UserName = samAccountName, Server = Server }); ResultPropertyCollection fields = result.Properties; foreach (string field in fields.PropertyNames) { foreach (object collection in fields[field]) { if (!properties.ContainsKey(field)) { properties.Add(field, collection.ToString()); } else { properties[field] = collection.ToString(); } } } SearchResults[samAccountName] = properties; } else { FireEvent(UserNotFound); if (throwIfNotFound) { throw new InvalidOperationException($"User {samAccountName} not found"); } } } } if (SearchResults.ContainsKey(samAccountName) && SearchResults[samAccountName].ContainsKey(DistinguishedName)) { return(SearchResults[samAccountName][DistinguishedName]); } return(string.Empty); }
/// <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"); } }
/// <summary> /// Create a new user /// </summary> /// <param name="domain"></param> /// <param name="login"></param> private void NewUser(string domain, string login) { DirectoryEntry obDirEntry = new DirectoryEntry("WinNT://" + domain); DirectoryEntries entries = obDirEntry.Children; DirectoryEntry obUser = entries.Add(login, "User"); obUser.Properties["FullName"].Add(login); object obRet = obUser.Invoke("SetPassword", "1111111111111111111"); obUser.CommitChanges(); }
/// <summary> /// 检测密码是否符合密码策略 /// </summary> /// <param name="password"></param> /// <returns></returns> public bool CheckPasswordStrategy(string password) { try { if (this.integratedMode == "OFF") { return(true); } // // CN=PasswordStrategy // // (*)在 LDAP 中建一个PasswordStrategy帐号,专门用来检测密码是否符合当前的密码策略。 // DirectoryEntry param = Find("passwordstrategy"); string defaultPassword = "******"; if (param == null) { DirectoryEntries directoryEntries = directoryEntry.Children; param = directoryEntries.Add("CN=PasswordStrategy,CN=Users", LDAPSchemaClassType.User); param.Properties["name"].Add("PasswordStrategy"); param.Properties["givenName"].Add("PasswordStrategy"); param.Properties["displayname"].Add("PasswordStrategy"); param.Properties["userPrincipalName"].Add(string.Format("{0}{1}", "passwordstrategy", this.suffixEmailDomain)); param.Properties["samAccountName"].Add("PasswordStrategy"); param.Properties["accountexpires"].Add("0"); param.CommitChanges(); param.Invoke("SetPassword", new object[] { defaultPassword }); param.CommitChanges(); } param.Invoke("SetPassword", new object[] { password }); param.CommitChanges(); return(true); } catch (Exception ex) { logger.Error(this.directoryEntry.Path + "|" + this.directoryEntry.Username, ex); return(false); } }
/// <summary> /// 新建Security Group /// </summary> /// <param name="path"></param> public void CreateGroup(string name) { if (!ObjectExists(name, "Group")) { DirectoryEntry dse = GetDirectoryEntry(); DirectoryEntries Groups = dse.Children; DirectoryEntry newgroup = Groups.Add("CN=" + name, "group"); newgroup.CommitChanges(); newgroup.Close(); dse.Close(); } else { Console.WriteLine("用户组已存在"); } }
/// <summary> /// 新建OU /// </summary> /// <param name="path"></param> public void CreateOU(string name) { if (!ObjectExists(name, "OU")) { DirectoryEntry dse = GetDirectoryEntry(); DirectoryEntries ous = dse.Children; DirectoryEntry newou = ous.Add("OU=" + name, "OrganizationalUnit"); newou.CommitChanges(); newou.Close(); dse.Close(); } else { Console.WriteLine("OU已存在"); } }
private DirectoryEntry Add(string FirstName, string MiddleInitial, string LastName, string UserPrincipalName, string PostalAddress, string MailingAddress, string ResidentialAddress, string Title, string HomePhone, string OfficePhone, string Mobile, string Fax, string Email, string Url, string UserName, string Password, string DistinguishedName, bool IsAccountActive) { string RootDSE; System.DirectoryServices.DirectorySearcher DSESearcher = new System.DirectoryServices.DirectorySearcher(); try { RootDSE = DSESearcher.SearchRoot.Path; RootDSE = RootDSE.Insert(7, Utility.ADUsersPath); System.DirectoryServices.DirectoryEntry myDE = new DirectoryEntry(RootDSE); DirectoryEntries myEntries = myDE.Children; System.DirectoryServices.DirectoryEntry myDirectoryEntry = myEntries.Add("CN=" + UserName, "user"); Utility.SetProperty(myDirectoryEntry, "givenName", FirstName); Utility.SetProperty(myDirectoryEntry, "initials", MiddleInitial); Utility.SetProperty(myDirectoryEntry, "sn", LastName); if (UserPrincipalName != null) { Utility.SetProperty(myDirectoryEntry, "UserPrincipalName", UserPrincipalName); } else { Utility.SetProperty(myDirectoryEntry, "UserPrincipalName", UserName); } Utility.SetProperty(myDirectoryEntry, "PostalAddress", PostalAddress); Utility.SetProperty(myDirectoryEntry, "StreetAddress", MailingAddress); Utility.SetProperty(myDirectoryEntry, "HomePostalAddress", ResidentialAddress); Utility.SetProperty(myDirectoryEntry, "Title", Title); Utility.SetProperty(myDirectoryEntry, "HomePhone", HomePhone); Utility.SetProperty(myDirectoryEntry, "TelephoneNumber", OfficePhone); Utility.SetProperty(myDirectoryEntry, "Mobile", Mobile); Utility.SetProperty(myDirectoryEntry, "FacsimileTelephoneNumber", Fax); Utility.SetProperty(myDirectoryEntry, "mail", Email); Utility.SetProperty(myDirectoryEntry, "Url", Url); Utility.SetProperty(myDirectoryEntry, "sAMAccountName", UserName); Utility.SetProperty(myDirectoryEntry, "UserPassword", Password); myDirectoryEntry.Properties["userAccountControl"].Value = Utility.UserStatus.Enable; myDirectoryEntry.CommitChanges(); myDirectoryEntry = GetUser(UserName); Utility.SetUserPassword(myDirectoryEntry, Password); return(myDirectoryEntry); } catch (Exception ex) { throw (ex); } }
/// <summary></summary> /// <param name="loginName"></param> /// <param name="password"></param> /// <param name="name"></param> /// <param name="telephone"></param> /// <param name="email"></param> public void Add(string loginName, string password, string name, string telephone, string email) { if (this.integratedMode == "OFF") { return; } try { if (!IsExist(loginName, name)) { DirectoryEntries directoryEntries = directoryEntry.Children; DirectoryEntry param = directoryEntries.Add(string.Format("CN={0},OU={1}", name, this.directoryName), LDAPSchemaClassType.User); param.Properties["samAccountName"].Add(loginName); param.Properties["name"].Add(name); param.Properties["givenName"].Add(name); param.Properties["displayname"].Add(name); param.Properties["userPrincipalName"].Add(string.Format("{0}{1}", loginName, this.suffixEmailDomain)); // 这两段代码放在龙湖的AD服务器上, 会抛出异常.. // //item.Properties["telephoneNumber"].Add(telephone); //item.Properties["mail"].Add(email); param.Properties["accountexpires"].Add("0"); param.CommitChanges(); //设置帐号状态 param.Properties["userAccountControl"].Value = 66048; //66048 启用, 546 禁用, 密码永不过期标志为 0x10000 param.CommitChanges(); this.SetPassword(loginName, password); } } catch (Exception ex) { logger.Error(ex.Message, ex); throw; } }
public static int Main(string[] args) { DirectoryEntry MyObject = new DirectoryEntry(); MyObject.Path = "LDAP://HMSRevenge/OU=Users,DC=Test,DC=com"; DirectoryEntries users = MyObject.Children; DirectoryEntry NewUser = users.Add("Greg MacBeth", "user"); NewUser.Properties["company"].Add("Microsoft Corporation"); NewUser.Properties["employeeID"].Add("1001"); NewUser.Properties["userPassword"].Add("Password"); NewUser.CommitChanges(); return(0); }
public static DirectoryEntry CreateLocalAccount(string AccountName, string Password) { try { DirectoryEntry DirEntry = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntries DirEntries = DirEntry.Children; DirectoryEntry NewUser = DirEntries.Add(AccountName, "user"); NewUser.Properties["FullName"].Add(AccountName); NewUser.Invoke("SetPassword", Password); NewUser.CommitChanges(); return(NewUser); } catch (Exception ex) { throw; } }
/// <summary> /// Creates a user based on an id. The created user has a prefix added to it. /// </summary> /// <param name="id">An id for the username.</param> /// <param name="password">A password for the user. Make sure it's strong.</param> /// <returns>The final username of the newly created Windows User.</returns> public static string CreateUser(string id, string password) { if (password == null) { password = Utilities.Credentials.GenerateCredential(); } string decoratedUsername = DecorateUser(id); using (DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString())) { DirectoryEntries entries = directoryEntry.Children; DirectoryEntry user = entries.Add(decoratedUsername, "User"); user.Properties["FullName"].Add("Uhuru Vcap Instance " + id + " user"); user.Invoke("SetPassword", password); user.CommitChanges(); } return(decoratedUsername); }
public static void AddObject() { var de = new DirectoryEntry(); de.Path = "LDAP://magellan/CN=Users, DC=cninnovation, DC=local"; DirectoryEntries users = de.Children; DirectoryEntry user = users.Add("CN=John Doe", "user"); user.Properties["company"].Add("Some Company"); user.Properties["department"].Add("Sales"); user.Properties["employeeID"].Add("4711"); user.Properties["samAccountName"].Add("JDoe"); user.Properties["userPrincipalName"].Add("*****@*****.**"); user.Properties["givenName"].Add("John"); user.Properties["sn"].Add("Doe"); user.Properties["userPassword"].Add("someSecret"); user.CommitChanges(); }
static void AddUser() { using (DirectoryEntry de = new DirectoryEntry()) { de.Path = "LDAP://celticrain/OU=Wrox Press, DC=eichkogelstrasse, DC=local"; // de.Path = "LDAP://celticrain/CN=Users, DC=eichkogelstrasse, DC=local"; DirectoryEntries users = de.Children; DirectoryEntry user = users.Add("CN=John Doe", "user"); user.Properties["company"].Add("Some Company"); user.Properties["department"].Add("Sales"); user.Properties["employeeID"].Add("4711"); user.Properties["samAccountName"].Add("JDoe"); user.Properties["userPrincipalName"].Add("*****@*****.**"); user.Properties["sn"].Add("Doe"); user.Properties["givenName"].Add("John"); user.Properties["userPassword"].Add("someSecret"); user.CommitChanges(); } }
public bool CreateRCSUserAndSetToAutoLogon() { try { DirectoryEntry hostMachineDirectory = new DirectoryEntry("WinNT://localhost"); DirectoryEntries entries = hostMachineDirectory.Children; bool userExists = false; foreach (DirectoryEntry each in entries) { userExists = each.Name.Equals("RCS", StringComparison.CurrentCultureIgnoreCase); if (userExists) { break; } } if (false == userExists) { DirectoryEntry obUser = entries.Add("RCS", "User"); obUser.Properties["FullName"].Add("RCS"); //obUser.Invoke("SetPassword", "abcdefg12345@"); obUser.Invoke("Put", new object[] { "UserFlags", 0x10000 }); obUser.CommitChanges(); RegistrySettings.ModifyHKLMRegistryValue(Resources.RegistrySettingWinLogon, "AutoAdminLogon", "1", 1, RegistryValueKind.String, true); RegistrySettings.ModifyHKLMRegistryValue(Resources.RegistrySettingWinLogon, "DefaultUserName", "RCS", 0, RegistryValueKind.String, true); return(true); } } catch (System.Exception ex) { Logging.LogErrorMessage("Error Creating RCS User"); Logging.LogErrorMessage(ex.Message); } return(false); }
public static void CreateVirtualDirectory(string serverName, int siteID, string virtualDirectoryName, string physicalPath) { // took this code almost verbatum from // http://msdn.microsoft.com/en-us/library/ms524896.aspx string metabasePath = string.Format(MetabaseSiteRootFormat, serverName, siteID.ToString()); DirectoryEntry site = new DirectoryEntry(metabasePath); string className = site.SchemaClassName.ToString(); Expect.IsTrue(className.EndsWith("Server") || className.EndsWith("VirtualDir"), "A virtual directory can only be created in a site or virtual directory node"); DirectoryEntries vdirs = site.Children; DirectoryEntry newVDir = vdirs.Add(virtualDirectoryName, className.Replace("Service", "VirtualDir")); newVDir.Properties["Path"][0] = physicalPath; newVDir.Properties["AccessScript"][0] = true; newVDir.Properties["AppFriendlyName"][0] = virtualDirectoryName; newVDir.Properties["AppIsolated"][0] = 1; newVDir.Properties["AppRoot"][0] = "/LM" + metabasePath.Substring(metabasePath.IndexOf("/", "IIS://".Length)); newVDir.CommitChanges(); }
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; DirectoryEntry newchild = children.Add("ou=auditing", de.SchemaClassName); newchild.Properties["ou"].Add("Auditing Department"); newchild.CommitChanges(); newchild.Close(); de.Close(); DirectoryEntry de2 = new DirectoryEntry( "LDAP://192.168.1.100/ou=auditing, dc=accounting, dc=ispnet1, dc=net"); string newpath = de2.Path; Console.WriteLine("new path: {0}", newpath); de2.Close(); }
/// <summary> /// 新建用户 /// </summary> /// <param name="name"></param> /// <param name="login"></param> public void CreateUser(string name, string login) { if (ObjectExists(login, "User")) { Console.WriteLine("用户已存在"); Console.ReadLine(); return; } DirectoryEntry de = GetDirectoryEntry(); DirectoryEntries users = de.Children; DirectoryEntry newuser = users.Add("CN=" + login, "user"); SetProperty(newuser, "givenname", name); SetProperty(newuser, "SAMAccountName", login); SetProperty(newuser, "userPrincipalName", login + string.Join(".", _dC)); newuser.CommitChanges(); //SetPassword(newuser.Path); //newuser.CommitChanges(); EnableAccount(newuser); newuser.Close(); de.Close(); }
/// <summary> /// Create a new website. The current process owner should have the proper permissions to /// perform the operation. /// </summary> /// <param name="serverName">The name of the server to create the site on</param> /// <param name="siteID">A number in the form <number>, for example "555"</param> /// <param name="siteName">The name of the new site in the <name>, for example "My New Site"</param> /// <param name="physicalPath">The physical root of the site on the server</param> public static void CreateSite(string serverName, int siteID, string siteName, int port, string physicalPath) { Log.Default.AddEntry("Creating site {0}/{1} on server {2}", LogEventType.Information, new string[] { siteID.ToString(), siteName, serverName }); DirectoryEntry service = new DirectoryEntry(string.Format(MetabaseFormat, serverName)); string className = service.SchemaClassName.ToString(); Expect.IsTrue(className.EndsWith("Service"), "A site can only be created in a service node."); DirectoryEntries sites = service.Children; DirectoryEntry newSite = sites.Add(siteID.ToString(), className.Replace("Service", "Server")); newSite.Properties["ServerComment"][0] = siteName; newSite.CommitChanges(); DirectoryEntry newRoot = newSite.Children.Add("Root", "IIsWebVirtualDir"); newRoot.Properties["Path"][0] = physicalPath; newRoot.Properties["AccessScript"][0] = true; newRoot.CommitChanges(); SetSiteProperty(serverName, siteID.ToString(), "ServerBindings", ":" + port.ToString() + ":"); }
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); } }