Ejemplo n.º 1
0
 /// <summary>
 /// If you use this function always call it again with a empty-string so the default
 /// configuration-manager-file is used!!
 /// </summary>
 /// <param name="otherappname">root name of the config-file</param>
 public static void SetConfigFile(string otherappname)
 {
     Configuration ConfigFile = null;
     if (otherappname.Length > 0)
     {
         if (File.Exists(Application.StartupPath + @otherappname) == true)
         {
             Debug.WriteLine("Try open " + Application.StartupPath + @otherappname);
             ConfigFile = ConfigurationManager.OpenExeConfiguration(Application.StartupPath
                         + @otherappname);
         }
         else
         {
             MessageBox.Show("Can not find " + otherappname);
             return;
         }
    }
     else
     {
         ConfigFile = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
     }
     AppSettings = ConfigFile.AppSettings;
 }
 void SetSetting(AppSettingsSection section, string setting, string value)
 {
     if (section.Settings[setting] != null)
         section.Settings[setting].Value = value;
     else
     {
         section.Settings.Add(new KeyValueConfigurationElement(setting, value));
     }
 }
Ejemplo n.º 3
0
        static bool ParseConfigurationCommandLineRun(out Dictionary <string, Dictionary <string, string> > subComs)
        {
            subComs = null;
            bool rc = false;

            // Get the current configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            ConfigurationSection appS = config.GetSection("appSettings");
            Type t0 = typeof(ConfigurationSection);
            AppSettingsSection appSettings = config.AppSettings;

            if (appSettings != null) //
            {
                //string ss = appSettings?.Settings?.AllKeys[0];
                //string ss1 = appSettings?.Settings?.AllKeys[1];
                //string ss2 = appSettings?.Settings.GetEnumerator.
            }
            //UserServices.ConfigurationCMDRun.
            Type t2 = typeof(ValidatedCMRunSection);
            ValidatedCMRunSection CMRunSection = config.GetSection("cmdrun")
                                                 as ValidatedCMRunSection;

            if (CMRunSection != null) //
            {
                Console.WriteLine("CMRunSection not null.");
            }
            // var AddConfSections1 = (CommandLineRunSection)config.GetSection("CmdRunConfs");
            Type t4 = typeof(CommandLineRunSection);
            CommandLineRunSection AddConfSections = config.GetSection("CmdRunConfs")
                                                    as CommandLineRunSection;

            if (AddConfSections != null) // получили секцию AddConfSections из конфигурации
            {
                if (subComs == null)     //
                {
                    subComs = new Dictionary <string, Dictionary <string, string> >();
                }
                for (int ii = 0; ii < AddConfSections.CmdRunConfs.Count; ii++)
                {
                    string subCom = AddConfSections.CmdRunConfs[ii].Subcommand;
                    if (string.IsNullOrEmpty(subCom)) // сбой значения
                    {
                        continue;
                    }
                    else
                    {
                        CommandLineSample cmdSample = CommandLineService.GetOrAddCommand(subCom, false);
                        if (cmdSample == null)  // Нет обработки
                        {
                            continue;
                        }

                        string assemblyNameWithPath = AddConfSections.CmdRunConfs[ii].AssemblyNameWithPath;
                        // создаем имя
                        cmdSample.AssemblyNameWithPath = assemblyNameWithPath;
                        int num = AddConfSections.CmdRunConfs[ii].NumberExecution;
                        Console.WriteLine($"Add: {subCom} -  {assemblyNameWithPath}.");
                    }
                }
            }
            Type tPr = typeof(CMDPropertySection);
            CMDPropertySection cmdProperties = config.GetSection("CMDProperties")
                                               as CMDPropertySection;

            if (cmdProperties != null) // получили секцию AddConfSections из конфигурации
            {
                if (subComs == null)   //
                {
                    subComs = new Dictionary <string, Dictionary <string, string> >();
                }
                for (int ii = 0; ii < cmdProperties.CMDProperties.Count; ii++)
                {
                    string subCom = cmdProperties.CMDProperties[ii].Subcommand;
                    if (string.IsNullOrEmpty(subCom)) // сбой значения
                    {
                        continue;
                    }
                    else
                    {
                        Dictionary <string, string> properties;
                        string val = cmdProperties.CMDProperties[ii].Value;
                        string key = cmdProperties.CMDProperties[ii].NameProperty;
                        if (!subComs.TryGetValue(subCom, out properties)) // нет в справочнике
                        {                                                 // создаем
                            properties = new Dictionary <string, string>();
                            subComs.Add(subCom, properties);
                        }
                        if (string.IsNullOrEmpty(key)) // сбой значения
                        {
                            continue;
                        }
                        else
                        {
                            properties.Add(key, val);
                            Console.WriteLine($"Add: {key} -  {val}.");
                            rc = true;
                        }
                    }
                }
            }

            // Обработка секции CmdRunSpecifications
            Type tPS = typeof(CMDPropertySection);
            CMDRunSpecificationSection cmdSpecifications = config.GetSection("CMDRunSpecifications")
                                                           as CMDRunSpecificationSection;

            if (cmdSpecifications != null) // получили секцию CmdRunSpecifications из конфигурации
            {
                if (subComs == null)       // ??? нужно ли выполнять
                {
                    subComs = new Dictionary <string, Dictionary <string, string> >();
                }

                for (int ii = 0; ii < cmdSpecifications.CMDRunSpecifications.Count; ii++)
                {
                    string subComLeft = cmdSpecifications.CMDRunSpecifications[ii].SubcommandLeft;
                    if (string.IsNullOrEmpty(subComLeft)) // сбой значения
                    {
                        continue;
                    }
                    string subComRight = cmdSpecifications.CMDRunSpecifications[ii].SubcommandRight;
                    if (string.IsNullOrEmpty(subComRight)) // сбой значения
                    {
                        continue;
                    }
                    string specification = cmdSpecifications.CMDRunSpecifications[ii].Specification;
                    if (string.IsNullOrEmpty(specification)) // сбой значения
                    {
                        continue;
                    }
                    else
                    {
                        specification = specification.ToUpper();
                        CommandLineSample cmdSampleL = CommandLineService.GetOrAddCommand(subComLeft, false);
                        if (cmdSampleL == null)  // Нет обработки
                        {
                            continue;
                        }
                        CommandLineSample cmdSampleR = CommandLineService.GetOrAddCommand(subComRight, false);
                        if (cmdSampleR == null)  // Нет обработки
                        {
                            continue;
                        }
                        else
                        {
                            switch (specification)
                            {
                            case "XOR":
                                cmdSampleL = cmdSampleL ^ cmdSampleR;
                                break;

                            case "OR":
                                cmdSampleL = cmdSampleL | cmdSampleR;
                                break;

                            case "AND":
                                cmdSampleL = cmdSampleL & cmdSampleR;
                                break;

                            default:
                                continue;
                            }
                        }
                    }
                }
            }
            Console.WriteLine("Expect  Enter.");
            Console.ReadKey();

            return(rc);
        }
        static void Main()
        {
            var configfile = "app.config";
            var region     = "";
            var table      = "";
            var index      = "";
            var id         = "3";

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;
                index  = appSettings.Settings["Index"].Value;
                id     = appSettings.Settings["ProductID"].Value;

                if ((region == "") || (table == "") || (index == "") || (id == ""))
                {
                    Console.WriteLine("You must specify Region, Table, Index, and ProductID values in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int val;

            try
            {
                val = int.Parse(id);

                if (val < 1)
                {
                    Console.WriteLine("The product ID must be > 0");
                    return;
                }
            }
            catch (FormatException)
            {
                Console.WriteLine(id + " is not an integer");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            var response = GetProductOrdersAsync(client, table, index, id);

            // To adjust date/time value
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            foreach (var item in response.Result.Items)
            {
                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        Console.WriteLine(attr + ": " + item[attr].S);
                    }
                    else if (item[attr].N != null)
                    {
                        // If the attribute contains the string "date", process it differently
                        if (attr.ToLower().Contains("date"))
                        {
                            long     span    = long.Parse(item[attr].N);
                            DateTime theDate = epoch.AddSeconds(span);

                            Console.WriteLine(attr + ": " + theDate.ToLongDateString());
                        }
                        else
                        {
                            Console.WriteLine(attr + ": " + item[attr].N);
                        }
                    }
                }

                Console.WriteLine("");
            }
        }
Ejemplo n.º 5
0
        public static async Task Main(string[] args)
        {
            var configfile = "app.config";
            var id         = string.Empty;
            var keys       = string.Empty;
            var values     = string.Empty;

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile,
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            string region;
            string table;

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;

                if ((region == string.Empty) || (table == string.Empty))
                {
                    Console.WriteLine("You must specify a Region and Table value in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-i":
                    i++;
                    id = args[i];
                    break;

                case "-k":
                    i++;
                    keys = args[i];
                    break;

                case "-v":
                    i++;
                    values = args[i];
                    break;
                }

                i++;
            }

            if ((keys == string.Empty) || (values == string.Empty) || (id == string.Empty))
            {
                Console.WriteLine("You must supply a comma-separated list of keys (-k \"key 1 ... keyN\") a comma-separated list of values (-v \"value1 ... valueN\") and an ID (-i ID)");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            var success = await AddItemAsync(client, table, id, keys, values);

            if (success)
            {
                Console.WriteLine($"Added item to {table} in {region}.");
            }
            else
            {
                Console.WriteLine($"Did not add item to {table} in {region}.");
            }
        }
Ejemplo n.º 6
0
        public object GetRemoteEquipmentJson(int checkmode = 0, string facname = "", string nodeid = "", int level = 0)
        {
            try
            {
                var treeList = new List <TreeEntity>();

                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

                fileMap.ExeConfigFilename = System.Web.HttpContext.Current.Server.MapPath(@"~/XmlConfig/remote_database.config");

                Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");

                string connectstring = appsection.Settings["RemoteBaseDb"].Value;

                IDatabase dbBase = new OracleDatabase(connectstring);

                string strWhere = " 1=1";

                if (!string.IsNullOrEmpty(nodeid))
                {
                    level    += 1;
                    strWhere += string.Format(@" and  parentid = '{0}' ", nodeid);
                }
                else
                {
                    strWhere += @" and  parentid = '-1' ";
                }
                if (!string.IsNullOrEmpty(facname))
                {
                    strWhere += string.Format(@" and facname like '%{0}%'", facname);
                }

                string sql = string.Format("select createdate, facname,faccode,parentid, id from factbfacility t where {0} order by faccode", strWhere);

                DataTable dt = dbBase.FindTable(sql);

                dt.Columns.Add("level", typeof(Int32));
                dt.Columns.Add("isLeaf", typeof(bool));
                dt.Columns.Add("expanded", typeof(bool));


                DataTable clonedt = dt.Clone();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        item["level"] = level;
                        DataRow[] itemDt = dt.Select(string.Format(" parentid ='{0}'", item["id"].ToString()));
                        item["isLeaf"]   = itemDt.Length > 0;
                        item["expanded"] = false;
                        DataRow crow = clonedt.NewRow();
                        crow["facname"]    = item["facname"];
                        crow["faccode"]    = item["faccode"];
                        crow["createdate"] = item["createdate"];
                        crow["level"]      = item["level"];
                        crow["parentid"]   = item["parentid"];
                        crow["isLeaf"]     = item["isLeaf"];
                        crow["id"]         = item["id"];
                        clonedt.Rows.Add(crow);
                    }
                }
                var jsonData = new
                {
                    rows    = clonedt,
                    total   = clonedt.Rows.Count,
                    page    = 1,
                    records = clonedt.Rows.Count,
                };
                return(ToJsonResult(jsonData));
            }
            catch (Exception ex)
            {
                return(Error(ex.Message));
            }
        }
