我想在数据库和Active Directory中创建用户。我担心对数据库或Active Directory进行部分提交,因此搜索是否存在使AD处于事务处理之下的任何代码。我获得了有关IEnlistmentNotification
的一些详细信息,并在AD上进行了尝试,但无法正常工作。即使在某些例外情况下,AD记录也不会回滚。
我的代码运行没有问题,但是我尝试抛出一些异常以回滚AD中的记录,但无法正常工作。
我在AD中的创建用户:
public class CreateUser : IEnlistmentNotification
{
private ADUser _adUser;
public CreateUser(ADUser adUser)
{
_adUser = adUser;
if (Transaction.Current != null)
{
Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
}
}
public bool CreateADUser()
{
try
{
using (var context = new PrincipalContext(ContextType.Domain, "xxxxxxxxxxxxxxxx", "xxxxxxxxxxxxx", "xxxxxxxxxxxxxxxx"))
{
using (var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName,_adUser.UserName))
{
if (userPrincipal.IsAccountLockedOut())
{
userPrincipal.UnlockAccount();
}
userPrincipal.SetPassword(_adUser.Password);
userPrincipal.Save();
}
}
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void Prepare(PreparingEnlistment preparingEnlistment)
{
preparingEnlistment.Prepared();
preparingEnlistment.ForceRollback();
}
public void Commit(Enlistment enlistment)
{
enlistment.Done();
}
public void Rollback(Enlistment enlistment)
{
try
{
// Do something
}
finally
{
enlistment.Done();
}
}
public void InDoubt(Enlistment enlistment)
{
enlistment.Done();
}
}
我的主程序:
static void Main(string[] args)
{
try
{
Guid guid = Guid.NewGuid();
using (TransactionScope scope = new TransactionScope())
{
var adUser = new CreateUser(new ADUser
{
UserName = "newmancroos",
Password = "Testpass_7",
FirstName = "Newman",
LastName = "Croos"
});
adUser.CreateADUser();
var userContext = new UserContext();
var user = new User
{
Id = 20,
FirstName = "Newman7",
LastName = "Croos7",
Address = "test Address7"
};
userContext.Users.Add(user);
userContext.SaveChanges();
throw new Exception("Test Exception");
scope.Complete();
}
}
catch (TransactionException ex)
{
Console.WriteLine(ex);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred " + ex.Message);
Console.ReadKey();
}
}
数据库更改已回滚,但没有回滚。
预先感谢您的帮助