Is there a way to find out if a local group already exists? My "best" solution works by catching an exception. Is there a way to do achieve the same goal without catching an exception?
var machine = Environment.MachineName;
var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
bool groupExists = true;
try
{
server.Children.Find("MyGroup", "group");
}
catch (COMException ex)
{
if (ex.ErrorCode == -2147022676)
groupExists = false;
else
throw;
}
You can try the below code
var machine = Environment.MachineName;
var server = new DirectoryEntry(string.Format("WinNT://{0},Computer", machine));
bool exists = server.Children.Cast<DirectoryEntry>().Any(d => d.SchemaClassName.Equals("Group") && d.Name.Equals("Administrators"));
Alternatively you could use the PrincipalContext class as follows:
using(var local = new PrincipalContext(ContextType.Machine))
{
var group = GroupPrincipal.FindByIdentity(local, "MyGroup");
var groupExists = group != null;
}
Related
My code to use the function for updating is here and it works also
[HttpPost]
public bool SaveDefCompny(DefCompanyDTO DefCmpny)
{
using (RPDBEntities db = new RPDBEntities())
{
using (TransactionScope trans = new TransactionScope())
{
//the problem is here incase of saving
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
List<DefCompany> list = new List<DefCompany>();
list.Add(UpdateDefCmpnyId);
try
{
foreach (DefCompany DefCmpny1 in list)
{
DefCmpny1.Id = DefCmpny1.Id;
DefCmpny1.ShortName = DefCmpny.ShortName;
DefCmpny1.FullName = DefCmpny.FullName;
DefCmpny1.ContactPerson = DefCmpny.ContactPerson;
DefCmpny1.Address1 = DefCmpny.Address1;
DefCmpny1.CompanyCity = DefCmpny.CompanyCity;
DefCmpny1.CompanyState = DefCmpny.CompanyState;
DefCmpny1.CompanyCountry = DefCmpny.CompanyCountry;
DefCmpny1.ZipPostCode = DefCmpny.ZipPostCode;
DefCmpny1.TelArea = DefCmpny.TelArea;
DefCmpny1.CurrentCurrencyCode = DefCmpny.CurrentCurrencyCode;
db.SaveChanges();
trans.Complete();
}
}
catch (Exception ex)
{
}
}
return false;
}
}
when I try to save instead of updating the line of code
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).First();
gives null value and hence saving fails because record is new and not present in database so how to handle null in case of saving how to use try catch so that when value is null it proceed to saving code that add
How about something along these lines:
var UpdateDefCmpnyId = (from CmpnyId in db.DefCompanies
where CmpnyId.Id == DefCmpny.Id
select CmpnyId).FirstOrDefault();
if(UpdateDefCmpnyId == null)
{
//insert
//(handle the id however you need to for insert. depending on your setup, you might be able to leave it empty and let the database put it in for you)
}
else
{
//update
//set the id as you do in the question
}
In my application I need to check whether or not I have permissions to write to a folder. I use the following method:
public bool IsAvailable(string path)
{
bool hasPermissions = false;
if (Directory.Exists(path))
{
var permission = new FileIOPermission(FileIOPermissionAccess.Write, path);
try
{
permission.Demand();
hasPermissions = true;
}
catch(SecurityException e)
{
hasPermissions = false;
}
}
return hasPermissions;
}
When I give it a path to a Folder that I know for certain no one has access to it (I've removed all permission for all users in the Security Tab of the Folder Properties), it doesn't throw any exception. It just continues along the try block.
Any ideas why or how to do this check better?
The AppDomain.PermissionSet Property related answers I found on other question had no succes.
Thank you in advance.
I had used the following method to get it done:
public static bool HasWritePermissionOnDir(string path)
{
var writeAllow = false;
var writeDeny = false;
var accessControlList = Directory.GetAccessControl(path);
if (accessControlList == null)
return false;
var accessRules = accessControlList.GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
if (accessRules == null)
return false;
foreach (FileSystemAccessRule rule in accessRules)
{
if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) continue;
if (rule.AccessControlType == AccessControlType.Allow)
writeAllow = true;
else if (rule.AccessControlType == AccessControlType.Deny)
writeDeny = true;
}
return writeAllow && !writeDeny;
}
Please let me know if it helped you and if yes mark it too
This method (ask if accessible, then do something) is prone to race conditions. Between your check and an actual access to content in that directory, the permissions may change.
Better just try to read/write something in that directory, and catch a potential exception.
So don't
if(IsAvailable(path)) {
try {
doSomething();
} catch (...) {
}
}
but rather
try {
doSomething();
} catch (...) {
}
Grace Hopper quote:
“It’s always easier to ask forgiveness than it is to get permission.”
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{}
I am LINQ to input information from a Database. I have my try.catch block set up to catch these exceptions. However I believe I ran into a sore spot where I am attempting to see what the message is but it just bypass printing the message to me and goes directly to error page. Here is an example of the code I have so far. I would love to get some input on why this seems to be acting so strange.
private void CreateEntry()
{
var date = DateTime.Today;
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
//Try to create an entry for the database. Upon failure, sends the exception to ThrowDbError();
try
{
ResidenceHallInspection rhi = new ResidenceHallInspection();
rhi.versionId = version.id;
rhi.submitDate = DateTime.Now;
rhi.CheckInOrOut = ddlCheck.SelectedItem.Text;
rhi.Id = txtId.Text;
rhi.FirstName = txtFirstName.Text;
rhi.MiddleName = txtMiddleName.Text;
rhi.LastName = txtLastName.Text;
rhi.Walls = chbxWalls.SelectedItem.Text;
rhi.Windows = chbxWindows.SelectedItem.Text;
rhi.Blinds = chbxBlinds.SelectedItem.Text;
rhi.Couch = chbxCouch.SelectedItem.Text;
rhi.CommonRoomCouch = chbxCRCouch.SelectedItem.Text;
rhi.CommonRoomChair = chbxCRChair.SelectedItem.Text;
rhi.Doors = chbxDoors.SelectedItem.Text;
rhi.Carpet = chbxCarpet.SelectedItem.Text;
rhi.Ceiling = chbxCeiling.SelectedItem.Text;
rhi.CommonRoomCounter = chbxCRCounter.SelectedItem.Text;
rhi.Cabinet = chbxCabinet.SelectedItem.Text;
rhi.Phone = chbxPhone.SelectedItem.Text;
rhi.Bed = chbxBed.SelectedItem.Text;
rhi.Desk = chbxDesk.SelectedItem.Text;
rhi.DeskChairs = chbxDeskChair.SelectedItem.Text;
rhi.Tub = chbxTub.SelectedItem.Text;
rhi.Vanity = chbxVanity.SelectedItem.Text;
rhi.Notes = txtNotes.Text;
rhi.Building = txtResHall.Text;
rhi.ApartmentNumber = txtSuitNo.Text;
rhi.BedSpace = txtBedSpace.Text;
house.AddToResidenceHallInspections(rhi);
house.SaveChanges();
}
catch (Exception oe)
{
ThrowDbError(oe);
Response.Write(oe.InnerException);
}
}
/*=================================================*/
/*Possible Errors */
/*=================================================*/
private void ThrowDbError(Exception oe)
{
Response.Write(oe.Source);
house.Dispose();
Session.Contents.Add("FormException", oe);
Response.Redirect("/Database-Error/", true);
}
The most likely reason for that to happen is that you are running the database version query outside the try/catch block. Any exception in this db access code will not be handled by the code you have shown above.
Try extending your try block to also include the db access code:
var version = (from v in house.StayLateVersions
where v.Active
select v).FirstOrDefault();
if (version == null)
{
throw new NullReferenceException();
}
and see if this time the error is caught.
I want to add a new user to newly created database and if this user exists then i will connect to that database.
My code is:
public CreateDatabaseOperationResult CreateDatabase(string databaseName,string username,string password, MongoServer server)
{
CreateDatabaseOperationResult createDatabaseOpResult = new CreateDatabaseOperationResult();
string message = null;
MongoCredentials credentials = new MongoCredentials(username, password);
MongoUser user = new MongoUser(credentials, false);
try
{
if (IsDatabaseNameValid(databaseName, out message))
{
if (server.DatabaseExists(databaseName, admincredentials) == true)
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
MongoUser tempuser = createDatabaseOpResult.Database.FindUser(username);
if (tempuser.Equals(user))
{
//createDatabaseOpResult.DatabaseExists = true;
createDatabaseOpResult.IsOperationSuccessfull = false;
throw new ArgumentException("Database Already exist with different set of credentials ");
}
}
else
{
createDatabaseOpResult.Database = server.GetDatabase(databaseName, credentials);
createDatabaseOpResult.Database.AddUser(user);
//createDatabaseOpResult.DatabaseExists = false;
}
createDatabaseOpResult.IsOperationSuccessfull = true;
}
}
catch (MongoQueryException ex)
{
createDatabaseOpResult.Error = ex;
}
//catch (MongoAuthenticationException ex)
//{
// createDatabaseOpResult.Error = ex;
//}
catch (MongoException ex)
{
createDatabaseOpResult.Error = ex;
}
catch (ArgumentException ex)
{
createDatabaseOpResult.Error = ex;
}
return createDatabaseOpResult;
}
When i use the existing database it connects to that database but when i try to add new use Database.AddUser gives error 'invalid credentials for this database'
Please see the error and reply
Most people use the mongo shell to add and remove users, but if you really want to do it in C# the trick is to use the right credentials depending on what you are trying to do. Assume you have the following two sets of credentials, one for the admin database and one for regular databases:
var adminCredentials = new MongoCredentials("myadminusername", "myadminpassword", true);
var userCredentials = new MongoCredentials("myusername", "myuserpassword");
Note that when creating the adminCredentials you must pass true to the admin parameter.
To test if a database exists requires admin credentials:
if (server.DatabaseExists("mydatabase", adminCredentials))
{
// database exists
}
To add a user requires admin credentials:
var myDatabaseWithAdminCredentials = server.GetDatabase("mydatabase", adminCredentials);
if (myDatabaseWithAdminCredentials.FindUser("myusername") == null)
{
myDatabaseWithAdminCredentials.AddUser(userCredentials);
}
Normally you use regular user credentials to work with a database:
var myDatabaseWithUserCredentials = server.GetDatabase("mydatabase", userCredentials);
var count = myDatabaseWithUserCredentials.GetCollection("mycollection").Count();
Also, keep in mind that each database can have any number of users, so you don't really need to be checking whether the database already exists with a different set of credentials.
I have the code:
public bool RemoveUserFromAdministratorsGroup(UserPrincipal oUserPrincipal, string computer)
{
try
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Machine, computer, null, ContextOptions.Negotiate, _sServiceUser, _sServicePassword);
GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, "Administrators");
oGroupPrincipal.Members.Remove(oUserPrincipal);
oGroupPrincipal.Save();
return true;
}
catch
{
return false;
}
}
It is worked without any excaption. But when i run my app again i see this user in my listview. So, the user wasn't removed.
I have solved the issue without AccountManagment namespace.
public bool RemoveUserFromAdminGroup(string computerName, string user)
{
try
{
var de = new DirectoryEntry("WinNT://" + computerName);
var objGroup = de.Children.Find(Settings.AdministratorsGroup, "group");
foreach (object member in (IEnumerable)objGroup.Invoke("Members"))
{
using (var memberEntry = new DirectoryEntry(member))
if (memberEntry.Name == user)
objGroup.Invoke("Remove", new[] {memberEntry.Path});
}
objGroup.CommitChanges();
objGroup.Dispose();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return false;
}
}
The below solution is for deleting the user with the help of Directory Service ...
using System.DirectoryServices
private DeleteUserFromActiveDirectory(DataRow in_Gebruiker)
{
DirectoryEntry AD = new DirectoryEntry(strPathActiveDirectory ,
strUsername, strPassword)
DirectoryEntry NewUser =
AD.Children.Find("CN=TheUserName", "User");
AD.Children.Remove(NewUser);
AD.CommitChanges();
AD.Close();
}
I don't know what is exactly your problem but coding this way :
try
{
PrincipalContext context = new PrincipalContext(ContextType.Domain, "WM2008R2ENT:389", "dc=dom,dc=fr", "jpb", "passwd");
/* Retreive a user principal
*/
UserPrincipal user = UserPrincipal.FindByIdentity(context, "user1");
/* Retreive a group principal
*/
GroupPrincipal adminGroup = GroupPrincipal.FindByIdentity(context, #"dom\Administrateurs");
foreach (Principal p in adminGroup.Members)
{
Console.WriteLine(p.Name);
}
adminGroup.Members.Remove(user);
adminGroup.Save();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Give me the following exception :
Information about the domain could not be retrieved (1355)
Digging a bit arround that show me that I was running my code on a computer that was not on the target domain. When I run the same code from the server itself it works. It seems that the machine running this code must at least contact the DNS of the target domain.