Ejemplo n.º 7
0
        protected void loadData()
        {
            bool BadSSL = CommonLogic.QueryStringBool("BadSSL");

            if (BadSSL)
            {
                resetError("No SSL certificate was found on your site. Please check with your hosting company! You must be able to invoke your store site using https:// before turning SSL on in this admin site!", false);
            }


            String PM = AppLogic.AppConfig("PaymentMethods", 0, false).ToUpperInvariant();


            BuildPaymentMethodList(PM);

            if (AppLogic.TrustLevel == AspNetHostingPermissionLevel.Unrestricted)
            {
                Configuration      webconfig   = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
                AppSettingsSection appsettings = (AppSettingsSection)webconfig.GetSection("appSettings");
                rblEncrypt.Items.FindByValue(appsettings.SectionInformation.IsProtected.ToString().ToLowerInvariant()).Selected = true;

                MachineKeySection mkeysec = (MachineKeySection)webconfig.GetSection("system.web/machineKey");

                if (mkeysec.ValidationKey.Equals("autogenerate", StringComparison.InvariantCultureIgnoreCase))
                {
                    rblStaticMachineKey.Items.FindByValue("false").Selected = true;
                    ltStaticMachineKey.Text = AppLogic.GetString("admin.wizard.SetStaticMachineKey", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }
                else
                {
                    rblStaticMachineKey.Items.FindByValue("false").Selected = true;
                    ltStaticMachineKey.Text = AppLogic.GetString("admin.wizard.ChangeStaticMachineKey", ThisCustomer.SkinID, ThisCustomer.LocaleSetting);
                }
            }

            switch (BuySafeController.GetBuySafeState())
            {
            case BuySafeState.NotEnabledFreeTrialAvailible:
                break;

            case BuySafeState.EnabledFullUserAfterFreeTrial:
            case BuySafeState.EnabledOnFreeTrial:
                pnlBuySafeActive.Visible   = true;
                pnlBuySafeInactive.Visible = false;
                litBuySafeActiveMsg.Text   = "buySAFE is enabled";
                break;

            case BuySafeState.EnabledFreeTrialExpired:
            case BuySafeState.NotEnabledFreeTrialExpired:
                pnlBuySafeActive.Visible   = true;
                pnlBuySafeInactive.Visible = false;
                litBuySafeActiveMsg.Text   = "<span style=\"line-height:normal;\">Trial expired. Please contact buySAFE to enable your account.<br />Call 1.888.926.6333 | Email: <a href=\"mailto:[email protected]\">[email protected]</a></span>";
                break;

            case BuySafeState.Error:
                pnlBuySafeActive.Visible   = true;
                pnlBuySafeInactive.Visible = false;
                litBuySafeActiveMsg.Text   = "<span style=\"line-height:normal;\">Please contact buySAFE to enable your account.<br />Call 1.888.926.6333 | Email: <a href=\"mailto:[email protected]\">[email protected]</a></span>";
                break;
            }
        }
Ejemplo n.º 8
0
        static void Main()
        {
            var configfile = "app.config";
            var region     = "";
            var table      = "";
            var starttime  = "";
            var endtime    = "";

            // Get default values from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region    = appSettings.Settings["Region"].Value;
                table     = appSettings.Settings["Table"].Value;
                starttime = appSettings.Settings["StartTime"].Value;
                endtime   = appSettings.Settings["EndTime"].Value;
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            // Make sure we have a table, Region, start time and end time
            if ((region == "") || (table == "") || (starttime == "") || (endtime == ""))
            {
                Console.WriteLine("You must specify Region, Table, StartTime, and EndTime values in " + configfile);
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            var response = GetOrdersInDateRangeAsync(client, table, starttime, endtime);

            // To adjust date/time value
            var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            foreach (var item in response.Result.Items)
            {
                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        Console.WriteLine(attr + ": " + item[attr].S);
                    }
                    else if (item[attr].N != null)
                    {
                        // If the attribute contains the string "date", process it differently
                        if (attr.ToLower().Contains("date"))
                        {
                            long     span    = long.Parse(item[attr].N);
                            DateTime theDate = epoch.AddSeconds(span);

                            Console.WriteLine(attr + ": " + theDate.ToLongDateString());
                        }
                        else
                        {
                            Console.WriteLine(attr + ": " + item[attr].N);
                        }
                    }
                }

                Console.WriteLine("");
            }
        }
Ejemplo n.º 9
0
        private void Authorize(string oauth_token, string oauth_verifier)
        {
            var    uri = new Uri(MagentoServer + "/oauth/token");
            string oauth_token_secret = (string)Session["oauth_token_secret"];

            OAuthBase oAuth     = new OAuthBase();
            string    nonce     = oAuth.GenerateNonce();
            string    timeStamp = oAuth.GenerateTimeStamp();
            string    parameters;
            string    normalizedUrl;
            string    signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret,
                                                          oauth_token, oauth_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT,
                                                          out normalizedUrl, out parameters);

            StringBuilder sb = new StringBuilder("OAuth ");

            sb.AppendFormat("oauth_verifier=\"{0}\",", oauth_verifier);
            sb.AppendFormat("oauth_token=\"{0}\",", oauth_token);
            sb.AppendFormat("oauth_version=\"{0}\",", "1.0");
            sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT");
            sb.AppendFormat("oauth_nonce=\"{0}\",", nonce);
            sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp);
            sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey);
            sb.AppendFormat("oauth_signature=\"{0}\"", signature);

            var request = (HttpWebRequest)WebRequest.Create(uri);

            request.Headers[HttpRequestHeader.Authorization] = sb.ToString();
            request.ContentType = "text/xml";
            request.Accept      = "text/xml";
            request.KeepAlive   = true;
            request.Method      = "POST";

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream       responseStream = response.GetResponseStream();
                    StreamReader responseReader = new StreamReader(responseStream);
                    string       text           = responseReader.ReadToEnd();
                    try
                    {
                        Dictionary <String, string> responseDic = GetDictionaryFromQueryString(text);

                        string token  = responseDic.First(q => q.Key == "oauth_token").Value;
                        string secret = responseDic.First(q => q.Key == "oauth_token_secret").Value;

                        Configuration      objConfig      = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                        AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
                        //Edit
                        if (objAppsettings != null)
                        {
                            objAppsettings.Settings["Magento.Token"].Value       = token;
                            objAppsettings.Settings["Magento.TokenSecret"].Value = secret;
                            objConfig.Save();
                        }

                        errorLabel.Text      = "Done";
                        errorLabel.ForeColor = System.Drawing.Color.Green;
                    }
                    catch (Exception ex)
                    {
                        errorLabel.Text = "Exchanging token failed.<br>Response text = " + text + "<br>Exception = " + ex.Message;
                    }
                }
            }
            catch (WebException ex)
            {
                var          responseStream = ex.Response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                string       resp           = responseReader.ReadToEnd();
                errorLabel.Text = resp;
            }
        }
