Search Results

Search found 80 results on 4 pages for 'directoryentry'.

Page 1/4 | 1 2 3 4  | Next Page >

  • Active Directory login - DirectoryEntry inconsistent exception

    - by Pavan Reddy
    I need to validate the LDAP user by checking if there exists such a user name in the specified domain. For this I am using this code - DirectoryEntry entry = new DirectoryEntry("LDAP://" + strDomainController); DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = "SAMAccountName=" + strUserName; SearchResult result = searcher.FindOne(); return (result != null) ? true : false; This is a method in a class library which I intened to reference and use whereever I need this functionality in my project. To test this, I created a simple test application. The test occurs like this - Console.WriteLine(MyClassLib.MyValidateUserMethod("UserName", "Domain",ref strError).ToString()); The problem I am facing is that this works fine when I test it with my testapp but in my project, when I try to use the same method with the same credentials - The DirectoryEntry object throws an "System.DirectoryServices.DirectoryServicesCOMException" exception and the search.Filter fails and throws ex = {"Logon failure: unknown user name or bad password.\r\n"} exception. I have tried impersonation but that doesn't help. Somehow the same method works fine in mytestapp and doesn't work in my project. Both these applications are in my local dev machine. What am I missing? Any ideas?

    Read the article

  • DirectoryEntry to change password: Different behavior between Vista/Server2008

    - by Gnucom
    Hey everyone, On a Vista dev machine I used this code successfully to change user "Administrator" password: directoryEntry.Invoke("SetPassword", "new"); When I moved it over to my Server 2008 dev machine that code did not work, and I was forced to use the following code: directoryEntry.Invoke("ChangePassword", new object[] { "old", "new" }); My question is, why? For both cases, I created my DirectoryEntry object as such: DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); Thanks! 8)

    Read the article

  • Enumerating computers in NT4 domain using WNetEnumResourceW (C++) or DirectoryEntry (C#)

    - by Kevin Davis
    I'm trying to enumerate computers in NT4 domains (not Active Directory) and support Unicode NetBIOS names. According to MSDN, WNetEnumResourceW is the Unicode counterpart of WNetEnumResource which to me would imply that using this would do the trick. However, I have not been able to get Unicode NetBIOS names properly using WNetEnumResourceW. I've also tried the C# rough equivalent DirectoryEntry using the WinNT: provider with no luck on Unicode names either. If I use DirectoryEntry on Active Directory (using the LDAP: provider) I do get Unicode names back. I noticed that during some debugging my code using DirectoryEntry and the WinNT: provider, the exceptions I saw were of type System.Runtime.InteropServices.COMException which tends to make me believe that this is just calling WNetEnumResourceW via COM. This web page implies that for some Net APIs the MS documentation is incomplete and possibly inaccurate which further confuses things. Additionally I've found that using the C# method which certainly results in cleaner, more understandable code also yields incomplete results in enumerating computers in domains\workgroups. Does anyone have any insight on this? Is it possible that computer acting as the WINS server is mangling the name? How would I determine this? Thanks

    Read the article

  • Use default credentials in order to call DirectoryEntry

    - by Copeleto
    Hi, I am working in a Login page and teh logic is like - try { DirectoryEntry LDAPLogin = new DirectoryEntry(ConfigurationSettings.AppSettings ["LDAPPath"].ToString(), Usuario, Txt_Contrasenia.Text.ToString()); if (LDAPLogin.NativeGuid != LDAPLogin.Name) ValidarGrupo(); } catch (Exception exc) { Label_Info.Text = "Sus credenciales no son validas: " + Usuario.ToString() + " " + exc.Message; } If the user enters the rights credentials I call a method ValidarGrupo that implements a lookup in the AD for a group of the user I would like to replace the username and password with UseDefaultCredentials in order to avoid that the user has to enter the username and password and the Login pages use the credentials of the user that is login on the machine.

    Read the article

  • usedefaultcredentials in order to call DirectoryEntry

    - by Copeleto
    Hi, I am working in a Login page and teh logic is like - try { DirectoryEntry LDAPLogin = new DirectoryEntry(ConfigurationSettings.AppSettings ["LDAPPath"].ToString(), Usuario, Txt_Contrasenia.Text.ToString()); if (LDAPLogin.NativeGuid != LDAPLogin.Name) ValidarGrupo(); } catch (Exception exc) { Label_Info.Text = "Sus credenciales no son validas: " + Usuario.ToString() + " " + exc.Message; } If the user enters the rights credentials I call a method ValidarGrupo that implements a lookup in the AD for a group of the user I woould like to replace the username and password with UseDefaultCredentials in order to avoid that the user has to enter the username and password and the Login pages use the credentials of the user that is login on the machine.

    Read the article

  • Issue Querying LDAP DirectoryEntry in ASP.NET

    - by davemackey
    I have users login to my application via Active Directory and then pull from their AD information to garner information about that user like so: Dim ID as FormsIdentity = DirectCast(User.Identity, FormsIdentity) Dim ticket as FormsAuthenticationTicket = ID.Ticket Dim adDirectory as New DirectoryEntry("LDAP://DC=my,DC=domain,DC=com") Dim adTicketID as String = ticket.Name.Substring(0, 5) Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value Session("person_name") = adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value Now, I want to be able to impersonate other users...so that I can "test" the application as them, so I added a textbox and a button to the page and when the button is clicked the text is assigned to a session variable like so: Session("impersonate_user") = TextBox1.Text When the page reloads I check to see if Session("impersonate_user") has a value other than "" and then attempt to query Active Directory using this session variable like so: If CStr(Session("impersonate_user")) <> "" Then Dim adDirectory as New DirectoryEntry(LDAP://DC=my,DC=domain,DC=com") Dim adTicketID as String = CStr(Session("impersonate_user")) Session("people_id") = adDirectory.Children.Find("CN=" & adTicketID).Properties("employeeID").Value Session("person_name")= adDirectory.Children.Find("CN=" & adTicketID).Properties("displayName").Value Else [use the actual ticket.name to get this info.] End If But this doesn't work. Instead, it throws an error on the first Session line stating, "DirectoryServicesCOMException was unhandled by user code There is no such object on the server." Why? I know I'm giving it a valid username! Is something strange happening in the casting of the session? The code is essentially the same between each method except that in one method rather than pulling from ticket.Name I pull from a session variable for the login I'll be looking up with AD.

    Read the article

  • Acquiring AD OU list.

    - by Stephen Murby
    Hi, I am looking to be able to pull a list of current OU's from Active Directory I have been looking at some example code online for sometime, but O don't seem to be able to get this to work. string defaultNamingContext; DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"); defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); DirectorySearcher ouSearch = new DirectorySearcher(rootDSE, "(objectClass=organizationalUnit)", null, SearchScope.Subtree); MessageBox.Show(rootDSE.ToString()); try { SearchResultCollection collectedResult = ouSearch.FindAll(); foreach (SearchResult temp in collectedResult) { comboBox1.Items.Add(temp.Properties["name"][0]); DirectoryEntry ou = temp.GetDirectoryEntry(); } The error I get is There provider does not support searching and cannot search LDAP://RootDSE Any Ideas? for each of those returned search results I want to add them to a combo box. (shouldn't be too hard)

    Read the article

  • Local active directory access and management for development?

    - by Huck
    Hi everybody, In an application we are developpment, we are accessing Active Directory users and groups using the .Net DirectoryEntry and DirectorySearcher classes. Managing the test groups and users during development is getting tedious. I am wondering if there was an easy way to setup a simple local AD in which we could easily create / delete users and assign them or remove them from groups as we want with the DirectoryEntry / DirectorySearcher classes? Thanks.

    Read the article

  • Do I need to replace localhost in the IIS://localhost/MimeMap when reading the Mimemap

    - by Rob
    I'm reading out the mime types from IIS's MimeMap using the command _mimeTypes = new Dictionary<string, string>(); //load from iis store. DirectoryEntry Path = new DirectoryEntry("IIS://localhost/MimeMap"); PropertyValueCollection PropValues = Path.Properties["MimeMap"]; IISOle.MimeMap MimeTypeObj; foreach (var item in PropValues) { // IISOle -> Add reference to Active DS IIS Namespace provider MimeTypeObj = (IISOle.MimeMap)item; _mimeTypes.Add(MimeTypeObj.Extension, MimeTypeObj.MimeType); } Do I need replace the localhost part when I deploy it to my live server? If not, why not and what are the implications of not doing so. Cheers

    Read the article

  • How to get a list of all domains?

    - by AngryHacker
    I'm trying to get all domains that are available in the Windows Login dialog (in the Domain dropdown). I've tried the following code but it only returns the domain I am logged into. Am I missing something? StringCollection domainList = new StringCollection(); try { DirectoryEntry en = new DirectoryEntry("LDAP://"); // Search for objectCategory type "Domain" DirectorySearcher srch = new DirectorySearcher("objectCategory=Domain"); SearchResultCollection coll = srch.FindAll(); // Enumerate over each returned domain. foreach (SearchResult rs in coll) { ResultPropertyCollection resultPropColl = rs.Properties; foreach( object domainName in resultPropColl["name"]) { domainList.Add(domainName.ToString()); } } } catch (Exception ex) { Trace.Write(ex.Message); } return domainList;

    Read the article

  • how to iterate over non-English file names in PHP

    - by Sabya
    I have a directory which contains several files, many of which has non-english name. I am using PHP in Windows 7. I want to list the filename and their content using PHP. Currently I am using DirectoryIterator and file_get_contents. This works for English files names but not for non-English (chinese) file names. For example, I have filenames like "?? ?? ?????????.eml", "hello ??????.eml". DirectoryIterator is not able to get the filename using ->getFilename() file_get_contents is also not able to open even if I hard code the filename in its parameter. How can I do it?

    Read the article

  • How to print all users from windows-group to a textfile?

    - by Tim
    Hello, i'm trying to print all users of a group "Students" to a Textfile "Students.txt". I'm not in a domain, so this does not work: net group "Students" >> students.txt because i get following: This command can be used only on a Windows Domain Controller. Thank you in advance If anybody is interested in a VB.Net solution, i've programmed a Winform solution with a multiline Textbox to copy/paste the members (anyway, thanks for your help): Imports System.DirectoryServices 'first add a refernce to it from .Net Tab' .... Private Sub PrintGroupMember_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim students As List(Of DirectoryEntry) = MembersOfGroup("Students") For Each user As DirectoryEntry In students Me.TextBox1.Text &= user.Name & vbCrLf Next End Sub Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry) Dim members As New List(Of DirectoryEntry) Try Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group") For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable) Dim memberEntry As New DirectoryEntry(member) members.Add(memberEntry) Next End Using Catch ex As Exception MessageBox.Show(ex.ToString) End Try Return members End Function

    Read the article

  • C# Active Directory - Check username / password

    - by Michael G
    I'm using the following code on Windows Vista Ultimate SP1 to query our active directory server to check the user name and password of a user on a domain. public Object IsAuthenticated() { String domainAndUsername = strDomain + @"\" + strUser; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, strPass); SearchResult result; try { //Bind to the native AdsObject to force authentication. DirectorySearcher search = new DirectorySearcher(entry) { Filter = ("(SAMAccountName=" + strUser + ")") }; search.PropertiesToLoad.Add("givenName"); // First Name search.PropertiesToLoad.Add("sn"); // Last Name search.PropertiesToLoad.Add("cn"); // Last Name result = search.FindOne(); if (null == result) { return null; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { return new Exception("Error authenticating user. " + ex.Message); } return user; } the target is using .NET 3.5, and compiled with VS 2008 standard I'm logged in under a domain account that is a domain admin where the application is running. The code works perfectly on windows XP; but i get the following exception when running it on Vista: System.DirectoryServices.DirectoryServicesCOMException (0x8007052E): Logon failure: unknown user name or bad password. at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_AdsObject() at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) at System.DirectoryServices.DirectorySearcher.FindOne() at Chain_Of_Custody.Classes.Authentication.LdapAuthentication.IsAuthenticated() at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) at System.DirectoryServices.DirectoryEntry.Bind() at System.DirectoryServices.DirectoryEntry.get_AdsObject() at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne) at System.DirectoryServices.DirectorySearcher.FindOne() at Chain_Of_Custody.Classes.Authentication.LdapAuthentication.IsAuthenticated() I've tried changing the authentication types, I'm not sure what's going on. See also: http://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory

    Read the article

  • C#, create virtual directory on remote system

    - by sankar
    The following code create only virtual directory on local system , but i need to create on remote sytem ..help me.. Thanks, Sankar DirectoryEntry iisServer; string VirDirSchemaName = "IIsWebVirtualDir"; public DirectoryEntry Connect() { try { if (txtPath.Text.ToLower().Trim() == "localhost") iisServer = new DirectoryEntry("IIS://" + txtPath.Text.Trim() + "/W3SVC/1/Root"); else iisServer = new DirectoryEntry("IIS://" + txtPath.Text + "/Schema/AppIsolated", "XYZ", "xyz"); iisServer.Dispose(); } catch (Exception e) { throw new Exception("Could not connect to: " + txtPath.Text.Trim(), e); } return iisServer; } public void CreateVirtualDirectory(DirectoryEntry iisServer) { DirectoryEntry folderRoot = new DirectoryEntry("IIS://" + txtPath.Text + "/W3SVC/1/Root", "XYZ", "xyz"); folderRoot.RefreshCache(); folderRoot.CommitChanges(); try { DirectoryEntry newVirDir = folderRoot.Children.Add(txtName.Text, VirDirSchemaName); newVirDir.CommitChanges(); newVirDir.Properties["AccessRead"].Add(true); newVirDir.Properties["Path"].Add(@"\\abc\abc"); newVirDir.Invoke("AppCreate", true); newVirDir.CommitChanges(); folderRoot.CommitChanges(); newVirDir.Close(); folderRoot.CommitChanges(); } catch (Exception e) { throw new Exception("Error! Virtual Directory Not Created", e); } } protected void btnCreate_Click(object sender, EventArgs e) { try { CreateVirtualDirectory(Connect()); } catch (Exception ex) { Response.Write(ex.Message); } } protected void Page_Load(object sender, EventArgs e) { }

    Read the article

  • Active Directory List OU's

    - by Stephen Murby
    I have this code currently, string defaultNamingContext; DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"); defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value.ToString(); rootDSE = new DirectoryEntry("LDAP://" + defaultNamingContext); //DirectoryEntry domain = new DirectoryEntry((string)"LDAP://" + defaultNamingContext); DirectorySearcher ouSearch = new DirectorySearcher(rootDSE,"(objectCategory=Organizational-Unit)", null, SearchScope.Subtree); MessageBox.Show(rootDSE.Path.ToString()); try { SearchResultCollection collectedResult = ouSearch.FindAll(); foreach (SearchResult temp in collectedResult) { comboBox1.Items.Add(temp.Properties["name"][0]); DirectoryEntry ou = temp.GetDirectoryEntry(); } } When i use the debugger i can see that rootDSE.Path is infact pointing to the right place, in this case "DC=g-t-p,DC=Local" but the directory searcher doesn't find any results. Can anyone help?

    Read the article

  • How to get foreignSecurityPrincipal from group. using DirectorySearcher

    - by kain64b
    What I tested with 0 results: string queryForeignSecurityPrincipal = "(&(objectClass=foreignSecurityPrincipal)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))"; sidsForeign = GetUsersSidsByQuery(groupName, string.Format(queryForeignSecurityPrincipal, groupPrincipal.DistinguishedName, 0, 0)); public IList<SecurityIdentifier> GetUsersSidsByQuery(string groupName, string query) { List<SecurityIdentifier> results = new List<SecurityIdentifier>(); try{ using (var context = new PrincipalContext(ContextType.Domain, DomainName, User, Password)) { using (var groupPrincipal = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, groupName)) { DirectoryEntry directoryEntry = (DirectoryEntry)groupPrincipal.GetUnderlyingObject(); do { directoryEntry = directoryEntry.Parent; } while (directoryEntry.SchemaClassName != "domainDNS"); DirectorySearcher searcher = new DirectorySearcher(directoryEntry){ SearchScope=System.DirectoryServices.SearchScope.Subtree, Filter=query, PageSize=10000, SizeLimit = 15000 }; searcher.PropertiesToLoad.Add("objectSid"); searcher.PropertiesToLoad.Add("distinguishedname"); using (SearchResultCollection result = searcher.FindAll()) { foreach (var obj in result) { if (obj != null) { var valueProp = ((SearchResult)obj).Properties["objectSid"]; foreach (var atributeValue in valueProp) { SecurityIdentifier value = (new SecurityIdentifier((byte[])atributeValue, 0)); results.Add(value); } } } } } } } catch (Exception e) { WriteSystemError(e); } return results; } I tested it on usual users with query: "(&(objectClass=user)(memberof:1.2.840.113556.1.4.1941:={0})(uSNChanged>={1})(uSNChanged<={2}))" and it is work, I test with objectClass=* ... nothing help... But If I call groupPrincipal.GetMembers,I get all foreing user account from group. BUT groupPrincipal.GetMembers HAS MEMORY LEAK. Any Idea how to fix my query????

    Read the article

  • get local groups and not the primary groups for a domain user

    - by user175084
    i have a code to get the groups a user belongs to. try { DirectoryEntry adRoot = new DirectoryEntry(string.Format("WinNT://{0}", Environment.UserDomainName)); DirectoryEntry user = adRoot.Children.Find(completeUserName, "User"); object obGroups = user.Invoke("Groups"); foreach (object ob in (IEnumerable)obGroups) { // Create object for each group. DirectoryEntry obGpEntry = new DirectoryEntry(ob); listOfMyWindowsGroups.Add(obGpEntry.Name); } return true; } catch (Exception ex) { new GUIUtility().LogMessageToFile("Error in getting User MachineGroups = " + ex); return false; } the above code works fine when i have to find the groups of a local user but for a domain user it returns a value "Domain User" which is kind of wierd as it is a part of 2 local groups. Please can some1 help in solving this mystery. thanks Research I did some finding and got that i am being returned the primary group of the domain user called "Domain User" group but what i actually want is the groups of the local machines the domain user is a part of... i cannot get that.. any suggestions another code using LDAP string domain = Environment.UserDomainName; DirectoryEntry DE = new DirectoryEntry("LDAP://" + domain, null, null, AuthenticationTypes.Secure); DirectorySearcher search = new DirectorySearcher(); search.SearchRoot = DE; search.Filter = "(SAMAccountName=" + completeUserName + ")"; //Searches active directory for the login name search.PropertiesToLoad.Add("displayName"); // Once found, get a list of Groups try { SearchResult result = search.FindOne(); // Grab the records and assign them to result if (result != null) { DirectoryEntry theUser = result.GetDirectoryEntry(); theUser.RefreshCache(new string[] { "tokenGroups" }); foreach (byte[] resultBytes in theUser.Properties["tokenGroups"]) { System.Security.Principal.SecurityIdentifier mySID = new System.Security.Principal.SecurityIdentifier(resultBytes, 0); DirectorySearcher sidSearcher = new DirectorySearcher(); sidSearcher.SearchRoot = DE; sidSearcher.Filter = "(objectSid=" + mySID.Value + ")"; sidSearcher.PropertiesToLoad.Add("distinguishedName"); SearchResult sidResult = sidSearcher.FindOne(); if (sidResult != null) { listOfMyWindowsGroups.Add((string)sidResult.Properties["distinguishedName"][0]); } } } else { new GUIUtility().LogMessageToFile("no user found"); } return true; } catch (Exception ex) { new GUIUtility().LogMessageToFile("Error obtaining group names: " + ex.Message + " Please contact your administrator."); // If an error occurs report it to the user. return false; } this works too but i get the same result "Domain Users" . Please can some1 tell me how to get the local machine groups...????

    Read the article

  • C# How to add an entry to LDAP with multiple object classes

    - by Jarmo
    I'm trying to create a new user record into OpenLDAP with object classes person and uidObject. The problem seems to be that with System.DirectoryServices.DirectoryEntry I've found only a way to add a new entry with one object class, but not a way to add multiple object classes. This C# code DirectoryEntry nRoot = new DirectoryEntry(path); nRoot.AuthenticationType = AuthenticationTypes.None; nRoot.Username = username; nRoot.Password = pwd; try { DirectoryEntry newUser = nRoot.Children.Add("CN=" + "test", "person"); newUser.Properties["cn"].Add("test"); newUser.Properties["sn"].Add("test"); newUser.Properties["objectClass"].Add("uidObject"); // this doesnt't make a difference newUser.Properties["uid"].Add("testlogin"); // this causes trouble newUser.CommitChanges(); } catch (COMException ex) { Console.WriteLine(ex.ErrorCode + "\t" + ex.Message); } ...results in error: -2147016684 The requested operation did not satisfy one or more constraints associated with the class of the object. (Exception from HRESULT: 0x80072014)

    Read the article

  • assign logon scripts to local users

    - by user311130
    Hello, I wrote a c# code that creates new local user DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry group = localMachine.Children.Find("administrators", "group"); DirectoryEntry user = localMachine.Children.Find(accountName, "user"); Console.WriteLine(user.Properties.ToString()); I tried to set the logon script for that user by doing: localMachine.Properties["scriptPath"].Insert(0, "logonScript.vbs"); localMachine.CommitChanges(); same with group or user instances.but the property doesn't exist in any of theses instances (localMachine, group or user). I know that because I did: System.Collections.ICollection col = localMachine.Properties.PropertyNames; foreach (Object ob in col) { Console.WriteLine(ob.ToString()); } Any idea of how to do that in other way?Cheers,

    Read the article

  • IIS: How to get the Metabase path?

    - by Ian Boyd
    i'm trying to get the list of mime types known to an IIS server (which you can see was asked and and answered by me 2 years ago). The copy-pasted answer involves: GetObject("IIS://LocalHost/MimeMap") msdn GetObject("IIS://localhost/mimemap") KB246068 GetObject("IIS://localhost/MimeMap") Scott Hanselman's Blog new DirectoryEntry("IIS://Localhost/MimeMap")) Stack Overflow new DirectoryEntry("IIS://Localhost/MimeMap")) Stack Overflow New DirectoryServices.DirectoryEntry("IIS://localhost/MimeMap") Velocity Reviews You get the idea. Everyone agrees that you use a magical path iis://localhost/mimemap. And this works great, except for the times when it doesn't. The only clue i can find as to why it fails, is from an IIS MVP, Chris Crowe's, blog: string ServerName = "LocalHost"; string MetabasePath = "IIS://" + ServerName + "/MimeMap"; // Note: This could also be something like // string MetabasePath = "IIS://" + ServerName + "/w3svc/1/root"; DirectoryEntry MimeMap = new DirectoryEntry(MetabasePath); There are two clues here: He calls iis://localhost/mimemap the Metabase Path. Which sounds to me like it is some sort of "path" to a "metabase". He says that the path to the metabase could be something else; and he gives an example of what it could be like. Right now i, and the entire planet, are hardcoding the "MetabasePath" as iis://localhost/MimeMap What should it really be? What should the code be doing to construct a valid MetabasePath? Note: i'm not getting an access denied error, the error is the same when you have an invalid MetabasePath, e.g. iis://localhost/SoTiredOfThis

    Read the article

  • What to Return? Error String, Bool with Error String Out, or Void with Exception

    - by Ranger Pretzel
    I spend most of my time in C# and am trying to figure out which is the best practice for handling an exception and cleanly return an error message from a called method back to the calling method. For example, here is some ActiveDirectory authentication code. Please imagine this Method as part of a Class (and not just a standalone function.) bool IsUserAuthenticated(string domain, string user, string pass, out errStr) { bool authentic = false; try { // Instantiate Directory Entry object DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass); // Force connection over network to authenticate object nativeObject = entry.NativeObject; // No exception thrown? We must be good, then. authentic = true; } catch (Exception e) { errStr = e.Message().ToString(); } return authentic; } The advantages of doing it this way are a clear YES or NO that you can embed right in your If-Then-Else statement. The downside is that it also requires the person using the method to supply a string to get the Error back (if any.) I guess I could overload this method with the same parameters minus the "out errStr", but ignoring the error seems like a bad idea since there can be many reasons for such a failure... Alternatively, I could write a method that returns an Error String (instead of using "out errStr") in which a returned empty string means that the user authenticated fine. string AuthenticateUser(string domain, string user, string pass) { string errStr = ""; try { // Instantiate Directory Entry object DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass); // Force connection over network to authenticate object nativeObject = entry.NativeObject; } catch (Exception e) { errStr = e.Message().ToString(); } return errStr; } But this seems like a "weak" way of doing things. Or should I just make my method "void" and just not handle the exception so that it gets passed back to the calling function? void AuthenticateUser(string domain, string user, string pass) { // Instantiate Directory Entry object DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, user, pass); // Force connection over network to authenticate object nativeObject = entry.NativeObject; } This seems the most sane to me (for some reason). Yet at the same time, the only real advantage of wrapping those 2 lines over just typing those 2 lines everywhere I need to authenticate is that I don't need to include the "LDAP://" string. The downside with this way of doing it is that the user has to put this method in a try-catch block. Thoughts? Is there another way of doing this that I'm not thinking of?

    Read the article

  • Active Directoy LDAP - Lock User Account

    - by Germ
    What is the prefered way to lock an Active Directory account? int val = (int)directoryentry.Properties["userAccountControl"].Value; directoryentry.Properties["userAccountControl"].Value = val | 0x0010; vs. directoryentry.InvokeSet("IsAccountLocked", true); Is there a better way?

    Read the article

1 2 3 4  | Next Page >