473,750 Members | 2,527 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Will this code work with an NT domain?

I have code to add a domain user to a local group but I'm not sure if it
will work with NT domains or whether it will only work with Active Directory
based systems. Here's the code:

public void AddDomainUserTo LocalGroup(stri ng computerName, string groupName,
string domainName, string userName)
{
Hashtable htRet = new Hashtable();
IADsContainer groupComputer = (IADsContainer) Win32.GetObject ("WinNT://"
+ computerName + ",computer" );
IADsGroup group = (IADsGroup)grou pComputer.GetOb ject("group",
groupName);
group.Add("WinN T://" + domainName + "/" + userName);
}

Nov 16 '05 #1
7 4807
Peter,

On domains where there is not an AD controller, the call to GetObject
will return nothing, so it will not work.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Peter Steele" <ps*****@z-force.com> wrote in message
news:el******** ******@TK2MSFTN GP09.phx.gbl...
I have code to add a domain user to a local group but I'm not sure if it
will work with NT domains or whether it will only work with Active
Directory based systems. Here's the code:

public void AddDomainUserTo LocalGroup(stri ng computerName, string
groupName, string domainName, string userName)
{
Hashtable htRet = new Hashtable();
IADsContainer groupComputer = (IADsContainer) Win32.GetObject ("WinNT://"
+ computerName + ",computer" );
IADsGroup group = (IADsGroup)grou pComputer.GetOb ject("group",
groupName);
group.Add("WinN T://" + domainName + "/" + userName);
}

Nov 16 '05 #2
Is there a generic implementation of this that would work with both NT and
AD domains? I assume there must be an underlying Win32 API call I could
make?

Peter

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard .caspershouse.c om> wrote in
message news:uP******** ******@TK2MSFTN GP14.phx.gbl...
Peter,

On domains where there is not an AD controller, the call to GetObject
will return nothing, so it will not work.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Peter Steele" <ps*****@z-force.com> wrote in message
news:el******** ******@TK2MSFTN GP09.phx.gbl...
I have code to add a domain user to a local group but I'm not sure if it
will work with NT domains or whether it will only work with Active
Directory based systems. Here's the code:

public void AddDomainUserTo LocalGroup(stri ng computerName, string
groupName, string domainName, string userName)
{
Hashtable htRet = new Hashtable();
IADsContainer groupComputer =
(IADsContainer) Win32.GetObject ("WinNT://" + computerName + ",computer" );
IADsGroup group = (IADsGroup)grou pComputer.GetOb ject("group",
groupName);
group.Add("WinN T://" + domainName + "/" + userName);
}


Nov 16 '05 #3

"Peter Steele" <ps*****@z-force.com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Is there a generic implementation of this that would work with both NT and
AD domains? I assume there must be an underlying Win32 API call I could
make?

Yep, here's a sample...

using System.Director yServices;
.....

private static void AddToGroup(stri ng groupName)
{
// Domain administrator account as a sample...
string userPath = "WinNT://DCName/Administrator,U ser";
DirectoryEntry userEntry = new DirectoryEntry( userPath,
"domainadmin"," hispwd", AuthenticationT ypes.ServerBind );
object o = userEntry.Nativ eObject;
if (o == null)
{
Console.WriteLi ne("No such account");
return;
}

using(Directory Entry container = new
DirectoryEntry( "WinNT://localMachineNam e","localadmin" , "hispwd",
AuthenticationT ypes.ServerBind ))
{
DirectoryEntry groupEntry = container.Child ren.Find(groupN ame, "group");
object newEntry = groupEntry.Invo ke("add",
new object[] {userEntry.Path } );
groupEntry.Comm itChanges();
}
}

public static void Main() {
// Add domain Administrator to Guests
AddToGroup("Gue sts");
}

Willy.
Nov 16 '05 #4
Thanks for this code, I'll have to give it a try. Is there similar technique
for creating a domain account using DirectoryServic es? I basically want to
do something like NetUserAdd to add user X to domain Y and there is a
possibility that the workstation where I am running the code will not be in
the domain.

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

"Peter Steele" <ps*****@z-force.com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Is there a generic implementation of this that would work with both NT
and AD domains? I assume there must be an underlying Win32 API call I
could make?

