I have seen some code for working with AD in this stackoverflow question
I am getting confused about the using statement. I thought that it was just used for things that you are worried could become memory leak, like a WebClient, or similar...
Anyway:
using (var context = new PrincipalContext( ContextType.Domain ))
{
using (var user = UserPrincipal.FindByIdentity( context, "username" ))
{
var groups = user.GetAuthorizationGroups();
...
}
}
when I reach the line var groups = user.GetAuthorizationGroups()
- user is null, so that line fails with a NullReference. When I mouse over it debugging it shows null, then shows Static Members, and has all the values.
If I take the line out of using statement and just have var user = UserPrincipal.FindByIdentity( context, "username" )
user is populated as required.
So what's going on ???
Edit: I stuffed up and was sending a bogus username. Oddly though when I check the variables during debug, when you would expect user to be completely null if I sent the bogus userid, but it showed under user: null, static members, and there had values for what I was currently logged in as-so I thought it was to do with the using statement potentially. Cheers!
What you're describing cannot happen. The specialness of a using
statement doesn't happen until the block is completed, when the object gets disposed. So inside that block, the user
variable is the same regardless of whether it's in a using
statement or not.
using is just syntactic sugar for try/finally and automatically calls Dispose on objects that implement IDisposable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With