Ejemplo n.º 10
0
        Config()
        {
            bool encrypted  = true;
            bool production = true;

            string encryptedStr = ConfigurationManager.AppSettings["encrypted"];

            if (encryptedStr != null && encryptedStr != string.Empty)
            {
                encrypted = Boolean.Parse(encryptedStr);
            }
            string productionStr = ConfigurationManager.AppSettings["production"];

            if (productionStr != null && productionStr != string.Empty)
            {
                production = Boolean.Parse(productionStr);
            }

            _AdminAccountIds = ConfigurationManager.AppSettings["AdminAccountIds"];

            _CardTelcoServiceUrl = ConfigurationManager.AppSettings["CARD_TELCO_SERVICE_URL"];
            _useCoinServiceKey   = ConfigurationManager.AppSettings["UseCoin.ServiceID"];
            _useCoinServiceUrl   = ConfigurationManager.AppSettings["USE_COIN_SERVICE_URL"];

            _SQLConnectionString = GetConnStr("SQLConnection", encrypted);

            if (!encrypted)
            {
                if (production)
                {
                    Configuration            config         = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
                    AppSettingsSection       appSettings    = (AppSettingsSection)config.GetSection("appSettings");
                    ConnectionStringsSection connectStrings = (ConnectionStringsSection)config.GetSection("connectionStrings");

                    UpdateAppSettings(appSettings, "encrypted", "true");

                    UpdateConnectionStrings(connectStrings, "SysPartnerKey", true);
                    UpdateConnectionStrings(connectStrings, "TokenConnectionString", true);

                    UpdateConnectionStrings(connectStrings, "AuthenDBConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "PaymentDBConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "ProfileDBConnectionString", true);

                    UpdateConnectionStrings(connectStrings, "SQLConnCMS", true);
                    UpdateConnectionStrings(connectStrings, "SQLConn", true);
                    UpdateConnectionStrings(connectStrings, "CGDGConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "GameDBConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "IntecomApiConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "ReportConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "EventConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "LogConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "BotConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "SSOConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "NotificationConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "DynamicPasswordAPIConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "DeviceFingerConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "EbankConnectionString", true);
                    UpdateConnectionStrings(connectStrings, "SmsBankingConnectionString", true);
                    config.Save();
                    ConfigurationManager.RefreshSection("connectionStrings");
                }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Commits specified properties (specified in the constructor) to the web.config file.
        /// WARNING - Causes an application restart!
        /// </summary>
        public List <Exception> Commit()
        {
            List <Exception> exceptions = new List <Exception>();

            Security.SecurityParams spa = Security.GetSecurityParams();

            //Wrap this all, as there inumerable things that could cause this to fail (permissions issues, medium trust, etc.)
            try
            {
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");

                AppSettingsSection       appSection        = (AppSettingsSection)config.GetSection("appSettings");
                ConnectionStringsSection connectionStrings = (ConnectionStringsSection)config.GetSection("connectionStrings");

                appSection.SectionInformation.ForceSave        = true;
                connectionStrings.SectionInformation.ForceSave = true;

                LogSecurityEvent("Web.config file opened for editing Success", "The web.config file has been opened for programmatic editing by the AspDotNetStorefront application.  This could be due to changing or setting an encryption key or machine key.  Additional information will be recorded in the security log.", spa);

                //We need to unprotect the web.config.  Otherwise we cannot write to it.
                if (appSection.SectionInformation.IsProtected || connectionStrings.SectionInformation.IsProtected)
                {
                    if (appSection.SectionInformation.IsProtected)
                    {
                        appSection.SectionInformation.UnprotectSection();
                    }
                    if (connectionStrings.SectionInformation.IsProtected)
                    {
                        connectionStrings.SectionInformation.UnprotectSection();
                    }
                    LogSecurityEvent("Web.config file decrypted Success", "The web.config appSettings and connectionString sections have been automatically decrypted to support editing.  They will be re-encrypted after editing if ProtectWebConfig is true.", spa);
                }

                //DO NOT SAVE UNTIL ALL ROUTINES ARE COMPLETE, AS COMMITTING WILL RESTART THE APPLICATION!

                #region Modify encryptKey
                try
                {
                    if (m_setEncryptKey)
                    {
                        string AddressSaltField = AppLogic.AppConfig("AddressCCSaltField");
                        string OrdersSaltField  = AppLogic.AppConfig("OrdersCCSaltField");
                        string oldEncryptKey    = spa.EncryptKey;

                        if (spa.EncryptIterations == 0)
                        {
                            spa.EncryptIterations = 1;
                        }

                        spa.EncryptKey = m_encryptKey;

                        var t = new DBTransaction();

                        using (var dbconn = DB.dbConn())
                        {
                            dbconn.Open();

                            string query = "SELECT AddressID,CustomerID,CardNumber FROM Address WHERE " +
                                           " CardNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),CardNumber)<>{0} AND CONVERT(NVARCHAR(4000),CardNumber)<>{1}" +
                                           " ORDER BY AddressID ";

                            query = string.Format(query, DB.SQuote(AppLogic.ro_CCNotStoredString), DB.SQuote(String.Empty));

                            using (var rsAddress = DB.GetRS(query, dbconn))
                            {
                                using (var dtAddress = new DataTable())
                                {
                                    dtAddress.Load(rsAddress);

                                    foreach (DataRow row in dtAddress.Rows)
                                    {
                                        var CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            var CNDecrypted = Security.UnmungeString(CN, row[AddressSaltField].ToString());
                                            if (CNDecrypted.StartsWith(Security.ro_DecryptFailedPrefix))
                                            {
                                                CNDecrypted = DB.RowField(row, "CardNumber");
                                            }
                                            row["CardNumber"] = CNDecrypted;
                                        }
                                    }

                                    foreach (DataRow row in dtAddress.Rows)
                                    {
                                        var CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            var CNEncrypted = Security.MungeString(CN, row[AddressSaltField].ToString(), spa);

                                            t.AddCommand("update Address set CardNumber=" + DB.SQuote(CNEncrypted) + " where AddressID=" + DB.RowFieldInt(row, "AddressID").ToString());
                                            CN = "1111111111111111";
                                            CN = null;
                                            row["CardNumber"] = "1111111111111111";
                                            row["CardNumber"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        using (var dbconn = DB.dbConn())
                        {
                            dbconn.Open();

                            var query = "SELECT OrderNumber,OrderGUID,CustomerID,CustomerGUID,EMail,CustomerID,CardNumber FROM Orders WHERE " +
                                        " CardNumber IS NOT NULL AND CONVERT(NVARCHAR(4000),CardNumber)<>{0} AND CONVERT(NVARCHAR(4000),CardNumber)<>{1}" +
                                        " ORDER BY OrderNumber ";

                            query = string.Format(query, DB.SQuote(AppLogic.ro_CCNotStoredString), DB.SQuote(String.Empty));

                            using (var rsOrders = DB.GetRS(query, dbconn))
                            {
                                using (var dtOrders = new DataTable())
                                {
                                    dtOrders.Load(rsOrders);

                                    foreach (DataRow row in dtOrders.Rows)
                                    {
                                        var CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            var CNDecrypted = Security.UnmungeString(CN, row[OrdersSaltField].ToString());
                                            if (CNDecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                            {
                                                CNDecrypted = DB.RowField(row, "CardNumber");
                                            }
                                            row["CardNumber"] = CNDecrypted;
                                        }
                                    }

                                    foreach (DataRow row in dtOrders.Rows)
                                    {
                                        var CN = DB.RowField(row, "CardNumber");
                                        if (CN.Length != 0 &&
                                            CN != AppLogic.ro_CCNotStoredString)
                                        {
                                            var CNEncrypted = Security.MungeString(CN, row[OrdersSaltField].ToString(), spa);
                                            t.AddCommand("update Orders set CardNumber=" + DB.SQuote(CNEncrypted) + " where OrderNumber=" + DB.RowFieldInt(row, "OrderNumber").ToString());
                                            CN = "1111111111111111";
                                            CN = null;
                                            row["CardNumber"] = "1111111111111111";
                                            row["CardNumber"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        using (var dbconn = DB.dbConn())
                        {
                            dbconn.Open();
                            using (var rsSecurityLog = DB.GetRS("select LogID,SecurityAction,Description from SecurityLog", dbconn))
                            {
                                using (var dtSecurityLog = new DataTable())
                                {
                                    dtSecurityLog.Load(rsSecurityLog);

                                    foreach (DataRow row in dtSecurityLog.Rows)
                                    {
                                        var DD          = DB.RowField(row, "Description");
                                        var DDDecrypted = Security.UnmungeString(DD);
                                        if (DDDecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            DDDecrypted = DB.RowField(row, "Description");
                                        }
                                        row["Description"] = DDDecrypted;

                                        var DDA          = DB.RowField(row, "SecurityAction");
                                        var DDADecrypted = Security.UnmungeString(DDA);
                                        if (DDADecrypted.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            DDADecrypted = DB.RowField(row, "SecurityAction");
                                        }
                                        row["SecurityAction"] = DDADecrypted;
                                    }

                                    // Only the table schema is enforcing the null constraint
                                    dtSecurityLog.Columns["Description"].AllowDBNull    = true;
                                    dtSecurityLog.Columns["SecurityAction"].AllowDBNull = true;

                                    foreach (DataRow row in dtSecurityLog.Rows)
                                    {
                                        var DD  = DB.RowField(row, "Description");
                                        var DDA = DB.RowField(row, "SecurityAction");
                                        if (DD.Length != 0 ||
                                            DDA.Length != 0)
                                        {
                                            var DDEncrypted  = Security.MungeString(DD, spa);
                                            var DDAEncrypted = Security.MungeString(DDA, spa);
                                            t.AddCommand("update SecurityLog set SecurityAction=" + DB.SQuote(DDAEncrypted) + ", Description=" + DB.SQuote(DDEncrypted) + " where logid=" + DB.RowFieldInt(row, "logid").ToString());
                                            DD = "1111111111111111";
                                            DD = null;
                                            row["Description"] = "1111111111111111";
                                            row["Description"] = null;
                                            DDA = "1111111111111111";
                                            DDA = null;
                                            row["SecurityAction"] = "1111111111111111";
                                            row["SecurityAction"] = null;
                                        }
                                    }
                                }
                            }
                        }

                        if (t.Commit())
                        {
                            // If a KEK has been supplied, we need to encrypt the EncryptionKey with it, otherwise it's
                            //  being manually set and should be left plain text.
                            //  Note that the KEK has already been encrypted and stored in the database.
                            if (!string.IsNullOrEmpty(KeyEncryptionKey))
                            {
                                // Encrypt the EncryptionKey with the KEK.
                                var encryptedEncryptKey = Security.MungeString(m_encryptKey, string.Empty, new Security.SecurityParams
                                {
                                    EncryptIterations    = AppLogic.AppConfigNativeInt("EncryptIterations"),
                                    EncryptKey           = KeyEncryptionKey,
                                    HashAlgorithm        = AppLogic.AppConfig("HashAlgorithm"),
                                    InitializationVector = AppLogic.AppConfig("InitializationVector"),
                                    KeySize = AppLogic.AppConfigNativeInt("KeySize")
                                });

                                // Save the encrypted EncryptionKey and the TEK. The TEK will be saved as plain text until the merchant encrypts the web.config.
                                appSection.Settings["EncryptKey"].Value = encryptedEncryptKey;
                                appSection.Settings[Security.TertiaryEncryptionKeyName].Value = TertiaryEncryptionKey;
                            }
                            else
                            {
                                appSection.Settings["EncryptKey"].Value = m_encryptKey;
                            }

                            ((AppConfigProvider)System.Web.Mvc.DependencyResolver.Current.GetService(typeof(AppConfigProvider)))
                            .SetAppConfigValue("NextKeyChange", DateTime.Now.AddMonths(3).ToString(), suppressSecurityLog: true);

                            LogSecurityEvent("EncryptKey Changed Success", "The encryption key was changed by a super admin using the built-in ChangeEncryptionKey Utility", spa);
                        }
                        else
                        {
                            //Set the encrypt key back, as it was not changed
                            spa.EncryptKey = oldEncryptKey;
                            LogSecurityEvent("Change EncryptKey Failed", "A database error prevented the encryption key from being changed", spa);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    LogSecurityEvent("Change EncryptKey Failed", "An exception prevented the encryption key from being changed.  View the system event log for more details", spa);
                    exceptions.Add(ex);
                }
                #endregion

                #region Modify machine key
                try
                {
                    if (m_setMachineKey)
                    {
                        //Make sure that if the KeyGenerationType is set to Manual, the user has specified a key
                        if ((m_decryptKeyGenMethod == KeyGenerationMethod.Manual && String.IsNullOrEmpty(m_decryptKey)) ||
                            (m_validationKeyGenMethod == KeyGenerationMethod.Manual && String.IsNullOrEmpty(m_validationKey)))
                        {
                            throw new ArgumentException("If your KeyGenerationMethod is set to manual, you MUST manually specify a valid key!");
                        }

                        //Random cannot be used for machine keys
                        if ((m_decryptKeyGenMethod == KeyGenerationMethod.Auto && m_decryptionKeyLength == KeyLength.Random) ||
                            (m_validationKeyGenMethod == KeyGenerationMethod.Auto && m_validationKeyLength == KeyLength.Random))
                        {
                            throw new ArgumentException("If your KeyGeneration Method is set to Auto, you must manually set the keylength");
                        }

                        MachineKeySection machineKeySec = (MachineKeySection)config.GetSection("system.web/machineKey");

                        machineKeySec.CompatibilityMode = m_compatibilityMode;
                        machineKeySec.Validation        = m_validationKeyType;

                        //Setting to anything other than AES will likely cause authentication failures, failure to add to cart, etc.
                        machineKeySec.Decryption = "AES";

                        if (m_decryptKeyGenMethod == KeyGenerationMethod.Auto)
                        {
                            m_decryptKey = Security.CreateRandomKey((int)m_decryptionKeyLength);
                        }
                        else
                        {
                            //Turn the manual key into a hex-encoded string
                            m_decryptKey = Security.ConvertToHex(m_decryptKey);
                        }

                        if (m_validationKeyGenMethod == KeyGenerationMethod.Auto)
                        {
                            m_validationKey = Security.CreateRandomKey((int)m_validationKeyLength);
                        }
                        else
                        {
                            //Turn the manual key into a hex-encoded string
                            m_validationKey = Security.ConvertToHex(m_validationKey);
                        }

                        machineKeySec.DecryptionKey = m_decryptKey;
                        machineKeySec.ValidationKey = m_validationKey;
                        machineKeySec.SectionInformation.ForceSave = true;

                        LogSecurityEvent("Static Machine Key Set/Changed Success", "The static machine key was set or changed by a super admin using the built-in Machine Key Utility", spa);
                    }
                }
                catch (Exception ex)
                {
                    SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                    LogSecurityEvent("Static Machine Key Set/Change Failed", "The static machine key could not be set or changed.  See the system event log for additional details.", spa);
                    exceptions.Add(ex);
                }
                #endregion

                #region Modify DBConn
                if (m_setDBConn)
                {
                    //TODO
                }
                #endregion

                #region Protect Web.Config

                if (m_protectWebConfig && !appSection.SectionInformation.IsProtected)
                {
                    appSection.SectionInformation.ProtectSection(m_webConfigEncryptProvider.ToString());
                    WebConfigRequiresReload = true;
                    LogSecurityEvent("Web.config file encrypted Success", "The web.config appSettings section has been encrypted.", spa);
                }
                if (m_protectWebConfig && !connectionStrings.SectionInformation.IsProtected)
                {
                    connectionStrings.SectionInformation.ProtectSection(m_webConfigEncryptProvider.ToString());
                    WebConfigRequiresReload = true;
                    LogSecurityEvent("Web.config file encrypted Success", "The web.config connectionStrings section has been encrypted.", spa);
                }

                if (!m_protectWebConfig && appSection.SectionInformation.IsProtected)
                {
                    appSection.SectionInformation.UnprotectSection();
                    WebConfigRequiresReload = true;
                    LogSecurityEvent("Web.config file decrypted Success", "The web.config appSettings section has been decrypted.", spa);
                }
                if (!m_protectWebConfig && connectionStrings.SectionInformation.IsProtected)
                {
                    connectionStrings.SectionInformation.UnprotectSection();
                    WebConfigRequiresReload = true;
                    LogSecurityEvent("Web.config file decrypted Success", "The web.config connectionStrings section has been decrypted.", spa);
                }

                #endregion

                LogSecurityEvent("Web.config file saved Success", "The web.config file has been written to disk.  See prior security log entries for details.", spa);

                //FINALLY, NOW SAVE
                config.Save(ConfigurationSaveMode.Minimal);
            }
            catch (Exception ex)
            {
                SysLog.LogException(ex, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                LogSecurityEvent("Web.config editing Failed", "An attempt to edit the web.config file programmatically failed.  See system event log for details.", spa);
                exceptions.Add(ex);
            }

            return(exceptions);
        }
Ejemplo n.º 12
0
 public static bool Contains(this AppSettingsSection config, string key)
 {
     return(config.Settings[key] != null);
 }
Ejemplo n.º 13
0
        //static async Task Main(string[] args)
        static void Main(string[] args)
        {
            var    configfile = "app.config";
            var    region     = "";
            var    table      = "";
            string filename   = "";
            string index      = "";
            bool   debug      = false;

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region   = appSettings.Settings["Region"].Value;
                table    = appSettings.Settings["Table"].Value;
                index    = appSettings.Settings["Index"].Value;
                filename = appSettings.Settings["Filename"].Value;

                if ((region == "") || (table == "") || (index == "") || (filename == ""))
                {
                    Console.WriteLine("You must specify a Region, Table, Index, and Filename in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-d":
                    debug = true;
                    break;

                default:
                    break;
                }

                i++;
            }

            // Make sure index is an int >= 0
            int indexVal;

            try
            {
                indexVal = int.Parse(index);
            }
            catch
            {
                Console.WriteLine("Could not parse " + index + " as an int");
                return;
            }

            if (indexVal < 0)
            {
                Console.WriteLine("The index value " + index + " is less than zero");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            // Open the file
            // filename is the name of the .csv file that contains customer data
            // Column1,...,ColumnN
            // in lines 2...N
            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(filename);

            DebugPrint(debug, "Opened file " + filename);

            // Store up to 25 at a time in an array
            string[] inputs = new string[26];

            // Get column names from the first line
            string headerline = file.ReadLine();

            var line  = "";
            var input = 1;

            while (((line = file.ReadLine()) != null) && (input < 26))
            {
                inputs[input] = line;
                input++;
            }

            AddItemsAsync(debug, client, table, inputs, indexVal).Wait();

            Console.WriteLine("Done");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Causes a reload of the settings containing paths with a new %pth substitution
        /// </summary>
        public void setPath(string path, Configuration config)
        {
            AppSettingsSection s       = config == null ? null : (AppSettingsSection)config.GetSection("appSettings");
            string             setting = "Set Path";

            try
            {
                if (path == null)
                {
                    path = get(s, setting = "Path", true, @"%exe\Processed");
                }

                if (string.IsNullOrEmpty(path))
                {
                    Path = Environment.CurrentDirectory;
                }
                else
                {
                    Path = (new DirectoryInfo(path)).FullName;
                }

                TempPath               = get(s, setting = "TempPath", true, @"%pth\Temp");
                SummaryLog             = get(s, setting = "SummaryLog", true, @"%pth\NKitSummary.txt");
                DatPathNameGameTdbMask = get(s, setting = "DatPathNameGameTdbMask", true, @"%exe\Dats\GameTdb\*.txt");

                if (DiscType == DiscType.GameCube)
                {
                    s = get(config, "gamecube");

                    DatPathRedumpMask = get(s, setting = "DatPathRedumpMask", true, @"%exe\Dats\GameCube_Redump\*.dat");
                    DatPathCustomMask = get(s, setting = "DatPathCustomMask", true, @"%exe\Dats\GameCube_Custom\*.dat");

                    RecoveryFilesPath      = get(s, setting = "RecoveryFilesPath", true, @"%exe\Recovery\GameCube");
                    OtherRecoveryFilesPath = get(s, setting = "OtherRecoveryFilesPath", true, @"%exe\Recovery\GameCube_Other");

                    RedumpMatchRenameToMask = get(s, setting = "RedumpMatchRenameToMask", true, @"%pth\Restored\GameCube\%nmm.%ext");
                    CustomMatchRenameToMask = get(s, setting = "CustomMatchRenameToMask", true, @"%pth\Restored\GameCube_Custom\%nmm.%ext");
                    MatchFailRenameToMask   = get(s, setting = "MatchFailRenameToMask", true, @"%pth\Restored\GameCube_MatchFail\%nmg %id6 [b].%ext");
                }
                else
                {
                    s = get(config, "wii");

                    DatPathRedumpMask = get(s, setting = "DatPathRedumpMask", true, @"%exe\Dats\Wii_Redump\*.dat");
                    DatPathCustomMask = get(s, setting = "DatPathCustomMask", true, @"%exe\Dats\Wii_Custom\*.dat");

                    RecoveryFilesPath      = get(s, setting = "RecoveryFilesPath", true, @"%exe\Recovery\Wii");
                    OtherRecoveryFilesPath = get(s, setting = "OtherRecoveryFilesPath", true, @"%exe\Recovery\Wii_Other");
                    NkitRecoveryFilesPath  = get(s, setting = "NkitRecoveryFilesPath", true, @"%exe\Recovery\Wii_NkitExtracted");

                    RedumpMatchRenameToMask = get(s, setting = "RedumpMatchRenameToMask", true, @"%pth\Restored\Wii\%nmm.%ext");
                    CustomMatchRenameToMask = get(s, setting = "CustomMatchRenameToMask", true, @"%pth\Restored\Wii_Custom\%nmm.%ext");
                    MatchFailRenameToMask   = get(s, setting = "MatchFailRenameToMask", true, @"%pth\Restored\Wii_MatchFail\%nmg %id6 [b].%ext");
                }

                DatPathNameGameTdb = getLatestFile(DatPathNameGameTdbMask);
                DatPathRedump      = getLatestFile(DatPathRedumpMask);
                DatPathCustom      = getLatestFile(DatPathCustomMask);
            }
            catch (Exception ex)
            {
                throw new HandledException(ex, "Settings - Error loading setting '{0}'", setting);
            }
        }
Ejemplo n.º 15
0
        public Settings(DiscType type, string overridePath, bool createPaths)
        {
            DiscType = type;
            string        setting = "Opening File";
            Configuration config;

            try
            {
                config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                AppSettingsSection s = config == null ? null : (AppSettingsSection)config.GetSection("appSettings");

                string path = overridePath ?? get(s, setting = "Path", true, @"%exe\Processed");
                if (string.IsNullOrEmpty(path))
                {
                    Path = Environment.CurrentDirectory;
                }
                else
                {
                    Path = (new DirectoryInfo(path)).FullName;
                }

                if (!int.TryParse(get(s, setting = "OutputLevel", false, "2"), out int ol))
                {
                    ol = 1;
                }

                OutputLevel = ol;

                EnableSummaryLog        = get(s, setting = "EnableSummaryLog", false, ConfigFileFound ? "true" : "false") == "true";
                RecoveryMatchFailDelete = get(s, setting = "RecoveryMatchFailDelete", false, ConfigFileFound ? "true" : "false") == "true";
                FullVerify      = get(s, setting = "FullVerify", false, "true") == "true";
                CalculateHashes = get(s, setting = "CalculateHashes", false, "false") == "true";
                DeleteSource    = get(s, setting = "DeleteSource", false, "false") == "true";
                TestMode        = get(s, setting = "TestMode", false, "false") == "true";
                MaskRename      = get(s, setting = "MaskRename", false, "true") == "true";
                string nkitFormat = get(s, setting = "NkitFormat", false, "iso"); //nkit format is experimental - undocumented
                NkitFormat = nkitFormat == "gcz" ? NkitFormatType.Gcz : NkitFormatType.Iso;

                NkitReencode = get(s, setting = "NkitReencode", false, "false") == "true";

                s = get(config, "junkIdSubstitutions");
                JunkIdSubstitutions = get(s, () => s?.Settings?.AllKeys?.Select(a => s.Settings[a])?.Select(a => new JunkIdSubstitution(a.Key, a.Value))?.ToArray(), new JunkIdSubstitution[0]);

                s = get(config, "junkStartOffset");
                JunkStartOffsets = get(s, () => s?.Settings?.AllKeys?.Select(a => s.Settings[a])?.Select(a => new JunkStartOffset(a.Key, long.Parse(a.Value, NumberStyles.HexNumber)))?.ToArray(), new JunkStartOffset[0]);

                s = get(config, "junkRedumpPatch");
                JunkRedumpPatches = get(s, () => s?.Settings?.AllKeys?.Select(a => s.Settings[a])?.Select(a => new JunkRedumpPatch(a.Key.Split('_')[0], long.Parse(a.Key.Split('_')[1], NumberStyles.HexNumber), Enumerable.Range(0, a.Value.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(a.Value.Substring(x, 2), 16)).ToArray()))?.ToArray(), new JunkRedumpPatch[0]);

                s = get(config, "preserveFstFileAlignment");
                PreserveFstFileAlignment = get(s, () => s?.Settings?.AllKeys?.Select(a => s.Settings[a])?.Select(a => new Tuple <string, long>(a.Key, long.Parse(a.Value, NumberStyles.HexNumber))).ToArray(), new Tuple <string, long> [0]);

                if (DiscType == DiscType.GameCube)
                {
                    s                = get(config, "gamecube");
                    RedumpFstCrcs    = get(s, setting = "RedumpFstCrcs", false, "")?.Split(',')?.Where(a => !string.IsNullOrEmpty(a)).Select(a => uint.Parse(a, NumberStyles.HexNumber)).ToArray() ?? new uint[0];
                    RedumpAppldrCrcs = get(s, setting = "RedumpAppldrCrcs", false, "")?.Split(',')?.Where(a => !string.IsNullOrEmpty(a)).Select(a => uint.Parse(a, NumberStyles.HexNumber)).ToArray() ?? new uint[0];
                }
                else
                {
                    s = get(config, "wii");
                    RedumpUpdateCrcs  = get(s, setting = "RedumpUpdateCrcs", false, "")?.Split(',')?.Where(a => !string.IsNullOrEmpty(a))?.Select(a => uint.Parse(a, NumberStyles.HexNumber)).ToArray() ?? new uint[0];
                    RedumpChannelCrcs = get(s, setting = "RedumpChannelCrcs", false, "")?.Split(',')?.Where(a => !string.IsNullOrEmpty(a))?.Select(a => uint.Parse(a, NumberStyles.HexNumber)).ToArray() ?? new uint[0];
                    RedumpChannels    = get(s, setting = "RedumpChannels", false, "")?.Split(',')?.Where(a => a != null)?.Where(a => !string.IsNullOrEmpty(a))?.Select(a => a.Split('_')).Select(a => new Tuple <string, int>(a[0], int.Parse(a[1]))).ToArray() ?? new Tuple <string, int> [0];
                    RedumpRegionData  = get(s, setting = "RedumpRegionData", false, "")?.Split(',')?.Where(a => !string.IsNullOrEmpty(a))?.Select(a => a.Split('_'))?.Select(a => new Tuple <byte[], int[]>(Enumerable.Range(0, a[0].Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(a[0].Substring(x, 2), 16)).ToArray(), a[1].Split(':').Select(b => int.Parse(b)).ToArray()))?.ToArray() ?? new Tuple <byte[], int[]> [0];

                    NkitUpdatePartitionRemoval = get(s, setting = "NkitUpdatePartitionRemoval", false, "false") == "true";
                }
            }
            catch (Exception ex)
            {
                throw new HandledException(ex, "Settings - Error loading setting '{0}'", setting);
            }
            setPath(Path, config);
            if (createPaths)
            {
                CreatePaths();
            }
        }
Ejemplo n.º 16
0
        public ActionResult SaveDB(string IP, string UID, string PWD, string DB, string IsSave)
        {
            #region 数据不为空
            if (string.IsNullOrEmpty(IP))
            {
                return(Json(new { data = "数据库IP不能为空" }, JsonRequestBehavior.AllowGet));
            }
            if (string.IsNullOrEmpty(UID))
            {
                return(Json(new { data = "数据库用户名不能为空" }, JsonRequestBehavior.AllowGet));
            }
            if (string.IsNullOrEmpty(PWD))
            {
                return(Json(new { data = "数据库密码不能为空" }, JsonRequestBehavior.AllowGet));
            }
            if (string.IsNullOrEmpty(DB))
            {
                return(Json(new { data = "数据库名不能为空" }, JsonRequestBehavior.AllowGet));
            }
            #endregion
            if (IsSave == "1")
            {
                #region 保存
                try
                {
                    Configuration      objConfig      = WebConfigurationManager.OpenWebConfiguration("~");
                    AppSettingsSection objAppSettings = (AppSettingsSection)objConfig.GetSection("appSettings");
                    if (objAppSettings != null)
                    {
                        objAppSettings.Settings["128IP"].Value  = IP;
                        objAppSettings.Settings["128UID"].Value = UID;
                        objAppSettings.Settings["128PWD"].Value = PWD;
                        objAppSettings.Settings["128DB"].Value  = DB;
                        objConfig.Save();
                        return(Json(new { data = "保存成功" }, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        return(Json(new { data = "获取配置信息为空" }, JsonRequestBehavior.AllowGet));
                    }
                }
                catch (Exception e)
                {
                    return(Json(new { data = "获取配置信息出错:" + e.Message }, JsonRequestBehavior.AllowGet));
                }
                #endregion
            }
            else
            {
                #region 测试
                //server=172.16.19.87;uid=sa;password=sa;database=ShineView_Data
                string        sql       = string.Format("server={0};uid={1};password={2};database={3}", IP, UID, PWD, DB);
                SqlConnection connecton = new SqlConnection(sql);

                try
                {
                    connecton.Open();
                    return(Json(new { data = "数据库连接测试成功", State = 1 }, JsonRequestBehavior.AllowGet));
                }
                catch (Exception err)
                {
                    return(Json(new { data = "数据库连接失败", State = 0 }, JsonRequestBehavior.AllowGet));
                }
                finally
                {
                    connecton.Close();
                }
                #endregion
            }
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            var configfile = "app.config";
            var region     = "";
            var table      = "";
            var id         = "";

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-i":
                    i++;
                    id = args[i];
                    break;

                default:
                    break;
                }

                i++;
            }

            if (id == "")
            {
                Console.WriteLine("You must supply an item ID (-i ID)");
                return;
            }

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;

                if ((region == "") || (table == ""))
                {
                    Console.WriteLine("You must specify Region and Table values in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            Task <QueryResponse> response = GetItemAsync(client, table, id);

            foreach (var item in response.Result.Items)
            {
                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        Console.WriteLine(attr + ": " + item[attr].S);
                    }
                    else if (item[attr].N != null)
                    {
                        Console.WriteLine(attr + ": " + item[attr].N.ToString());
                    }
                }

                Console.WriteLine("");
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Tab1 - 적용 버튼을 눌렀을 때
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApply_Tab1_Click(object sender, EventArgs e)
        {
            // Get the application configuration file.
            Configuration      config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection app    = config.AppSettings;

            #region 키 값 설정
            //송출 서버시스템 포트 설정
            if (ConfigurationManager.AppSettings["TCPPort"] != this.txtPort.Text)
            {
                MessageBox.Show("프로그램 재 시작시, 변경한 포트가 적용됩니다.");
                app.Settings["TCPPort"].Value = this.txtPort.Text;
            }

            //MUX 기본
            app.Settings["MUXTcId"].Value  = this.txtMUXTcId.Text;
            app.Settings["MUXRetry"].Value = this.txtMUXRetry.Text;

            //특수메세지
            app.Settings["SpcMaxId"].Value     = this.txtSpcMaxId.Text;
            app.Settings["SpcRepeatNum"].Value = this.txtSpcRepeatNum.Text;
            app.Settings["SpcWaitTime"].Value  = this.txtSpcWaitTime.Text;
            app.Settings["SpcCycle"].Value     = this.txtSpcCycle.Text;

            //일반메세지
            app.Settings["NorMaxId"].Value     = this.txtNorMaxId.Text;
            app.Settings["NorProcNum"].Value   = this.txtNorProcNum.Text;
            app.Settings["NorTransTime"].Value = this.txtNorTransTime.Text;
            app.Settings["NorRepeatNum"].Value = this.txtNorRepeatNum.Text;
            app.Settings["NorCycle"].Value     = this.txtNorCycle.Text;
            app.Settings["NorWaitTime"].Value  = this.txtNorWaitTime.Text;
            #endregion

            // Save the configuration file.
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");


            #region 이전 코드
            ////송출 시스템 설정
            //ConfigurationManager.AppSettings["TCPPort"] = this.txtPort.Text;

            ////먹스 설정
            //ConfigurationManager.AppSettings["MUXTcId"] = this.txtMUXTcId.Text;
            //ConfigurationManager.AppSettings["MUXRetry"] = this.txtMUXRetry.Text;

            ////특수 메세지
            //ConfigurationManager.AppSettings["SpcMaxId"] = this.txtSpcMaxId.Text;
            //ConfigurationManager.AppSettings["SpcRepeatNum"] = this.txtSpcRepeatNum.Text;
            //ConfigurationManager.AppSettings["SpcWaitTime"] = this.txtSpcWaitTime.Text;
            //ConfigurationManager.AppSettings["SpcCycle"] = this.txtSpcCycle.Text;

            ////일반 메세지
            //ConfigurationManager.AppSettings["NorMaxId"] = this.txtNorMaxId.Text;
            //ConfigurationManager.AppSettings["NorProcNum"] = this.txtNorProcNum.Text;
            //ConfigurationManager.AppSettings["NorTransTime"] = this.txtNorTransTime.Text;
            //ConfigurationManager.AppSettings["NorRepeatNum"] = this.txtNorRepeatNum.Text;
            //ConfigurationManager.AppSettings["NorCycle"] = this.txtNorCycle.Text;
            //ConfigurationManager.AppSettings["NorWaitTime"] = this.txtNorWaitTime.Text;
            #endregion
        }
Ejemplo n.º 19
0
        //处理微信信息
        public static void  Excute(string postStr)
        {
            Configuration      config     = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            AppSettingsSection appsection = config.GetSection("appSettings") as AppSettingsSection;

            string WechatId = appsection.Settings["WechatId"].Value.ToString();

            //   LogHelper.Info("构建xml");

            XmlDocument xmldoc = new XmlDocument();

            //  LogHelper.Info("加载字符串");
            xmldoc.Load(new System.IO.MemoryStream(System.Text.Encoding.GetEncoding("GB2312").GetBytes(postStr)));
            //   LogHelper.Info("查找字节");
            XmlNode MsgType      = xmldoc.SelectSingleNode("/xml/MsgType");
            XmlNode FromUserName = xmldoc.SelectSingleNode("/xml/FromUserName");

            LogHelper.Info(MsgType.InnerText);
            LogHelper.Info(FromUserName.InnerText);
            if (MsgType != null)
            {
                if (MsgType.InnerText == "event")
                {
                    XmlNode EventContent = xmldoc.SelectSingleNode("/xml/Event");
                    switch (EventContent.InnerText)
                    {
                    case "subscribe":
                        string subscribereplycontent = WechatReplyService.GetWechatReplyByKey("关注回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, subscribereplycontent);
                        break;

                    case "unsubscribe":
                        WechatMessageServices.ResponseSuccessMessage(FromUserName.InnerText, WechatId);
                        //此处应该给数据库中添加一个字段帮助其判断是否关注了。
                        //  WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "我哪里做的不好了,你居然敢离开我。");
                        break;

                    case "CLICK":

                        //string token = AccessTokenService.GetAccessToken();
                        //string PreMsg= "感谢您的认可,正在为您生成专属邀请卡。";
                        //string cardMediaId="slv-URo_tcvYdETXRXCkYC9LsbMh2atzB72d0NznT0o";
                        //string LastMsg="你可以把这张图片发送给需要的人,让更多星星的孩子能够健康成长。";
                        //MyWechatServices.invitationCard(token, FromUserName.InnerText, PreMsg, cardMediaId, LastMsg);
                        string CLICKreplycontent = WechatReplyService.GetWechatReplyByKey("点击回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, CLICKreplycontent);
                        break;

                    case "LOCATION":
                        // WechatMessageServices.ResponseSuccessMessage(FromUserName.InnerText, WechatId);
                        string LOCATIONreplycontent = WechatReplyService.GetWechatReplyByKey("地理位置回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, LOCATIONreplycontent);
                        break;

                    default:
                        //这是非常好用的一个地方,打开公众号,我就会和你打招呼。
                        //  string defaultreplycontent = WechatReplyService.GetWechatReplyByKey("默认回复").ReplyContent;
                        // WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, defaultreplycontent);
                        break;
                    }
                }
                else
                {
                    switch (MsgType.InnerText)
                    {
                    case "image":
                        string imgreplycontent = WechatReplyService.GetWechatReplyByKey("图片回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, imgreplycontent);
                        break;

                    case "text":

                        XmlNode TextContent = xmldoc.SelectSingleNode("/xml/Content");
                        string  keywords    = TextContent.InnerText;
                        LogHelper.Info("获取关键词:" + keywords);
                        string replycontent = WechatReplyService.GetWechatReplyByKey(keywords).ReplyContent;
                        LogHelper.Info("得到回复:" + keywords);
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, replycontent);
                        //if (string.IsNullOrEmpty(keywords))
                        //{
                        //    WechatMessageServices.ResponseSuccessMessage(FromUserName.InnerText, WechatId);
                        //    WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "您好,这是自闭症儿童家庭训练和评估系统,请点击下方菜单开始使用。\n\n 如有疑问,您可以拨打13945016428联系瑞夕老师进行咨询。");

                        //}
                        //else
                        //{
                        //    switch (keywords)
                        //    {
                        //        case "自闭症资料":
                        //            WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "您好,请先分享图片到朋友圈,帮助更多的自闭症家庭。\n\n然后请使用百度网盘下载该资料。\n\n 链接地址:https://pan.baidu.com/s/1pLdwA3D \n 密码:zeju \n\n 同时建议您点击下方开始训练按钮,加入自闭症家庭训练计划,让孩子提升更快。\n\n <a href=\"http://zbz.zuyanquxian.cn/wechat/login\">点击获取更多资料</a>");

                        //            break;
                        //        default:
                        //            LogHelper.Info("默认的东西");
                        //            WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "您好,这是自闭症儿童家庭训练和评估系统,请点击下方菜单开始使用。\n\n 如有疑问,您可以拨打13945016428联系瑞夕老师进行咨询。");
                        //            break;
                        //    }

                        //}

                        break;

                    default:
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "祝星星宝贝健康快乐成长。");
                        break;

                    //这几个一般用不到,我就没做判断。
                    case "voice":
                        string voicereplycontent = WechatReplyService.GetWechatReplyByKey("语音回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, voicereplycontent);
                        break;

                    case "video":
                        string videoreplycontent = WechatReplyService.GetWechatReplyByKey("视频回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, videoreplycontent);
                        break;

                    case "shortvideo":
                        string shortvideoreplycontent = WechatReplyService.GetWechatReplyByKey("小视频回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, shortvideoreplycontent);
                        break;

                    case "location":
                        string locationreplycontent = WechatReplyService.GetWechatReplyByKey("地理位置回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, locationreplycontent);
                        break;

                    case "link":
                        string linkreplycontent = WechatReplyService.GetWechatReplyByKey("链接回复").ReplyContent;
                        WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, linkreplycontent);
                        break;
                    }
                }
            }
            else
            {
                WechatMessageServices.ResponseTextMessage(FromUserName.InnerText, WechatId, "success");
            }
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            var    configfile = "app.config";
            string region;
            string table;
            var    indexName        = "";
            var    mainKey          = "";
            var    mainKeyType      = "";
            var    secondaryKey     = "";
            var    secondaryKeyType = "";

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-i":
                    i++;
                    indexName = args[i];
                    break;

                case "-m":
                    i++;
                    mainKey = args[i];
                    break;

                case "-k":
                    i++;
                    mainKeyType = args[i];
                    break;

                case "-s":
                    i++;
                    secondaryKey = args[i];
                    break;

                case "-t":
                    i++;
                    secondaryKeyType = args[i];
                    break;
                }

                i++;
            }

            bool          empty = false;
            StringBuilder sb    = new StringBuilder("You must supply a non-empty ");

            if (indexName == "")
            {
                empty = true;
                sb.Append("index name (-i INDEX), ");
            }

            if (mainKey == "")
            {
                empty = true;
                sb.Append("mainkey (-m PARTITION-KEY), ");
            }

            if (mainKeyType == "")
            {
                empty = true;
                sb.Append("main key type (-k TYPE), ");
            }

            if (secondaryKey == "")
            {
                empty = true;
                sb.Append("secondary key (-s SORT-KEY), ");
            }

            if (secondaryKeyType == "")
            {
                empty = true;
                sb.Append("secondary key type (-t TYPE), ");
            }

            if (empty)
            {
                Console.WriteLine(sb.ToString());
                return;
            }

            if ((mainKeyType != "string") && (mainKeyType != "number"))
            {
                Console.WriteLine("The main key type must be string or number");
                return;
            }

            if ((secondaryKeyType != "string") && (secondaryKeyType != "number"))
            {
                Console.WriteLine("The secondary key type must be string or number");
                return;
            }

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;

                if ((region == "") || (table == ""))
                {
                    Console.WriteLine("You must specify Region and Table values in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            Task <UpdateTableResponse> response = AddIndexAsync(client, table, indexName, mainKey, mainKeyType, secondaryKey, secondaryKeyType);

            Console.WriteLine("Task status:   " + response.Status);
            Console.WriteLine("Result status: " + response.Result.HttpStatusCode);
        }
Ejemplo n.º 21
0
 public AppSettingsNodeBuilder(IServiceProvider serviceProvider, AppSettingsSection appSettingsSection)
     : base(serviceProvider)
 {
     this.appSettingsSection = appSettingsSection;
 }
Ejemplo n.º 22
0
        static void Main(string[] args)
        {
            bool   debug      = false;
            var    configfile = "app.config";
            var    region     = "";
            var    table      = "";
            string customers  = "";
            string orders     = "";
            string products   = "";

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-d":
                    debug = true;
                    break;

                case "-h":
                    Usage();
                    return;

                default:
                    break;
                }

                i++;
            }

            // Get default region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region    = appSettings.Settings["Region"].Value;
                table     = appSettings.Settings["Table"].Value;
                customers = appSettings.Settings["Customers"].Value;
                orders    = appSettings.Settings["Orders"].Value;
                products  = appSettings.Settings["Products"].Value;

                if ((region == "") || (table == "") || (customers == "") || (orders == "") || (products == ""))
                {
                    Console.WriteLine("You must specify Region, Table, Customers, Orders, and Products values in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            DebugPrint(debug, "Adding customers from " + customers);
            var index = 0;

            Task <int> result = AddFromCSVAsync(debug, client, table, customers, index);

            index = result.Result;

            if (index == 0)
            {
                return;
            }

            DebugPrint(debug, "Adding orders from " + orders);

            result = AddFromCSVAsync(debug, client, table, orders, index);

            index = result.Result;

            if (index == 0)
            {
                return;
            }

            DebugPrint(debug, "Adding products from " + products);

            result = AddFromCSVAsync(debug, client, table, products, index);

            index = result.Result;

            if (index == 0)
            {
                return;
            }

            Console.WriteLine("Done");
        }
Ejemplo n.º 23
0
        public static void Main(string[] args)
        {
            Boolean syncParam   = false;
            Boolean deleteParam = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i].ToLower().Equals("-sync"))
                {
                    syncParam = true;
                }
                else if (args[i].ToLower().Equals("-delete"))
                {
                    deleteParam = true;
                }
            }

            Configuration         config    = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            AppSettingsSection    amSection = (AppSettingsSection)config.Sections["AMSettings"];
            ActiveDirectoryClient client    = new ActiveDirectoryClient(config);

            client.getUserDetailsFromActiveDirectory(
                amSection.Settings["UserExcludeFilter"].Value,
                amSection.Settings["ExcludeDisableAccount"].Value
                );
            string[] csvStr = client.createImportFile();
            Console.WriteLine("################### Sync Users - Start ###################");
            Console.WriteLine("");
            StringBuilder importDataStr = new StringBuilder();

            for (int i = 0; i < csvStr.Length; i++)
            {
                importDataStr.AppendLine(csvStr[i]);
                Console.WriteLine(csvStr[i]);
            }
            string response = "";

            if (syncParam)
            {
                response = client.uploadToAlertMedia(importDataStr.ToString());
                Console.WriteLine("*********************************************************");
                Console.WriteLine("");
                Console.WriteLine(response);
                Console.WriteLine("");
                Console.WriteLine("*********************************************************");
            }
            else
            {
                Console.WriteLine("*********************************************************");
                Console.WriteLine("");
                Console.WriteLine(" Above listed users have not been synced to AlertMedia. This was a dry run. To actually sync them, you need to send an args parameter (-sync)");
                Console.WriteLine("");
                Console.WriteLine("*********************************************************");
            }
            Console.WriteLine("");
            Console.WriteLine("################### Sync Users - End ###################");
            if (syncParam)
            {
                ArrayList                   importedUserList = new ArrayList();
                JavaScriptSerializer        j = new JavaScriptSerializer();
                Dictionary <string, object> a = (Dictionary <string, object>)j.Deserialize(response, typeof(Dictionary <string, object>));
                StringBuilder               textBoxResponse = new StringBuilder();
                if (a.ContainsKey("stats"))
                {
                    importedUserList = (ArrayList)a["successes"];
                    ArrayList failuresList = (ArrayList)a["failures"];
                    for (int i = 0; i < failuresList.Count; i++)
                    {
                        importedUserList.Add(failuresList[i]);
                    }
                }
                Console.WriteLine("################### Delete Users - Start ###################");
                Console.WriteLine("");
                string[]  delCsvStr         = client.previewDeleteUserList(importedUserList);
                ArrayList deletedUserIdList = new ArrayList();
                for (int i = 1; i < delCsvStr.Length; i++)
                {
                    string strLine = delCsvStr[i];
                    Console.WriteLine(strLine);
                    List <string> fields = SplitCSV(strLine);
                    deletedUserIdList.Add(fields[0].Replace("\"", ""));
                }
                if (deleteParam)
                {
                    client.deleteUsersFromAlertMedia(deletedUserIdList);
                    Console.WriteLine("*********************************************************");
                    Console.WriteLine("");
                    Console.WriteLine(" All the " + deletedUserIdList.Count + " users have been deleted from AlertMedia ");
                    Console.WriteLine("");
                    Console.WriteLine("*********************************************************");
                }
                else
                {
                    Console.WriteLine("*********************************************************");
                    Console.WriteLine("");
                    Console.WriteLine(deletedUserIdList.Count + " of the above listed users have not been deleted from AlertMedia. This was a dry run. To actually delete them, you need to send two args parameter (-sync -delete)");
                    Console.WriteLine("");
                    Console.WriteLine("*********************************************************");
                }
                Console.WriteLine("");
                Console.WriteLine("################### Sync Users - End ###################");
                Console.ReadLine();
            }
        }
Ejemplo n.º 24
0
 internal SparkCLRConfiguration(System.Configuration.Configuration configuration)
 {
     appSettings = configuration.AppSettings;
 }
Ejemplo n.º 25
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main(string[] args)
        {
            string paths         = null;
            string workingFolder = null;

            System.Configuration.Configuration configuration = null;

            Console.WriteLine("Vault2Git -- converting history from Vault repositories to Git");
            System.Console.InputEncoding = System.Text.Encoding.UTF8;

            // First look for Config file in the current directory - allows for repository-based config files
            string configPath = System.IO.Path.Combine(Environment.CurrentDirectory, "Vault2Git.exe.config");

            if (File.Exists(configPath))
            {
                System.Configuration.ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                configFileMap.ExeConfigFilename = configPath;

                configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
            }
            else
            {
                // Get normal exe file config.
                // This is what happens by default when using ConfigurationManager.AppSettings["setting"]
                // to access config properties
            #if DEBUG
                string applicationName = Environment.GetCommandLineArgs()[0];
            #else
                string applicationName = Environment.GetCommandLineArgs()[0] + ".exe";
            #endif

                configPath    = System.IO.Path.Combine(Environment.CurrentDirectory, applicationName);
                configuration = ConfigurationManager.OpenExeConfiguration(configPath);
            }

            // Get access to the AppSettings properties in the chosen config file
            AppSettingsSection appSettings = (AppSettingsSection)configuration.GetSection("appSettings");

            Console.WriteLine("Using config file " + configPath);

            // Get Paths parameter first as its required for validation of branches parameter
            var paramInitial = Params.InitialParse(args);
            paths = paramInitial.Paths;

            if (paths == null)
            {
                //get configuration for branches
                paths = appSettings.Settings["Convertor.Paths"].Value;
            }

            var pathPairs = paths.Split(';')
                            .ToDictionary(
                pair =>
                pair.Split('~')[1], pair => pair.Split('~')[0]
                );

            //parse rest of params
            var param = Params.Parse(args, pathPairs.Keys);

            //get count from param
            if (param.Errors.Count() > 0)
            {
                foreach (var e in param.Errors)
                {
                    Console.WriteLine(e);
                }
                return;
            }

            Console.WriteLine("   use Vault2Git --help to get additional info");

            _useConsole   = param.UseConsole;
            _useCapsLock  = param.UseCapsLock;
            _ignoreLabels = param.IgnoreLabels;
            workingFolder = param.Work;

            if (workingFolder == null)
            {
                workingFolder = appSettings.Settings["Convertor.WorkingFolder"].Value;
            }

            if (param.Verbose)
            {
                Console.WriteLine("WorkingFolder = {0}", workingFolder);
                Console.WriteLine("GitCmd = {0}", appSettings.Settings["Convertor.GitCmd"].Value);
                Console.WriteLine("GitDomainName = {0}", appSettings.Settings["Git.DomainName"].Value);
                Console.WriteLine("VaultServer = {0}", appSettings.Settings["Vault.Server"].Value);
                Console.WriteLine("VaultRepository = {0}", appSettings.Settings["Vault.Repo"].Value);
                Console.WriteLine("VaultUser = {0}", appSettings.Settings["Vault.User"].Value);
                Console.WriteLine("VaultPassword = {0}", appSettings.Settings["Vault.Password"].Value);
                Console.WriteLine("Converterpaths = {0}\n", appSettings.Settings["Convertor.Paths"].Value);
            }

            var processor = new Vault2Git.Lib.Processor()
            {
                WorkingFolder      = workingFolder,
                GitCmd             = appSettings.Settings["Convertor.GitCmd"].Value,
                GitDomainName      = appSettings.Settings["Git.DomainName"].Value,
                VaultServer        = appSettings.Settings["Vault.Server"].Value,
                VaultRepository    = appSettings.Settings["Vault.Repo"].Value,
                VaultUser          = appSettings.Settings["Vault.User"].Value,
                VaultPassword      = appSettings.Settings["Vault.Password"].Value,
                Progress           = ShowProgress,
                SkipEmptyCommits   = param.SkipEmptyCommits,
                Verbose            = param.Verbose,
                Pause              = param.Pause,
                ForceFullFolderGet = param.ForceFullFolderGet
            };


            processor.Pull
            (
                pathPairs.Where(p => param.Branches.Contains(p.Key))
                , 0 == param.Limit ? 999999999 : param.Limit
                , 0 == param.RestartLimit ? 20 : param.RestartLimit
            );

            if (!_ignoreLabels)
            {
                processor.CreateTagsFromLabels();
            }

#if DEBUG
            Console.WriteLine("Press ENTER");
            Console.ReadLine();
#endif
        }
        static void Main(string[] args)
        {
            try
            {
                // Set the path of the config file.
                string configPath = "/aspnet";

                // Get the Web application configuration object.
                Configuration config =
                    WebConfigurationManager.OpenWebConfiguration(configPath);

                // Get the section related object.
                AppSettingsSection configSection =
                    (AppSettingsSection)config.GetSection
                        ("appSettings");

                // Display title and info.
                Console.WriteLine("ASP.NET Configuration Info");
                Console.WriteLine();

                // Display Config details.
                Console.WriteLine("File Path: {0}",
                                  config.FilePath);
                Console.WriteLine("Section Path: {0}",
                                  configSection.SectionInformation.Name.ToString());
                Console.WriteLine();

                // <Snippet2>
                // Create the KeyValueConfigurationElement.
                KeyValueConfigurationElement myAdminKeyVal =
                    new KeyValueConfigurationElement(
                        "myAdminTool", "admin.aspx");
                // </Snippet2>

                // Determine if the configuration contains
                // any KeyValueConfigurationElements.
                KeyValueConfigurationCollection configSettings =
                    config.AppSettings.Settings;
                if (configSettings.AllKeys.Length == 0)
                {
                    // <Snippet6>
                    // Add KeyValueConfigurationElement to collection.
                    config.AppSettings.Settings.Add(myAdminKeyVal);
                    // </Snippet6>

                    if (!configSection.SectionInformation.IsLocked)
                    {
                        config.Save();
                        Console.WriteLine("** Configuration updated.");
                    }
                    else
                    {
                        Console.WriteLine("** Could not update, section is locked.");
                    }
                }

                // <Snippet3>
                // <Snippet4>
                // Get the KeyValueConfigurationCollection
                // from the configuration.
                KeyValueConfigurationCollection settings =
                    config.AppSettings.Settings;
                // </Snippet4>

                // <Snippet5>
                // Display each KeyValueConfigurationElement.
                foreach (KeyValueConfigurationElement keyValueElement in settings)
                {
                    Console.WriteLine("Key: {0}", keyValueElement.Key);
                    Console.WriteLine("Value: {0}", keyValueElement.Value);
                    Console.WriteLine();
                }
                // </Snippet5>
                // </Snippet3>
            }
            catch (Exception e)
            {
                // Unknown error.
                Console.WriteLine(e.ToString());
            }

            // Display and wait
            Console.ReadLine();
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Retrieves configuration information, parses the application command
        /// line, and then updates the item specified.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        public static async Task Main(string[] args)
        {
            var configfile = "app.config";
            var region     = string.Empty;
            var table      = string.Empty;
            var id         = string.Empty;
            var status     = string.Empty;

            // Get default Region and table from config file
            var efm = new ExeConfigurationFileMap
            {
                ExeConfigFilename = configfile,
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;
                table  = appSettings.Settings["Table"].Value;

                if ((region == string.Empty) || (table == string.Empty))
                {
                    Console.WriteLine("You must specify a Region and Table value in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-i":
                    i++;
                    id = args[i];
                    break;

                case "-s":
                    i++;
                    status = args[i];
                    break;
                }

                i++;
            }

            if ((status == string.Empty) || (id == string.Empty) || ((status != "backordered") && (status != "delivered") && (status != "delivering") && (status != "pending")))
            {
                Console.WriteLine("You must supply a partition number (-i ID), and status value (-s STATUS) of backordered, delivered, delivering, or pending");
                return;
            }

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            // Silenty ignores issue if id does not identify an order
            var response = await ModifyOrderStatusAsync(client, table, id, status);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Successfully updated item in " + table + " in region " + region);
            }
            else
            {
                Console.WriteLine("Could not update order status");
            }
        }
        public void BaseBehavior_Expand()
        {
            // Expand - ProcessConfigurationSection is a noop
            var builder = new FakeConfigBuilder();

            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }
            });
            AppSettingsSection origSettings = GetAppSettings();
            AppSettingsSection newSettings  = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());

            Assert.AreEqual(origSettings.Settings.Count, newSettings.Settings.Count);
            foreach (string key in origSettings.Settings.AllKeys)
            {
                Assert.AreEqual(origSettings.Settings[key].Value, newSettings.Settings[key]?.Value);
            }

            // Expand - ProcessConfigurationSection is a noop, even with prefix stuff
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }, { "prefix", "Prefix_" }, { "stripPrefix", "true" }
            });
            newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());
            Assert.AreEqual(origSettings.Settings.Count, newSettings.Settings.Count);
            foreach (string key in origSettings.Settings.AllKeys)
            {
                Assert.AreEqual(origSettings.Settings[key].Value, newSettings.Settings[key]?.Value);
            }

            // Expand - ProcessRawXml
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }
            });
            XmlNode xmlInput  = GetNode(rawXmlInput);
            XmlNode xmlOutput = builder.ProcessRawXml(xmlInput);

            Assert.AreEqual("appSettings", xmlOutput.Name);
            Assert.AreEqual("val1", GetValueFromXml(xmlOutput, "TestKey1"));
            Assert.AreEqual("TestKey1Value", GetValueFromXml(xmlOutput, "test1"));
            Assert.AreEqual("expandTestValue", GetValueFromXml(xmlOutput, "TestKey1Value"));
            Assert.AreEqual("PrefixTest1", GetValueFromXml(xmlOutput, "TestKey"));
            Assert.AreEqual("PrefixTest2", GetValueFromXml(xmlOutput, "Prefix_TestKey"));
            Assert.AreEqual("Prefix_TestKey1Value", GetValueFromXml(xmlOutput, "PreTest2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "Prefix_TestKey1"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "${TestKey1}"));

            // Expand - ProcessRawXml with prefix
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }, { "prefix", "Prefix_" }
            });
            xmlInput  = GetNode(rawXmlInput);
            xmlOutput = builder.ProcessRawXml(xmlInput);
            Assert.AreEqual("appSettings", xmlOutput.Name);
            Assert.AreEqual("val1", GetValueFromXml(xmlOutput, "TestKey1"));
            Assert.AreEqual("${TestKey1}", GetValueFromXml(xmlOutput, "test1"));
            Assert.AreEqual("expandTestValue", GetValueFromXml(xmlOutput, "${TestKey1}"));
            Assert.AreEqual("PrefixTest1", GetValueFromXml(xmlOutput, "TestKey"));
            Assert.AreEqual("PrefixTest2", GetValueFromXml(xmlOutput, "Prefix_TestKey"));
            Assert.AreEqual("Prefix_TestKey1Value", GetValueFromXml(xmlOutput, "PreTest2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "Prefix_TestKey1"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey1Value"));

            // Expand - ProcessRawXml with prefix - NOT Case-Sensitive
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }, { "prefix", "prEFiX_" }
            });
            xmlInput  = GetNode(rawXmlInput);
            xmlOutput = builder.ProcessRawXml(xmlInput);
            Assert.AreEqual("appSettings", xmlOutput.Name);
            Assert.AreEqual("val1", GetValueFromXml(xmlOutput, "TestKey1"));
            Assert.AreEqual("${TestKey1}", GetValueFromXml(xmlOutput, "test1"));
            Assert.AreEqual("expandTestValue", GetValueFromXml(xmlOutput, "${TestKey1}"));
            Assert.AreEqual("PrefixTest1", GetValueFromXml(xmlOutput, "TestKey"));
            Assert.AreEqual("PrefixTest2", GetValueFromXml(xmlOutput, "Prefix_TestKey"));
            Assert.AreEqual("Prefix_TestKey1Value", GetValueFromXml(xmlOutput, "PreTest2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "Prefix_TestKey1"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey1Value"));

            // Expand - ProcessRawXml with prefix and strip
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }, { "prefix", "prEFiX_" }, { "stripPrefix", "true" }
            });
            xmlInput  = GetNode(rawXmlInput);
            xmlOutput = builder.ProcessRawXml(xmlInput);
            Assert.AreEqual("appSettings", xmlOutput.Name);
            Assert.AreEqual("val1", GetValueFromXml(xmlOutput, "TestKey1"));
            Assert.AreEqual("Prefix_TestKey1Value", GetValueFromXml(xmlOutput, "test1"));
            Assert.AreEqual("expandTestValue", GetValueFromXml(xmlOutput, "Prefix_TestKey1Value"));
            Assert.AreEqual("PrefixTest1", GetValueFromXml(xmlOutput, "TestKey"));
            Assert.AreEqual("PrefixTest2", GetValueFromXml(xmlOutput, "Prefix_TestKey"));
            Assert.AreEqual("${Prefix_TestKey1}", GetValueFromXml(xmlOutput, "PreTest2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "${TestKey1}"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey1Value"));

            // Expand - ProcessRawXml with strip with no prefix
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Expand" }, { "stripPrefix", "true" }
            });
            xmlInput  = GetNode(rawXmlInput);
            xmlOutput = builder.ProcessRawXml(xmlInput);
            Assert.AreEqual("appSettings", xmlOutput.Name);
            Assert.AreEqual("val1", GetValueFromXml(xmlOutput, "TestKey1"));
            Assert.AreEqual("TestKey1Value", GetValueFromXml(xmlOutput, "test1"));
            Assert.AreEqual("expandTestValue", GetValueFromXml(xmlOutput, "TestKey1Value"));
            Assert.AreEqual("PrefixTest1", GetValueFromXml(xmlOutput, "TestKey"));
            Assert.AreEqual("PrefixTest2", GetValueFromXml(xmlOutput, "Prefix_TestKey"));
            Assert.AreEqual("Prefix_TestKey1Value", GetValueFromXml(xmlOutput, "PreTest2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "Prefix_TestKey1"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "TestKey2"));
            Assert.IsNull(GetValueFromXml(xmlOutput, "${TestKey1}"));
        }
Ejemplo n.º 29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        this.UCSys1.AddTable();
        this.UCSys1.AddCaptionLeft("站点全局信息配置:(您也可以打开web.config中直接修改它)");
        this.UCSys1.AddTR();
        this.UCSys1.AddTDTitle("IDX");
        this.UCSys1.AddTDTitle("项目Key");
        this.UCSys1.AddTDTitle("名称");
        this.UCSys1.AddTDTitle("值");
        this.UCSys1.AddTDTitle("描述");
        this.UCSys1.AddTREnd();

        // BP.Web.WebUser.Style

        WebConfigDescs ens = new WebConfigDescs();

        ens.RetrieveAll();

        Configuration      cfg        = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        AppSettingsSection appSetting = cfg.AppSettings;
        bool is1 = false;
        int  i   = 1;

        foreach (System.Configuration.KeyValueConfigurationElement mycfg in appSetting.Settings)
        {
            WebConfigDesc en = ens.GetEnByKey("No", mycfg.Key) as WebConfigDesc;
            if (en == null)
            {
                en    = new WebConfigDesc();
                en.No = mycfg.Key;
            }

            is1 = this.UCSys1.AddTR(is1);
            this.UCSys1.AddTDIdx(i++);
            this.UCSys1.AddTD(en.No);
            this.UCSys1.AddTD(en.Name);
            switch (en.DBType)
            {
            case "Boolen":

                RadioButton rb1 = new RadioButton();
                rb1.Text      = "是";
                rb1.GroupName = en.No;
                rb1.ID        = "rb1" + en.No;
                rb1.Enabled   = en.IsEnable;

                RadioButton rb0 = new RadioButton();
                rb0.Text      = "否";
                rb0.GroupName = en.No;
                rb0.ID        = "rb0" + en.No;
                rb0.Enabled   = en.IsEnable;


                if (System.Web.Configuration.WebConfigurationManager.AppSettings[en.No] == "1")
                {
                    rb1.Checked = true;
                }
                else
                {
                    rb0.Checked = true;
                }


                this.UCSys1.AddTDBegin();
                this.UCSys1.Add(rb1);
                this.UCSys1.Add(rb0);
                this.UCSys1.AddTDEnd();
                break;

            case "Enum":
                BP.Web.Controls.DDL ddl = new BP.Web.Controls.DDL();
                ddl.ID      = "DDL_" + en.No;
                ddl.Enabled = en.IsEnable;

                BP.Sys.SysEnums ses = new BP.Sys.SysEnums(en.No, en.Vals);
                ddl.BindSysEnum(en.No, int.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings[en.No]));
                this.UCSys1.AddTD(ddl);
                break;

            case "String":
            default:
                TextBox tb = new TextBox();
                tb.ID      = "TB_" + en.No;
                tb.Text    = System.Web.Configuration.WebConfigurationManager.AppSettings[en.No];
                tb.Columns = 80;
                tb.Enabled = en.IsEnable;
                this.UCSys1.AddTD(tb);
                break;
            }
            this.UCSys1.AddTD(en.Note);
            this.UCSys1.AddTREnd();
        }
        this.UCSys1.AddTRSum();
        this.UCSys1.AddTD();
        this.UCSys1.AddTD();
        this.UCSys1.AddTD();

        Button btn = new Button();

        btn.ID       = "Btn_Save";
        btn.Text     = " 保存全局设置 ";
        btn.CssClass = "Btn";

        this.UCSys1.AddTD(btn);
        btn.Click += new EventHandler(btn_Click);
        this.UCSys1.AddTD();
        this.UCSys1.AddTREnd();
        this.UCSys1.AddTableEnd();
    }
        public void BaseBehavior_Greedy()
        {
            // Greedy - ProcessRawXml is a noop
            var builder = new FakeConfigBuilder();

            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }
            });
            XmlNode xmlInput = GetNode(rawXmlInput);

            Assert.AreEqual(xmlInput, builder.ProcessRawXml(xmlInput));

            // Greedy - ProcessRawXml is a noop, even with prefix stuff
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }, { "prefix", "PreFIX_" }, { "stripPrefix", "true" }
            });
            xmlInput = GetNode(rawXmlInput);
            Assert.AreEqual(xmlInput, builder.ProcessRawXml(xmlInput));

            // Greedy - ProcessConfigurationSection
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }
            });
            AppSettingsSection newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());

            Assert.AreEqual("TestKey1Value", newSettings.Settings["TestKey1"]?.Value);
            Assert.AreEqual("${TestKey1}", newSettings.Settings["test1"]?.Value);
            Assert.AreEqual("expandTestValue", newSettings.Settings["${TestKey1}"]?.Value);
            Assert.AreEqual("PrefixTest1", newSettings.Settings["TestKey"]?.Value);
            Assert.AreEqual("Prefix_TestKeyValue", newSettings.Settings["Prefix_TestKey"]?.Value);
            Assert.AreEqual("${Prefix_TestKey1}", newSettings.Settings["PreTest2"]?.Value);
            Assert.AreEqual("TestKey2Value", newSettings.Settings["TestKey2"]?.Value);
            Assert.AreEqual("Prefix_TestKey1Value", newSettings.Settings["Prefix_TestKey1"]?.Value);

            // Greedy - ProcessConfigurationSection with prefix
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }, { "prefix", "Prefix_" }
            });
            newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());
            Assert.AreEqual("val1", newSettings.Settings["TestKey1"]?.Value);
            Assert.AreEqual("${TestKey1}", newSettings.Settings["test1"]?.Value);
            Assert.AreEqual("expandTestValue", newSettings.Settings["${TestKey1}"]?.Value);
            Assert.AreEqual("PrefixTest1", newSettings.Settings["TestKey"]?.Value);
            Assert.AreEqual("Prefix_TestKeyValue", newSettings.Settings["Prefix_TestKey"]?.Value);
            Assert.AreEqual("${Prefix_TestKey1}", newSettings.Settings["PreTest2"]?.Value);
            Assert.AreEqual("Prefix_TestKey1Value", newSettings.Settings["Prefix_TestKey1"]?.Value);
            Assert.IsNull(newSettings.Settings["TestKey2"]?.Value);

            // Greedy - ProcessConfigurationSection with prefix - NOT Case-Sensitive
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }, { "prefix", "preFIX_" }
            });
            newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());
            Assert.AreEqual("val1", newSettings.Settings["TestKey1"]?.Value);
            Assert.AreEqual("${TestKey1}", newSettings.Settings["test1"]?.Value);
            Assert.AreEqual("expandTestValue", newSettings.Settings["${TestKey1}"]?.Value);
            Assert.AreEqual("PrefixTest1", newSettings.Settings["TestKey"]?.Value);
            Assert.AreEqual("Prefix_TestKeyValue", newSettings.Settings["Prefix_TestKey"]?.Value);
            Assert.AreEqual("${Prefix_TestKey1}", newSettings.Settings["PreTest2"]?.Value);
            Assert.AreEqual("Prefix_TestKey1Value", newSettings.Settings["Prefix_TestKey1"]?.Value);
            Assert.IsNull(newSettings.Settings["TestKey2"]?.Value);

            // Greedy - ProcessConfigurationSection with prefix and strip
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }, { "prefix", "preFIX_" }, { "stripPrefix", "true" }
            });
            newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());
            Assert.AreEqual("Prefix_TestKey1Value", newSettings.Settings["TestKey1"]?.Value);
            Assert.AreEqual("${TestKey1}", newSettings.Settings["test1"]?.Value);
            Assert.AreEqual("expandTestValue", newSettings.Settings["${TestKey1}"]?.Value);
            Assert.AreEqual("Prefix_TestKeyValue", newSettings.Settings["TestKey"]?.Value);
            Assert.AreEqual("PrefixTest2", newSettings.Settings["Prefix_TestKey"]?.Value);
            Assert.AreEqual("${Prefix_TestKey1}", newSettings.Settings["PreTest2"]?.Value);
            Assert.IsNull(newSettings.Settings["Prefix_TestKey1"]?.Value);
            Assert.IsNull(newSettings.Settings["TestKey2"]?.Value);

            // Greedy - ProcessConfigurationSection with strip with no prefix
            builder = new FakeConfigBuilder();
            builder.Initialize("test", new System.Collections.Specialized.NameValueCollection()
            {
                { "mode", "Greedy" }, { "stripPrefix", "true" }
            });
            newSettings = (AppSettingsSection)builder.ProcessConfigurationSection(GetAppSettings());
            Assert.AreEqual("TestKey1Value", newSettings.Settings["TestKey1"]?.Value);
            Assert.AreEqual("${TestKey1}", newSettings.Settings["test1"]?.Value);
            Assert.AreEqual("expandTestValue", newSettings.Settings["${TestKey1}"]?.Value);
            Assert.AreEqual("PrefixTest1", newSettings.Settings["TestKey"]?.Value);
            Assert.AreEqual("Prefix_TestKeyValue", newSettings.Settings["Prefix_TestKey"]?.Value);
            Assert.AreEqual("${Prefix_TestKey1}", newSettings.Settings["PreTest2"]?.Value);
            Assert.AreEqual("TestKey2Value", newSettings.Settings["TestKey2"]?.Value);
            Assert.AreEqual("Prefix_TestKey1Value", newSettings.Settings["Prefix_TestKey1"]?.Value);
        }
