Beispiel #1
0
 private void regrasToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         if (dataGridView.Rows.Count <= 1)
         {
             buttonRunQuery_Click(sender, e);
         }
         //else
         {
             Regras r = new Regras();
             r.RefreshFields(m_Fields);
             r.Show();
         }
     }
     catch
     {
     }
 }
Beispiel #2
0
        /// <summary>
        /// Atualiza o AD a partir das configurações especificadas. Método também acionado pelo thread m_AdUpdateThread.
        /// </summary>
        /// <param name="service">Determina execução em batch ou interativa (Verdadeiro = batch).</param>
        public void adUpdate(object service)
        {
            Boolean isService = (Boolean)service;

            if (!isService)
            {
                ControlSetEnabled(buttonUpdateAD, false);
                ControlSetEnabled(buttonRunQuery, false);
                ControlSetEnabled(dataGridView, false);
                StatusSetLabel("");
            }

            DateTime start = DateTime.Now;

            if (dataGridView.Rows.Count == 0 || dataGridView.Rows[0].Cells[0].Value == null)
            {
                buttonRunQuery_Click(this, new EventArgs());
            }

            Setup   setup = new Setup();
            Boolean log   = !String.IsNullOrEmpty(setup.textBoxLogFile.Text);

            StreamWriter swlog = null;

            if (log)
            {
                swlog = new StreamWriter(setup.textBoxLogFile.Text, true);
                swlog.WriteLine();
                swlog.WriteLine();
                swlog.WriteLine("*** Log Start: " + start.ToShortDateString() + " " + start.ToShortTimeString() + " ***");
            }
            String keyOrafield = "";
            String keyADfield  = "";

            foreach (DataGridViewRow datareader in dataGridView.Rows)
            {
                if (datareader.Cells[0].Value != null)
                {
                    if (datareader.Cells[0].Value.ToString() == setup.textBoxKeyField.Text)
                    {
                        keyOrafield = datareader.Cells[0].Value.ToString();
                        keyADfield  = datareader.Cells[1].Value.ToString();
                        break;
                    }
                }
            }

            if (String.IsNullOrEmpty(keyOrafield))
            {
                keyOrafield = setup.textBoxKeyField.Text;
                keyADfield  = "cn";
            }

            if (log)
            {
                swlog.WriteLine("keyOrafield: " + keyOrafield);
                swlog.WriteLine("keyADfield: " + keyADfield);
            }

            ADWork adw = new ADWork(setup.dataGridViewLdapStrings, setup.textBoxLdapUsername.Text, setup.textBoxLdapPassword.Text);
            Dictionary <String, Userdata> usuarios = new Dictionary <string, Userdata>();
            String OldOraHome = Environment.GetEnvironmentVariable("ORACLE_HOME");

            if (!String.IsNullOrEmpty(setup.textBoxOraHome.Text))
            {
                Environment.SetEnvironmentVariable("ORACLE_HOME", setup.textBoxOraHome.Text);
            }

            if (log)
            {
                swlog.WriteLine("OldOraHome: " + OldOraHome);
                swlog.WriteLine("ORACLE_HOME: " + setup.textBoxOraHome.Text);
            }
            try
            {
                OracleConnection conn = new OracleConnection(setup.ConnectionStringOracle);
                conn.Open();
                OracleCommand cmd = new OracleCommand();
                cmd.Connection  = conn;
                cmd.CommandText = "SELECT * from " + setup.textBoxOraView.Text + " order by " + keyOrafield + " asc";
                cmd.CommandType = CommandType.Text;
                OracleDataReader dr = cmd.ExecuteReader();
                usuarios.Clear();
                if (dr.HasRows)
                {
                    while (dr.Read())
                    {
                        Userdata us = new Userdata(dr, m_Fields);
                        try
                        {
                            if (!usuarios.ContainsKey(us.Attribute[keyOrafield]) && !String.IsNullOrEmpty(us.Attribute[keyOrafield]))
                            {
                                usuarios.Add(us.Attribute[keyOrafield], us);
                            }
                            else
                            {
                                Int32 countNulls1 = 0;
                                Int32 countNulls2 = 0;
                                foreach (KeyValuePair <String, String> s in usuarios[us.Attribute[keyOrafield]].Attribute)
                                {
                                    if (String.IsNullOrEmpty(s.Value.Trim()))
                                    {
                                        countNulls1++;
                                    }
                                    if (String.IsNullOrEmpty(us.Attribute[s.Key].Trim()))
                                    {
                                        countNulls2++;
                                    }
                                }
                                if (countNulls2 > countNulls1)
                                {
                                    usuarios[us.Attribute[keyOrafield]] = us;
                                }
                                if (log && !String.IsNullOrEmpty(us.Attribute[keyOrafield].Trim()))
                                {
                                    swlog.WriteLine("Tentando adicionar usuário já existente na lista: " + us.Attribute[keyOrafield]);
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }

                dr.Close();
                conn.Dispose();
            }
            catch (Exception e)
            {
                if (log)
                {
                    swlog.WriteLine("Erro ao abrir BD: " + e.Message);
                }
            }

            if (!String.IsNullOrEmpty(setup.textBoxOraHome.Text))
            {
                Environment.SetEnvironmentVariable("ORACLE_HOME", OldOraHome);
            }
            Dictionary <Tuple <String, String>, Tuple <String, String> > m_ChangeLog = new Dictionary <Tuple <string, string>, Tuple <string, string> >();
            Dictionary <String, Boolean> m_EnableLog = new Dictionary <String, Boolean>();

            ProgressSetMax(usuarios.Count * (dataGridView.Rows.Count - 1));
            ProgressReset();

            Regras regras = new Regras();

            regras.RefreshFields(m_Fields);
            foreach (KeyValuePair <String, Userdata> user in usuarios)
            {
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    if (!row.IsNewRow)
                    {
                        if (user.Value.Attribute.ContainsKey(row.Cells["CampoOrigem"].Value.ToString().ToUpper()))
                        {
                            try
                            {
                                String username = user.Key;
                                String field    = row.Cells["CampoDestino"].Value.ToString();
                                String value    = user.Value.Attribute[row.Cells["CampoOrigem"].Value.ToString().ToUpper()];
                                String domain   = setup.textBoxLdapDomain.Text;

                                StatusSetLabel("Atualizando " + username + ", campo " + field + " para " + value);
                                KeyValuePair <Tuple <String, String>, Tuple <String, String> > result;
                                Boolean allowBlankField = row.Cells["CampoOrigem"].Value.ToString() == "*BRANCO*";
                                result =
                                    adw.SetADInfo(user.Key, row.Cells["CampoDestino"].Value.ToString(),
                                                  user.Value.Attribute[row.Cells["CampoOrigem"].Value.ToString().ToUpper()],
                                                  setup.textBoxLdapDomain.Text, keyADfield, allowBlankField);

                                if (result.Key != null)
                                {
                                    if (!String.IsNullOrEmpty(result.Key.Item1) &&
                                        !String.IsNullOrEmpty(result.Key.Item2))
                                    {
                                        if (result.Value.Item1.Trim() != result.Value.Item2.Trim())
                                        {
                                            m_ChangeLog.Add(result.Key, result.Value);
                                            //Desativa usuário
                                            if (regras.rulesetDisableUser.checkBoxEnable.Checked)
                                            {
                                                Boolean disableUser = regras.rulesetDisableUser.MatchRule(user.Value);
                                                KeyValuePair <String, Boolean> result2 = adw.EnableUser(user.Key,
                                                                                                        row.Cells["CampoDestino"].Value.ToString(), !disableUser,
                                                                                                        setup.textBoxLdapDomain.Text, keyADfield);
                                                if (m_EnableLog.ContainsKey(result2.Key))
                                                {
                                                    m_EnableLog[result2.Key] = result2.Value;
                                                }
                                                else
                                                {
                                                    m_EnableLog.Add(result2.Key, result2.Value);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                if (log)
                                {
                                    swlog.WriteLine("Erro ao alterar usuário: " + e.Message);
                                }
                            }

                            ProgressPerformStep();
                        }
                    }
                }
            }
            if (setup.checkBoxSendMail.Checked && m_ChangeLog.Count > 0)
            {
                List <String> usuariosad  = new List <string>(adw.ListADInfo());
                List <String> usuariosdel = new List <string>();
                foreach (KeyValuePair <String, Userdata> us in usuarios)
                {
                    if (us.Value.ContainsKey("USRRED"))
                    {
                        if (!usuariosad.Contains(us.Value["USRRED"]))
                        {
                            usuariosdel.Add(us.Value["USRRED"]);
                        }
                    }
                }
                FileInfo file  = new FileInfo(Path.Combine(Path.GetTempPath(), "AlteraAD" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv"));
                FileInfo file2 = new FileInfo(Path.Combine(Path.GetTempPath(), "AtivaAD" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv"));

                SmtpClient client = new SmtpClient();
                client.Host = setup.textBoxSMTPServer.Text;
                client.Port = Int32.Parse(setup.textBoxSMTPPort.Text);
                if (setup.checkBoxSMTPAuth.Checked)
                {
                    client.Credentials = new NetworkCredential(setup.textBoxSMTPUser.Text,
                                                               setup.textBoxSMTPPassword.Text);
                }
                client.EnableSsl = setup.checkBoxSMTPSSL.Checked;
                MailMessage msg = new MailMessage();
                foreach (String to in setup.textBoxDstMailAddresses.Text.Split(','))
                {
                    try
                    {
                        msg.To.Add(new MailAddress(to.Trim()));
                    }
                    catch
                    {
                    }
                }
                try
                {
                    msg.From = new MailAddress(setup.textBoxSrcMailAddress.Text);
                }
                catch
                {
                }
                StreamWriter sw = new StreamWriter(file.FullName, false, Encoding.UTF8);
                sw.WriteLine("Usuario,Campo AD,Valor Original,Valor Novo");
                foreach (KeyValuePair <Tuple <String, String>, Tuple <String, String> > change in m_ChangeLog)
                {
                    sw.WriteLine("\"" + change.Key.Item1 + "\",\"" + change.Key.Item2 + "\",\"" + change.Value.Item1 + "\",\"" + change.Value.Item2 + "\"");
                    msg.Body += "Usuário: " + change.Key.Item1 + ", Campo AD: " + change.Key.Item2 + ", Valor Original: " + (String.IsNullOrEmpty(change.Value.Item1.Trim()) ? "Em Branco" : change.Value.Item1.Trim()) + ", Valor Novo: " + (String.IsNullOrEmpty(change.Value.Item2.Trim()) ? "Em Branco" : change.Value.Item2.Trim()) + ";\r\n";
                }
                sw.Close();
                msg.Body += "\r\n\r\n";
                sw        = new StreamWriter(file2.FullName, false, Encoding.UTF8);
                sw.WriteLine("Usuario,Status");
                foreach (KeyValuePair <String, Boolean> change in m_EnableLog)
                {
                    sw.WriteLine("\"" + change.Key + "\",\"" + (change.Value ? "Ativado" : "Desativado") + "\"");
                    msg.Body += "Usuário: " + change.Key + ", Status: " + (change.Value ? "Ativado" : "Desativado") + ";\r\n";
                }
                sw.Close();
                if (usuariosdel.Count > 0)
                {
                    msg.Body += "\r\n\r\n";
                    msg.Body += "Usuarios da view inexistentes no AD:\r\n";
                    foreach (String us in usuariosdel)
                    {
                        if (usuarios[us].ContainsKey("CODSIT") && usuarios[us].Attribute["CODSIT"] != "7")
                        {
                            msg.Body += us + "\r\n";
                        }
                    }
                }
                msg.Subject = "Log Alterações AD - " + DateTime.Now;

                try
                {
                    if (m_ChangeLog.Count > 0)
                    {
                        msg.Attachments.Add(new Attachment(file.FullName));
                    }
                    if (m_EnableLog.Count > 0)
                    {
                        msg.Attachments.Add(new Attachment(file2.FullName));
                    }
                    client.Send(msg);
                    file.Delete();
                    file2.Delete();
                }
                catch (Exception e)
                {
                    if (log)
                    {
                        swlog.WriteLine("Erro ao enviar e-mail para " + msg.To + ": " + e.Message);
                    }
                }
            }

            if (!isService)
            {
                String unit = "";
                Double val  = 0;
                if ((int)((DateTime.Now - start).TotalDays) > 0)
                {
                    val  = (DateTime.Now - start).TotalDays;
                    unit = "dias";
                }
                else if ((int)((DateTime.Now - start).TotalHours) > 0)
                {
                    val  = (DateTime.Now - start).TotalHours;
                    unit = "horas";
                }
                else if ((int)((DateTime.Now - start).TotalMinutes) > 0)
                {
                    val  = (DateTime.Now - start).TotalMinutes;
                    unit = "minutos";
                }
                else if ((int)((DateTime.Now - start).TotalSeconds) > 0)
                {
                    val  = (DateTime.Now - start).TotalSeconds;
                    unit = "segundos";
                }
                else if ((int)((DateTime.Now - start).TotalMilliseconds) > 0)
                {
                    val  = (DateTime.Now - start).TotalMilliseconds;
                    unit = "milissegundos";
                }
                try
                {
                    MessageBox.Show(this, "Atualização completa em " + Math.Round(val, 0) + " " + unit + ".", "Atualização completa", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch
                {
                }
                ControlSetEnabled(buttonUpdateAD, true);
                ControlSetEnabled(buttonRunQuery, true);
                ControlSetEnabled(dataGridView, true);
                ProgressReset();
                StatusSetLabel("");
                if (log)
                {
                    swlog.WriteLine("*** Log End: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + " ***");
                    swlog.Close();
                }
            }
        }