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 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("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 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 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; } }
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 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; } }
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 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; } }
private Int32 _Deploy(Int64 entityId, Int64 resourcePluginId) { //Busca todos os plugins e recursos a serem publicados DataTable dtPlugins = null; Dictionary <Int64, LicenseControl> licControl = null; DataTable dtEnt = null; Int32 packageCount = 0; StringBuilder deployLog = new StringBuilder(); try { dtPlugins = db.Select("select r.context_id, p.id, p.scheme, p.uri, p.assembly, p.create_date, rp.id resource_plugin_id, rp.deploy_individual_package, r.id resource_id, r.proxy_id, p1.name as proxy_name, p1.id proxy_id, p1.enterprise_id, rp.deploy_after_login, rp.password_after_login, rp.deploy_process, rp.deploy_all, rp.deploy_password_hash, rp.use_password_salt, rp.password_salt_end, rp.password_salt from plugin p with(nolock) inner join resource_plugin rp with(nolock) on rp.plugin_id = p.id inner join [resource] r on r.id = rp.resource_id inner join proxy p1 on r.proxy_id = p1.id where " + (resourcePluginId > 0 ? " rp.id = " + resourcePluginId + " and " : "") + " r.enabled = 1 and rp.enabled = 1 and rp.enable_deploy = 1 order by rp.[order]"); if ((dtPlugins == null) || (dtPlugins.Rows.Count == 0)) { if ((entityId > 0) || (resourcePluginId > 0)) { throw new Exception("0 plugin to process"); } //TextLog.Log(moduleSender, "\t0 plugin to process"); DebugLog(entityId, "0 plugin to process"); return(0); } DebugLog(entityId, dtPlugins.Rows.Count + " plugin to process"); licControl = new Dictionary <long, LicenseControl>(); String rolesText = ""; //Lista todos os plugins e resources habilitados foreach (DataRow dr in dtPlugins.Rows) { Boolean individualPackage = (Boolean)dr["deploy_individual_package"]; deployLog = new StringBuilder(); DebugLog(entityId, "proxy_name = " + dr["proxy_name"].ToString() + ", plugin = " + dr["uri"].ToString() + ", deploy_all? " + dr["deploy_all"].ToString()); ProxyConfig config = new ProxyConfig(true); config.GetDBCertConfig(db.Connection, Int64.Parse(dr["enterprise_id"].ToString()), dr["proxy_name"].ToString()); DirectoryInfo proxyDir = new DirectoryInfo(Path.Combine(outDirBase.FullName, dr["proxy_id"].ToString() + "_" + dr["proxy_name"].ToString() + "\\" + Path.GetFileNameWithoutExtension(dr["assembly"].ToString()) + "\\rp" + dr["resource_plugin_id"].ToString())); List <PluginConnectorBaseDeployPackage> packageList = new List <PluginConnectorBaseDeployPackage>(); List <Int64> roles = new List <Int64>(); Int64 enterpriseId = (Int64)dr["enterprise_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, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], (Int64)dr["enterprise_id"], 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "License error: " + lic.Error); } lic.Notified = true; continue; } if (!(Boolean)dr["deploy_all"]) { //Busca os "roles" top String rolesSQL = "select rpr.* from resource_plugin_role rpr with(nolock) inner join resource_plugin rp on rpr.resource_plugin_id = rp.id where rp.resource_id = " + dr["resource_id"].ToString() + " and rp.plugin_id = " + dr["id"]; DebugLog(entityId, "Role SQL = " + rolesSQL); DataTable dtRoles = db.Select(rolesSQL); if (dtRoles == null) { db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : "")); continue; } List <String> roleNames = new List <String>(); //Busca toda a arvore de "roles" a se buscar foreach (DataRow drR in dtRoles.Rows) { DataTable dtR = db.Select("select * from dbo.fn_selectRoleTree(" + drR["role_id"] + ")"); if (dtR == null) { continue; } foreach (DataRow drRT in dtR.Rows) { if (!roles.Contains((Int64)drRT["role_id"])) { roleNames.Add(drRT["name"].ToString()); roles.Add((Int64)drRT["role_id"]); } } } if (roles.Count == 0) { db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Not found roles x identities to deploy"); continue; } //Para efeitos de log captura o nome dos roles rolesText = String.Join(", ", roleNames); dtRoles.Clear(); dtRoles = null; } //Seleciona todas as entidades do mesmo contexto //Esta listagem considera somente as entidades pertencentes aos plugins de entrada String sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id where i.deleted = 0 and e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) group by e.id, e.last_login, e.change_password, i.id"; if (!(Boolean)dr["deploy_all"]) { sql = "select e.id, e.last_login, e.change_password, i.id identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id inner join [identity] i with(nolock) on i.entity_id = e.id inner join [resource_plugin] rp with(nolock) on i.resource_plugin_id = rp.id inner join identity_role ir with(nolock) on ir.identity_id = i.id inner join (select rpr.role_id from resource_plugin_role rpr with(nolock) inner join resource_plugin rp with(nolock) on rp.id = rpr.resource_plugin_id inner join resource r with(nolock) on r.id = rp.resource_id where r.id = "+ dr["resource_id"].ToString() + ") ro on ro.role_id = ir.role_id where i.deleted = 0 and e.deleted = 0 {0} and ir.role_id in (" + String.Join(",", roles) + ")" + (entityId > 0 ? " and e.id = " + entityId : "") + " and not exists (select 1 from identity_block_inheritance bi where bi.identity_id = i.id) and e.context_id = " + dr["context_id"] + " group by e.id, e.last_login, e.change_password, i.id"; } DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1")); //Lista todas as entidades e identidades para exportar dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1")); if (dtEnt == null) { DebugLog(entityId, "SQL result is empty"); db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : "")); continue; } if (dtEnt.Rows.Count == 0) { DebugLog(entityId, "SQL result is empty, trying with all plugins"); DebugLog(entityId, String.Format(sql, "")); //Lista todas as entidades e identidades para exportar dtEnt = db.Select(String.Format(sql, "")); if (dtEnt == null) { DebugLog(entityId, "SQL result is empty"); db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : "")); continue; } } sql = null; if ((dtEnt.Rows.Count == 0) && ((Boolean)dr["deploy_all"])) { DebugLog(entityId, "SQL result is empty with all plugins, trying with only entity data"); sql = "select e.id, e.last_login, e.change_password, cast(0 as bigint) identity_id from entity e with(nolock) inner join resource r with(nolock) on e.context_id = r.context_id cross join [resource_plugin] rp with(nolock) where e.deleted = 0 {0} and e.context_id = " + dr["context_id"] + (entityId > 0 ? " and e.id = " + entityId : "") + " group by e.id, e.last_login, e.change_password"; DebugLog(entityId, String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1")); //Lista todas as entidades e identidades para exportar dtEnt = db.Select(String.Format(sql, "and rp.enable_import = 1 and rp.permit_add_entity = 1")); if (dtEnt == null) { DebugLog(entityId, "SQL result is empty"); db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "DB error: " + (((db.LastDBError != null) && (db.LastDBError != "")) ? db.LastDBError : "")); continue; } } sql = null; DebugLog(entityId, "SQL result count " + dtEnt.Rows.Count); if ((dtEnt.Rows.Count > 0) && (entityId == 0)) { deployLog.AppendLine("Starting check to deploy " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users")); } Int32 total = dtEnt.Rows.Count; Int32 licError = 0; Int32 loguedIgnore = 0; Int32 deploy = 0; //db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy with " + dtEnt.Rows.Count + " identities for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users")); foreach (DataRow drE in dtEnt.Rows) { //Checagens de licenciamento lic.Count++; if ((lic.Entities > 0) && (lic.Count > lic.Entities)) { db.AddUserLog(LogKey.Licence_error, null, "Deploy", UserLogLevel.Error, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "License error: License limit (" + lic.Entities + " entities) exceeded"); licError++; continue; } try { if (((Boolean)dr["deploy_after_login"]) && (drE["last_login"] == DBNull.Value)) { db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "User NOT addedd in deploy package because the user is not logged in yet"); loguedIgnore++; continue; } //db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Identity addedd in deploy package"); PluginConnectorBaseDeployPackage newPkg = DeployPackage.GetPackage(db, (Int64)dr["proxy_id"], (Int64)dr["resource_plugin_id"], (Int64)drE["id"], (Int64)drE["identity_id"], (Boolean)dr["password_after_login"], (drE["change_password"] == DBNull.Value ? null : (DateTime?)drE["change_password"]), (dr["deploy_password_hash"] == DBNull.Value ? "none" : dr["deploy_password_hash"].ToString()), (Boolean)dr["use_password_salt"], (Boolean)dr["password_salt_end"], dr["password_salt"].ToString()); packageList.Add(newPkg); deploy++; #if DEBUG try { db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Debug, 0, enterpriseId, 0, (Int64)dr["resource_id"], (Int64)dr["id"], newPkg.entityId, newPkg.identityId, "Package generated: " + newPkg.pkgId, SafeTrend.Json.JSON.Serialize <PluginConnectorBaseDeployPackage>(newPkg)); } catch { } #endif packageCount++; } catch (Exception ex) { db.AddUserLog(LogKey.User_Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], (Int64)drE["id"], (Int64)drE["identity_id"], "Erro on deploy user: "******"Total identities: " + total); deployLog.AppendLine("Ignored by licence check: " + licError); deployLog.AppendLine("Ignored by first login rule: " + loguedIgnore); deployLog.AppendLine("Published: " + deploy); db.AddUserLog(LogKey.Deploy, null, "Deploy", UserLogLevel.Info, (Int64)dr["proxy_id"], 0, 0, (Int64)dr["resource_id"], (Int64)dr["id"], 0, 0, "Deploy package generated for " + ((!(Boolean)dr["deploy_all"]) ? rolesText : "all users"), deployLog.ToString()); } db.closeDB(); db.Dispose(); } catch (Exception ex) { DebugLog(entityId, "Erro on Deploy: " + ex.Message); throw ex; } finally { deployLog.Clear(); deployLog = null; if (dtPlugins != null) { dtPlugins.Clear(); } dtPlugins = null; if (dtEnt != null) { dtEnt.Clear(); } dtEnt = null; if (licControl != null) { try { List <Int64> k = new List <Int64>(); k.AddRange(licControl.Keys); foreach (Int64 l in k) { if (licControl[l] != null) { licControl[l].Dispose(); licControl[l] = null; } } k.Clear(); } catch { } } licControl = null; } return(packageCount); }
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(); } }
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("Dispatcher", null); db.closeDB(); db.Dispose(); break; } catch (Exception ex) { if (cnt < 10) { TextLog.Log("Dispatcher", "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 */ dispatcherTimer = new Timer(new TimerCallback(DispatcherTimer), null, 1000, 60000); deployNowTimer = new Timer(new TimerCallback(DeployNowTimer), null, 1000, 60000); statusTimer = new Timer(new TimerCallback(TmrServiceStatusCallback), null, 100, 10000); }
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); } }
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(); } } }
protected void Page_Load(object sender, EventArgs e) { if (Request.HttpMethod != "POST") { return; } String area = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["area"])) { area = (String)RouteData.Values["area"]; } Int64 enterpriseId = 0; if ((Session["enterprise_data"]) != null && (Session["enterprise_data"] is EnterpriseData)) { enterpriseId = ((EnterpriseData)Session["enterprise_data"]).Id; } Boolean newItem = false; if ((RouteData.Values["new"] != null) && (RouteData.Values["new"] == "1")) { newItem = true; } String ApplicationVirtualPath = Session["ApplicationVirtualPath"].ToString(); LMenu menu1 = new LMenu("Dashboard", ApplicationVirtualPath + "admin/"); LMenu menu2 = new LMenu("Perfis", ApplicationVirtualPath + "admin/system_roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "")); LMenu menu3 = new LMenu("Perfis do sistema", ApplicationVirtualPath + "admin/system_roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "")); WebJsonResponse contentRet = null; String html = ""; String eHtml = ""; String js = null; String errorTemplate = "<span class=\"empty-results\">{0}</span>"; String infoTemplate = "<tr><td class=\"col1\">{0}</td><td class=\"col2\"><span class=\"no-edit\">{1}</span></td></tr>"; //Verifica se está sendo selecionada uma role Int64 roleId = 0; try { roleId = Int64.Parse((String)RouteData.Values["id"]); if (roleId < 0) { roleId = 0; } } catch { } String error = ""; SystemRoleGetResult selectedRole = null; String filter = ""; HashData hashData = new HashData(this); if (!String.IsNullOrWhiteSpace((String)RouteData.Values["filter"])) { filter = (String)RouteData.Values["filter"]; } if ((roleId > 0) && (area.ToLower() != "search")) { try { String rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "systemrole.get", parameters = new { roleid = roleId, permissions = true }, id = 1 }); IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()); String jData = ""; try { jData = WebPageAPI.ExecuteLocal(database, this, rData); } finally { if (database != null) { database.Dispose(); } } selectedRole = JSON.Deserialize <SystemRoleGetResult>(jData); if (selectedRole == null) { error = MessageResource.GetMessage("system_role_not_found"); } else if (selectedRole.error != null) { error = selectedRole.error.data; selectedRole = null; } else if (selectedRole.result == null || selectedRole.result.info == null) { error = MessageResource.GetMessage("system_role_not_found"); selectedRole = null; } else { menu3.Name = selectedRole.result.info.name; menu3.HRef = ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : ""); } } catch (Exception ex) { error = MessageResource.GetMessage("api_error"); Tools.Tool.notifyException(ex, this); selectedRole = null; } } switch (area) { case "": case "search": case "content": if (newItem) { html = "<h3>Adição de perfil</h3>"; html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/action/add_role/\">"; html += "<div class=\"no-tabs fields\"><table><tbody>"; html += String.Format(infoTemplate, "Nome", "<input id=\"add_role_name\" name=\"add_role_name\" placeholder=\"Digite o nome do perfil\" type=\"text\">"); html += String.Format(infoTemplate, "Admin", "<input id=\"enterprise_admin\" name=\"enterprise_admin\" type=\"checkbox\"><span class=\"description\">Perfil com direitos em todas as operações desta empresa</span>"); html += "</select></div>"; html += "</tbody></table></div>"; html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Adicionar</button> <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>"; contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); } else { if (selectedRole == null) { Int32 page = 1; Int32 pageSize = 20; Boolean hasNext = true; Int32.TryParse(Request.Form["page"], out page); if (page < 1) { page = 1; } String roleTemplate = "<div id=\"role-list-{0}\" data-id=\"{0}\" data-name=\"{1}\" data-total=\"{2}\" class=\"app-list-item\">"; roleTemplate += "<table>"; roleTemplate += " <tbody>"; roleTemplate += " <tr>"; roleTemplate += " <td class=\"col1\">"; roleTemplate += " <span id=\"total_{0}\" class=\"total \">{2}</span>"; roleTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\">"; roleTemplate += " <div class=\"app-btn a-btn\"><span class=\"a-btn-inner\">Ver usuários</span></div>"; roleTemplate += " </a>"; roleTemplate += " </td>"; roleTemplate += " <td class=\"col2\">"; roleTemplate += " <div class=\"title\"><span class=\"name field-editor\" id=\"role_name_{0}\" data-id=\"{0}\" data-function=\"iamadmin.editTextField('#role_name_{0}',null,roleNameEdit);\">{1}</span><span class=\"date\">{3}</span><div class=\"clear-block\"></div></div>"; roleTemplate += " <div class=\"description\">Permissões atribuidas: {4}"; roleTemplate += " </div>"; roleTemplate += " <div class=\"links\">"; roleTemplate += " <div class=\"line\">"; roleTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-change\">Editar</div></a>"; roleTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/permissions/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-checkmark\">Permissões</div></a>"; roleTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\"><div class=\"ico icon-user-add\">Adicionar usuário</div></a>"; roleTemplate += " <a href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/action/delete_all_users/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente todos os usuários do perfil '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Excluir usuários</div></a>"; roleTemplate += " <a class=\"confirm-action\" href=\"" + ApplicationVirtualPath + "admin/system_roles/{0}/action/delete/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o perfil '{1}'?\" ok=\"Excluir\" cancel=\"Cancelar\"><div class=\"ico icon-close\">Apagar</div></a>"; roleTemplate += " </div><div class=\"clear-block\"></div>"; roleTemplate += " </div>"; roleTemplate += " </td>"; roleTemplate += " </tr>"; roleTemplate += " </tbody>"; roleTemplate += "</table></div>"; js += "roleNameEdit = function(thisId, changedText) { iamadmin.changeName(thisId,changedText); };"; html += "<div id=\"box-container\" class=\"box-container\">"; String query = ""; try { String rData = ""; if (!String.IsNullOrWhiteSpace((String)RouteData.Values["query"])) { query = (String)RouteData.Values["query"]; } if (String.IsNullOrWhiteSpace(query) && !String.IsNullOrWhiteSpace(hashData.GetValue("query"))) { query = hashData.GetValue("query"); } if (String.IsNullOrWhiteSpace(query)) { rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "systemrole.list", parameters = new { page_size = pageSize, page = page, permissions = true }, id = 1 }); } else { rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "systemrole.search", parameters = new { text = query, page_size = pageSize, page = page, permissions = true }, id = 1 }); } IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString()); String jData = ""; try { jData = WebPageAPI.ExecuteLocal(database, this, rData); } finally { if (database != null) { database.Dispose(); } } if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } SystemRoleListResult ret2 = JSON.Deserialize <SystemRoleListResult>(jData); if (ret2 == null) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("system_role_not_found")); hasNext = false; } else if (ret2.error != null) { #if DEBUG eHtml += String.Format(errorTemplate, ret2.error.data + ret2.error.debug); #else eHtml += String.Format(errorTemplate, ret2.error.data); #endif hasNext = false; } else if (ret2.result == null || (ret2.result.Count == 0 && page == 1)) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("system_role_not_found")); hasNext = false; } else { foreach (SystemRoleData role in ret2.result) { List <String> perm = new List <string>(); if (!role.enterprise_admin && (role.permissions != null) && (role.permissions.Count > 0)) { foreach (SystemRolePermission p in role.permissions) { perm.Add(p.module_name + "/" + p.sub_module_name + "/" + p.name); } } if (role.enterprise_admin) { perm.Add("Administração da empresa - todas as permissões"); } if (perm.Count == 0) { perm.Add("Nenhuma permissão atribuida"); } html += String.Format(roleTemplate, role.role_id, role.name, role.entity_qty, (role.create_date > 0 ? "Criado em " + MessageResource.FormatDate(new DateTime(1970, 1, 1).AddSeconds(role.create_date), true) : ""), String.Join(", ", perm)); } if (ret2.result.Count < pageSize) { hasNext = false; } } } catch (Exception ex) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error")); } if (page == 1) { html += "</div>"; html += "<span class=\"empty-results content-loading role-list-loader hide\"></span>"; contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); } else { contentRet = new WebJsonResponse("#content-wrapper #box-container", (eHtml != "" ? eHtml : html), true); } contentRet.js = js + "$( document ).unbind('end_of_scroll');"; if (hasNext) { contentRet.js += "$( document ).bind( 'end_of_scroll.loader_role', function() { $( document ).unbind('end_of_scroll.loader_role'); $('.role-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'" + (!String.IsNullOrWhiteSpace(query) ? query : "") + "' }, function(){ $('.role-list-loader').addClass('hide'); } ); });"; } } else //Esta sendo selecionado a role { if (error != "") { contentRet = new WebJsonResponse("#content-wrapper", String.Format(errorTemplate, error)); } else { switch (filter) { case "": html += "<h3>Configurações gerais"; if (hashData.GetValue("edit") != "1") { html += "<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div>"; } html += "</h3>"; html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/action/change_role/\">"; html += "<div class=\"no-tabs fields\"><table><tbody>"; if (hashData.GetValue("edit") == "1") { html += String.Format(infoTemplate, "Nome", "<input id=\"name\" name=\"name\" placeholder=\"Digite o nome do perfil\" type=\"text\" value=\"" + selectedRole.result.info.name + "\">"); html += String.Format(infoTemplate, "Admin", "<input id=\"enterprise_admin\" name=\"enterprise_admin\" type=\"checkbox\" " + (selectedRole.result.info.enterprise_admin ? "checked" : "") + "><span class=\"description\">Perfil com direitos em todas as operações desta empresa</span>"); } else { html += String.Format(infoTemplate, "Nome", selectedRole.result.info.name); html += String.Format(infoTemplate, "Admin", (selectedRole.result.info.enterprise_admin ? MessageResource.GetMessage("yes") : MessageResource.GetMessage("no"))); } html += "</tbody></table></div>"; if (hashData.GetValue("edit") == "1") { html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button> <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/\" class=\"button link floatleft\">Cancelar</a></form>"; } contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); break; case "users": Int32 page = 1; Int32 pageSize = 20; Boolean hasNext = true; Int32.TryParse(Request.Form["page"], out page); if (page < 1) { page = 1; } if (page == 1) { html += "<table id=\"users-table\" class=\"sorter\"><thead>"; html += " <tr>"; html += " <th class=\"w50 mHide {sorter: false}\"><div class=\"select-all\"></div></th>"; html += " <th class=\"pointer header headerSortDown\" data-column=\"name\">Nome <div class=\"icomoon\"></div></th>"; html += " <th class=\"pointer tHide mHide header\" data-column=\"login\">Login <div class=\"icomoon\"></div></th>"; html += " <th class=\"pointer w200 tHide mHide header\" data-column=\"last_login\">Ações <div class=\"icomoon\"></div></th>"; html += " </tr>"; html += "</thead>"; html += "<tbody>"; } String trTemplate = " <tr class=\"user\" data-login=\"{1}\" data-userid=\"{0}\">"; trTemplate += " <td class=\"select mHide\"><div class=\"checkbox\"></div></td>"; trTemplate += " <td class=\"ident10\">{2}</td>"; trTemplate += " <td class=\"tHide mHide\">{1}</td>"; trTemplate += " <td class=\"tHide mHide\"><button class=\"a-btn\" onclick=\"window.location = '" + ApplicationVirtualPath + "admin/users/{0}/';\">Abrir</button> <button href=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/action/delete_user/{0}/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"a-btn confirm-action\" confirm-title=\"Exclusão\" confirm-text=\"Deseja excluir definitivamente o vínculo do usuário '{2}' com o perfil de sistema '" + selectedRole.result.info.name + "'?\" ok=\"Excluir\" cancel=\"Cancelar\">Excluir</button></td>"; trTemplate += " </tr>"; try { String rData = ""; rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "systemrole.users", parameters = new { page_size = pageSize, page = page, roleid = roleId }, id = 1 }); String jData = ""; using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); if (String.IsNullOrWhiteSpace(jData)) { throw new Exception(""); } SearchResult ret2 = JSON.Deserialize <SearchResult>(jData); if (ret2 == null) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found")); //ret = new WebJsonResponse("", MessageResource.GetMessage("user_not_found"), 3000, true); hasNext = false; } else if (ret2.error != null) { eHtml += String.Format(errorTemplate, ret2.error.data); //ret = new WebJsonResponse("", ret2.error.data, 3000, true); hasNext = false; } else if (ret2.result == null || (ret2.result.Count == 0 && page == 1)) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("user_not_found")); hasNext = false; } else { foreach (UserData user in ret2.result) { html += String.Format(trTemplate, user.userid, user.login, user.full_name); } if (ret2.result.Count < pageSize) { hasNext = false; } } } catch (Exception ex) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("api_error")); //ret = new WebJsonResponse("", MessageResource.GetMessage("api_error"), 3000, true); } if (page == 1) { html += "</tbody></table>"; html += "<span class=\"empty-results content-loading user-list-loader hide\"></span>"; contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); } else { contentRet = new WebJsonResponse("#content-wrapper tbody", (eHtml != "" ? eHtml : html), true); } contentRet.js = "$( document ).unbind('end_of_scroll.loader_usr');"; if (hasNext) { contentRet.js += "$( document ).bind( 'end_of_scroll.loader_usr', function() { $( document ).unbind('end_of_scroll.loader_usr'); $('.user-list-loader').removeClass('hide'); iamadmin.getPageContent2( { page: " + ++page + ", search:'' }, function(){ $('.user-list-loader').addClass('hide'); } ); });"; } break; case "add_user": html = "<h3>Adição de usuário</h3>"; html += "<form id=\"form_add_user\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/" + roleId + "/action/add_user/\"><div class=\"no-tabs pb10\">"; html += "<div class=\"form-group\" id=\"add_user\"><label>Usuário</label><input id=\"add_user_text\" placeholder=\"Digite o nome do usuário\" type=\"text\"\"></div>"; html += "<div class=\"clear-block\"></div></div>"; html += "<h3>Usuários selecionados</h3>"; html += "<div id=\"box-container\" class=\"box-container\"><div class=\"no-tabs pb10 none\">"; html += "Nenhum usuário selecionado"; html += "</div></div>"; html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Cadastrar</button> <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "\" class=\"button link floatleft\">Cancelar</a></form>"; contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); contentRet.js = "iamadmin.autoCompleteText('#add_user_text', '" + ApplicationVirtualPath + "admin/users/content/search_user/', null , function(thisId, selectedItem){ $(thisId).val(''); $('.none').remove(); $('.box-container').append(selectedItem.html); } )"; break; case "permissions": html += "<h3>Permissões"; if ((hashData.GetValue("edit") != "1") && (!selectedRole.result.info.enterprise_admin)) { html += "<div class=\"btn-box\"><div class=\"a-btn ico icon-change\" onclick=\"iamadmin.changeHash( 'edit/1' );\">Editar</div></div>"; } html += "</h3>"; html += "<form id=\"form_add_role\" method=\"post\" action=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/action/change_permissions/\">"; html += "<div class=\"no-tabs fields\"><table><tbody>"; String infoTemplate2 = "<tr><td class=\"colfull\">{0}</td></tr>"; if (selectedRole.result.info.enterprise_admin) { html += String.Format(infoTemplate2, "<span style=\"text-align: center; width: 100%; display:block;\">Esto perfil tem permissão de administração total nesta empresa, desta forma não necessita configurar permissões específicas</span>"); } else { String rData = SafeTrend.Json.JSON.Serialize2(new { jsonrpc = "1.0", method = "systemrole.permissionstree", parameters = new { }, id = 1 }); String jData = ""; using (IAMDatabase database = new IAMDatabase(IAMDatabase.GetWebConnectionString())) jData = WebPageAPI.ExecuteLocal(database, this, rData); SystemRolePermissionsTree retPTree = JSON.Deserialize <SystemRolePermissionsTree>(jData); if (retPTree == null) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("permissions_not_found")); } else if (retPTree.error != null) { eHtml += String.Format(errorTemplate, retPTree.error.data); } else if (retPTree.result == null) { eHtml += String.Format(errorTemplate, MessageResource.GetMessage("permissions_not_found")); } else { if (hashData.GetValue("edit") == "1") { String field = ""; field += "<div id=\"tree\">"; field += "<ul>"; foreach (SystemRolePermissionModule module in retPTree.result) { if (module.submodules.Count > 0) { field += " <li class=\"" + (module.submodules.Count == 0 ? "no-chield" : "") + "\"><input type=\"checkbox\"><span>" + module.name + "</span>"; field += " <ul>"; foreach (SystemRolePermissionSubModule subModule in module.submodules) { if (subModule.permissions.Count > 0) { field += " <li class=\"" + (subModule.permissions.Count == 0 ? "no-chield" : "") + "\"><input type=\"checkbox\"><span>" + subModule.name + "</span>"; field += " <ul>"; foreach (SystemRolePermissionItem permission in subModule.permissions) { field += " <li class=\"no-chield\"><input type=\"checkbox\" name=\"permission_id\" value=\"" + permission.permission_id + "\" " + (selectedRole.result.info.permissions != null && selectedRole.result.info.permissions.Exists(p => (p.permission_id == permission.permission_id)) ? "checked" : "") + "><span>" + permission.name + "</span></li>"; } field += " </ul>"; field += "</li>"; } } field += " </ul>"; field += "</li>"; } } field += "</ul>"; field += "</div>"; html += String.Format(infoTemplate2, field); js = "$('#tree').tree({ dnd: false });"; } else { foreach (SystemRolePermissionModule module in retPTree.result) { if (module.submodules.Count > 0) { foreach (SystemRolePermissionSubModule subModule in module.submodules) { if (subModule.permissions.Count > 0) { List <String> per = new List <string>(); foreach (SystemRolePermissionItem permission in subModule.permissions) { if (selectedRole.result.info.permissions != null && selectedRole.result.info.permissions.Exists(p => (p.permission_id == permission.permission_id))) { per.Add(permission.name); } } if (per.Count == 0) { per.Add("Nenhuma permissão definida"); } html += String.Format(infoTemplate, module.name + "/" + subModule.name, String.Join(", ", per)); } } } } } } } html += "</tbody></table></div>"; if (hashData.GetValue("edit") == "1") { html += "<button type=\"submit\" id=\"user-profile-password-save\" class=\"button secondary floatleft\">Salvar</button> <a href=\"" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/permissions/\" class=\"button link floatleft\">Cancelar</a></form>"; } contentRet = new WebJsonResponse("#content-wrapper", (eHtml != "" ? eHtml : html)); contentRet.js = js; break; } } } } break; case "sidebar": if (menu1 != null) { html += "<div class=\"sep\"><div class=\"section-nav-header\">"; html += " <div class=\"crumbs\">"; html += " <div class=\"subject subject-color\">"; html += " <a href=\"" + menu1.HRef + "\">" + menu1.Name + "</a>"; html += " </div>"; if (menu2 != null) { html += " <div class=\"topic topic-color\">"; html += " <a href=\"" + menu2.HRef + "\">" + menu2.Name + "</a>"; html += " </div>"; } html += " </div>"; if (menu3 != null) { html += " <div class=\"crumbs tutorial-title\">"; html += " <h2 class=\"title tutorial-color\"><a href=\"" + menu3.HRef + "\">" + menu3.Name + "</a></h2>"; html += " </div>"; } html += "</div></div>"; } if (!newItem) { html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/system_roles/new/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Novo perfil</button></div>"; if (selectedRole != null) { if (filter != "add_user") { html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/add_user/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Adicionar usuários</button></div>"; } if (filter != "permissions") { html += "<div class=\"sep\"><button class=\"a-btn-big a-btn\" type=\"button\" onclick=\"window.location='" + ApplicationVirtualPath + "admin/system_roles/" + selectedRole.result.info.role_id + "/permissions/" + (Request.Form["hashtag"] != null ? "#" + Request.Form["hashtag"].ToString() : "") + "'\">Alterar permissões</button></div>"; } } } contentRet = new WebJsonResponse("#main aside", html); break; case "mobilebar": break; case "buttonbox": break; } if (contentRet != null) { if (!String.IsNullOrWhiteSpace((String)Request["cid"])) { contentRet.callId = (String)Request["cid"]; } Retorno.Controls.Add(new LiteralControl(contentRet.ToJSON())); } }