public async Task <IActionResult> Get2() { IDirectoryContext context = new DirectoryContext(); var user = new ADUser(); user = context.Query <ADUser>() .FirstOrDefault(u => u.FirstName == "rohan"); return(Ok(new JsonResult(new { user.Guid, user.CommonName, user.FirstName, user.LastName, CreatedAt = user.WhenCreated.ToShortDateString(), UpdatedAt = user.WhenChanged.ToShortDateString(), user.Title, user.Office, user.TelephoneNumber, user.MobileNumber, user.Extension, user.EmployeeNumber, user.EmployeeId, user.Department, user.Supervisor, user.TitleDescription, user.Notes, user.Email, }).Value)); }
public static async Task ExecuteAsync() { var config = new LdapConfiguration() .MaxPageSizeIs(1000) .AddMapping(new LdapUserMapping()); config.ConfigureFactory("FADDIV") .UsePort(50000) .AuthenticateBy(System.DirectoryServices.Protocols.AuthType.Negotiate) .AuthenticateAs(CredentialCache.DefaultNetworkCredentials) .ProtocolVersion(3); config.UseStaticStorage(); using var conn = config.ConnectionFactory.GetConnection(); conn.Bind(); using var ctx = new DirectoryContext(conn); var result = await ctx.Query <LdapUser>() .Where(e => e.CommonName == "Abel_Harvey" || e.CommonName == "Adrienne_Schaefer") .Select(e => new { e.DisplayName, e.MemberOf }) .ToListAsync(); foreach (var item in result) { Console.WriteLine("{0} - {1}", item.DisplayName, string.Join("; ", item.MemberOf)); } }
private static void PopulateDirectoryForTests() { var user2Container = DnParser.ParseName(TestUserDirectoryContainer); var user2Prefix = DnParser.ParseRDN(TestUserDirectoryContainer); AddContainerIfNecessary(user2Prefix, user2Container); using (var context = new DirectoryContext()) { AddEntryIfNecessary("CN=PasswordUser," + TestUserDirectoryContainer, "user", context); AddEntryIfNecessary("CN=persontest," + TestUserDirectoryContainer, "user", context); AddEntryIfNecessary("CN=TestUser," + TestUserDirectoryContainer, "user", context); AddEntryIfNecessary("CN=TestUser2," + TestUserDirectoryContainer, "user", context); } var roleContainer = DnParser.ParseName(RolesDirectoryContainer); var rolePrefix = DnParser.ParseRDN(RolesDirectoryContainer); AddContainerIfNecessary(rolePrefix, roleContainer); using (var context = new DirectoryContext()) { IDirectoryAttributes rangeTest = AddEntryIfNecessary("CN=RangeTest," + RolesDirectoryContainer, "group", context); foreach (var kvp in rangeTest.Where(kvp => kvp.Key.StartsWith("member", StringComparison.OrdinalIgnoreCase))) { if (kvp.Value is IEnumerable <string> && ((IEnumerable <string>)kvp.Value).Any()) { Console.WriteLine("RangeTest members already populated"); return; } } var newMembers = new List <string>(); newMembers.AddRange(context.Query <LdsUser>().Take(10000).Select(u => u.DistinguishedName)); rangeTest.Set("member", newMembers); context.Update(rangeTest); } }
private static void EnablePasswordChangesOn389() { using (var context = new DirectoryContext()) { var attributes = context.ListServerAttributes("namingcontexts"); var namingContexts = attributes.GetStrings("namingcontexts"); var configurationDN = namingContexts != null ? namingContexts .FirstOrDefault(s => DnParser.ParseName(s) .Equals("Configuration", StringComparison.OrdinalIgnoreCase)) : null; bool success = false; if (configurationDN != null) { var directoryService = context.Query(configurationDN) .Where(_ => Filter.Equal(_, "cn", "Directory Service", true)) .Select("distinguishedName") .FirstOrDefault(); if (directoryService != null) { directoryService.Set("dSHeuristics", "0000000001001"); context.Update(directoryService); success = true; } } if (!success) { Console.WriteLine("Could not set a password policy"); } } }
public static List <User> GetDomainUser() { var users = new List <User>(); using (var context = new DirectoryContext(Config)) { var adUsers = context.Query(Ldap, objectClass: "User"); foreach (var adUser in adUsers) { if (adUser.GetStrings(Groups).Any(x => x.Contains(OuCentral))) { var login = adUser.Where(x => x.Key.Equals("samaccountname")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var mail = adUser.Where(x => x.Key.Equals("mail")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var fullName = adUser.Where(x => x.Key.Equals("displayname")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var surName = adUser.Where(x => x.Key.Equals("sn")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var initials = adUser.Where(x => x.Key.Equals("initials")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var title = adUser.Where(x => x.Key.Equals("title")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var company = adUser.Where(x => x.Key.Equals("company")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var mobile = adUser.Where(x => x.Key.Equals("mobile")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var phone = adUser.Where(x => x.Key.Equals("telephonenumber")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var department = adUser.Where(x => x.Key.Equals("department")).Select(x => new { x.Key, x.Value }).FirstOrDefault(); var user = new User { Login = login?.Value.ToString().ToLower(), Mail = mail?.Value.ToString(), FullName = fullName?.Value.ToString(), SurName = surName?.Value.ToString(), Initials = initials?.Value.ToString(), Title = title?.Value.ToString(), Company = company?.Value.ToString(), Mobile = mobile?.Value.ToString(), Phone = phone?.Value.ToString(), Department = department?.Value.ToString() }; foreach (var userGroup in adUser.GetStrings(Groups).Where(x => !x.Contains(OuHewDist))) { var group = userGroup .Replace($",{CnUsers}", "") .Replace($",{OuCentral}", "") .Replace($",{OuHewDist}", "") .Replace($",{OuHewGroups}", "") .Replace("CN=", ""); user.Groups.Add(group); } users.Add(user); } } } return(users.OrderBy(x => x.Login).ToList()); }
private static void PopulateDirectory() { using (var context = new DirectoryContext()) { int entryCount = context.Query <LdsUser>().Count(); if (entryCount > 1) { Console.WriteLine("Directory already populated with {0} entries", entryCount); return; } } var employees = new LdsUser[50000]; Parallel.For(0, 50000, i => { var firstName = GetRandomName() + i; var lastName = GetRandomName() + i; var distinguishedName = "CN=" + firstName + " " + lastName + "," + UserDirectoryContainer; var employee = new LdsUser { DistinguishedName = distinguishedName, Employees = new Collection <LdsUser>(), FirstName = firstName, LastName = lastName, EmployeeId = 50 + i, Comment = "This entry was generated by random data.", PhoneNumber = "(123) 555-9857", Title = GetRandomTitle(), Street = "1234 Cool St.", City = GetRandomCity(), Country = GetRandomCountry(), PostalCode = "12345" }; employees[i] = employee; }); var random = new Random(10000); int count = 0; foreach (var employee in employees) { if (count % 7 == 0) { var index = random.Next(0, 50000); var e = employees[index]; if (e != employee && e.Manager == null) { e.Manager = employee.DistinguishedName; employee.Employees.Add(e); } } count++; } var managers = employees.Where(e => e.Manager == null).ToList(); foreach (var employee in managers.AsParallel()) { using (var context = new DirectoryContext()) { context.Add(employee); if (employee.Employees != null && employee.Employees.Count > 0) { foreach (var subordinate in employee.Employees) { if (subordinate.Manager != employee.DistinguishedName) { throw new Exception("What?"); } context.Add(subordinate); } } } Console.WriteLine("{0} added", employee.DistinguishedName); if (employee.Employees == null) { continue; } foreach (var e in employee.Employees) { Console.WriteLine("{0} added", e.DistinguishedName); } } }
private static void PropulateDirectoryForInheritance() { AddContainerIfNecessary("CN", "InheritanceTest"); using (var context = new DirectoryContext()) { int entryCount = context.Query(InheritanceDirectoryContainer).Count(); if (entryCount > 1) { Console.WriteLine("Inheritince Directory already populated with {0} entries", entryCount); return; } } var users = new DirectoryAttributes[10000]; Parallel.For(0, 10000, i => { var firstName = GetRandomName() + i; var lastName = GetRandomName() + i; var distinguishedName = "CN=" + firstName + " " + lastName + "," + InheritanceDirectoryContainer; var user = new DirectoryAttributes(distinguishedName); var objectClass = i % 5 == 0 ? "user" : (i % 3 == 0 ? "organizationalPerson" : "person"); user.Set("objectClass", objectClass); if (objectClass == "user") { user.Set("givenname", firstName) .Set("sn", lastName) .Set("employeeid", 50 + i) .Set("comment", "This entry was generated by random data.") .Set("telephonenumber", "(123) 555-9857") .Set("title", GetRandomTitle()) .Set("street", "1234 Cool St.") .Set("l", GetRandomCity()) .Set("c", GetRandomCountry()) .Set("PostalCode", "12345"); } else if (objectClass == "person") { user.Set("sn", lastName); } else { user.Set("givenname", firstName) .Set("sn", lastName) .Set("employeeid", 50 + i) .Set("comment", "This entry was generated by random data.") .Set("telephonenumber", "(123) 555-9857") .Set("title", GetRandomTitle()) .Set("street", "1234 Cool St.") .Set("l", GetRandomCity()) .Set("c", GetRandomCountry()) .Set("postalCode", "12345"); } users[i] = user; }); foreach (var user in users.AsParallel()) { using (var context = new DirectoryContext()) { context.Add(user); } Console.WriteLine("{0} added", user.DistinguishedName); } }
public ActionResult SearchResultsRead([DataSourceRequest] DataSourceRequest request) { EmployeeSearchAdditionalData employeeSearchAdditionalData = new EmployeeSearchAdditionalData(); TryUpdateModel(employeeSearchAdditionalData); int searchType = FindSearchType(employeeSearchAdditionalData); if (searchType == 0) { return null; } string domain = ConfigurationManager.AppSettings["LDAPDomain"]; string serviceUser = ConfigurationManager.AppSettings["ServiceUser"]; string servicePassword = ConfigurationManager.AppSettings["ServicePassword"]; LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(domain); NetworkCredential myCredentials = new NetworkCredential(serviceUser, servicePassword); LdapConnection connection = new LdapConnection(ldapDirectoryIdentifier, myCredentials, AuthType.Basic); connection.SessionOptions.ProtocolVersion = 3; DirectoryContext context = new DirectoryContext(connection); var orders = context.Query<User>(); switch (searchType) { case 1: orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword))); break; case 2: orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode1)); break; case 3: orders = orders.Where(u => ((u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword))) && (u.CountryCode == employeeSearchAdditionalData.CountryCode1)); break; case 4: if(!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FirstName)) { orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.FirstName))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.LastName)) { orders = orders.Where(u => (u.LastName.Contains(employeeSearchAdditionalData.LastName))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.CountryCode2)) { orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode2)); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.Location)) { orders = orders.Where(u => (u.Location == employeeSearchAdditionalData.Location)); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.PositionTitle)) { orders = orders.Where(u => (u.PositionTitle.Contains(employeeSearchAdditionalData.PositionTitle))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FunctionalArea)) { orders = orders.Where(u => (u.FunctionalArea == employeeSearchAdditionalData.FunctionalArea)); } break; } orders = orders.Where(c => (c.Status == "Actif")); var total = orders.Count(); orders = orders.ApplyOrdersSorting(request.Groups, request.Sorts); var x = orders.ApplyOrdersPaging(request.Page, request.PageSize, total); var result = new DataSourceResult() { Data = x, Total = total }; return Json(result); }
public ActionResult SearchResultsRead([DataSourceRequest] DataSourceRequest request) { EmployeeSearchAdditionalData employeeSearchAdditionalData = new EmployeeSearchAdditionalData(); TryUpdateModel(employeeSearchAdditionalData); int searchType = FindSearchType(employeeSearchAdditionalData); if (searchType == 0) { return(null); } string domain = ConfigurationManager.AppSettings["LDAPDomain"]; string serviceUser = ConfigurationManager.AppSettings["ServiceUser"]; string servicePassword = ConfigurationManager.AppSettings["ServicePassword"]; LdapDirectoryIdentifier ldapDirectoryIdentifier = new LdapDirectoryIdentifier(domain); NetworkCredential myCredentials = new NetworkCredential(serviceUser, servicePassword); LdapConnection connection = new LdapConnection(ldapDirectoryIdentifier, myCredentials, AuthType.Basic); connection.SessionOptions.ProtocolVersion = 3; DirectoryContext context = new DirectoryContext(connection); var orders = context.Query <User>(); switch (searchType) { case 1: orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword))); break; case 2: orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode1)); break; case 3: orders = orders.Where(u => ((u.FirstName.Contains(employeeSearchAdditionalData.Keyword)) || (u.LastName.Contains(employeeSearchAdditionalData.Keyword))) && (u.CountryCode == employeeSearchAdditionalData.CountryCode1)); break; case 4: if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FirstName)) { orders = orders.Where(u => (u.FirstName.Contains(employeeSearchAdditionalData.FirstName))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.LastName)) { orders = orders.Where(u => (u.LastName.Contains(employeeSearchAdditionalData.LastName))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.CountryCode2)) { orders = orders.Where(u => (u.CountryCode == employeeSearchAdditionalData.CountryCode2)); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.Location)) { orders = orders.Where(u => (u.Location == employeeSearchAdditionalData.Location)); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.PositionTitle)) { orders = orders.Where(u => (u.PositionTitle.Contains(employeeSearchAdditionalData.PositionTitle))); } if (!String.IsNullOrWhiteSpace(employeeSearchAdditionalData.FunctionalArea)) { orders = orders.Where(u => (u.FunctionalArea == employeeSearchAdditionalData.FunctionalArea)); } break; } orders = orders.Where(c => (c.Status == "Actif")); var total = orders.Count(); orders = orders.ApplyOrdersSorting(request.Groups, request.Sorts); var x = orders.ApplyOrdersPaging(request.Page, request.PageSize, total); var result = new DataSourceResult() { Data = x, Total = total }; return(Json(result)); }
private byte[] GetActiveDirectoryBinaryImage(string assignedTo) { LdapConnectionFactory factory = new LdapConnectionFactory( ConfigurationManager.AppSettings["LdapServerName"] + ":" + ConfigurationManager.AppSettings["LdapServerPort"]); using (DirectoryContext context = new DirectoryContext(factory.GetConnection(), disposeOfConnection: true)) { var userMapping = new { DistinguishedName = string.Empty, Cn = string.Empty, givenName = string.Empty, ObjectGuid = default(Guid), Members = default(string[]), jpegPhoto = default(byte[]), thumbnailPhoto = default(byte[]) }; List<string> words = assignedTo.Split(' ').ToList(); List<string> wordsToRemove = new List<string>(); foreach (string word in words) { if (word.Length == 1) { wordsToRemove.Add(word); } else { if (word.Last() == '.') { wordsToRemove.Add(word); } } } words = words.Except(wordsToRemove).Distinct().ToList(); List<dynamic> users = new List<dynamic>(); foreach (string word in words) { var user = context.Query(userMapping, ConfigurationManager.AppSettings["LdapFilter"], objectClass: "User") .Where(r => r.Cn.Contains(word) && (r.Cn.StartsWith(word) || r.Cn.EndsWith(word)) && r.thumbnailPhoto != null) .FirstOrDefault(); if (user != null) { users.Add(user); if (users.Count == 2 && users[0].ObjectGuid == users[1].ObjectGuid) { users.RemoveAt(1); break; } } } if (users.Count == 1) { return users[0].thumbnailPhoto; } // Not unique object guids - try some comparisons of results (last resort) dynamic unknownUser = users.FirstOrDefault(x => words.All(y => x.DistinguishedName.Contains(y))); return unknownUser != null ? unknownUser.thumbnailPhoto : null; } }