I am currently working on an application for the company I work for. Part of this application deals with discrepancy reporting and sending emails out when a new discrepancy number has been created. First, it is important to realize that I am redeveloping this application from VB.NET to C#. In the old application the developer chose to read an XML file for a few email addresses. I've read to use alternate options unless the XML file is full of information. This is not intended to be an opinionated question and sorry if this sounds like one. However, I am looking for the correct way of doing this. Should these email addresses be kept in a database table for easy adding/deleting or is there a more standardized way to do this? Please find the current code below.
public void PrepareEmail(string subject, string message)
{
if (MessageBox.Show(#"Are you sure you want to save and send Discrepancy Report: " + tbxDRNumber.Text + #"?\n Click YES to save\n Click NO to cancel", #"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
SendEmail(subject, message);
}
}
public Array AddEmail()
{
string[] dRemail = { "", "", "" };
if (File.Exists(#"\\fs01\Applications\EMS-Manager\DREmailAddresses.xml"))
{
XmlReader emailDocument = new XmlTextReader(#"\\fs01\Applications\EMS-Manager\DREmailAddresses.xml");
while (emailDocument.Read())
{
var type = emailDocument.NodeType;
switch (type)
{
case XmlNodeType.Element:
if (emailDocument.Name == "DRCreatedAddEmail")
{
dRemail[0] = emailDocument.ReadInnerXml();
}
if (emailDocument.Name == "DRActionNeededAddEmail")
{
dRemail[1] = emailDocument.ReadInnerXml();
}
if (emailDocument.Name == "DRPendingAddEmail")
{
dRemail[2] = emailDocument.ReadInnerXml();
}
else
{
MessageBox.Show(#"The file: 'DREmailAddresses.xml' was not found at: \\fs01\Applications\EMS-Manager");
}
break;
}
}
}
return dRemail;
}
public void SendEmail(string subjectText, string bodyText)
{
string[] email = (string[])AddEmail();
//object oOutlook = default(Microsoft.Office.Interop.Outlook.Application);
var oMessage = default(MailItem);
Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application"));
if (subjectText == "New Discrepancy Created. DR" + tbxDRNumber.Text + " ")
{
oMessage.To = email[0];
oMessage.Subject = subjectText;
oMessage.HTMLBody = bodyText;
try
{
oMessage.Send();
}
catch (System.Exception e)
{
MessageBox.Show(#"Send Failed with error: " + e);
throw;
}
}
else if (subjectText == tbxDRNumber.Text + " - Action Needed")
{
oMessage.To = email[1];
oMessage.Subject = subjectText;
oMessage.HTMLBody = bodyText;
try
{
oMessage.Send();
}
catch (System.Exception e)
{
MessageBox.Show(#"Send Failed with error: " + e);
throw;
}
}
else if (subjectText == tbxDRNumber.Text + "DR Pending Approval")
{
oMessage.To = email[2];
oMessage.Subject = subjectText;
oMessage.HTMLBody = bodyText;
try
{
oMessage.Send();
}
catch (System.Exception e)
{
MessageBox.Show(#"Send Failed with error: " + e);
throw;
}
}
}
There isn't necessarily anything wrong with flat file configuration files. It really depends on your use case. How often do the emails in the file change? How many entries are there? Do users of the application edit the list? Are there any complex rules where different addresses will get sent different emails?
If this just a simple mailing list that doesn't change often it's probably fine to use the xml file. You could also just create an email distribution list to send to instead, like ApplicationDiscrepancyReport. That way you can just manage the recipients in active directory. If you stick with the XML email addresses, at the very least I would try to get rid of the hardcoded path to the xml file located on your file share.
If the email addresses change a lot, and are changed by users of the application, I would recommend moving this to a SQL database. If the recipients list is changing frequently you may want to add tracking of when these addresses get edited as well.
I am coding against the OneDrive C# SDK and I was shared a folder which contains multiple files. When accessing the shared folder from the onedrive.com, I am able to view the files -- however when trying to check the Item the children count is always at zero. I am assuming this may be some mix up on my end or permissions issue -- but I just wanted to run it past for a sanity check.
Code:
private async Task GetItem(string id = null)
{
List<string> idsToSearch = new List<string>();
var expandValue = this.clientType == ClientType.Consumer
? "thumbnails,children(expand=thumbnails)"
: "thumbnails,children";
try
{
Item folder;
if (id == null)
{
folder = await this.oneDriveClient.Drive.Root.Request()
.Expand(expandValue).GetAsync(); //root
}
else
{
folder = await this.oneDriveClient.Drive.Items[id].Request()
.Expand(expandValue).GetAsync(); //children of root
}
WriteToFile(new List<string>(new[] { #"Folder: " + folder.Name }));
if (folder.Children.Count == 0)
{
WriteToFile(new List<string>(new[] { #"NO Children" }));
}
else
{
foreach (var child in folder.Children)
{
WriteToFile(new List<string>(new[] {
#"Children of " + folder.Name + " : " + child.Name }));
}
foreach (var item in folder.Children)
{
GetItem(item.Id);
idsToSearch.Add(item.Id);
}
}
}
catch (Exception exception)
{
PresentServiceException(exception);
}
}
I also included a snapshot of the Item object when it reaches the Shared folder object:
Update
After looking through the folder object some more I found that there is RemoteItem which is returning the correct number of child counts -- however does not have any meta data to fetch the child elements.
From the comments on the question it was determined that this is a RemoteItem scenario. Remote items are different to local items - while there's some local metadata that's useful for rendering, the actual metadata for the item lives in another user's drive. Therefore, when such an item is encountered it may be necessary (e.g. if you need to enumerate children of a remote folder) for a subsequent request needs to be made directly for the item in question (using the driveId from the remoteItem.parentReference and the id from remoteItem.Id).
Have a look at this documentation for some more information.
I have looked around a lot of MS Dynamics CRM blogs and SO questions and tried all the solutions but they haven't worked.
The problem I am facing is as follows: I am trying to loop through an excel file with company names and company type. I then find company with matching names in CRM and set values for some custom fields depending on the company type in excel. When I do this though code for a single company it works fine however when I try to run a loop for a large number of companies I am constantly getting:
SecLib::CrmCheckPrivilege failed. Returned hr = -2147220943 on UserId: xxxxxx and PrivilegeType: Read.
The user in question has all privilleges and is an admin user with Read/Write CAL. Also like I pointed out I am able to do the updates for a single record. But when run as a loop that very same record throws an error.
I have been unable to find a solution for this so any help would be much appreciated. I am using MS Dynamics CRM online.
Here's my code:
while (!parser.EndOfData)
{
counter++;
if (counter >= 20)
{
try
{
counter = 0;
context.SaveChanges();
}
catch (Exception exc)
{
while (exc != null)
{
System.Diagnostics.Debug.WriteLine("ERROR: " + exc.Message);
exc = exc.InnerException;
}
continue;
}
}
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
{
//TODO: Process field
company.Add(fields[0]);
category.Add(fields[1]);
var currAccs = context.CreateQuery<Account>().Where(x => x.Name.Contains(fields[0])).ToList();
if (currAccs != null)
{
foreach (var currAcc in currAccs)
{
System.Diagnostics.Debug.WriteLine("Processing: " + currAcc.Name);
currAcc.cir_MediaOwner = false;
currAcc.cir_Agency = false;
currAcc.cir_AdvertiserBrand = false;
if (fields[1].Contains("MO"))
{
currAcc.cir_MediaOwner = true;
}
if (fields[1].Contains("A"))
{
currAcc.cir_Agency = true;
}
if (fields[1].Contains("B"))
{
currAcc.cir_AdvertiserBrand = true;
}
try
{
context.UpdateObject(currAcc);
}
catch (Exception exc)
{
while (exc != null)
{
System.Diagnostics.Debug.WriteLine("ERROR: " + exc.Message);
exc = exc.InnerException;
}
continue;
}
}
}
break;
}
}
It is possible that you have either a Workflow or Plugin Step related to account and create/update message, impersonated with an User without the proper privileges.
For workflows, these could have the option "execute as: the owner of the workflow" (link)
For plug-in steps, these have an option "Run in User's Context" that can be set to a fix user (link)
Research:
Similar Issue with workaround, but not actual solution to existing problem
Similar issue pointing to Microsoft End Point update as culprit
The above links are the most suited to my problem, I have also viewed every similar question listed by Stack Overflow upon creating this post, and only the above referenced questions fit my issue.
Background:
I have been using UserPrincipal.GetAuthorizationGroups for permissions for specific page access running IIS 7.5 on Server 2008 R2 in a C#.NET 4.0 web forms site for 2 and a half years. On May 15 2013 we removed a primary Domain controller running Server 2008 (not r2) and replaced it with a Server 2012 Domain Controller. The next day we started receiving the exception listed below.
I use Principal Context for Forms Authentication. The username/pass handshake succeeds and the auth cookie is properly set, but the subsequent Principal Context call that also calls UserPrincipal.GetAuthorizationGroups fails intermittently. We've resolved a few BPA issues that appeared in the Server 2012 Domain Controller but this has yet to resolve the issue. I also instituted a cron that runs on two separate servers. The two servers will fail at Group SID resolution at different times though they are running the same code base. (A dev environment and production environment).
The issue resolves itself temporarily upon web server reboot, and also on the dev server it will resolve itself after 12 hours of not functioning. The production server will usually stop functioning properly until a reboot without resolving itself.
At this point I am trying to refine the cron targeting specific Domain Controllers in the network as well as the new DC and using the standard LDAP query that is currently failing to yield more targeted exception times. Thus far we've found on one web server that there is no pattern to the days at which it fails, but it will recover within roughly 12 hours. The latest results show Group SID resolution failure between 8AM-8PM then it recovers, several days later it will fail at 8pm and recover at 8am then run fine for another 12 hours and fail again. We are hoping to see if it is just a specific server communication issue or to see if it is the entire set of Domain Controllers.
Exception:
Exception information:
Exception type: PrincipalOperationException
Exception message: An error (1301) occurred while enumerating the groups.
The group's SID could not be resolved.
at System.DirectoryServices.AccountManagement.SidList.TranslateSids(String target, IntPtr[] pSids)
at System.DirectoryServices.AccountManagement.SidList..ctor(SID_AND_ATTR[] sidAndAttr)
at System.DirectoryServices.AccountManagement.AuthZSet..ctor(Byte[] userSid, NetCred credentials, ContextOptions contextOptions, String flatUserAuthority, StoreCtx userStoreCtx, Object userCtxBase)
at System.DirectoryServices.AccountManagement.ADStoreCtx.GetGroupsMemberOfAZ(Principal p)
at System.DirectoryServices.AccountManagement.UserPrincipal.GetAuthorizationGroups()
Question:
Given the above information, does anyone have any idea why decommissioning the Windows Server 2008 (not r2) and implementing a new Server 2012 DC would cause UserPrincipal.GetAuthorizationGroups to fail with the 1301 SID resolution error?
Ideas on eliminating possible causes would also be appreciated.
Disclaimer:
This is my first post to Stack Overflow, I often research here but have not joined in discussions until now. Forgive me if I should have posted elsewhere and feel free to point out better steps before posting.
UPDATE 13-JUN-2013:
On the 12th of June I addressed the possibility of items not disposed causing the issue.
The time frame has been too short to determine if the adjusted code has fixed the issue, but I will continue to update as we work towards a resolution such that maybe with any luck someone here can lend a hand.
Original Code
public bool isGroupMember(string userName, ArrayList groupList)
{
bool valid = false;
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain_server + ".domain.org:636", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer);
// find the user in the identity store
UserPrincipal user =
UserPrincipal.FindByIdentity(
ctx,
userName);
// get the groups for the user principal and
// store the results in a PrincipalSearchResult object
PrincipalSearchResult<Principal> groups =
user.GetAuthorizationGroups();
// display the names of the groups to which the
// user belongs
foreach (Principal group in groups)
{
foreach (string groupName in groupList)
{
if (group.ToString() == groupName)
{
valid = true;
}
}
}
return valid;
}
Updated Code
public bool isGroupMember(string userName, ArrayList groupList, string domain_server)
{
bool valid = false;
try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain_server + ".domain.org:636", null, ContextOptions.Negotiate | ContextOptions.SecureSocketLayer))
{
// find the user in the identity store
UserPrincipal user =
UserPrincipal.FindByIdentity(
ctx,
userName);
try
{
// get the groups for the user principal and
// store the results in a PrincipalSearchResult object
using (PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups())
{
// display the names of the groups to which the
// user belongs
foreach (Principal group in groups)
{
foreach (string groupName in groupList)
{
if (group.ToString() == groupName)
{
valid = true;
}
}
group.Dispose();
}
}//end using-2
}
catch
{
log_gen("arbitrary info");
return false;
}
}//end using-1
}
catch
{
log_gen("arbitrary info");
return false;
}
return valid;
}
I have just run into this same issue and the info I have managed to track down may be helpful; as above we have seen this problem where the domain controller is running Server 2012 - firstly with a customer deployment and then replicated on our own network.
After some experimentation we found that our code would run fine on Server 2012, but hit the 1301 error code when the client system was running Server 2008. The key information about what was happening was found here:
MS blog translated from German
The hotfix referred to in the link below has fixed the problem on our test system
SID S-1-18-1 and SID S-1-18-2 can't be mapped
Hope this is helpful for someone! As many have noted this method call seems rather fragile and we will probably look at implementing some alternative approach before we hit other issues.
Gary
Here's my solution. It seems to work consistently well. Because the problem happens when iterating over the collection, I use a different approach when iterating in order to handle the exception without blocking the actual iterating:
private string[] GetUserRoles(string Username)
{
List<string> roles = new List<string>();
try
{
string domain = Username.Contains("\\") ? Username.Substring(0, Username.IndexOf("\\")) : string.Empty;
string username = Username.Contains("\\") ? Username.Substring(Username.LastIndexOf("\\") + 1) : Username;
if (!string.IsNullOrEmpty(domain) && !string.IsNullOrEmpty(username))
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domain);
UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, username);
if (user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
int count = groups.Count();
for (int i = 0; i < count; i++)
{
IEnumerable<Principal> principalCollection = groups.Skip(i).Take(1);
Principal principal = null;
try
{
principal = principalCollection.FirstOrDefault();
}
catch (Exception e)
{
//Error handling...
//Known exception - sometimes AD can't query a particular group, requires server hotfix?
//http://support.microsoft.com/kb/2830145
}
if (principal!=null && principal is GroupPrincipal)
{
GroupPrincipal groupPrincipal = (GroupPrincipal)principal;
if (groupPrincipal != null && !string.IsNullOrEmpty(groupPrincipal.Name))
{
roles.Add(groupPrincipal.Name.Trim());
}
}
}
}
}
}
catch (Exception e)
{
//Error handling...
}
return roles.ToArray();
}
We experienced this issue when our infrastructure team brought a 2012 Domain Controller online. We also had pre-2012 DCs in place and so we experienced the issue intermittently. We came up with a fix which I wanted to share - it has 2 parts.
First of all, install the hotfix mentioned by Gary Hill. This will resolve the following issue:
An error (1301) occurred while enumerating the groups. The group's SID could not be resolved.
We thought we were home free after installing this hotfix. However, after it was installed we got a different intermittent error. Certain groups that we were interrogating had a null sAMAccountName property. The actual property was populated in Active Directory but it was incorrectly being returned with a null value by the API. I presume this is a bug somewhere in the Active Directory API but I don't know any more than that.
Fortunately we were able to work around the issue by switching to use the group Name property instead of the sAMAccountName property. This worked for us. I believe, that sAMAccountName is effectively deprecated and exists only for backwards compatibility reasons. That being the case it seemed a reasonable change to make.
I enclose a cut down version of our GetRolesForUser code to demonstrate the change in place.
using (var context = new PrincipalContext(ContextType.Domain, _domainName))
{
try
{
var p = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
if (p == null) throw new NullReferenceException(string.Format("UserPrincipal.FindByIdentity returned null for user: {0}, this can indicate a problem with one or more of the AD controllers", username));
var groups = p.GetAuthorizationGroups();
var domain = username.Substring(0, username.IndexOf(#"\", StringComparison.InvariantCultureIgnoreCase)).ToLower();
foreach (GroupPrincipal group in groups)
{
if (!string.IsNullOrEmpty(group.Name))
{
var domainGroup = domain + #"\" + group.Name.ToLower();
if (_groupsToUse.Any(x => x.Equals(domainGroup, StringComparison.InvariantCultureIgnoreCase)))
{
// Go through each application role defined and check if the AD domain group is part of it
foreach (string role in roleKeys)
{
string[] roleMembers = new [] { "role1", "role2" };
foreach (string member in roleMembers)
{
// Check if the domain group is part of the role
if (member.ToLower().Contains(domainGroup))
{
// Cache the Application Role (NOT the AD role)
results.Add(role);
}
}
}
}
}
group.Dispose();
}
}
catch (Exception ex)
{
throw new ProviderException("Unable to query Active Directory.", ex);
}
}
Hope that helps.
I experienced error code 1301 with UserPrincipal.GetAuthorizationGroups while using a brand new virtual development domain which contained 2 workstations and 50 users/groups (many of which are the built in ones). We were running Windows Server 2012 R2 Essentials with two Windows 8.1 Enterprise workstations joined to the domain.
I was able to recursively obtain a list of a user's group membership using the following code:
class ADGroupSearch
{
List<String> groupNames;
public ADGroupSearch()
{
this.groupNames = new List<String>();
}
public List<String> GetGroups()
{
return this.groupNames;
}
public void AddGroupName(String groupName)
{
this.groupNames.Add(groupName);
}
public List<String> GetListOfGroupsRecursively(String samAcctName)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, System.Environment.UserDomainName);
Principal principal = Principal.FindByIdentity(ctx, IdentityType.SamAccountName, samAcctName);
if (principal == null)
{
return GetGroups();
}
else
{
PrincipalSearchResult<Principal> searchResults = principal.GetGroups();
if (searchResults != null)
{
foreach (GroupPrincipal sr in searchResults)
{
if (!this.groupNames.Contains(sr.Name))
{
AddGroupName(sr.Name);
}
Principal p = Principal.FindByIdentity(ctx, IdentityType.SamAccountName, sr.SamAccountName);
try
{
GetMembersForGroup(p);
}
catch (Exception ex)
{
//ignore errors and continue
}
}
}
return GetGroups();
}
}
private void GetMembersForGroup(Principal group)
{
if (group != null && typeof(GroupPrincipal) == group.GetType())
{
GetListOfGroupsRecursively(group.SamAccountName);
}
}
private bool IsGroup(Principal principal)
{
return principal.StructuralObjectClass.ToLower().Equals("group");
}
}
I'm in an environment with multiple domain forests and trusts. I have pretty much this exact same code running on a web site form used to perform user security group lookups across the different domains.
I get this exact error in one of the very large domains where group membership can include 50+ different groups. It works fine in other domains forests.
In my research I found a thread that looks unrelated, but actually has the same stack trace. It is for a remote application running on SBS. The thread mentions that the error is caused by unresolvable SIDS in a group. I believe these would be what are known as "tombstoned" SIDS in active directory. See the thread here.
The thread suggests that finding the tombstoned enteries and removing them from the groups solves the problem. Is it possible the error you are receiving is because SIDS are getting tombstoned every 12 hours by a separate unrelated process? Ultimately, I believe this is a bug in the framework, and that the method should not crash because of tombstoned/unresolvable SIDS.
Good luck!
If anyone is interested this is a VB.NET version of the same code.
Few things you have to do before this code can work
1) You have to reference the assembly System.DirectoryServices
2) Make sure to pass "theusername" variable without the domain, so if your domain is "GIS" and your username is "Hussein" Windows generally authenticate you as GIS\Hussein. So you have to send in just purely the username "Hussein". I worked out the case sensitive stuff.
3) The method GetGroupsNew takes a username and returns a list of groups
4) The method isMemberofnew takes a username and a group and verifies that this user is part of that group or not, this is the one I was interested in.
Private Function getGroupsNew(theusername As String) As List(Of String)
Dim lstGroups As New List(Of String)
Try
Dim allDomains = Forest.GetCurrentForest().Domains.Cast(Of Domain)()
Dim allSearcher = allDomains.[Select](Function(domain)
Dim searcher As New DirectorySearcher(New DirectoryEntry("LDAP://" + domain.Name))
searcher.Filter = [String].Format("(&(&(objectCategory=person)(objectClass=user)(userPrincipalName=*{0}*)))", theusername)
Return searcher
End Function)
Dim directoryEntriesFound = allSearcher.SelectMany(Function(searcher) searcher.FindAll().Cast(Of SearchResult)().[Select](Function(result) result.GetDirectoryEntry()))
Dim memberOf = directoryEntriesFound.[Select](Function(entry)
Using entry
Return New With { _
Key .Name = entry.Name, _
Key .GroupName = DirectCast(entry.Properties("MemberOf").Value, Object()).[Select](Function(obj) obj.ToString()) _
}
End Using
End Function)
For Each user As Object In memberOf
For Each groupName As Object In user.GroupName
lstGroups.Add(groupName)
Next
Next
Return lstGroups
Catch ex As Exception
Throw
End Try
End Function
Private Function isMemberofGroupNew(theusername As String, thegroupname As String) As Boolean
Try
Dim lstGroups As List(Of String) = getGroupsNew(theusername)
For Each sGroup In lstGroups
If sGroup.ToLower.Contains(thegroupname.ToLower) Then Return True
Next
Return False
Catch ex As Exception
Throw
End Try
End Function
we had a similar issue after upgrading the domain controller to 2012. Suddenly my call to user.GetAuthorizationGroups() started failing; I was getting the same exception you were (error 1301). So, I changed it to user.GetGroups(). That worked for a little while, then started failing intermittently on "bad username or password". My latest workaround appears to fix it, for the moment at least. Instead of calling either of those, after constructing the user object, I also construct a group object, one for each group I want to see if the user is a member of. ie, "user.IsMemberOf(group)". That seems to work.
try
{
using (HostingEnvironment.Impersonate())
{
using (var principalContext = new PrincipalContext(ContextType.Domain, "MYDOMAIN"))
{
using (var user = UserPrincipal.FindByIdentity(principalContext, userName))
{
if (user == null)
{
Log.Debug("UserPrincipal.FindByIdentity failed for userName = " + userName + ", thus not authorized!");
isAuthorized = false;
}
if (isAuthorized)
{
firstName = user.GivenName;
lastName = user.Surname;
// so this code started failing:
// var groups = user.GetGroups();
// adGroups.AddRange(from #group in groups where
// #group.Name.ToUpper().Contains("MYSEARCHSTRING") select #group.Name);
// so the following workaround, which calls, instead,
// "user.IsMemberOf(group)",
// appears to work (for now at least). Will monitor for issues.
// test membership in SuperUsers
const string superUsersGroupName = "MyApp-SuperUsers";
using (var superUsers = GroupPrincipal.FindByIdentity(principalContext, superUsersGroupName))
{
if (superUsers != null && user.IsMemberOf(superUsers))
// add to the list of groups this user is a member of
// then do something with it later
adGroups.Add(superUsersGroupName);
}
I had same exception. If someone don't wanna used "LDAP", use this code. Cause I'm had nested groups, I'm used GetMembers(true) and it's little bit longer in time than GetMembers().
https://stackoverflow.com/a/27548271/1857271
or download fix from here: http://support.microsoft.com/kb/2830145
Facing the same problem enumerating authorization groups and the patches noted in the answer did not apply to our web server.
Manually enumerating and ignoring the trouble causing groups is working well, however:
private static bool UserIsMember(string usr, string grp)
{
usr = usr.ToLower();
grp = grp.ToLower();
using (var pc = new PrincipalContext(ContextType.Domain, "DOMAIN_NAME"))
{
using (var user = UserPrincipal.FindByIdentity(pc, usr))
{
var isMember = false;
var authGroups = user?.GetAuthorizationGroups().GetEnumerator();
while (authGroups?.MoveNext() ?? false)
{
try
{
isMember = authGroups.Current.Name.ToLower().Contains(grp);
if (isMember) break;
}
catch
{
// ignored
}
}
authGroups?.Dispose();
return isMember;
}
}
}
I had the problem that if i am connected over VPN and use groups=UserPrincipal.GetGroups() then the Exception occures when iterating over the groups.
If someone want to read all groups of a user there is following possibility (which is faster than using GetGroups())
private IList<string> GetUserGroupsLDAP(string samAccountName)
{
var groupList = new List<string>();
var domainConnection = new DirectoryEntry("LDAP://" + serverName, serverUser, serverUserPassword); // probably you don't need username and password
var samSearcher = new DirectorySearcher();
samSearcher.SearchRoot = domainConnection;
samSearcher.Filter = "(samAccountName=" + samAccountName + ")";
var samResult = samSearcher.FindOne();
if (samResult != null)
{
var theUser = samResult.GetDirectoryEntry();
theUser.RefreshCache(new string[] { "tokenGroups" });
var sidSearcher = new DirectorySearcher();
sidSearcher.SearchRoot = domainConnection;
sidSearcher.PropertiesToLoad.Add("name");
sidSearcher.Filter = CreateFilter(theUser);
foreach (SearchResult result in sidSearcher.FindAll())
{
groupList.Add((string)result.Properties["name"][0]);
}
}
return groupList;
}
private string CreateFilter(DirectoryEntry theUser)
{
string filter = "(|";
foreach (byte[] resultBytes in theUser.Properties["tokenGroups"])
{
var SID = new SecurityIdentifier(resultBytes, 0);
filter += "(objectSid=" + SID.Value + ")";
}
filter += ")";
return filter;
}
Is it possible to read the sharing permissions assigned to a shared folder? I'm able to read in the local security settings programmaticaly (the ones found under Right Click > Properties > Security) no problem. But, I'm wondering how I can read the permissions under Right Click > Sharing and Security... > Permissions
Here is an image of the Permissions I want to read:
Is this possible? I'm running an XP Pro machine if it helps.
Edit:
As per my answer I was able to iterate through all the shares, and get the access you (ie the person running the program) has on that share, but have not found a way to read the permissions others have on that share. This was done using Win32_Share class, however it does not have an option for getting the share permissions of other users. If anyone has any helpful hints that would be a huge help.
I was able to get this working by expanding on the approach taken by Petey B. Also, be sure that the process that runs this code impersonates a privileged user on the server.
using System;
using System.Management;
...
private static void ShareSecurity(string ServerName)
{
ConnectionOptions myConnectionOptions = new ConnectionOptions();
myConnectionOptions.Impersonation = ImpersonationLevel.Impersonate;
myConnectionOptions.Authentication = AuthenticationLevel.Packet;
ManagementScope myManagementScope =
new ManagementScope(#"\\" + ServerName + #"\root\cimv2", myConnectionOptions);
myManagementScope.Connect();
if (!myManagementScope.IsConnected)
Console.WriteLine("could not connect");
else
{
ManagementObjectSearcher myObjectSearcher =
new ManagementObjectSearcher(myManagementScope.Path.ToString(), "SELECT * FROM Win32_LogicalShareSecuritySetting");
foreach(ManagementObject share in myObjectSearcher.Get())
{
Console.WriteLine(share["Name"] as string);
InvokeMethodOptions options = new InvokeMethodOptions();
ManagementBaseObject outParamsMthd = share.InvokeMethod("GetSecurityDescriptor", null, options);
ManagementBaseObject descriptor = outParamsMthd["Descriptor"] as ManagementBaseObject;
ManagementBaseObject[] dacl = descriptor["DACL"] as ManagementBaseObject[];
foreach (ManagementBaseObject ace in dacl)
{
try
{
ManagementBaseObject trustee = ace["Trustee"] as ManagementBaseObject;
Console.WriteLine(
trustee["Domain"] as string + #"\" + trustee["Name"] as string + ": " +
ace["AccessMask"] as string + " " + ace["AceType"] as string
);
}
catch (Exception error)
{
Console.WriteLine("Error: "+ error.ToString());
}
}
}
}
}
I know you can with Windows Home Server:
http://msdn.microsoft.com/en-us/library/bb425864.aspx
You can do this in MMC and most of that is available through code, so it should be possible. If you can't find it there then you should check out Windows API calls. I've seen it done in C++, so it should also be possible in C#. Sorry, I don't have any sample code or other links to provide for those. I'll see if I can dig some up though.
I also just saw this on SO:
how to create shared folder in C# with read only access?
Another good link:
http://social.msdn.microsoft.com/Forums/en/windowssdk/thread/de213b61-dc7e-4f33-acdb-893aa96837fa
The best I could come up with is iterating through all the shares on a machine and reading the permissions you have on the share.
ManagementClass manClass = new ManagementClass(#"\\" +computerName +#"\root\cimv2:Win32_Share"); //get shares
//run through all the shares
foreach (ManagementObject objShare in manClass.GetInstances())
{
//ignore system shares
if (!objShare.Properties["Name"].Value.ToString().Contains('$'))
{
//print out the share name and location
textBox2.Text += String.Format("Share Name: {0} Share Location: {1}", objShare.Properties["Name"].Value, objShare.Properties["Path"].Value) + "\n";
Int32 permissions = 0;
try
{
//get the access values you have
ManagementBaseObject result = objShare.InvokeMethod("GetAccessMask", null, null);
//value meanings: http://msdn.microsoft.com/en-us/library/aa390438(v=vs.85).aspx
permissions = Convert.ToInt32(result.Properties["ReturnValue"].Value);
}
catch (ManagementException me)
{
permissions = -1; //no permissions are set on the share
}
textBox2.Text += "You have permissions: " + permissions + "\n\n";
}
}
If anyone could figure out how to get the permissions others have on the share that would be amazing.