Yep, here's a sample...

using System.Director yServices;
....

private static void AddToGroup(stri ng groupName)
{
// Domain administrator account as a sample...
string userPath = "WinNT://DCName/Administrator,U ser";
DirectoryEntry userEntry = new DirectoryEntry( userPath,
"domainadmin"," hispwd", AuthenticationT ypes.ServerBind );
object o = userEntry.Nativ eObject;
if (o == null)
{
Console.WriteLi ne("No such account");
return;
}

using(Directory Entry container = new
DirectoryEntry( "WinNT://localMachineNam e","localadmin" , "hispwd",
AuthenticationT ypes.ServerBind ))
{
DirectoryEntry groupEntry = container.Child ren.Find(groupN ame, "group");
object newEntry = groupEntry.Invo ke("add",
new object[] {userEntry.Path } );
groupEntry.Comm itChanges();
}
}

public static void Main() {
// Add domain Administrator to Guests
AddToGroup("Gue sts");
}

Willy.

Nov 16 '05 #5

"Peter Steele" <ps*****@z-force.com> wrote in message
news:Ol******** *****@TK2MSFTNG P12.phx.gbl...
Thanks for this code, I'll have to give it a try. Is there similar
technique for creating a domain account using DirectoryServic es? I
basically want to do something like NetUserAdd to add user X to domain Y
and there is a possibility that the workstation where I am running the
code will not be in the domain.

Sure, check this
http://msdn.microsoft.com/library/de...ry_objects.asp

Note that most of the samples in
http://msdn.microsoft.com/library/en..._examples.asp?
are for AD domain management using the LDAP provider interface, NT4 domains
only support a limitted subset of the AD properties and the semantics and
syntax can differ significantly, check MSDN for differences.

To get you started, here's a sample that creates a local account in the
Guest alias.

using System.Director yServices;
using System.Runtime. InteropServices ;
using System;
class AdsiUser
{
// User flags used to set user properties see AdSI doc's in MSDN
const int UF_SCRIPT = 0x0001;
const int UF_ACCOUNTDISAB LE = 0x0002;
const int UF_HOMEDIR_REQU IRED = 0x0008;
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWD_NOTRE QD = 0x0020;
const int UF_PASSWD_CANT_ CHANGE = 0x0040;
const int UF_TEMP_DUPLICA TE_ACCOUNT = 0x0100;
const int UF_NORMAL_ACCOU NT = 0x0200;
const int UF_DONT_EXPIRE_ PASSWD = 0x10000;
const int UF_PASSWORD_EXP IRED = 0x800000;
public static void Main()
{
string userName = "Tester";
DirectoryEntry NewUser;
//Bind and get the local computer container object using WinNT provider
// Use LDAP as provider to bind against an AD domain
using(Directory Entry computer = new DirectoryEntry( "WinNT://" +
Environment.Mac hineName + ",computer" , ".\\Administrat or", "kevin"))
{
// delete user when existing
NewUser = computer.Childr en.Find(userNam e, "User");
if (NewUser != null)
computer.Childr en.Remove(NewUs er);

// Add entry using the user schema
NewUser = computer.Childr en.Add(userName , "user");
NewUser.Propert ies["fullname"].Add("Tester account");
NewUser.Propert ies["descriptio n"].Add("test user acount");
NewUser.Propert ies["PasswordExpire d"].Add(1); // user must change
password at next login
// Set some user flags
// this flag is different when binding to computer domain using LDAP
NewUser.Propert ies["userFlags"].Add(UF_NORMAL_ ACCOUNT
|UF_DONT_EXPIRE _PASSWD
);
// invoke native method 'SetPassword' before commiting
// for computer domain accounts this must be done after commiting
NewUser.Invoke( "SetPasswor d", new Object[] {"#12345Abc" });
NewUser.CommitC hanges();
foreach(string s in NewUser.Propert ies.PropertyNam es)
Console.WriteLi ne(s + " " + (NewUser.Proper ties[s])[0]);

// Add user to guests alias
DirectoryEntry grp = computer.Childr en.Find("guests ", "group");
try {
if (grp.Name != null)
grp.Invoke("Add ", new Object[] {NewUser.Path.T oString()});
Console.WriteLi ne("Account Created Successfully");
}
catch(Exception ex)
{
Console.WriteLi ne(ex);
}
}
}
}
Willy.

