/// <summary> /// Получить группу Active Directory /// </summary> /// <param name="sGroupName">Группа для получения</param> /// <returns>Возвращает объект GroupPrincipal</returns> public static GroupPrincipal GetGroup(string sGroupName) { PrincipalContext oPrincipalContext = GetPrincipalContext(); return(GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName)); }
public static bool isValidUser(string userInfo) { var userName = getLogin(userInfo); var domainName = getDomain(userInfo); var groupToCheck = System.Configuration.ConfigurationManager.AppSettings["groupName"]; var domainToCheck = System.Configuration.ConfigurationManager.AppSettings["domainName"]; logger.Info("Request Details" + Environment.NewLine + userInfo); logger.Info("Group and Domain Setting from config" + Environment.NewLine + " group to check--> " + groupToCheck + " domain to check--> " + domainToCheck); try { // set up domain context logger.Info("set up domain context" + Environment.NewLine + domainToCheck); PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainToCheck); logger.Info("domain context found" + Environment.NewLine + ctx); if (ctx != null) { logger.Info("domain found" + Environment.NewLine + ctx); } else { logger.Info("domain not found" + Environment.NewLine); } // find a user logger.Info("find a user " + Environment.NewLine + userName); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userName); if (user != null) { logger.Info("user found" + Environment.NewLine + user); } else { logger.Info("user not found" + Environment.NewLine); } // find the group in question logger.Info("find a the group " + Environment.NewLine + groupToCheck); GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupToCheck); if (group != null) { logger.Info("group found" + Environment.NewLine + group); } else { logger.Info("group not found" + Environment.NewLine); } if (HttpContext.Current.User.Identity.IsAuthenticated && user != null && group != null) { // Verify that the user is in the given AD group (if any) logger.Info("checking if user is IsAuthenticated" + Environment.NewLine + HttpContext.Current.User.Identity.IsAuthenticated); logger.Info(" check if user is member of that group" + Environment.NewLine + user.IsMemberOf(group)); // check if user is member of that group if (user.IsMemberOf(group)) { logger.Info(" user is Authenticated" + Environment.NewLine + userInfo); return(true); } } logger.Info("Authenticated is failed" + Environment.NewLine + $"not authenticated: {userInfo},username: {userName} ,domainName: {domainName},group: {groupToCheck}"); return(false); } catch (Exception e) { logger.Info("exception occured " + Environment.NewLine + e); return(false); } }
protected override void Execute(CodeActivityContext context) { PrincipalContext principalContext; if (IsLocalAccount.Get(context)) { principalContext = new PrincipalContext(ContextType.Machine); } else { principalContext = new PrincipalContext(ContextType.Domain, Domain.Get(context), DomainContainer.Get(context)); } UserPrincipal principal = UserPrincipal.FindByIdentity(principalContext, Username.Get(context)); if (principal == null) { principal = new UserPrincipal(principalContext, Username.Get(context), Password.Get(context), true); principal.DisplayName = Firstname.Get(context) + " " + Lastname.Get(context); principal.PasswordNeverExpires = true; principal.Save(); IList <string> groups = GroupMemberships.Get(context) ?? new List <string>(); foreach (var group in groups) { GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, group); if (!groupPrincipal.Members.Contains(principal)) { groupPrincipal.Members.Add(principal); } groupPrincipal.Save(); } } else if (UpdateExistingUser.Get(context)) { principal.SetPassword(Password.Get(context)); principal.DisplayName = Firstname.Get(context) + " " + Lastname.Get(context); principal.PasswordNeverExpires = true; principal.Save(); IList <string> groups = GroupMemberships.Get(context) ?? new List <string>(); foreach (var group in groups) { GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(principalContext, group); if (!groupPrincipal.Members.Contains(principal)) { groupPrincipal.Members.Add(principal); } groupPrincipal.Save(); } GroupPrincipal allGroups = new GroupPrincipal(principalContext); allGroups.Name = "*"; PrincipalSearcher searcher = new PrincipalSearcher(allGroups); var allGroupList = searcher.FindAll(); foreach (GroupPrincipal group in allGroupList) { if (!groups.Contains(group.Name) && group.Members.Contains(principal)) { group.Members.Remove(principal); group.Save(); } } } }
//void Progression(object sender, EventArgs e) //{ // // Start the background worker // backgroundWorker1.RunWorkerAsync(); //} //// On worker thread so do our thing! //void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) //{ //} //// Back on the 'UI' thread so we can update the progress bar //void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) //{ // // The progress percentage is a property of e // progressBar1.Value = e.ProgressPercentage*2; //} //loading of data private void Form2_Load(object sender, EventArgs e) { //panel1.Visible = false; label10.Text = ""; label11.Visible = false; label12.Visible = false; label13.Visible = false; this.ActiveControl = textBox2; this.textBox1.Hide(); this.textBox4.Hide(); this.textBox5.Hide(); this.textBox6.Hide(); this.textBox7.Hide(); this.label15.Visible = false; Someoneelse.Checked = false; Someoneelse.Visible = false; Someoneelselabel.Visible = false; comboBox2.Visible = false; comboBox2.Enabled = false; //Assign ticket to someone if (isadmin) { Someoneelse.Visible = true; string groupName = "Domain Users"; string domainName = "192.168.10.5"; //get AD users PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName); try { foreach (Principal p in grp.GetMembers(false)) { if (p.DisplayName != null) { comboBox2.Items.Add(p.DisplayName); } } grp.Dispose(); ctx.Dispose(); } catch { MessageBox.Show("We are sorry, we are not able to run the program at this time. Please check Internet and VPN connections."); _owner.Close(); } comboBox2.Sorted = true; } username.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name; try { string domainName = "192.168.10.5"; //get AD users PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); UserPrincipal user = UserPrincipal.FindByIdentity(ctx, username.Text.ToString()); textBox2.Text = user.EmailAddress; textBox3.Text = user.VoiceTelephoneNumber; } catch { } DateTime mountain = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time")); label5.Text = mountain.ToString("MM-dd-yyyy h:mm tt"); label2.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name; label4.Text = mountain.ToString("MM-dd-yyyy h:mm tt"); System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer(); timer.Interval = (900 * 1000); timer.Tick += new EventHandler(timer_tick); timer.Start(); }
private SupportInfoElement LoadData(SupportInfotype sit, int number, int col) { if (sit == SupportInfotype.UserName) { var user = WindowsIdentity.GetCurrent().Name; StringBuilder sbu = new StringBuilder(1024); uint sbu_size = (uint)sbu.Capacity; var fn = string.Empty; //fn = System.DirectoryServices.AccountManagement.UserPrincipal.Current.GivenName; return(new SupportInfoElement() { Name = "Benutzername", Value = $"{user} {fn}", Number = number, Column = col }); } if (sit == SupportInfotype.IsAdmin) { var current_user_sid = WindowsIdentity.GetCurrent().User.Value; bool CurrentUserIsmemberOfAdminGroup = false; try { var administrator_group_sid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); using (PrincipalContext pc = new PrincipalContext(ContextType.Machine, Environment.MachineName)) { GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Sid, administrator_group_sid.Value); if (gp != null) { PrincipalCollection members = gp.Members; if (members != null) { foreach (Principal p in members) { if (p.Sid != null) { if (p.Sid.Value.Equals(current_user_sid)) { CurrentUserIsmemberOfAdminGroup = true; } } } } } } } catch { } if (CurrentUserIsmemberOfAdminGroup) { return new SupportInfoElement() { Name = "Administrative Rechte", Value = "JA", MakeBold = true, Number = number, Column = col } } ; else { return new SupportInfoElement() { Name = "Administrative Rechte", Value = "NEIN", Number = number, Column = col } }; } if (sit == SupportInfotype.ComputerName) { return(new SupportInfoElement() { Name = "Computername", Value = Environment.MachineName, Number = number, Column = col }); } if (sit == SupportInfotype.OperatingSystem) { var versionString = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("productName"); var releaseID = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("ReleaseID"); var x64 = Environment.Is64BitOperatingSystem ? "x64" : "x86"; return(new SupportInfoElement() { Name = "Betriebssystem-Edition | -Release | -Architektur", Value = $"{versionString} | {releaseID} | {x64}", Number = number, Column = col }); } if (sit == SupportInfotype.WindowsVersionInfo) { var os_major = (int)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("CurrentMajorVersionNumber"); var os_minor = (int)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("CurrentMinorVersionNumber"); var currentBuildNumber = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("currentBuildNumber"); var ubr = (int)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("UBR"); return(new SupportInfoElement() { Name = "Betriebssystem-Version", Value = $"{os_major}.{os_minor}.{currentBuildNumber}.{ubr}", Number = number, Column = col }); } if (sit == SupportInfotype.ComputerManufacturer) { string manufacturer = string.Empty; try { ManagementClass cs = new ManagementClass("win32_baseboard"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { manufacturer = MO.Properties["Manufacturer"].Value.ToString(); } } } catch { } return(new SupportInfoElement() { Name = "Hersteller", Value = manufacturer, Number = number, Column = col }); } if (sit == SupportInfotype.ComputerModel) { string model = string.Empty; try { ManagementClass cs = new ManagementClass("win32_baseboard"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { model = MO.Properties["Product"].Value.ToString(); } } } catch { } return(new SupportInfoElement() { Name = "Modell", Value = model, Number = number, Column = col }); } if (sit == SupportInfotype.SerialBaseboard) { string serial = string.Empty; try { ManagementClass cs = new ManagementClass("win32_baseboard"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { serial = MO.Properties["SerialNumber"].Value.ToString(); } } } catch { } return(new SupportInfoElement() { Name = "Serien-Nummer (Baseboard)", Value = $"{serial}", Number = number, Column = col }); } if (sit == SupportInfotype.SerialBios) { string serial = string.Empty; try { ManagementClass cs = new ManagementClass("win32_bios"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { serial = MO.Properties["SerialNumber"].Value.ToString(); } } } catch { } return(new SupportInfoElement() { Name = "Serien-Nummer (BIOS)", Value = $"{serial}", Number = number, Column = col }); } if (sit == SupportInfotype.CPU) { string cpu = string.Empty; try { ManagementClass cs = new ManagementClass("win32_processor"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { cpu = MO.Properties["Name"].Value.ToString(); } } } catch { } return(new SupportInfoElement() { Name = "CPU", Value = cpu, Number = number, Column = col }); } if (sit == SupportInfotype.Firmware) { // Firmware string bios_manufacturer = string.Empty; string bios_version = string.Empty; DateTime bios_datetime = DateTime.MinValue; try { ManagementClass cs = new ManagementClass("win32_bios"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { bios_manufacturer = MO.Properties["Manufacturer"].Value.ToString(); bios_version = MO.Properties["SMBIOSBIOSVersion"].Value.ToString(); bios_datetime = ManagementDateTimeConverter.ToDateTime(MO.Properties["ReleaseDate"].Value.ToString()); } } } catch { } return(new SupportInfoElement() { Name = "Firmware-Hersteller | -Version | -Datum", Value = $"{bios_manufacturer} | {bios_version} | {bios_datetime.ToString("dd.MM.yyyy")}", Number = number, Column = col }); } if (sit == SupportInfotype.Memory) { // RAM string ram = string.Empty; try { ManagementClass cs = new ManagementClass("Win32_OperatingSystem"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { ram = Convert.ToInt64(MO.Properties["TotalVisibleMemorySize"].Value).Kilobytes().Humanize("#.#"); } } } catch { } return(new SupportInfoElement() { Name = "RAM", Value = ram, Number = number, Column = col }); } if (sit == SupportInfotype.PhysicalDrives) { // physical disk drives List <DiskDrive> DiskDrives = new List <DiskDrive>(); string disk_info = string.Empty; try { string caption = string.Empty; string size_text = string.Empty; ManagementClass cs = new ManagementClass("win32_diskdrive"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { var type = MO.Properties["MediaType"]?.Value?.ToString(); if (type == null) { continue; } if (!type.Equals("fixed hard disk media", StringComparison.InvariantCultureIgnoreCase)) { continue; } DiskDrives.Add(new DiskDrive() { Caption = MO.Properties["Caption"].Value.ToString(), Size = Convert.ToInt64(MO.Properties["Size"].Value), SerialNumber = MO.Properties["SerialNumber"].Value.ToString(), Index = Convert.ToInt32(MO.Properties["Index"].Value) }); } // sortieren DiskDrives = DiskDrives.OrderBy(x => x.Index).ToList(); } } catch { } return(new SupportInfoElement() { Name = "Laufwerke (physikalisch)", Value = string.Join("\n", DiskDrives.Select(x => x.ToString())), Number = number, Column = col }); } if (sit == SupportInfotype.LogicalDrives) { // logical drives List <LogicalVolume> L = new List <LogicalVolume>(); string drive_string = string.Empty; try { foreach (var d in DriveInfo.GetDrives()) { if (!d.DriveType.Equals(DriveType.Fixed)) { continue; } L.Add(new LogicalVolume() { Name = d.Name, TotalSpace = d.TotalSize, FreeSpace = d.AvailableFreeSpace }); } } catch { } return(new SupportInfoElement() { Name = "Laufwerke (logisch)", Value = string.Join("\n", L.Select(x => x.ToString())), Number = number, Column = col }); } if (sit == SupportInfotype.Network) { // netzwerk info List <NetworkInfo> NetworkAdapter = new List <NetworkInfo>(); string net_info = string.Empty; try { foreach (var n in NetworkInterface.GetAllNetworkInterfaces()) { if (n.NetworkInterfaceType.Equals(NetworkInterfaceType.Loopback)) { continue; } //if (n.OperationalStatus.Equals(OperationalStatus.Down)) continue; IPInterfaceProperties ipip = n.GetIPProperties(); if ((ipip.GatewayAddresses == null) || (ipip.GatewayAddresses.Count.Equals(0))) { NetworkAdapter.Add(new NetworkInfo() { AdapterName = n.Description, Speed = n.Speed }); continue; } ; foreach (var u in ipip.UnicastAddresses) { if (!u.Address.AddressFamily.Equals(System.Net.Sockets.AddressFamily.InterNetwork)) { continue; } NetworkAdapter.Add(new NetworkInfo() { AdapterName = n.Description, Speed = n.Speed, IP = u.Address.ToString() }); } } } catch { } return(new SupportInfoElement() { Name = "Netzwerk", Value = string.Join("\n", NetworkAdapter.Select(x => x.ToString())), Number = number, Column = col }); } if (sit == SupportInfotype.Ping) { // Ping string ping_info = string.Empty; Ping ping = new Ping(); try { PingReply pr = ping.Send(new System.Net.IPAddress(new byte[] { 8, 8, 8, 8 }), 1000); var ping_result = pr.Status.ToString(); var ping_ms = pr.RoundtripTime.ToString(); ping_info = $"Ergebnis: {ping_result}, {ping_ms} ms"; } catch { } return(new SupportInfoElement() { Name = "Ping (8.8.8.8)", Value = ping_info, Number = number, Column = col }); } if (sit == SupportInfotype.Webcam) { // Webcam string WebCamInfo = string.Empty; FilterInfoCollection videoInputCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice); if ((videoInputCollection != null) && (videoInputCollection.Count > 0)) { foreach (FilterInfo videoDevice in videoInputCollection) { WebCamInfo += $"{videoDevice.Name}\n"; } } return(new SupportInfoElement() { Name = "Webcam", Value = WebCamInfo, Number = number, Column = col }); } if (sit == SupportInfotype.AudioOutDevices) { // Audio string AudioOutInfo = string.Empty; try { for (int i = -1; i < WaveOut.DeviceCount; i++) { var c = WaveOut.GetCapabilities(i); AudioOutInfo += c.ProductName + "\n"; } } catch { } return(new SupportInfoElement() { Name = "Audio (Out)", Value = AudioOutInfo, Number = number, Column = col }); } if (sit == SupportInfotype.AudioInDevices) { string AudioInInfo = string.Empty; try { for (int i = -1; i < WaveIn.DeviceCount; i++) { var c = WaveIn.GetCapabilities(i); AudioInInfo += c.ProductName + "\n"; } } catch { } return(new SupportInfoElement() { Name = "Audio (In)", Value = AudioInInfo, Number = number, Column = col }); } if (sit == SupportInfotype.GraphicsCard) { // Grafik List <GraphicsAdapter> G = new List <GraphicsAdapter>(); try { ManagementClass cs = new ManagementClass("win32_videocontroller"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { G.Add(new GraphicsAdapter() { Name = MO.Properties["Name"].Value.ToString(), DriverVersion = MO.Properties["DriverVersion"].Value.ToString() }); } } } catch { } return(new SupportInfoElement() { Name = "Grafikkarte", Value = string.Join("\n", G.Select(x => x.ToString())), Number = number, Column = col }); } if (sit == SupportInfotype.Display) { List <DisplayInfo> D = new List <DisplayInfo>(); try { ManagementClass cs = new ManagementClass("win32_desktopmonitor"); ManagementObjectCollection moc = cs.GetInstances(); if (moc.Count != 0) { foreach (ManagementObject MO in cs.GetInstances()) { D.Add(new DisplayInfo() { Manufacturer = MO.Properties["MonitorManufacturer"].Value != null ? MO.Properties["MonitorManufacturer"].Value.ToString() : string.Empty, Name = MO.Properties["MonitorType"].Value != null ? MO.Properties["MonitorType"].Value.ToString() : string.Empty }); } } } catch { } return(new SupportInfoElement() { Name = "Monitor", Value = string.Join("\n", D.Select(x => x.ToString())), Number = number, Column = col }); } if (sit == SupportInfotype.Bitlocker) { // Bitlocker var bitLocker = string.Empty; IShellProperty prop = ShellObject.FromParsingName("C:").Properties.GetProperty("System.Volume.BitLockerProtection"); int? bitLockerProtectionStatus = (prop as ShellProperty <int?>).Value; if (bitLockerProtectionStatus.HasValue && (bitLockerProtectionStatus == 1 || bitLockerProtectionStatus == 3 || bitLockerProtectionStatus == 5)) { bitLocker = "Ein"; } else { bitLocker = "Aus"; } return(new SupportInfoElement() { Name = "Bitlocker (C:)", Value = bitLocker, Number = number, Column = col }); } return(null); }
private void buttonAdd_Click(object sender, EventArgs e) { int failed = 0; string corp_phone = null; string phone = null; string bday = null; textEnLastName.BackColor = System.Drawing.Color.White; textEnLastName.ForeColor = System.Drawing.Color.Black; textEnFirstName.BackColor = System.Drawing.Color.White; textEnFirstName.ForeColor = System.Drawing.Color.Black; textLogin.BackColor = System.Drawing.Color.White; textLogin.ForeColor = System.Drawing.Color.Black; textPassword.BackColor = System.Drawing.Color.White; textPassword.ForeColor = System.Drawing.Color.Black; textEnPosition.BackColor = System.Drawing.Color.White; textEnPosition.ForeColor = System.Drawing.Color.Black; textRuFirstName.BackColor = System.Drawing.Color.White; textRuFirstName.ForeColor = System.Drawing.Color.Black; textRuLastName.BackColor = System.Drawing.Color.White; textRuLastName.ForeColor = System.Drawing.Color.Black; textRuPosition.BackColor = System.Drawing.Color.White; textRuPosition.ForeColor = System.Drawing.Color.Black; comboDepartment.BackColor = System.Drawing.Color.White; comboDepartment.ForeColor = System.Drawing.Color.Black; if (textEnLastName.Text == null || textEnLastName.Text.Length == 0) { textEnLastName.BackColor = System.Drawing.Color.Red; textEnLastName.ForeColor = System.Drawing.Color.White; failed++; } if (textEnFirstName.Text == null || textEnFirstName.Text.Length == 0) { textEnFirstName.BackColor = System.Drawing.Color.Red; textEnFirstName.ForeColor = System.Drawing.Color.White; failed++; } if (textLogin.Text == null || textLogin.Text.Length == 0) { textLogin.BackColor = System.Drawing.Color.Red; textLogin.ForeColor = System.Drawing.Color.White; failed++; } if (textPassword.Text == null || textPassword.Text.Length == 0) { textPassword.BackColor = System.Drawing.Color.Red; textPassword.ForeColor = System.Drawing.Color.White; failed++; } if (textCorpPhone.Text != null && textCorpPhone.Text.Length > 0 && System.Text.RegularExpressions.Regex.Match(textCorpPhone.Text, @"^\d{3}$").Success) { corp_phone = textCorpPhone.Text; } if (textCellPhone.Text != null && textCellPhone.Text.Length > 0 && System.Text.RegularExpressions.Regex.Match(textCellPhone.Text, @"^\+7 \d{3} \d{3} \d{4}$").Success) { phone = textCellPhone.Text; } if (textBirthday.Text != null && textBirthday.Text.Length > 0 && System.Text.RegularExpressions.Regex.Match(textBirthday.Text, @"^(?:(?:0[1-9])|(?:[12][0-9])|(?:3[01]))\.(?:(?:0[1-9])|(?:1[0-2]))$").Success) { bday = textBirthday.Text; } if (textEnPosition.Text == null || textEnPosition.Text.Length == 0) { textEnPosition.BackColor = System.Drawing.Color.Red; textEnPosition.ForeColor = System.Drawing.Color.White; failed++; } if (textRuFirstName.Text == null || textRuFirstName.Text.Length == 0) { textRuFirstName.BackColor = System.Drawing.Color.Red; textRuFirstName.ForeColor = System.Drawing.Color.White; failed++; } if (textRuLastName.Text == null || textRuLastName.Text.Length == 0) { textRuLastName.BackColor = System.Drawing.Color.Red; textRuLastName.ForeColor = System.Drawing.Color.White; failed++; } if (textRuPosition.Text == null || textRuPosition.Text.Length == 0) { textRuPosition.BackColor = System.Drawing.Color.Red; textRuPosition.ForeColor = System.Drawing.Color.White; failed++; } if (comboDepartment.Text == null || comboDepartment.Text.Length == 0) { comboDepartment.BackColor = System.Drawing.Color.Red; comboDepartment.ForeColor = System.Drawing.Color.White; failed++; } if (failed > 0) { return; } string textOrganisation; string[] groups; if (comboDepartment.Text == "Horizon") { textOrganisation = "Horizon"; groups = new string[] { "$GetSignature", "$Horizon" }; } else if (comboDepartment.Text == "Air") { textOrganisation = "Air"; groups = new string[] { }; } else { textOrganisation = "Mediainstinct"; if (comboDepartment.Text == "OOH Buying") { groups = new string[] { "$GetSignature", "$OOH Buying" }; } else if (comboDepartment.Text == "Accounting") { groups = new string[] { "$GetSignature", "$Accounting" }; } else if (comboDepartment.Text == "Digital") { groups = new string[] { "$GetSignature", "$Digital" }; } else if (comboDepartment.Text == "Finance") { groups = new string[] { "$GetSignature", "$Finance" }; } else if (comboDepartment.Text == "HR") { groups = new string[] { "$GetSignature", "$HR" }; } else if (comboDepartment.Text == "Lawyer") { groups = new string[] { "$GetSignature", "$Lawyer" }; } else if (comboDepartment.Text == "Match") { groups = new string[] { "$GetSignature", "$Match" }; } else if (comboDepartment.Text == "Media planning") { groups = new string[] { "$GetSignature", "$Media planing" }; } else if (comboDepartment.Text == "New Business") { groups = new string[] { "$GetSignature", "$NewBusiness" }; } else if (comboDepartment.Text == "OOH Buying") { groups = new string[] { "$GetSignature", "$OOHBuying" }; } else if (comboDepartment.Text == "Print Buying") { groups = new string[] { "$GetSignature", "$Print Buying" }; } else if (comboDepartment.Text == "Strategy & Research") { groups = new string[] { "$GetSignature", "$Strategy" }; } else if (comboDepartment.Text == "TV Buying") { groups = new string[] { "$GetSignature", "$TV Buying" }; } else if (comboDepartment.Text == "Print Production") { groups = new string[] { "$GetSignature", "$OOH Production" }; } else { groups = new string[] { "$GetSignature" }; } } // Creating the PrincipalContext PrincipalContext principalContext = null; try { string context; if (textOrganisation == "Air") { context = "OU=Mediainstinct,OU=Air,DC=srv1,DC=sbcmedia,DC=ru"; } else if (textOrganisation == "Horizon") { context = "OU=Horizon,OU=Mediainstinct,DC=srv1,DC=sbcmedia,DC=ru"; } else { context = "OU=" + textOrganisation + ",DC=srv1,DC=sbcmedia,DC=ru"; } principalContext = new PrincipalContext(ContextType.Domain, "sbcmedia", context); } catch (Exception exc) { MessageBox.Show("Failed to create PrincipalContext. Exception: " + exc); Application.Exit(); } // Check if user object already exists in the store UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, textLogin.Text); if (usr != null) { MessageBox.Show(textLogin.Text + " already exists. Please use a different User Logon Name."); return; } // Create the new UserPrincipal object UserPrincipal userPrincipal = new UserPrincipal(principalContext); userPrincipal.UserPrincipalName = textLogin.Text + "@srv1.sbcmedia.ru"; userPrincipal.Surname = textEnLastName.Text; userPrincipal.GivenName = textEnFirstName.Text; //userPrincipal.DisplayName = textEnLastName.Text + ' ' + textEnFirstName.Text; //userPrincipal.Name = textEnLastName.Text + ' ' + textEnFirstName.Text; userPrincipal.DisplayName = textEnFirstName.Text + ' ' + textEnLastName.Text; userPrincipal.Name = textEnFirstName.Text + ' ' + textEnLastName.Text; userPrincipal.SamAccountName = textLogin.Text; userPrincipal.SetPassword(textPassword.Text); userPrincipal.EmailAddress = textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru"; userPrincipal.Enabled = true; userPrincipal.PasswordNeverExpires = true; try { userPrincipal.Save(); } catch (Exception exc) { MessageBox.Show("Exception creating user object. " + exc); return; } File.AppendAllText("users.txt", DateTime.Now.ToString() + " : " + textEnLastName.Text + ' ' + textEnFirstName.Text + " : " + textLogin.Text + " : " + textPassword.Text + Environment.NewLine); if (userPrincipal.GetUnderlyingObjectType() == typeof(DirectoryEntry)) { DirectoryEntry entry = (DirectoryEntry)userPrincipal.GetUnderlyingObject(); if (phone != null) { entry.Properties["mobile"].Value = phone; } if (corp_phone != null) { entry.Properties["telephoneNumber"].Value = corp_phone; } entry.Properties["title"].Value = textEnPosition.Text; entry.Properties["description"].Value = textRuFirstName.Text + ' ' + textRuLastName.Text; if (bday != null) { entry.Properties["info"].Value = textRuPosition.Text + ", " + bday; } else { entry.Properties["info"].Value = textRuPosition.Text; } entry.Properties["department"].Value = comboDepartment.Text; entry.Properties["company"].Value = textOrganisation; try { entry.CommitChanges(); } catch (Exception exc) { MessageBox.Show("Exception modifying info of the user. " + exc); return; } } try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "sbcmedia", "DC=srv1,DC=sbcmedia,DC=ru")) { foreach (string groupName in groups) { GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName); group.Members.Add(pc, IdentityType.UserPrincipalName, userPrincipal.UserPrincipalName); group.Save(); } } } catch (System.DirectoryServices.DirectoryServicesCOMException exc) { MessageBox.Show("Exception modifying group. " + exc); return; } //PSCredential credential = null; var password = new SecureString(); Array.ForEach("password".ToCharArray(), password.AppendChar); PSCredential credential = new PSCredential("login", password); WSManConnectionInfo ci = new WSManConnectionInfo(new Uri("https://outlook.office365.com/powershell-liveid/"), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", credential); ci.AuthenticationMechanism = AuthenticationMechanism.Basic; try { using (Runspace runspace = RunspaceFactory.CreateRunspace(ci)) { using (PowerShell session = PowerShell.Create()) { runspace.Open(); session.Runspace = runspace; var pwd = new SecureString(); Array.ForEach(textPassword.Text.ToCharArray(), pwd.AppendChar); var result = session.AddCommand("New-Mailbox") .AddParameter("Alias", textLogin.Text) .AddParameter("Name", textEnFirstName.Text + ' ' + textEnLastName.Text) .AddParameter("FirstName", textEnFirstName.Text) .AddParameter("LastName", textEnLastName.Text) .AddParameter("DisplayName", textEnFirstName.Text + ' ' + textEnLastName.Text) .AddParameter("MicrosoftOnlineServicesID", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .AddParameter("Password", pwd) .AddParameter("ResetPasswordOnNextLogon", false) .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); if (textOrganisation == "Horizon") { result = session.AddCommand("New-Mailbox") .AddParameter("Shared") .AddParameter("Name", textEnFirstName.Text + ' ' + textEnLastName.Text + "Horizon") .AddParameter("Alias", textLogin.Text + "_hz") .AddParameter("PrimarySmtpAddress", textEnFirstName.Text + '.' + textEnLastName.Text + "@horizonmedia.ru") .AddParameter("DisplayName", textEnFirstName.Text + ' ' + textEnLastName.Text) .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create shared mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); result = session.AddCommand("Set-Mailbox") .AddParameter("Identity", textLogin.Text + "_hz") .AddParameter("GrantSendOnBehalfTo", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create shared mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); result = session.AddCommand("Add-MailboxPermission") .AddParameter("Identity", textLogin.Text + "_hz") .AddParameter("User", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .AddParameter("AccessRights", "FullAccess") .AddParameter("InheritanceType", "All") .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create shared mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); result = session.AddCommand("Add-RecipientPermission") .AddParameter("Identity", textLogin.Text + "_hz") .AddParameter("Trustee", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .AddParameter("AccessRights", "SendAs") .AddParameter("confirm", false) .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create shared mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); } session.AddCommand("Exit-PSSession").Invoke(); runspace.Close(); } } } catch (Exception exc) { MessageBox.Show("Create mailbox error. " + exc); return; } InitialSessionState initialSession = InitialSessionState.CreateDefault(); initialSession.ImportPSModule(new[] { "MSOnline" }); try { using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSession)) { using (PowerShell session = PowerShell.Create()) { runspace.Open(); session.Runspace = runspace; var pwd = new SecureString(); Array.ForEach(textPassword.Text.ToCharArray(), pwd.AppendChar); var result = session.AddCommand("Connect-MsolService") .AddParameter("Credential", credential) .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); result = session.AddCommand("Set-MsolUser") .AddParameter("UserPrincipalName", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .AddParameter("UsageLocation", "RU") .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); result = session.AddCommand("Set-MsolUserLicense") .AddParameter("UserPrincipalName", textEnFirstName.Text + '.' + textEnLastName.Text + "@mediainstinctgroup.ru") .AddParameter("AddLicenses", "reseller-account:EXCHANGESTANDARD") .Invoke(); if (session.HadErrors) { string err_msg = null; foreach (var error in session.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create mailbox failed!\n\n" + err_msg); return; } session.Commands.Clear(); runspace.Close(); } } } catch (Exception exc) { MessageBox.Show("Create mailbox error. " + exc); return; } if ((textOrganisation != "Air") && MessageBox.Show("Insert new initialized eToken", "Certificate", MessageBoxButtons.OKCancel) == DialogResult.OK) { try { PowerShell ps = PowerShell.Create(); ps.Commands.AddScript( "$pkcs10 = New-Object -ComObject X509Enrollment.CX509CertificateRequestPkcs10;" + "$pkcs10.InitializeFromTemplateName(0x1,\"Win2003Пользовательсосмарт-картой\");" + "$pkcs10.Encode();" + "$pkcs7 = New-Object -ComObject X509enrollment.CX509CertificateRequestPkcs7;" + "$pkcs7.InitializeFromInnerRequest($pkcs10);" + "$pkcs7.RequesterName = \"SBCMEDIA\\" + textLogin.Text + "\";" + "$signer = New-Object -ComObject X509Enrollment.CSignerCertificate;" + "$cert = Get-ChildItem Cert:\\CurrentUser\\My | Where-Object {$_.Extensions | Where-Object {$_.Oid.Value -eq \"2.5.29.37\" -and $_.EnhancedKeyUsages[\"1.3.6.1.4.1.311.20.2.1\"]}};" + "$base64 = [Convert]::ToBase64String($cert.RawData);" + "$signer = New-Object -ComObject X509Enrollment.CSignerCertificate;" + "$signer.Initialize(0, 0, 1,$base64);" + "$pkcs7.SignerCertificate = $signer;" + "$Request = New-Object -ComObject X509Enrollment.CX509Enrollment;" + "$Request.InitializeFromRequest($pkcs7);" + "$Request.Enroll();" ); var result = ps.Invoke(); if (ps.HadErrors) { string err_msg = null; foreach (var error in ps.Streams.Error) { err_msg += error + "\n"; } MessageBox.Show("Create certificate errors:\n\n" + err_msg); } } catch (Exception exc) { MessageBox.Show("Create certificate failed. " + exc); } } MessageBox.Show("User successfully added!"); }
internal static GroupPrincipal GetGroupPrincipal(string name) { PrincipalContext ctx = new PrincipalContext(ContextType.Domain); return(GroupPrincipal.FindByIdentity(ctx, name)); }
private static GroupPrincipal GetGroup(PrincipalContext context, string groupSid) => GroupPrincipal.FindByIdentity(context, IdentityType.Sid, groupSid);
public static object BuscarCoords() { var context = new PrincipalContext(ContextType.Domain, ConfigurationManager.AppSettings["Dominio"], "9077401526", "12qw!@QW"); //usuario com direitos q nao entendi... GroupPrincipal gro = GroupPrincipal.FindByIdentity(context, "G_FACULDADE_COORDENADOR_R"); List <Usuario> usuarios = new List <Usuario>(); List <Funcionario> funcionarios = new List <Funcionario>(); foreach (UserPrincipal userPrincipal in gro.Members) { Usuario user = usuarioRepository.GetUsuarioById(userPrincipal.SamAccountName); if (user != null) { if (user.Permissao == EnumPermissaoUsuario.professor || user.Permissao == EnumPermissaoUsuario.secretaria) { user.Permissao = EnumPermissaoUsuario.coordenador; user.Funcionario.FirstOrDefault().Permissao = EnumPermissaoUsuario.coordenador; } else if (user.Permissao == EnumPermissaoUsuario.aluno) { user.Permissao = EnumPermissaoUsuario.coordenador; Funcionario f = new Funcionario(); f.Permissao = EnumPermissaoUsuario.coordenador; f.IdUsuario = user.IdUsuario; funcionarios.Add(f); } else if (user.Permissao == EnumPermissaoUsuario.coordenador) { continue; } usuarios.Add(user); } else { if (usuarioRepository.GetUsuarioById(userPrincipal.SamAccountName) == null) { Usuario ususario = new Usuario(); Funcionario f = new Funcionario(); ususario.IdUsuario = userPrincipal.SamAccountName; ususario.Nome = userPrincipal.Name; ususario.Permissao = EnumPermissaoUsuario.coordenador; f.IdUsuario = ususario.IdUsuario; f.Permissao = EnumPermissaoUsuario.coordenador; funcionarios.Add(f); usuarios.Add(ususario); } } } switch (usuarioRepository.PersisteUsuario(usuarios.ToArray())) { case "Cadastrado": usuarioRepository.PersisteFuncionario(funcionarios.ToArray()); return(true); default: return(false); } }
private static GroupPrincipal GetGroup(string id) { var ctx = new PrincipalContext(ContextType.Domain); return(GroupPrincipal.FindByIdentity(ctx, id)); }
public List <Entidades.Usuario> Obtener(Sesion poSesion, string psFiltro, string psValor) { List <Entidades.Usuario> loUsuarios = new List <Entidades.Usuario>(); try { using (DirectoryEntry loDirectorio = new DirectoryEntry("LDAP://" + poSesion.Conexion.Servidor, poSesion.Conexion.Credenciales.Usuario, poSesion.Conexion.Credenciales.Cifrado.Descifrar(poSesion.Conexion.Credenciales.Contrasenia))) { using (DirectorySearcher loBuscador = new DirectorySearcher(loDirectorio)) { #region Definir propiedades a recuperar loBuscador.PropertiesToLoad.Add("department"); loBuscador.PropertiesToLoad.Add("company"); loBuscador.PropertiesToLoad.Add("givenName"); loBuscador.PropertiesToLoad.Add("initials"); loBuscador.PropertiesToLoad.Add("ipPhone"); loBuscador.PropertiesToLoad.Add("l"); loBuscador.PropertiesToLoad.Add("mail"); loBuscador.PropertiesToLoad.Add("mobile"); loBuscador.PropertiesToLoad.Add("name"); loBuscador.PropertiesToLoad.Add("pager"); loBuscador.PropertiesToLoad.Add("postOfficeBox"); loBuscador.PropertiesToLoad.Add("postalCode"); loBuscador.PropertiesToLoad.Add("samAccountName"); loBuscador.PropertiesToLoad.Add("sn"); loBuscador.PropertiesToLoad.Add("st"); loBuscador.PropertiesToLoad.Add("streetAddress"); loBuscador.PropertiesToLoad.Add("telephoneNumber"); loBuscador.PropertiesToLoad.Add("title"); loBuscador.PropertiesToLoad.Add("userAccountControl"); loBuscador.PropertiesToLoad.Add("userPrincipalName"); if (psValor.Length > 0) { loBuscador.Filter = "(&(objectCategory=person)(objectClass=user)(" + psFiltro + "=*" + psValor + "*))"; } else { loBuscador.Filter = "(&(objectCategory=person)(objectClass=user)(!(name=*ADMINISTRA*)))"; } loBuscador.Sort = new SortOption("name", SortDirection.Ascending); #endregion #region Obtener el contexto principal PrincipalContext loContexto = new PrincipalContext(ContextType.Domain, poSesion.Conexion.Nombre, poSesion.Conexion.Credenciales.Usuario, poSesion.Conexion.Credenciales.Cifrado.Descifrar(poSesion.Conexion.Credenciales.Contrasenia)); GroupPrincipal loGrupo = GroupPrincipal.FindByIdentity(loContexto, ConfigurationManager.AppSettings["GrupoInactivos"]); #endregion SearchResultCollection loResultados = loBuscador.FindAll(); int lnConsecutivo = 1; foreach (SearchResult loResultado in loResultados) { string lsUsuarioDominio = (loResultado.Properties.Contains("samAccountName")) ? loResultado.Properties["samAccountName"][0].ToString().ToLower() : string.Empty; if (loGrupo != null) { UserPrincipal loUsuarioPrincipal = UserPrincipal.FindByIdentity(loContexto, lsUsuarioDominio); if (loUsuarioPrincipal != null && loGrupo.Members.Contains(loUsuarioPrincipal)) { continue; } } loUsuarios.Add(new Entidades.Usuario() { #region Inicializar propiedades Apellido = (loResultado.Properties.Contains("sn")) ? loResultado.Properties["sn"][0].ToString().ToUpper() : null, Colonia = (loResultado.Properties.Contains("postOfficeBox")) ? loResultado.Properties["postOfficeBox"][0].ToString().ToUpper() : null, Compania = (loResultado.Properties.Contains("company")) ? loResultado.Properties["company"][0].ToString().ToUpper() : null, Consecutivo = lnConsecutivo++, Correo = (loResultado.Properties.Contains("mail")) ? loResultado.Properties["mail"][0].ToString().ToLower() : null, CP = (loResultado.Properties.Contains("postalCode")) ? loResultado.Properties["postalCode"][0].ToString().ToUpper() : null, Departamento = (loResultado.Properties.Contains("department")) ? loResultado.Properties["department"][0].ToString().ToUpper() : null, Direccion = (loResultado.Properties.Contains("streetAddress")) ? loResultado.Properties["streetAddress"][0].ToString().ToUpper() : null, Estado = (loResultado.Properties.Contains("st")) ? loResultado.Properties["st"][0].ToString().ToUpper() : null, Estatus = true, Extension = (loResultado.Properties.Contains("pager")) ? loResultado.Properties["pager"][0].ToString().ToUpper() : null, Movil = (loResultado.Properties.Contains("mobile")) ? loResultado.Properties["mobile"][0].ToString().ToUpper() : null, Nombre = (loResultado.Properties.Contains("givenName")) ? loResultado.Properties["givenName"][0].ToString().ToUpper() : null, NombreCompleto = (loResultado.Properties.Contains("name")) ? loResultado.Properties["name"][0].ToString().ToUpper() : null, Puesto = (loResultado.Properties.Contains("title")) ? loResultado.Properties["title"][0].ToString().ToUpper() : null, Radio = (loResultado.Properties.Contains("ipPhone")) ? loResultado.Properties["ipPhone"][0].ToString().ToUpper() : null, Sucursal = (loResultado.Properties.Contains("l")) ? loResultado.Properties["l"][0].ToString().ToUpper() : null, Telefono = (loResultado.Properties.Contains("telephoneNumber")) ? loResultado.Properties["telephoneNumber"][0].ToString().ToUpper() : null, Titulo = (loResultado.Properties.Contains("initials")) ? loResultado.Properties["initials"][0].ToString().ToUpper() : null, UsuarioDominio = lsUsuarioDominio, UsuarioPrincipal = (loResultado.Properties.Contains("userPrincipalName")) ? loResultado.Properties["userPrincipalName"][0].ToString().ToLower() : null #endregion }); } } } return(loUsuarios); } catch (Exception ex) { throw new Excepcion(ex.Message, ex); } }
/// <summary> /// Configures User Groups in Activity Directory for each user count.. /// </summary> /// <param name="credential">The credential.</param> /// <param name="addToGroups">Whether to add the user to the AD groups specified in the manifest.</param> protected void ConfigureUserGroups(OfficeWorkerCredential credential, bool addToGroups = true) { if (credential == null) { throw new ArgumentNullException("credential"); } string userName = credential.UserName; // Check to be sure there are user groups to configure string securityGroupXml = SystemManifest.Resources.GetByUsername(userName).SecurityGroups; if (string.IsNullOrEmpty(securityGroupXml)) { // There are no active directory groups to process, so return return; } // Get the groups to be processed and the appropriate logging label Collection <ActiveDirectoryGroup> groups = null; string label = string.Empty; if (addToGroups) { groups = LegacySerializer.DeserializeDataContract <Collection <ActiveDirectoryGroup> >(securityGroupXml); label = "Adding"; } else { groups = new Collection <ActiveDirectoryGroup>(); label = "Removing"; } PrincipalContext context = new PrincipalContext(ContextType.Domain); // Compare what the list of groups are to the master list from Active Directory // for every entry found in active directory add it to the list to be processed. // If there is a group listed to be assigned but it doesn't exist anymore in active // directory, log that error. var groupsToAssign = new List <GroupPrincipal>(); if (addToGroups) { foreach (var group in groups) { GroupPrincipal groupPrincipal = GroupPrincipal.FindByIdentity(context, group.Name); if (groupPrincipal != null) { TraceFactory.Logger.Debug("Group {0} will be assigned to {1}".FormatWith(groupPrincipal.Name, credential.UserName)); groupsToAssign.Add(groupPrincipal); } else { TraceFactory.Logger.Error("The group {0} does not exist in the Active Directory server".FormatWith(group.Name)); } } } // Find any groups the user is a member of that must be removed. Ignore Domain Users, since that group cannot be unjoined. UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, userName); var existingUserGroups = userPrincipal.GetAuthorizationGroups().OfType <GroupPrincipal>(); var groupsToRemove = existingUserGroups.Except(groupsToAssign).Where(n => n.Name != "Domain Users"); Action action = () => { ActiveDirectoryController.RemoveUserFromGroups(userPrincipal, groupsToRemove); ActiveDirectoryController.AddUserToGroups(userPrincipal, groupsToAssign); }; try { Retry.WhileThrowing(action, 10, TimeSpan.FromSeconds(5), new List <Type> { typeof(DirectoryServicesCOMException) }); } catch (UnauthorizedAccessException) { TraceFactory.Logger.Debug("User {0} is not authorized to assign group membership. {1} will not be assigned." .FormatWith(Environment.UserName, credential.UserName)); } }
/// <summary> /// The get group. /// </summary> public static GroupPrincipal GetGroup(string groupName) { PrincipalContext principalContext = GetPrincipalContext; return(GroupPrincipal.FindByIdentity(principalContext, IdentityType.Name, groupName)); }
private void queryGroupMembers(bool nested) { if (!cachedGroupMembers) { updateProgressGroupMembers(true); lvMembers.Items.Clear(); Thread thloadUserGroups = new Thread(() => { //this.Invoke((MethodInvoker)delegate { lvMembers.BeginUpdate(); }); GroupPrincipal group = GroupPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, frmMain.domainAccountData[0], frmMain.domainAccountData[1], frmMain.domainAccountData[2]), this.groupToQuery); if (group != null) { List <Principal> groups = null; List <Principal> groupsNoNest = null; if (nested) { groups = group.GetMembers(true).OrderBy(o => o.Name).ToList(); groupsNoNest = groups; } else { groups = group.GetMembers().OrderBy(o => o.Name).ToList(); } int i = groups.Count(); Invoke((MethodInvoker) delegate { lblMembersCount.Text = i.ToString() + ", members."; }); List <ListViewItem> items = new List <ListViewItem>(); foreach (Principal userResult in groups) { ListViewItem objectItem = new ListViewItem(); string formatedFolder = ""; if ((userResult.DistinguishedName != null) && (userResult.DistinguishedName != string.Empty)) { string userDN = userResult.DistinguishedName.Substring(userResult.DistinguishedName.IndexOf(',') + 1, userResult.DistinguishedName.Length - (userResult.DistinguishedName.IndexOf(',') + 1)); formatedFolder = userDN.Replace("CN=", string.Empty).Replace("DC=", string.Empty).Replace("OU=", string.Empty).Replace(",", "/"); } if ((nested) && (groupsNoNest != null) && (groupsNoNest.Count() > 0)) { if (!groupsNoNest.Select(g => g.SamAccountName).Contains(userResult.SamAccountName)) { this.Invoke((MethodInvoker) delegate { objectItem.BackColor = Color.SandyBrown; }); } } else { if (lvMembers.Items.Count % 2 != 0) { objectItem.BackColor = Color.White; } else { objectItem.BackColor = Color.WhiteSmoke; } } if (userResult.StructuralObjectClass != null) { switch (userResult.StructuralObjectClass.ToString()) { case "user": objectItem.ImageIndex = 1; break; case "group": objectItem.ImageIndex = 10; break; case "computer": objectItem.ImageIndex = 4; break; default: break; } } else { objectItem.ImageIndex = 12; } objectItem.Tag = userResult.SamAccountName + "," + formatedFolder; objectItem.Tag = userResult; objectItem.Text = userResult.Name; objectItem.SubItems.Add(userResult.SamAccountName); objectItem.SubItems.Add(formatedFolder); items.Add(objectItem); } try { this.Invoke((MethodInvoker) delegate { ListViewItem[] arr = items.ToArray(); lvMembers.BeginUpdate(); //foreach (ListViewItem item in items) lvMembers.Items.AddRange(arr); lvMembers.EndUpdate(); }); //Dispose group.Dispose(); groups = null; groupsNoNest = null; items = null; } catch { Thread.CurrentThread.Abort(); } } cachedGroupMembers = true; try { this.Invoke((MethodInvoker) delegate { updateProgressGroupMembers(false); // lvMembers.EndUpdate(); }); } catch { Thread.CurrentThread.Abort(); } // this.Invoke((MethodInvoker)delegate { lvMembers.EndUpdate(); }); }); thloadUserGroups.IsBackground = true; thloadUserGroups.Start(); } }
/// <summary> /// Returns a PrincipalCollection that is the members of the specified groups. /// </summary> /// <param name="group">The unique identifier of the group.</param> /// <returns>A PrincipalCollection.</returns> public static PrincipalCollection GetMembers(string group) { GroupPrincipal g = GroupPrincipal.FindByIdentity(GetPrincipalContext(), group); return(g.Members); }
private List <ADUser> GetMembersLDAP(string groupName) { List <ADUser> users = new List <ADUser>(); try { using (System.Web.Hosting.HostingEnvironment.Impersonate()) { string dlManagerUserName = AppCredentials.Instance.UserName; string dlManagerPassword = AppCredentials.Instance.Password; int dlThreshold = Convert.ToInt32(AppCredentials.Instance.Threshold); using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName, dlManagerUserName, dlManagerPassword)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(oPrincipalContext, groupName); DirectoryEntry entry = new DirectoryEntry(); PrincipalSearcher srch = new PrincipalSearcher(); DirectorySearcher search = new DirectorySearcher(entry); string query = "(&(objectCategory=person)(objectClass=user)(memberOf=" + group.DistinguishedName + "))"; search.Filter = query; search.PropertiesToLoad.Add("memberOf"); search.PropertiesToLoad.Add("displayname"); search.PropertiesToLoad.Add("mail"); search.PropertiesToLoad.Add("samaccountname"); search.PageSize = 20000; ADUser obj = null; System.DirectoryServices.SearchResultCollection mySearchResultColl = search.FindAll(); //Console.WriteLine("Members of the {0} Group in the {1} Domain", groupName, domainName); int i = 0; foreach (SearchResult result in mySearchResultColl) { foreach (string prop in result.Properties["memberOf"]) { if (prop.Contains(groupName)) { try { obj = new ADUser(); obj.Name = result.Properties["displayname"][0].ToString();// .Properties["displayname"][0] + ""; obj.Email = result.Properties["mail"][0].ToString(); obj.StaffID = result.Properties["samaccountname"][0].ToString(); users.Add(obj); if (i == dlThreshold + 1) { break; } i++; } catch { //LoggingHelper.Instance.LogAudit("Error User-" + groupName, result.Properties["samaccountname"][0].ToString()); } //Console.WriteLine(" " + result.Properties["name"][0].ToString()); } } if (i == dlThreshold + 1) { break; } } } } } catch (Exception ex) { LoggingHelper.Instance.LogError(LogOptions.GetMembers, ex); } return(users); }
public void CreateMany(string userNamePrefix, int usernameSuffix, int teamId, string password, int port, string userGroupName, string userNames, bool disablepwchange, bool pwneverexpires) { GroupPrincipal group = GroupPrincipal.FindByIdentity(context, userGroupName); string[] studentNames = userNames.Replace(Environment.NewLine, "").Split(',').Select(x => x.Trim()).ToArray(); string usernamePrefix = userNamePrefix.Replace(" ", ""); string username = usernamePrefix + usernameSuffix; string description = "Bruger oprettet med UserHelper"; string physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\"; try { for (int i = 0; i < studentNames.Length; i++) { UserPrincipal user = new UserPrincipal(context); UserManagement management = new UserManagement(user, group); //Create Windows User management.CreateLocalWindowsAccount(username, password, username, description, disablepwchange, pwneverexpires, user); management.AddUserToGroup(group, user); //Create IIS Website iis.CreateWebsite(username, "DefaultAppPool", "*:" + port + ":", physicalPath); //Create FTP Virtual Directory //txtStatusMessages.Text += iis.CreateFTPVDir("localhost", username, physicalPath, username); iis.CreateVirtualDirectory("_FTP", username, physicalPath); //create databases sql.CreateSQLLoginUserAndDatabase(username, username, password); Credentials cred = new Credentials(); cred.DatabaseUserName = username; cred.DatabasePassword = password; cred.FTPUserName = username; cred.FTPPassword = password; cred.WebsitePort = port; cred.WindowsUserGroupName = group.Name; Student student = new Student(); student.Name = studentNames[i]; student.Team = db.Teams.Find(teamId); student.Credentials = cred; db.Students.Add(student); //Change username and port for next iteration usernameSuffix++; username = usernamePrefix + usernameSuffix; physicalPath = "C:\\inetpub\\wwwroot\\" + username + "\\"; port++; } db.SaveChanges(); BatchState.State = UserProcessState.INITIAL; //done } catch (Exception) { throw; } }
private List <ADUser> GetMembers(string groupName) { List <ADUser> users = new List <ADUser>(); try { using (System.Web.Hosting.HostingEnvironment.Impersonate()) { string dlManagerUserName = AppCredentials.Instance.UserName; string dlManagerPassword = AppCredentials.Instance.Password; using (PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, Environment.UserDomainName, dlManagerUserName, dlManagerPassword)) { // find the group in question GroupPrincipal group = GroupPrincipal.FindByIdentity(oPrincipalContext, groupName); // Principal group = GroupPrincipal.FindByIdentity(oPrincipalContext, groupName); // if found.... if (group != null) { // iterate over members var searchPrincipal = new UserPrincipal(oPrincipalContext); PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher(); insPrincipalSearcher.QueryFilter = searchPrincipal; PrincipalSearchResult <Principal> results = insPrincipalSearcher.FindAll(); ADUser obj = null; UserPrincipal theUser = null; foreach (Principal p in results) { if (p is UserPrincipal) { // do whatever you need to do to those members theUser = p as UserPrincipal; obj = new ADUser(); obj.Name = theUser.Name;// .Properties["displayname"][0] + ""; obj.Email = theUser.EmailAddress; obj.StaffID = theUser.SamAccountName; users.Add(obj); //users.Add(theUser.SamAccountName); } } //PrincipalSearchResult<Principal> lstMembers = group.GetMembers(); //ADUser obj = null; //UserPrincipal theUser = null; //foreach (Principal p in lstMembers) //{ // // do whatever you need to do to those members // if (p is UserPrincipal) // { // // do whatever you need to do to those members // theUser = p as UserPrincipal; // obj = new ADUser(); // obj.Name = theUser.Name;// .Properties["displayname"][0] + ""; // obj.Email = theUser.EmailAddress; // obj.StaffID = theUser.SamAccountName; // users.Add(obj); // //users.Add(theUser.SamAccountName); // } //} } } } } catch (Exception ex) { LoggingHelper.Instance.LogError(LogOptions.GetMembers, ex); } return(users); }
public Ticket[] getMyTickets(string username) { List <Ticket> tickets = new List <Ticket>(); hapConfig config = hapConfig.Current; if (config.HelpDesk.Provider == "xml") { XmlDocument doc = new XmlDocument(); doc.Load(Server.MapPath("~/App_Data/Tickets.xml")); string xpath = string.Format("/Tickets/Ticket[@status!='Fixed']"); GroupPrincipal gp = GroupPrincipal.FindByIdentity(HAP.AD.ADUtils.GetPContext(), "Domain Admins"); bool ia = false; try { ia = new User(username).IsMemberOf(gp); } catch { } if (ia) { foreach (XmlNode node in doc.SelectNodes(xpath)) { tickets.Add(Ticket.Parse(node)); } return(tickets.ToArray()); } else { tickets = new List <Ticket>(); foreach (XmlNode node in doc.SelectNodes(xpath)) { if (node.SelectNodes("Note")[0].Attributes["username"].Value.ToLower() == username.ToLower()) { tickets.Add(Ticket.Parse(node)); } } return(tickets.ToArray()); } } else { HAP.Data.SQL.sql2linqDataContext sql = new Data.SQL.sql2linqDataContext(ConfigurationManager.ConnectionStrings[hapConfig.Current.HelpDesk.Provider].ConnectionString); foreach (HAP.Data.SQL.Ticket tick in sql.Tickets.Where(t => t.Archive == "")) { Ticket t = new Ticket(tick); bool add = false; foreach (string s in hapConfig.Current.HelpDesk.UserOpenStates.Split(new char[] { ',' })) { if (t.Status == s.Trim()) { add = true; break; } } if (!add) { foreach (string s in hapConfig.Current.HelpDesk.OpenStates.Split(new char[] { ',' })) { if (t.Status == s.Trim()) { add = true; break; } } } if (add) { tickets.Add(t); } } } return(tickets.ToArray()); }
public GroupPrincipal FindAdminGroup(PrincipalContext principialContext, IdentityType Itype, string adminGroupName) { GroupPrincipal groupPrincipial = GroupPrincipal.FindByIdentity(principialContext, Itype, adminGroupName); return(groupPrincipial); }
private GroupPrincipal FindGroup(string groupName, PrincipalContext context) { return(GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName)); }
public void CreateUserWithTemplate(User user, UserTemplateSettings userTemplateSettings) { using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ServerName, userTemplateSettings.DomainOU, ContextOptions.Negotiate, ServiceUser, ServicePassword)) { using (ADUser newUser = new ADUser(context)) { newUser.SamAccountName = user.Username; newUser.GivenName = user.FirstName; newUser.MiddleName = user.MiddleName; newUser.Surname = user.LastName; newUser.EmailAddress = user.EmailAddress; newUser.PhoneNumber = user.PhoneNumber; newUser.Title = user.Title; newUser.Department = user.Department; newUser.Notes = "Created by ADWeb on " + DateTime.Now.ToString() + "."; newUser.DisplayName = user.LastName + ", " + user.FirstName + " " + user.Initials; newUser.UserPrincipalName = user.Username + UPNSuffix; newUser.Enabled = true; // Settings from the User template newUser.UserCannotChangePassword = userTemplateSettings.UserCannotChangePassword; if (userTemplateSettings.ChangePasswordAtNextLogon) { // This will force the user to change their password // the next time they login newUser.ExpirePasswordNow(); } newUser.PasswordNeverExpires = userTemplateSettings.PasswordNeverExpires; if (userTemplateSettings.AccountExpires) { // We have to determine how long until the user's account // will expire in relation to the date that it is being created. DateTime?expirationDate = new DateTime(); switch (userTemplateSettings.ExpirationRange) { case UserExpirationRange.Days: expirationDate = DateTime.Now.AddDays(userTemplateSettings.ExpirationValue.Value); break; case UserExpirationRange.Weeks: int totalDays = 7 * userTemplateSettings.ExpirationValue.Value; expirationDate = DateTime.Now.AddDays(totalDays); break; case UserExpirationRange.Months: expirationDate = DateTime.Now.AddMonths(userTemplateSettings.ExpirationValue.Value); break; case UserExpirationRange.Years: expirationDate = DateTime.Now.AddYears(userTemplateSettings.ExpirationValue.Value); break; default: break; } newUser.AccountExpirationDate = expirationDate; } newUser.SetPassword(user.Password); newUser.Save(); // Now add the user to the groups associated with the user template foreach (var grp in userTemplateSettings.Groups) { // We are using RootDSE for now because we are looking at the // whole domain. This will need to be changed later on so that // only certain OU's will be searched for groups using (PrincipalContext groupContext = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword)) { GroupPrincipal group = GroupPrincipal.FindByIdentity(groupContext, grp); if (group != null) { group.Members.Add(newUser); group.Save(); } } } } } }
/// <summary> /// /// </summary> /// <param name="groupName"></param> public void GetUsersInGroup(string groupName) { try { string domainName = Properties.Settings.Default.App_CompanyDomain; PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName); ListView lvwListView = this.lvwAttributes; ListViewItem itmListItem = default(ListViewItem); lvwListView.Clear(); lvwListView.Columns.Add("Name", 175, HorizontalAlignment.Left); lvwListView.Columns.Add("LanID", 100, HorizontalAlignment.Left); lvwListView.Columns.Add("Email", 225, HorizontalAlignment.Left); lvwListView.Columns.Add("Office", 150, HorizontalAlignment.Left); lvwListView.Columns.Add("Title", 200, HorizontalAlignment.Left); lvwListView.Columns.Add("Phone Number", 150, HorizontalAlignment.Left); lvwListView.Columns.Add("When Created", 150, HorizontalAlignment.Left); if (grp != null) { foreach (Principal p in grp.GetMembers(false)) { itmListItem = new ListViewItem(); itmListItem.Text = p.Name; itmListItem.SubItems.Add(p.SamAccountName); if (p.StructuralObjectClass == "user") { var uP = (UserPrincipal)p; if (uP != null) { itmListItem.SubItems.Add(uP.EmailAddress); } } var creationDate = string.Empty; var physicaldeliveryofficename = string.Empty; var title = string.Empty; var telephoneNumber = string.Empty; var prop = string.Empty; var directoryEntry = p.GetUnderlyingObject() as DirectoryEntry; prop = "whenCreated"; if (directoryEntry.Properties.Contains(prop)) { creationDate = directoryEntry.Properties[prop].Value.ToString(); } prop = "physicaldeliveryofficename"; if (directoryEntry.Properties.Contains(prop)) { physicaldeliveryofficename = directoryEntry.Properties[prop].Value.ToString(); } prop = "title"; if (directoryEntry.Properties.Contains(prop)) { title = directoryEntry.Properties[prop].Value.ToString(); } prop = "telephoneNumber"; if (directoryEntry.Properties.Contains(prop)) { telephoneNumber = directoryEntry.Properties[prop].Value.ToString(); } itmListItem.SubItems.Add(physicaldeliveryofficename); itmListItem.SubItems.Add(title); itmListItem.SubItems.Add(telephoneNumber); itmListItem.SubItems.Add(creationDate); lvwListView.Items.Add(itmListItem); lvwListView.Refresh(); itmListItem = null; this.Text = Application.ProductName + " (" + groupName + ")"; } grp.Dispose(); ctx.Dispose(); } } catch (Exception ex) { ErrorHandler.DisplayMessage(ex); } }
public static void MakePrincipalUser( string AllowReversiblePasswordEncryption, string DelegationPermitted, string Description, string DisplayName, string EmailAddress, string EmployeeId, string Enabled, string GivenName, string HomeDirectory, string HomeDrive, string MiddleName, string Name, string PasswordNeverExpires, string PasswordNotRequired, string PermittedWorkstations, string SamAccountName, string ScriptPath, string SmartcardLogonRequired, string Surname, string UserCannotChangePassword, string UserPrincipalName, string VoiceTelephoneNumber) { try { PrincipalContext context = new PrincipalContext(ContextType.Machine); UserPrincipal user = new UserPrincipal(context); user.Name = Name; user.SetPassword("ala"); Console.WriteLine("Password and set"); //now add user to "Users" group so it displays in Control Panel Console.WriteLine("Initial account saved"); //user.AccountExpirationDate = Convert.ToDateTime(AccountExpirationDate); //user.AccountLockoutTime = AccountLockoutTime; // read only //user.AdvancedSearchFilter = AdvancedSearchFilter; // read only user.AllowReversiblePasswordEncryption = Convert.ToBoolean(AllowReversiblePasswordEncryption); Console.WriteLine("AllowReversiblePasswordEncryption set"); //user.BadLogonCount = BadLogonCount; // read only //user.Certificates = Certificates; // read only //user.Context = Context; // read only //user.ContextType = ContextType; // ContextType is Domain user.DelegationPermitted = Convert.ToBoolean(DelegationPermitted); Console.WriteLine("DelegationPermitted set"); user.Description = Description; Console.WriteLine("Description set"); user.DisplayName = DisplayName; Console.WriteLine("DisplayName set"); //user.DistinguishedName = DistinguishedName; // read only //user.EmailAddress = EmailAddress.ToString(); //Console.WriteLine("EmailAddress set"); //user.EmployeeId = EmployeeId.ToString(); //Console.WriteLine("EmployeeId set"); user.Enabled = Convert.ToBoolean(Enabled); Console.WriteLine("Enabled set"); //user.GivenName = GivenName; //Console.WriteLine("GivenName set"); //user.Guid = Guid; // read only user.HomeDirectory = HomeDirectory; Console.WriteLine("HomeDirectory set"); user.HomeDrive = HomeDrive; Console.WriteLine("HomeDrive set"); //user.LastBadPasswordAttempt = LastBadPasswordAttempt; // read only //user.LastLogon = LastLogon; // read only //user.LastPasswordSet = LastPasswordSet; // read only //user.MiddleName = MiddleName; //Console.WriteLine("MiddleName set"); user.PasswordNeverExpires = Convert.ToBoolean(PasswordNeverExpires); Console.WriteLine("PasswordNeverExpires set"); user.PasswordNotRequired = Convert.ToBoolean(PasswordNotRequired); Console.WriteLine("PasswordNotRequired set"); //user.PermittedLogonTimes = new byte[Convert.ToByte(PermittedLogonTimes)]; //Console.WriteLine("PermittedLogonTimes set"); //user.PermittedWorkstations = PermittedWorkstations; // read only user.SamAccountName = SamAccountName; // read only user.ScriptPath = ScriptPath; Console.WriteLine("ScriptPath set"); //user.Sid = Sid; // read only user.SmartcardLogonRequired = Convert.ToBoolean(SmartcardLogonRequired); Console.WriteLine("SmartcardLogonRequired set"); //user.StructuralObjectClass = StructuralObjectClass; // read only //user.Surname = Surname; //Console.WriteLine("Surname set"); user.UserCannotChangePassword = Convert.ToBoolean(UserCannotChangePassword); Console.WriteLine("UserCannotChangePassword set"); //user.UserPrincipalName = UserPrincipalName; //Console.WriteLine("UserPrincipalName set"); //user.VoiceTelephoneNumber = VoiceTelephoneNumber; //Console.WriteLine("VoiceTelephoneNumber set"); user.Save(); GroupPrincipal groupPrinc = GroupPrincipal.FindByIdentity(context, "Users"); groupPrinc.Members.Add(user); groupPrinc.Save(); Console.WriteLine("User saved"); return; } catch (Exception ex) { Console.WriteLine("Error creating account: {0}", ex.Message); } }
public void CreateUserWithTemplate(User user, UserTemplateSettings userTemplateSettings) { using (PrincipalContext context = new PrincipalContext(ContextType.Domain, ServerName, userTemplateSettings.DomainOU, ContextOptions.Negotiate, ServiceUser, ServicePassword)) { using (ADUser newUser = new ADUser(context)) { newUser.SamAccountName = user.Username; newUser.GivenName = user.FirstName; newUser.MiddleName = user.MiddleName; newUser.Surname = user.LastName; newUser.EmailAddress = user.EmailAddress; newUser.PhoneNumber = user.PhoneNumber; newUser.Title = user.Title; newUser.Department = user.Department; newUser.Notes = "Created by ADWeb on " + DateTime.Now.ToString() + "."; newUser.DisplayName = user.LastName + ", " + user.FirstName; //newUser.Name = user.LastName + ", " + user.FirstName; //newUser.CommonName = "CN=" + user.LastName + "\\, " + user.FirstName + "," + userTemplateSettings.DomainOU; newUser.UserPrincipalName = user.Username + UPNSuffix; newUser.Enabled = true; // Settings from the User template newUser.UserCannotChangePassword = userTemplateSettings.UserCannotChangePassword; if (userTemplateSettings.ChangePasswordAtNextLogon) { // This will force the user to change their password // the next time they login newUser.ExpirePasswordNow(); } newUser.PasswordNeverExpires = userTemplateSettings.PasswordNeverExpires; if (userTemplateSettings.AccountExpires) { // We have to determine how long until the user's account // will expire in relation to the date that it is being created. DateTime?expirationDate = new DateTime(); switch (userTemplateSettings.ExpirationRange) { case UserExpirationRange.Days: expirationDate = DateTime.Now.AddDays(userTemplateSettings.ExpirationValue.Value); break; case UserExpirationRange.Weeks: int totalDays = 7 * userTemplateSettings.ExpirationValue.Value; expirationDate = DateTime.Now.AddDays(totalDays); break; case UserExpirationRange.Months: expirationDate = DateTime.Now.AddMonths(userTemplateSettings.ExpirationValue.Value); break; case UserExpirationRange.Years: expirationDate = DateTime.Now.AddYears(userTemplateSettings.ExpirationValue.Value); break; default: break; } newUser.AccountExpirationDate = expirationDate; } newUser.SetPassword(user.Password); newUser.Save(); // Now now have to add the user to the groups associated with the user template. // Note: We are using RootDSE for now because we are looking at the whole domain. // This will need to be changed later on so that only certain OU's will be searched // for groups using (PrincipalContext groupContext = new PrincipalContext(ContextType.Domain, ServerName, null, ContextOptions.Negotiate, ServiceUser, ServicePassword)) { foreach (var grp in userTemplateSettings.Groups) { using (GroupPrincipal group = GroupPrincipal.FindByIdentity(groupContext, grp)) { if (group != null) { // This is being done to address Github Issue #79. For now we are using // the underlying DirectoryEntry object so that the application can be // hosted on a machine that is not part of the domain. DirectoryEntry groupDE = (DirectoryEntry)group.GetUnderlyingObject(); groupDE.Invoke("Add", new object[] { "LDAP://" + ServerName + "/" + newUser.DistinguishedName }); groupDE.Close(); //group.Members.Add(newUser); //group.Save(); } } } } } } }
public IObservable <GroupObject> GetGroup(string identity, IScheduler scheduler = null) => Observable.Start(() => { var up = GroupPrincipal.FindByIdentity(_principalContext, identity); return(up != null ? new GroupObject(up) : null); }, scheduler ?? TaskPoolScheduler.Default);
public static List <string> UserGroupSearch(string q, bool isUser) { /** ** Parametros para conexão ao seu AD ** @param[0] = Corresponde ao seu dominio ** @param[1] = Usuario utilizado para o login no AD ** @param[2] = Senha do usuario utilizado para o login no AD **/ string[] param = { "domain", "user", "password" }; //Aqui criamos uma lista de string para o retorno das informações List <string> ret = new List <string>(); /** ** Criamos os objetos de conexão e os Objetos de pesquisa para usuario e senha passando como parametro de pesquisa ** a informação que vira no input, no caso nosso parametro é o "q", as informações para pesquisa devem ser o ** ususario de login ou o grupo de AD, caso seja informado o usuario, retornara todos os grupos ao qual ele ** pertence, caso contrario, retornara todos os usarios vinculado ao grupo informado, o parametro isUser é usado ** para alternar entre usuario ou grupo no momento do envio da informação. ** ** @q = Query que recebera as informações do input **/ PrincipalContext ctx = new PrincipalContext(ContextType.Domain, param[0], param[1], param[2]); GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, q); UserPrincipal usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, q); if (grp != null && !isUser) { foreach (Principal g in grp.GetMembers(false)) { if (g.StructuralObjectClass == "user") { var user = ( UserPrincipal )g; if (user != null) { ret.Add(user.Name); } } } grp.Dispose(); ctx.Dispose(); } else if (usr != null && isUser) { foreach (Principal u in usr.GetGroups()) { if (u.StructuralObjectClass == "group") { var group = ( GroupPrincipal )u; if (group != null) { ret.Add(group.Name); } } } usr.Dispose(); ctx.Dispose(); } return(ret); }
/// <summary> /// This method returns a GroupPrincipal object that corrosponds to the specified group name. /// </summary> /// <param name="name">The group to get</param> /// <returns>Returns a GroupPrincipal Object.</returns> public static GroupPrincipal GetGroup(string name) { PrincipalContext pc = GetPrincipalContext(); return(GroupPrincipal.FindByIdentity(pc, name)); }
public void AddUser(string groupName, string userPrincipalName) { GroupPrincipal gp = null; UserPrincipal usr = null; try { if (string.IsNullOrEmpty(groupName)) { throw new MissingFieldException("Users", "groupName"); } if (string.IsNullOrEmpty(userPrincipalName)) { throw new MissingFieldException("Users", "userPrincipalName"); } log.DebugFormat("Attempting to add {0} to group {1}...", userPrincipalName, groupName); pc = GetPrincipalContext(); gp = GroupPrincipal.FindByIdentity(pc, IdentityType.Name, groupName); if (gp == null) { throw new NoMatchingPrincipalException(groupName); } usr = UserPrincipal.FindByIdentity(pc, IdentityType.UserPrincipalName, userPrincipalName); if (usr == null) { throw new NoMatchingPrincipalException(userPrincipalName); } if (!gp.Members.Contains(usr)) { gp.Members.Add(usr); gp.Save(); log.InfoFormat("Successfully added {0} to group {1}.", userPrincipalName, groupName); } else { log.DebugFormat("Did not add {0} to group {1} because the user was already a member.", userPrincipalName, groupName); } } catch (Exception ex) { log.ErrorFormat("Error adding {0} to group {1}. Exception: {2}", userPrincipalName, groupName, ex.ToString()); throw; } finally { if (usr != null) { usr.Dispose(); } if (gp != null) { gp.Dispose(); } } }
/// <summary> /// /// </summary> /// <param name="principalContext"></param> /// <param name="groupName"></param> /// <returns></returns> public static IGroupPrincipal FindByIdentity(IPrincipalContext principalContext, string groupName) { return(new GroupPrincipalWrap(GroupPrincipal.FindByIdentity(principalContext.PrincipalContextInstance, groupName))); }