Exemplo n.º 1
0
        private void LicTimer(Object oData)
        {
            using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                using (ServerKey2 sk = new ServerKey2(db2.Connection))
                    try
                    {
                        db2.openDB();

                        TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now;

                        if (ts.TotalDays < 60)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Fatal, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 180)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Error, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }
                        else if (ts.TotalDays < 360)
                        {
                            db2.AddUserLog(LogKey.Certificate_Error, null, "Engine", UserLogLevel.Warning, 0, 0, 0, 0, 0, 0, 0, "Server certificate will expire in " + sk.ServerCert.NotAfter.ToString("yyyy-MM-dd") + ", please renew", sk.ServerInstallationKey.AbsoluteUri);
                        }

                        db2.closeDB();
                    }
                    catch { }
        }
Exemplo n.º 2
0
        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 { }
            }
        }
Exemplo n.º 3
0
        protected override void OnStart(string[] args)
        {
            /*************
             * Carrega configurações
             */

            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }

            Int32 cnt      = 0;
            Int32 stepWait = 15000;

            while (cnt <= 10)
            {
                try
                {
                    IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);
                    db.openDB();

                    db.ServiceStart("Engine", null);

                    db.closeDB();

                    break;
                }
                catch (Exception ex)
                {
                    if (cnt < 10)
                    {
                        TextLog.Log("Engine", "Falha ao acessar o banco de dados: " + ex.Message);
                        Thread.Sleep(stepWait);
                        stepWait = stepWait * 2;
                        cnt++;
                    }
                    else
                    {
                        StopOnError("Falha ao acessar o banco de dados", ex);
                    }
                }
            }



            /*************
             * Gera os certificados do servidor
             * Verifica se o certificade está próximo de vencer
             */
            IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword);

            db2.openDB();
            ServerKey2 sk = new ServerKey2(db2.Connection);

            TimeSpan ts = sk.ServerCert.NotAfter - DateTime.Now;

            if (ts.TotalDays < 360)
            {
                //Inicia o timer que ficará gerando evento
                licTimer = new Timer(new TimerCallback(LicTimer), null, 200, 86400000); //a cada 24 Horas caso este processo não for reiniciado
            }

            db2.closeDB();


            intoTimer = new Timer(new TimerCallback(InfoTimer), null, 200, 900); //a cada 15 minutos

            /*************
             * Inicia as classes de processamento
             */

            RegistryImporter imp = new RegistryImporter(localConfig);

            imp.Start();

            TimeAccessControl acl = new TimeAccessControl(localConfig);

            acl.Start();
        }
Exemplo n.º 4
0
        private void InfoTimer(Object oData)
        {
            TimeSpan tsInfo = lastInfo - new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0);

            if (infoExec || ((Int32)tsInfo.TotalDays == 0))
            {
                return;
            }

            infoExec = true;

            using (IAMDatabase db2 = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
                using (ServerKey2 sk = new ServerKey2(db2.Connection))
                    try
                    {
                        db2.openDB();

                        List <Object> lics    = new List <Object>();
                        Version       version = new Version("0.0");

                        try
                        {
                            DataTable dtLicCount = db2.ExecuteDataTable("select count(e.id) qty, c.enterprise_id from entity e with(nolock) inner join context c with(nolock) on c.id = e.context_id where e.deleted = 0 group by c.enterprise_id");
                            if (dtLicCount != null)
                            {
                                foreach (DataRow dr in dtLicCount.Rows)
                                {
                                    String        message = "";
                                    List <String> data    = new List <string>();

                                    DataTable dtLic = db2.ExecuteDataTable("select * from license where enterprise_id in (0, " + dr["enterprise_id"] + ")");
                                    if (dtLic == null)
                                    {
                                        message = "Error on get licenses on server";
                                    }

                                    if (dtLic.Rows.Count == 0)
                                    {
                                        message = "License list is empty";
                                    }

                                    foreach (DataRow dr2 in dtLic.Rows)
                                    {
                                        data.Add(dr2["license_data"].ToString());
                                    }

                                    //Resgata do banco a contagem atual de entidades

                                    var eItem = new {
                                        id      = dr["enterprise_id"].ToString(),
                                        message = message,
                                        entity  = dr["qty"],
                                        data    = data
                                    };

                                    lics.Add(eItem);
                                }
                            }


                            try
                            {
                                version = Assembly.GetEntryAssembly().GetName().Version;
                            }
                            catch { }

                            var info = new
                            {
                                date             = DateTime.UtcNow.ToString("o"),
                                product          = "SafeId",
                                version          = version.ToString(),
                                installation_key = sk.ServerInstallationKey.AbsoluteUri,
                                server_cert      = sk.ServerCertString,
                                licences         = lics
                            };

                            String jData = JSON.Serialize2(info);

                            WebClient client = new WebClient();
                            client.UploadData("https://licencing.safetrend.com.br/si/", Encoding.UTF8.GetBytes(jData));

                            lastInfo = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, 0, 0, 0);
                        }
                        catch { }
                        finally
                        {
                            db2.closeDB();
                        }
                    }
                    catch { }

            infoExec = false;
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            ServerLocalConfig localConfig;

            /*************
             * Carrega configurações
             */

            localConfig = new ServerLocalConfig();
            localConfig.LoadConfig();

            if ((localConfig.SqlServer == null) || (localConfig.SqlServer.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlserver' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlDb == null) || (localConfig.SqlDb.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqldb' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlUsername == null) || (localConfig.SqlUsername.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlusername' não localizado no arquivo de configuração 'server.conf'", null);
            }

            if ((localConfig.SqlPassword == null) || (localConfig.SqlPassword.Trim() == ""))
            {
                StopOnError("Parâmetro 'sqlpassword' não localizado no arquivo de configuração 'server.conf'", null);
            }


            using (IAMDatabase db = new IAMDatabase(localConfig.SqlServer, localConfig.SqlDb, localConfig.SqlUsername, localConfig.SqlPassword))
            {
                try
                {
                    db.openDB();
                }
                catch (Exception ex)
                {
                    StopOnError("Erro on acess database ", ex);
                }

                try
                {
                    ServerKey2 sk = new ServerKey2(db.Connection);
                    sk.RenewCert(db.Connection);

                    Console.WriteLine("Renewed certificate successfully");
                    TextLog.Log("RenewServerCert", "Renewed certificate successfully");
                }
                catch (Exception ex)
                {
                    UnhandledException.WriteEvent(null, ex, false);
                    StopOnError("Error on renew certificate ", ex);
                }
            }

            Console.WriteLine("Pressione ENTER para finalizar");
            Console.ReadLine();
        }