Nov 16 '05 #6
Thanks much!

Peter

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:um******** ******@TK2MSFTN GP11.phx.gbl...

"Peter Steele" <ps*****@z-force.com> wrote in message
news:Ol******** *****@TK2MSFTNG P12.phx.gbl...
Thanks for this code, I'll have to give it a try. Is there similar
technique for creating a domain account using DirectoryServic es? I
basically want to do something like NetUserAdd to add user X to domain Y
and there is a possibility that the workstation where I am running the
code will not be in the domain.

Sure, check this
http://msdn.microsoft.com/library/de...ry_objects.asp

Note that most of the samples in
http://msdn.microsoft.com/library/en..._examples.asp?
are for AD domain management using the LDAP provider interface, NT4
domains only support a limitted subset of the AD properties and the
semantics and syntax can differ significantly, check MSDN for differences.

To get you started, here's a sample that creates a local account in the
Guest alias.

using System.Director yServices;
using System.Runtime. InteropServices ;
using System;
class AdsiUser
{
// User flags used to set user properties see AdSI doc's in MSDN
const int UF_SCRIPT = 0x0001;
const int UF_ACCOUNTDISAB LE = 0x0002;
const int UF_HOMEDIR_REQU IRED = 0x0008;
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWD_NOTRE QD = 0x0020;
const int UF_PASSWD_CANT_ CHANGE = 0x0040;
const int UF_TEMP_DUPLICA TE_ACCOUNT = 0x0100;
const int UF_NORMAL_ACCOU NT = 0x0200;
const int UF_DONT_EXPIRE_ PASSWD = 0x10000;
const int UF_PASSWORD_EXP IRED = 0x800000;
public static void Main()
{
string userName = "Tester";
DirectoryEntry NewUser;
//Bind and get the local computer container object using WinNT provider
// Use LDAP as provider to bind against an AD domain
using(Directory Entry computer = new DirectoryEntry( "WinNT://" +
Environment.Mac hineName + ",computer" , ".\\Administrat or", "kevin"))
{
// delete user when existing
NewUser = computer.Childr en.Find(userNam e, "User");
if (NewUser != null)
computer.Childr en.Remove(NewUs er);

// Add entry using the user schema
NewUser = computer.Childr en.Add(userName , "user");
NewUser.Propert ies["fullname"].Add("Tester account");
NewUser.Propert ies["descriptio n"].Add("test user acount");
NewUser.Propert ies["PasswordExpire d"].Add(1); // user must change
password at next login
// Set some user flags
// this flag is different when binding to computer domain using LDAP
NewUser.Propert ies["userFlags"].Add(UF_NORMAL_ ACCOUNT
|UF_DONT_EXPIRE _PASSWD
);
// invoke native method 'SetPassword' before commiting
// for computer domain accounts this must be done after commiting
NewUser.Invoke( "SetPasswor d", new Object[] {"#12345Abc" });
NewUser.CommitC hanges();
foreach(string s in NewUser.Propert ies.PropertyNam es)
Console.WriteLi ne(s + " " + (NewUser.Proper ties[s])[0]);

// Add user to guests alias
DirectoryEntry grp = computer.Childr en.Find("guests ", "group");
try {
if (grp.Name != null)
grp.Invoke("Add ", new Object[] {NewUser.Path.T oString()});
Console.WriteLi ne("Account Created Successfully");
}
catch(Exception ex)
{
Console.WriteLi ne(ex);
}
}
}
}
Willy.

Nov 16 '05 #7
One thing I've noticed in your code is that you make explicit reference to
the domain controller:

"WinNT://DCName/Administrator,U ser"

In my original version the code doesn't need to know this information. All
it needs to know is the name of the domain, not the DC servicing the domain.
Is there a way around this or should I plan on passing it as a parameter?

"Willy Denoyette [MVP]" <wi************ *@pandora.be> wrote in message
news:%2******** ********@TK2MSF TNGP11.phx.gbl. ..

