public static string RestoreAllowedInstancesConfigsToMostRecentBak()
        {
            StringBuilder result = new StringBuilder();

            try
            {
                ServerAssignmentModel model = ServerAssignmentModel.GetInstance();
                for (int i = 0; i < model.CpRkFrontEndMachines.Length; i++)
                {
                    string riskWebConfigPath = @"\\{0}\{1}$\Program Files (x86)\Microsoft CTP\Risk\web.config".FormatWith(model.CpRkFrontEndMachines[i], "C");
                    result.AppendLine(RestoreAllowedInstancesConfigsToMostRecentBak(riskWebConfigPath));
                    string machineConfigPath = @"\\{0}\{1}$\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C");
                    result.AppendLine(RestoreAllowedInstancesConfigsToMostRecentBak(machineConfigPath));
                    string x64MachineConfigPath = @"\\{0}\{1}$\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C");
                    result.AppendLine(RestoreAllowedInstancesConfigsToMostRecentBak(x64MachineConfigPath));
                    result.AppendLine();
                }
            }
            catch (Exception ex)
            {
                result.AppendLine(ExceptionHelper.CentralProcess(ex));
            }

            return(result.ToString());
        }
Example #2
0
        /// <summary>
        /// Enables the azure write.
        /// </summary>
        /// <returns>Rows affected.</returns>
        public static int EnableAzureWrite()
        {
            string sql    = @"IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#Keys'))
	                            DROP TABLE dbo.#Keys;                            
                            CREATE TABLE #Keys (vcKey varchar(900), nvcValue nvarchar(MAX));
                            INSERT INTO #Keys (vcKey, nvcValue) VALUES {0};
                            IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#NewKeysAndValues')) DROP TABLE dbo.#NewKeysAndValues;
                            SELECT DISTINCT C.vcKey, K.nvcValue INTO #NewKeysAndValues FROM RiMEConfig.dbo.Config C JOIN #Keys K ON C.vcKey LIKE '%.%.' + K.vcKey OR C.vcKey LIKE '%.%' + K.vcKey + '%.%';
                            UPDATE RiMEConfig.dbo.Config SET nvcValue = (SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey) WHERE EXISTS(SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey);";
            string values = string.Join(",", Settings.Default.AzureWriteKeysAndValues_Enable.Cast <string>().Select(value => { string[] arr = value.Split(new char[] { '\t', '=' }, StringSplitOptions.RemoveEmptyEntries); return("('" + arr[0].Replace("'", "''") + "', N'" + arr[1].Replace("'", "''") + "')"); }).ToArray <string>());

            sql = sql.FormatWith(values);
            string originalServer = SqlServerHelper.ConnectionString.Server;

            ServerAssignmentModel serverAssignment = ServerAssignmentModel.GetInstance();

            if (serverAssignment.CpRkRiskConfigServers.Length > 0)
            {
                int rowsAffected = 0;
                for (int i = 0; i < serverAssignment.CpRkRiskConfigServers.Length; i++)
                {
                    SqlServerHelper.ConnectionString.Server = serverAssignment.CpRkRiskConfigServers[i];
                    try
                    {
                        rowsAffected = SqlServerHelper.Execute(sql);
                        break;
                    }
                    catch (SqlServerHelperException ex)
                    {
                        if (!(ex.InnerException != null && ex.InnerException is System.Data.SqlClient.SqlException &&
                              ex.InnerException.Message.Equals(@"The database ""RiMEConfig"" cannot be opened. It is acting as a mirror database.")))
                        {
                            ExceptionHelper.CentralProcess(ex);
                        }
                        else
                        {
                        }

                        continue;
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                        continue;
                    }
                }

                SqlServerHelper.ConnectionString.Server = originalServer;
                return(rowsAffected);
            }
            else
            {
                return(SqlServerHelper.Execute(sql));
            }
        }
