示例#1
0
        static void Main(string[] args)
        {
            Arguments CommandLine = new Arguments(args);
            string operation = "";
            string file = "";
             if (CommandLine["F"] != null)
            {
                file = CommandLine["F"];
            }
            else Console.WriteLine("File not defined full path needed -F=c:\\xxx\\yyy\\zzz\\file.ldap warning there is no sanity check on the path");

            operation = CommandLine["O"];
            if (CommandLine["O"] != null)
            {
                if (CommandLine["O"] != "users" || CommandLine["O"] != "groups" || CommandLine["O"] != "OUmap" || CommandLine["O"] != "gmail")
                {
                    Console.WriteLine("Operation not defined -O=users -O=groups -O=OUmap -O=gmail");
                }
                else
                {
                    operation = CommandLine["O"];
                }
            }

             // Check for tests first
             // If tests are desired, skip normal opretaions
             if( CommandLine["T"] != null ){

            // Collection of Class objects
            // Each class needs to have a runTests() method
            GroupSynch groupconfig = new GroupSynch();
            UserSynch userconfig = new UserSynch();
            GmailUsers guserconfig = new GmailUsers();
            executionOrder execution = new executionOrder();
            UserStateChange usermapping = new UserStateChange();
            ConfigSettings settingsconfig = new ConfigSettings();
            utils.ToolSet tools = new ToolSet();
            LogFile log = new LogFile();
            ObjectADSqlsyncGroup groupSyncr = new ObjectADSqlsyncGroup();
            ObjectADGoogleSync gmailSyncr = new ObjectADGoogleSync();
            StopWatch timer = new StopWatch();
            log.initiateTrn();

            // Sift through are different tests
            switch(CommandLine["T"])
            {
               // Run tests specific to users sync
               case "users":
                  // userconfig.runTests();
                  break;

               // Run tests specific to group sync
               case "groups":
                  // groupconfig.runTests();
                  break;

               // Run tests specific to OUmap sync
               case "OUmap":
                  // Not sure how this operation is used
                  break;

               // Run tests specifc to gmail sync
               case "gmail":
                  // guserconfig.runTests();
                  break;

               // Run all tests
               default:
               case "all":
                  // userconfig.runTests();
                  // groupconfig.runTests();
                  // guserconfig.runTests();
                  break;
               }
            }
            // MessageBox.Show("operation is " + operation + " file is " + file);
            else if (file != "" && operation != "")
            {

                // woot halleluijah we have input from the user time to execute
                //duplicate the gui fucntionality in cmd line
                // we won't check this input cause its from a really smart system administrator
                // just in case file expects a full path
                // c:\blah\blah\blah.ext
                // valid oprations are
                // users	groups	 OUmap	 gmail
                // create objects to hold save data

                GroupSynch groupconfig = new GroupSynch();
                UserSynch userconfig = new UserSynch();
                GmailUsers guserconfig = new GmailUsers();
                executionOrder execution = new executionOrder();
                UserStateChange usermapping = new UserStateChange();
                ConfigSettings settingsconfig = new ConfigSettings();
                utils.ToolSet tools = new ToolSet();
                LogFile log = new LogFile();
                ObjectADSqlsyncGroup groupSyncr = new ObjectADSqlsyncGroup();
                ObjectADGoogleSync gmailSyncr = new ObjectADGoogleSync();
                StopWatch timer = new StopWatch();
                log.initiateTrn();

                // perform operations based on the data input from the user fro groups users, OU's and gmail
                if (operation == "group")
                {
                    Dictionary<string, string> properties = new Dictionary<string, string>();
                    try
                    {
                        StreamReader re = File.OpenText(file);
                        string input = null;
                        while ((input = re.ReadLine()) != null && input != "<config>")
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        // Load values into text boxes
                        // reload properties each time as they are overwritten with the combo object trigger events
                        groupconfig.Load(properties);

                        //load config settings
                        properties.Clear();
                        while ((input = re.ReadLine()) != null)
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        re.Close();
                        settingsconfig.Load(properties);

                        log.addTrn("Start Groups Syncs", "Info");
                        timer.Start();
                        groupSyncr.ExecuteGroupSync(groupconfig, settingsconfig, tools, log);
                        timer.Stop();
                        log.addTrn("Groups " + groupconfig.Group_Append + " Setup Completion time :" + timer.GetElapsedTimeSecs().ToString(), "Transaction");
                        tools.savelog(log, settingsconfig);
                    }
                    catch
                    {
                        log.errors.Add("Failed to load save file");
                    }

                    //// save log to disk
                    //SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    //saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    //saveFileDialog1.FilterIndex = 2;
                    //saveFileDialog1.RestoreDirectory = true;
                    //if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    //{
                    //    // create a file stream, where "c:\\testing.txt" is the file path
                    //    System.IO.FileStream fs = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);

                    //    // create a stream writer
                    //    System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.ASCII);

                    //    // write to file (buffer), where textbox1 is your text box
                    //    sw.WriteLine("{0}", result2);
                    //    sw.WriteLine("{0}", result);

                    //    // flush buffer (so the text really goes into the file)
                    //    sw.Flush();

                    //    // close stream writer and file
                    //    sw.Close();
                    //    fs.Close();
                    //}

                }
                if (operation == "users")
                {
                    Dictionary<string, string> properties = new Dictionary<string, string>();
                    DataTable customs = new DataTable();
                    BindingSource bs = new BindingSource();

                    //OpenFileDialog openFileDialog1 = new OpenFileDialog();
                    //openFileDialog1.InitialDirectory = "c:\\";
                    //openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                    //openFileDialog1.FilterIndex = 2;
                    //openFileDialog1.RestoreDirectory = true;
                    //if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    //{
                    try
                    {
                        StreamReader re = File.OpenText(file);

                        string input = null;
                        while ((input = re.ReadLine()) != null && input != "<config>")
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        userconfig.Load(properties);

                        //load config settings
                        properties.Clear();
                        while ((input = re.ReadLine()) != null)
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        re.Close();
                        settingsconfig.Load(properties);
                        log.addTrn("Start User Synch", "Info");
                        timer.Start();
                        groupSyncr.ExecuteUserSync(userconfig, settingsconfig, tools, log);
                        timer.Stop();
                        log.addTrn("Users " + userconfig.BaseUserOU + " Setup Completion time :" + timer.GetElapsedTimeSecs().ToString(), "Transaction");
                        tools.savelog(log, settingsconfig);
                    }
                    catch
                    {
                        Console.Write("Failed to load save file");
                    }

                }
                if (operation == "gmail")
                {
                    Dictionary<string, string> properties = new Dictionary<string, string>();
                    BindingSource bs = new BindingSource();
                    try
                    {
                        StreamReader re = File.OpenText(file);

                        string input = null;
                        while ((input = re.ReadLine()) != null && input != "<config>")
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }

                        guserconfig.Load(properties);
                        //load config settings
                        properties.Clear();
                        while ((input = re.ReadLine()) != null)
                        {
                            string[] parts = input.Split('|');
                            properties.Add(parts[0].Trim(), parts[1].Trim());
                        }
                        re.Close();
                        settingsconfig.Load(properties);
                        log.addTrn("Start Gmail Synch", "Info");
                        timer.Start();
                        gmailSyncr.EmailUsersSync(guserconfig, settingsconfig, tools, log);
                        timer.Stop();
                        log.addTrn("Gmail " + guserconfig.Admin_domain + " Setup Completion time :" + timer.GetElapsedTimeSecs().ToString(), "Transaction");
                        tools.savelog(log, settingsconfig);
                    }
                    catch
                    {
                        Console.Write("Failed to load save file");
                    }

                }

            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
        }