"Peter Steele" <ps*****@z-force.com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
Is there a generic implementation of this that would work with both NT
and AD domains? I assume there must be an underlying Win32 API call I
could make?

Yep, here's a sample...

using System.Director yServices;
....

private static void AddToGroup(stri ng groupName)
{
// Domain administrator account as a sample...
string userPath = "WinNT://DCName/Administrator,U ser";
DirectoryEntry userEntry = new DirectoryEntry( userPath,
"domainadmin"," hispwd", AuthenticationT ypes.ServerBind );
object o = userEntry.Nativ eObject;
if (o == null)
{
Console.WriteLi ne("No such account");
return;
}

using(Directory Entry container = new
DirectoryEntry( "WinNT://localMachineNam e","localadmin" , "hispwd",
AuthenticationT ypes.ServerBind ))
{
DirectoryEntry groupEntry = container.Child ren.Find(groupN ame, "group");
object newEntry = groupEntry.Invo ke("add",
new object[] {userEntry.Path } );
groupEntry.Comm itChanges();
}
}

public static void Main() {
// Add domain Administrator to Guests
AddToGroup("Gue sts");
}

Willy.

Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2092
by: jason | last post by:
I am getting twisted by the possibility that my virtual includes which currently work great on non-domain remote IP will crash if I purchase a domain and point it to one of my designated folders.....Here is the scenario and question:: If my remote webhost at (eg): http://69.8.9.9 ....has a subfolder with with:
20
5140
by: Clark | last post by:
Hi all. I'm looking for good C source code to study and be able to advance my C programming skills. Do you recomend any open source project in particular that in your opinion has good writen C code? Thanks.
11
5563
by: ricolee99 | last post by:
Hi everyone, I'm trying to invoke my .exe application from a remote server. Here is the code: ManagementClass processClass = new ManagementClass ("\\\\" +"RemoteServerName" + "\\root\\CIMV2:Win32_Process");
3
2228
by: Paul Kenny | last post by:
Hi, I have developed an application that uses mixed C++ to integrate managed ..NET applications with an unmanaged C++ application whose behaviour I cannot change. The unmanaged C++ application uses the Win32 API's CreateThread fn to create a thread that listens for requests. These requests then call into the mixed C++ code. This all works fine when the application lives in the same app domain.
2
1514
by: Neo Geshel | last post by:
I have the two subs: Sub UniqueHits() Dim StrSQLQuery As String Dim ObjAdapter as New OleDbDataAdapter() Dim ObjDataSet as DataSet StrSQLQuery = "SELECT * FROM Browser WHERE IsUnique = True" ObjAdapter.SelectCommand = new OleDbCommand(StrSQLQuery, ObjConnection) ObjDataSet = new DataSet()
8
1794
by: msnews.microsoft.com | last post by:
I have ADSI code that I can make work at the command line. I cannot in any way get it to work in asp.net. Even using Windows authentication, impersonation on, and providing the credentials hardcoded, I cannot make this same code happen. This is all I am trying to do: static void Stuff() { //we don't need the credentials on this form // so store in session state.
5
2084
by: jacquesvdz | last post by:
Hi Hope you guys can help me with this? I live in a house with 10 people.In the beginning wehn there were only two people, I gave them my password for the use of my pc. But since I got Internet at my home, everybody thinks its fun to use my pc.
12
2339
tpgames
by: tpgames | last post by:
I've tried JS cookie on the html page that contains the iFrame code linking to the php jigsaw puzzle game. That did NOT work. I've tried JS cookie on the php page; php cookie on the php page, php cookie on the html page, and none of those have worked. <?php session_start(); $rating1=$rating; session_destroy(); $today=time(); $atoday=getdate($today); //Get the date into an array $atoday->mon++; //set the month to next...
4
5810
by: =?Utf-8?B?QXZhRGV2?= | last post by:
ASP.Net 2. We are migrating to Windows 2008 64 bit Server with IIS 7 from Windows 2003 32 Bit with IIS 6. A few library classes we wrote uses impersonation in code like explained in this article: http://support.microsoft.com/?id=306158#4 This doesn't work in Windows 2008 Server, we receive the following exception:
0
8839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
9345
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9257
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8265
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6811
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4716
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4894
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2809
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2227
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.