Example #3
0
        /// <summary>
        /// Gets the azure write settings.
        /// </summary>
        /// <returns>Data table contains the azure write settings</returns>
        public static DataTable GetAzureWriteSettings()
        {
            string sql    = @"IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#Keys'))
	                        DROP TABLE dbo.#Keys;
                        CREATE TABLE #Keys (vcKey varchar(900));
                        INSERT INTO #Keys (vcKey) VALUES {0};
                        SELECT DISTINCT C.vcKey, C.nvcValue, C.iConfigObjectType FROM RiMEConfig.dbo.Config C JOIN #Keys K ON C.vcKey LIKE '%.%.' + K.vcKey OR C.vcKey LIKE '%.%' + K.vcKey + '%.%';";
            string values = string.Join(",", Settings.Default.AzureWriteKeysAndValues_Disable.Cast <string>().Select(value => "('" + value.Split(new char[] { '\t', '=' }, StringSplitOptions.RemoveEmptyEntries)[0].Replace("'", "''") + "')").ToArray <string>());

            sql = sql.FormatWith(values);

            string originalServer = SqlServerHelper.ConnectionString.Server;

            ServerAssignmentModel serverAssignment = ServerAssignmentModel.GetInstance();

            if (serverAssignment.CpRkRiskConfigServers.Length > 0)
            {
                DataTable dt = new DataTable();
                for (int i = 0; i < serverAssignment.CpRkRiskConfigServers.Length; i++)
                {
                    SqlServerHelper.ConnectionString.Server = serverAssignment.CpRkRiskConfigServers[i];
                    try
                    {
                        dt = SqlServerHelper.Query(sql);
                        break;
                    }
                    catch (SqlServerHelperException ex)
                    {
                        if (!(ex.InnerException != null && ex.InnerException is System.Data.SqlClient.SqlException &&
                              ex.InnerException.Message.Equals(@"The database ""RiMEConfig"" cannot be opened. It is acting as a mirror database.")))
                        {
                            ////ExceptionHelper.CentralProcess(ex);
                        }
                        else
                        {
                            ExceptionHelper.CentralProcess(ex);
                        }

                        // Continue trying SQL query on another server.
                        continue;
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                        continue;
                    }
                }
                SqlServerHelper.ConnectionString.Server = originalServer;
                return(dt);
            }
            else
            {
                return(SqlServerHelper.Query(sql));
            }
        }
        public static string GetCurrentAllowedInstancesConfigsWithoutErrorHandling()
        {
            StringBuilder result = new StringBuilder();

            ServerAssignmentModel model = ServerAssignmentModel.GetInstance();

            for (int i = 0; i < model.CpRkFrontEndMachines.Length; i++)
            {
                #region Risk Web config
                string riskWebConfigPath = @"\\{0}\{1}$\Program Files (x86)\Microsoft CTP\Risk\web.config".FormatWith(model.CpRkFrontEndMachines[i], "C");
                result.AppendLine("Current configs in machine '{0}: '".FormatWith(model.CpRkFrontEndMachines[i]));

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(riskWebConfigPath);
                XmlNode node = xmlDoc.SelectSingleNode("/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior[@name='RiskWSBehavior']/serviceThrottling");
                result.AppendLine("Service Throttling/maxConcurrentCalls: {0}".FormatWith(node != null && node.Attributes["maxConcurrentCalls"] != null ? node.Attributes["maxConcurrentCalls"].Value : "Not found."));
                result.AppendLine("Service Throttling/maxConcurrentInstances: {0}".FormatWith(node != null && node.Attributes["maxConcurrentInstances"] != null ? node.Attributes["maxConcurrentInstances"].Value : "Not found."));
                result.AppendLine();
                #endregion Risk Web config
                #region machine config
                string[] machineConfigs = new string[] {
                    @"\\{0}\{1}$\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C"),
                    @"\\{0}\{1}$\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C")
                };
                for (int j = 0; j < machineConfigs.Length; j++)
                {
                    string machineConfigPath = machineConfigs[j];
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(machineConfigPath);
                    result.AppendLine("Current machine configs in machine '{0}': ".FormatWith(model.CpRkFrontEndMachines[i]));
                    string     xpath   = "/configuration/system.web/processModel";
                    XmlElement element = xmlDoc.SelectSingleNode(xpath) as XmlElement;
                    if (element != null)
                    {
                        result.AppendLine("processModel/autoConfig: {0}".FormatWith(element.Attributes["autoConfig"] != null ? element.Attributes["autoConfig"].Value : "Not found."));
                        result.AppendLine("processModel/maxWorkerThreads: {0}".FormatWith(element.Attributes["maxWorkerThreads"] != null ? element.Attributes["maxWorkerThreads"].Value : "Not found."));
                        result.AppendLine("processModel/maxIoThreads: {0}".FormatWith(element.Attributes["maxIoThreads"] != null ? element.Attributes["maxIoThreads"].Value : "Not found."));
                        result.AppendLine("processModel/minWorkerThreads: {0}".FormatWith(element.Attributes["minWorkerThreads"] != null ? element.Attributes["minWorkerThreads"].Value : "Not found."));
                        result.AppendLine();
                    }
                    else
                    {
                        result.AppendLine("Xml element '{0}' in machine config '{1}' not found.".FormatWith(xpath, machineConfigPath));
                    }
                }
                #endregion machine config
            }

            return(result.ToString());
        }
