internal dSPropertyCollection(ResultPropertyCollection rp) { _rp = rp; }
public bool IsLoginValid() { bool isValid = false; password_supplied = false; //return true; if (password != "") { this.password_supplied = true; try { string fullUsername = string.Format(@"{0}\{1}", domainName, username); // Fulluser name: e.g. bgsu\jsmith DirectoryEntry entry = new DirectoryEntry(ldapPath, fullUsername, password, at); DirectorySearcher searcher = new DirectorySearcher(entry); searcher.Filter = string.Format("(samAccountName={0})", username); SearchResult result = searcher.FindOne(); isValid = (null != result); SearchResultCollection AllResults = searcher.FindAll(); string sb = ""; foreach (SearchResult myResults in AllResults) { ResultPropertyCollection propcoll = myResults.Properties; foreach (string key in propcoll.PropertyNames) { foreach (object values in propcoll[key]) { // MessageBox.Show(values.ToString()); switch (key) { case "displayname": _FullName = values.ToString(); sb = key.ToString() + " = " + values.ToString(); break; case "givenname": _FirstName = values.ToString(); sb = key.ToString() + " = " + values.ToString(); break; case "sn": _LastName = values.ToString(); sb = key.ToString() + " = " + values.ToString(); break; case "userprincipalname": this._Email = values.ToString(); sb = key.ToString() + " = " + values.ToString(); break; default: sb = key.ToString() + " = " + values.ToString(); // MessageBox.Show(sb); break; } } } } this._AthenticationType = result.GetDirectoryEntry().AuthenticationType.ToString(); } catch { /* Replace this code with logging, etc. */ } } return(isValid); }
public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject) { Type type = resultObject.GetType(); ResultPropertyCollection propertys = new ResultPropertyCollection(); try { string[] writeableMemberNames = ReflectionInfo.GetInstance(type).GetWriteableMemberNames(); Hashtable hashtable = new Hashtable(); int length = writeableMemberNames.Length; for (int i = 0; i < length; i++) { ISetAccessor accessor = dataExchangeFactory.AccessorFactory.SetAccessorFactory.CreateSetAccessor(type, writeableMemberNames[i]); hashtable.Add(writeableMemberNames[i], accessor); } DataTable schemaTable = reader.GetSchemaTable(); int count = schemaTable.Rows.Count; for (int j = 0; j < count; j++) { string memberName = schemaTable.Rows[j][0].ToString(); ISetAccessor setAccessor = hashtable[memberName] as ISetAccessor; ResultProperty property = new ResultProperty { ColumnName = memberName, ColumnIndex = j }; if (resultObject is Hashtable) { property.PropertyName = memberName; propertys.Add(property); } Type memberTypeForSetter = null; if (setAccessor == null) { try { memberTypeForSetter = ObjectProbe.GetMemberTypeForSetter(resultObject, memberName); } catch { _logger.Error("The column [" + memberName + "] could not be auto mapped to a property on [" + resultObject.ToString() + "]"); } } else { memberTypeForSetter = setAccessor.MemberType; } if ((memberTypeForSetter != null) || (setAccessor != null)) { property.PropertyName = (setAccessor != null) ? setAccessor.Name : memberName; if (setAccessor != null) { property.Initialize(dataExchangeFactory.TypeHandlerFactory, setAccessor); } else { property.TypeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(memberTypeForSetter); } property.PropertyStrategy = PropertyStrategyFactory.Get(property); propertys.Add(property); } } } catch (Exception exception) { throw new DataMapperException("Error automapping columns. Cause: " + exception.Message, exception); } return(propertys); }
private static IEnumerable <DFSShare> Get_DomainDFSShareV1(Args_Get_DomainSearcher args = null) { if (args == null) { args = new Args_Get_DomainSearcher(); } var DFSSearcher = GetDomainSearcher.Get_DomainSearcher(args); if (DFSSearcher != null) { var DFSShares = new List <DFSShare>(); ResultPropertyCollection Properties = null; DFSSearcher.Filter = @"(&(objectClass=fTDfs))"; try { ResultPropertyValueCollection Pkt = null; var Results = DFSSearcher.FindAll(); if (Results != null) { foreach (SearchResult result in Results) { Properties = result.Properties; var RemoteNames = Properties[@"remoteservername"]; Pkt = Properties[@"pkt"]; if (RemoteNames != null) { foreach (string name in RemoteNames) { try { if (name.Contains(@"\")) { DFSShares.Add(new DFSShare { Name = Properties[@"name"][0] as string, RemoteServerName = name.Split(new char[] { '\\' })[2] }); } } catch (Exception e) { Logger.Write_Verbose([email protected]"[Get-DomainDFSShare] Get-DomainDFSShareV1 error in parsing DFS share : {e}"); } } } try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose([email protected]"[Get-DomainDFSShare] Get-DomainDFSShareV1 error disposing of the Results object: {e}"); } } DFSSearcher.Dispose(); if (Pkt != null && Pkt[0] != null) { var servers = Parse_Pkt(Pkt[0] as byte[]); if (servers != null) { foreach (var server in servers) { // If a folder doesn't have a redirection it will have a target like // \\null\TestNameSpace\folder\.DFSFolderLink so we do actually want to match // on 'null' rather than $Null if (server != null && server != @"null" && DFSShares.Any(x => x.RemoteServerName == server)) { DFSShares.Add(new DFSShare { Name = Properties[@"name"][0] as string, RemoteServerName = server }); } } } } } } catch (Exception e) { Logger.Write_Warning([email protected]"[Get-DomainDFSShare] Get-DomainDFSShareV1 error : {e}"); } return(DFSShares); } return(null); }
static lccLDAPObjectClass lccFFindLDAPobject(string lccParamSSearchOU, string lccParamSId, string lccParamSObjectType) { lccLDAPObjectClass lccReturn = new lccLDAPObjectClass(); DirectoryEntry lccDESearchOU = null; DirectorySearcher lccDSSearcher = null; SearchResultCollection lccSRCCollection = null; ResultPropertyCollection lccRPCCollection = null; try { lccDESearchOU = new DirectoryEntry(lccParamSSearchOU); lccDSSearcher = null; lccDSSearcher = new DirectorySearcher(lccDESearchOU); lccDSSearcher.PageSize = 1; lccDSSearcher.SizeLimit = 1; //lccDSSearcher.PropertiesToLoad.Add("sAMAccountName"); lccDSSearcher.PropertiesToLoad.Add("cn"); if (lccParamSObjectType.Equals("Group") == true) { lccDSSearcher.PropertiesToLoad.Add("member"); } lccDSSearcher.PropertiesToLoad.Add("sn"); lccDSSearcher.PropertiesToLoad.Add("distinguishedname"); lccDSSearcher.SearchScope = SearchScope.Subtree; lccDSSearcher.Filter = "(samAccountName=" + lccParamSId + ")"; if (lccDSSearcher.FindOne() != null) { lccSRCCollection = lccDSSearcher.FindAll(); if (lccSRCCollection.Count == 0) { lccReturn.lccIReturnVal = 3; lccFLogInfo(0, "[lccFFindLDAPobject] No objects returned from Active Directory for [" + lccParamSId + "]"); } else { try { foreach (SearchResult aSearchResult in lccSRCCollection) { if (lccSCSettings.lccBDebugMode == true) { lccFLogInfo(0, "[lccFFindLDAPobject] Object Path: " + aSearchResult.Path); } lccRPCCollection = aSearchResult.Properties; if (lccRPCCollection != null) { foreach (String aPropertyName in lccRPCCollection.PropertyNames) { if (lccParamSObjectType.Equals("Group") == true) { if (aPropertyName.CompareTo("member") == 0) { foreach (object aCollection in lccRPCCollection[aPropertyName]) { lccFLogInfo(0, "[lccFModifyGroup] Found Member [" + aCollection.ToString() + "]"); lccReturn.lccALMembers.Add(aCollection.ToString()); } } } /* * if (aPropertyName.CompareTo("cn") == 0) * { * foreach (object aCollection in lccRPCCollection[aPropertyName]) * { * lccFLogInfo(0, "[lccFModifyGroup] Found Object CN [" + aCollection.ToString() + "]"); * } * } */ if (aPropertyName.CompareTo("distinguishedname") == 0) { foreach (object aCollection in lccRPCCollection[aPropertyName]) { if (lccSCSettings.lccBDebugMode == true) { lccFLogInfo(0, "[lccFFindLDAPobject] Found Object DN [" + aCollection.ToString() + "]"); } lccReturn.lccSDN = aCollection.ToString(); } } } } } } catch (Exception lccExceptionCollectionSearchResults) { lccReturn.lccIReturnVal = 3; lccFLogInfo(0, "[lccFFindLDAPobject] Object attributes failed to read. ERROR: " + lccExceptionCollectionSearchResults.Message); } } } else { lccReturn.lccIReturnVal = 3; lccFLogInfo(0, "[lccFFindLDAPobject] No object found for [" + lccParamSId + "]"); } } catch (Exception lccException) { lccFLogInfo(0, "[lccFFindLDAPobject] ERROR: " + lccException.Message); } return(lccReturn); }
public void ProcessRequest(HttpContext context) { /*string returnStr = ""; * SqlConnection mycon = null; * SqlCommand com = null; * SqlDataReader dr = null; * context.Response.ContentType = "text/plain"; * //context.Response.Write("Hello World"); * string userStr = context.Request.Form["user"]; * userStr = userStr.Trim(); * string pwdStr = context.Request.Form["password"]; * pwdStr = pwdStr.Trim(); * string checkedStr = context.Request.Form["checked"]; * mycon = DBConnect.ConnectSQLServer(); * try * { * mycon.Open(); * string SQLText = "select user_id,name,username,opid,dept,telephone,email,weixin_no from User_Manage where (username='******' or email='" + userStr.ToLower() + "' or opid='" + userStr.ToUpper() + "') and password='******' and user_state='1'"; * com = mycon.CreateCommand(); * com.CommandText = SQLText; * dr = com.ExecuteReader(); * int userCount = 0; * while (dr.Read()) * { * userCount++; * //将用户信息保存至session中,客户端网页关闭后自动清除 * context.Session["user_id"] = dr[0].ToString(); * context.Session["Name"] = dr[1].ToString(); * context.Session["UserName"] = dr[2].ToString(); * context.Session["OPID"] = dr[3].ToString(); * context.Session["Department"] = dr[4].ToString(); * context.Session["Telephone"] = dr[5].ToString(); * context.Session["Email"] = dr[6].ToString(); * context.Session["WeiXin"] = dr[7].ToString(); * break; * } * if (userCount > 0) * { * returnStr = "OK"; * if (checkedStr.ToLower() == "true" && object.Equals(context.Request.Cookies["UserName"], null) && object.Equals(context.Request.Cookies["Password"], null)) * { * context.Response.Cookies["UserName"].Value = userStr; * context.Response.Cookies["Password"].Value= pwdStr; * context.Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1); * context.Response.Cookies["Password"].Expires = DateTime.Now.AddDays(1); * } * } * else * returnStr = "登陆账号密码错误或用户不存在!"; * } * catch(Exception msg) * { * returnStr = msg.Message; * } * finally * { * if (dr != null) * dr.Close(); * if (mycon.State != System.Data.ConnectionState.Closed) * mycon.Close(); * mycon = null; * }*/ string returnStr = ""; SqlConnection mycon = null; SqlCommand com = null; SqlDataReader dr = null; context.Response.ContentType = "text/plain"; string nameStr = "", opidStr = "", deptStr = "", deptDesStr = "", postStr = "", telephoneStr = "", emailStr = ""; string create_timeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); string update_timeStr = create_timeStr; bool LoginFlag = false; //context.Response.Write("Hello World"); string userStr = context.Request.Form["user"]; userStr = userStr.Trim().ToLower(); if (!userStr.Contains("acn\\")) { userStr = "acn\\" + userStr; } string pwdStr = context.Request.Form["password"]; pwdStr = pwdStr.Trim(); string checkedStr = context.Request.Form["checked"]; //DA验证登陆 using (DirectoryEntry adsEntry = new DirectoryEntry(ConfigurationManager.AppSettings["DAVerify"].ToString(), userStr, pwdStr, AuthenticationTypes.Secure)) { using (DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry)) { adsSearcher.Filter = "(sAMAccountName=" + userStr.Substring(4) + ")"; adsSearcher.PropertiesToLoad.Add("msrtcsip-userenabled"); adsSearcher.PropertiesToLoad.Add("mobile"); adsSearcher.PropertiesToLoad.Add("mail"); adsSearcher.PropertiesToLoad.Add("title"); try { SearchResult adsSearchResult = adsSearcher.FindOne(); ResultPropertyCollection rprops = adsSearchResult.Properties; foreach (string name in rprops.PropertyNames) { foreach (object vl in rprops[name]) { switch (name) { case "msrtcsip-userenabled": LoginFlag = Convert.ToBoolean(vl.ToString()); break; case "mobile": telephoneStr = vl.ToString(); break; case "mail": emailStr = vl.ToString().ToLower(); break; case "title": postStr = vl.ToString(); break; } } } ServiceReference1.Service1SoapClient getUserClient = new ServiceReference1.Service1SoapClient(); DataTable dt = getUserClient.GeteOAUserForDCC(userStr); foreach (DataRow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { switch (column.Caption) { case "var_hrid": opidStr = row[column].ToString().ToUpper(); break; case "var_name": nameStr = row[column].ToString(); break; case "var_dept": deptStr = row[column].ToString().ToUpper(); break; case "var_deptname": deptDesStr = row[column].ToString().ToUpper(); break; } } } } catch (Exception ex) { returnStr = ex.Message; } finally { adsEntry.Close(); } } } StringBuilder sb = new StringBuilder(); if (LoginFlag && returnStr == "") { mycon = DBConnect.ConnectSQLServer(); //DA认证成功后,查询数据表里是否有维护上面查询到的部门和职务,若没有则插入对应的数据表并返回部门或职务对应的id号,并将用户信息更新到数据表里,同时初始化权限 try { mycon.Open(); com = mycon.CreateCommand(); //部门 if (deptStr != "") { sb.Clear(); sb.Append("if not exists(select id from Department_Manage where dept_code='" + deptStr + "')\n"); sb.Append("begin\n"); sb.Append("insert into Department_Manage(dept,dept_code,create_by,create_time,update_by,update_time)\n"); sb.Append("values('" + deptDesStr + "','" + deptStr + "',(select max(user_id) from User_Manage)+1,'" + create_timeStr + "',(select max(user_id) from User_Manage)+1,'" + update_timeStr + "')\n"); sb.Append("end"); com.CommandText = sb.ToString(); com.ExecuteNonQuery(); com.CommandText = "select id from Department_Manage where dept_code='" + deptStr + "'"; deptStr = com.ExecuteScalar().ToString(); } //职务 if (postStr != "") { sb.Clear(); sb.Append("if not exists(select id from Job_Manage where post='" + postStr + "')\n"); sb.Append("begin\n"); sb.Append("insert into Job_Manage(post,create_by,create_time,update_by,update_time)\n"); sb.Append("values('" + postStr + "',(select max(user_id) from User_Manage)+1,'" + create_timeStr + "',(select max(user_id) from User_Manage)+1,'" + update_timeStr + "')\n"); sb.Append("end"); com.CommandText = sb.ToString(); com.ExecuteNonQuery(); com.CommandText = "select id from Job_Manage where post='" + postStr + "'"; postStr = com.ExecuteScalar().ToString(); } //将用户插入数据表或更新用户信息 userStr = userStr.Substring(4); sb.Clear(); sb.Append("if not exists(select user_id from User_Manage where username='******' or opid='" + opidStr + "')\n"); sb.Append("begin\n"); sb.Append("insert into User_Manage(name,username,opid,password,dept,post,telephone,email,weixin_no,user_state,create_by,create_time,update_by,update_time)\n"); sb.Append("values(N'" + nameStr + "','" + userStr + "','" + opidStr + "','" + pwdStr + "','" + deptStr + "','" + postStr + "','" + telephoneStr + "','" + emailStr + "','','1',(select max(user_id) from User_Manage)+1,'" + create_timeStr + "',(select max(user_id) from User_Manage)+1,'" + update_timeStr + "')\n"); sb.Append("end\n"); sb.Append("else\n"); sb.Append("begin\n"); sb.Append("update User_Manage set name='" + nameStr + "',username='******',password='******',opid='" + opidStr + "',dept='" + deptStr + "',post='" + postStr + "',telephone='" + telephoneStr + "',email='" + emailStr + "',update_time='" + update_timeStr + "' where (username='******' or opid='" + opidStr + "') and user_state='1'\n"); sb.Append("end\n"); sb.Append("select @@IDENTITY"); com.CommandText = sb.ToString(); string ret = com.ExecuteScalar().ToString(); //初始化用户权限 if (ret != "" && ret != null) { sb.Clear(); sb.Append("insert into Auth_Manage(user_id,menu_id,power_no,power_desc,create_by,create_time,update_by,update_time)\n"); sb.Append("select '" + ret + "',menu_id,init_power,'','" + ret + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','" + ret + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' from Menu_Manage"); com.CommandText = sb.ToString(); sb.Clear(); com.ExecuteNonQuery(); } //将用户信息保存至session中,客户端网页关闭后自动清除 string SQLText = "select user_id,name,username,opid,dept,telephone,email,weixin_no from User_Manage where (username='******' or opid='" + opidStr + "') and user_state='1'"; com.CommandText = SQLText; dr = com.ExecuteReader(); int userCount = 0; while (dr.Read()) { userCount++; //将用户信息保存至session中,客户端网页关闭后自动清除 context.Session["user_id"] = dr[0].ToString(); context.Session["Name"] = dr[1].ToString(); context.Session["UserName"] = dr[2].ToString(); context.Session["OPID"] = dr[3].ToString(); context.Session["Department"] = dr[4].ToString(); context.Session["Telephone"] = dr[5].ToString(); context.Session["Email"] = dr[6].ToString(); context.Session["WeiXin"] = dr[7].ToString(); break; } returnStr = "OK"; } catch (Exception msg) { returnStr = msg.Message; } finally { if (dr != null) { dr.Close(); dr = null; } if (mycon.State != ConnectionState.Closed) { mycon.Close(); } mycon = null; } } context.Response.Write(returnStr); }
public static string GetValue(this ResultPropertyCollection coll, string key) { return(coll[key].Count > 0 ? coll[key][0].ToString() : null); }
static void Main(string[] args) { string ldapCookie = "adsync-cookie.dat"; string str_dcName = "dc01.isengard.local"; bool firstRun = true; _nullSids = new ConcurrentDictionary <string, byte>(); _guidMap = new ConcurrentDictionary <string, string>(); _baseGuids = new ConcurrentDictionary <string, string>(); _baseGuids.TryAdd("user", "bf967aba-0de6-11d0-a285-00aa003049e2"); _baseGuids.TryAdd("computer", "bf967a86-0de6-11d0-a285-00aa003049e2"); _baseGuids.TryAdd("group", "bf967a9c-0de6-11d0-a285-00aa003049e2"); _baseGuids.TryAdd("domain", "19195a5a-6da0-11d0-afd3-00c04fd930c9"); _baseGuids.TryAdd("gpo", "f30e3bc2-9ff0-11d1-b603-0000f80367c1"); System.DirectoryServices.DirectoryEntry rootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://rootDSE"); System.Net.NetworkCredential cr = new System.Net.NetworkCredential(@"Administrator", "1qazxsw2..", "isengard.local"); LdapConnection connection = new LdapConnection(str_dcName); connection.Credential = cr; connection.Bind(); DirectorySynchronization sync = new DirectorySynchronization(); DirectorySearcher src2 = new DirectorySearcher(); if (File.Exists(ldapCookie)) { byte[] byteCookie = File.ReadAllBytes(ldapCookie); sync.ResetDirectorySynchronizationCookie(byteCookie); firstRun = false; } src2.DirectorySynchronization = sync; foreach (SearchResult res in src2.FindAll()) { ResultPropertyCollection fields = res.Properties; foreach (String ldapField in fields.PropertyNames) { foreach (Object myCollection in fields[ldapField]) { if (!firstRun) { if (ldapField == "distinguishedname") { Console.WriteLine(String.Format("[+] DN = {0}", myCollection)); } if (ldapField == "ntsecuritydescriptor") { Console.WriteLine("[+] Detected ACL Change: "); var aces = new List <ACL>(); var newDescriptor = new ActiveDirectorySecurity(); newDescriptor.SetSecurityDescriptorBinaryForm((byte[])myCollection); // todo add owner foreach (ActiveDirectoryAccessRule ace in newDescriptor.GetAccessRules(true, true, typeof(SecurityIdentifier))) { //Ignore null aces if (ace == null) { continue; } //Ignore Deny aces if (!ace.AccessControlType.Equals(AccessControlType.Allow)) { continue; } //Resolve the principal in the ACE var principal = GetAcePrincipal(ace, "isengard.local"); string name = new System.Security.Principal.SecurityIdentifier(principal).Translate(typeof(System.Security.Principal.NTAccount)).ToString(); //If its null, we don't care so move on if (principal == null) { continue; } //Interesting Domain ACEs - GenericAll, WriteDacl, WriteOwner, Replication Rights, AllExtendedRights var rights = ace.ActiveDirectoryRights; var objectAceType = ace.ObjectType.ToString(); if (rights.HasFlag(ActiveDirectoryRights.GenericAll)) { if (objectAceType == AllGuid || objectAceType == "") { aces.Add(new ACL { AceType = "", RightName = "GenericAll", PrincipalName = name, PrincipalType = principal }); } //GenericAll includes every other flag, so continue here so we don't duplicate privs continue; } if (rights.HasFlag(ActiveDirectoryRights.WriteDacl)) { aces.Add(new ACL { AceType = "", RightName = "WriteDacl", PrincipalName = name, PrincipalType = principal }); } if (rights.HasFlag(ActiveDirectoryRights.WriteOwner)) { aces.Add(new ACL { AceType = "", RightName = "WriteOwner", PrincipalName = name, PrincipalType = principal }); } if (rights.HasFlag(ActiveDirectoryRights.ExtendedRight)) { if (objectAceType == "1131f6aa-9c07-11d1-f79f-00c04fc2dcd2") { aces.Add(new ACL { AceType = "GetChanges", RightName = "ExtendedRight", PrincipalName = name, PrincipalType = principal }); } else if (objectAceType == "1131f6ad-9c07-11d1-f79f-00c04fc2dcd2") { aces.Add(new ACL { AceType = "GetChangesAll", RightName = "ExtendedRight", PrincipalName = name, PrincipalType = principal }); } else if (objectAceType == AllGuid || objectAceType == "") { aces.Add(new ACL { AceType = "All", RightName = "ExtendedRight", PrincipalName = name, PrincipalType = principal }); } } } foreach (var ace in aces) { Console.WriteLine(String.Format("[+] {0} has {1}", ace.PrincipalName, ace.RightName)); } ; } if (ldapField == "useraccountcontrol") { Console.WriteLine(String.Format("[+] UAC edited: {0}", myCollection)); } } } } } File.WriteAllBytes(ldapCookie, sync.GetDirectorySynchronizationCookie()); }
public LDAPUserObjectLink GetUserObjectLinkByName(string accountName, string userName = "", string password = "") { LDAPUserObjectLink userObjeLink = new LDAPUserObjectLink(); DirectoryEntry ldapConnector = null; DirectorySearcher ldapSearcher = null; //userName = AppConfig.DomainUsername; //password = AppConfig.DomainPassword; try { if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(m_ldappath)) { //property = null; } else { ldapConnector = new DirectoryEntry(m_ldappath, userName, password); ldapSearcher = new DirectorySearcher(ldapConnector); ldapSearcher.Filter = String.Format(LDAP_FILTER_USER, accountName); ldapSearcher.PropertiesToLoad.Add("samaccountname"); ldapSearcher.PropertiesToLoad.Add("company"); ldapSearcher.PropertiesToLoad.Add("mail"); ldapSearcher.PropertiesToLoad.Add("department"); ldapSearcher.PropertiesToLoad.Add("cn"); ldapSearcher.PropertiesToLoad.Add("domain"); ldapSearcher.PropertiesToLoad.Add("givenname"); //First Name ldapSearcher.PropertiesToLoad.Add("sn"); //Last Name SearchResultCollection colResult = ldapSearcher.FindAll(); foreach (SearchResult result in colResult) { ResultPropertyCollection props = result.Properties; foreach (string propName in props.PropertyNames) { //Loop properties and pick out company,department string tmp = (string)props[propName][0]; } } //SearchResult searchResult = ldapSearcher.FindOne(); foreach (SearchResult result in colResult) { if (result.Properties["samaccountname"][0].ToString().Trim().Length > 0) { List <string> lstOU = null; lstOU = ExtractUserOU(result.Path); string strAccName = null; string strFirstName = null; string strLastName = null; string strDomain = null; string strDepart = null; string strDisp = null; string strMail = null; string strComp = null; if (result.Properties.Contains("sAMAccountName")) { strAccName = result.Properties["sAMAccountName"][0].ToString(); } if (result.Properties.Contains("givenname")) { strFirstName = result.Properties["givenname"][0].ToString(); } if (result.Properties.Contains("sn")) { strLastName = result.Properties["sn"][0].ToString(); } if (result.Properties.Contains("domain")) { strDomain = result.Properties["domain"][0].ToString(); } else if (ldapConnector.Name != null && ldapConnector.Name.Length > 3) { strDomain = ldapConnector.Name.Substring(3); } if (result.Properties.Contains("department")) { strDepart = result.Properties["department"][0].ToString(); } if (result.Properties.Contains("cn")) { strDisp = result.Properties["cn"][0].ToString(); } if (result.Properties.Contains("mail")) { strMail = result.Properties["mail"][0].ToString(); } if (result.Properties.Contains("company")) { strComp = result.Properties["company"][0].ToString(); } LDAPUserObject objUser = new LDAPUserProperties( strAccName, strFirstName, strLastName, strDomain, strDepart, strDisp, strMail, strComp, lstOU); userObjeLink.AddLast(objUser); } } colResult.Dispose(); } } catch (Exception ex) { throw ex; } finally { if (null != ldapSearcher) { ldapSearcher.Dispose(); } if (null != ldapConnector) { ldapConnector.Dispose(); } } return(userObjeLink); }
private void LOGIN() { if (TXT_KULLANICI_ADI.Text == null || TXT_KULLANICI_ADI.Text == "") { AlertBox.Show("<br> Kullanıcı Adı Giriniz! </b> ", MessageBoxIcon.Stop, alignment: System.Drawing.ContentAlignment.MiddleCenter, autoCloseDelay: 1000); return; } if (TXT_SIFRE.Text == null || TXT_SIFRE.Text == "") { AlertBox.Show("<br> Şifre Giriniz! </b> ", MessageBoxIcon.Stop, alignment: System.Drawing.ContentAlignment.MiddleCenter, autoCloseDelay: 1000); return; } try { DirectoryEntry de = GetDirectoryObject(TXT_KULLANICI_ADI.Text.Trim(), TXT_SIFRE.Text.Trim()); DirectorySearcher deSearch = new DirectorySearcher() { SearchRoot = de, Filter = string.Format("(&(objectClass=user)(SAMAccountName={0}))", TXT_KULLANICI_ADI.Text.Trim()) }; deSearch.PropertiesToLoad.Add("mail"); deSearch.PropertiesToLoad.Add("userPrincipalName"); SortOption Srt = new SortOption("mail", System.DirectoryServices.SortDirection.Ascending); deSearch.Sort = Srt; //Sonuçları bir değişkene atalım. var test = deSearch.FindAll(); SearchResultCollection Results = deSearch.FindAll(); if (Results != null) { foreach (SearchResult Result in Results) { ResultPropertyCollection Rpc = Result.Properties; Application.Session._KULLANICI_MAIL_ADRESI = Rpc["userPrincipalName"][0].ToString(); } if (Application.Session._KULLANICI_MAIL_ADRESI == null) { AlertBox.Show("<br> Bilgiler Doğrulanamadı! </b> ", MessageBoxIcon.Stop, alignment: System.Drawing.ContentAlignment.MiddleCenter, autoCloseDelay: 1000); return; } ; using (SqlConnection SqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection_VISION"].ToString())) { SqlCon.Open(); using (SqlCommand Cmd = new SqlCommand("SELECT top 1 * FROM ADM_KULLANICI WHERE [email protected]_ADRESI and AKTIF='True' ", SqlCon)) { Cmd.Parameters.AddWithValue("@MAIL_ADRESI", Application.Session._KULLANICI_MAIL_ADRESI); SqlDataReader rdr = Cmd.ExecuteReader(); while (rdr.Read()) { Application.Session._KULLANICI_ID = rdr["ID"].ToString(); Application.Session._KULLANICI_ADI_SOYADI = rdr["ADI"].ToString() + " " + rdr["SOYADI"].ToString(); Application.Session._SIRKET_KODU = rdr["SIRKET_KODU"].ToString(); Application.Session._DEPARTMANI = rdr["DEPARTMANI"].ToString(); Application.Session._GOREVI = rdr["GOREVI"].ToString(); Application.Session._UNVANI = rdr["UNVANI"].ToString(); Application.Session._KULLANICI_TURU = rdr["UNVANI"].ToString(); Application.Session._ISE_GIRIS_TARIHI = rdr["GIRIS_TARIHI"].ToString(); } using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Connection_VISION"].ToString())) { DateTime RUN_DATE = DateTime.Now; string SQL = " INSERT INTO [dbo].[XLG_HAREKET_KAYITLARI] (SIRKET_KODU,ISLEM_TARIHI,ISLEM_SAATI,YAPILAN_ISLEM,ISLEMI_YAPAN) VALUES ('" + Application.Session._SIRKET_KODU + "','" + RUN_DATE.ToString("yyyy.MM.dd") + "','" + RUN_DATE.ToString("HH:mm:ss") + "','GİRİŞ','" + Application.Session._KULLANICI_MAIL_ADRESI + "')"; SqlCommand command = new SqlCommand(SQL, conn); conn.Open(); command.CommandTimeout = 0; command.ExecuteReader(CommandBehavior.CloseConnection); conn.Close(); } rdr.Close(); } } if (Application.Session._SIRKET_KODU != null) { this.Close(); } else { { AlertBox.Show("<br> Bilgiler Doğrulanamadı! </b> ", MessageBoxIcon.Stop, alignment: System.Drawing.ContentAlignment.MiddleCenter, autoCloseDelay: 1000); return; } } } } catch (DirectoryServicesCOMException ex) { if (ex.Data == null) { throw; } else { AlertBox.Show("<br> Bilgiler Doğrulanamadı! </b> ", MessageBoxIcon.Stop, alignment: System.Drawing.ContentAlignment.MiddleCenter, autoCloseDelay: 2000); } } }
/// <summary> /// Parses the properties for a contact that came from AD /// and return GWiseContact object created from those properties. /// If some of the properties are misisng or mallformed /// the function will return null. /// In addition to parsing the contact the function returns the /// URL for the folder that contains the free busy message for /// the account, if it wasn't computed yet. /// </summary> /// <param name="contactProps">The properties of the contact</param> /// <param name="freeBusyUrl">If not already computed, /// it will be set to the free busy folder URL</param> /// <returns>A contact object or null</returns> private static GWiseContact ParseGWiseContactsFromADProperties( ResultPropertyCollection contactProps, ref string freeBusyUrl) { string gwiseUid = null; string gwiseAddress = null; string commonGroup = null; string freeBusyUrlTemp = null; GWiseContact gwiseContact = null; foreach (string propName in contactProps.PropertyNames) { foreach (Object propObject in contactProps[propName]) { string propValue = propObject.ToString(); if ((freeBusyUrl == null) && (freeBusyUrlTemp == null)) { freeBusyUrlTemp = GenerateParentFreeBusyFolderUrl( propName, propValue); } if (gwiseUid == null) { gwiseUid = GetGWiseUidFromLegacyExchangeDN( propName, propValue); } if (commonGroup == null) { commonGroup = GetCommonGroupFromLegacyExchangeDN( propName, propValue); } if (gwiseAddress == null) { gwiseAddress = GetGWiseAddressFromProxyAddresses( propName, propValue); } } } if ((gwiseAddress != null) && (gwiseUid != null) && (commonGroup != null)) { gwiseContact = new GWiseContact(gwiseUid, gwiseAddress, commonGroup); } if ((freeBusyUrl == null) && (gwiseContact != null) && (freeBusyUrlTemp != null)) { // Return the free busy URL if not set already, // but do that only for well formed accounts. freeBusyUrl = freeBusyUrlTemp; } return(gwiseContact); }
static void Main(string[] args) { Console.WriteLine("It is currently {0}", System.DateTime.Now); //Console.WriteLine("One hour ago it was {0}", System.DateTime.Now.AddHours(-1)); Console.Write("Enter user (login): "); String username = Console.ReadLine(); try { // create LDAP connection object DirectoryEntry myLdapConnection = createDirectoryEntry(); //Console.WriteLine("DirectoryEntry.Path: {0}", myLdapConnection.Path); //Console.WriteLine("DirectoryEntry.Parent.Path: {0}", myLdapConnection.Parent.Path); //Console.ReadKey(); // create search object which operates on LDAP connection object // and set search object to only find the user specified //Console.WriteLine("Using base DN: {0}", myLdapConnection.Path); //string baseDN = "OU=roundrocktexas.gov,DC=corr,DC=round-rock,DC=tx,DC=us"; string[] PropertiesToLoad = { "department", "division", "title", "displayname", "mail", "physicaldeliveryofficename" }; string ldapFilter = "(&(objectClass=user)(samaccountname=" + username + ")(mail=*)(objectCategory=person)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"; DirectorySearcher search = new DirectorySearcher(myLdapConnection, ldapFilter, PropertiesToLoad); search.Filter = "(samaccountname=" + username + ")"; //search.Filter = "(objectClass=organizationalUnit)"; // create results objects from search object SearchResult result = search.FindOne(); if (result != null) { // user exists, cycle through LDAP fields (cn, telephonenumber etc.) ResultPropertyCollection fields = result.Properties; if (fields.Contains("title")) { Console.WriteLine("Found {0} with value {1}.", "title", fields["title"][0]); } if (fields.Contains("objectsid")) { printBytes((byte[])fields["objectsid"][0], "objectsid"); } if (fields.Contains("objectguid")) { printBytes((byte[])fields["objectguid"][0], "objectguid"); } foreach (String ldapField in fields.PropertyNames) { // cycle through objects in each field e.g. group membership // (for many fields there will only be one object such as name) foreach (Object myCollection in fields[ldapField]) { Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString())); } } } else { // user does not exist Console.WriteLine("User not found!"); } //This block is for testing a search that returns a //collection of SearchResult objects (FindAll()) //search.Filter = "(&(objectClass=user)(cn=" + username + "*))"; //SearchResultCollection results = search.FindAll(); ////var json = JsonConvert.SerializeObject(results); //int count = 0; //string[] resArray = new String[results.Count]; //foreach (SearchResult res in results) //{ // ResultPropertyCollection fields = res.Properties; // //foreach (String ldapField in fields.PropertyNames) // //{ // // foreach (Object myCollection in fields[ldapField]) // // Console.WriteLine(String.Format("{0,-20} : {1}", // // ldapField, myCollection.ToString())); // //} // Console.WriteLine(String.Format("{0,-20} : {1}", // "Name", fields["name"][0])); // resArray[count] = (String)fields["name"][0]; // //Console.WriteLine(String.Format(" {0,-20} : *** {1}", // // "Name", fields["distinguishedname"][0])); // count += 1; // if (count > 20) // { // break; // } //} //using (StreamWriter file = File.CreateText(@"file.json")) //{ // JsonSerializer serializer = new JsonSerializer(); // serializer.Serialize(file, resArray); //} Console.Write("Press any key to exit"); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Exception caught:\n\n" + e.ToString()); } }
private void runSearch(string pantherID, string fiuUsername) { String output = "", emplOutput = "", studentOutput = "", visitorOutput = "", macOutput = ""; if (pantherID.Length == 7 || fiuUsername != "") // Panther ID { DirectorySearcher emplDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/)); if (fiuUsername != "") { emplDS.Filter = "(&((&(objectCategory=Person)))(sAMAccountName=" + fiuUsername + "))"; } else { emplDS.Filter = "(&((&(objectCategory=Person)))(EmployeeID=" + pantherID + "))"; } SearchResult emplSR = emplDS.FindOne(); if (emplSR != null) { ResultPropertyCollection emplResult = emplSR.Properties; foreach (string myKey in emplResult.PropertyNames) { emplOutput += myKey + " = "; foreach (Object myCollection in emplResult[myKey]) { emplOutput += myCollection + " "; } emplOutput += Environment.NewLine; } try { output += "Name: " + emplSR.Properties["displayName"][0]; } catch (Exception) { output += "Name: N/A"; } output += Environment.NewLine + "-----------------------" + Environment.NewLine; try { output += "Username: "******"sAMAccountName"][0] + Environment.NewLine; } catch (Exception) { output += "Username: N/A\n"; } try { output += "Panther ID: " + emplSR.Properties["EmployeeID"][0] + Environment.NewLine; } catch (Exception) { output += "Panther ID: N/A" + Environment.NewLine; } try { int accountState = Convert.ToInt32(emplSR.Properties["userAccountControl"][0]); if (accountState.Equals(544) | accountState.Equals(512)) { output += "Status: Enabled" + Environment.NewLine; } else if (accountState.Equals(546)) { output += "Status: Disabled" + Environment.NewLine; } else { output += "Status: Other" + Environment.NewLine; } } catch (Exception e) { output += "Status: Unknown" + Environment.NewLine; ; } try { output += "Department: " + emplSR.Properties["department"][0].ToString() + Environment.NewLine + Environment.NewLine; } catch (Exception) { output += "Department: Unknown" + Environment.NewLine + Environment.NewLine; } output += "Demographic Information" + Environment.NewLine + "----------------------------" + Environment.NewLine; try { output += "Date of Birth: " + emplSR.Properties["fiubirthdate"][0] + Environment.NewLine; } catch (Exception) { output += "Date of Birth: N/A" + Environment.NewLine; } try { output += "Last 4 SSN: " + emplSR.Properties["fiul4ssn"][0] + Environment.NewLine; } catch (Exception) { output += "Last 4 SSN: N/A" + Environment.NewLine; } try { output += "Zip Code: " + emplSR.Properties["fiucontactzip"][0] + Environment.NewLine + Environment.NewLine; } catch (Exception) { output += "Zip Code: N/A" + Environment.NewLine + Environment.NewLine; } output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine; try { long expirationTime = (long)emplSR.Properties["accountExpires"][0]; if (expirationTime > 0) { output += "**ACCOUNT TO EXPIRE ON " + DateTime.FromFileTime(expirationTime) + "**" + Environment.NewLine; } } catch (Exception e) { output += ""; } try { output += "Lync Enabled: " + emplSR.Properties["msRTCSIP-UserEnabled"][0] + Environment.NewLine; } catch (Exception e) { output += "MS Lync Enabled: Unknown" + Environment.NewLine; } try { String mail = emplSR.Properties["mail"][0].ToString(); } catch { } String targetaddress = ""; try { targetaddress = emplSR.Properties["targetaddress"][0].ToString(); } catch { } String homemdb = ""; try { homemdb = emplSR.Properties["homemdb"][0].ToString(); } catch { } if (!(targetaddress.Equals("")) && !(homemdb.Equals(""))) { output += "Mailbox Type: Unknown" + Environment.NewLine; // may be broken } else if ((targetaddress.Equals("")) && !(homemdb.Equals(""))) { output += "Mailbox Type: Exchange" + Environment.NewLine; } else if (!(targetaddress.Equals("")) && (homemdb.Equals(""))) { output += "Mailbox Type: Office 365" + Environment.NewLine; } else if ((targetaddress.Equals("")) && (homemdb.Equals(""))) { output += "Mailbox Type: None" + Environment.NewLine; } else { output += "Mailbox Type: Unknown" + Environment.NewLine; } try { if ((long)emplSR.Properties["LockOutTime"][0] == 0) { output += "Locked out: False" + Environment.NewLine; } else { output += "Locked out: True" + Environment.NewLine; } } catch (Exception) { output += "Locked out: Unknown" + Environment.NewLine; } if ((long)emplSR.Properties["pwdLastSet"][0] == 0) { output += "Password Last Set : Not Set or May be Default" + Environment.NewLine; } else { output += "Password Last Set : " + DateTime.FromFileTime((long)emplSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine; } DateTime d1 = DateTime.Now; DateTime d2 = DateTime.FromFileTime((long)emplSR.Properties["pwdLastSet"][0]); System.TimeSpan diff = d1.Subtract(d2); int daysLeft = 182 - diff.Days; // 6 months == 182.621 days if (daysLeft <= 0) { output += "**PASSWORD IS EXPIRED**" + Environment.NewLine; } else if (daysLeft <= 14) { output += String.Format("**PASSWORD WILL EXPIRE IN {0} DAY(S)**" + Environment.NewLine, daysLeft); } try { output += "Last Logon: " + DateTime.FromFileTime((long)emplSR.Properties["lastLogon"][0]) + Environment.NewLine; } catch (Exception) { output += "Last Login: Unknown" + Environment.NewLine; } try { output += "Bad Password: "******"badPasswordTime"][0]) + Environment.NewLine; } catch (Exception) { output += "Bad Password: Unknown" + Environment.NewLine; } output += "When Created: " + emplSR.Properties["whenCreated"][0] + Environment.NewLine; } else { output += ""; } DirectorySearcher studentDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); if (fiuUsername != "") { studentDS.Filter = "(&((&(objectCategory=Person)))(sAMAccountName=" + fiuUsername + "))"; } else { studentDS.Filter = "(&((&(objectCategory=Person)))(EmployeeID=" + pantherID + "))"; } SearchResult studentSR = studentDS.FindOne(); if (studentSR != null) { if (emplSR != null) { output += Environment.NewLine + "==============================" + Environment.NewLine; } ResultPropertyCollection studentResult = studentSR.Properties; foreach (string myKey in studentResult.PropertyNames) { studentOutput += myKey + " = "; foreach (Object myCollection in studentResult[myKey]) { studentOutput += myCollection + " "; } studentOutput += Environment.NewLine; } try { output += "Name: " + studentSR.Properties["displayName"][0]; } catch (Exception) { output += "Name: Unknown"; } output += Environment.NewLine + "-----------------------" + Environment.NewLine; try { output += "Username: "******"sAMAccountName"][0] + Environment.NewLine; } catch (Exception) { output += "Username: Unknown" + Environment.NewLine; } try { output += "Panther ID: " + studentSR.Properties["EmployeeID"][0] + Environment.NewLine; } catch (Exception) { output += "Panther ID: Unknown" + Environment.NewLine; } try { String fiuStatus = studentSR.Properties["fiuStatus"][0].ToString(); output += "Status: " + fiuStatus + Environment.NewLine; } catch (Exception) { output += "Status: Unknown" + Environment.NewLine; } output += Environment.NewLine + "Demographic Information" + Environment.NewLine + "----------------------------" + Environment.NewLine; try { output += "Date of Birth: " + studentSR.Properties["fiubirthdate"][0] + Environment.NewLine; } catch (Exception) { output += "Date of Birth: N/A" + Environment.NewLine; } try { output += "Last 4 SSN: " + studentSR.Properties["fiul4ssn"][0] + Environment.NewLine; } catch (Exception) { output += "Last 4 SSN: N/A" + Environment.NewLine; } try { output += "Zip Code: " + studentSR.Properties["fiucontactzip"][0] + Environment.NewLine + Environment.NewLine; } catch (Exception) { output += "Zip Code: N/A" + Environment.NewLine + Environment.NewLine; } output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine; try { if ((long)studentSR.Properties["LockOutTime"][0] == 0) { output += "Locked out: False" + Environment.NewLine; } else { output += "Locked out: True" + Environment.NewLine; } } catch (Exception) { output += "Locked out? UNKNOWN" + Environment.NewLine; } if ((long)studentSR.Properties["pwdLastSet"][0] == 0) { output += "Password Last Set : Not Set or May be Default" + Environment.NewLine; } else { output += "Password Last Set : " + DateTime.FromFileTime((long)studentSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine; } DateTime d1 = DateTime.Now; DateTime d2 = DateTime.FromFileTime((long)studentSR.Properties["pwdLastSet"][0]); System.TimeSpan diff = d1.Subtract(d2); int daysLeft = 182 - diff.Days; // 6 months == 182.621 days if (daysLeft <= 0) { output += "**PASSWORD IS EXPIRED**" + Environment.NewLine; } else if (daysLeft <= 14) { output += String.Format("**PASSWORD WILL EXPIRE IN {0} DAY(S)**" + Environment.NewLine, daysLeft); } try { output += "Last Logon: " + DateTime.FromFileTime((long)studentSR.Properties["lastLogon"][0]) + Environment.NewLine; } catch (Exception) { output += "Last Login: Unknown" + Environment.NewLine; } try { output += "Bad Password: "******"badPasswordTime"][0]) + Environment.NewLine; } catch (Exception) { output += "Bad Password: Unknown" + Environment.NewLine; } output += "When Created: " + studentSR.Properties["whenCreated"][0] + Environment.NewLine; } if (pantherID != "" && (emplSR != null|| studentSR !=null)) { DirectorySearcher devicesDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); devicesDS.Filter = "(&((&(objectCategory=Person)))(fiunsseowner=" + pantherID + "))"; SearchResultCollection devicesSR = devicesDS.FindAll(); if (devicesSR != null) { output += Environment.NewLine + "==============================" + Environment.NewLine; foreach (SearchResult deviceSR in devicesSR) { output += "MAC: " + deviceSR.Properties["GivenName"][0] + Environment.NewLine; output += "Description: " + deviceSR.Properties["fiuNSSEdescription"][0] + Environment.NewLine + Environment.NewLine; } } } else if(emplSR == null && studentSR == null) { output += "No Results Found" + Environment.NewLine; } } else if (pantherID.Length == 10)// Visitor Account { DirectorySearcher visitorDS = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); visitorDS.Filter = "(&((&(objectCategory=Person)))(CN=" + pantherID + "))"; SearchResult visitorSR = visitorDS.FindOne(); if (visitorSR != null) { ResultPropertyCollection visitorResult = visitorSR.Properties; foreach (string myKey in visitorResult.PropertyNames) { visitorOutput += myKey + " = "; foreach (Object myCollection in visitorResult[myKey]) { visitorOutput += myCollection + " "; } visitorOutput += Environment.NewLine; } try { output += "Username: "******"samaccountname"][0].ToString() + Environment.NewLine; } catch { output += "" + Environment.NewLine; } output += "-----------------------" + Environment.NewLine; try { output += "Description: " + visitorSR.Properties["fiuNSSEdescription"][0].ToString() + Environment.NewLine; } catch { output += ""; } try { output += "Email: " + visitorSR.Properties["fiunsseowner"][0].ToString() + Environment.NewLine + Environment.NewLine; } catch (Exception) { output += ""; } output += "Extra Information" + Environment.NewLine + "-----------------------" + Environment.NewLine; output += "Registered on: " + DateTime.FromFileTime((long)visitorSR.Properties["pwdLastSet"][0]).ToString() + Environment.NewLine; output += "Expires: " + DateTime.FromFileTime((long)visitorSR.Properties["accountExpires"][0]).ToString() + Environment.NewLine; } else { } } else if (fiuUsername.Length == 17 || fiuUsername.Length == 12) // MAC Registration { String macColon = "", macDash = "", macNone = ""; if (fiuUsername.Contains(":")) { macColon = fiuUsername; macDash = fiuUsername.Replace(":", "-"); macNone = fiuUsername.Replace(":", ""); } else if (fiuUsername.Contains("-")) { macColon = fiuUsername.Replace("-", ":"); macDash = fiuUsername; macNone = fiuUsername.Replace("-", ""); } else { macColon = fiuUsername.Substring(0, 2) + ":" + fiuUsername.Substring(2, 2) + ":" + fiuUsername.Substring(4, 2) + ":" + fiuUsername.Substring(6, 2) + ":" + fiuUsername.Substring(8, 2) + ":" + fiuUsername.Substring(10, 2); macDash = fiuUsername.Substring(0, 2) + "-" + fiuUsername.Substring(2, 2) + "-" + fiuUsername.Substring(4, 2) + "-" + fiuUsername.Substring(6, 2) + "-" + fiuUsername.Substring(8, 2) + "-" + fiuUsername.Substring(10, 2); macNone = fiuUsername; } resultBox.Text = output; DirectorySearcher dsColon = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); dsColon.Filter = "(&((&(objectCategory=Person)))(CN=" + macColon + "))"; SearchResult srColon = dsColon.FindOne(); if (srColon != null) { ResultPropertyCollection macResult = srColon.Properties; foreach (string myKey in macResult.PropertyNames) { macOutput += myKey + " = "; foreach (Object myCollection in macResult[myKey]) { macOutput += myCollection + " "; } macOutput += Environment.NewLine; } output += "Registration Information\n-----------------------\n"; try { output += "Device \"Name\": " + srColon.Properties["fiuNSSEdescription"][0] + "\n"; } catch (Exception) { output += "Device \"Name\": N/A\n"; } try { output += "Device MAC Address: " + srColon.Properties["GivenName"][0] + "\n"; } catch (Exception) { } output += "Registered to: " + srColon.Properties["fiuNSSEowner"][0] + "\n\n"; output += "Extra Information\n-----------------------\n"; output += "Registered on: " + DateTime.FromFileTime((long)srColon.Properties["pwdLastSet"][0]).ToString() + "\n"; output += "Registration Expires on: " + DateTime.FromFileTime((long)srColon.Properties["accountExpires"][0]).ToString() + "\n\n"; resultBox.Text = output; } DirectorySearcher dsDash = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); dsDash.Filter = "(&((&(objectCategory=Person)))(CN=" + macDash + "))"; SearchResult srDash = dsDash.FindOne(); if (srDash != null) { ResultPropertyCollection macResult = srDash.Properties; foreach (string myKey in macResult.PropertyNames) { macOutput += myKey + " = "; foreach (Object myCollection in macResult[myKey]) { macOutput += myCollection + " "; } macOutput += Environment.NewLine; } output += "Registration Information\n-----------------------\n"; output += "Device \"Name\": " + srDash.Properties["fiuNSSEdescription"][0] + "\n"; output += "Device MAC Address: " + srDash.Properties["GivenName"][0] + "\n"; output += "Registered to: " + srDash.Properties["fiuNSSEowner"][0] + "\n\n"; output += "Extra Information\n-----------------------\n"; output += "Registered on: " + DateTime.FromFileTime((long)srDash.Properties["pwdLastSet"][0]).ToString() + "\n"; output += "Registration Expires on: " + DateTime.FromFileTime((long)srDash.Properties["accountExpires"][0]).ToString() + "\n\n"; resultBox.Text = output; } DirectorySearcher dsNone = new DirectorySearcher(new DirectoryEntry(/*LDAP HERE*/))); dsNone.Filter = "(&((&(objectCategory=Person)))(CN=" + macNone + "))"; SearchResult srNone = dsNone.FindOne(); if (srNone != null) { ResultPropertyCollection macResult = srNone.Properties; foreach (string myKey in macResult.PropertyNames) { macOutput += myKey + " = "; foreach (Object myCollection in macResult[myKey]) { macOutput += myCollection + " "; } macOutput += Environment.NewLine; } output += "Registration Information\n-----------------------\n"; output += "Device \"Name\": " + srNone.Properties["fiuNSSEdescription"][0] + "\n"; output += "Device MAC Address: " + srNone.Properties["GivenName"][0] + "\n"; output += "Registered to: " + srNone.Properties["fiuNSSEowner"][0] + "\n\n"; output += "Extra Information\n-----------------------\n"; output += "Registered on: " + DateTime.FromFileTime((long)srNone.Properties["pwdLastSet"][0]).ToString() + "\n"; output += "Registration Expires on: " + DateTime.FromFileTime((long)srNone.Properties["accountExpires"][0]).ToString() + "\n\n"; } } else { output += "No Results Found For " + pantherID + " " + fiuUsername; } resultBox.Text = output; if (exportLogFileToolStripMenuItem.Checked == true) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(Environment.GetFolderPath(System.Environment.SpecialFolder.Personal))) { writer.WriteLine(emplOutput + Environment.NewLine + studentOutput + Environment.NewLine + visitorOutput + Environment.NewLine + macOutput); } } }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType); string[] membersName = reflectionInfo.GetWriteableMemberNames(); IDictionary<string, ISetAccessor> propertyMap = new Dictionary<string, ISetAccessor>(); int length = membersName.Length; for (int i = 0; i < length; i++) { ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]); propertyMap.Add(membersName[i], setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. DataTable dataColumn = reader.GetSchemaTable(); int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { string propertyName = string.Empty; string columnName = dataColumn.Rows[i][0].ToString(); ISetAccessor matchedSetAccessor = null; propertyMap.TryGetValue(columnName, out matchedSetAccessor); int columnIndex = i; if (resultObject is Hashtable) { propertyName = columnName; ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, null); properties.Add(property); } Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { _logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject + "]"); } } else { propertyType = matchedSetAccessor.MemberType; } if (propertyType != null || matchedSetAccessor != null) { propertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); ITypeHandler typeHandler = null; if (matchedSetAccessor != null) { //property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(matchedSetAccessor.MemberType); } else { typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } //property.PropertyStrategy = PropertyStrategyFactory.Get(property); ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, typeHandler); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return properties; }
/// <summary> /// Отправка сообщения об изменении объекта /// </summary> /// <param name="directoryEntry"></param> /// <param name="prop">Строковое значения имени изменившегося поля</param> /// <param name="delta">Список полей изменившегося объекта</param> private static void ProcessChanged(DirectoryEntry directoryEntry, string prop, ResultPropertyCollection delta) { var schemeClass = directoryEntry.SchemaClassName ?? string.Empty; if (!schemeClass.Equals("computer", StringComparison.OrdinalIgnoreCase) && !schemeClass.Equals("user", StringComparison.OrdinalIgnoreCase) && !schemeClass.Equals("group", StringComparison.OrdinalIgnoreCase)) { return; } foreach (var val in delta[prop]) { var name = directoryEntry.Name?.Substring(3) ?? string.Empty; var parent = directoryEntry.Parent.Name ?? string.Empty; if (name.Equals(val.ToString(), StringComparison.OrdinalIgnoreCase)) { continue; } _adNotifyCollection.Push(CreateNotifyMessage(schemeClass, name, prop, val, parent)); } }
private Forest GetProperties(Forest forest, ResultPropertyCollection fields) { try { ServerRepository sr = new ServerRepository(_mySQLContext); foreach (String ldapField in fields.PropertyNames) { foreach (Object myCollection in fields[ldapField]) { switch (ldapField) { case "domain": forest.Domain = myCollection.ToString(); break; case "name": forest.Name = myCollection.ToString(); break; case "displayName": forest.DisplayName = myCollection.ToString(); break; case "description": forest.Description = myCollection.ToString(); break; case "samaccountname": forest.SamAccountName = myCollection.ToString(); break; case "managedby": forest.Manager = myCollection.ToString(); break; case "adspath": forest.PathDomain = myCollection.ToString(); break; case "l": forest.City = myCollection.ToString(); break; case "st": forest.State = myCollection.ToString(); break; case "postalcode": forest.PostalCode = myCollection.ToString(); break; case "c": forest.Country = myCollection.ToString(); break; case "mail": forest.Email = myCollection.ToString(); break; case "whenchanged": forest.WhenChanged = myCollection.ToString(); break; case "whencreated": forest.WhenCreated = myCollection.ToString(); break; case "ou": forest.Ou = myCollection.ToString(); break; case "distinguishedname": forest.DistinguishedName = myCollection.ToString(); break; case "street": forest.Street = myCollection.ToString(); break; case "iscriticalsystemobject": forest.IsCriticalSystemObject = (bool)myCollection; break; case "cn": forest.CommonName = myCollection.ToString(); break; } Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString())); } } return(forest); } catch (System.DirectoryServices.DirectoryServicesCOMException e) { Console.WriteLine("\r\nUnexpected exception occurred:\r\n\t" + e.GetType() + ":" + e.Message); return(null); } }
public static List <AppUser> GetADUsers(string ldap) { List <AppUser> users = new List <AppUser>(); try { DirectoryEntry searchRoot = new DirectoryEntry(ldap); DirectorySearcher search = new DirectorySearcher(searchRoot); search.Filter = "(&(objectClass=user)(objectCategory=person))"; SearchResult result = null; SearchResultCollection resultCol = search.FindAll(); Func <string, string> GetPropertyValue = (propertyName) => { try { return(result.Properties[propertyName][0].ToString()); } catch { return(string.Empty); } }; if (resultCol != null) { for (int counter = 0; counter < resultCol.Count; counter++) { string current = string.Empty; result = resultCol[counter]; if (result.Properties.Contains("samaccountname") || result.Properties.Contains("mail") || result.Properties.Contains("displayname")) { AppUser user = new AppUser(); user.Email = GetPropertyValue("mail"); user.Login = GetPropertyValue("samaccountname"); user.Name = GetPropertyValue("displayname"); ResultPropertyCollection prop = result.Properties; ICollection coll = prop.PropertyNames; IEnumerator enu = coll.GetEnumerator(); while (enu.MoveNext()) { current = (enu.Current ?? string.Empty).ToString(); if (current.IsNullOrEmpty()) { continue; } user.Properties.Add(new AppUserProperties(current, GetPropertyValue(current))); } user.Active = !user.Properties.Where(a => a.PropertyValue.ToLower().Contains("desativado")).HasItems(); if (user.Active) { AppUserProperties p = user.Properties.Where(a => a.PropertyName == "useraccountcontrol").FirstOrDefault(); if (p.PropertyValue == "514" || p.PropertyValue == "66050") { user.Active = false; } } users.Add(user); } } } } catch { } return(users); }
/// <summary> /// Deserializes the specified config. /// </summary> /// <param name="config">The config.</param> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="waitResultPropertyResolution">The wait result property resolution delegate.</param> /// <param name="waitDiscriminatorResolution">The wait discriminator resolution.</param> /// <returns></returns> public static ResultMap Deserialize( IConfiguration config, DataExchangeFactory dataExchangeFactory, WaitResultPropertyResolution waitResultPropertyResolution, WaitDiscriminatorResolution waitDiscriminatorResolution ) { string id = config.Id; string className = ConfigurationUtils.GetMandatoryStringAttribute(config, ConfigConstants.ATTRIBUTE_CLASS); string extends = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_EXTENDS); string groupBy = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_GROUPBY); string keyColumns = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_KEYS_PROPERTIES); string suffix = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_SUFFIX, string.Empty); string prefix = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_PREFIX, string.Empty); Type type = dataExchangeFactory.TypeHandlerFactory.GetType(className); IDataExchange dataExchange = dataExchangeFactory.GetDataExchangeForClass(type); IFactory factory = null; ArgumentPropertyCollection arguments = new ArgumentPropertyCollection(); #region Get the constructor & associated parameters ConfigurationCollection constructors = config.Children.Find(ConfigConstants.ELEMENT_CONSTRUCTOR); if (constructors.Count > 0) { IConfiguration constructor = constructors[0]; Type[] argumentsType = new Type[constructor.Children.Count]; string[] argumentsName = new string[constructor.Children.Count]; // Builds param name list for (int i = 0; i < constructor.Children.Count; i++) { argumentsName[i] = ConfigurationUtils.GetStringAttribute(constructor.Children[i].Attributes, ConfigConstants.ATTRIBUTE_ARGUMENTNAME); } // Find the constructor ConstructorInfo constructorInfo = GetConstructor(id, type, argumentsName); // Build ArgumentProperty and parameter type list for (int i = 0; i < constructor.Children.Count; i++) { ArgumentProperty argumentMapping = ArgumentPropertyDeSerializer.Deserialize( constructor.Children[i], type, constructorInfo, dataExchangeFactory); arguments.Add(argumentMapping); if (argumentMapping.NestedResultMapName.Length > 0) { waitResultPropertyResolution(argumentMapping); } argumentsType[i] = argumentMapping.MemberType; } // Init the object factory factory = dataExchangeFactory.ObjectFactory.CreateFactory(type, argumentsType); } else { if (!dataExchangeFactory.TypeHandlerFactory.IsSimpleType(type) && type != typeof(DataRow)) { factory = dataExchangeFactory.ObjectFactory.CreateFactory(type, Type.EmptyTypes); } } #endregion ResultPropertyCollection properties = BuildResultProperties( id, config, type, prefix, suffix, dataExchangeFactory, waitResultPropertyResolution); Discriminator discriminator = BuildDiscriminator(config, type, dataExchangeFactory, waitDiscriminatorResolution); ResultMap resultMap = new ResultMap( id, className, extends, groupBy, keyColumns, type, dataExchange, factory, dataExchangeFactory.TypeHandlerFactory, properties, arguments, discriminator ); return(resultMap); }
/// <summary> /// /// </summary> /// <param name="resultPropertyCollection"> /// </param> public ResultPropertyCollectionWrap(ResultPropertyCollection resultPropertyCollection) { this.resultPropertyCollection = resultPropertyCollection; this.PropertyNames = this.resultPropertyCollection.PropertyNames; this.Values = this.resultPropertyCollection.Values; }
/// <summary> /// Initializes a new instance of the <see cref="ResultMap"/> class. /// </summary> /// <param name="id">Identifier used to identify the resultMap amongst the others.</param> /// <param name="className">The output class name of the resultMap.</param> /// <param name="extendMap">The extend result map bame.</param> /// <param name="groupBy">The groupBy properties</param> /// <param name="keyColumns">The key columns.</param> /// <param name="type">The result type.</param> /// <param name="dataExchange">The data exchange.</param> /// <param name="objectFactory">The object factory.</param> /// <param name="typeHandlerFactory">The type handler factory.</param> /// <param name="properties">The properties.</param> /// <param name="parameters">The parameters.</param> /// <param name="discriminator">The discriminator.</param> public ResultMap( string id, string className, string extendMap, string groupBy, string keyColumns, Type type, IDataExchange dataExchange, IFactory objectFactory, TypeHandlerFactory typeHandlerFactory, ResultPropertyCollection properties, ArgumentPropertyCollection parameters, Discriminator discriminator) { Contract.Require.That(id, Is.Not.Null & Is.Not.Empty).When("retrieving argument id in ResultMap constructor"); Contract.Require.That(className, Is.Not.Null & Is.Not.Empty).When("retrieving argument className in ResultMap constructor"); Contract.Require.That(type, Is.Not.Null).When("retrieving argument type in ResultMap constructor"); Contract.Require.That(typeHandlerFactory, Is.Not.Null).When("retrieving argument typeHandlerFactory in ResultMap constructor"); nullResultMap = new NullResultMap(); this.id = id; this.className = className; this.extendMap = extendMap; this.type = type; this.dataExchange = dataExchange; this.properties = properties; this.parameters = parameters; this.discriminator = discriminator; this.objectFactory = objectFactory; isSimpleType = typeHandlerFactory.IsSimpleType(type); if (!string.IsNullOrEmpty(groupBy)) { string[] props = groupBy.Split(','); for (int i = 0; i < props.Length; i++) { string memberName = props[i].Trim(); groupByPropertyNames.Add(memberName); } InitializeGroupByProperties(); CheckGroupBy(); } if (!string.IsNullOrEmpty(keyColumns)) { string[] columns = keyColumns.Split(','); for (int i = 0; i < columns.Length; i++) { string column = columns[i].Trim(); keyPropertyNames.Add(column); } InitializeKeysProperties(); CheckKeysProperties(); } }
private static string GetValue(ResultPropertyCollection properties, string parameter) { return(properties.Contains(parameter) ? properties[parameter][0].ToString() : null); }
static public Hashtable getDIRXMLAttributes(String username) { int maxtry = 10; int retrydelay = 500; Hashtable h = null; bool again = true; int trycount = 0; string lasterror = null; while (again && trycount <= maxtry) { trycount++; again = false; AuditSec.checkDIRXMLAccess(lasterror); if (!AuditSec.picdisabled && AuditSec.settings.picpw != null) { try { //Console.WriteLine("Retrieving DirXML data of " + username + "..."); try { DirectorySearcher s = new DirectorySearcher( new DirectoryEntry(AuditSec.defaultLdap, "cn=" + UserPrincipal.Current.SamAccountName + ",ou=USER,o=MYCOMPANY", AuditSec.settings.picpw, AuthenticationTypes.None), "(&(objectClass=MYCOMPANYUser)(cn=" + username + "))", DIRXMLattr2, SearchScope.OneLevel ); SearchResult result = s.FindOne(); if (result == null) { Console.WriteLine("DirXML data of " + username + ": Error: Not found."); } ResultPropertyCollection p = result.Properties; h = new Hashtable(); for (int i = 0; i < DIRXMLattr.Length; i++) { string attr = DIRXMLattr[i]; string attr2 = DIRXMLattr2[i]; Type type = getDIRXMLtype(attr); //Console.WriteLine("Retrieving DirXML data of " + username + "/" + attribute + "..."); string value = p[attr2].Count > 0 ? p[attr2][0].ToString() : ""; if (getDIRXMLalias(attr).Equals("Decentralized")) { value = value.ToLower().Contains("decentralized") ? "Home-based" : "Office-based"; } h.Add(attr, getValue(type, value)); } //Console.WriteLine("DirXML data of " + username + ": " + h.ToString()); } catch (AccessViolationException ave) { throw new Exception(ave.Message); } } catch (Exception e) { lasterror = e.Message; if (e.Message.StartsWith("Object reference not set to an instance of an object")) { ;//not found. ok } else if (e.Message.StartsWith("A device attached to the system is not functioning")) { lasterror = e.Message; Thread.Sleep(retrydelay); again = true; } else { Console.WriteLine("DirXML data of " + username + ": " + e.Message); } if (e.Message.StartsWith("Logon failure") || e.Message.EndsWith("A constraint violation occurred.") || e.Message.StartsWith("The server is unwilling to process the request")) { lasterror = "Invalid password."; AuditSec.settings.picpw = null; again = true; } } } if (again && trycount > maxtry) { Console.WriteLine("DirXML data of " + username + ": Error: " + lasterror + "\nMaximum retry reached."); } } return(h); }
private void button1_Click(object sender, EventArgs e) { txtResults.Text = string.Empty; string logid = txtLogID.Text.Trim(); if (String.IsNullOrWhiteSpace(logid)) { txtResults.Text = "Please enter logon id."; return; } try { //perform a search string ldapBindingStr = @"LDAP://helloworld.com/DC=hellods,DC=world,DC=com"; DirectoryEntry ldapConnection = new DirectoryEntry(ldapBindingStr); DirectorySearcher search = new DirectorySearcher(ldapConnection); search.ReferralChasing = ReferralChasingOption.All; search.Filter = "(samaccountName=" + logid + ")"; // user's logon id gzhou // search.Filter = "(cn=" + username + ")"; // this is full name, zhou, gary SearchResult result = search.FindOne(); if (result != null) { ResultPropertyCollection fields = result.Properties; foreach (String ldapField in fields.PropertyNames) { //*************** output all properties ********************************************************************* // cycle through objects in each field e.g. group membership // (for many fields there will only be one object such as name) foreach (Object myCollection in fields[ldapField]) { if (ldapField.Equals("accountexpires")) { if ("9223372036854775807" == fields["accountexpires"][0].ToString()) // this is magic default value { txtResults.Text = txtResults.Text + (String.Format(OutputFormatStr, ldapField, "never expire.")) + Environment.NewLine; } else { txtResults.Text = txtResults.Text + (String.Format(OutputFormatStr, ldapField, DateTime.FromFileTime(long.Parse(fields["accountexpires"][0].ToString())))) + Environment.NewLine; } } else if (ldapField.Equals("pwdlastset")) { txtResults.Text = txtResults.Text + (String.Format(OutputFormatStr, ldapField, DateTime.FromFileTime(long.Parse(fields["pwdlastset"][0].ToString())))) + Environment.NewLine; } else if (ldapField.Equals("objectguid")) { txtResults.Text = txtResults.Text + (String.Format(OutputFormatStr, ldapField, new Guid((byte[])myCollection))) + Environment.NewLine; } else { txtResults.Text = txtResults.Text + (String.Format(OutputFormatStr, ldapField, myCollection.ToString())) + Environment.NewLine; } } } } else { // user does not exist txtResults.Text = "User not found!"; } } catch (Exception ex) { txtResults.Text = ex.Message; } }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// 根据reader的字段从resultObject类中获取对应的属性类集合 /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType); string[] membersName = reflectionInfo.GetWriteableMemberNames(); //为结果类resultObject的属性设置对应的访问与获取的函数类 IDictionary <string, ISetAccessor> propertyMap = new Dictionary <string, ISetAccessor>(); int length = membersName.Length; for (int i = 0; i < length; i++) { ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]); propertyMap.Add(membersName[i], setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. DataTable dataColumn = reader.GetSchemaTable(); int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { string propertyName = string.Empty; string columnName = dataColumn.Rows[i][0].ToString(); //获取当前列字段对应的设置访问类 ISetAccessor matchedSetAccessor = null; propertyMap.TryGetValue(columnName, out matchedSetAccessor); int columnIndex = i; if (resultObject is Hashtable) { propertyName = columnName; //将当前列字段信息转化为ResultProperty类 ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, null); properties.Add(property); } //获取当前列字段的类型 Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { _logger.Error("The column [" + columnName + "] could not be auto mapped to a property on [" + resultObject + "]"); } } else { propertyType = matchedSetAccessor.MemberType; } //获取当前列字段的名称及对应的处理类 if (propertyType != null || matchedSetAccessor != null) { propertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); ITypeHandler typeHandler = null; if (matchedSetAccessor != null) { //property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(matchedSetAccessor.MemberType); } else { typeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } //property.PropertyStrategy = PropertyStrategyFactory.Get(property); ResultProperty property = new ResultProperty( propertyName, columnName, columnIndex, string.Empty, string.Empty, string.Empty, false, string.Empty, null, string.Empty, targetType, dataExchangeFactory, typeHandler); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return(properties); }
public void worker_DoWork(object sender, DoWorkEventArgs e) { string col1; string col2; string col3; string col4; string col5; string col6; string col7; string col8; string col9; string col10; BackgroundWorker worker = sender as BackgroundWorker; count = 0; DirectoryEntry objDE; objDE = new DirectoryEntry(Properties.Settings.Default.RootOU); var deSearch = new DirectorySearcher(objDE) { SearchRoot = objDE, Filter = searchString }; SearchResultCollection searchResult = deSearch.FindAll(); foreach (SearchResult sr in searchResult) { ResultPropertyCollection pc = sr.Properties; try { col1 = pc[comboChoice.Col1][0].ToString(); } catch { col1 = ""; } try { col2 = pc[comboChoice.Col2][0].ToString(); } catch { col2 = ""; } try { col3 = pc[comboChoice.Col3][0].ToString(); } catch { col3 = ""; } try { col4 = pc[comboChoice.Col4][0].ToString(); } catch { col4 = ""; } try { col5 = pc[comboChoice.Col5][0].ToString(); } catch { col5 = ""; } try { col6 = pc[comboChoice.Col6][0].ToString(); } catch { col6 = ""; } try { col7 = pc[comboChoice.Col7][0].ToString(); } catch { col7 = ""; } try { col8 = pc[comboChoice.Col8][0].ToString(); } catch { col8 = ""; } try { col9 = pc[comboChoice.Col9][0].ToString(); } catch { col9 = ""; } try { col10 = pc[comboChoice.Col10][0].ToString(); } catch { col10 = ""; } userList.Add(new UserList() { Col1 = col1, Col2 = col2, Col3 = col3, Col4 = col4, Col5 = col5, Col6 = col6, Col7 = col7, Col8 = col8, Col9 = col9, Col10 = col10 }); count++; worker.ReportProgress(count, totalCount); } deSearch.Dispose(); searchResult.Dispose(); objDE.Dispose(); }
private static IEnumerable <DFSShare> Get_DomainDFSShareV2(Args_Get_DomainSearcher args = null) { if (args == null) { args = new Args_Get_DomainSearcher(); } var DFSSearcher = GetDomainSearcher.Get_DomainSearcher(args); if (DFSSearcher != null) { var DFSShares = new List <DFSShare>(); ResultPropertyCollection Properties = null; DFSSearcher.Filter = @"(&(objectClass=msDFS-Linkv2))"; DFSSearcher.PropertiesToLoad.AddRange(new string[] { @"msdfs-linkpathv2", @"msDFS-TargetListv2" }); try { var Results = DFSSearcher.FindAll(); if (Results != null) { foreach (SearchResult result in Results) { Properties = result.Properties; var target_list = Properties[@"msdfs-targetlistv2"][0] as byte[]; var xml = new XmlDocument(); xml.LoadXml(System.Text.Encoding.Unicode.GetString(target_list.Skip(2).Take(target_list.Length - 1 + 1 - 2).ToArray())); if (xml.FirstChild != null) { foreach (XmlNode node in xml.FirstChild.ChildNodes) { try { var Target = node.InnerText; if (Target.Contains(@"\")) { var DFSroot = Target.Split('\\')[3]; var ShareName = Properties[@"msdfs-linkpathv2"][0] as string; DFSShares.Add(new DFSShare { Name = [email protected]"{DFSroot}{ShareName}", RemoteServerName = Target.Split('\\')[2] }); } } catch (Exception e) { Logger.Write_Verbose([email protected]"[Get-DomainDFSShare] Get-DomainDFSShareV2 error in parsing target : {e}"); } } } } try { Results.Dispose(); } catch (Exception e) { Logger.Write_Verbose([email protected]"[Get-DomainDFSShare] Error disposing of the Results object: {e}"); } } DFSSearcher.Dispose(); } catch (Exception e) { Logger.Write_Warning([email protected]"[Get-DomainDFSShare] Get-DomainDFSShareV2 error : {e}"); } return(DFSShares); } return(null); }
/// <summary> /// Builds a <see cref="ResultPropertyCollection"/> for an <see cref="AutoResultMap"/>. /// </summary> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="reader">The reader.</param> /// <param name="resultObject">The result object.</param> public static ResultPropertyCollection Build(DataExchangeFactory dataExchangeFactory, IDataReader reader, ref object resultObject) { Type targetType = resultObject.GetType(); ResultPropertyCollection properties = new ResultPropertyCollection(); try { // Get all PropertyInfo from the resultObject properties ReflectionInfo reflectionInfo = ReflectionInfo.GetInstance(targetType); string[] membersName = reflectionInfo.GetWriteableMemberNames(); Hashtable propertyMap = new Hashtable(); int length = membersName.Length; for (int i = 0; i < length; i++) { ISetAccessorFactory setAccessorFactory = dataExchangeFactory.AccessorFactory.SetAccessorFactory; ISetAccessor setAccessor = setAccessorFactory.CreateSetAccessor(targetType, membersName[i]); propertyMap.Add(membersName[i], setAccessor); } // Get all column Name from the reader // and build a resultMap from with the help of the PropertyInfo[]. DataTable dataColumn = reader.GetSchemaTable(); int count = dataColumn.Rows.Count; for (int i = 0; i < count; i++) { string columnName = dataColumn.Rows[i][0].ToString(); ISetAccessor matchedSetAccessor = propertyMap[columnName] as ISetAccessor; ResultProperty property = new ResultProperty(); property.ColumnName = columnName; property.ColumnIndex = i; if (resultObject is Hashtable) { property.PropertyName = columnName; properties.Add(property); } Type propertyType = null; if (matchedSetAccessor == null) { try { propertyType = ObjectProbe.GetMemberTypeForSetter(resultObject, columnName); } catch { } } else { propertyType = matchedSetAccessor.MemberType; } if (propertyType != null || matchedSetAccessor != null) { property.PropertyName = (matchedSetAccessor != null ? matchedSetAccessor.Name : columnName); if (matchedSetAccessor != null) { property.Initialize(dataExchangeFactory.TypeHandlerFactory, matchedSetAccessor); } else { property.TypeHandler = dataExchangeFactory.TypeHandlerFactory.GetTypeHandler(propertyType); } property.PropertyStrategy = PropertyStrategyFactory.Get(property); properties.Add(property); } } } catch (Exception e) { throw new DataMapperException("Error automapping columns. Cause: " + e.Message, e); } return(properties); }
// Voir un utilisateur en détail (fini) static void ReadDetails(DirectoryEntry ldap) { DirectorySearcher searcher = new DirectorySearcher(ldap); // Recherche par login car aucun utilisateur ne peut avoir le même Console.Write("Veuillez entrer le login de l'utilisateur : "); string loginUser = Console.ReadLine(); Console.WriteLine(); searcher.Filter = "(SAMAccountName=" + loginUser + ")"; SearchResult result = searcher.FindOne(); if (result != null) { // L'utilisateur existe, on liste les champs ResultPropertyCollection fields = result.Properties; foreach (String ldapField in fields.PropertyNames) { // Il peut y avoir plusieurs objets dans chaque champs (ex: appartenance à des groupes) foreach (Object myCollection in fields[ldapField]) { Console.WriteLine(String.Format("{0,-20} : {1}", ldapField, myCollection.ToString())); } } } else { // L'utilisateur n’existe pas Console.WriteLine("Utilisateur non trouvé !"); while (true) { Console.Write("Souhaitez-vous réessayer ? (O/N) :"); string answer = Console.ReadLine(); answer = answer.ToUpper(); if (answer == "O" || answer == "OUI") { ReadDetails(ldap); } if (answer == "N" || answer == "NON") { Menu(ldap); } else { Console.WriteLine("Je n'ai pas compris votre réponse. Veuillez réessayer."); Console.WriteLine(); } } } Console.WriteLine(); Console.WriteLine("Appuyer sur n'importe quelle touche pour revenir au menu principal."); Console.ReadLine(); Menu(ldap); }
protected SortedList <String, List <String> > GetLDAPInfo(String aFilter) { SortedList <String, List <String> > wSL = null; String domainAndUsername = @"LDAP://212.219.42.19/o=WC"; string userName = string.Empty; string passWord = string.Empty; AuthenticationTypes at = AuthenticationTypes.Anonymous; //Create the object necessary to read the info from the LDAP directory DirectoryEntry entry = new DirectoryEntry(domainAndUsername, userName, passWord, at); DirectorySearcher mySearcher = new DirectorySearcher(entry); SearchResultCollection results; mySearcher.Filter = aFilter; try { results = mySearcher.FindAll(); if (results.Count > 0) { SearchResult resEnt = results[0]; { wSL = new SortedList <String, List <String> >(); ResultPropertyCollection propcoll = resEnt.Properties; String wKey = ""; foreach (string key in propcoll.PropertyNames) { wKey = key; switch (key) { case "sn": wKey = "surname"; break; case "l": wKey = "location"; break; case "st": wKey = "state"; break; case "ngwmailboxexpirationtime": wKey = "gwexpire"; break; case "groupmembership": wKey = "grpmbr"; break; case "uid": wKey = "userid"; break; default: break; } if (key != "nsimhint") { foreach (object values in propcoll[key]) { //added 11/04/2011 SJL: needed to add the string for the ndshomedirectory //as part of the test for creating additional home directories. //originally the text 'system.byte[] was written to the wSL String sValue = ""; if (values.ToString() == "System.Byte[]") { Byte[] x; x = (Byte[])values; Char v; for (int i = 0; i < x.Length; i++) { v = Convert.ToChar(x[i]); sValue = sValue + v.ToString(); } addAttributeValue(wSL, wKey, sValue.ToString()); } else { addAttributeValue(wSL, wKey, values.ToString()); } } } } //mResult.Add(wSL["cn"][0], wSL); } } } catch (Exception ex) { string msg = ex.Message; } return(wSL); }
public List <Dictionary <string, dynamic> > SearchLdapUserData(string searchUser) { //dEntry.Path= path; DirectorySearcher dSearcher = new DirectorySearcher(dEntry); List <Dictionary <string, dynamic> > ldapUserDataCollection = new List <Dictionary <string, dynamic> >(); //Dictionary<int, Dictionary<string, string>> ldapUserData = new Dictionary<int, Dictionary<string, string>>(); dSearcher.Filter = "(|(cn=*" + searchUser + "*)(samaccountname=*" + searchUser + "*)(displayname=*" + searchUser + "*)(sn=*" + searchUser + "*))"; SearchResultCollection results = dSearcher.FindAll(); if (results != null) { // user exists, cycle through LDAP fields (cn, telephonenumber etc.) foreach (SearchResult result in results) { ResultPropertyCollection fields = result.Properties; Dictionary <string, dynamic> ldapUserData = new Dictionary <string, dynamic>(); string searchName = ""; foreach (String ldapField in fields.PropertyNames) { // cycle through objects in each field e.g. group membership // (for many fields there will only be one object such as name) foreach (Object myCollection in fields[ldapField]) { Debug.WriteLine(ldapField + "," + myCollection.ToString()); if (listLdapField.Contains(ldapField)) { if (ldapField == "manager") { string strManager = myCollection.ToString(); string pattern = "^CN=(.*),OU"; Match m = Regex.Match(strManager, pattern, RegexOptions.IgnoreCase); if (m.Success) { string manager = m.Groups[1].Value; ldapUserData.Add(ldapField, manager); Debug.WriteLine(manager); Debug.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index); } else { ldapUserData.Add(ldapField, ""); } //var pattern = Regex.Match(strManager, ); //Debug.WriteLine(pattern); } else { ldapUserData.Add(ldapField, myCollection.ToString()); } if (ldapField == "samaccountname") { searchName = myCollection.ToString(); } } } } Dictionary <string, dynamic> userRole = GetUserDb(searchName); if (userRole != null) { foreach (var roleData in userRole) { ldapUserData.Add(roleData.Key, roleData.Value); } } ldapUserDataCollection.Add(ldapUserData); } } else { // user does not exist Console.WriteLine("User not found!"); } return(ldapUserDataCollection); }
// Check if mobile id authenicator is available for the user private bool isAvailableForUser(Claim identityClaim, IAuthenticationContext ctx) { logger.TraceEvent(TraceEventType.Verbose, 0, "IsAvailableForUser(claim=" + _str(identityClaim) + ", ctx=" + _str(ctx) + ")"); string upn = identityClaim.Value; // UPN Claim from the mandatory Primary Authentication string msisdn = null; string snOfDN = null; bool needLoadSerialNumber = cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.warnMismatch) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence) || !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowMismatch); // Search for the user try { using (DirectoryEntry entry = new DirectoryEntry()) { DirectorySearcher ds = new DirectorySearcher(entry); ds.SearchScope = SearchScope.Subtree; ds.Filter = "(&(objectClass=user)(objectCategory=person)(userPrincipalName=" + upn + "))"; ds.PropertiesToLoad.Add(cfgAdfs.AdAttrMobile); if (needLoadSerialNumber) { ds.PropertiesToLoad.Add(cfgAdfs.AdAttrMidSerialNumber); } SearchResult result = ds.FindOne(); if (result != null) { ResultPropertyCollection propertyCollection = result.Properties; foreach (string thisProperty in propertyCollection.PropertyNames) { foreach (string propertyValue in propertyCollection[thisProperty]) { if (thisProperty.ToLower(System.Globalization.CultureInfo.InvariantCulture) == cfgAdfs.AdAttrMobile) { msisdn = propertyValue.ToString(); string msisdnSanitized; try { msisdnSanitized = Util.SanitizePhoneNumber(msisdn, cfgMid); } catch (Exception e) { Logging.Log.AttrMobileMalformed(upn, msisdn); throw e; } ctx.Data.Add(MSISDN, msisdnSanitized); // let it blow up if MSISDN is ambiguous } if (needLoadSerialNumber && (thisProperty.ToLower(System.Globalization.CultureInfo.InvariantCulture) == cfgAdfs.AdAttrMidSerialNumber)) { snOfDN = propertyValue.ToString(); if (cfgAdfs.AdAttrMidSerialNumber == "altsecurityidentities") { // special treatment for attribute altSecurityIdentities (1.2.840.113556.1.4.867, https://msdn.microsoft.com/en-us/library/ms677943.aspx) if (!string.IsNullOrWhiteSpace(snOfDN) && snOfDN.StartsWith("MID:<SN>", true, CultureInfo.InvariantCulture)) { ctx.Data.Add(UKEYSN, snOfDN.Substring(8)); // let it blow up if UKEYSN is ambiguous } ; } else { ctx.Data.Add(UKEYSN, propertyValue.ToString()); // let it blow up if UKEYSN is ambiguous } } } } //EventLog.WriteEntry(EVENTLOGSource, "Found user " + upn + " using " + ds.Filter + // " with properties " + cfgAdfs.AdAttrMobile + "=" + msisdn + "," + cfgAdfs.AdAttrMidSerialNumber + "=" + snOfDN); logger.TraceEvent(TraceEventType.Verbose, 0, "AdSearch.Found: upn=" + upn + ", filter=" + ds.Filter + ", " + cfgAdfs.AdAttrMobile + "=" + msisdn + ", " + cfgAdfs.AdAttrMidSerialNumber + "=" + snOfDN); Logging.Log.AdSearch(upn, ds.Filter, cfgAdfs.AdAttrMobile, msisdn, cfgAdfs.AdAttrMidSerialNumber, snOfDN); } else { // EventLog.WriteEntry(EVENTLOGSource, "User not found " + upn + " using " + ds.Filter, EventLogEntryType.Error, 102); logger.TraceEvent(TraceEventType.Warning, 0, "User not found in AD: upn=" + upn + ", ldapFilter=" + ds.Filter); Logging.Log.AttrUserNotFound(upn, ds.Filter); } ds.Dispose(); } } catch (Exception ex) { logger.TraceEvent(TraceEventType.Error, 0, "AD Search Error: " + ex.Message); Logging.Log.AdSearchError(ex.Message); return(false); } if (String.IsNullOrEmpty(msisdn)) { // EventLog.WriteEntry(EVENTLOGSource, "Method not available for user " + upn + " (no MSISN requireExistence)", EventLogEntryType.Error, 102); logger.TraceEvent(TraceEventType.Warning, 0, "Mobile ID not available for " + upn + ": mobile attribute not found in AD"); Logging.Log.AttrMobileNotFound(upn); return(false); } if (String.IsNullOrEmpty(snOfDN) && !cfgMid.UserSerialNumberPolicy.HasFlag(UserSerialNumberPolicy.allowAbsence)) { logger.TraceEvent(TraceEventType.Information, 0, "Serial Number not found for " + upn); Logging.Log.AttrUserSerialNumberNotFound(upn); return(false); } // store "session"-scope information to ctx. The life time of a "session" is identical with the lifetime of ctx. // It seems to begin with a BeginAuthentication(...), continue with 0+ TryEndAuthentication(...), // ends when (a) TryEndAuthentication(...) returns null and claim, or (b) on browser closure, or (c) on timeout. ctx.Data.Add(USERUPN, upn); return(true); }
/// <summary> /// Builds the result properties. /// </summary> /// <param name="resultMapId">The result map id.</param> /// <param name="resultMapConfig">The result map config.</param> /// <param name="resultClass">The result class.</param> /// <param name="prefix">The prefix.</param> /// <param name="suffix">The suffix.</param> /// <param name="dataExchangeFactory">The data exchange factory.</param> /// <param name="waitResultPropertyResolution">The wait result property resolution.</param> /// <returns></returns> private static ResultPropertyCollection BuildResultProperties( string resultMapId, IConfiguration resultMapConfig, Type resultClass, string prefix, string suffix, DataExchangeFactory dataExchangeFactory, WaitResultPropertyResolution waitResultPropertyResolution) { ResultPropertyCollection properties = new ResultPropertyCollection(); //获取result节点的集合配置信息 ConfigurationCollection resultsConfig = resultMapConfig.Children.Find(ConfigConstants.ELEMENT_RESULT); for (int i = 0; i < resultsConfig.Count; i++) { ResultProperty mapping = null; try { mapping = ResultPropertyDeSerializer.Deserialize(resultsConfig[i], resultClass, prefix, suffix, dataExchangeFactory); } catch(Exception e) { throw new ConfigurationException("In ResultMap (" + resultMapId + ") can't build the result property: " + ConfigurationUtils.GetStringAttribute(resultsConfig[i].Attributes, ConfigConstants.ATTRIBUTE_PROPERTY) + ". Cause " + e.Message, e); } if (mapping.NestedResultMapName.Length > 0)//resultMapping属性如果有值 此处一般会有 { //添加到DefaultModelBuilder中的ResultPropertyCollection nestedProperties集合中 waitResultPropertyResolution(mapping); } properties.Add(mapping); } return properties; }
public Dictionary <string, object> AuthenWithDomain(string username, string password) { Dictionary <string, object> userDetail = new Dictionary <string, object>(); string domainAndUsername = null; domainAndUsername = string.Format(@"{0}\{1}", this.Domain, username); entry = new DirectoryEntry(Path, domainAndUsername, password); try { Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); string usernameField = !string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_USERNAME_FIELD")) ? AMSCore.WebConfigReadKey("AD_USERNAME_FIELD") : "SAMAccountName"; search.Filter = "(" + usernameField + "=" + domainAndUsername + ")"; string[] requiredProps = { }; if (!string.IsNullOrEmpty(AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS"))) { //The input string is in the "xxxx,xx,xxxxx" format. //It has to be transformed to an array of string. requiredProps = AMSCore.WebConfigReadKey("AD_DIRECTORY_PROPERTY_OUTPUT_FIELDS").Split(','); search.PropertiesToLoad.AddRange(requiredProps); } SearchResult result = search.FindOne(); if (result != null) { if (requiredProps.Length > 0)//if the required property is not null or emptry { ResultPropertyCollection resultPropColl = result.Properties; foreach (string prop in requiredProps) { foreach (Object memberColl in resultPropColl[prop]) { userDetail.Add(prop, memberColl); } } } else //if the required property is null or emptry, it will return all properties. { var enumEntry = result.Properties.GetEnumerator(); while (enumEntry.MoveNext()) { object value = enumEntry.Value; if (value is DateTime) { value = Util.DateTimeToString(value as DateTime?); } userDetail.Add(enumEntry.Key.ToString(), value); } } } } catch { return(userDetail); } finally { entry.Close(); } return(userDetail); }