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 { } } }
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(); }