Example #5
0
        /// <summary>
        /// Lists the service status.
        /// </summary>
        /// <returns>Service status message.</returns>
        public static string ListServiceStatus()
        {
            ServerAssignmentModel serverAssignment = ServerAssignmentModel.GetInstance();
            string cpWebStoreConfigMachine         = serverAssignment.CpWebStoreConfigPrimaryMachine;
            // This approach would get socket errors:

            /*
             * WMICmdHelper wmiHelper = new WMICmdHelper(cpWebStoreConfigMachine,
             *  "\"C:\\Program Files (x86)\\Microsoft SPS\\ServiceLocatorServer\\ServiceLocatorControl.exe\" /action:list");
             * return wmiHelper.RunCommandReturnOutput();
             */

            string cmd            = @"psexec \\{0} -u Administrator -p #Bugsfor$ ""C:\Program Files (x86)\Microsoft SPS\ServiceLocatorServer\ServiceLocatorControl.exe"" /action:list".FormatWith(cpWebStoreConfigMachine);
            string outputFileName = Path.Combine(Directory.GetCurrentDirectory(), @"WMICmdOutput.{0}.txt".FormatWith(DateTime.Now.ToString("yyyy-MM-ddThh-mm-ssZ")));

            cmd += @" >" + outputFileName;
            cmd += " & exit";
            CmdHelper cmdHelper = new CmdHelper();

            cmdHelper.StartCmdDirectly(cmd);

            string outputContent = "";

            try
            {
                outputContent = File.ReadAllText(outputFileName);
                File.Delete(outputFileName);
            }
            catch (Exception ex)
            {
                outputContent += "\r\n" + ExceptionHelper.CentralProcess(ex);
            }

            Log.Info(outputContent);
            return(outputContent);
        }
        public static string IncreaseAllowedInstancesConfigsWithoutErrorHandling()
        {
            StringBuilder         result = new StringBuilder();
            ServerAssignmentModel model  = ServerAssignmentModel.GetInstance();

            for (int i = 0; i < model.CpRkFrontEndMachines.Length; i++)
            {
                #region Risk Web Config
                string riskWebConfigPath = @"\\{0}\{1}$\Program Files (x86)\Microsoft CTP\Risk\web.config".FormatWith(model.CpRkFrontEndMachines[i], "C");

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(riskWebConfigPath);
                string bakFilePath = riskWebConfigPath + ".{0}.bak".FormatWith(DateTime.Now.ToString("yyyy-MM-ddThh-mm-ssZ"));
                xmlDoc.Save(bakFilePath);
                result.AppendLine("Backed up current config to '{0}'.".FormatWith(bakFilePath));
                result.AppendLine("Current configs in machine '{0}': ".FormatWith(model.CpRkFrontEndMachines[i]));
                string  xpath = "/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior[@name='RiskWSBehavior']/serviceThrottling";
                XmlNode node  = xmlDoc.SelectSingleNode(xpath);
                if (node != null)
                {
                    result.AppendLine("Service Throttling/maxConcurrentCalls: {0}".FormatWith(node.Attributes["maxConcurrentCalls"] != null ? node.Attributes["maxConcurrentCalls"].Value : "Not found."));
                    result.AppendLine("Now update it to 1000...");
                    if (node.Attributes["maxConcurrentCalls"] != null)
                    {
                        node.Attributes["maxConcurrentCalls"].Value = "1000";
                    }
                    else
                    {
                        XmlElement e = node as XmlElement;
                        e.SetAttribute("maxConcurrentCalls", "1000");
                    }
                    result.AppendLine("Service Throttling/maxConcurrentInstances: {0}".FormatWith(node.Attributes["maxConcurrentInstances"] != null ? node.Attributes["maxConcurrentInstances"].Value : "Not found."));
                    result.AppendLine("Now update it to 10000...");
                    if (node.Attributes["maxConcurrentInstances"] != null)
                    {
                        node.Attributes["maxConcurrentInstances"].Value = "10000";
                    }
                    else
                    {
                        XmlElement e = node as XmlElement;
                        e.SetAttribute("maxConcurrentInstances", "10000");
                    }
                    result.AppendLine();
                    xmlDoc.Save(riskWebConfigPath);
                }
                else
                {
                    result.AppendLine("Xml node '{0}' in config '{1}' not found.".FormatWith(xpath, riskWebConfigPath));
                }
                #endregion Risk Web Config
                #region Machine Config
                string[] machineConfigs = new string[] {
                    @"\\{0}\{1}$\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C"),
                    @"\\{0}\{1}$\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config".FormatWith(model.CpRkFrontEndMachines[i], "C")
                };
                for (int j = 0; j < machineConfigs.Length; j++)
                {
                    string machineConfigPath = machineConfigs[j];
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(machineConfigPath);
                    bakFilePath = machineConfigPath + ".{0}.bak".FormatWith(DateTime.Now.ToString("yyyy-MM-ddThh-mm-ssZ"));
                    xmlDoc.Save(bakFilePath);
                    result.AppendLine("Backed up current machine config to '{0}'.".FormatWith(bakFilePath));
                    result.AppendLine("Current machine configs in machine '{0}': ".FormatWith(model.CpRkFrontEndMachines[i]));
                    xpath = "/configuration/system.web/processModel";
                    XmlElement element = xmlDoc.SelectSingleNode(xpath) as XmlElement;
                    if (element != null)
                    {
                        result.AppendLine("processModel/autoConfig: {0}".FormatWith(element.Attributes["autoConfig"] != null ? element.Attributes["autoConfig"].Value : "Not found."));
                        result.AppendLine("Now update it to false...");
                        element.SetAttribute("autoConfig", "false");
                        result.AppendLine("processModel/maxWorkerThreads: {0}".FormatWith(element.Attributes["maxWorkerThreads"] != null ? element.Attributes["maxWorkerThreads"].Value : "Not found."));
                        result.AppendLine("Now udpate it to 1000...");
                        element.SetAttribute("maxWorkerThreads", "1000");
                        result.AppendLine("processModel/maxIoThreads: {0}".FormatWith(element.Attributes["maxIoThreads"] != null ? element.Attributes["maxIoThreads"].Value : "Not found."));
                        result.AppendLine("Now update it to 100...");
                        element.SetAttribute("maxIoThreads", "100");
                        result.AppendLine("processModel/minWorkerThreads: {0}".FormatWith(element.Attributes["minWorkerThreads"] != null ? element.Attributes["minWorkerThreads"].Value : "Not found."));
                        result.AppendLine("Now update it to 50...");
                        element.SetAttribute("minWorkerThreads", "50");
                        result.AppendLine();
                        xmlDoc.Save(machineConfigPath);
                    }
                    else
                    {
                        result.AppendLine("Xml element '{0}' in machine config '{1}' not found.".FormatWith(xpath, machineConfigPath));
                    }
                }
                #endregion
            }

            return(result.ToString());
        }
