Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Clinical ID Switcher
- * Justin Mangum
- * 05/19/2011
- *
- * Tasks to be done:
- * Get Data from SCCM, load into array
- *
- *
- * Functions to be written:
- *
- *
- *
- * Connection Strings:
- * Data Source=FTWSCCMSQL01\INSTANCE1;Initial Catalog=SMS_TH1;Integrated Security=True
- *
- *
- * Test Accounts Info:
- * User accounts:
- * JCPSite01 - 04 wired 01 - 03
- * JCPSite01 - 04 wireless 01 - 03
- *
- * Groups:
- * Wired Test Site 1-4
- * Wireless Test Site 1-4
- *
- */
- using System;
- using System.Collections;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- using System.DirectoryServices;
- using System.DirectoryServices.AccountManagement;
- using System.Data.SqlClient;
- using System.Text.RegularExpressions;
- using System.IO;
- namespace Clinical_ID_Switcher
- {
- public partial class frmMain : Form
- {
- String[, ,] _SCCMInfo;
- String[, ,] _ADInfo;
- String[, ,] _Final;
- String[, ,] _Final2;
- String[] _sites;
- String[] _groups;
- public enum objectClass
- {
- user, group, computer
- }
- public enum returnType
- {
- distinguishedName, ObjectGUID
- }
- public enum logType
- {
- notification, warning, error
- }
- public frmMain()
- {
- Log("Initializing",logType.notification);
- InitializeComponent();
- _SCCMInfo = new String[15, 2, 2000];
- _ADInfo = new String[15, 2, 2000];
- _Final = new String[15, 2, 2000];
- _Final2 = new String[15, 2, 2000];
- _sites = new String[15];
- _sites[0] = "THA";
- _sites[1] = "THAM";
- _sites[2] = "THAZ";
- _sites[3] = "THC";
- _sites[4] = "THD";
- _sites[5] = "THDN";
- _sites[6] = "THFW";
- _sites[7] = "THHEB";
- _sites[8] = "THHV";
- _sites[9] = "THK";
- _sites[10] = "THP";
- _sites[11] = "THPG";
- _sites[12] = "THS";
- _sites[13] = "THSW";
- _sites[14] = "THW";
- _groups = new String[2];
- _groups[0] = "Wired";
- _groups[1] = "Wireless";
- lblStatus.Text = "Getting Data from SCCM";
- progressBar1.Value = 33;
- backgroundGetSCCM.RunWorkerAsync();
- txtUser.Text = "texas\\e~mangumj";
- foreach (string site in _sites)
- {
- lstSites.Items.Add(site.ToString());
- }
- }
- public void AddToGroup(string userDn, string groupDn)
- {
- try
- {
- //"LDAP://CN"
- userDn = userDn.Substring(7);
- DirectoryEntry dirEntry = new DirectoryEntry(groupDn, txtUser.Text, txtPass.Text);
- dirEntry.Properties["member"].Add(userDn);
- dirEntry.CommitChanges();
- dirEntry.Close();
- Log("Add successful", logType.notification);
- }
- catch (System.DirectoryServices.DirectoryServicesCOMException e)
- {
- MessageBox.Show(e.Message);
- Log("Adding " + userDn + " failed - " + e.Message, logType.error);
- }
- catch (Exception ex)
- {
- Log("Adding " + userDn + " failed - " + ex.Message,logType.error);
- MessageBox.Show(ex.Message);
- }
- }
- public void RemoveFromGroup(string userDn, string groupDn)
- {
- try
- {
- userDn = userDn.Substring(7);
- DirectoryEntry dirEntry = new DirectoryEntry(groupDn, txtUser.Text, txtPass.Text);
- dirEntry.Properties["member"].Remove(userDn);
- dirEntry.CommitChanges();
- dirEntry.Close();
- Log("Removal successful", logType.notification);
- }
- catch (System.DirectoryServices.DirectoryServicesCOMException e)
- {
- Log("Removing " + userDn + " failed - " + e.Message, logType.error);
- MessageBox.Show(e.Message);
- }
- catch (Exception ex)
- {
- Log("Removing " + userDn + " failed - " + ex.Message, logType.error);
- MessageBox.Show(ex.Message);
- }
- }
- public ArrayList GetUsersInGroup(string myGroup)
- {
- ArrayList memberList = new ArrayList();
- var myDomain = new PrincipalContext(ContextType.Domain, "txhealth.org", "OU=THR Users,DC=txhealth,DC=org");
- var group = GroupPrincipal.FindByIdentity(myDomain, myGroup);
- if (group != null)
- {
- Log("Getting users in group: " + group, logType.notification);
- var members = group.GetMembers();
- foreach (var member in members)
- {
- string tempUser = member.SamAccountName;
- if (!Regex.IsMatch(tempUser, @"^[\p{L}]+$"))
- memberList.Add(tempUser);
- else
- Log(tempUser + " ignored.", logType.warning);
- }
- }
- else
- {
- Log(@"Could not find group " + myGroup + ". Try again.", logType.error);
- return null;
- }
- return memberList;
- }
- private void lstSites_SelectedIndexChanged(object sender, EventArgs e)
- {
- lstGroups.Items.Clear();
- lstUsers.Items.Clear();
- foreach (string group in _groups)
- {
- lstGroups.Items.Add(group);
- }
- }
- private void lstGroups_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (lstSites.FocusedItem == null)
- return;
- if (lstGroups.FocusedItem == null)
- return;
- lstUsers.Items.Clear();
- int x =0;
- while (_Final2[lstSites.FocusedItem.Index, lstGroups.FocusedItem.Index, x] != null)
- {
- x++;
- }
- for (int i = 0; i < x; i++)
- {
- string temp = _Final2[lstSites.FocusedItem.Index, lstGroups.FocusedItem.Index, i];
- if (temp.Contains("+"))
- {
- lstUsers.Items.Add(temp.Substring(1));
- lstUsers.Items[i].BackColor = Color.Green;
- }
- else if (temp.Contains("-"))
- {
- lstUsers.Items.Add(temp.Substring(1));
- lstUsers.Items[i].BackColor = Color.Red;
- }
- else
- lstUsers.Items.Add(temp);
- }
- }
- private void btnCancel_Click(object sender, EventArgs e)
- {
- Log("Closing", logType.notification);
- this.Close();
- }
- private void btnCleanup_Click(object sender, EventArgs e)
- {
- //HERE WE GO!
- int x = 0, y = 0, z = 0;
- string tempUser = "", tempGroup = "";
- foreach (string site in _sites)
- {
- y = 0;
- foreach (string group in _groups)
- {
- z = 0;
- tempGroup = GetObjectDistinguishedName("Clinical IDs " + site + " " + group, objectClass.group);
- bool end = false;
- do
- {
- if (_Final2[x, y, z] != null)
- {
- tempUser = _Final2[x, y, z];
- if (tempUser.Contains("+"))
- {
- //add user
- tempUser = tempUser.Substring(1);
- if (tempUser.Contains("texas"))
- tempUser = tempUser.Substring(6);
- Log("Adding " + tempUser + " to " + tempGroup, logType.notification);
- try
- {
- tempUser = GetObjectDistinguishedName(tempUser, objectClass.user);
- AddToGroup(tempUser, tempGroup);
- }
- catch (Exception ex)
- {
- Log(ex.Message, logType.error);
- }
- }
- else if (tempUser.Contains("-"))
- {
- //remove user
- tempUser = tempUser.Substring(1);
- if (tempUser.Contains("texas"))
- tempUser = tempUser.Substring(6);
- Log("Removing " + tempUser + " from " + tempGroup, logType.notification);
- try
- {
- tempUser = GetObjectDistinguishedName(tempUser, objectClass.user);
- RemoveFromGroup(tempUser, tempGroup);
- }
- catch (Exception ex)
- {
- Log(ex.Message, logType.error);
- }
- }
- else
- {
- //do nothing
- }
- }
- else
- end = true;
- z++;
- } while (!end);
- y++;
- }
- x++;
- }
- Log("Completed Cleanup. Closing", logType.notification);
- this.Close();
- }
- public string GetObjectDistinguishedName(string objectName, objectClass objectCls)
- {
- returnType returnValue = returnType.distinguishedName;
- string LdapDomain = "txhealth.org";
- string distinguishedName = string.Empty;
- string connectionPrefix = "LDAP://" + LdapDomain;
- DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
- DirectorySearcher mySearcher = new DirectorySearcher(entry);
- switch (objectCls)
- {
- case objectClass.user:
- mySearcher.Filter = "(&(objectClass=user)(|(cn=" + objectName + ")(sAMAccountName=" + objectName + ")))";
- break;
- case objectClass.group:
- mySearcher.Filter = "(&(objectClass=group)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
- break;
- case objectClass.computer:
- mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + objectName + ")(dn=" + objectName + ")))";
- break;
- }
- SearchResult result = mySearcher.FindOne();
- if (result == null)
- {
- throw new NullReferenceException
- ("unable to locate the distinguishedName for the object " +
- objectName + " in the " + LdapDomain + " domain");
- }
- DirectoryEntry directoryObject = result.GetDirectoryEntry();
- if (returnValue.Equals(returnType.distinguishedName))
- {
- distinguishedName = "LDAP://" + directoryObject.Properties
- ["distinguishedName"].Value;
- }
- if (returnValue.Equals(returnType.ObjectGUID))
- {
- distinguishedName = directoryObject.Guid.ToString();
- }
- entry.Close();
- entry.Dispose();
- mySearcher.Dispose();
- return distinguishedName;
- }
- static void Log(string note, logType lType)
- {
- using (var logFile = new StreamWriter("c:\\logs\\IDClean.log", true))
- {
- string type = "";
- switch (lType)
- {
- case logType.notification:
- type = "1";
- break;
- case logType.warning:
- type = "2";
- break;
- case logType.error:
- type = "3";
- break;
- }
- //logFile.WriteLine("[" + DateTime.Now.ToString() + "] " + note);
- string Time = DateTime.Now.ToShortTimeString().Contains("PM") ? DateTime.Now.ToLongTimeString().Replace(" PM", ".679+300") : DateTime.Now.ToLongTimeString().Replace(" AM", ".679+300");
- logFile.WriteLine("<![LOG[" + note + "]LOG]!><time=\"" + Time + "\" date=\"" + DateTime.Now.ToShortDateString().Replace("/", "-") + "\" component=\"IDSwitcher\" context=\"\" type=\""+type+"\" file=\"execreqmgr.cpp:6524\">");
- logFile.Close();
- }
- }
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- //bool end = false;
- //Compare each list in _Final to all other lists, find common users, load to _Final2
- for (int x = 0; x < 15; x++)
- {
- Log("Site " + x, logType.notification);
- for (int y = 0; y < 2; y++)
- {
- int o = 0;
- int i = 0;
- while (_Final[x, y, i] != null)
- {
- i++;
- }
- for (int z = 0; z < i; z++)
- {
- string temp = _Final[x, y, z];
- string temp2 = "";
- if (!temp.Contains("-"))
- {
- _Final2[x, y, o] = temp;
- o++;
- }
- if (temp.Contains("-"))
- {
- temp2 = "+" + temp.Substring(1);
- for (int x2 = 0; x2 < 15; x2++)
- {
- for (int y2 = 0; y2 < 2; y2++)
- {
- int i2 = 0;
- while (_Final[x2, y2, i2] != null)
- {
- i2++;
- }
- for (int z2 = 0; z2 < i2; z2++)
- {
- if (_Final[x2, y2, z2] != null)
- {
- if (temp2 == _Final[x2, y2, z2])
- {
- //found
- _Final2[x, y, o] = temp;
- o++;
- Log(temp.Substring(1) + " found in SCCM, will be removed from its group", logType.notification);
- }
- }
- else
- {
- Log(temp.Substring(1) + " not found in SCCM, will not be removed from its group", logType.warning);
- //not found, do not remove
- }
- }
- }
- }
- //if (_Final[x, y, z] != null)
- //{
- // string curUser = _Final[x, y, z];
- // if (temp2 == curUser)
- // {
- // //found
- // _Final2[x, y, o] = temp;
- // o++;
- // }
- //}
- //else
- //{
- // Log(temp.Substring(1) + "not found in SCCM, will not be removed from its group", logType.warning);
- // //not found, do not remove
- // //_Final[x, y, z] = temp;
- //}
- //backgroundCompare1.ReportProgress(0, temp);
- }
- }
- }
- }
- }
- private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- }
- private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- lblStatus.Visible = false;
- progressBar1.Visible = false;
- lblStatus2.Visible = false;
- progressBar2.Visible = false;
- lblGroup.Visible = true;
- lblPass.Visible = true;
- lblSite.Visible = true;
- lblUserID.Visible = true;
- lblUsers.Visible = true;
- txtPass.Visible = true;
- txtUser.Visible = true;
- lstGroups.Visible = true;
- lstSites.Visible = true;
- lstUsers.Visible = true;
- btnCancel.Visible = true;
- btnCleanup.Visible = true;
- }
- private void backgroundGetSCCM_DoWork(object sender, DoWorkEventArgs e)
- {
- Log("Getting data from SCCM", logType.notification);
- int x = 0, y = 0, z = 0;
- SqlConnection myConnection = new SqlConnection("Data Source=FTWSCCMSQL01\\INSTANCE1;Initial Catalog=SMS_TH1;Integrated Security=True");
- try
- {
- myConnection.Open();
- Log("SQL Connection opened", logType.notification);
- SqlDataReader myReader = null;
- SqlCommand myCommand = new SqlCommand("SELECT v_R_System.User_Name0, v_RA_System_SystemOUName.System_OU_Name0 FROM v_R_System INNER JOIN v_RA_System_SystemOUName ON v_R_System.ResourceID = v_RA_System_SystemOUName.ResourceID WHERE (v_RA_System_SystemOUName.System_OU_Name0 LIKE '%Clinical%') AND (v_R_System.User_Name0 IS NOT NULL) ORDER BY v_RA_System_SystemOUName.System_OU_Name0, v_R_System.User_Name0", myConnection);
- myReader = myCommand.ExecuteReader();
- Log("SQL Reader started", logType.notification);
- while (myReader.Read())
- {
- x = 0;
- y = 0;
- z = 0;
- string user = myReader[0].ToString();
- string OU = myReader[1].ToString();
- OU = OU.Substring(OU.IndexOf("/") + 1);
- OU = OU.Substring(OU.IndexOf("/") + 1);
- OU = OU.Substring(OU.IndexOf("/") + 1);
- //MessageBox.Show(OU);
- y = OU.Contains("WIRED") ? 0 : 1;
- string site = OU.Substring(OU.IndexOf(" ") + 1);
- site = site.Substring(site.IndexOf(" ") + 1);
- //MessageBox.Show(OU);
- switch (site)
- {
- case ("THHV"):
- //_sites[8] = "THHV";
- x = 8;
- break;
- case ("THPG"):
- //_sites[11] = "THPG";
- x = 11;
- break;
- case ("AMH"):
- //_sites[1] = "THAM";
- x = 1;
- break;
- case ("HEB"):
- //_sites[7] = "THHEB";
- x = 7;
- break;
- case ("HFW"):
- //_sites[6] = "THFW";
- x = 6;
- break;
- case ("HMEC"):
- //_sites[12] = "THS";
- x = 12;
- break;
- case ("HNW"):
- //_sites[2] = "THAZ";
- x = 2;
- break;
- case ("HSW"):
- //_sites[13] = "THSW";
- x = 13;
- break;
- case ("PHA"):
- //_sites[0] = "THA";
- x = 0;
- break;
- case ("PHD"):
- //_sites[4] = "THD";
- x = 4;
- break;
- case ("PHK"):
- //_sites[9] = "THK";
- x = 9;
- break;
- case ("PHP"):
- //_sites[10] = "THP";
- x = 10;
- break;
- case ("PHW"):
- //_sites[14] = "THW";
- x = 14;
- break;
- case ("THDN"):
- //_sites[5] = "THDN";
- x = 5;
- break;
- case ("WAL"):
- //_sites[3] = "THC";
- x = 3;
- break;
- default:
- MessageBox.Show(site);
- break;
- }
- //we now have site and group, now add to list of users for that
- while (_SCCMInfo[x, y, z] != null)
- {
- z++;
- }
- if (!Regex.IsMatch(user, @"^[\p{L}]+$"))
- _SCCMInfo[x, y, z] = user;
- else
- Log(user + " ignored from SCCM data.", logType.warning);
- backgroundGetSCCM.ReportProgress(50, user);
- z = 0;
- }
- Log("SQL Reader finished, closing connection", logType.notification);
- myConnection.Close();
- myConnection.Dispose();
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message, "SQL Error");
- Log(ex.Message, logType.error);
- return;
- }
- }
- private void backgroundGetSCCM_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- progressBar2.Value = e.ProgressPercentage;
- lblStatus2.Text = e.UserState.ToString();
- }
- private void backgroundGetSCCM_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- lblStatus.Text = "Getting Data from Active Directory";
- progressBar1.Value = 66;
- progressBar2.Value = 0;
- progressBar2.Maximum = 15;
- backgroundGetAD.RunWorkerAsync();
- }
- private void backgroundGetAD_DoWork(object sender, DoWorkEventArgs e)
- {
- Log("Getting data from Active Directory", logType.notification);
- //_ADInfo = null;
- int x = 0, y = 0, z = 0, i=0;
- foreach (string site in _sites)
- {
- i++;
- backgroundGetAD.ReportProgress(i, site);
- y = 0;
- foreach (string group in _groups)
- {
- z = 0;
- ArrayList members = GetUsersInGroup("Clinical IDs " + site + " " + group);
- if (members != null)
- {
- foreach (string member in members)
- {
- _ADInfo[x, y, z] = member;
- z++;
- }
- }
- y++;
- }
- x++;
- }
- }
- private void backgroundGetAD_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- progressBar2.Value = e.ProgressPercentage;
- lblStatus2.Text = e.UserState.ToString();
- }
- private void backgroundGetAD_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- lblStatus.Text = "Comparing Data";
- progressBar1.Value = 80;
- progressBar2.Value = 0;
- progressBar2.Maximum = _SCCMInfo.Length + _ADInfo.Length;
- backgroundCompare1.RunWorkerAsync();
- }
- private void backgroundCompare1_DoWork(object sender, DoWorkEventArgs e)
- {
- Log("Begin Comparing", logType.notification);
- int x = 0, y = 0, z = 0, i = 0;
- string temp = "";
- bool end = false;
- Log("Start with comparing SCCM to AD", logType.notification);
- foreach (string site in _sites)
- {
- y = 0;
- foreach (string group in _groups)
- {
- z = 0;
- i = 0;
- end = false;
- do
- {
- if (_SCCMInfo[x, y, z] != null)
- {
- temp = _SCCMInfo[x, y, z];
- for (i = 0; i < 10000; i++)
- {
- if (_ADInfo[x, y, i] != null)
- {
- if (temp == _ADInfo[x, y, i])
- {
- //found
- i = 10000;
- _Final[x, y, z] = temp;
- }
- }
- else
- {
- i = 10000;
- //not found
- _Final[x, y, z] = "+" + temp;
- }
- //backgroundCompare1.ReportProgress(0, temp);
- }
- }
- else
- end = true;
- z++;
- } while (!end);
- y++;
- }
- x++;
- }
- Log("Now reverse the comparison, to find what is being removed", logType.notification);
- //Log("This has been disabled for now",logType.warning);
- x = 0;
- y = 0;
- z = 0;
- i = 0;
- temp = "";
- end = false;
- foreach (string site in _sites)
- {
- y = 0;
- foreach (string group in _groups)
- {
- z = 0;
- i = 0;
- int z2 = 0;
- while (_Final[x, y, z2] != null)
- {
- z2++;
- }
- end = false;
- do
- {
- if (_ADInfo[x, y, z] != null)
- {
- temp = _ADInfo[x, y, z];
- for (i = 0; i < 2000; i++)
- {
- if (_SCCMInfo[x, y, i] != null)
- {
- if (temp == _SCCMInfo[x, y, i])
- {
- //found
- i = 2000;
- for (int f = 0; f < 2000; f++)
- {
- if (_Final[x, y, f] == temp)
- {
- //already been found, don't add
- f = 1999;
- }
- if (_Final[x, y, f] == null && f != 1999)
- {
- //not added previously, add now
- _Final[x, y, z2] = temp;
- z2++;
- f = 2000;
- }
- }
- }
- }
- else
- {
- i = 2000;
- //not found
- _Final[x, y, z2] = "-" + temp;
- z2++;
- }
- //backgroundCompare1.ReportProgress(0, temp);
- }
- }
- else
- end = true;
- z++;
- } while (!end);
- y++;
- }
- x++;
- }
- }
- private void backgroundCompare1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- //progressBar2.Value += 1;
- //lblStatus2.Text = e.UserState.ToString();
- }
- private void backgroundCompare1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- backgroundWorker1.RunWorkerAsync();
- lblStatus.Text = "Doing Final Comparison";
- progressBar1.Value = 95;
- progressBar2.Value = 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement