private void frmDatabaseLoginPrompt_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult != DialogResult.OK) { _dbEngineUtil = null; } }
//private void WebInstaller_BeforeInstall(object sender, InstallEventArgs e) { // ProcessStartInfo psiASPNET = new ProcessStartInfo("aspnet_regiis.exe", " /i"); // try { // psiASPNET.UseShellExecute = true; // string windir = Environment.GetEnvironmentVariable("WINDIR"); // psiASPNET.WorkingDirectory = windir + @"\Microsoft.NET\Framework\v2.0.50727\"; // Process p2 = Process.Start(psiASPNET); // p2.WaitForExit(); // // stateSaver["ASPNET_REGIIS_EXIT_CODE"] = p2.ExitCode; // } catch (Exception ex2) { // Context.LogMessage("Exception registering asp.net with IIS: " + ex2.Message); // throw; // } //} private void WebInstaller_AfterInstall(object sender, InstallEventArgs e) { try { string targetDir = getTargetDir(); // update the config file... string configFile = targetDir + "web.config"; if (File.Exists(configFile)) { string contents = File.ReadAllText(configFile); // look up engine from registry (assumes database has been installed already) string engine = "" + Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\GRIN-Global", "DatabaseEngine", "") as string; string connectionString = "" + Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\GRIN-Global", "DatabaseConnectionString", "") as string; string finalConnectionString = connectionString.Replace("__USERID__", "gg_user").Replace("__PASSWORD__", "gg_user_passw0rd!"); string appSetting = String.Format(@"<add providerName=""{0}"" name=""DataManager"" connectionString=""{1}"" />", engine, finalConnectionString); contents = contents.Replace("<!-- __CONNECTIONSTRING__ -->", appSetting); contents = contents.Replace("<!-- __COMMENT__ -->", "<!-- TESTING "); contents = contents.Replace("<!-- __ENDCOMMENT__ -->", " -->"); File.WriteAllText(configFile, contents); try { // need to make the ~/uploads folder writable (for images // create a batch file to do that for us (thanks to cacls requiring a 'Y' to confirm) string tempFile = Path.GetTempFileName() + ".bat"; // give ASPNET user full control to the ~/uploads folder string uploadsDir = @"""" + Toolkit.ResolveDirectoryPath(targetDir + @"\uploads", true) + @""""; // vista needs "IUSR", XP needs "ASPNET" string userName = (Toolkit.IsWindowsVistaOrLater ? "IUSR" : "ASPNET"); File.WriteAllText(tempFile, String.Format("echo y| cacls.exe {0} /T /C /G {1}:F", uploadsDir, userName)); string output = Toolkit.ExecuteProcess(tempFile, null, null); } catch { // eat problems with this for now, have to release (2009-07-23) } try { var engineName = Utility.GetDatabaseEngine(Context, e.SavedState, false); var instanceName = Utility.GetDatabaseInstanceName(Context, e.SavedState); var dbEngineUtil = DatabaseEngineUtil.CreateInstance(engineName, null, instanceName); string file = targetDir + engine + @"_create_users.sql"; string replaced = File.ReadAllText(file).Replace("__MACHINENAME__", Dns.GetHostName()).Replace("__WWWUSER__", Toolkit.IsWindowsVistaOrLater ? "NETWORKSERVICE" : "ASPNET"); File.WriteAllText(file, replaced); dbEngineUtil.ExecuteSqlFile(null, true, file); // MessageBox.Show("creating users result - " + output); } catch (Exception exCreateUsers) { Context.LogMessage("Exception creating users: " + exCreateUsers.Message); } } } finally { } }
private void button2_Click(object sender, EventArgs e) { try { var dbeu = DatabaseEngineUtil.CreateInstance("sqlserver", Toolkit.ResolveFilePath("~/gghelper.exe", false), textBox1.Text); MessageBox.Show("Info:\nServiceName=" + dbeu.ServiceName + "\nBase Directory=" + dbeu.BaseDirectory + "\nBinDirectory=" + dbeu.BinDirectory + "\nDataDirectory=" + dbeu.DataDirectory + "\nEngineName=" + dbeu.EngineName + "\nFriendlyName=" + dbeu.FriendlyName + "\nFullPathToHelperExe=" + dbeu.FullPathToHelperExe + "\nInstallParameter=" + dbeu.InstallParameter + "\nSuperUserName="******"Error: " + ex.Message + "\n" + (ex.InnerException == null ? "" : ex.InnerException.Message)); } }
private void createDatabaseUser(frmSplash splash, DatabaseEngineUtil dbEngineUtil, string superUserPassword, string userName, string userPassword) { try { splash.ChangeText(getDisplayMember("createDatabaseUser{start}", "Creating database users as needed...")); var dnsName = Dns.GetHostName(); var netBIOSName = Toolkit.Cut(dnsName, 0, 15); var output = ""; if (dbEngineUtil is SqlServerEngineUtil) { // SQL Server and using Windows Authentication... // XP output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "NETWORK SERVICE", netBIOSName, null, false, true); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user NETWORK SERVICE allowed from machine " + netBIOSName + "... Result: " + output, EventLogEntryType.Information); output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "ASPNET", netBIOSName, null, false, true); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user ASPNET allowed from machine " + netBIOSName + "... Result: " + output, EventLogEntryType.Information); // Vista output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "NETWORK SERVICE", "NT AUTHORITY", null, false, true); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user NETWORK SERVICE allowed from machine NT AUTHORITY" + "... Result: " + output, EventLogEntryType.Information); output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "SYSTEM", "NT AUTHORITY", null, false, true); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user SYSTEM allowed from machine NT AUTHORITY" + "... Result: " + output, EventLogEntryType.Information); // Windows 7 output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "DEFAULTAPPPOOL", "IIS AppPool", null, false, true); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user DEFAULTAPPPOOL allowed from machine " + netBIOSName + "... Result: " + output, EventLogEntryType.Information); // SQL Server mixed mode... output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, netBIOSName, userPassword, false, false); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user " + userName + " allowed from machine " + netBIOSName + "... Result: " + output, EventLogEntryType.Information); } else if (dbEngineUtil is MySqlEngineUtil) { output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, "%", userPassword, false, false); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user " + userName + " allowed from machine % ... Result: " + output, EventLogEntryType.Information); } else if (dbEngineUtil is OracleEngineUtil) { output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, null, userPassword, false, false); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user " + userName + " allowed from machine [null] ... Result: " + output, EventLogEntryType.Information); } else if (dbEngineUtil is PostgreSqlEngineUtil) { output = dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, dnsName, userPassword, false, false); EventLog.WriteEntry("GRIN-Global Web Application", "Created db user " + userName + " allowed from machine " + dnsName + "... Result: " + output, EventLogEntryType.Information); } } catch (Exception exCreateUsers) { //Context.LogMessage("Exception creating users: " + exCreateUsers.Message); EventLog.WriteEntry("GRIN-Global Web Application", "Exception creating user(s): " + exCreateUsers.Message, EventLogEntryType.Error); //MessageBox.Show("could not create db user: " + exCreateUsers.Message); } }
private void button1_Click(object sender, EventArgs e) { try { var dbeu = DatabaseEngineUtil.CreateInstance("sqlserver", Toolkit.ResolveFilePath("~/gghelper.exe", false), textBox1.Text); dbeu.StopService(); dbeu.StartService(); MessageBox.Show("SQL Server instance '" + textBox1.Text + "' restarted."); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message + "\n" + (ex.InnerException == null ? "" : ex.InnerException.Message)); } }
public DialogResult ShowDialog(IWin32Window owner, DatabaseEngineUtil dbEngineUtil, bool loadFromRegistry, bool writeToRegistryOnSave, bool clientMode, string superUserPassword, bool?useWindowsAuthentication, bool enableAutoLogin, bool showSkipDatabase) { _saveToRegistry = writeToRegistryOnSave; btnSkip.Visible = showSkipDatabase; ClientMode = clientMode; if (dbEngineUtil == null) { try { if (loadFromRegistry) { this.loadFromRegistry(); refreshEngineUtil(true); if (useWindowsAuthentication != null) { _dbEngineUtil.UseWindowsAuthentication = (bool)useWindowsAuthentication; } chkWindowsAuthentication.Checked = _dbEngineUtil.UseWindowsAuthentication; txtPassword.Text = superUserPassword; if (enableAutoLogin) { if (_dbEngineUtil.UseWindowsAuthentication || !String.IsNullOrEmpty(txtPassword.Text)) { if (_dbEngineUtil.TestLogin(txtUsername.Text, txtPassword.Text) == null) { // valid login, do not prompt, just return it's valid return(DialogResult.OK); } } } } } catch (Exception ex) { MessageBox.Show(getDisplayMember("ShowDialog{failed}", "Error showing database connection prompt: {0}", ex.Message)); throw; } } else { EngineName = dbEngineUtil.EngineName; txtServerName.Text = dbEngineUtil.ServerName; txtPort.Text = dbEngineUtil.Port.ToString(); //if (dbEngineUtil is SqlServerEngineUtil) { // txtSID.Text = (dbEngineUtil as SqlServerEngineUtil).InstanceName; //} else { // txtSID.Text = ""; //} chkWindowsAuthentication.Checked = (dbEngineUtil.UseWindowsAuthentication || (useWindowsAuthentication == true)) && (dbEngineUtil is SqlServerEngineUtil); } return(this.ShowDialog(owner)); }
public static string GetDatabaseEngine(InstallContext ctx, IDictionary state, bool throwExceptionIfNotFound) { string ret = null; StringBuilder sb = new StringBuilder(); if (ctx != null) { ret = ctx.Parameters["engine"]; sb.AppendLine("\r\nContext.Parameters['engine']=" + ret); if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = ctx.Parameters["ENGINE"]; sb.AppendLine("Context.Parameters['ENGINE']=" + ret); } } if (!DatabaseEngineUtil.IsValidEngine(ret) && state != null) { ret = state["ENGINE"] as string; sb.AppendLine("state['ENGINE']=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(RootRegistryKey, "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + RootRegistryKey + "DatabaseEngine)=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(RootRegistryKey + @"\Database", "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + RootRegistryKey + @"\Database\DatabaseEngine)=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { if (throwExceptionIfNotFound) { throw new InvalidOperationException(@"GetDatabaseEngine could not resolve a valid engine name. Inspected locations/values:" + sb.ToString()); } } else { if (ctx != null) { ctx.Parameters["engine"] = ret; } } return(ret); }
private void btnTest5_Click(object sender, EventArgs e) { var dbEngineUtil = DatabaseEngineUtil.CreateInstance("sqlserver", Toolkit.GetPathToUACExe(), "sqlexpress"); dbEngineUtil.UseWindowsAuthentication = true; MessageBox.Show(dbEngineUtil.BaseDirectory + "\n" + dbEngineUtil.BinDirectory + "\n" + dbEngineUtil.DataDirectory + "\n" + dbEngineUtil.Port + "\n" + dbEngineUtil.ServerName + "\n" + dbEngineUtil.ServiceName + "\n" + dbEngineUtil.UseWindowsAuthentication); try { var output = dbEngineUtil.CreateDatabase(null, "gringlobal"); MessageBox.Show("output=" + output); } catch (Exception ex) { MessageBox.Show("error: " + ex.Message + "\n\n" + ex.ToString()); } }
private void button1_Click(object sender, EventArgs e) { var dsc = new DataConnectionSpec(ddlProvider.Text, null, null, txtValue.Text); var f = new frmDatabaseLoginPrompt(); var util = DatabaseEngineUtil.CreateInstance(dsc.ProviderName, Toolkit.ResolveFilePath(@".\gguac.exe", false), "SQLExpress"); var dr = f.ShowDialog(this, util, false, false, false, null, null, false, false); if (dr == DialogResult.OK) { txtValue.Text = f.txtConnectionstring.Text; ddlProvider.SelectedIndex = ddlProvider.FindString(f.DatabaseEngineUtil.EngineName); } }
private void createDatabaseUser(frmSplash splash, DatabaseEngineUtil dbEngineUtil, string superUserPassword, string userName, string userPassword) { try { splash.ChangeText(getDisplayMember("createDatabaseUser{start}", "Creating database users as needed...")); var dnsName = Dns.GetHostName(); if (dbEngineUtil is SqlServerEngineUtil) { var netBIOSName = Toolkit.Cut(dnsName, 0, 15); // SQL Server, Integrated authority -- XP dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "NETWORK SERVICE", netBIOSName, null, false, true); dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "ASPNET", netBIOSName, null, false, true); // SQL Server, Integrated authority -- Vista dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "NETWORK SERVICE", "NT AUTHORITY", null, false, true); dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "SYSTEM", "NT AUTHORITY", null, false, true); // SQL Server, Integrated authority -- Windows 7 dbEngineUtil.CreateUser(superUserPassword, "gringlobal", "DEFAULTAPPPOOL", "IIS AppPool", null, false, true); // SQL Server mixed mode dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, netBIOSName, userPassword, false, false); } else if (dbEngineUtil is MySqlEngineUtil) { dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, "*", userPassword, false, false); } else if (dbEngineUtil is OracleEngineUtil) { dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, null, userPassword, false, false); } else if (dbEngineUtil is PostgreSqlEngineUtil) { dbEngineUtil.CreateUser(superUserPassword, "gringlobal", userName, dnsName, userPassword, false, false); } } catch (Exception exCreateUsers) { //Context.LogMessage("Exception creating users: " + exCreateUsers.Message); //MessageBox.Show("could not create db user: "******"GRIN-Global Search Engine", "Exception creating users: " + exCreateUsers.Message); } }
private static string GetDatabaseEngine(InstallContext ctx, IDictionary state, bool throwExceptionIfNotFound) { string ret = null; StringBuilder sb = new StringBuilder(); if (ctx != null) { if (ctx.Parameters["action"] == "uninstall") { // default to using registry entries if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(Utility.RootRegistryKey + @"\Database", "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + Utility.RootRegistryKey + @"\Database\DatabaseEngine)=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(Utility.RootRegistryKey, "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + Utility.RootRegistryKey + "DatabaseEngine)=" + ret); } } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = ctx.Parameters["engine"]; sb.AppendLine("\r\nContext.Parameters['engine']=" + ret); if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = ctx.Parameters["ENGINE"]; sb.AppendLine("Context.Parameters['ENGINE']=" + ret); } } } if (!DatabaseEngineUtil.IsValidEngine(ret) && state != null) { ret = state["ENGINE"] as string; sb.AppendLine("state['ENGINE']=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(Utility.RootRegistryKey, "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + Utility.RootRegistryKey + "DatabaseEngine)=" + ret); } if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = Registry.GetValue(Utility.RootRegistryKey + @"\Database", "DatabaseEngine", "") as string; sb.AppendLine("Registry.GetValue(" + Utility.RootRegistryKey + @"\Database\DatabaseEngine)=" + ret); } // HACK: always make it sqlserver until we have other options available... if (!DatabaseEngineUtil.IsValidEngine(ret)) { ret = "sqlserver"; } if (!DatabaseEngineUtil.IsValidEngine(ret)) { if (throwExceptionIfNotFound) { throw new InvalidOperationException(@"GetDatabaseEngine could not resolve a valid engine name. Inspected locations/values:" + sb.ToString()); } } else { if (ctx != null) { ctx.Parameters["engine"] = ret; } } return(ret); }
private static void precacheLookups(string[] args) { string lastSqlRan = ""; try { var providerName = args[1]; var connectionString = args[2]; var serverName = args[3]; if (String.IsNullOrEmpty(providerName)) { showUsage(); return; } if (String.IsNullOrEmpty(connectionString)) { showUsage(); return; } if (String.IsNullOrEmpty(serverName)) { showUsage(); return; } var dsc = new DataConnectionSpec(providerName, null, null, connectionString); string newDatabaseName = "GRINGlobal_" + serverName.Replace(".", "_").Replace("-", "_").Replace(":", "_"); var dbEngineUtil = DatabaseEngineUtil.CreateInstance(providerName, Toolkit.ResolveFilePath("~/gguac.exe", false), null); if (dbEngineUtil is SqlServerEngineUtil) { if (String.IsNullOrEmpty(dsc.Password)) { (dbEngineUtil as SqlServerEngineUtil).UseWindowsAuthentication = true; } } try { Console.WriteLine("Dropping existing client database for server " + serverName + "..."); dbEngineUtil.DropDatabase(dsc.Password, newDatabaseName); } catch (Exception exDrop) { Console.WriteLine("Could not drop database: " + exDrop.Message); Console.WriteLine("Continuing anyway"); } Console.WriteLine("Creating new client database for server " + serverName + "..."); dbEngineUtil.CreateDatabase(dsc.Password, newDatabaseName); Console.WriteLine("Getting list of tables to precache for server " + serverName + "..."); lastSqlRan = @" SELECT dv.sys_dataview_id, dv.dataview_name, dvs.sql_statement, sdl.title, sdl.description, stf.field_name as pk_field_name, st.table_name as table_name FROM sys_dataview dv left join sys_dataview_lang sdl on dv.sys_dataview_id = sdl.sys_dataview_id and sdl.sys_lang_id = 1 inner join sys_dataview_sql dvs on dv.sys_dataview_id = dvs.sys_dataview_id and dvs.database_engine_tag = 'sqlserver' inner join sys_dataview_field sdvf on sdvf.sys_dataview_id = dv.sys_dataview_id and sdvf.is_primary_key = 'Y' inner join sys_table_field stf on sdvf.sys_table_field_id = stf.sys_table_field_id inner join sys_table st on stf.sys_table_id = st.sys_table_id WHERE dv.dataview_name like '%_lookup' order by dv.dataview_name "; using (DataManager dm = DataManager.Create(dsc)) { var dt = dm.Read(lastSqlRan, new DataParameters(":enginecode", dm.DataConnectionSpec.EngineName)); Console.WriteLine("Found " + dt.Rows.Count + " tables to precache."); try { // drop lookup status table lastSqlRan = String.Format("drop table [{0}].dbo.lookup_table_status", newDatabaseName); dm.Write(lastSqlRan); } catch (Exception exStatus) { //Console.WriteLine("Failed dropping lookup status table: " + exStatus.Message); //Console.WriteLine("Continuing anyway"); } try { Console.Write("Creating lookup status table..."); // create the lookup status table lastSqlRan = String.Format(@" CREATE TABLE [{0}].[dbo].[lookup_table_status]( [table_name] [varchar](255) NOT NULL, [pk_field_name] [varchar](255) NULL, [dataview_name] [varchar](255) NULL, [title] [varchar](255) NULL, [description] [varchar](255) NULL, [current_pk] [int] NULL, [min_pk] [int] NULL, [max_pk] [int] NULL, [row_count] [int] NULL, [auto_update] [varchar](255) NULL, [status] [varchar](255) NULL, [sync_date] [datetime] NULL, PRIMARY KEY CLUSTERED ( [table_name] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ", newDatabaseName); dm.Write(lastSqlRan); Console.WriteLine("Done"); } catch (Exception exStatus2) { Console.WriteLine("Failed to create lookup status table: " + exStatus2.Message); Console.WriteLine("Continuing anyway"); } lastSqlRan = String.Format("delete from [{0}].[dbo].[lookup_table_status]", newDatabaseName); dm.Write(lastSqlRan); foreach (DataRow dr in dt.Rows) { string lookupSql = dr["sql_statement"].ToString(); string newTableName = dr["dataview_name"].ToString(); string sourceTableName = dr["table_name"].ToString(); string pkFieldName = dr["pk_field_name"].ToString(); string title = dr["title"].ToString(); string description = dr["description"].ToString(); // grab all parameters for the dataview so we can just null them out // (the way the dataview lookup queries are written this will cause all rows to be returned) lastSqlRan = @" select param_name from sys_dataview_param where sys_dataview_id = :id "; var dtParams = dm.Read(lastSqlRan, new DataParameters(":id", dr["sys_dataview_id"], DbType.Int32)); foreach (DataRow drParam in dtParams.Rows) { lookupSql = lookupSql.Replace(drParam["param_name"].ToString(), "NULL"); } // now use that munged sql statement a to create a common table expression so we can // do a select into against it w/o marshalling everything from sql server to our process then back to sql server again Console.Write(("Precaching " + newTableName + "...").PadRight(50, ' ')); try { lastSqlRan = String.Format(@" drop table [{0}].[dbo].[{1}]; ", newDatabaseName, newTableName); dm.Write(lastSqlRan); } catch { } // create the structure // (we avoid copying the rows with the common table expression as that creates a lot of memory overhead // and on boxes with 512 MB of RAM it'll bomb). lastSqlRan = String.Format(@" WITH lookuptable as ({0}) SELECT * INTO [{1}].[dbo].[{2}] FROM lookuptable ", lookupSql, newDatabaseName, newTableName); // create the table in the new database dm.Write(lastSqlRan); // get name of primary key for lookup table // (assumes first field is PK and PK is an int) lastSqlRan = String.Format("select top 1 * from [{0}].[dbo].[{1}]", newDatabaseName, newTableName); var dtTemp = dm.Read(lastSqlRan); var pkLookupFieldName = dtTemp.Columns[0].ColumnName; // make sure the PK is set so CT works properly lastSqlRan = String.Format(@" ALTER TABLE [{0}].[dbo].[{1}] ADD CONSTRAINT PK_{1} PRIMARY KEY CLUSTERED ( {2} ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ", newDatabaseName, newTableName, pkLookupFieldName); dm.Write(lastSqlRan); var min = Toolkit.ToInt32(dm.ReadValue(String.Format("select min({2}) from [{0}].[dbo].[{1}]", newDatabaseName, newTableName, pkLookupFieldName)), 0); var max = Toolkit.ToInt32(dm.ReadValue(String.Format("select max({2}) from [{0}].[dbo].[{1}]", newDatabaseName, newTableName, pkLookupFieldName)), 0); var rowCount = Toolkit.ToInt32(dm.ReadValue(String.Format("select count(*) from [{0}].[dbo].[{1}]", newDatabaseName, newTableName)), 0); // add to the lookup status table lastSqlRan = String.Format(@" insert into [{0}].[dbo].[lookup_table_status] (table_name, pk_field_name, dataview_name, title, description, current_pk, min_pk, max_pk, row_count, auto_update, status, sync_date) values (:tbl, :pk, :dv, :title, :description, :curpk, :minpk, :maxpk, :rc, :auto, :status, getutcdate()) ", newDatabaseName); dm.Write(lastSqlRan, new DataParameters(":tbl", sourceTableName, ":pk", pkFieldName, ":dv", newTableName, ":title", title, ":description", (String.IsNullOrEmpty(description) ? null : description), ":curpk", max, DbType.Int32, ":minpk", min, DbType.Int32, ":maxpk", max, DbType.Int32, ":rc", rowCount, DbType.Int32, ":auto", "Y", ":status", "Completed")); if (rowCount == 0) { dm.Write(String.Format("drop table [{0}].[dbo].[{1}]", newDatabaseName, newTableName)); } Console.WriteLine(rowCount + " records copied."); } Console.WriteLine("Successfully created and precached " + dt.Rows.Count + " lookup tables"); } } catch (Exception exDropClientDB) { var msg = "Error precaching client data: " + exDropClientDB.Message + "\nLast SQL Ran: " + lastSqlRan; Console.WriteLine(msg); } }
private void refreshEngineUtil(bool forceRefresh) { var gguacPath = Utility.GetPathToUACExe(); if (!File.Exists(gguacPath)) { gguacPath = Toolkit.ResolveFilePath("~/gguac.exe", false); if (!File.Exists(gguacPath)) { throw new InvalidOperationException(getDisplayMember("refreshEngineUtil{nouac}", "Could not locate the path to gguac.exe. Can not continue.")); } } var databaseName = "gringlobal"; lnkMixedMode.Visible = false; txtPassword.Visible = true; if (forceRefresh) { _dbEngineUtil = null; } switch (EngineName) { case "sqlserver": if (_dbEngineUtil == null || !(_dbEngineUtil is SqlServerEngineUtil)) { _dbEngineUtil = DatabaseEngineUtil.CreateInstance("sqlserver", gguacPath, null); } var port = Toolkit.ToInt32(txtPort.Text, -1); var instanceName = ""; if (port > -1 && port < 65536) { // assume they gave us a port number _dbEngineUtil.Port = port; } else { // assume they gave us an instance name instanceName = txtPort.Text; (_dbEngineUtil as SqlServerEngineUtil).InstanceName = instanceName; } (_dbEngineUtil as SqlServerEngineUtil).UseWindowsAuthentication = chkWindowsAuthentication.Enabled && chkWindowsAuthentication.Checked; if (!chkWindowsAuthentication.Checked) { if (!(_dbEngineUtil as SqlServerEngineUtil).IsMixedModeEnabled(instanceName)) { lnkMixedMode.Visible = true; lnkMixedMode.Left = txtPassword.Left; lnkMixedMode.Top = txtPassword.Top; txtPassword.Visible = false; } } break; case "mysql": if (_dbEngineUtil == null || !(_dbEngineUtil is MySqlEngineUtil)) { _dbEngineUtil = DatabaseEngineUtil.CreateInstance("mysql", gguacPath, null); } break; case "oracle": if (_dbEngineUtil == null || !(_dbEngineUtil is OracleEngineUtil)) { _dbEngineUtil = DatabaseEngineUtil.CreateInstance("oracle", gguacPath, txtSID.Text); } break; case "postgresql": if (_dbEngineUtil == null || !(_dbEngineUtil is PostgreSqlEngineUtil)) { _dbEngineUtil = DatabaseEngineUtil.CreateInstance("postgresql", gguacPath, null); } break; case "sqlite": if (_dbEngineUtil == null || !(_dbEngineUtil is SqliteEngineUtil)) { _dbEngineUtil = DatabaseEngineUtil.CreateInstance("sqlite", gguacPath, null); // sqlite simply points at a file, so we specify the full file path as the database name databaseName = txtServerName.Text; } break; case "": // ignore, happens when launched from an installer context for some reason // next pass around will give us the right value so.... whatever. return; default: throw new InvalidOperationException(getDisplayMember("refreshEngineUtil{default}", "No valid database engine selected.")); } _dbEngineUtil.Port = Toolkit.ToInt32(txtPort.Text, 0); _dbEngineUtil.ServerName = txtServerName.Text; _dbEngineUtil.SID = txtSID.Text; // _dbEngineUtil.SuperUserName = txtUsername.Text; // NOTE we already set the UseWindowsAuthentication above for sql server so no special code is needed here // don't show the password in the connection string... txtConnectionstring.Text = _dbEngineUtil.GetDataConnectionSpec(databaseName, txtUsername.Text, "__PASSWORD__").ConnectionString; _genericConnectionString = _dbEngineUtil.GetDataConnectionSpec(databaseName, "__USERID__", "__PASSWORD__").ConnectionString; Application.DoEvents(); }
private void customInstall(IDictionary state) { string targetDir = Utility.GetTargetDirectory(this.Context, state, "Search Engine"); string targetDataDir = Toolkit.ResolveDirectoryPath(@"*COMMONAPPLICATIONDATA*\GRIN-Global\GRIN-Global Search Engine", true); int installerWindowHandle = 0; var splash = new frmSplash(); try { string gguacPath = Toolkit.ResolveFilePath(targetDir + @"\gguac.exe", false); splash.ChangeText(getDisplayMember("customInstall{extracting}", "Extracting bundled files...")); var utility64CabPath = Toolkit.ResolveFilePath(targetDir + @"\utility64.cab", false); var utility64ExePath = Toolkit.ResolveFilePath(targetDir + @"\ggutil64.exe", false); var tempPath = Utility.GetTempDirectory(15); if (!File.Exists(utility64ExePath)) { if (File.Exists(utility64CabPath)) { // wipe out any existing utility64.exe file in the temp folder var extracted = Toolkit.ResolveFilePath(tempPath + @"\ggutil64.exe", false); if (File.Exists(extracted)) { File.Delete(extracted); } // extract it from our cab var cabOutput = Utility.ExtractCabFile(utility64CabPath, tempPath, gguacPath); // move it to the final target path (we can't do this up front because expand.exe tells us "can't expand cab file over itself" for some reason. if (File.Exists(extracted)) { File.Move(extracted, utility64ExePath); } } } // delete any existing index file(s) string indexDir = (targetDataDir + @"\indexes").Replace(@"\\", @"\"); if (Directory.Exists(targetDataDir)) { Directory.Delete(targetDataDir, true); } string helperPath = (Utility.GetTargetDirectory(this.Context, state, "Search Engine") + @"\gguac.exe").Replace(@"\\", @"\"); // prompt user to tell us what to do -- download files or begin recreating locally... var f = new frmInstallIndexes(); f.HelperPath = helperPath; installerWindowHandle = Toolkit.GetWindowHandle("GRIN-Global Search Engine"); //// HACK: try to give MSI form a moment to focus before we show our dialog... //Thread.Sleep(500); //Application.DoEvents(); //Thread.Sleep(500); // we no longer allow user to download indexes. always issue a recreate. File.WriteAllText(Toolkit.ResolveFilePath(indexDir + @"\recreate.init", true), ""); //DialogResult result = DialogResult.Cancel; //var autoIncludeOptionalData = Utility.GetParameter("optionaldata", null, this.Context, null); //if (("" + autoIncludeOptionalData).ToUpper() == "TRUE" || ("" + autoIncludeOptionalData).ToUpper() == "1") { // f.DownloadAllFiles(); // result = DialogResult.OK; //} else if (("" + autoIncludeOptionalData).ToUpper() == "FALSE" || ("" + autoIncludeOptionalData).ToUpper() == "0"){ // result = DialogResult.OK; //} else { // result = f.ShowDialog(installerWindowHandle); //} //if (result == DialogResult.OK) { // if (f.rdoCreateLocally.Checked) { // // need to create locally // File.WriteAllText(Toolkit.ResolveFilePath(indexDir + @"\recreate.init", true), ""); // // EventLog.WriteEntry("GRIN-Global Search Engine", "Should recreate indexes locally...", EventLogEntryType.Information); // } else { // if (f.IndexFiles != null && f.IndexFiles.Count > 0) { // // downloaded files. // splash.Show("Inspecting index files (" + f.IndexFiles.Count + ")...", false, null); // for (var i = 0; i < f.IndexFiles.Count; i++) { // var s = f.IndexFiles[i]; // splash.ChangeText("Extracting index files (" + (i + 1) + " of " + f.IndexFiles.Count + ")..."); // Utility.ExtractCabFile(s, indexDir, helperPath); // // we expanded the cab file, now delete it since we don't need it anymore (and want the next install to re-request data from the server and ignore the cache) // try { // var moveTo = s.Replace(@"\downloaded\", @"\installed\"); // if (File.Exists(moveTo)) { // File.Delete(moveTo); // } // File.Move(s, moveTo); // } catch { // try { // // move failed, try to delete it // File.Delete(s); // } catch { // // ultimately ignore all file movement errors // } // } // } // } else { // EventLog.WriteEntry("GRIN-Global Search Engine", "User chose to download indexes, but selected 0 indexes to download. Empty indexes will be created.", EventLogEntryType.Information); // } // } //} else { // // user cancelled out. // //Context.LogMessage("User cancelled out of choosing to generate indexes locally or download from server"); // EventLog.WriteEntry("GRIN-Global Search Engine", "User cancelled out of choosing to generate indexes locally or download from server"); // // this.Rollback(state); // throw new InvalidOperationException("User cancelled out of choosing to generate indexes locally or download from server."); //} } catch (Exception ex) { splash.Close(); //this.Context.LogMessage("Setup failed to extract the index files: " + ex.Message); EventLog.WriteEntry("GRIN-Global Search Engine", "Setup failed to extract the index files: " + ex.Message); // this.Rollback(state); throw; } // // first unzip the data (note we need to run this is athe currently logged-in user for it to work) // Utility.ExtractCabFile((targetDir + @"\search.cab").Replace(@"\\", @"\"), indexDir, helperPath); //// Utility.Unzip((Utility.DataDirectory + @"\gringlobal_search_small.zip").Replace(@"\\", @"\"), indexDir); string configFile = Toolkit.ResolveFilePath(targetDir + @"\GrinGlobal.Search.Engine.Service.exe.config", false); try { // update the config file... if (File.Exists(configFile)) { splash.ChangeText(getDisplayMember("customInstall{verifying}", "Verifying database connection...")); string superUserPassword = Utility.GetSuperUserPassword(Context, state); bool? useWindowsAuthentication = Utility.GetUseWindowsAuthentication(Context, state); //MessageBox.Show("pw=" + superUserPassword + ", windowsAuth=" + useWindowsAuthentication); DatabaseEngineUtil dbEngineUtil = promptForDatabaseConnectionInfo(splash, ref superUserPassword, ref useWindowsAuthentication); createDatabaseUser(splash, dbEngineUtil, superUserPassword, "gg_search", "gg_search_PA55w0rd!"); string connectionString = null; if (useWindowsAuthentication == true) { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", null, null).ConnectionString; } else { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", "gg_search", "gg_search_PA55w0rd!").ConnectionString; } EventLog.WriteEntry("GRIN-Global Search Engine", "Database connection string=" + connectionString, EventLogEntryType.Information); splash.ChangeText(getDisplayMember("customInstall{writingconfig}", "Writing configuration file...")); string contents = File.ReadAllText(configFile); string appSetting = @"<add providerName=""__ENGINE__"" name=""DataManager"" connectionString=""__CONNECTION_STRING__"" />".Replace("__ENGINE__", dbEngineUtil.EngineName).Replace("__CONNECTION_STRING__", connectionString); contents = contents.Replace("<!-- __CONNECTIONSTRING__ -->", appSetting); contents = contents.Replace("<!-- __COMMENT__ -->", "<!-- TESTING "); contents = contents.Replace("<!-- __ENDCOMMENT__ -->", " -->"); File.WriteAllText(configFile, contents); } } catch (Exception ex) { splash.Close(); //this.Context.LogMessage("Setup failed to update the configuration file (" + configFile + "): " + ex.Message); EventLog.WriteEntry("GRIN-Global Search Engine", "Setup failed to update the configuration file (" + configFile + "): " + ex.Message); // this.Rollback(state); throw; } finally { splash.Close(); if (installerWindowHandle > 0) { Toolkit.RestoreWindow(installerWindowHandle); } } }
public DialogResult ShowDialog(int installerWindowHandle, DatabaseEngineUtil dbEngineUtil, bool loadFromRegistry, bool writeToRegistryOnSave, bool clientMode, string superUserPassword, bool?useWindowsAuthentication, bool enableAutoLogin, bool showSkipDatabase) { _installerWindowHandle = installerWindowHandle; return(ShowDialog(null, dbEngineUtil, loadFromRegistry, writeToRegistryOnSave, clientMode, superUserPassword, useWindowsAuthentication, enableAutoLogin, showSkipDatabase)); }
public override void Install(IDictionary stateSaver) { base.Install(stateSaver); var splash = new frmSplash(); try { string targetDir = Utility.GetTargetDirectory(Context, stateSaver, "Web Application"); string gguacPath = Toolkit.ResolveFilePath(targetDir + @"\gguac.exe", false); //MessageBox.Show("config file=" + configFile); splash.ChangeText(getDisplayMember("Install{extracting}", "Extracting bundled files...")); var utility64CabPath = Toolkit.ResolveFilePath(targetDir + @"\utility64.cab", false); var utility64ExePath = Toolkit.ResolveFilePath(targetDir + @"\ggutil64.exe", false); var tempPath = Utility.GetTempDirectory(100); if (!File.Exists(utility64ExePath)) { if (File.Exists(utility64CabPath)) { // wipe out any existing utility64.exe file in the temp folder var extracted = Toolkit.ResolveFilePath(tempPath + @"\ggutil64.exe", false); if (File.Exists(extracted)) { File.Delete(extracted); } // extract it from our cab var cabOutput = Utility.ExtractCabFile(utility64CabPath, tempPath, gguacPath); // move it to the final target path (we can't do this up front because expand.exe tells us "can't expand cab file over itself" for some reason. if (File.Exists(extracted)) { File.Move(extracted, utility64ExePath); } } } // update the config file... string configFile = Toolkit.ResolveFilePath(targetDir + @"\web.config", false); if (File.Exists(configFile)) { splash.ChangeText(getDisplayMember("Install{verifying}", "Verifying database connection...")); string superUserPassword = Utility.GetSuperUserPassword(Context, stateSaver); bool? useWindowsAuth = Utility.GetUseWindowsAuthentication(Context, stateSaver); DatabaseEngineUtil dbEngineUtil = promptForDatabaseConnectionInfo(splash, ref superUserPassword, ref useWindowsAuth); createDatabaseUser(splash, dbEngineUtil, superUserPassword, "gg_user", "PA55w0rd!"); string connectionString = null; if (useWindowsAuth == true) { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", null, null).ConnectionString; } else { connectionString = dbEngineUtil.GetDataConnectionSpec("gringlobal", "gg_user", "PA55w0rd!").ConnectionString; } EventLog.WriteEntry("GRIN-Global Web Application", "Database connection string=" + connectionString, EventLogEntryType.Information); splash.ChangeText(getDisplayMember("Install{writingconfig}", "Writing configuration file...")); string contents = File.ReadAllText(configFile); string appSetting = @"<add providerName=""__ENGINE__"" name=""DataManager"" connectionString=""__CONNECTION_STRING__"" />".Replace("__ENGINE__", dbEngineUtil.EngineName).Replace("__CONNECTION_STRING__", connectionString); contents = contents.Replace("<!-- __CONNECTIONSTRING__ -->", appSetting); contents = contents.Replace("<!-- __COMMENT__ -->", "<!-- TESTING "); contents = contents.Replace("<!-- __ENDCOMMENT__ -->", " -->"); File.WriteAllText(configFile, contents); } // give ASPNET user full control to the ~/uploads folder splash.ChangeText(getDisplayMember("Install{settingperms}", "Setting permissions on uploads folder...")); assignFolderPermissions(Utility.ResolveDirectoryPath(targetDir + @"\uploads", true)); } catch (Exception ex) { MessageBox.Show(getDisplayMember("Install{failed}", "Error: {0}", ex.Message)); throw; } finally { splash.Close(); } }
static void import(string[] args) { // /import "c:\cabfile_here" "provider_name_here" "connection_string_here" db_name_here string folder = args[1].Replace("\"", ""); string during = "Connecting to database"; try { // parse the dsc into a DataConnectionSpec object DataConnectionSpec dsc = new DataConnectionSpec(args[2].Replace("\"", ""), args[3].Replace("\"", "")); if (String.IsNullOrEmpty(dsc.DatabaseName)) { dsc.DatabaseName = args[4]; } __frmProgress = new frmProgress(); __frmProgress.Show(); __frmProgress.Text = "Importing Data to " + args[4] + " Database..."; updateProgress("Expanding source data files..."); string targetDir = Toolkit.ResolveDirectoryPath(@".\", false); if (args[1].ToLower().EndsWith(".cab")) { // they gave us a cab file. extract it, plow into local folder Utility.ExtractCabFile(args[1].Replace(@"""", ""), targetDir, null); } else { // they gave us a folder. mark that as our target dir. targetDir = args[1].Replace(@"""", ""); } // Utility.Unzip(args[1].Replace("\"", ""), targetDir); // read table info from the given folder\__schema.xml file Creator c = Creator.GetInstance(dsc); c.OnProgress += new ProgressEventHandler(c_OnProgress); during = "loading table information"; List <TableInfo> tables = c.LoadTableInfo(targetDir); // create tables in the database during = "creating tables"; c.CreateTables(tables, args[4]); // copy the data to the database during = "copying data"; c.CopyDataToDatabase(targetDir, args[4].Replace("\"", ""), tables, false, false); // create the indexes during = "creating indexes"; foreach (TableInfo ti in tables) { ti.IsSelected = true; } c.CreateIndexes(tables); // create the constraints during = "creating constraints"; foreach (TableInfo ti in tables) { ti.IsSelected = true; } c.CreateConstraints(tables, true, true); // get all the sequences up to snuff so new inserts work properly (i.e. make sure sequence id's are past the last one currently in each table) var dbUtil = DatabaseEngineUtil.CreateInstance(args[2].Replace("\"", ""), null, args[3].Replace("\"", "")); if (dsc.ProviderName.ToLower() == "oracle") { during = "restarting sequences"; foreach (var t in tables) { updateProgress("restarting sequence for " + t.TableName + "..."); var ret = ((OracleEngineUtil)dbUtil).RestartSequenceForTable(dsc.Password, dsc.UserName, dsc.Password, t.TableName, t.PrimaryKey.Name); updateProgress(ret); } } else if (dsc.ProviderName.ToLower() == "postgresql") { during = "restarting sequences"; foreach (var t in tables) { updateProgress("restarting sequence for " + t.TableName + "..."); var ret = ((PostgreSqlEngineUtil)dbUtil).RestartSequenceForTable(dsc.Password, dsc.DatabaseName, dsc.ServerName, t.TableName, t.PrimaryKey.Name); updateProgress(ret); } } else if (dsc.ProviderName.ToLower() == "mysql") { c.RebuildIndexes(tables); } } catch (Exception ex) { updateProgress("Error while " + during + ": " + ex.Message); throw; } __frmProgress.btnDone.Enabled = true; __frmProgress.Close(); //while (__frmProgress.Visible) { // Thread.Sleep(1000); // Application.DoEvents(); //} }