|
What would be the best method to iterate the localgroups on windows 2003 and possibly add/remove users to and from it?
|
|
|
|
|
I use this snippet code to create a user. It's successful when I run in winform but when I process in webpage, the error is always throwed exception: "general access denied error". I don't know if there are any privileges were assigned to my computer to create new user, I can use control panel to create user by the logon account. And I have done by webpage with this snippet code on other computers. Please give me the reason and solutions. Thanks
|
|
|
|
|
Hi,
Did u able t get the solution for this?
I m facing same problem.
please mail me at "naresh_0204@hotmail.com" if u found solution. i will appriciate your help.
Thanks in advance.
Naresh Hanchate
naresh_0204@hotmail.com
|
|
|
|
|
As I far as I can see, you problem is that you do not have enough rights to create a user.
When run from a winform, your thread has the rights of the user currently logged in (so you have enough permissions).
On the other hand, when running from a webpage, the thread that executes your code doesn't have enough rights.
To see the difference between the two ways, use this code:
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
To solve your problem, you need to use impersonation - at least this is the method I have successfully used. To do this, you need a valid domain/user/pass account that has enough rights to create a new user account.
I found this piece of code that helped me:
http://www.dotnet247.com/247reference/msgs/7/38183.aspx[^]
Note: when running the code above in an domainless environment, just pass null value for the domain parameter in impersonateValidUser() function.
|
|
|
|
|
many thanks for you nano2k,
you solved a big problem for me.
have a nice day
MohdM
|
|
|
|
|
Hi ,
I am getting the same access denied error. I tried to access the link which you have provided , but it shows "BAD REQUEST" error message . Could you please help me on the "access denied error" problem. Could you please tell me what i need to do to solve this issue .
Regards,
Lisha
lishamj
|
|
|
|
|
I used impersonation to solve this problem. I found the information on this page:
http://msdn.microsoft.com/en-us/library/xh507fc5.aspx
Add the code as indicated to the system.web section of your web.config file, entering the username and password of a user with sufficient privileges to create a new user. I created a new local user on the web server with admin privileges, and used this user.
|
|
|
|
|
When I add a user to AD using DirectoryEntry.Children.Add or DirectoryEntries.Add, it reponses too slow.
Is there any other way to speed up this?
If I add about 1000 users to AD, it took about 30minutes to complete
|
|
|
|
|
hello ,
plz see this code , i have a problem .
it give me this error --->
exception has been thrown by the target of an invocation
Dim _Path As String = "LDAP://server"
Dim domain As String = "prd.com"
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Try
Dim nun As String = "k11110"
Dim username As String = "amini"
Dim pwd As String = "test123"
Dim DE As DirectoryEntry = New DirectoryEntry(_Path, domain & "\" & username, pwd)
Dim OU As DirectoryEntry = DE.Children.Find("CN=USERS")
Dim NewUser As DirectoryEntry = OU.Children.Add("CN=" + nun, "User")
NewUser.Properties("sAMAccountName").Value = nun
NewUser.Properties("userPrincipalName").Add(nun + "@prd-co.com")
NewUser.Properties("GivenName").Add("sanaz")
NewUser.Properties("initials").Add("a")
NewUser.Properties("sn").Add("amini")
NewUser.Properties("displayName").Add("Amini")
NewUser.Properties("description").Add("Amini")
NewUser.CommitChanges()
NewUser.NativeObject.accountdisabled = False
NewUser.Properties("accountExpires").Value = 0
NewUser.Properties("pwdLastSet").Value = -1
NewUser.Invoke("setpassword", pwd)
NewUser.CommitChanges()
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
thank you.
|
|
|
|
|
Has anyone seen this before? I am using this code snippet to add an account on my pc. The page i created kept hanging, so i debugged it, and i found that it was telling me that the specified username is invalid. I have tried using the credentials of a local admin account on the machine to take out the possibility of not actually authenticating, but no matter what, i continually get the same error. When i remove the authentication information, it steps through the entire code, but then fails at the end because no credentials were supplied....
|
|
|
|
|
Hi,
i'd like to know how i can do the same in vb.net ?
In fact, what i really wanted is to browse my domain (!! NT 4 => not Active directory) and for each groups, list all the user.
I've done in vb but in .net, i'm lost...
thx,
Troll
|
|
|
|
|
Here's a link to the MSDN site that explains how to load up all the info on AD(and i'm using all this stuff without AD and it seems to be working just fine) into a tree view.
The other links on the left are ALL useful stuff on how to use the DirectoryServices.dll and all the code samples are in C# and VB.NET
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbtskremovingactivedirectorynodes.asp
|
|
|
|
|
|
In this article you say: "Operating system does not give access to clear text password value". I'm creating windows tasks that wont run unless they have the user name and password set. How do some applications (such as Norton System Works) manage to create system tasks which use my user name and my password to run? I don't remember having provided any password during instalation. I need to provide the current user's password in the moment I create the task.
Thanks in advance for any suggestion.
Regards Juanma.
Juan Manuel Gómez Ramos
B.Sc. Computer Science
<cronosxfiles@yahoo.com>
|
|
|
|
|
When I crate a account in AD ? How can I crate a mail in Exchange and IM ?
Thx for some hints.
|
|
|
|
|
This post has been a great help.
Is there any way to add new users to groups.
andy
|
|
|
|
|
You should try GroupMembership attribute, which should contain collection of distinguishedNames of groups.
But better is to add user into group via group itself. It is member attribute which should contain collection of distinguishedNames of users.
|
|
|
|
|
I'm using the following code in C# to "Add a User to Administrators Group"
--------------------------CODE-----------------------------------------------------
DirectoryEntry DirEntry = new DirectoryEntry("WinNT://" + strDomain);
DirectoryEntries entries = DirEntry.Children;
DirectoryEntry adminGroup = entries.Find("Administrators", "Group");
DirectoryEntry newUser = entries.Add(strLogin, "User");
newUser.Properties["FullName"].Add(textBox2.Text);
object Ret = newUser.Invoke("SetPassword", strPassword);
newUser.CommitChanges();
adminGroup.Properties["member"].Add(newUser.Properties["distinguishedName"].Value);
adminGroup.CommitChanges();
------------------------------------------------------------------------------------
but the following exeption occurs:
==============================Exeption
Value cannot be null.
Parameter name: value
======================================
I think there are not valid members
adminGroup.Properties["member"] & newUser.Properties["distinguishedName"]
Anybody can help in this context
Thanx in advance
Watch Your Thoughts for they will become your actions.
Watch Your Actions for they will become your habits.
Watch Your Habits for they will become your beliefs.
Watch Your Beliefs for they will determine your destiny.
|
|
|
|
|
Hello,
The code has helped me get a better understanding on the process of adding a user, but I also need to set the user UserFlag UF_DONT_EXPIRE_PASSWD to not expire. I have added the UserFlag property, but I have no clue how to set or even access the don't expire password bit.
Using your original code, how would you prevent the password from changing? There are no resources on the net that describe this operation in C#.
Thanks!
CK
|
|
|
|
|
Got it.
//Add the following:
const int UF_PASSWD_CANT_CHANGE = 0x0040;
NewUser.Properties["userFlags"].Add(UF_PASSWD_CANT_CHANGE);
// Done
Self prescribed help at its best.
CK
|
|
|
|
|
I'm sure this article's code works for some, but creating a user this way gives me all kinds of errors, like "The server is unwilling to process the request." and "The server said it'll think about it and get back to you"... I just spent a couple of days dealing with this, and finally came up with the following C# helper class, based on other pieces of code I gleaned from the newsgroups. Anyhow, hope this helps, it works for me.
-Brendan Tompkins
brendan_f_tompkins@hotmail.com
using System;
using System.DirectoryServices;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Configuration;
namespace Util.ActiveDirectory
{
public class ADHelper
{
#region Private Variables
/// Path to your AD -LDAP://machine.domain.org/DC=machine,DC=domain,DC=org
private static string ADPath = ConfigurationSettings.AppSettings[StringConstants.Configuration.AD_PATH_KEY] ;
/// Path to your AD Container where you want to create users - LDAP://machine.domain.org/OU=container,DC=machine,DC=domain,DC=org
private static string ADContainerPath = ConfigurationSettings.AppSettings[StringConstants.Configuration.AD_CONAINER_PATH_KEY] ;
/// Path to your AD Server -machine.domain.org
private static string ADServer = ConfigurationSettings.AppSettings[StringConstants.Configuration.AD_SERVER_KEY] ;
#endregion
#region Enumerations
public enum ADAccountOptions
{
UF_TEMP_DUPLICATE_ACCOUNT = 0x0100,
UF_NORMAL_ACCOUNT =0x0200,
UF_INTERDOMAIN_TRUST_ACCOUNT =0x0800,
UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
UF_SERVER_TRUST_ACCOUNT =0x2000,
UF_DONT_EXPIRE_PASSWD=0x10000,
UF_SCRIPT =0x0001,
UF_ACCOUNTDISABLE=0x0002,
UF_HOMEDIR_REQUIRED =0x0008,
UF_LOCKOUT=0x0010,
UF_PASSWD_NOTREQD=0x0020,
UF_PASSWD_CANT_CHANGE=0x0040,
UF_ACCOUNT_LOCKOUT=0x0010,
UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED=0x0080,
}
public enum ADErrors : uint
{
ERR_PROPERTY_NOT_FOUND = 0x80020006
}
public enum LoginResult
{
LOGIN_OK=0,
LOGIN_USER_DOESNT_EXIST,
LOGIN_USER_ACCOUNT_INACTIVE
}
#endregion
/// Given a username, return bool if exists
public static bool UserExists(string UserName)
{
//create an instance of the DirectoryEntry
DirectoryEntry de = GetDirectoryObject(ADContainerPath);
//create instance fo the direcory searcher
DirectorySearcher deSearch = new DirectorySearcher();
//set the search filter
deSearch.SearchRoot = de;
deSearch.Filter = "(SAMAccountName=" + UserName +")";
//find the first instance
SearchResultCollection results= deSearch.FindAll();
//if the username and password do match, then this implies a valid login
//if so then return the DirectoryEntry object
if(results.Count == 0) return false;
return true;
}
/// Creates a new user
public static DirectoryEntry CreateNewUser(ActiveDirectoryUser user)
{
DirectoryEntry container = GetDirectoryObject(ADContainerPath);
DirectoryEntry userEntry = AddUserAccount(container, user);
SetPassword(userEntry, user.password);
EnableUserAccount(userEntry);
return userEntry;
}
/// Add Account to the given container
public static DirectoryEntry AddUserAccount(DirectoryEntry container, ActiveDirectoryUser user)
{
DirectoryEntry newUser = container.Children.Add("CN=" + user.userName, "User");
// Add mandatory properties
newUser.Properties["sAMAccountName"].Add(user.userName);
//Optional properties
newUser.Properties["mail"].Add(user.mail);
newUser.Properties["givenName"].Add(user.givenName);
newUser.Properties["sn"].Add(user.sn);
// // add some more obscure properties
// object[] objAddress = new object[] {"Somestreet","PB", "SomeCity", "PROV","PB0000", "Country"};
//
// //Set the Address and Province
// newUser.Properties["postalAddress"].AddRange(objAddress);
newUser.CommitChanges();
return newUser;
}
/// Enable the user account after it has been created and after it's password has been set.
private static void EnableUserAccount(DirectoryEntry newUser)
{
int currentAccountControl = (int)newUser.Properties["userAccountControl"].Value;
int acctControlFlags = currentAccountControl - (int)ADAccountOptions.UF_PASSWD_NOTREQD - (int)ADAccountOptions.UF_ACCOUNTDISABLE;
acctControlFlags = acctControlFlags | (int)ADAccountOptions.UF_NORMAL_ACCOUNT | (int)ADAccountOptions.UF_PASSWD_CANT_CHANGE | (int)ADAccountOptions.UF_DONT_EXPIRE_PASSWD;
newUser.Properties["userAccountControl"].Clear();
newUser.Properties["userAccountControl"].Add(acctControlFlags);
newUser.CommitChanges();
}
/// Set the password of a user entry
private static void SetPassword(DirectoryEntry userEntry, string password)
{
object[] oPassword = new object[] {password};
object ret = userEntry.Invoke("SetPassword", oPassword );
userEntry.CommitChanges();
}
/// Gets a directory object given an LDAP path
private static DirectoryEntry GetDirectoryObject(string path)
{
DirectoryEntry de;
string _ADPath = path;
de = new DirectoryEntry(_ADPath);
return de;
}
/// Gets a directory object, given a path, username, ans password.
private static DirectoryEntry GetDirectoryObject(string path, string UserName, string Password)
{
DirectoryEntry de;
de = new DirectoryEntry(path,UserName,Password,AuthenticationTypes.Secure);
return de;
}
/// Gets a property givent a directory entry and property name
public static string GetProperty(DirectoryEntry de, string PropertyName)
{
if(de.Properties.Contains(PropertyName))
{
return de.Properties[PropertyName][0].ToString() ;
}
else
{
return string.Empty;
}
}
/// Gets a formatted LDAP domain string given a servername
private static string GetLDAPDomain(string servername)
{
StringBuilder LDAPDomain = new StringBuilder();
string[] LDAPDC = servername.Split('.');
for(int i=0;i < LDAPDC.GetUpperBound(0)+1;i++)
{
LDAPDomain.Append("DC="+LDAPDC[i]);
if(i <LDAPDC.GetUpperBound(0))
{
LDAPDomain.Append(",");
}
}
return LDAPDomain.ToString();
}
/// Write out all of the properties of a given directory entry
public static void WriteProperties(DirectoryEntry dirEntry)
{
string[] propNames = new string[dirEntry.Properties.Count];
dirEntry.Properties.PropertyNames.CopyTo(propNames,0);
for (int propertyIndex = 0; propertyIndex < dirEntry.Properties.Count; propertyIndex++)
{
System.Diagnostics.Trace.WriteLine("Name: {0}", propNames[propertyIndex]);
int valueCount = dirEntry.Properties[propNames[propertyIndex]].Count;
for (int valueIndex = 0; valueIndex < valueCount; valueIndex++)
System.Diagnostics.Trace.WriteLine(String.Format(" Value {0}: {1}", valueIndex, dirEntry.Properties[propNames[propertyIndex]][valueIndex]));
}
}
}
[Serializable()]
public struct ActiveDirectoryUser
{
private string _userName;
private string _password;
private string _description;
private string _displayName;
private string _mail;
private string _givenName;
private string _sn;
public ActiveDirectoryUser(string userName, string password)
{
_userName = userName;
_password = password;
_description = "";
_displayName = "";
_mail = "";
_givenName = "";
_sn = "";
}
public string userName
{
get { return _userName; }
set { _userName = value; }
}
public string password
{
get { return _password; }
set { _password = value; }
}
public string description
{
get { return _description; }
set { _description = value; }
}
public string displayName
{
get { return _displayName; }
set { _displayName = value; }
}
public string mail
{
get { return _mail; }
set { _mail = value; }
}
public string givenName
{
get { return _givenName; }
set { _givenName = value; }
}
public string sn
{
get { return _sn; }
set { _sn = value; }
}
}
}
|
|
|
|
|
Brenden,
thanks for sharing your code with us. We faced issues with other way round. LDAP provider was giving a lot of problems where as WinNT provider worked like charm. I think it more to do with how the domains are set up. and security policies.
thanks,
Softomatix
---
Softomatix
http://www.pardesifashions.com/Softomatix/default.aspx
|
|
|
|
|
Brendan Pumpkins, you are the man even if your still using that crusty old WinNT provider, but should start using LDAP instead. LDAP will be around alot longer than WinNT.
;P ;)
|
|
|
|
|
Brendan,
You saved me a lot time by this ADHelper.
Thanks a lot!
|
|
|
|
|
Could you please explain what "ADContainerPath" is and how it should be set up? I always get the error "The server is not operational"
|
|
|
|
|