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 LocalConfig(); 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); } try { MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.closeDB(); } catch (Exception ex) { StopOnError("Falha ao acessar o banco de dados", ex); } /************* * Inicia timer que processa os arquivos */ inboundTimer = new Timer(new TimerCallback(InboundTimer), null, 1000, 900000); outboundTimer = new Timer(new TimerCallback(OutboundTimer), null, 1000, 900000); }
private void InboundTimer(Object state) { TextLog.Log("Server", "Starting inbound timer"); try { DirectoryInfo inDir = new DirectoryInfo(Path.Combine(basePath, "In")); if (!inDir.Exists) { TextLog.Log("Server", "\t0 files to process"); return; } FileInfo[] files = inDir.GetFiles("*.iamreq"); TextLog.Log("Server", "\t" + files.Length + " files to process"); MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); foreach (FileInfo f in files) { JSONRequest req = null; try { using (FileStream fs = f.OpenRead()) req = JSON.GetRequest(fs); if ((req.host == null) || (req.host == "")) { TextLog.Log("Server", "Paramter 'host' is empty on " + f.Name); continue; } if ((req.enterpriseid == null) || (req.enterpriseid == "")) { TextLog.Log("Server", "Paramter 'enterpriseid' is empty on " + f.Name); continue; } try { Int64 tst = Int64.Parse(req.enterpriseid); } catch { if ((req.enterpriseid == null) || (req.enterpriseid == "")) { TextLog.Log("Server", "Paramter 'enterpriseid' is not Int64 " + f.Name); continue; } } ProxyConfig config = new ProxyConfig(true); config.GetDBCertConfig(db.conn, 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; TextLog.Log("Server", "Error on decrypt package data " + f.Name + " for enterprise " + req.enterpriseid + " and proxy " + req.host + ", " + ex.Message); } if (jData == null) { continue; } Int32 contextCol = jData.GetKeyIndex("context"); Int32 uriCol = jData.GetKeyIndex("uri"); Int32 importidCol = jData.GetKeyIndex("importid"); Int32 registryidCol = jData.GetKeyIndex("registryid"); Int32 datanameCol = jData.GetKeyIndex("dataname"); Int32 datavalueCol = jData.GetKeyIndex("datavalue"); Int32 datatypeCol = jData.GetKeyIndex("datatype"); if (uriCol == -1) { TextLog.Log("Server", "Erro on find column 'uri' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (importidCol == -1) { TextLog.Log("Server", "Erro on find column 'importid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (registryidCol == -1) { TextLog.Log("Server", "Erro on find column 'registryid' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datanameCol == -1) { TextLog.Log("Server", "Erro on find column 'dataname' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datavalueCol == -1) { TextLog.Log("Server", "Erro on find column 'datavalue' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } if (datatypeCol == -1) { TextLog.Log("Server", "Erro on find column 'datatype' in " + f.Name + " enterprise " + req.enterpriseid + " and proxy " + req.host); continue; } DateTime date = DateTime.Now; //Realiza a importação no modelo BulkInsert por melhor desempenho do banco DataTable dtBulk = new DataTable(); dtBulk.Columns.Add(new DataColumn("date", typeof(DateTime))); dtBulk.Columns.Add(new DataColumn("plugin_uri", typeof(String))); dtBulk.Columns.Add(new DataColumn("context_id", typeof(Int64))); dtBulk.Columns.Add(new DataColumn("import_id", typeof(String))); dtBulk.Columns.Add(new DataColumn("registry_id", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_name", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_value", typeof(String))); dtBulk.Columns.Add(new DataColumn("data_type", typeof(String))); foreach (String[] dr in jData.data) { dtBulk.Rows.Add(new Object[] { date, dr[uriCol], Int64.Parse(dr[contextCol]), dr[importidCol], dr[registryidCol], dr[datanameCol], dr[datavalueCol], dr[datatypeCol] }); } db.BulkCopy(dtBulk, "collector_imports"); TextLog.Log("Server", "Imported " + dtBulk.Rows.Count + " registers for enterprise " + req.enterpriseid + " and proxy " + req.host); dtBulk.Dispose(); dtBulk = null; jData = null; f.Delete(); } else { TextLog.Log("Server", "Proxy config not found for enterprise " + req.enterpriseid + " and proxy " + req.host); } config = null; } finally { req = null; } } db.closeDB(); } catch (Exception ex) { TextLog.Log("Server", "Error on inbound timer " + ex.Message); } finally { TextLog.Log("Server", "Finishing inbound timer"); } }
static void Main(string[] args) { 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); } /************* * Gera os certificados do servidor */ MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); db.Timeout = 300; Int64 entityId = 0; if (args.Length > 0) { Int64.TryParse(args[0], out entityId); } DataTable tmp = db.Select(String.Format("select e.*, e1.id enterprise_id from entity e inner join context c on c.id = e.context_id inner join enterprise e1 on e1.id = c.enterprise_id where e.id = {0}", entityId)); if (tmp == null) { StopOnError("Select is null", null); } if (tmp.Rows.Count == 0) { StopOnError("Select is empty", null); } EnterpriseKeyConfig sk = new EnterpriseKeyConfig(db.conn, (Int64)tmp.Rows[0]["entity_id"]); Int64 context = (Int64)tmp.Rows[0]["context_id"]; Int64 enterpriseId = (Int64)tmp.Rows[0]["enterprise_id"]; Console.WriteLine("##############################"); Console.WriteLine("C Pwd: " + tmp.Rows[0]["password"].ToString()); Console.WriteLine(""); Console.WriteLine("##############################"); using (CryptApi cApi = CryptApi.ParsePackage(sk.ServerPKCS12Cert, Convert.FromBase64String(tmp.Rows[0]["password"].ToString()))) Console.WriteLine("Pwd: " + Encoding.UTF8.GetString(cApi.clearData)); String text = ""; do { //Console.Clear(); Console.Write("Deseja redefinir a senha do usuário? (Y/N): "); text = Console.ReadLine().Trim(); if (text.ToLower() == "y") { break; } else if (text.ToLower() == "n") { text = ""; break; } else { text = ""; } } while (text == ""); if (text.ToLower() == "y") { BuildPassword(db, null, context, entityId, enterpriseId); } db.closeDB(); StopOnError("", null); }
static void Main(string[] args) { 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 { MSSQLDB db = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db.openDB(); 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 */ MSSQLDB db2 = new MSSQLDB(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword); db2.openDB(); DataTable created = db2.Select("select * from vw_entity_mails where create_date between CONVERT(datetime, convert(varchar(10),DATEADD(DAY, -1, GETDATE()),120) + ' 00:00:00', 120) and CONVERT(datetime, convert(varchar(10),getdate(),120) + ' 23:59:59', 120) order by context_name, full_name"); DataTable all = db2.Select("select * from vw_entity_mails order by context_name, full_name"); Dictionary <String, String> title = new Dictionary <string, string>(); title.Add("context_name", "Contexto"); title.Add("full_name", "Nome completo"); title.Add("login", "Login"); title.Add("create_date", "Data de criação"); title.Add("last_login", "Ultimo login"); title.Add("mail", "E-mail"); title.Add("locked", "Bloqueado"); ReportBase rep1 = new ReportBase(created, title); ReportBase rep2 = new ReportBase(all, title); List <Attachment> atts = new List <Attachment>(); using (MemoryStream ms1 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetTXT()))) using (MemoryStream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(rep1.GetXML("Usuários", "")))) using (MemoryStream ms3 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetTXT()))) using (MemoryStream ms4 = new MemoryStream(Encoding.UTF8.GetBytes(rep2.GetXML("Usuários", "")))) { atts.Add(new Attachment(ms1, "created.txt")); atts.Add(new Attachment(ms2, "created.xls")); atts.Add(new Attachment(ms3, "all.txt")); atts.Add(new Attachment(ms4, "all.xls")); List <String> to = new List <string>(); to.Add("*****@*****.**"); to.Add("*****@*****.**"); to.Add("*****@*****.**"); sendEmail(db2, "Listagem de usuários em " + DateTime.Now.ToString("dd/MM/yyyy"), to, created.Rows.Count + " usuários criados de " + DateTime.Now.AddDays(-1).ToString("dd/MM/yyyy") + " até " + DateTime.Now.ToString("dd/MM/yyyy"), false, atts); } db2.closeDB(); }