示例#2
0
        public void UpdateUsers(SqlDataReader users, string ldapDomain, UserSynch usersyn, LogFile log)
        {
            // requires distinguished name to be a field
            // all field names must be valid AD field names
            // does not blank out fields

            int fieldcount = 0;
            int i = 0;
            string name = "";
            string fdqn = "";
            try
            {
            fieldcount = users.FieldCount;
                while (users.Read())
                {

                    DirectoryEntry user = new DirectoryEntry("LDAP://" + (string)users["distinguishedname"]);
                    for (i = 0; i < fieldcount; i++)
                    {
                        name = users.GetName(i);
                        // eliminiate non updatable fields
                        if (name != "password" && name != "CN" && name != "sAMAccountName" && name != "distinguishedname")
                        {

                            // mail needs some special handling
                            switch (name)
                            {
                                case "mail":
                                    if ((string)users[name] != "")
                                    {
                                        // check to see if mail field has illegal characters
                                        string hi = (System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("%40", "@").Replace("%5f", "_"));
                                        string hi3 = (string)users[name];
                                        if (System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("%40", "@").Replace("%5f", "_") == (string)users[name])
                                        {
                                            // no illegal characters input the value into AD
                                            user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("!", "%21").Replace("(", "%28").Replace(")", "%29").Replace("'", "%27").Replace("%5f", "_").Replace(" ", "%20").Replace("%40", "@");
                                        }
                                        else
                                        {
                                            user.Properties[name].Value = "illegal Email";
                                        }
                                    }
                                    break;
                                case "userAccountControl":
                                    if ((string)users[name] != "")
                                    {
                                        int val = (int)user.Properties["userAccountControl"].Value;
                                        user.Properties["userAccountControl"].Value = val | Convert.ToInt32(System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").ToString());
                                    }
                                    break;
                                case "manager":
                                    if ((string)users[name] != "")
                                    {
                                        fdqn = GetObjectDistinguishedName(objectClass.user, returnType.distinguishedName, System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A"), ldapDomain, log);
                                        if (!fdqn.Contains("CN"))
                                        {
                                            log.addTrn("Issue Updating User: "******"distinguishedname"] + " Invalid Manager selected. ", "Error");
                                        }
                                        else
                                        {
                                            user.Properties["manager"].Value = fdqn.Substring(fdqn.IndexOf("CN"));
                                        }
                                    }
                                    break;
                                case "sn":
                                    if ((string)users[name] != "")
                                    {
                                        user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A");
                                        user.Properties["displayName"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");
                                        user.Properties["description"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");

                                    }
                                    break;
                                case "givenName":
                                    if ((string)users[name] != "")
                                    {
                                        user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A");
                                        user.Properties["displayName"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");
                                        user.Properties["description"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");

                                    }
                                    break;
                                default:
                                    if ((string)users[name] != "")
                                    {
                                        user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A");
                                    }
                                    break;
                            }

                            //if (name != "mail")
                            //{
                            //    if ((string)users[name] != "")
                            //    {
                            //        user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A");
                            //    }
                            //}
                            //else
                            //{
                            //    // check to see if mail field has illegal characters
                            //    string hi = (System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("%40", "@"));
                            //    string hi3 = (string)users[name];
                            //    if (System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("%40", "@") != (string)users[name])
                            //    {
                            //        // no illegal characters input the value into AD
                            //        user.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("!", "%21").Replace("(", "%28").Replace(")", "%29").Replace("'", "%27").Replace("_", "%5f").Replace(" ", "%20").Replace("%40", "@");
                            //    }
                            //    else
                            //    {
                            //        user.Properties[name].Value = "illegal Email";
                            //    }
                            //}

                        }
                    }
                    user.CommitChanges();
                    log.addTrn("User updated |" + (string)users["distinguishedname"] + " ", "Transaction");
                }
            }
            catch (Exception ex)
            {
                if (users != null)
                {
                    log.addTrn("issue updating user " + name + " " + System.Web.HttpUtility.UrlEncode((string)users["distinguishedname"]).Replace("+", " ").Replace("*", "%2A") + "\n" + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                }
                else
                {
                    log.addTrn("issue updating users data reader is null " + "\n" + ex.Message.ToString(), "Error");
                }
            }
        }
示例#3
0
        public void CreateUsersAccounts(string ouPath, SqlDataReader users, string groupDn, string ldapDomain, UserSynch usersyn, LogFile log)
        {
            // oupath holds the path for the AD OU to hold the Users
            // users is a sqldatareader witht the required fields in it ("CN") other Datastructures would be easy to substitute
            // groupDN is a base group which all new users get automatically inserted into

            int i;
            int fieldcount;
            int val;
            string name = "";
            string last = "";
            string first = "";
            fieldcount = users.FieldCount;
            try
            {
                while (users.Read())
                {
                    try
                    {

                        if (users[usersyn.User_password].ToString() != "")
                        {
                            if (!DirectoryEntry.Exists("LDAP://CN=" + System.Web.HttpUtility.UrlEncode(users[usersyn.User_sAMAccount].ToString()).Replace("+", " ").Replace("*", "%2A") + "," + ouPath))
                            {

                                DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
                                DirectoryEntry newUser = entry.Children.Add("CN=" + System.Web.HttpUtility.UrlEncode(users[usersyn.User_CN].ToString()).Replace("+", " ").Replace("*", "%2A"), "user");
                                // generated
                                newUser.Properties["samAccountName"].Value = System.Web.HttpUtility.UrlEncode(users[usersyn.User_sAMAccount].ToString()).Replace("+", " ").Replace("*", "%2A");
                                //newUser.Properties["mail"].Value = System.Web.HttpUtility.UrlEncode(users[usersyn.User_mail].ToString()).Replace("+", " ").Replace("*", "%2A") + "@" + System.Web.HttpUtility.UrlEncode(users[usersyn.UserEmailDomain].ToString()).Replace("+", " ").Replace("*", "%2A");
                                newUser.Properties["UserPrincipalName"].Value = System.Web.HttpUtility.UrlEncode(users[usersyn.User_sAMAccount].ToString()).Replace("+", " ").Replace("*", "%2A");
                                newUser.Properties["displayName"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");
                                newUser.Properties["description"].Value = System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Lname]).Replace("+", " ").Replace("*", "%2A") + ", " + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_Fname]).Replace("+", " ").Replace("*", "%2A");

                                newUser.CommitChanges();

                                // SQL query generated ensures matching field names between the SQL form fields and AD
                                for (i = 0; i < fieldcount; i++)
                                {
                                    name = users.GetName(i);
                                    // eliminiate non updatable fields
                                    if (name != "password" && name != "CN")
                                    {
                                        // mail needs some special handling
                                        if (name != "mail")
                                        {
                                            if ((string)users[name] != "")
                                            {
                                                newUser.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A");
                                            }
                                        }
                                        else
                                        {
                                            first = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("%40", "@");
                                            last = (string)users[name];
                                            // check to see if mail field has illegal characters
                                            if (first == last)
                                            {
                                                // no illegal characters input the value into AD
                                                newUser.Properties[name].Value = System.Web.HttpUtility.UrlEncode((string)users[name]).Replace("+", " ").Replace("*", "%2A").Replace("!", "%21").Replace("(", "%28").Replace(")", "%29").Replace("'", "%27").Replace("_", "%5f").Replace(" ", "%20").Replace("%40", "@");
                                            }
                                            else
                                            {
                                                // newUser.Properties[name].Value = "";
                                            }
                                        }
                                    }
                                }

                                AddUserToGroup("CN=" + System.Web.HttpUtility.UrlEncode(users[usersyn.User_sAMAccount].ToString()).Replace("+", " ").Replace("*", "%2A") + "," + usersyn.UserHoldingTank, groupDn, false, ldapDomain, log);
                                newUser.Invoke("SetPassword", new object[] { System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_password]).Replace("+", " ").Replace("*", "%2A") });
                                newUser.CommitChanges();

                                val = (int)newUser.Properties["userAccountControl"].Value;
                                // set to normal user
                                newUser.Properties["userAccountControl"].Value = val | (int)accountFlags.ADS_UF_NORMAL_ACCOUNT;
                                // set to enabled account val & ~0c0002 creates a bitmask which reverses the disabled bit
                                newUser.Properties["userAccountControl"].Value = val & ~(int)accountFlags.ADS_UF_ACCOUNTDISABLE;
                                newUser.CommitChanges();
                                newUser.Close();
                                newUser.Dispose();
                                entry.Close();
                                entry.Dispose();
                                log.addTrn("User added |" + (string)users[usersyn.User_sAMAccount] + " " + usersyn.UserHoldingTank, "Transaction");
                            }
                            else
                            {
                                log.addTrn("CN=" + System.Web.HttpUtility.UrlEncode((string)users[usersyn.User_sAMAccount]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + " user already exists from adding", "Error");
                                //MessageBox.Show("CN=" + System.Web.HttpUtility.UrlEncode((string)users["CN"]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + " user already exists from adding");
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        string debugdata = "";
                        for (i = 0; i < fieldcount; i++)
                        {

                            debugdata += users.GetName(i) + "=" + System.Web.HttpUtility.UrlEncode((string)users[i]).Replace("+", " ").Replace("*", "%2A") + ", ";

                        }
                        log.addTrn("issue create user LDAP://CN=" + System.Web.HttpUtility.UrlEncode((string)users["CN"]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + "\n" + debugdata + " User create failed, commit error" + name + " | " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                        // MessageBox.Show(e.Message.ToString() + "issue create user LDAP://CN=" + System.Web.HttpUtility.UrlEncode((string)users["CN"]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + "\n" + debugdata);
                    }
                }

            }
            catch (Exception ex)
            {
                if (users != null)
                {
                    string debugdata = "";
                    for (i = 0; i < fieldcount; i++)
                    {

                        debugdata += users.GetName(i) + "=" + System.Web.HttpUtility.UrlEncode((string)users[i]).Replace("+", " ").Replace("*", "%2A") + ", ";

                    }
                    log.addTrn("issue create user LDAP://CN=" + System.Web.HttpUtility.UrlEncode((string)users["CN"]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + "\n" + debugdata + " failed field maybe " + name + " | " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                    // MessageBox.Show(e.Message.ToString() + "issue create user LDAP://CN=" + System.Web.HttpUtility.UrlEncode((string)users["CN"]).Replace("+", " ").Replace("*", "%2A") + "," + ouPath + "\n" + debugdata);
                }
                else
                {
                    log.addTrn("issue creating users datareader is null " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                }

            }

            /*
                //Add this to the create account method
                int val = (int)newUser.Properties["userAccountControl"].Value;
                     //newUser is DirectoryEntry object
                newUser.Properties["userAccountControl"].Value = val | 0x80000;
                    //ADS_UF_TRUSTED_FOR_DELEGATION

             *
             * UserAccountControlFlags
             * CONST   HEX
                -------------------------------
                SCRIPT 0x0001
                ACCOUNTDISABLE 0x0002
                HOMEDIR_REQUIRED 0x0008
                LOCKOUT 0x0010
                PASSWD_NOTREQD 0x0020
                PASSWD_CANT_CHANGE 0x0040
                ENCRYPTED_TEXT_PWD_ALLOWED 0x0080
                TEMP_DUPLICATE_ACCOUNT 0x0100
                NORMAL_ACCOUNT 0x0200
                INTERDOMAIN_TRUST_ACCOUNT 0x0800
                WORKSTATION_TRUST_ACCOUNT 0x1000
                SERVER_TRUST_ACCOUNT 0x2000
                DONT_EXPIRE_PASSWORD 0x10000
                MNS_LOGON_ACCOUNT 0x20000
                SMARTCARD_REQUIRED 0x40000
                TRUSTED_FOR_DELEGATION 0x80000
                NOT_DELEGATED 0x100000
                USE_DES_KEY_ONLY 0x200000
                DONT_REQ_PREAUTH 0x400000
                PASSWORD_EXPIRED 0x800000
                TRUSTED_TO_AUTH_FOR_DELEGATION 0x1000000
             * */
        }
示例#4
0
        public ArrayList SqlColumns(UserSynch userconfig)
        {
            ArrayList columnList = new ArrayList();
            if (userconfig.DBCatalog != "" && userconfig.DataServer != "")
            {
                //populates columns dialog with columns depending on the results of a query
                try
                {
                    SqlConnection sqlConn = new SqlConnection("Data Source=" + userconfig.DataServer.ToString() + ";Initial Catalog=" + userconfig.DBCatalog.ToString() + ";Integrated Security=SSPI;");

                    sqlConn.Open();
                    // create the command object
                    SqlCommand sqlComm = new SqlCommand("SELECT column_name FROM information_schema.columns WHERE table_name = '" + userconfig.User_dbTable + "'", sqlConn);
                    sqlComm.CommandTimeout = 360;
                    SqlDataReader r = sqlComm.ExecuteReader();
                    while (r.Read())
                    {
                        columnList.Add((string)r[0].ToString().Trim());
                    }
                    r.Close();
                    sqlConn.Close();
                }
                catch
                {
                    columnList.Add("Error pulling SQL columns");
                }
            }
            return columnList;
        }
示例#5
0
        public void ExecuteUserSync(UserSynch usersyn, ConfigSettings settingsConfig, ToolSet tools, LogFile log)
        {
            int i;
            ArrayList debugList = new ArrayList();
            StopWatch time = new StopWatch();

            string baseOU = usersyn.BaseUserOU;
            string DC = baseOU.Substring(baseOU.IndexOf("DC"));
            string sqlForCustomFields = "";

            // Table string place holders
            string sqlUsersTable = "#FHC_USERS_SQLusersTable";
            string adUsersTable = "#FHC_USERS_ADusersTable";

            SqlDataReader add;
            SqlDataReader delete;
            SqlDataReader update;

            SearchScope scope = SearchScope.OneLevel;
            ArrayList completeSqlKeys = new ArrayList();
            ArrayList completeADKeys = new ArrayList();
            ArrayList adUpdateKeys = new ArrayList();
            ArrayList sqlUpdateKeys = new ArrayList();
            ArrayList extraFieldsToReturn = new ArrayList();
            ArrayList fields = new ArrayList();
            Dictionary<string, string> userObject = new Dictionary<string, string>();
            SqlConnection sqlConn = new SqlConnection("Data Source=" + usersyn.DataServer + ";Initial Catalog=" + usersyn.DBCatalog + ";Integrated Security=SSPI;Connect Timeout=360");

            if (settingsConfig.TempTables == true)
            {
                sqlUsersTable = "#FHC_USERS_SQLusersTable";
                adUsersTable = "#FHC_USERS_ADusersTable";
            }
            else
            {
                sqlUsersTable = "FHC_USERS_SQLusersTable";
                adUsersTable = "FHC_USERS_ADusersTable";

            }

            //SqlDataReader sqlusers;
            SqlCommand sqlComm;
            SqlCommand sqlComm2;
            string recordCount = "";
            DataTable adUsers = new DataTable();

            sqlConn.Open();
            //housecleaning
            log.addTrn("Cleaning out tables", "Info");
            if (settingsConfig.TempTables == false)
            {
                tools.DropTable(sqlUsersTable, sqlConn, log);
                tools.DropTable(adUsersTable, sqlConn, log);
            }

            //if were only updating it doesnt matter where we want ot put new users
            if (usersyn.UpdateOnly == false)
            {
                log.addTrn("Initial setup of OUs and Groups", "Info");
                // create initial ou's; will log a warning out if they already exist
                tools.CreateOURecursive(usersyn.BaseUserOU, log);
                tools.CreateOURecursive(usersyn.UserHoldingTank, log);

                // setup extentions for the user accounts to go in to the right ou's
                userObject.Add("sAMAccountName", usersyn.UniversalGroup.Remove(0, 3).Remove(usersyn.UniversalGroup.IndexOf(",") - 3));
                userObject.Add("CN", usersyn.UniversalGroup.Remove(0, 3).Remove(usersyn.UniversalGroup.IndexOf(",") - 3));
                userObject.Add("description", "Universal Group For Users");
                // creates the group if it does not exist
                tools.CreateGroup(usersyn.UniversalGroup.Remove(0, usersyn.UniversalGroup.IndexOf(",") + 1), userObject, log);
            }

            // need to add this field first to use as a primary key when checking for existance in AD
            completeSqlKeys.Add("sAMAccountName");
            completeSqlKeys.Add("CN");
            completeSqlKeys.Add("sn");
            completeSqlKeys.Add("givenName");
            completeSqlKeys.Add("homePhone");
            completeSqlKeys.Add("st");
            completeSqlKeys.Add("streetAddress");
            completeSqlKeys.Add("l");
            completeSqlKeys.Add("postalCode");
            // ?????? MIGHT NOT BE USED

            // Lets make the SQL fields to check for update
            sqlUpdateKeys.Add("sn");
            sqlUpdateKeys.Add("givenName");
            sqlUpdateKeys.Add("homePhone");
            sqlUpdateKeys.Add("st");
            sqlUpdateKeys.Add("streetAddress");
            sqlUpdateKeys.Add("l");
            sqlUpdateKeys.Add("postalCode");

            // Lets make the Active Directory Keys as well
            completeADKeys.Add("sAMAccountName");
            completeADKeys.Add("CN");
            completeADKeys.Add("sn");
            completeADKeys.Add("givenName");
            completeADKeys.Add("homePhone");
            completeADKeys.Add("st");
            completeADKeys.Add("streetAddress");
            completeADKeys.Add("l");
            completeADKeys.Add("postalCode");
            completeADKeys.Add("distinguishedName");

            // Lets make the Active Directory fields to check for update
            adUpdateKeys.Add("sn");
            adUpdateKeys.Add("givenName");
            adUpdateKeys.Add("homePhone");
            adUpdateKeys.Add("st");
            adUpdateKeys.Add("streetAddress");
            adUpdateKeys.Add("l");
            adUpdateKeys.Add("postalCode");

            //build custom keys
            for (i = 0; i < usersyn.UserCustoms.Rows.Count; i++)
            {
                // build keys to pull back from SQL
                // as well keys to check if these fields need updating
                completeSqlKeys.Add(usersyn.UserCustoms.Rows[i][0].ToString());
                sqlUpdateKeys.Add(usersyn.UserCustoms.Rows[i][0].ToString());

                // build keys to pull back from AD
                // as well keys to check if these fields need updating
                completeADKeys.Add(usersyn.UserCustoms.Rows[i][0].ToString());
                adUpdateKeys.Add(usersyn.UserCustoms.Rows[i][0].ToString());

                // build fields to pull back from SQL
                //create props from rows in usercustoms datatable our column names match the appropriate fields in AD and SQL
                if (usersyn.UserCustoms.Rows[i][1].ToString() != "Static Value")
                {
                    sqlForCustomFields += ", RTRIM(" + usersyn.UserCustoms.Rows[i][1].ToString() + ") AS " + usersyn.UserCustoms.Rows[i][0].ToString();
                }
                // static fields get static values for the table to get updated
                else
                {
                    sqlForCustomFields += ", '" + usersyn.UserCustoms.Rows[i][2].ToString() + "' AS " + usersyn.UserCustoms.Rows[i][0].ToString();
                }
            }

            // grab users data from sql
            log.addTrn("Get users from SQL tables", "Info");
            if (usersyn.User_where == "")
            {
                sqlComm = new SqlCommand("SELECT DISTINCT RTRIM(" + usersyn.User_sAMAccount + ") AS sAMAccountName" +
                    ", RTRIM(" + usersyn.User_CN + ") AS CN" +
                    ", RTRIM(" + usersyn.User_Lname + ") AS sn" +
                    ", RTRIM(" + usersyn.User_Fname + ") AS givenName" +
                    ", RTRIM(" + usersyn.User_Mobile + ") AS homePhone" +
                    ", RTRIM(" + usersyn.User_State + ") AS st" +
                    ", RTRIM(" + usersyn.User_Address + ") AS streetAddress" +
                    //", RTRIM(" + usersyn.User_mail + ") AS mail" +
                    ", RTRIM(" + usersyn.User_city + ") AS l" +
                    ", RTRIM(" + usersyn.User_Zip + ") AS postalCode" +
                    ", RTRIM(" + usersyn.User_password + ") AS password" +
                    sqlForCustomFields +
                    " INTO " + sqlUsersTable + " FROM " + usersyn.User_dbTable, sqlConn);
            }
            else
            {
                sqlComm = new SqlCommand("SELECT DISTINCT RTRIM(" + usersyn.User_sAMAccount + ") AS sAMAccountName" +
                    ", RTRIM(" + usersyn.User_CN + ") AS CN" +
                    ", RTRIM(" + usersyn.User_Lname + ") AS sn" +
                    ", RTRIM(" + usersyn.User_Fname + ") AS givenName" +
                    ", RTRIM(" + usersyn.User_Mobile + ") AS homePhone" +
                    ", RTRIM(" + usersyn.User_State + ") AS st" +
                    ", RTRIM(" + usersyn.User_Address + ") AS streetAddress" +
                    //", RTRIM(" + usersyn.User_mail + ") AS mail" +
                    ", RTRIM(" + usersyn.User_city + ") AS l" +
                    ", RTRIM(" + usersyn.User_Zip + ") AS postalCode" +
                    ", RTRIM(" + usersyn.User_password + ") AS password" +
                    sqlForCustomFields +
                    " INTO " + sqlUsersTable + " FROM " + usersyn.User_dbTable +
                    " WHERE " + usersyn.User_where, sqlConn);
            }
            try
            {
                sqlComm.CommandTimeout = 360;
                sqlComm.ExecuteNonQuery();
                log.addTrn(sqlComm.CommandText.ToString(), "Query");

            }
            catch (Exception ex)
            {
                log.addTrn("Failed SQL command " + sqlComm.CommandText.ToString() + " error " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                throw;
            }
            if (usersyn.SearchScope == "Subtree")
            {
                scope = SearchScope.Subtree;
            }

            // go grab all the users from AD
            log.addTrn("Get users from active directory", "Info");
            adUsers = tools.EnumerateUsersInOUDataTable(usersyn.BaseUserOU, completeADKeys, adUsersTable, scope, log);
            if (adUsers.Rows.Count > 0)
            {
                // make the temp table for ou comparisons

                tools.Create_Table(adUsers, adUsersTable, sqlConn, log);

                // Quick check to stop adding if the update only box is checked
                if (usersyn.UpdateOnly == false)
                {
                    // compare query for the add/remove
                    log.addTrn("Query to find users to add", "Info");
                    add = tools.QueryNotExistsByPkey(sqlUsersTable, adUsersTable, sqlConn, "sAMAccountName", adUsers.Columns[0].ColumnName, log);

                    // actual add stuff
                    log.addTrn("Adding users", "Info");
                    tools.CreateUsersAccounts(usersyn.UserHoldingTank, add, usersyn.UniversalGroup, DC, usersyn, log);
                    add.Close();

                    sqlComm2 = new SqlCommand("select count(sAMAccountName) FROM " + sqlUsersTable, sqlConn);
                    sqlComm2.CommandTimeout = 360;
                    recordCount = sqlComm2.ExecuteScalar().ToString();
                    sqlComm2.Dispose();

                    if (recordCount != "0")
                    {
                        // compare query to find records which need deletion
                        log.addTrn("Query to find users to delete", "Info");
                        delete = tools.QueryNotExistsByPkey(adUsersTable, sqlUsersTable, sqlConn, usersyn.User_sAMAccount, completeADKeys[0].ToString(), log);

                        // delete users in AD
                        log.addTrn("Deleting users", "Info");
                        try
                        {
                            while (delete.Read())
                            {

                                tools.DeleteUserAccount((string)delete["distinguishedname"], log);
                                // log.addTrn("User removed ;" + (string)delete[adUpdateKeys[1].ToString()].ToString().Trim());
                            }
                        }
                        catch (Exception ex)
                        {
                            log.addTrn("Issue deleting AD users datareader is null " + ex.Message.ToString() + "\n" + ex.StackTrace.ToString(), "Error");
                        }
                        delete.Close();
                    }
                }

                // add the extra fields in form ".field ,"
                extraFieldsToReturn.Add(adUsersTable + ".distinguishedname ,");

                log.addTrn("Query to find users to update", "Info");
                update = tools.CheckUpdate(sqlUsersTable, adUsersTable, "sAMAccountName", "sAMAccountName", sqlUpdateKeys, adUpdateKeys, extraFieldsToReturn, 1, sqlConn, log);

                // update users in ad
                // last record which matches the primary key is the one which gets inserted into the database
                log.addTrn("Updating users", "Info");
                tools.UpdateUsers(update, DC, usersyn, log);

                update.Close();
            }
            // did not find any records in AD we are only adding users
            else
            {
                // and we are not updating users
                if (usersyn.UpdateOnly == false)
                {
                    // add the users without doing additional checks
                    tools.Create_Table(adUsers, adUsersTable, sqlConn, log);
                    log.addTrn("Query to find users to add", "Info");
                    add = tools.QueryNotExistsAllFields(sqlUsersTable, adUsersTable, sqlConn, "sAMAccountName", adUsers.Columns[0].ColumnName, log);
                    log.addTrn("Add all users", "Info");
                    tools.CreateUsersAccounts(usersyn.UserHoldingTank, add, usersyn.UniversalGroup, DC, usersyn, log);
                    add.Close();
                }
            }
            sqlConn.Close();
        }