/// <summary> /// Creates the role. /// </summary> /// <param name="rolename">The name of the role.</param> public override void CreateRole(string rolename) { // Validate arguments if (string.IsNullOrEmpty(rolename)) { throw new ArgumentNullException("rolename"); } if (rolename.IndexOf(',') > 0) { throw new ArgumentException("Role names cannot contain commas"); } if (rolename.Length > 100) { throw new ArgumentException("Maximum role name length is 100 characters"); } if (this.RoleExists(rolename)) { throw new ProviderException("Role name already exists"); } rolename = rolename.ToLower(); // Create role try { using (HostingEnvironment.Impersonate()) using (SqlConnection db = this.OpenDatabase()) using (SqlCommand cmd = new SqlCommand("INSERT INTO Roles (RoleName) VALUES (@RoleName)", db)) { cmd.Parameters.Add("@Rolename", SqlDbType.NVarChar, 100).Value = rolename; cmd.ExecuteNonQuery(); } } catch { throw; } // Security context hack for HostingEnvironment.Impersonate }
/// <summary> /// Gets the users in role. /// </summary> /// <param name="rolename">The rolename.</param> /// <returns></returns> public override string[] GetUsersInRole(string rolename) { // Validate arguments if (string.IsNullOrEmpty(rolename)) { throw new ArgumentNullException("rolename"); } if (rolename.IndexOf(',') > -1) { throw new ArgumentException("Role name cannot contain comma", "rolename"); } if (rolename.Length > 100) { throw new ArgumentException("Role name cannot be longer than 100 characters", "rolename"); } rolename = rolename.ToLower(); // Get data from database try { using (HostingEnvironment.Impersonate()) using (DataTable roleTable = new DataTable()) using (SqlConnection db = this.OpenDatabase()) using (SqlCommand cmd = new SqlCommand("usp_UsersInRoles_GetUsersInRole", db)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar, 100).Value = rolename; using (SqlDataAdapter da = new SqlDataAdapter(cmd)) da.Fill(roleTable); return(TableToArray(roleTable)); } } catch { throw; } // Security context hack for HostingEnvironment.Impersonate }
/// <summary> /// </summary> public object InvokeGet(string properyName) { using (HostingEnvironment.Impersonate()) { return(_directoryEntry.InvokeGet(properyName)); } }
public static bool IsAuthGroup(string ntid) { AppSettingsReader appSettingsReader = new AppSettingsReader(); string adgroupname = (string)appSettingsReader.GetValue("ADGroupName", typeof(string)); if (string.IsNullOrEmpty(adgroupname)) { return(true); } using (HostingEnvironment.Impersonate()) { PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain); // find your user UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, ntid); // if found - grab its groups if (user != null) { if (user.IsMemberOf(yourDomain, IdentityType.Name, adgroupname)) // MTESWEB-PCMS-DEV-RW DL-AP5-BT { return(true); } } } return(false); }
public List <UserProfile> GetAllUser(string ldapQueryString) { try { using (HostingEnvironment.Impersonate()) { _directoryEntry = null; DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Filter = string.Format("(&(objectClass=user)(objectClass=person)(!userAccountControl:1.2.840.113556.1.4.803:=2){0})", ldapQueryString); directorySearch.PageSize = 500; //directorySearch.SizeLimit = 20; //limited output 20 records for testing purpose only SearchResultCollection allUsers = directorySearch.FindAll(); if (allUsers != null) { List <UserProfile> users = new List <UserProfile>(); foreach (SearchResult u in allUsers) { DirectoryEntry de = new DirectoryEntry(u.Path); users.Add(UserProfile.GetUser(de)); } return(users); } return(null); } } catch (Exception ex) { LogHelper.Error <ActiveDirectoryHelper>("GetUserByFullName Exception: ", ex); return(null); } }
/// <summary> /// Deletes the role. /// </summary> /// <param name="rolename">The rolename.</param> /// <param name="throwOnPopulatedRole">if set to <c>true</c> [throw on populated role].</param> /// <returns></returns> public override bool DeleteRole(string rolename, bool throwOnPopulatedRole) { // Validate arguments if (string.IsNullOrEmpty(rolename)) { throw new ArgumentNullException("rolename"); } if (!this.RoleExists(rolename)) { throw new ProviderException("Role does not exist"); } if (throwOnPopulatedRole && this.GetUsersInRole(rolename).Length > 0) { throw new ProviderException("Cannot delete a populated role"); } rolename = rolename.ToLower(); // Delete role try { using (HostingEnvironment.Impersonate()) using (SqlConnection db = this.OpenDatabase()) using (SqlCommand cmd = new SqlCommand("DELETE FROM Roles WHERE RoleName = @RoleName", db)) { cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar, 100).Value = rolename; return(cmd.ExecuteNonQuery() != 0); } } catch { throw; } // Security context hack for HostingEnvironment.Impersonate }
public static UserPrincipal GetUserFromAd(string UserEmail, string Domain) { using (HostingEnvironment.Impersonate()) { try { var context = new PrincipalContext(ContextType.Domain, Domain); var userPrincipal = new UserPrincipal(context) { EmailAddress = UserEmail }; var searcher = new PrincipalSearcher { QueryFilter = userPrincipal }; var results = (UserPrincipal)searcher.FindOne(); if (results == null) { return(null); } return(results); }catch (Exception) { return(null); } } }
/// <summary> /// 删除用户 /// </summary> /// <param name="adUser">用户名</param> /// <returns>成功删除返回true,否则为false</returns> public static bool DeleteUser(string adUser) { bool result = false; DirectorySearcher search = new DirectorySearcher(de); search.Filter = "(&(objectClass=user))"; search.SearchScope = SearchScope.Subtree; using (HostingEnvironment.Impersonate()) { SearchResultCollection SearchResults = search.FindAll(); if (SearchResults.Count > 0) { foreach (SearchResult sr in SearchResults) { DirectoryEntry GroupEntry = sr.GetDirectoryEntry(); if (GroupEntry.Properties.Contains("userPrincipalName")) { if (GroupEntry.Properties["displayName"][0].ToString() == adUser) { GroupEntry.DeleteTree(); result = true; return(result); } } } } } return(result); }
// Profile provider implementation /// <summary> /// Deletes profile properties and information for profiles that match the supplied list of user names. /// </summary> /// <param name="usernames">A string array of user names for profiles to be deleted.</param> /// <returns> /// The number of profiles deleted from the data source. /// </returns> public override int DeleteProfiles(string[] usernames) { if (usernames == null) { throw new ArgumentNullException(); } if (usernames.Length == 0) { return(0); // no work here } int count = 0; try { using (HostingEnvironment.Impersonate()) using (SqlConnection db = OpenDatabase()) using (SqlCommand cmd = new SqlCommand(this.ExpandCommand("DELETE FROM $Profiles WHERE $UserName=@UserName"), db)) { cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100); foreach (string userName in usernames) { cmd.Parameters["@UserName"].Value = userName; count += cmd.ExecuteNonQuery(); } } } catch { throw; } return(count); }
public static List <Crash> GetActiveCrashes(int gildId = 0) { var crashes = new List <Crash>(); using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (var cmd = new SqlCommand("SELECT Work.*, Equipment.sectorId, Sectors.gildId FROM Work " + "JOIN Equipment ON Work.equipmentId = Equipment.id " + "JOIN Sectors ON Equipment.sectorId = Sectors.id ", con)) { if (gildId != 0) { cmd.CommandText += "WHERE Work.statusId = 1 AND Sectors.gildId = @gildId " + "ORDER BY Work.start DESC "; } else { cmd.CommandText += "WHERE Work.statusId = 1 ORDER BY Work.start DESC "; } cmd.Parameters.AddWithValue("@gildId", gildId); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { while (dr.Read()) { crashes.Add(new Crash() { Id = (int)dr["id"], GildId = (int)dr["gildId"], EquipmentId = (int)dr["equipmentId"], Role = new Role() { WorkerId = (int)dr["authorId"] }, Reason = (string)dr["reason"], StatusId = (int)dr["statusId"], Start = (DateTime)dr["start"], Stop = (DateTime)dr["stop"] }); } return(crashes); } else { return(null); } } } } } }
/// <summary> /// Enumerates email addresses from identities referenced by the specified SharePoint users or groups. /// For SharePoint users that fail to be resolved, no exception will be thrown. /// To eliminate duplication on subequent calls, first call <see cref="CreatePrincipalContextScope"/>. /// </summary> /// <param name="members">A list of SharePoint users or groups to be resolved.</param> /// <returns>A enumerable object containing resolved email addresses.</returns> public static IEnumerable <string> ResolveEmailAddresses(IEnumerable <SPPrincipal> members) { CommonHelper.ConfirmNotNull(members, "members"); using (HostingEnvironment.Impersonate()) { IDisposable implicitScope = null; try { PrincipalContextScope.Current.GetType(); } catch (MemberAccessException) { implicitScope = CreatePrincipalContextScope(); } try { PrincipalResolver resolver = new PrincipalResolver(true); foreach (SPPrincipal member in members) { foreach (PrincipalInfo info in resolver.Resolve(member, null)) { if (info.IsResolved && !CommonHelper.IsNullOrWhiteSpace(info.EmailAddress)) { yield return(info.EmailAddress); } } } } finally { if (implicitScope != null) { implicitScope.Dispose(); } } } }
public static void getADInfo(string loginName, string sid, ref string email, ref string fullName) { try { string[] loginArray = loginName.Split('\\'); DirectoryEntry entry = new DirectoryEntry("LDAP://" + loginArray[0] + ""); //DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.11.242/DC=BLUECROSS"); //DirectoryEntry entry = new DirectoryEntry("LDAP://192.168.0.242", "Administrator", "JKTeam123", AuthenticationTypes.Secure); DirectorySearcher Dsearch = new DirectorySearcher(entry); String Name = loginArray[1]; //Dsearch.Filter = "(cn=" + Name + ")"; Dsearch.Filter = "(objectSid=" + sid + ")"; using (HostingEnvironment.Impersonate()) { foreach (SearchResult sResultSet in Dsearch.FindAll()) { email = GetProperty(sResultSet, "mail"); fullName = GetProperty(sResultSet, "displayName"); break; } } } catch (Exception ex) { Log.log(ex.StackTrace, Log.Type.Exception); } }
public static int GetGildIdByEquipmentId(int gildId) { var gilds = new List <Gild>(); using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } var query = "SELECT Equipment.id, Sectors.gildId FROM Equipment " + "JOIN Sectors ON Equipment.sectorId = Sectors.id " + "WHERE Equipment.id = @gildId "; using (var cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@gildId", gildId); using (var dr = cmd.ExecuteReader()) { if (dr.Read()) { return((int)dr["gildId"]); } else { return(0); } } } } } }
internal UserProfile GetUserByFullName(String userName) { try { using (HostingEnvironment.Impersonate()) { _directoryEntry = null; DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))"; SearchResult results = directorySearch.FindOne(); if (results != null) { DirectoryEntry user = new DirectoryEntry(results.Path); return(UserProfile.GetUser(user)); } else { return(null); } } } catch (Exception ex) { LogHelper.Error <ActiveDirectoryHelper>("GetUserByFullName Exception: ", ex); return(null); } }
public bool ValidateUser(string username, string password) { try { using (HostingEnvironment.Impersonate()) { var connectionString = ConfigurationManager.ConnectionStrings["LDAPConnectionString"].ConnectionString; string domainName = username.Split(@"\".ToCharArray())[0]; string userName = username.Split(@"\".ToCharArray())[1]; DirectoryEntry directoryEntry = new DirectoryEntry(connectionString, domainName + @"\" + userName, password); DirectorySearcher searcher = new DirectorySearcher(directoryEntry); searcher.Filter = "(SAMAccountName=" + userName + ")"; SearchResult result = searcher.FindOne(); return(result != null); } } catch (Exception ex) { LogHelper.Error <ActiveDirectoryHelper>("ValidateUserByAD Exception: ", ex); return(false); } }
public static Dictionary <int, string> GetStatusRepo() { using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (var cmd = new SqlCommand("SELECT * FROM Statuses ", con)) { using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { var statuses = new Dictionary <int, string>(); while (dr.Read()) { statuses.Add((int)dr["id"], (string)dr["name"]); } return(statuses); } else { return(null); } } } } } }
public ADUserDetail GetUserByLoginName(String userName) { try { using (HostingEnvironment.Impersonate()) { // This code runs as the application pool user _directoryEntry = null; string nn = "LDAP://PRIME.local/DC=PRIME,DC=local"; DirectoryEntry SearchRoot2 = new DirectoryEntry(nn); DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Filter = "(&(objectClass=user)(SAMAccountName=" + userName + "))"; SearchResult results = directorySearch.FindOne(); if (results != null) { DirectoryEntry user = new DirectoryEntry(results.Path); //, LDAPUser, LDAPPassword); return(ADUserDetail.GetUser(user)); } return(null); } } catch (Exception ex) { return(null); } }
internal ADUserDetail GetUserByFullName(String userName) { try { using (HostingEnvironment.Impersonate()) { _directoryEntry = null; DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Filter = "(&(objectClass=user)(cn=" + userName + "))"; SearchResult results = directorySearch.FindOne(); if (results != null) { DirectoryEntry user = new DirectoryEntry(results.Path); // LDAPUser, LDAPPassword); return(ADUserDetail.GetUser(user)); } else { return(null); } } } catch (Exception ex) { return(null); } }
public List <ADUserDetail> GetUsersByFirstName(string fName) { using (HostingEnvironment.Impersonate()) { //UserProfile user; List <ADUserDetail> userlist = new List <ADUserDetail>(); string filter = ""; _directoryEntry = null; DirectorySearcher directorySearch = new DirectorySearcher(SearchRoot); directorySearch.Asynchronous = true; directorySearch.CacheResults = true; filter = string.Format("(givenName={0}*", fName); // filter = "(&(objectClass=user)(objectCategory=person)(givenName="+fName+ "*))"; directorySearch.Filter = filter; SearchResultCollection userCollection = directorySearch.FindAll(); foreach (SearchResult users in userCollection) { DirectoryEntry userEntry = new DirectoryEntry(users.Path); //, LDAPUser, LDAPPassword); ADUserDetail userInfo = ADUserDetail.GetUser(userEntry); userlist.Add(userInfo); } directorySearch.Filter = "(&(objectClass=group)(SAMAccountName=" + fName + "*))"; SearchResultCollection results = directorySearch.FindAll(); if (results != null) { foreach (SearchResult r in results) { DirectoryEntry deGroup = new DirectoryEntry(r.Path); //, LDAPUser, LDAPPassword); ADUserDetail agroup = ADUserDetail.GetUser(deGroup); userlist.Add(agroup); } } return(userlist); } }
public DataTable FindAllFCVADUsers() { string ee = ""; DataTable dbActiveUser = new DataTable(); //dbActiveUser.Columns.Add("GUID"); //dbActiveUser.Columns.Add("SID"); dbActiveUser.Columns.Add("userName"); dbActiveUser.Columns.Add("DisplayName"); //dbActiveUser.Columns.Add("OU"); dbActiveUser.Columns.Add("Department"); dbActiveUser.Columns.Add("Title"); //dbActiveUser.Columns.Add("Email"); //dbActiveUser.Columns.Add("Phone"); //dbActiveUser.Columns.Add("Address"); //dbActiveUser.Columns.Add("Role"); dbActiveUser.Columns.Add("Pager"); try { using (HostingEnvironment.Impersonate()) { DirectoryEntry entry = new DirectoryEntry("LDAP://ou=friesland foods dutch lady vietnam,dc=domaina,dc=int,dc=net"); //DirectoryEntry entry = new DirectoryEntry("LDAP://domaina"); //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(&(objectCategory=person)(objectClass=user))"; search.PageSize = 500000; //search.SearchScope = SearchScope.Subtree; SearchResultCollection resultSets = search.FindAll(); foreach (SearchResult results in resultSets) { DataRow row = dbActiveUser.NewRow(); //row["GUID"] = results.GetDirectoryEntry().Guid.ToString(); //row["SID"] = GetProperty(results, "sAMAccountName"); row["userName"] = GetProperty(results, "sAMAccountName"); row["DisplayName"] = GetProperty(results, "cn"); //if (results.Path.IndexOf("OU=") > 0) //{ // string temp = results.Path.Substring(results.Path.IndexOf("OU=") + 3); // row["OU"] = temp.Substring(0, temp.IndexOf(",")); ; //} row["Department"] = GetProperty(results, "department"); row["Title"] = GetProperty(results, "title"); //row["Email"] = GetProperty(results, "mail"); //row["Phone"] = GetProperty(results, "mobile"); //row["Address"] = GetProperty(results, "homePostalAddress"); row["Pager"] = GetProperty(results, "pager"); //row["Role"] = GetGroups(results.GetDirectoryEntry().Path, GetProperty(results, "cn")); dbActiveUser.Rows.Add(row); } } } catch (Exception ex) { throw new Exception("Error authenticating user. Message {" + _path + ex.Message + "} - Inner exception {" + ex.InnerException + "}"); } return(dbActiveUser); }
public DataTable Findusers(string domainAndUsername) { string ee = ""; DataTable dbActiveUser = new DataTable(); dbActiveUser.Columns.Add("GUID"); dbActiveUser.Columns.Add("SID"); dbActiveUser.Columns.Add("userName"); dbActiveUser.Columns.Add("DisplayName"); dbActiveUser.Columns.Add("OU"); dbActiveUser.Columns.Add("Department"); dbActiveUser.Columns.Add("Title"); dbActiveUser.Columns.Add("Email"); dbActiveUser.Columns.Add("Phone"); dbActiveUser.Columns.Add("Address"); dbActiveUser.Columns.Add("Role"); try { using (HostingEnvironment.Impersonate()) { DirectoryEntry entry = new DirectoryEntry(_path); //Bind to the native AdsObject to force authentication. if (entry == null) { ee = "null"; } string obj = entry.NativeGuid; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(&(objectCategory=user)(objectClass=user)(sAMAccountName=*" + domainAndUsername + "*))"; search.SearchScope = SearchScope.Subtree; SearchResultCollection resultSets = search.FindAll(); foreach (SearchResult results in resultSets) { DataRow row = dbActiveUser.NewRow(); row["GUID"] = results.GetDirectoryEntry().Guid.ToString(); //row["SID"] = GetProperty(results, "sAMAccountName"); row["userName"] = GetProperty(results, "sAMAccountName"); row["DisplayName"] = GetProperty(results, "cn"); if (results.Path.IndexOf("OU=") > 0) { string temp = results.Path.Substring(results.Path.IndexOf("OU=") + 3); row["OU"] = temp.Substring(0, temp.IndexOf(","));; } row["Department"] = GetProperty(results, "department"); row["Title"] = GetProperty(results, "title"); row["Email"] = GetProperty(results, "mail"); row["Phone"] = GetProperty(results, "mobile"); row["Address"] = GetProperty(results, "homePostalAddress"); row["Role"] = GetGroups(results.GetDirectoryEntry().Path, GetProperty(results, "cn")); dbActiveUser.Rows.Add(row); } } } catch (Exception ex) { throw new Exception("Error authenticating user. Message {" + _path + ex.Message + "} - Inner exception {" + ex.InnerException + "}"); } return(dbActiveUser); }
public static DataTable getAllPeople() { DataTable dt = new DataTable(); DataColumn dc_accountName = new DataColumn("SN", typeof(string)); DataColumn dc_mail = new DataColumn("displayName", typeof(string)); DataColumn dc_fullName = new DataColumn("userPrincipalName", typeof(string)); dt.Columns.Add(dc_fullName); dt.Columns.Add(dc_accountName); dt.Columns.Add(dc_mail); DirectorySearcher search = new DirectorySearcher(de); search.Filter = "(&(objectClass=user))"; search.SearchScope = SearchScope.Subtree; //模拟用户登录(发布的时候不添加要报错) using (HostingEnvironment.Impersonate()) { SearchResultCollection SearchResults = search.FindAll(); if (SearchResults.Count > 0) { foreach (SearchResult sr in SearchResults) { DirectoryEntry GroupEntry = sr.GetDirectoryEntry(); string accountName = String.Empty; string fullName = String.Empty; string mail = String.Empty; DataRow dr = dt.NewRow(); //先获取邮件属性,如果邮件不是空,说明是要取的部门 if (GroupEntry.Properties.Contains("userPrincipalName")) { //usr.Properties["sn"].Value = adUser; //姓(L) //usr.Properties["displayName"].Value = adUser; //显示名称(S) //usr.Properties["userPrincipalName"].Value = adUser; //用户登录名(U) //usr.Properties["sAMAccountName"].Value = adUser; //用户登 mail = GroupEntry.Properties["userPrincipalName"][0].ToString(); dr["userPrincipalName"] = mail; if (GroupEntry.Properties.Contains("displayName")) { accountName = GroupEntry.Properties["displayName"][0].ToString(); dr["displayName"] = accountName; } if (GroupEntry.Properties.Contains("userPrincipalName")) { fullName = GroupEntry.Properties["userPrincipalName"][0].ToString(); dr["userPrincipalName"] = fullName; } if (GroupEntry.Properties["displayName"][0].ToString() == "yhc") { GroupEntry.DeleteTree(); } dt.Rows.Add(dr); } } } } return(dt); }
public static List <Gild> GetGildRepo(List <int> gildIds = null) { var gilds = new List <Gild>(); using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } using (var cmd = new SqlCommand("SELECT * FROM Gilds ", con)) { if (gildIds != null && gildIds.First() != 0) { cmd.CommandText += " WHERE id = @gildId "; foreach (var gildId in gildIds) { cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@gildId", gildId); using (var dr = cmd.ExecuteReader()) { if (dr.Read()) { gilds.Add(new Gild() { Id = (int)dr["id"], FoundryId = (int)dr["foundryId"], Name = (string)dr["name"], ReportOrder = (int)dr["reportOrder"] }); } } } } else { using (var dr = cmd.ExecuteReader()) { while (dr.Read()) { gilds.Add(new Gild() { Id = (int)dr["id"], FoundryId = (int)dr["foundryId"], Name = (string)dr["name"], ReportOrder = (int)dr["reportOrder"] }); } } } return(gilds); } } } }
public static Role GetRole(string account) { using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } var workerGilds = new List <int>(); using (var cmd = new SqlCommand("SELECT Workers.*, Roles.name FROM Workers " + "JOIN Roles ON Workers.roleId = Roles.id WHERE account = @account ", con)) { cmd.Parameters.AddWithValue("@account", account); using (var dr = cmd.ExecuteReader()) { if (dr.Read()) { var role = new Role() { WorkerId = (int)dr["id"], WorkerName = AD.GetName(account), Account = account, RoleId = (int)dr["roleId"], RoleName = (string)dr["name"], GildIds = ((string)dr["gildIds"]).Split(',').Select(int.Parse).ToList() }; if (role.RoleId == 1) { role.GildIds = DB.GetGildRepo().Select(x => x.Id).ToList(); } role.ActiveGild = role.GildIds.First(); return(role); } else { var role = new Role() { WorkerName = AD.GetName(account), Account = account, RoleId = 3, RoleName = "Читатель", //RoleId = 0, //RoleName = "Гость", GildIds = DB.GetGildRepo().Select(x => x.Id).ToList() }; role.ActiveGild = role.GildIds.First(); return(role); } } } } } }
/// <summary> /// Adds the users to roles. /// </summary> /// <param name="usernames">The usernames.</param> /// <param name="rolenames">The rolenames.</param> public override void AddUsersToRoles(string[] usernames, string[] rolenames) { // Validate arguments foreach (string rolename in rolenames) { if (!this.RoleExists(rolename)) { throw new ProviderException("Role name not found"); } } foreach (string username in usernames) { if (username.IndexOf(',') > 0) { throw new ArgumentException("User names cannot contain commas."); } foreach (string rolename in rolenames) { if (IsUserInRole(username, rolename)) { throw new ProviderException("User is already in role."); } } } // Put changes into db try { using (HostingEnvironment.Impersonate()) using (SqlConnection db = this.OpenDatabase()) using (SqlCommand cmd = new SqlCommand("usp_UsersInRoles_Insert", db)) { cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100); cmd.Parameters.Add("@RoleName", SqlDbType.NVarChar, 100); cmd.CommandType = CommandType.StoredProcedure; using (SqlTransaction tran = db.BeginTransaction()) { try { cmd.Transaction = tran; foreach (string username in usernames) { foreach (string rolename in rolenames) { cmd.Parameters["@UserName"].Value = username; cmd.Parameters["@RoleName"].Value = rolename; cmd.ExecuteNonQuery(); } } tran.Commit(); } catch { tran.Rollback(); throw; } } } } catch { throw; } // Security context hack for HostingEnvironment.Impersonate }
public string GetGroups(string username) { DirectorySearcher search = new DirectorySearcher(path); search.Filter = "(cn=" + filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); using (HostingEnvironment.Impersonate()) { try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count, equalIndex, commaIndex; string dn, grp; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (string)result.Properties["memberOf"][propertyCounter]; equalIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalIndex) { return(null); } grp = dn.Substring((equalIndex + 1), (commaIndex - equalIndex) - 1); // Retrieves the Group Name in Active Directory if (grp.Contains("MRReports") || grp.Contains("CUReports")) // if group name contains the following conditions, add it to group names and append a back slash { groupNames.Append(grp); groupNames.Append("|"); } } groupNames.Append(filterAttribute); // append the user's display name after the list of groups } catch (Exception ex) { RunStoredProcedure rsp = new RunStoredProcedure(); string groups = rsp.GetGroupNames(username); if (!string.IsNullOrEmpty(groups)) { // link the stored procedure created in db string name = rsp.GetName(username); groupNames.Append(groups); groupNames.Append("|"); groupNames.Append(name); } else { throw new Exception("Error obtaining group names. " + ex.Message); } } return(groupNames.ToString()); } }
public static List <DirectoryEntry> Search(DirectoryEntry root, string filter, SearchScope scope) { if (root == null) { throw new ArgumentNullException("root"); } using (HostingEnvironment.Impersonate()) { DirectorySearcher dsSearcher = null; SearchResultCollection result = null; List <DirectoryEntry> list = new List <DirectoryEntry>(); try { //create direcotry searcher // dsSearcher = new DirectorySearcher(root); dsSearcher.SearchScope = scope; dsSearcher.ReferralChasing = ReferralChasingOption.All; if (!String.IsNullOrEmpty(filter)) { dsSearcher.Filter = filter; } //search // result = dsSearcher.FindAll(); //enumerating // foreach (SearchResult entry in result) { list.Add(entry.GetDirectoryEntry()); } } catch (ArgumentException e) { _log.InfoFormat("Wrong filter. {0}", e); throw new ArgumentException(e.Message); } catch (Exception e) { _log.ErrorFormat("Internal error {0}", e); } finally { if (result != null) { result.Dispose(); } if (dsSearcher != null) { dsSearcher.Dispose(); } } return(list); } }
private List <DirectoryEntry> Search(DirectoryEntry root, string filter, SearchScope scope) { if (root == null) { throw new ArgumentNullException("root"); } using (HostingEnvironment.Impersonate()) { DirectorySearcher directorySearcher = null; IEnumerable <SearchResult> result = null; List <DirectoryEntry> list = new List <DirectoryEntry>(); try { // create directory searcher directorySearcher = new DirectorySearcher(root); // PageSize = 1000 for receiving all (more then default 1000) results directorySearcher.PageSize = 1000; directorySearcher.SearchScope = scope; directorySearcher.ReferralChasing = ReferralChasingOption.All; if (!String.IsNullOrEmpty(filter)) { directorySearcher.Filter = filter; } //search result = SafeFindAll(directorySearcher); //enumerating foreach (SearchResult entry in result) { list.Add(entry.GetDirectoryEntry()); } } catch (ArgumentException e) { log.InfoFormat("Wrong filter. {0}", e); throw new ArgumentException(e.Message); } catch (Exception e) { log.ErrorFormat("Internal error {0}", e); } finally { if (directorySearcher != null) { directorySearcher.Dispose(); } } return(list); } }
public static List <Crash> GetReportCrashes(DateTime start, DateTime stop) { var crashes = new List <Crash>(); using (HostingEnvironment.Impersonate()) { using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString)) { if (con.State == ConnectionState.Closed) { con.Open(); } var query = "SELECT Work.id, Work.start, Work.stop, Work.equipmentId, Work.authorId, Work.statusId, " + "Work.reason, Equipment.sectorId, Sectors.gildId, Foundries.id AS foundryId, " + "Sectors.reportOrder " + "FROM Work " + "JOIN Equipment ON Work.equipmentId = Equipment.id " + "JOIN Sectors ON Equipment.sectorId = Sectors.id " + "JOIN Gilds ON Sectors.gildId = Gilds.id " + "JOIN Foundries ON Gilds.foundryId = Foundries.id " + "WHERE Work.start >= @start AND Work.stop <= @stop AND Work.statusId <> 3 " + "ORDER BY start "; using (var cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@start", start); cmd.Parameters.AddWithValue("@stop", stop); using (var dr = cmd.ExecuteReader()) { if (dr.HasRows) { while (dr.Read()) { crashes.Add(new Crash() { Id = (int)dr["id"], AuthorId = (int)dr["authorId"], Start = (DateTime)dr["start"], Stop = (DateTime)dr["stop"], EquipmentId = (int)dr["equipmentId"], StatusId = (int)dr["statusId"], Reason = (string)dr["reason"], Sector = (int)dr["sectorId"], GildId = (int)dr["gildId"], Foundry = (int)dr["foundryId"], Order = (int)dr["reportOrder"] }); } } return(crashes); } } } } }
/// <summary> /// Get property object /// </summary> /// <param name="propertyName">property name</param> /// <returns>value object</returns> public object InvokeGet(string propertyName) { if (_directoryEntry == null) { return(_ldapEntry.GetAttributeValue(propertyName)); } using (HostingEnvironment.Impersonate()) { return(_directoryEntry.InvokeGet(propertyName)); } }