Example #7
0
        /// <summary>
        /// Setups the global settings.
        /// </summary>
        /// <returns>Rows affected.</returns>
        /// <exception cref="System.Exception">Tried all {0} 'CP RK Database Servers' as the target sql server on which to execute the following sql statement but none of the trials succeeded: \r\n{1}\r\nThe tried servers are: {2}.Format2(serverAssignment.CpRkDatabaseServers.Length, sql, string.Join(, , serverAssignment.CpRkDatabaseServers))</exception>
        public static int SetupGlobalSettings(
            string netUserName = "******", string netPassword = "******", string netDomain = ".",
            string sqlServerWindowsAuthUserName = "******",
            string sqlServerWindowsAuthPassword = "******",
            string sqlServerWindowsAuthDomain   = "."
            )
        {
            string sql    = @"IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#Keys'))
	                            DROP TABLE dbo.#Keys;                            
                            CREATE TABLE #Keys (vcKey varchar(900), nvcValue nvarchar(MAX));
                            INSERT INTO #Keys (vcKey, nvcValue) VALUES {0};
                            IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects WHERE id = OBJECT_ID('tempdb.dbo.#NewKeysAndValues')) DROP TABLE dbo.#NewKeysAndValues;
                            SELECT DISTINCT C.vcKey, K.nvcValue INTO #NewKeysAndValues FROM RiMEConfig.dbo.Config C JOIN #Keys K ON C.vcKey LIKE '%.%.' + K.vcKey OR C.vcKey LIKE '%.%' + K.vcKey + '%.%';
                            UPDATE RiMEConfig.dbo.Config SET nvcValue = (SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey) WHERE EXISTS(SELECT KV.nvcValue FROM #NewKeysAndValues KV WHERE KV.vcKey = Config.vcKey);";
            string values = string.Join(",", Settings.Default.GlobalSettings.Cast <string>().Select(value => { string[] arr = value.Split(new char[] { '\t', '=' }, StringSplitOptions.RemoveEmptyEntries); return("('" + arr[0].Replace("'", "''").Replace("%quote%", "\"") + "', N'" + arr[1].Replace("'", "''").Replace("%quote%", "\"") + "')"); }).ToArray <string>());

            sql = sql.FormatWith(values);
            string originalServer = SqlServerHelper.ConnectionString.Server;

            ServerAssignmentModel serverAssignment = ServerAssignmentModel.GetInstance(netUserName, netPassword, netDomain);

            //if (serverAssignment.CpRkRiskConfigServers.Length > 0)
            if (serverAssignment.CpRkDatabaseServers.Length > 0)
            {
                int rowsAffected         = 0;
                int exceptionCount       = 0;
                int mirrorExceptionCount = 0;

                for (int i = 0; i < serverAssignment.CpRkDatabaseServers.Length; i++)
                {
                    Impersonator impersonator = new Impersonator(sqlServerWindowsAuthUserName, sqlServerWindowsAuthDomain, sqlServerWindowsAuthPassword);
                    #region Sql server connection and sql execution
                    SqlServerHelper.ConnectionString.Server = serverAssignment.CpRkDatabaseServers[i];
                    try
                    {
                        Log.Info("Executing command on server '{1}': \r\n{0}".FormatWith(sql, SqlServerHelper.ConnectionString.Server));
                        rowsAffected = SqlServerHelper.Execute(sql);
                        break;
                    }
                    catch (SqlServerHelperException ex)
                    {
                        if (!(ex.InnerException != null && ex.InnerException is System.Data.SqlClient.SqlException &&
                              ex.InnerException.Message.Equals(@"The database ""RiMEConfig"" cannot be opened. It is acting as a mirror database.")))
                        {
                            ExceptionHelper.CentralProcess(ex);
                        }
                        else
                        {
                            mirrorExceptionCount++;
                        }
                        exceptionCount++;
                        continue;
                    }
                    catch (Exception ex)
                    {
                        ExceptionHelper.CentralProcess(ex);
                        exceptionCount++;
                        continue;
                    }
                    finally
                    {
                        impersonator.Undo();
                    }
                    #endregion Sql server connection and sql execution
                }

                if (mirrorExceptionCount == serverAssignment.CpRkDatabaseServers.Length)
                {
                    throw new Exception(@"The database ""RiMEConfig"" cannot be opened on all these 'CP RK Risk Config' Server: {0}. It is acting as a mirror database.".FormatWith(string.Join(", ", serverAssignment.CpRkDatabaseServers)));
                }

                if (exceptionCount == serverAssignment.CpRkDatabaseServers.Length)
                {
                    throw new Exception("Tried all {0} 'CP RK Risk Config' Servers as the target sql server on which to execute the following sql statement but none of the trials succeeded: \r\n{1}\r\nThe tried servers are: {2}".FormatWith(serverAssignment.CpRkDatabaseServers.Length, sql, string.Join(", ", serverAssignment.CpRkDatabaseServers)));
                }

                SqlServerHelper.ConnectionString.Server = originalServer;
                return(rowsAffected);
            }
            else
            {
                return(SqlServerHelper.Execute(sql));
            }
        }