Ejemplo n.º 31
0
    //</Snippet4>

    // Show how use the AppSettings and ConnectionStrings
    // properties.
    static void GetSections(string section)
    {
        try
        {
            // Get the current configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Get the selected section.
            switch (section)
            {
            case "appSettings":
                //<Snippet5>
                try
                {
                    AppSettingsSection appSettings =
                        config.AppSettings as AppSettingsSection;
                    Console.WriteLine("Section name: {0}",
                                      appSettings.SectionInformation.SectionName);

                    // Get the AppSettings section elements.
                    Console.WriteLine();
                    Console.WriteLine("Using AppSettings property.");
                    Console.WriteLine("Application settings:");
                    // Get the KeyValueConfigurationCollection
                    // from the configuration.
                    KeyValueConfigurationCollection settings =
                        config.AppSettings.Settings;

                    // Display each KeyValueConfigurationElement.
                    foreach (KeyValueConfigurationElement keyValueElement in settings)
                    {
                        Console.WriteLine("Key: {0}", keyValueElement.Key);
                        Console.WriteLine("Value: {0}", keyValueElement.Value);
                        Console.WriteLine();
                    }
                }
                catch (ConfigurationErrorsException e)
                {
                    Console.WriteLine("Using AppSettings property: {0}",
                                      e.ToString());
                }
                //</Snippet5>
                break;

            case "connectionStrings":
                //<Snippet6>
                ConnectionStringsSection
                    conStrSection =
                    config.ConnectionStrings as ConnectionStringsSection;
                Console.WriteLine("Section name: {0}",
                                  conStrSection.SectionInformation.SectionName);

                try
                {
                    if (conStrSection.ConnectionStrings.Count != 0)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Using ConnectionStrings property.");
                        Console.WriteLine("Connection strings:");

                        // Get the collection elements.
                        foreach (ConnectionStringSettings connection in
                                 conStrSection.ConnectionStrings)
                        {
                            string name             = connection.Name;
                            string provider         = connection.ProviderName;
                            string connectionString = connection.ConnectionString;

                            Console.WriteLine("Name:               {0}",
                                              name);
                            Console.WriteLine("Connection string:  {0}",
                                              connectionString);
                            Console.WriteLine("Provider:            {0}",
                                              provider);
                        }
                    }
                }
                catch (ConfigurationErrorsException e)
                {
                    Console.WriteLine("Using ConnectionStrings property: {0}",
                                      e.ToString());
                }
                //</Snippet6>
                break;

            default:
                Console.WriteLine(
                    "GetSections: Unknown section (0)", section);
                break;
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetSections: (0)", err.ToString());
        }
    }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            var debug      = false;
            var region     = "";
            var configfile = "app.config";

            // Get default region from config file
            var efm = new ExeConfigurationFileMap {
                ExeConfigFilename = configfile
            };

            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(efm, ConfigurationUserLevel.None);

            if (configuration.HasFile)
            {
                AppSettingsSection appSettings = configuration.AppSettings;
                region = appSettings.Settings["Region"].Value;

                if (region == "")
                {
                    Console.WriteLine("You must set a Region value in " + configfile);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Could not find " + configfile);
                return;
            }

            int i = 0;

            while (i < args.Length)
            {
                switch (args[i])
                {
                case "-h":
                    Usage();
                    return;

                case "-d":
                    debug = true;
                    break;

                default:
                    break;
                }

                i++;
            }

            DebugPrint(debug, "Debugging enabled");

            var             newRegion = RegionEndpoint.GetBySystemName(region);
            IAmazonDynamoDB client    = new AmazonDynamoDBClient(newRegion);

            Task <ListTablesResponse> response = ShowTablesAsync(client);

            Console.WriteLine("Found " + response.Result.TableNames.Count.ToString() + " tables in " + region + " region:");

            foreach (var table in response.Result.TableNames)
            {
                Console.WriteLine("  " + table);
            }
        }