private void TmrServiceStatusCallback(Object o) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; db.ServiceStatus("Engine", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), total_registers = totalReg, atual_register = atualReg, percent = iPercent, errors = errors, new_users = newUsers, ignored = ignored, thread_count = (queueManager != null ? queueManager.ThreadCount : 0), queue_count = (queueManager != null ? queueManager.QueueCount : 0), last_status = last_status, queue_description = (queueManager != null ? queueManager.QueueCount2 : "") }), null); db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } }
private void LicTimer(Object oData) { using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword)) using (ServerKey2 sk = new ServerKey2(db2.Connection)) try { db2.openDB(); TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now; if (ts.TotalDays < 60) { db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Fatal, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri); } else if (ts.TotalDays < 180) { db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri); } else if (ts.TotalDays < 360) { db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri); } db2.closeDB(); } catch { } }
private void TmrServiceStatusCallback(Object o) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; Double percent = 0; percent = ((Double)(filesProcessed) / (Double)filesToProcess) * 100F; if (Double.IsNaN(percent) || Double.IsInfinity(percent)) { percent = 0; } db.ServiceStatus("Inbound", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), last_status = last_status, total_files = filesToProcess, processed_files = filesProcessed, percent = percent }), null); db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } }
private void TmrServiceStatusCallback(Object o) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; db.ServiceStatus("Report", JSON.Serialize2(new { host = Environment.MachineName, executing = executing }), null); db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } }
private void TmrServiceStatusCallback(Object o) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; db.ServiceStatus("WorkflowProcessor", JSON.Serialize2(new { host = Environment.MachineName, executing = executing, start_time = startTime.ToString("o"), last_status = last_status }), null); db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } }
private void ReportTimer(Object state) { if (executing) { return; } executing = true; //TextLog.Log("Report", "Starting report timer"); try { //IAMDeploy deploy = new IAMDeploy("report", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); //deploy.DeployAll(); IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); DataTable dtS = db.Select("select * from report_schedule"); try { //Processa um a um dos agendamentos foreach (DataRow dr in dtS.Rows) { CheckSchedule(db, (Int64)dr["id"], (Int64)dr["report_id"], dr["schedule"].ToString(), (DateTime)dr["next"]); } } catch (Exception ex) { TextLog.Log("Report", "\tError on report timer schedule: " + ex.Message); db.AddUserLog(LogKey.Report, null, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on report scheduler", ex.Message); } db.closeDB(); } catch (Exception ex1) { TextLog.Log("Report", "\tError on report timer: " + ex1.Message); } finally { //TextLog.Log("Report", "\tScheduled for new report process in 60 seconds"); //TextLog.Log("Report", "Finishing report timer"); executing = false; } }
public IAMDeploy(String moduleSender, String sqlServer, String sqlDb, String sqlUsername, String sqlPassword) { System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType()); basePath = Path.GetDirectoryName(asm.Location); this.executionLog = new StringBuilder(); this.moduleSender = moduleSender; db = new IAMDatabase(sqlServer, sqlDb, sqlUsername, sqlPassword); db.openDB(); outDirBase = new DirectoryInfo(Path.Combine(basePath, "Out")); if (!outDirBase.Exists) { outDirBase.Create(); } }
private void DispatcherTimer(Object state) { if (executing) { return; } executing = true; TextLog.Log("Dispatcher", "Starting dispatcher timer"); try { IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); DataTable dtS = db.Select("select * from vw_schedules order by context_id, [order]"); //Processa um a um dos agendamentos foreach (DataRow dr in dtS.Rows) { CheckSchedule(db, (Int64)dr["schedule_id"], (Int64)dr["resource_plugin_id"], (Int64)dr["resource_id"], dr["schedule"].ToString(), (DateTime)dr["next"]); } dtS.Clear(); dtS = null; db.closeDB(); db.Dispose(); db = null; } catch (Exception ex) { TextLog.Log("Dispatcher", "\tError on dispatcher timer " + ex.Message); } finally { TextLog.Log("Dispatcher", "Finishing dispatcher timer"); executing = false; } }
public IAMDeploy(String moduleSender, String connectionString, String basePath) { this.executionLog = new StringBuilder(); this.moduleSender = moduleSender; db = new IAMDatabase(connectionString); db.openDB(); DirectoryInfo tmp = new DirectoryInfo(basePath); if (tmp.Name.ToLower() == "out") { outDirBase = new DirectoryInfo(tmp.FullName); } else { outDirBase = new DirectoryInfo(Path.Combine(basePath, "Out")); } if (!outDirBase.Exists) { outDirBase.Create(); } }
private void WatchdogTimerCallback(Object o) { IAMDatabase db = null; try { //check if we need to stop any service db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; //Limpa status lixo db.ExecuteNonQuery("delete from service_status where last_status < DATEADD(day,-15,getdate())"); //seleciona os servicos comproblema ou parados DataTable dtServices = db.Select("select * from service_status where started_at is null or last_status < DATEADD(hour,-1,getdate()) or case when started_at is null then cast(getdate() as date) else cast(started_at as date) end <> cast(getdate() as date)"); if (dtServices != null && dtServices.Rows.Count > 0) { foreach (DataRow dr in dtServices.Rows) { String svcName = dr["service_name"].ToString(); if (svcName.ToLower().IndexOf("watchdog") >= 0) { continue; } TextLog.Log("Watchdog", "Killing service '" + svcName + "'"); Killall(svcName); Killall("IAM" + svcName); } } db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } try { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in ServiceController.GetServices()) { try { switch (service.ServiceName.ToLower()) { case "iambackup": case "iamdispatcher": case "iamengine": case "iaminbound": case "iamreport": case "iamproxy": case "iammultiproxy": case "iammessenger": case "iamworkflowprocessor": StartupState stMode = StartMode(service.ServiceName); switch (stMode) { case StartupState.Automatic: if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending))) { TextLog.Log("Watchdog", "Starting service '" + service.DisplayName + "'"); service.Start(); try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; db.AddUserLog(LogKey.Watchdog, null, "Watchdog", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Starting service '" + service.DisplayName + "'"); db.closeDB(); } catch { } finally { if (db != null) { db.Dispose(); } db = null; } } break; default: TextLog.Log("Watchdog", "Unknow action for service start mode '" + stMode.ToString() + "' for service '" + service.DisplayName + "'"); break; } break; } } catch (Exception ex) { TextLog.Log("Watchdog", "Erro ao processar o controle do serviço '" + service.DisplayName + "': " + ex.Message); } } } catch (Exception ex) { TextLog.Log("Watchdog", "Erro ao processar o controle dos serviços: " + ex.Message); } }
private void startInstall() { Application.DoEvents(); Boolean success = false; txtCheckConfig.Text = "Iniciando instalação" + Environment.NewLine; IAMDatabase db = null; try { txtCheckConfig.Text += "Definindo variáveis de ambiente: "; Application.DoEvents(); DirectoryInfo appDir = new DirectoryInfo(Environment.CurrentDirectory); try { appDir = new DirectoryInfo(args[0]); } catch { } txtCheckConfig.Text += "OK" + Environment.NewLine; txtCheckConfig.Text += "\tDiretório de execução: " + appDir.FullName + Environment.NewLine; Application.DoEvents(); txtCheckConfig.Text += "Conectando no banco de dados: "; Application.DoEvents(); if (txtDatabase.Text.Trim().ToLower() == "master") { throw new Exception("Não pode ser utilizado a base de dados Master"); } db = new IAMDatabase(txtDbServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text); db.openDB(); txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Estrutura de dados txtCheckConfig.Text += "Criando estrutura de dados: "; Application.DoEvents(); //Verifica se a base de dados está sendo utilizada Int64 tableCount = db.ExecuteScalar <Int64>("SELECT cast(COUNT(*) as bigint) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo'"); if (tableCount > 0) { if (MessageBox.Show("A base de dados " + txtDatabase.Text + " contém " + tableCount + " tabelas e aparentemente está sendo utilizado por outra aplicação.\r\n\r\nDeseja continuar a instalação nesta base?", "Deseja continuar a instalação?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.No) { throw new Exception("Cancelado pelo usuário"); } } Object trans = db.BeginTransaction(); try { using (IAMDbInstall dbCreate = new IAMDbInstall(db)) dbCreate.Create(trans); db.Commit(); } catch (Exception ex) { db.Rollback(); throw ex; } txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Verificvando existência de outras empresas txtCheckConfig.Text += "Verificando configuração existente: "; Int64 enterpriseCount = db.ExecuteScalar <Int64>("SELECT cast(COUNT(*) as bigint) FROM enterprise"); if (enterpriseCount > 0) { throw new Exception("Base de dados com informações de outras empresas."); } txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Atualizando Base de dados txtCheckConfig.Text += "Atualizando base de dados: "; try { using (IAM.GlobalDefs.Update.IAMDbUpdate updt = new IAM.GlobalDefs.Update.IAMDbUpdate(txtDbServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text)) updt.Update(); txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); } catch (Exception ex) { throw new Exception("Falha ao atualizar o banco de dados: " + ex.Message); } //############################## //Finalizando instalação txtCheckConfig.Text += "Configurando diretórios: "; Application.DoEvents(); db.ExecuteNonQuery("delete from server_config where data_name = 'pluginFolder'; insert into server_config (data_name, data_value) values ('pluginFolder','" + Path.Combine(appDir.FullName, "IAMServer\\Plugins") + "')"); db.ExecuteNonQuery("delete from server_config where data_name = 'inboundFiles'; insert into server_config (data_name, data_value) values ('inboundFiles','" + Path.Combine(appDir.FullName, "IAMServer\\In") + "')"); db.ExecuteNonQuery("delete from server_config where data_name = 'outboundFiles'; insert into server_config (data_name, data_value) values ('outboundFiles','" + Path.Combine(appDir.FullName, "IAMServer\\Out") + "')"); txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Certificados e chaves de instalação txtCheckConfig.Text += "Gerando chave de instalação: "; Application.DoEvents(); using (ServerKey2 sk = new ServerKey2(db.Connection)) sk.RenewCert(db.Connection); txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Criando a empresa txtCheckConfig.Text += "Criando empresa: "; Application.DoEvents(); Creator creator = new Creator(db, txtName.Text.Trim(), txtUri.Text.Trim(), "pt-BR"); creator.BuildCertificates(); creator.Commit(); txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); //############################## //Criando a empresa txtCheckConfig.Text += "Criando arquivos de configuração: "; Application.DoEvents(); FileInfo serverFile = new FileInfo(Path.Combine(appDir.FullName, "IAMServer\\server.conf")); if (serverFile.Exists) { serverFile.Delete(); } WriteToFile(serverFile, "sqlserver=" + txtDbServer.Text.Trim() + Environment.NewLine); WriteToFile(serverFile, "sqldb=" + txtDatabase.Text.Trim() + Environment.NewLine); WriteToFile(serverFile, "sqlusername="******"sqlpassword="******"enginemaxthreads=30" + Environment.NewLine); //Web.config FileInfo webConfigFile = new FileInfo(Path.Combine(appDir.FullName, "IAMServer\\web\\web.config")); if (webConfigFile.Exists) { XmlDocument doc = new XmlDocument(); doc.Load(webConfigFile.FullName); //get root element System.Xml.XmlElement Root = doc.DocumentElement; XmlNode connectionStringsNode = Root["connectionStrings"]; foreach (XmlNode cs in connectionStringsNode.ChildNodes) { Boolean update = false; foreach (XmlAttribute att in cs.Attributes) { if (att.Name.ToLower() == "name" && att.Value.ToLower() == "iamdatabase") { update = true; } } if (update) { foreach (XmlAttribute att in cs.Attributes) { if (att.Name.ToLower() == "connectionstring") { att.Value = db.ConnectionString; } } } } doc.Save(webConfigFile.FullName); doc = null; } txtCheckConfig.Text += "OK" + Environment.NewLine; Application.DoEvents(); success = true; } catch (Exception ex) { success = false; txtCheckConfig.Text += "ERRO" + Environment.NewLine; txtCheckConfig.Text += "\t" + ex.Message + Environment.NewLine; Application.DoEvents(); return; } finally { if (db != null) { db.Dispose(); } if (!success) { txtCheckConfig.Text += Environment.NewLine + "PROCESSO ABORTADO!!!" + Environment.NewLine; btnBack.Enabled = true; btnBack.Visible = true; btnNext.Text = "&Avançar >"; btnCancel.Enabled = true; } else { txtCheckConfig.Text += Environment.NewLine + "Instalação realizada com sucesso." + Environment.NewLine; btnCancel.Text = "Finalizar"; btnCancel.Enabled = true; btnNext.Visible = false; step = WizardStep.Installed; } //Localiza e remove todos os arquivos .cer e .pfx deste diretório try { List <FileInfo> files = new List <FileInfo>(); try { files.AddRange(new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.cer")); files.AddRange(new DirectoryInfo(Environment.CurrentDirectory).GetFiles("*.pfx")); } catch { } try { System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType()); files.AddRange(new DirectoryInfo(Path.GetDirectoryName(asm.Location)).GetFiles("*.cer")); files.AddRange(new DirectoryInfo(Path.GetDirectoryName(asm.Location)).GetFiles("*.pfx")); } catch { } foreach (FileInfo f in files) { try { f.Delete(); } catch { } } } catch { } } }
private Boolean TestConn() { //return true; this.Cursor = Cursors.WaitCursor; try { if (txtDbServer.Text.Trim() == "") { MessageBox.Show("Favor preencher o endereço do banco de dados.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); txtDbServer.Focus(); return(false); } if (txtDatabase.Text.Trim() == "") { MessageBox.Show("Favor preencher a base de dados.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); txtDatabase.Focus(); return(false); } if (txtUsername.Text.Trim() == "") { MessageBox.Show("Favor preencher o nome do usuário.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); txtUsername.Focus(); return(false); } if (txtPassword.Text.Trim() == "") { MessageBox.Show("Favor preencher a senha.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); txtPassword.Focus(); return(false); } IAMDatabase db = null; try { if (txtDatabase.Text.Trim().ToLower() == "master") { throw new Exception("Não pode ser utilizado a base de dados Master"); } db = new IAMDatabase(txtDbServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text); db.openDB(); } catch (Exception ex) { MessageBox.Show("Erro ao conectar na base de dados.\r\n\r\n" + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } finally { if (db != null) { db.Dispose(); } } return(true); } finally { this.Cursor = Cursors.Default; } }
protected override void OnStart(string[] args) { /************* * Carrega configurações */ localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } Int32 cnt = 0; Int32 stepWait = 15000; while (cnt <= 10) { try { IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.ServiceStart("Engine", null); db.closeDB(); break; } catch (Exception ex) { if (cnt < 10) { TextLog.Log("Engine", "Falha ao acessar o banco de dados: " + ex.Message); Thread.Sleep(stepWait); stepWait = stepWait * 2; cnt++; } else { StopOnError("Falha ao acessar o banco de dados", ex); } } } /************* * Gera os certificados do servidor * Verifica se o certificade está próximo de vencer */ IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db2.openDB(); ServerKey2 sk = new ServerKey2(db2.Connection); TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now; if (ts.TotalDays < 360) { //Inicia o timer que ficará gerando evento licTimer = new Timer(new TimerCallback(LicTimer), null, 200, 86400000); //a cada 24 Horas caso este processo não for reiniciado } db2.closeDB(); intoTimer = new Timer(new TimerCallback(InfoTimer), null, 200, 900); //a cada 15 minutos /************* * Inicia as classes de processamento */ RegistryImporter imp = new RegistryImporter(localConfig); imp.Start(); TimeAccessControl acl = new TimeAccessControl(localConfig); acl.Start(); }
protected override void OnStart(string[] args) { /************* * Carrega configurações */ System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType()); basePath = Path.GetDirectoryName(asm.Location); localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } Int32 cnt = 0; Int32 stepWait = 15000; while (cnt <= 10) { try { IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.ServiceStart("Report", null); db.closeDB(); break; } catch (Exception ex) { if (cnt < 10) { TextLog.Log("Report", "Falha ao acessar o banco de dados: " + ex.Message); Thread.Sleep(stepWait); stepWait = stepWait * 2; cnt++; } else { StopOnError("Falha ao acessar o banco de dados", ex); } } } /************* * Inicia timer que processa os arquivos */ reportTimer = new Timer(new TimerCallback(ReportTimer), null, 1000, 60000); statusTimer = new Timer(new TimerCallback(TmrServiceStatusCallback), null, 100, 10000); }
private void DeployNowTimer(Object state) { if (executing2) { return; } executing2 = true; try { IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); DataTable dtS = db.Select("select entity_id, MAX(date) [date] from deploy_now with(nolock) where date < GETDATE() group by entity_id order by MAX(date)"); if ((dtS == null) || (dtS.Rows.Count == 0)) { return; } TextLog.Log("Dispatcher", "Starting deploy now timer"); //Processa um a um dos agendamentos foreach (DataRow dr in dtS.Rows) { try { Int32 count = 0; using (IAMDeploy deploy = new IAMDeploy("Dispatcher", localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword)) { count = deploy.DeployOne((Int64)dr["entity_id"]); if (count == 0) { db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: no package sent", deploy.ExecutionLog); } } db.ExecuteNonQuery("delete from deploy_now where entity_id = " + dr["entity_id"], CommandType.Text, null); } catch (Exception ex2) { db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Error, 0, 0, 0, 0, 0, (Int64)dr["entity_id"], 0, "Erro on deploy now user: "******"Dispatcher", "\tError on deploy now timer " + ex.Message + ex.StackTrace); } finally { TextLog.Log("Dispatcher", "Finishing deploy now timer"); executing2 = false; } }
static void Main(string[] args) { ServerLocalConfig localConfig; /************* * Carrega configurações */ localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } using (IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword)) { try { db.openDB(); } catch (Exception ex) { StopOnError("Erro on acess database ", ex); } try { ServerKey2 sk = new ServerKey2(db.Connection); sk.RenewCert(db.Connection); Console.WriteLine("Renewed certificate successfully"); TextLog.Log("RenewServerCert", "Renewed certificate successfully"); } catch (Exception ex) { UnhandledException.WriteEvent(null, ex, false); StopOnError("Error on renew certificate ", ex); } } Console.WriteLine("Pressione ENTER para finalizar"); Console.ReadLine(); }
private void MessengerTimer(Object state) { if (executing) { return; } executing = true; startTime = DateTime.Now; try { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 900; //Lista todas as mensagens pendêntes de entrega //Status: W = Waiting, PE = Protocol error //DataTable dtMessages = db.ExecuteDataTable("select m.*, e.last_uri from [st_messages] m with(nolock) inner join enterprise e with(nolock) on e.id = m.enterprise_id where status in ('W','PE')"); DataTable dtMessages = db.ExecuteDataTable("select m.id from [st_messages] m with(nolock) where status in ('W','PE')"); if ((dtMessages != null) && (dtMessages.Rows.Count > 0)) { try { TextLog.Log("Messenger", "Starting message timer"); foreach (DataRow dr in dtMessages.Rows) { try { using (MessageSender sender = new MessageSender(db, (Int64)dr["id"])) using (ServerDBConfig conf = new ServerDBConfig(db.Connection, true)) sender.Send(conf.GetItem("mailFrom"), conf.GetItem("smtpServer"), conf.GetItem("username"), conf.GetItem("password")); } catch (Exception ex) { DbParameterCollection par = new DbParameterCollection(); par.Add("@message_id", typeof(Int64)).Value = (Int64)dr["id"]; par.Add("@status", typeof(String)).Value = "Erro no envio"; par.Add("@description", typeof(String)).Value = ex.Message; db.ExecuteNonQuery("UPDATE st_messages SET [status] = 'E' WHERE id = @message_id; INSERT INTO st_messages_status (message_id,date,error,status,description) VALUES(@message_id,getdate(),1,@status,@description);", par); } } } finally { if (db != null) { db.Dispose(); } TextLog.Log("Messenger", "Finishing message timer"); } } db.closeDB(); } finally { if (db != null) { db.Dispose(); } } } catch (Exception ex) { TextLog.Log("Messenger", "Error on message timer " + ex.Message); } finally { executing = false; last_status = ""; startTime = new DateTime(1970, 1, 1); } }
protected void Page_Load(object sender, EventArgs e) { WebJsonResponse contentRet = null; String action = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["action"])) { action = (String)RouteData.Values["action"]; } Int64 pluginId = 0; if ((action != "add_license") && (action != "upload_item_template") && (action != "upload") && (action != "add_new")) { try { pluginId = Int64.Parse((String)RouteData.Values["id"]); if (pluginId < 0) { pluginId = 0; } } catch { } if (pluginId == 0) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("plugin_not_found"), 3000, true); action = ""; } } Int64 enterpriseId = 0; if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id; } String rData = ""; //SqlConnection //conn = DB.GetConnection(); String jData = ""; try { switch (action) { case "upload_item_template": String id = Request.Form["id"]; String file = Request.Form["file"]; String tSize = Request.Form["size"]; if (String.IsNullOrEmpty(id)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(file)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else if (String.IsNullOrEmpty(tSize)) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("role_not_found"), 3000, true); } else { String userHtmlTemplate = "<div id=\"file{0}\" data-id=\"{0}\" data-name=\"{1}\" class=\"app-list-item file-item\">"; userHtmlTemplate += "<div class=\"form-content\"><input type=\"hidden\" name=\"file_name_{0}\" value=\"{1}\">"; userHtmlTemplate += "<input type=\"hidden\" name=\"{1}\" value=\"{0}\"></div>"; userHtmlTemplate += "<table>"; userHtmlTemplate += " <tbody>"; userHtmlTemplate += " <tr>"; userHtmlTemplate += " <td class=\"colfull\">"; userHtmlTemplate += " <div class=\"title\"><span class=\"name\" id=\"file_name_{0}\" data-id=\"{0}\">{1}</span><div class=\"clear-block\"></div></div>"; userHtmlTemplate += " <div class=\"description\">{2}</div></div>"; userHtmlTemplate += " </td>"; userHtmlTemplate += " </tr>"; userHtmlTemplate += " </tbody>"; userHtmlTemplate += "</table></div>"; String infoTemplate = "<div class=\"line\">"; infoTemplate += "<label>{1}</label>"; infoTemplate += "<span class=\"no-edit {0}\">{2}</span></div>"; String desc = ""; desc += String.Format(infoTemplate, "status", "Status", "Enviando"); String tHtml = String.Format(userHtmlTemplate, id, file, desc); contentRet = new WebJsonResponse("#" + id, tHtml); } break; case "upload": MultipartFormDataParser mp = new MultipartFormDataParser(Request.InputStream); List <String> fls = new List <String>(); String infoTemplate2 = "<div class=\"line\">"; infoTemplate2 += "<label>{1}</label>"; infoTemplate2 += "<span class=\"no-edit {0}\">{2}</span></div>"; // Loop through all the files foreach (FilePart mpF in mp.Files) { try { String d = ""; try { Byte[] rawAssembly = new Byte[mpF.Data.Length]; mpF.Data.Read(rawAssembly, 0, rawAssembly.Length); IAMKeyData memKey = null; String fileData = Convert.ToBase64String(rawAssembly); try { memKey = IAMKey.ExtractFromCert(fileData); } catch { } if (memKey != null) { d += String.Format(infoTemplate2, "", "Nome", mpF.FileName); d += String.Format(infoTemplate2, "", "Tamanho", mpF.Data.Length + " bytes"); Boolean useLicense = false; if (memKey.IsServerKey) { d += String.Format(infoTemplate2, "", "Definitiva?", (memKey.IsTemp ? MessageResource.GetMessage("no") : MessageResource.GetMessage("yes"))); if (memKey.IsTemp) { d += String.Format(infoTemplate2, "", "Expiração", (memKey.TempDate.HasValue ? MessageResource.FormatDate(memKey.TempDate.Value, true) : "não definido")); } d += String.Format(infoTemplate2, "", "Entidades", (memKey.NumLic == 0 ? MessageResource.GetMessage("unlimited") : memKey.NumLic.ToString())); String installKey = ""; using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection())) installKey = sk.ServerInstallationKey.AbsoluteUri; d += String.Format(infoTemplate2, "", "Chave de instalação", (memKey.InstallKey == installKey ? "Válida" : "Inválida")); if (memKey.InstallKey == installKey) { if (!memKey.IsTemp) { useLicense = true; } else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0)) { useLicense = true; } } } else { d += String.Format(infoTemplate2, "", "Status", "Licença inválida"); } if (useLicense) { d += "<input type=\"hidden\" name=\"key_data\" value=\"" + fileData + "\">"; } /* * if (p2.Count > 0) * d += String.Format(infoTemplate2, "", "Plugins", String.Join(", ", p2)); * else * d += String.Format(infoTemplate2, "", "Plugins", "Nenhum plugin encontrado no arquivo enviado"); * * if (p2.Count > 0) * { * using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) * { * DataTable dt = database.Select("select * from plugin where enterprise_id in (0," + enterpriseId + ") and (assembly in ('" + String.Join("','", p2) + "') or uri in ('" + String.Join("','", p2Uri) + "'))"); * * if (dt.Rows.Count > 0) * throw new Exception("Plugin/uri ja cadastrado no sistema"); * } * * FileInfo newFile = new FileInfo(Path.Combine(pluginsDir.FullName, mpF.FileName)); * if (newFile.Exists) * newFile.Delete(); * File.WriteAllBytes(newFile.FullName, rawAssembly); * }*/ } else { d += String.Format(infoTemplate2, "", "Status", "Arquivo válido"); } } catch (Exception ex) { d = String.Format(infoTemplate2, "", "Status", "Erro ao realizar o upload"); d += String.Format(infoTemplate2, "", "Informação do erro", ex.Message); } fls.Add(JSON.Serialize2(new { name = mpF.FileName, html = d })); } catch { fls.Add(JSON.Serialize2(new { name = mpF.FileName, error = "Erro enviando o arquivo" })); } } Retorno.Controls.Add(new LiteralControl("{\"files\": [" + String.Join(",", fls) + "]}")); contentRet = null; break; case "add_new": String key_data = ""; key_data = Request.Form["key_data"]; if (!String.IsNullOrEmpty(key_data)) { IAMKeyData memKey = null; try { memKey = IAMKey.ExtractFromCert(key_data); } catch { } if (memKey != null) { Boolean useLicense = false; if (memKey.IsServerKey) { String installKey = ""; using (IAM.Config.ServerKey2 sk = new IAM.Config.ServerKey2(IAMDatabase.GetWebConnection())) installKey = sk.ServerInstallationKey.AbsoluteUri; if (memKey.InstallKey == installKey) { if (!memKey.IsTemp) { useLicense = true; } else if ((memKey.IsTemp) && (memKey.TempDate.Value.CompareTo(DateTime.Now) > 0)) { useLicense = true; } } if (useLicense) { using (IAMDatabase db = new IAMDatabase(IAMDatabase.GetWebConnectionString())) { db.openDB(); Object trans = db.BeginTransaction(); try { db.ExecuteNonQuery("delete from license where enterprise_id = " + enterpriseId, CommandType.Text, null, trans); using (DbParameterCollection par = new DbParameterCollection()) { par.Add("@enterprise_id", typeof(Int64)).Value = enterpriseId; par.Add("@license", typeof(String)).Value = key_data; db.ExecuteNonQuery("insert into license (enterprise_id,license_data) VALUES(@enterprise_id,@license)", CommandType.Text, par, trans); } db.Commit(); contentRet = new WebJsonResponse(Session["ApplicationVirtualPath"] + "admin/license/"); } catch (Exception ex) { db.Rollback(); contentRet = new WebJsonResponse("", "Falha ao aplicar a licença", 5000, true); } } } else { contentRet = new WebJsonResponse("", "Licença inválida", 5000, true); } } else { contentRet = new WebJsonResponse("", "Licença inválida", 5000, true); } } } else { contentRet = new WebJsonResponse("", "Nenhuma licença válida encontrada para aplicar", 5000, true); } break; } } catch (Exception ex) { contentRet = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } finally { } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }
protected override void OnStart(string[] args) { /************* * Carrega configurações */ System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(this.GetType()); basePath = Path.GetDirectoryName(asm.Location); localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } Int32 cnt = 0; Int32 stepWait = 15000; while (cnt <= 10) { try { IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.ServiceStart("Inbound", null); //Recria a tabela temporária db.ExecuteNonQuery(@" IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'collector_imports_temp')) BEGIN DROP TABLE [collector_imports_temp]; END", System.Data.CommandType.Text, null, null); db.ExecuteNonQuery(@" IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'collector_imports_temp')) BEGIN select top 0 * into [collector_imports_temp] from [collector_imports]; END", System.Data.CommandType.Text, null, null); db.closeDB(); break; } catch (Exception ex) { if (cnt < 10) { TextLog.Log("Inbound", "Falha ao acessar o banco de dados: " + ex.Message); Thread.Sleep(stepWait); stepWait = stepWait * 2; cnt++; } else { StopOnError("Falha ao acessar o banco de dados", ex); } } } /************* * Inicia processo de verificação/atualização da base de dados */ try { using (IAM.GlobalDefs.Update.IAMDbUpdate updt = new GlobalDefs.Update.IAMDbUpdate(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword)) updt.Update(); } catch (Exception ex) { StopOnError("Falha ao atualizar o banco de dados", ex); } /************* * Inicia timer que processa os arquivos */ Int32 maxThreads = 1; if (maxThreads > 0) { maxThreads = localConfig.EngineMaxThreads; } this.fileQueue = new QueueManager <FileInfo>(maxThreads, ProcQueue); this.fileQueue.Start(); inboundTimer = new Timer(new TimerCallback(InboundTimer), null, 1000, 60000); statusTimer = new Timer(new TimerCallback(TmrServiceStatusCallback), null, 100, 10000); }
private void ProcQueue(FileInfo f, Object oStarter) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 900; Boolean rebuildIndex = false; String type = ""; type = ""; JSONRequest req = null; try { using (FileStream fs = f.OpenRead()) req = JSON.GetRequest(fs); if ((req.host == null) || (req.host == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'host' is empty on " + f.Name); return; } if ((req.enterpriseid == null) || (req.enterpriseid == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is empty on " + f.Name); return; } try { Int64 tst = Int64.Parse(req.enterpriseid); } catch { if ((req.enterpriseid == null) || (req.enterpriseid == "")) { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Paramter 'enterpriseid' is not Int64 " + f.Name); return; } } ProxyConfig config = new ProxyConfig(true); config.GetDBCertConfig(db.Connection, Int64.Parse(req.enterpriseid), req.host); if (config.fqdn != null) //Encontrou o proxy { JsonGeneric jData = new JsonGeneric(); try { String certPass = CATools.SHA1Checksum(Encoding.UTF8.GetBytes(config.fqdn)); using (CryptApi cApi = CryptApi.ParsePackage(CATools.LoadCert(Convert.FromBase64String(config.server_pkcs12_cert), certPass), Convert.FromBase64String(req.data))) jData.FromJsonBytes(cApi.clearData); } catch (Exception ex) { jData = null; db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message); } if (jData == null) { return; } type = jData.function.ToLower(); switch (type) { case "processimport-disabled": rebuildIndex = true; //ImportRegisters(config, jData, f, req, db); f.Delete(); break; case "processimportv2": rebuildIndex = true; last_status = "Executando importação de registros"; ImportRegistersV2(config, jData, f, req, db); f.Delete(); break; case "processstructimport": last_status = "Executando importação de registros de estrutura"; ImportRegistersStruct(config, jData, f, req, db); f.Delete(); break; case "notify": last_status = "Executando importação de notificações"; ImportNotify(config, jData, f, req, db); f.Delete(); break; case "deleted": last_status = "Executando importação de exclusões"; ImportDelete(config, jData, f, req, db); f.Delete(); break; case "logrecords": last_status = "Executando importação de logs"; ImportLogs(config, jData, f, req, db); f.Delete(); //f.MoveTo(f.FullName + ".imported"); break; case "packagetrack": last_status = "Executando importação de track dos pacotes"; ImportPackageTrack(config, jData, f, req, db); f.Delete(); //f.MoveTo(f.FullName + ".imported"); break; default: db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, config.proxyID, 0, 0, 0, 0, 0, 0, "Invalid jData function '" + jData.function + "'"); break; } } else { db.AddUserLog(LogKey.Inbound, null, "Inbound", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host); } config = null; } catch (Exception ex) { TextLog.Log("Inbound", "Erro on process file '" + f.Name + "' (" + type + "): " + ex.Message); db.AddUserLog(LogKey.Import, null, "Inbound", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Erro processing file '" + f.Name + "' (" + type + "): " + ex.Message); } finally { last_status = ""; req = null; filesProcessed++; } /* * if (rebuildIndex) * { * db.Timeout = 900; * last_status = "Reindexando registros"; * db.ExecuteNonQuery("sp_reindex_imports", CommandType.StoredProcedure, null); * }*/ } catch (Exception ex) { TextLog.Log("Inbound", "Error importing file (" + f.Name + ")" + ex.Message); } finally { if (db != null) { db.closeDB(); } } }
private void TmrCallback(Object sender) { if (executing) { return; } executing = true; TextLog.Log("Engine", "Time access control", "Starting processor timer"); IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; //Seleciona as entidades/identidades vinculadas a um resource x plugin que tenha controle de acesso por horário DataTable dtRegs = db.Select("select i.id, i.temp_locked, e.id entity_id, r.name resource_name from entity e with(nolock) inner join [identity] i with(nolock) on e.id = i.entity_id inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id and i.resource_plugin_id = rp.id inner join resource r with(nolock) on rp.resource_id = r.id inner join resource_plugin_role_time_acl acl with(nolock) on acl.resource_plugin_id = rp.id inner join role r1 with(nolock) on r1.id = acl.role_id inner join identity_role ir with(nolock) on ir.identity_id = i.id and ir.role_id = r1.id where r.enabled = 1 and rp.enabled = 1 group by i.id, i.temp_locked, e.id, r.name"); if ((dtRegs == null) || (dtRegs.Rows.Count == 0)) { TextLog.Log("Engine", "Time access control", "\t0 registers to process"); return; } foreach (DataRow dr in dtRegs.Rows) { try { using (EntityTimeControl eAcl = new EntityTimeControl(db, (Int64)dr["id"])) { StringBuilder tLog = new StringBuilder(); EntityTimeControl.ProccessLog log = new EntityTimeControl.ProccessLog(delegate(String text) { tLog.AppendLine(text); #if DEBUG TextLog.Log("Engine", "Time access control", text); #endif }); eAcl.OnLog += log; eAcl.Process((Boolean)dr["temp_locked"]); eAcl.OnLog -= log; if ((Boolean)dr["temp_locked"] != eAcl.Locked) { db.AddUserLog((eAcl.Locked ? LogKey.User_TempLocked : LogKey.User_TempUnlocked), null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, Int64.Parse(dr["entity_id"].ToString()), Int64.Parse(dr["id"].ToString()), "Identity of resource " + dr["resource_name"] + (eAcl.Locked ? " locked by the time profile" : " unlocked by the time profile"), tLog.ToString()); } tLog.Clear(); tLog = null; } } catch (Exception ex) { TextLog.Log("Engine", "Time access control", "\tError on time control processor " + ex.Message); } } Console.WriteLine(""); } catch (Exception ex) { db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on time control processor", ex.Message); TextLog.Log("Engine", "Time access control", "\tError on time control processor timer " + ex.Message); } finally { TextLog.Log("Engine", "Time access control", "Finishing processor timer"); if (db != null) { db.closeDB(); } executing = false; } }
private void BuildBackup() { StringBuilder bkpLog = new StringBuilder(); IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); bkpLog.AppendLine("Listando tabelas da base de dados..."); DataTable dtS = db.Select("select TABLE_NAME from information_schema.tables where TABLE_TYPE = 'BASE TABLE' order by TABLE_NAME"); if ((dtS == null) || (dtS.Rows.Count == 0)) { bkpLog.AppendLine("Listagem de tabelas vazia ou nula"); throw new Exception("Table list is null or empty"); } bkpLog.AppendLine(dtS.Rows.Count + " tabelas"); FileInfo bkpFile = new FileInfo(Path.Combine(Path.Combine(basePath, "Backup"), "bkp-" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ".iambkp")); if (!bkpFile.Directory.Exists) { bkpFile.Directory.Create(); } bkpLog.AppendLine("Criando arquivo de backup: " + bkpFile.FullName); using (SqliteBase exportDB = new SqliteBase(bkpFile)) { foreach (DataRow drSrc in dtS.Rows) { String tableName = drSrc["TABLE_NAME"].ToString(); bkpLog.AppendLine("Exportando tabela: " + tableName); Console.WriteLine(tableName); DataTable dtSchema = db.GetSchema(tableName); StringBuilder createCmd = new StringBuilder(); createCmd.AppendLine("DROP TABLE IF EXISTS [" + tableName.ToLower() + "];"); /* * CREATE TABLE [Events] ( * id INTEGER PRIMARY KEY AUTOINCREMENT, * test_id TEXT NOT NULL, * date datetime not null DEFAULT (datetime('now','localtime')), * event_text TEXT NULL * );*/ List <String> columns = new List <string>(); bkpLog.AppendLine("Criando estrutura da tabela"); try { foreach (DataColumn dc in dtSchema.Columns) { if (dc.DataType.Equals(typeof(Int32)) || dc.DataType.Equals(typeof(Int64))) { columns.Add("[" + dc.ColumnName + "] INTEGER NULL"); } else if (dc.DataType.Equals(typeof(DateTime))) { columns.Add("[" + dc.ColumnName + "] datetime NULL"); } else { columns.Add("[" + dc.ColumnName + "] TEXT NULL"); } } } catch (Exception ex) { bkpLog.AppendLine("Erro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao listar as colunas da tabela '" + tableName + "': " + ex.Message); throw ex; } try { createCmd.AppendLine("CREATE TABLE [" + tableName.ToLower() + "] ("); createCmd.AppendLine(String.Join(", " + Environment.NewLine, columns)); createCmd.AppendLine(");"); exportDB.ExecuteNonQuery(createCmd.ToString()); } catch (Exception ex) { bkpLog.AppendLine("Erro ao criando tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro ao criando tabela '" + tableName + "': " + ex.Message); throw ex; } //Copiando dados das tabelas try { bkpLog.AppendLine("Copiando dados"); if (tableName.ToLower() == "logs") { DataTable dtSrcData = db.ExecuteDataTable("select l.* from [logs] l with(nolock) inner join [entity_timeline] et with(nolock) on et.log_id = l.id"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else if (tableName.ToLower() == "entity") { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } else { DataTable dtSrcData = db.ExecuteDataTable("select * from [" + tableName + "] with(nolock)"); exportDB.BulkCopy(dtSrcData, tableName.ToLower()); } } catch (Exception ex) { bkpLog.AppendLine("Erro copiando dados da tabela '" + tableName + "': " + ex.Message); TextLog.Log("Backup", "\tErro copiando dados da tabela '" + tableName + "': " + ex.Message); //throw ex; } } //No final de todo o processo atualiza as senhas como cleartext try { bkpLog.AppendLine("Atualizando as senhas das entidades"); DataTable dtEnt = db.ExecuteDataTable("select id from [enterprise] with(nolock)"); foreach (DataRow drEnt in dtEnt.Rows) { using (EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.Connection, (Int64)drEnt["id"])) { DataTable dtSrcData = db.ExecuteDataTable("select e.id, e.password, c.enterprise_id from [entity] e with(nolock) inner join [context] c with(nolock) on e.context_id = c.id where c.enterprise_id = " + drEnt["id"]); //Atualiza senha em clear text de cada usu[ario foreach (DataRow drUser in dtSrcData.Rows) { try { using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(drUser["password"].ToString()))) { exportDB.ExecuteNonQuery("update entity set password = '******' where id = " + drUser["id"]); } } catch (Exception ex) { bkpLog.AppendLine("Erro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); TextLog.Log("Backup", "\tErro decriptografando a senha da entidade '" + drUser["id"] + "': " + ex.Message); //throw ex; } } } } } catch (Exception ex) { bkpLog.AppendLine("Erro atualizando as senhas para cleartext: " + ex.Message); TextLog.Log("Backup", "\tErro atualizando as senhas para cleartext: " + ex.Message); //throw ex; } } db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Backup realizado com sucesso", bkpLog.ToString()); } catch (Exception ex) { TextLog.Log("Backup", "\tError building backup: " + ex.Message); bkpLog.AppendLine("Error building backup: " + ex.Message); try { db.AddUserLog(LogKey.Backup, DateTime.Now, "Backup", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Backup finalizado com erro", bkpLog.ToString()); } catch { } } finally { if (bkpLog != null) { bkpLog = null; } if (db != null) { db.Dispose(); } } }
private void WorkflowTimer(Object state) { if (executing) { return; } executing = true; startTime = DateTime.Now; try { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 900; DataTable dtRequests = db.ExecuteDataTable("select id, workflow_id from [st_workflow_request] r with(nolock) where r.deployed = 0 order by r.create_date"); if ((dtRequests != null) && (dtRequests.Rows.Count > 0)) { try { TextLog.Log("WorkflowProcessor", "Starting workflow processor timer"); foreach (DataRow dr in dtRequests.Rows) { try { WorkflowRequest request = new WorkflowRequest((Int64)dr["id"]); request.GetInicialData(db); WorkflowConfig workflow = new WorkflowConfig(); workflow.GetDatabaseData(db, (Int64)dr["workflow_id"]); switch (request.Status) { case WorkflowRequestStatus.Deny: case WorkflowRequestStatus.Expired: case WorkflowRequestStatus.UserCanceled: //Somente atualiza como deployed, para não ficar verificando db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); continue; break; case WorkflowRequestStatus.Waiting: //Verifica escalation DateTime escalation = request.ActivityCreated.AddDays(request.Activity.EscalationDays); DateTime expired = request.ActivityCreated.AddDays(request.Activity.ExpirationDays); if (expired.CompareTo(DateTime.Now) < 0) { request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId); db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); } else if (escalation.CompareTo(DateTime.Now) < 0) { request.SetStatus(db, WorkflowRequestStatus.Escalated, request.UserId); db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); } break; case WorkflowRequestStatus.Escalated: //Verifica escalation DateTime expired2 = request.ActivityCreated.AddDays(request.Activity.ExpirationDays); if (expired2.CompareTo(DateTime.Now) < 0) { request.SetStatus(db, WorkflowRequestStatus.Expired, request.UserId); db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); } break; case WorkflowRequestStatus.Approved: //Somente executa alguma ação quando não há mais nenhuma atividade a ser executada if (request.NextActivity == null) { switch (workflow.AccessType) { case WorkflowAccessType.RoleGrant: WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access; //Seleciona todas as identidades do usuário e adiciona na role DataTable drIdent = db.ExecuteDataTable("select i.* from [identity] i with(nolock) inner join resource_plugin rp with(nolock) on i.resource_plugin_id = rp.id where rp.enable_import = 1 and rp.permit_add_entity = 1 and i.entity_id = " + request.UserId); if ((drIdent == null) || (drIdent.Rows.Count == 0)) { using (DbParameterCollection par2 = new DbParameterCollection()) { par2.Add("@workflow_request_id", typeof(Int64)).Value = request.RequestId; par2.Add("@status", typeof(String)).Value = (Int32)request.Status; par2.Add("@description", typeof(String)).Value = "No inbound identity found for allow access"; par2.Add("@activity_id", typeof(Int64)).Value = request.Activity.ActivityId; par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy; db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null); } } else { //Lista o nome e id de todas as roles que serão utilizadas List <String> roleList = new List <String>(); foreach (Int64 r in rg.Roles) { roleList.Add(r.ToString()); } DataTable drRoles = db.ExecuteDataTable("select * from [role] where id in (" + String.Join(",", roleList) + ")"); if ((drRoles == null) || (drRoles.Rows.Count == 0)) { using (DbParameterCollection par2 = new DbParameterCollection()) { par2.Add("@workflow_request_id", typeof(Int64)).Value = request.RequestId; par2.Add("@status", typeof(String)).Value = (Int32)request.Status; par2.Add("@description", typeof(String)).Value = "No role found for allow access"; par2.Add("@activity_id", typeof(Int64)).Value = request.Activity.ActivityId; par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy; db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null); } } else { String roleNames = ""; //Adiciona as roles foreach (DataRow dr2 in drIdent.Rows) { foreach (DataRow drRole in drRoles.Rows) { DbParameterCollection par = new DbParameterCollection(); par.Add("@identity_id", typeof(Int64)).Value = dr2["id"]; par.Add("@role_id", typeof(Int64)).Value = drRole["id"]; Boolean added = db.ExecuteScalar <Boolean>("sp_insert_identity_role", CommandType.StoredProcedure, par); if (added) { roleNames += drRole["name"] + Environment.NewLine; } } } if (roleNames != null) { db.AddUserLog(LogKey.User_IdentityRoleBind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, 0, "Entity bind to roles by workflow access request", roleNames); } using (DbParameterCollection par2 = new DbParameterCollection()) { par2.Add("@workflow_request_id", typeof(Int64)).Value = request.RequestId; par2.Add("@status", typeof(String)).Value = (Int32)request.Status; par2.Add("@description", typeof(String)).Value = "Entity bind to roles"; par2.Add("@activity_id", typeof(Int64)).Value = request.Activity.ActivityId; par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy; db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null); } } } db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); break; } } break; case WorkflowRequestStatus.Revoked: //Remove as permissões dadas switch (workflow.AccessType) { case WorkflowAccessType.RoleGrant: WorkflowAccessRoleGrant rg = (WorkflowAccessRoleGrant)workflow.Access; //Lista o nome e id de todas as roles que serão utilizadas List <String> roleList = new List <String>(); foreach (Int64 r in rg.Roles) { roleList.Add(r.ToString()); } String log = ""; DataTable drRoles = db.ExecuteDataTable("select distinct ir.*, r.name role_name from [role] r with(nolock) inner join identity_role ir with(nolock) on ir.role_id = r.id inner join [identity] i with(nolock) on ir.identity_id = i.id where i.entity_id = " + request.UserId + " and r.id in (" + String.Join(",", roleList) + ")"); if ((drRoles != null) && (drRoles.Rows.Count > 0)) { foreach (DataRow dr2 in drRoles.Rows) { log += "Identity unbind to role " + dr2["role_name"] + Environment.NewLine; db.AddUserLog(LogKey.User_IdentityRoleUnbind, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, request.UserId, (Int64)dr2["identity_id"], "Identity unbind to role " + dr2["role_name"]); db.ExecuteNonQuery("delete from identity_role where identity_id = " + dr2["identity_id"] + " and role_id = " + dr2["role_id"], CommandType.Text, null); } using (DbParameterCollection par2 = new DbParameterCollection()) { par2.Add("@workflow_request_id", typeof(Int64)).Value = request.RequestId; par2.Add("@status", typeof(String)).Value = (Int32)request.Status; par2.Add("@description", typeof(String)).Value = log; par2.Add("@activity_id", typeof(Int64)).Value = request.Activity.ActivityId; par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy; db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null); } } else { using (DbParameterCollection par2 = new DbParameterCollection()) { par2.Add("@workflow_request_id", typeof(Int64)).Value = request.RequestId; par2.Add("@status", typeof(String)).Value = (Int32)request.Status; par2.Add("@description", typeof(String)).Value = "No permission to remove"; par2.Add("@activity_id", typeof(Int64)).Value = request.Activity.ActivityId; par2.Add("@executed_by_entity_id", typeof(Int64)).Value = request.LastExecutedBy; db.ExecuteNonQuery("INSERT INTO [st_workflow_request_status]([workflow_request_id],[status],[description],[executed_by_entity_id],[activity_id])VALUES(@workflow_request_id,@status,@description,@executed_by_entity_id,@activity_id)", CommandType.Text, par2, null); } } db.ExecuteNonQuery("update [st_workflow_request] set deployed = 1 where id = " + dr["id"]); break; } break; case WorkflowRequestStatus.UnderReview: //Nada break; } } catch (Exception ex) { db.AddUserLog(LogKey.Workflow, null, "Workflow", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Workflow proccess error", ex.Message); } } } finally { if (db != null) { db.Dispose(); } TextLog.Log("WorkflowProcessor", "Finishing workflow processor timer"); } } db.closeDB(); } finally { if (db != null) { db.Dispose(); } } } catch (Exception ex) { TextLog.Log("WorkflowProcessor", "Error on message timer " + ex.Message); } finally { executing = false; last_status = ""; startTime = new DateTime(1970, 1, 1); } }
private void BuildReport(Int64 reportId) { IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); DataTable dtS = db.Select("select * from report where id = " + reportId); if ((dtS == null) || (dtS.Rows.Count == 0)) { return; } //Chega as propriedades básicas do report List <MailAddress> recipents = new List <MailAddress>(); if ((dtS.Rows[0]["recipient"] != DBNull.Value) && (!String.IsNullOrWhiteSpace((String)dtS.Rows[0]["recipient"]))) { String[] tTo = dtS.Rows[0]["recipient"].ToString().Split(",;".ToCharArray()); foreach (String s in tTo) { try { if (!String.IsNullOrWhiteSpace(s)) { recipents.Add(new MailAddress(s)); } } catch { } } } if (recipents.Count == 0) { throw new Exception("No valid email informed in recipient"); } switch (dtS.Rows[0]["type"].ToString().ToLower()) { case "audit": auditReport(db, dtS, recipents); break; case "integrity": integrityTextReport(db, dtS, recipents); break; default: usersTextReport(db, dtS, recipents); break; } } catch (Exception ex) { TextLog.Log("Report", "\tError building report: " + ex.Message); try { db.AddUserLog(LogKey.Report, DateTime.Now, "Report", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Erro building report", ex.Message); } catch { } } finally { if (db != null) { db.Dispose(); } } }
private void InfoTimer(Object oData) { TimeSpan tsInfo = lastInfo - new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0); if (infoExec || ((Int32)tsInfo.TotalDays == 0)) { return; } infoExec = true; using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword)) using (ServerKey2 sk = new ServerKey2(db2.Connection)) try { db2.openDB(); List <Object> lics = new List <Object>(); Version version = new Version("0.0"); try { DataTable dtLicCount = db2.ExecuteDataTable("select count(e.id) qty, c.enterprise_id from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where e.deleted = 0 group by c.enterprise_id"); if (dtLicCount != null) { foreach (DataRow dr in dtLicCount.Rows) { String message = ""; List <String> data = new List <string>(); DataTable dtLic = db2.ExecuteDataTable("select * from license where enterprise_id in (0, " + dr["enterprise_id"] + ")"); if (dtLic == null) { message = "Error on get licenses on server"; } if (dtLic.Rows.Count == 0) { message = "License list is empty"; } foreach (DataRow dr2 in dtLic.Rows) { data.Add(dr2["license_data"].ToString()); } //Resgata do banco a contagem atual de entidades var eItem = new { id = dr["enterprise_id"].ToString(), message = message, entity = dr["qty"], data = data }; lics.Add(eItem); } } try { version = Assembly.GetEntryAssembly().GetName().Version; } catch { } var info = new { date = DateTime.UtcNow.ToString("o"), product = "SafeId", version = version.ToString(), installation_key = sk.ServerInstallationKey.AbsoluteUri, server_cert = sk.ServerCertString, licences = lics }; String jData = JSON.Serialize2(info); WebClient client = new WebClient(); client.UploadData("https://licencing.safetrend.com.br/si/", Encoding.UTF8.GetBytes(jData)); lastInfo = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0); } catch { } finally { db2.closeDB(); } } catch { } infoExec = false; }
static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Parâmetros: nome fqdn "); return; } ServerLocalConfig localConfig = new ServerLocalConfig(); localConfig.LoadConfig(); if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == "")) { StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == "")) { StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == "")) { StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null); } if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == "")) { StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null); } IAMDatabase db = null; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); } catch (Exception ex) { StopOnError("Erro conectando na base de dados: " + ex.Message, null); } //Verifica se existe um certificado de servidor para usar //Desabilitado em 2018-03-05 (por erro de checagem de certificado por parte do proxy) //O Instalador precisa sempre usar o mesmo certificado disponível em Certificates e vinculado a este executável /* * DataTable dt = db.ExecuteDataTable("select server_cert, server_pkcs12_cert from server_cert with(nolock)"); * * if ((dt != null) && (dt.Rows.Count > 0)) //Existe certificado, então lê * { * //this.ServerCertString = dt.Rows[0]["server_cert"].ToString(); * //this.ServerPKCS12String = dt.Rows[0]["server_pkcs12_cert"].ToString(); * * * try * { * System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(Program)); * FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "IAMServerCertificateRoot.cer")); * if (certFile.Exists) * certFile.Delete(); * * File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(dt.Rows[0]["server_cert"].ToString())); * } * catch { } * * try * { * System.Reflection.Assembly asm = System.Reflection.Assembly.GetAssembly(typeof(Program)); * FileInfo certFile = new FileInfo(Path.Combine(Path.GetDirectoryName(asm.Location), "IAMServerCertificateRoot.pfx")); * if (certFile.Exists) * certFile.Delete(); * * File.WriteAllBytes(certFile.FullName, Convert.FromBase64String(dt.Rows[0]["server_pkcs12_cert"].ToString())); * } * catch { } * * }*/ //Creator creator = new Creator(db, "SafeID - Start enterprise", "demo.safeid.com.br", "pt-BR", "//login.safeid.com.br/cas/"); Creator creator = new Creator(db, args[0], args[1], "pt-BR"); creator.BuildCertificates(); creator.Commit(); }
private void TmrCallback(Object o) { if (executing) { return; } executing = true; TextLog.Log("Engine", "Importer", "Starting registry processor timer"); Console.WriteLine("Starting registry processor timer"); IAMDatabase db = null; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Dictionary <Int64, PluginConfig> resourcePluginCache = new Dictionary <Int64, PluginConfig>(); StringBuilder procLog = new StringBuilder(); Boolean writeLog = false; last_status = "Iniciando..."; try { db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 600; //db.Debug = true; Console.WriteLine("Select data..."); Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate); startTime = DateTime.Now; newUsers = 0; errors = 0; totalReg = 0; ignored = 0; atualReg = 0; //Seleciona os registros prontos para serem importados //Não colocar order neste select, fica extremamente lento //Coloca um limite de 500.000 somente p/ não estourar memória last_status = "Selecionando registros a serem processados"; DataTable dtRegs = db.Select("select top 5000 * from vw_collector_imports_regs with(nolock) order by priority desc"); if (dtRegs == null) { TextLog.Log("Engine", "Importer", "\tError on select registries: " + db.LastDBError); db.AddUserLog(LogKey.Engine, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on select registries: " + db.LastDBError); executing = false; return; } if (dtRegs.Rows.Count == 0) { TextLog.Log("Engine", "Importer", "\t0 registers to process"); Console.WriteLine("0 registers to process"); executing = false; return; } totalReg = dtRegs.Rows.Count; TextLog.Log("Engine", "Importer", "\t" + dtRegs.Rows.Count + " registers to process"); procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + dtRegs.Rows.Count + " registers to process"); Console.WriteLine(dtRegs.Rows.Count + " registers to process"); //Carrega todos os logins do sistema Console.WriteLine("Fetch logins..."); last_status = "Listando login do sistema"; DataTable dtLogins = db.Select("select context_id,id,login from vw_entity_logins2 with(nolock)"); if ((dtLogins != null) || (dtLogins.Rows.Count > 0)) { foreach (DataRow dr in dtLogins.Rows) { LoginCache.AddItem((Int64)dr["context_id"], (Int64)dr["id"], dr["login"].ToString()); } } //Carrega todos os e-mails do sistema Console.WriteLine("Fetch e-mails..."); last_status = "Listando e-mails do sistema"; DataTable dtEmails = db.Select("select context_id, entity_id, mail from vw_entity_mails with(nolock)"); if ((dtEmails != null) || (dtEmails.Rows.Count > 0)) { foreach (DataRow dr in dtEmails.Rows) { EmailCache.AddItem((Int64)dr["context_id"], (Int64)dr["entity_id"], dr["mail"].ToString()); } } //Calcula a quantidade de threads com base na quantidade de registros Int32 tCount = dtRegs.Rows.Count / 10; if (tCount < 1) { tCount = 1; } else if (tCount > this.maxThreads) { tCount = this.maxThreads; } #if DEBUG tCount = 1; #endif DebugMessage dbgC = new DebugMessage(delegate(String message) { procLog.AppendLine(message); }); Console.WriteLine("Starting..."); queueManager = new QueueManager <RegistryProcessStarter>(tCount, ProcQueue); queueManager.OnThreadStart += new QueueManager <RegistryProcessStarter> .StartThread(delegate(Int32 threadIndex) { LocalTheadObjects obj = new LocalTheadObjects(); for (Int32 t = 0; t <= 10; t++) { try { obj.db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); obj.db.openDB(); obj.db.Timeout = 600; #if DEBUG //obj.db.Debug = true; #endif obj.lockRules = new LockRules(); obj.ignoreRules = new IgnoreRules(); obj.roleRules = new RoleRules(); obj.lockRules.GetDBConfig(obj.db.Connection); obj.ignoreRules.GetDBConfig(obj.db.Connection); obj.roleRules.GetDBConfig(obj.db.Connection); obj.debugCallback = dbgC; break; } catch (Exception ex) { if (t >= 10) { throw ex; } } } return(obj); }); queueManager.OnThreadStop += new QueueManager <RegistryProcessStarter> .ThreadStop(delegate(Int32 threadIndex, Object state) { if ((state != null) && (state is LocalTheadObjects)) { ((LocalTheadObjects)state).Dispose(); } state = null; }); Console.WriteLine("Starting treads..."); last_status = "Iniciando treads"; queueManager.Start(); if (queueManager.ExecutingCount == 0) { throw new Exception("Erro on start queue manager"); } /* * _queue = new RegistryQueue[tCount]; * Int32 qIndex = 0; * * for (Int32 i = 0; i < _queue.Length; i++) * _queue[i] = new RegistryQueue(); */ Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Normal); Taskbar.TaskbarProgress.SetProgressValue(0, (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle); Int32 addCount = 0; last_status = "Processando registros"; foreach (DataRow dr in dtRegs.Rows) { Int64 enterpriseId = (Int64)dr["enterprise_id"]; Int64 contextId = (Int64)dr["context_id"]; LicenseControl lic = null; if (!licControl.ContainsKey(enterpriseId)) { lic = LicenseChecker.GetLicenseData(db.Connection, null, enterpriseId); licControl.Add(enterpriseId, lic); } else { lic = licControl[enterpriseId]; } if (!lic.Valid) { if (!lic.Notified) { db.AddUserLog(LogKey.Licence_error, null, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: " + lic.Error); } lic.Notified = true; db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null); continue; } if ((lic.Entities > 0) && (lic.Count > lic.Entities)) { if (!lic.Notified) { db.AddUserLog(LogKey.Licence_error, null, "Engine", UserLogLevel.Error, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["plugin_id"], 0, 0, "License error: License limit (" + lic.Entities + " entities) exceeded"); } lic.Notified = true; db.ExecuteNonQuery("update collector_imports set status = 'LE' where status = 'F' and resource_plugin_id = '" + dr["resource_id"] + "' and import_id = '" + dr["import_id"] + "' and package_id = '" + dr["package_id"] + "'", CommandType.Text, null); continue; } if (!entKeys.ContainsKey(enterpriseId)) { entKeys.Add(enterpriseId, new EnterpriseKeyConfig(db.Connection, enterpriseId)); } if (entKeys[enterpriseId] == null) { entKeys[enterpriseId] = new EnterpriseKeyConfig(db.Connection, enterpriseId); } addCount++; queueManager.AddItem(new RegistryProcessStarter(enterpriseId, contextId, new Uri(dr["plugin_uri"].ToString()), Int64.Parse(dr["resource_id"].ToString()), Int64.Parse(dr["plugin_id"].ToString()), Int64.Parse(dr["resource_plugin_id"].ToString()), (String)dr["import_id"], (String)dr["package_id"], (String)dr["package"])); //A cada 100 registros monitora a CPU para adicionar mais registros //O Objetivo deste processo é controlar a carga de processamento if (addCount >= 100) { addCount = 0; Int32 c = 0; while (((c = queueManager.QueueCount) > 500) || ((getCPUCounter() >= 70) && (c > 0))) { Thread.Sleep(500); } } /* * _queue[qIndex].Add(enterpriseId, contextId, Int64.Parse(dr["plugin_id"].ToString()), (String)dr["plugin_uri"], Int64.Parse(dr["resource_id"].ToString()), (String)dr["import_id"], (String)dr["registry_id"]); * * qIndex++; * if (qIndex > _queue.Length - 1) qIndex = 0; */ } /* * for (Int32 i = 0; i < _queue.Length; i++) * { * Thread procQueue = new Thread(new ParameterizedThreadStart(ProcQueue)); * procQueue.Start(i); * //Thread.Sleep(1000); * }*/ Console.WriteLine("Waiting treads execution..."); /* * Int64 rest = 0; * Double percent = 0; * Int32 iPercent = 0; * do * { * rest = 0; * * rest = queueManager.QueueCount; * * //for (Int32 i = 0; i < _queue.Length; i++) * // rest += _queue[i].Count; * * percent = ((Double)(totalReg - rest) / (Double)totalReg) * 100F; * * if (iPercent != (Int32)percent) * { * iPercent = (Int32)percent; * procLog.AppendLine("[" + DateTime.Now.ToString("o") + "] " + iPercent + "%"); * TextLog.Log("Engine", "Importer", "\t" + iPercent + "%"); * Console.Write(" " + iPercent + "% "); * * Taskbar.TaskbarProgress.SetProgressValue((Int32)(totalReg - rest), (Int32)totalReg, System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle); * * } * * Thread.Sleep(1000); * * } while (rest > 0);*/ //Envia comando para finalizar a execução e aguarda a finalização last_status = "Processando registros"; queueManager.StopAndWait(); Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.Indeterminate); last_status = "Finalizando"; Console.WriteLine("Finishing..."); if (dtRegs.Rows.Count > 0) { writeLog = true; } procLog.AppendLine("New users: " + newUsers); procLog.AppendLine("Errors: " + errors); procLog.AppendLine("Ignored: " + ignored); procLog.AppendLine("Updated: " + (totalReg - errors - ignored - newUsers)); procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Import registry processed with " + dtRegs.Rows.Count + " registers"); //Joga todos os registros para a tabela de importados //e exclui da atual db.ExecuteNonQuery("sp_migrate_imported", CommandType.StoredProcedure, null); //Reconstroi os índices das tabelas de entidades e identidades try { db.ExecuteNonQuery("sp_reindex_entity", CommandType.StoredProcedure, null); db.ExecuteNonQuery("sp_rebuild_entity_keys", CommandType.StoredProcedure, null); } catch { } Console.WriteLine(""); } catch (SqlException e) { procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] DB Error on registry processor: " + e.Message); procLog.AppendLine(db.LastDBError); db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "DB Error on registry processor", procLog.ToString()); TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + e.Message + " " + db.LastDBError); } catch (OutOfMemoryException ex) { procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message); db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Out Of Memory processing registry, killing processor", procLog.ToString()); TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message); System.Diagnostics.Process.GetCurrentProcess().Kill(); } catch (Exception ex) { procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Error on registry processor: " + ex.Message); db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Error on registry processor", procLog.ToString()); TextLog.Log("Engine", "Importer", "\tError on registry processor timer " + ex.Message); } finally { stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; executing = false; last_status = ""; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:0000}", ts.TotalHours, ts.Minutes, ts.Seconds, ts.Milliseconds); TextLog.Log("Engine", "Importer", "\tElapsed time: " + elapsedTime); TextLog.Log("Engine", "Importer", "\tScheduled for new registry processor in 60 seconds"); TextLog.Log("Engine", "Importer", "Finishing registry processor timer"); procLog.AppendLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "] Elapsed time: " + elapsedTime); Console.WriteLine("Import registry processed " + procLog.ToString()); Console.WriteLine("Elapsed time: " + elapsedTime); if (writeLog) { db.AddUserLog(LogKey.Import, null, "Engine", UserLogLevel.Info, 0, 0, 0, 0, 0, 0, 0, "Import registry processed", procLog.ToString()); } Taskbar.TaskbarProgress.SetProgressState(Taskbar.TaskbarProgressState.NoProgress); startTime = new DateTime(1970, 1, 1); try { List <Int64> keys = new List <Int64>(); if ((entKeys != null) && (entKeys.Count > 0)) { keys.AddRange(entKeys.Keys); foreach (Int64 k in keys) { try { if (entKeys[k] != null) { entKeys[k].Dispose(); entKeys[k] = null; } } catch { } try { entKeys.Remove(k); } catch { } } } } catch { } try { licControl.Clear(); } catch { } try { LoginCache.Clear(); } catch { } if (db != null) { db.Dispose(); } db = null; Thread.CurrentThread.Abort(); } }