Ejemplo n.º 1
0
 /// <summary>
 /// This method is used to update the key value
 /// </summary>
 /// <param name="newValue">New value of the key</param>
 private static void UpdateKey(string newValue)
 {
     ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
     configFile.ExeConfigFilename = ConfigurationManager.AppSettings["configPath"];
     Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
     config.AppSettings.Settings["password"].Value = newValue;
     config.Save();
 }
		public override object Clone ()
		{
			ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
			map.exeConfigFilename = exeConfigFilename;
			map.localUserConfigFilename = localUserConfigFilename;
			map.roamingUserConfigFilename = roamingUserConfigFilename;
			map.MachineConfigFilename = MachineConfigFilename;
			return map;
		}
Ejemplo n.º 3
0
    public Configuration GetConfig(string Path)
    {
        Configuration retVal;

        ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();

        configFileMap.ExeConfigFilename = Path;

        retVal = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

        return retVal;
    }
Ejemplo n.º 4
0
 public static string Config(string key)
 {
     try
     {
         ExeConfigurationFileMap file = new ExeConfigurationFileMap();
         file.ExeConfigFilename = @"D:\FlowPortal.net\Message.config";
         Configuration config = ConfigurationManager.OpenMappedExeConfiguration(file, ConfigurationUserLevel.None);
         AppSettingsSection appsection = (AppSettingsSection)config.GetSection("appSettings");
         return appsection.Settings[key].Value;
     }
     catch (Exception ex)
     {
         throw new Exception(String.Format("在获取Key为{0}时出现异常:{1}/源位置:{2}", key, ex.Message, ex.StackTrace));
     }
 }
Ejemplo n.º 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = Server.MapPath("~/config/app.config") };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            var section = (AppSettingsSection)config.GetSection("appSettings");
            var strUseSSL = section.Settings["UseSSL"].Value;

            txtHost.Text = section.Settings["Host"].Value;
            txtPort.Text = section.Settings["Port"].Value;
            txtEmail.Text = section.Settings["Email"].Value;
            txtUserName.Text = section.Settings["UserName"].Value;
            txtReceivedEmails.Text = section.Settings["ReceivedEmails"].Value;
            chkUseSSL.Checked = strUseSSL.ToLower() == "true" ? true : false;
        }
    }
Ejemplo n.º 6
0
    protected void btnSaveEmail_Click(object sender, EventArgs e)
    {
        lblSaveEmail.Text = "";
        var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = Server.MapPath("~/config/app.config") };
        var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        var section = (AppSettingsSection)config.GetSection("appSettings");
        var strUseSSL = section.Settings["UseSSL"].Value;

        section.Settings["Host"].Value=txtHost.Text;
        section.Settings["Port"].Value=txtPort.Text;
        section.Settings["Email"].Value = txtEmail.Text;
        section.Settings["UserName"].Value = txtUserName.Text;
        section.Settings["Password"].Value = TLLib.MD5Hash.Encrypt(txtPassword.Text.Trim(), true);
        section.Settings["ReceivedEmails"].Value = txtReceivedEmails.Text;
        section.Settings["UseSSL"].Value = chkUseSSL.Checked.ToString().ToLower();

        config.Save(ConfigurationSaveMode.Full);  // Save changes

        lblSaveEmail.Text = "Done.";
    }
Ejemplo n.º 7
0
 /// <inheritdoc />
 public global::System.Configuration.Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap pExeConfigurationFileMap, ConfigurationUserLevel pConfigurationUserLevel)
 {
     return(ConfigurationManager.OpenMappedExeConfiguration(pExeConfigurationFileMap, pConfigurationUserLevel));
 }
Ejemplo n.º 8
0
        }//end ServerEnvironment

        public static void Init()
        {
            try
            {
                ExeConfigurationFileMap ecf = new ExeConfigurationFileMap();
                DirectoryInfo           currentDirectory = new DirectoryInfo(Environment.CurrentDirectory);
                string constFileName = currentDirectory.ToString().Replace("\\bin\\Debug", "") + "\\TestSettings.config";
                //string constFileName = currentDirectory.ToString().Replace("\\bin\\Release", "") + "\\TestSettings.config";
                ecf.ExeConfigFilename = constFileName;
                Configuration dllConfig = ConfigurationManager.OpenMappedExeConfiguration(ecf, ConfigurationUserLevel.None);
                _frameGlobalsConfig           = dllConfig;
                StartedTime                   = DateTime.Now;
                testFixtureName               = dllConfig.AppSettings.Settings["TestFixtureName"].Value;
                BaseUrl                       = dllConfig.AppSettings.Settings["Base_URL"].Value;
                App_File                      = dllConfig.AppSettings.Settings["APP_File"].Value;
                AndroidVersion                = dllConfig.AppSettings.Settings["AndroidVersion"].Value;
                userAgent                     = dllConfig.AppSettings.Settings["UserAgent"].Value;
                userAgentName                 = dllConfig.AppSettings.Settings["UserAgentName"].Value.ToString();
                BrowserName                   = dllConfig.AppSettings.Settings["browserName"].Value;
                DeviceName                    = dllConfig.AppSettings.Settings["DeviceName"].Value;
                AutomationName                = dllConfig.AppSettings.Settings["AutomationName"].Value;
                PlatformVersion               = dllConfig.AppSettings.Settings["platformVersion"].Value;
                PlatformName                  = dllConfig.AppSettings.Settings["platformName"].Value;
                AppPackage                    = dllConfig.AppSettings.Settings["appPackage"].Value;
                AppActivity                   = dllConfig.AppSettings.Settings["appActivity"].Value;
                implicitWait                  = dllConfig.AppSettings.Settings["ImplicitTimeOut"].Value;
                waitForScript                 = dllConfig.AppSettings.Settings["WaitForScript"].Value;
                DeviceToTest                  = (DeviceTypes)Enum.Parse(typeof(DeviceTypes), dllConfig.AppSettings.Settings["DeviceType"].Value.ToString(CultureInfo.InvariantCulture));
                browserType                   = (BrowserTypes)Enum.Parse(typeof(BrowserTypes), dllConfig.AppSettings.Settings["BrowserType"].Value.ToString(CultureInfo.InvariantCulture));
                automationApproach            = (AutomationApproach)Enum.Parse(typeof(AutomationApproach), dllConfig.AppSettings.Settings["AutomationApproach"].Value.ToString(CultureInfo.InvariantCulture));
                appType                       = (AppType)Enum.Parse(typeof(AppType), dllConfig.AppSettings.Settings["AppType"].Value.ToString(CultureInfo.InvariantCulture));
                CapturescreenshotforPassSetps = dllConfig.AppSettings.Settings["CapturescreenshotforAllsteps"].Value;
                //TestDataPath = dllConfig.AppSettings.Settings["TestDataPath"].Value.ToString(CultureInfo.InvariantCulture);
                htmlPath = FileReader.GetFilePath(FilePath.Report);
                //htmlPath = BaseTest.fileReport;
                language = dllConfig.AppSettings.Settings["Language"].Value;

                // Assing values
                if (FrameGlobals.automationApproach != AutomationApproach.Mobile)
                {
                    if (userAgent == "Yes")
                    {
                        switch (userAgentName)
                        {
                        //iPhone ios4
                        case "ios4":
                            userAgentValue = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5";
                            break;

                        //iPhone ios4s
                        case "ios4s":
                            userAgentValue = "Mozilla/5.0 (iPhone; CPU iPhone OS6_1_3 like Mac OS X)App|eWebKit/536.26 (KHTML, likeGecko) Version/6.0 Mobile/10B329Safari/8536.25";
                            break;

                        //iPhone ios5
                        case "ios5":
                            userAgentValue = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48";
                            break;

                        // iPod IoS3
                        case "ipod":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
                            break;

                        // iPad Mini
                        case "ipadmini":
                            userAgentValue = "Mozilla/5.0 (iPad; CPU 08 6_1 like Mac OS X)AppIeWebKit/536.26 (KHTML, like Gecko)Version/6.0 Mobile/10B141 Safari/8536.25";
                            break;

                        // ipad
                        case "ipad":
                            userAgentValue = "Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10";
                            break;

                        // iPad2
                        case "ipad2":
                            userAgentValue = "Mozilla/5.0(iPad; U; CPU OS 4_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8F191 Safari/6533.18.5";
                            break;

                        //Nexus 4 (4.2)
                        case "nexus4":
                            userAgentValue = "Mozilla/5.0 (Linux; Android 4.2; Nexus 4 Build/JVP15Q) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19";
                            break;

                        //Nexus 5 (4.4)
                        case "nexus5":
                            userAgentValue = "Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/KRT16M) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 Mobile Safari/537.36";
                            break;

                        //Nexus 7 (4.1.1)
                        case "nexus7":
                            userAgentValue = "Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19";
                            break;

                        //HTC pyramid (2.3.4)
                        case "htcp":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 2.3.3; zh-tw; HTC_Pyramid Build/GRI40) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                            break;

                        //HTC One (4.0.3)
                        case "htc1":
                            userAgentValue = "Mozilla/5.0 (Linux; Android 4.0.3; HTC One X Build/IML74K) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19";
                            break;

                        //Sony - experia arc (2.3)
                        case "sonyxarc":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 2.3; xx-xx; SonyEricssonLT26i Build/6.0.A.0.507) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                            break;

                        //Windows Phone 7 (Nokia Lumia 800 - OS7.5:IE9)
                        case "win7":
                            userAgentValue = "Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0; NOKIA; Lumia 800)";
                            break;

                        //Windows Phone 8 (Nokia Lumia 920: OS8:IE10)
                        case "win8":
                            userAgentValue = "Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 920)";
                            break;

                        //BlackBerry 9800 (6.0)
                        case "BB9800":
                            userAgentValue = "Mozilla/5.0 (BlackBerry; U; BlackBerry 9800; en) AppleWebKit/534.1+ (KHTML, like Gecko) Version/6.0.0.337 Mobile Safari/534.1+2011-10-16 20:21:10";
                            break;

                        //BlackBerry 9320 (7.1)
                        case "BB9320":
                            userAgentValue = "Mozilla/5.0 (BlackBerry; U; BlackBerry 9320; en-GB) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.398 Mobile Safari/534.11+";
                            break;

                        //Samsung - galaxy ace (2.2.1)
                        case "samace":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 2.2.1; en-gb; GT-S5830 Build/FROYO) AppleWebKit/525.10 (KHTML, like Gecko) Version/3.0.4 Mobile Safari/523.12.2";
                            break;

                        //Samsung - S2 (4.0.3)
                        case "sams2":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 4.0.3; fr-fr; GT-I9100 Samsung Galaxy S2 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
                            break;

                        //Samsung - S3 (4.1.1)
                        case "sams3":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Samsung Galaxy S3) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
                            break;

                        //Samsung - S4 (4.0.3)
                        case "sams4":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 4.0.3; fr-fr; SGH-I1337 Samsung Galaxy S4 Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
                            break;

                        //Samsung Tab
                        case "samtab":
                            userAgentValue = "Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-N8000Buildl|MM76D) App|eWebKitl534.30 (KHTML, like Gecko)Version/4.0 Safaril534.30";
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //}//end if
        }//end Init
Ejemplo n.º 9
0
        private void UpdateCrmSvcUtilConfig(EarlyBoundGeneratorConfig earlyBoundGeneratorConfig)
        {
            lock (_updateAppConfigToken)
            {
                if (_configUpdated)
                {
                    return;
                }
                //load custom config file
                Configuration file;

                string filePath = Path.GetFullPath(earlyBoundGeneratorConfig.CrmSvcUtilPath) + ".config";
                var    map      = new ExeConfigurationFileMap {
                    ExeConfigFilename = filePath
                };
                try
                {
                    file = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
                }
                catch (ConfigurationErrorsException ex)
                {
                    if (ex.BareMessage == "Root element is missing.")
                    {
                        File.Delete(filePath);
                        UpdateCrmSvcUtilConfig(earlyBoundGeneratorConfig);
                        return;
                    }
                    throw;
                }

                var extensions = earlyBoundGeneratorConfig.ExtensionConfig;
                if (UpdateConfigAppSetting(file, "ActionCommandLineText", extensions.ActionCommandLineText, true) |
                    UpdateConfigAppSetting(file, "ActionsToSkip", extensions.ActionsToSkip?.Replace("-", "")) |
                    UpdateConfigAppSetting(file, "AddDebuggerNonUserCode", extensions.AddDebuggerNonUserCode.ToString()) |
                    UpdateConfigAppSetting(file, "AddNewFilesToProject", extensions.AddNewFilesToProject.ToString()) |
                    UpdateConfigAppSetting(file, "CreateOneFilePerAction", extensions.CreateOneFilePerAction.ToString()) |
                    UpdateConfigAppSetting(file, "CreateOneFilePerEntity", extensions.CreateOneFilePerEntity.ToString()) |
                    UpdateConfigAppSetting(file, "CreateOneFilePerOptionSet", extensions.CreateOneFilePerOptionSet.ToString()) |
                    UpdateConfigAppSetting(file, "EntityAttributeSpecifiedNames", extensions.EntityAttributeSpecifiedNames) |
                    UpdateConfigAppSetting(file, "EntityCommandLineText", extensions.EntityCommandLineText, true) |
                    UpdateConfigAppSetting(file, "EntitiesToSkip", extensions.EntitiesToSkip) |
                    UpdateConfigAppSetting(file, "EntitiesWhitelist", extensions.EntitiesWhitelist) |
                    UpdateConfigAppSetting(file, "EntityPrefixesToSkip", extensions.EntityPrefixesToSkip) |
                    UpdateConfigAppSetting(file, "GenerateActionAttributeNameConsts", extensions.GenerateActionAttributeNameConsts.ToString()) |
                    UpdateConfigAppSetting(file, "GenerateAttributeNameConsts", extensions.GenerateAttributeNameConsts.ToString()) |
                    UpdateConfigAppSetting(file, "GenerateAnonymousTypeConstructor", extensions.GenerateAnonymousTypeConstructor.ToString()) |
                    UpdateConfigAppSetting(file, "GenerateEntityRelationships", extensions.GenerateEntityRelationships.ToString()) |
                    UpdateConfigAppSetting(file, "GenerateEnumProperties", extensions.GenerateEnumProperties.ToString()) |
                    UpdateConfigAppSetting(file, "GenerateOnlyReferencedOptionSets", extensions.GenerateOnlyReferencedOptionSets.ToString()) |
                    UpdateConfigAppSetting(file, "InvalidCSharpNamePrefix", extensions.InvalidCSharpNamePrefix) |
                    UpdateConfigAppSetting(file, "MakeAllFieldsEditable", extensions.MakeAllFieldsEditable.ToString()) |
                    UpdateConfigAppSetting(file, "MakeReadonlyFieldsEditable", extensions.MakeReadonlyFieldsEditable.ToString()) |
                    UpdateConfigAppSetting(file, "MakeResponseActionsEditable", extensions.MakeResponseActionsEditable.ToString()) |
                    UpdateConfigAppSetting(file, "LocalOptionSetFormat", extensions.LocalOptionSetFormat) |
                    UpdateConfigAppSetting(file, "OptionSetPrefixesToSkip", extensions.OptionSetPrefixesToSkip) |
                    UpdateConfigAppSetting(file, "OptionSetsToSkip", extensions.OptionSetsToSkip) |
                    UpdateConfigAppSetting(file, "OptionSetCommandLineText", extensions.OptionSetCommandLineText, true) |
                    UpdateConfigAppSetting(file, "OptionSetLanguageCodeOverride", extensions.OptionSetLanguageCodeOverride?.ToString()) |
                    UpdateConfigAppSetting(file, "PropertyEnumMappings", extensions.PropertyEnumMappings) |
                    UpdateConfigAppSetting(file, "RemoveRuntimeVersionComment", extensions.RemoveRuntimeVersionComment.ToString()) |
                    UpdateConfigAppSetting(file, "UseDeprecatedOptionSetNaming", extensions.UseDeprecatedOptionSetNaming.ToString()) |
                    UpdateConfigAppSetting(file, "UnmappedProperties", extensions.UnmappedProperties) |
                    UpdateConfigAppSetting(file, "UseTfsToCheckoutFiles", extensions.UseTfsToCheckoutFiles.ToString()) |
                    UpdateConfigAppSetting(file, "UseXrmClient", extensions.UseXrmClient.ToString()))

                {
                    file.Save(ConfigurationSaveMode.Minimal);
                }
                _configUpdated = true;
            }
        }
Ejemplo n.º 10
0
    protected void LoadConfiguration()
    {
        if(!System.IO.File.Exists(this.AppHomeDirectory + "/gpartimage-ng.config")) return;

        var mapper = new ExeConfigurationFileMap { ExeConfigFilename = this.AppHomeDirectory + "/gpartimage-ng.config" };

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

        if (config.AppSettings.Settings["ManualPort"] != null)
        {
            ManualPort.Active = bool.Parse(config.AppSettings.Settings["ManualPort"].Value);
            PortFromList.Active = !(bool.Parse(config.AppSettings.Settings["ManualPort"].Value));
        }

        if (config.AppSettings.Settings["HostPortNum"] != null) HostPortNum.Text = config.AppSettings.Settings["HostPortNum"].Value;

        if (config.AppSettings.Settings["ImageFilePath"] != null) ImageFilePath.Text = config.AppSettings.Settings["ImageFilePath"].Value;

        if (config.AppSettings.Settings["ManualDevName"] != null)
        {
            ManualDevName.Active = bool.Parse(config.AppSettings.Settings["ManualDevName"].Value);
            DevNameFromList.Active = !(bool.Parse(config.AppSettings.Settings["ManualDevName"].Value));
        }

        if (config.AppSettings.Settings["DevWord"] != null) DevWord.Text = config.AppSettings.Settings["DevWord"].Value;

        if (config.AppSettings.Settings["SaveImageFilePath"] != null) SaveImageFilePath.Text = config.AppSettings.Settings["SaveImageFilePath"].Value;

        if (config.AppSettings.Settings["ManualSaveDevName"] != null)
        {
            ManualSaveDevName.Active = bool.Parse(config.AppSettings.Settings["ManualSaveDevName"].Value);
            SaveDevNameFromList.Active = !(bool.Parse(config.AppSettings.Settings["ManualSaveDevName"].Value));
        }

        if (config.AppSettings.Settings["SaveDevWord"] != null) SaveDevWord.Text = config.AppSettings.Settings["SaveDevWord"].Value;

        if (config.AppSettings.Settings["ManualDelDevName"] != null)
        {
            ManualDelDevName.Active = bool.Parse(config.AppSettings.Settings["ManualDelDevName"].Value);
            DelDevNameFromList.Active = !(bool.Parse(config.AppSettings.Settings["ManualDelDevName"].Value));
        }

        if (config.AppSettings.Settings["DelDevWord"] != null) DelDevWord.Text = config.AppSettings.Settings["DelDevWord"].Value;

        if (config.AppSettings.Settings["CmdShell"] != null)
        {
            this.CmdShell = config.AppSettings.Settings["CmdShell"].Value;
            CfgCmdShell.Text = this.CmdShell;
        }

        if (config.AppSettings.Settings["Partimage"] != null)
        {
            this.PartImage = config.AppSettings.Settings["Partimage"].Value;
            CfgPartImage.Text = this.PartImage;
        }
    }
Ejemplo n.º 11
0
        public UploaderApplicationContext()
        {
            // TEMPORARY MAINTENANCE: Keep around for a few weeks after 2011/02/3
            // Clean up from version 0.025 and lower, delete old config file
            try { File.Delete(executableLocation + ".config"); } catch (Exception) {}
            try { File.Delete(executableLocation + ".old_version"); } catch (Exception) {}

            InitializeContext();

            Microsoft.Win32.SystemEvents.SessionEnding    += new Microsoft.Win32.SessionEndingEventHandler(SystemEvents_SessionEnding);
            Microsoft.Win32.SystemEvents.PowerModeChanged += new Microsoft.Win32.PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);

            string localData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();

            configFileMap.ExeConfigFilename = Path.Combine(localData, "shurcooL/InstantBackgroundUploader/InstantBackgroundUploader.local.config");
            config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            if (null != config.AppSettings.Settings["Usage Time"])
            {
                usageSeconds = Convert.ToInt64(config.AppSettings.Settings["Usage Time"].Value);
            }
            if (null != config.AppSettings.Settings["Total Time"])
            {
                totalSeconds = Convert.ToInt64(config.AppSettings.Settings["Total Time"].Value);
            }
            if (null != config.AppSettings.Settings["Has Been Plugged In"])
            {
                hasBeenPluggedIn = Convert.ToBoolean(config.AppSettings.Settings["Has Been Plugged In"].Value);
            }
            if (null != config.AppSettings.Settings["Previous BatteryLifePercent"])
            {
                double previousBatteryLifePercent = Convert.ToDouble(config.AppSettings.Settings["Previous BatteryLifePercent"].Value);

                if (SystemInformation.PowerStatus.BatteryLifePercent > previousBatteryLifePercent + 0.03)
                {
                    hasBeenPluggedIn = true;
                }
            }

            if (SystemInformation.PowerStatus.BatteryLifePercent >= 0.95)
            {
                // Battery is almost fully charged at start up, reset Usage and Total counters
                usageSeconds     = 0;
                totalSeconds     = 0;
                hasBeenPluggedIn = false;
            }

            // Check if we're inside Dropbox

            /*try {
             *      string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
             *      TextReader tr = new StreamReader(Path.Combine(appData, "Dropbox/host.db"));
             *      tr.ReadLine();		// Skip first line
             *      MessageBox.Show(DecodeFrom64(tr.ReadLine()) + "\n" + executableLocation);
             *      tr.Close();
             * } catch (Exception) {}*/

            // Compute SHA1 hash

            /*try {
             *      long exeLength = new FileInfo(executableLocation).Length;
             *      byte[] exeData = File.ReadAllBytes(executableLocation);
             *      string exeHash = SHA1Encrypt(exeData);
             *      MessageBox.Show("Length: " + exeLength + "\n" + exeHash);
             * } catch (Exception) {}*/

            if (!releaseMode)
            {
                ShowMainForm();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Loads server connection information and application settings from persistent file storage.
        /// </summary>
        /// <remarks>A setting named OverrideConfig can optionally be added. If a config file that this setting
        /// refers to exists, that config file is read instead of the config file specified in the path parameter.
        /// This allows for an alternate config file, for example a global config file shared by multiple applications.
        /// </summary>
        /// <param name="connectionName">The name of the connection string in the configuration file to use.
        /// Each CRM organization can have its own connection string. A value of null or String.Empty results
        /// in the first (top most) connection string being used.</param>
        /// <param name="path">The full or relative pathname of the configuration file.</param>
        public virtual void Load(string connectionName, string path)
        {
            // Check passed parameters.
            if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path))
            {
                throw new ArgumentException("The specified app.config file path is invalid.", this.ToString());
            }
            else
            {
                PathToConfig = path;
            }

            try
            {
                // Read the app.config file and obtain the app settings.
                System.Configuration.Configuration config        = null;
                ExeConfigurationFileMap            configFileMap = new ExeConfigurationFileMap();
                configFileMap.ExeConfigFilename = PathToConfig;
                config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

                var appSettings = config.AppSettings.Settings;

                // If an alternate config file exists, load that configuration instead. Note the test
                // for redirectTo.Equals(path) to avoid an infinite loop.
                if (appSettings["AlternateConfig"] != null)
                {
                    var redirectTo = appSettings["AlternateConfig"].Value;
                    if (redirectTo != null && !redirectTo.Equals(path) && System.IO.File.Exists(redirectTo))
                    {
                        Load(connectionName, redirectTo);
                        return;
                    }
                }

                // Get the connection string.
                ConnectionStringSettings connection;
                if (string.IsNullOrEmpty(connectionName))
                {
                    // No connection string name specified, so use the first one in the file.
                    connection = config.ConnectionStrings.ConnectionStrings[0];
                    Name       = connection.Name;
                }
                else
                {
                    connection = config.ConnectionStrings.ConnectionStrings[0];
                    Name       = connectionName;
                }

                // Get the connection string parameter values.
                if (connection != null)
                {
                    var parameters = connection.ConnectionString.Split(';');
                    foreach (string parameter in parameters)
                    {
                        var trimmedParameter = parameter.Trim();
                        if (trimmedParameter.StartsWith("Url="))
                        {
                            ServiceUrl = parameter.Replace("Url=", String.Empty).TrimStart(' ');
                        }

                        if (trimmedParameter.StartsWith("Username="******"Username="******"Password="******"Password="******"Domain="))
                        {
                            Domain = parameter.Replace("Domain=", String.Empty).TrimStart(' ');
                        }
                    }
                }
                else
                {
                    throw new Exception("The specified connection string could not be found.");
                }

                // Get the Azure Active Directory application registration settings.
                RedirectUrl = appSettings["RedirectUrl"]?.Value;
                ClientId    = appSettings["ClientId"]?.Value;
            }
            catch (InvalidOperationException e)
            {
                throw new Exception("Required setting in app.config does not exist or is of the wrong type.", e);
            }
        }
Ejemplo n.º 13
0
    // <Snippet5>
    // Get the roaming configuration file associated
    // with the application.
    // This function uses the OpenExeConfiguration(
    // ConfigurationUserLevel userLevel) method to
    // get the configuration file.
    // It also creates a custom ConsoleSection and
    // sets its ConsoleEment BackgroundColor and
    // ForegroundColor properties to blue and yellow
    // respectively. Then it uses these properties to
    // set the console colors.
    public static void GetRoamingConfiguration()
    {
        // Define the custom section to add to the
        // configuration file.
        string         sectionName    = "consoleSection";
        ConsoleSection currentSection = null;

        // Get the roaming configuration
        // that applies to the current user.
        Configuration roamingConfig =
            ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.PerUserRoaming);

        // Map the roaming configuration file. This
        // enables the application to access
        // the configuration file using the
        // System.Configuration.Configuration class
        ExeConfigurationFileMap configFileMap =
            new ExeConfigurationFileMap();

        configFileMap.ExeConfigFilename =
            roamingConfig.FilePath;

        // Get the mapped configuration file.
        Configuration config =
            ConfigurationManager.OpenMappedExeConfiguration(
                configFileMap, ConfigurationUserLevel.None);

        try
        {
            currentSection =
                (ConsoleSection)config.GetSection(
                    sectionName);

            // Synchronize the application configuration
            // if needed. The following two steps seem
            // to solve some out of synch issues
            // between roaming and default
            // configuration.
            config.Save(ConfigurationSaveMode.Modified);

            // Force a reload of the changed section,
            // if needed. This makes the new values available
            // for reading.
            ConfigurationManager.RefreshSection(sectionName);

            if (currentSection == null)
            {
                // Create a custom configuration section.
                currentSection = new ConsoleSection();

                // Define where in the configuration file
                // hierarchy the associated
                // configuration section can be declared.
                // The following assignment assures that
                // the configuration information can be
                // defined in the user.config file in the
                // roaming user directory.
                currentSection.SectionInformation.AllowExeDefinition =
                    ConfigurationAllowExeDefinition.MachineToLocalUser;

                // Allow the configuration section to be
                // overridden by lower-level configuration files.
                // This means that lower-level files can contain
                // the section (use the same name) and assign
                // different values to it as done by the
                // function GetApplicationConfiguration() in this
                // example.
                currentSection.SectionInformation.AllowOverride =
                    true;

                // Store console settings for roaming users.
                currentSection.ConsoleElement.BackgroundColor =
                    ConsoleColor.Blue;
                currentSection.ConsoleElement.ForegroundColor =
                    ConsoleColor.Yellow;

                // Add configuration information to
                // the configuration file.
                config.Sections.Add(sectionName, currentSection);
                config.Save(ConfigurationSaveMode.Modified);
                // Force a reload of the changed section. This
                // makes the new values available for reading.
                ConfigurationManager.RefreshSection(
                    sectionName);
            }
        }
        catch (ConfigurationErrorsException e)
        {
            Console.WriteLine("[Exception error: {0}]",
                              e.ToString());
        }

        // Set console properties using values
        // stored in the configuration file.
        Console.BackgroundColor =
            currentSection.ConsoleElement.BackgroundColor;
        Console.ForegroundColor =
            currentSection.ConsoleElement.ForegroundColor;
        // Apply the changes.
        Console.Clear();

        // Display feedback.
        Console.WriteLine();
        Console.WriteLine(
            "Using OpenExeConfiguration(ConfigurationUserLevel).");
        Console.WriteLine(
            "Configuration file is: {0}", config.FilePath);
    }
Ejemplo n.º 14
0
        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.ToString());
                        }
                    }
                }

                Console.WriteLine("");
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static int Main(string[] args)
        {
            Params param = null;

            Parser.Default.ParseArguments <Params>(args)
            .WithParsed(opts => param = opts)
            .WithNotParsed(PrintErrorAndExit);

            Log.Logger = MakeLogger(param.Verbose);

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

            Configuration configuration;

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

            if (File.Exists(configPath))
            {
                var configFileMap = new ExeConfigurationFileMap {
                    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
                var applicationName = Environment.GetCommandLineArgs()[0];
            #if !DEBUG
                applicationName += ".exe";
            #endif

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

            Log.Information($"Using config file {configPath}");

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

            var git2VaultRepoPaths = param.Paths.ToDictionary(pair => RemoveTrailingSlash(pair.Split('~')[1]),
                                                              pair => RemoveTrailingSlash(pair.Split('~')[0]));
            if (!git2VaultRepoPaths.Keys.All(p => param.Branches.Contains(p)))
            {
                Console.Error.WriteLine($"Config git branches ({string.Join(",", git2VaultRepoPaths.Keys)}) are not a superset of branches ({string.Join(",", param.Branches)})");
                return(-2);
            }
            param.Branches = git2VaultRepoPaths.Keys;

            // check working folder ends with trailing slash
            if (param.WorkingFolder.Last() != '\\')
            {
                param.WorkingFolder += '\\';
            }

            Log.Information(param.ToString());

            var git   = new GitProvider(param.WorkingFolder, param.GitCmd, param.GitDomainName, param.SkipEmptyCommits, param.IgnoreGitIgnore);
            var vault = new VaultProvider(param.VaultServer, param.VaultRepo, param.VaultUser, param.VaultPassword);

            var processor = new Processor(git, vault, param.Directories.ToList(), param.Limit, param.DoGitPushOrigin, param.SampleTimeWhenNoFullPathAvailable, param.BeginDate)
            {
                WorkingFolder      = param.WorkingFolder,
                ForceFullFolderGet = param.ForceFullFolderGet
            };

            var git2VaultRepoPathsSubset = new Dictionary <string, string>();
            foreach (var branch in param.Branches)
            {
                git2VaultRepoPathsSubset[branch] = git2VaultRepoPaths[branch];
            }

            if (param.RunContinuously)
            {
                var consecutiveErrorCount = 0;
                var cancelKeyPressed      = false;
                Console.CancelKeyPress += delegate { cancelKeyPressed = true; Log.Information("Stop process requested"); };
                var nextRun = DateTime.UtcNow;
                do
                {
                    if (nextRun <= DateTime.UtcNow)
                    {
                        try
                        {
                            processor.Pull(git2VaultRepoPathsSubset);
                            consecutiveErrorCount = 0;
                        }
                        catch (Exception e)
                        {
                            Log.Warning($"Exception caught while pulling in new versions from vault. Current consecutive exception count: {consecutiveErrorCount}.\n{e}");
                        }
                        nextRun = DateTime.UtcNow.AddMinutes(1);
                        Log.Information($"Next run scheduled for {nextRun:u}");
                    }
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                } while (!cancelKeyPressed);
            }
            else
            {
                processor.Pull(git2VaultRepoPathsSubset);
            }

            if (!param.IgnoreLabels)
            {
                processor.CreateTagsFromLabels();
            }

            return(0);
        }
Ejemplo n.º 16
0
        static TestCommon()
        {
            // Load configuration in a way that's compatible with a .Net Core test project as well
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = @"..\..\..\App.config" //Path to your config file
            };

            configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            // Read configuration data
            TenantUrl         = AppSetting("SPOTenantUrl");
            DevSiteUrl        = AppSetting("SPODevSiteUrl");
            O365AccountDomain = AppSetting("O365AccountDomain");
            DefaultSiteOwner  = AppSetting("DefaultSiteOwner");


            if (string.IsNullOrEmpty(DefaultSiteOwner))
            {
                DefaultSiteOwner = AppSetting("SPOUserName");
            }

            if (string.IsNullOrEmpty(TenantUrl))
            {
                throw new ConfigurationErrorsException("Tenant site Url in App.config are not set up.");
            }

            if (string.IsNullOrEmpty(DevSiteUrl))
            {
                throw new ConfigurationErrorsException("Dev site url in App.config are not set up.");
            }



            // Trim trailing slashes
            TenantUrl  = TenantUrl.TrimEnd(new[] { '/' });
            DevSiteUrl = DevSiteUrl.TrimEnd(new[] { '/' });

            if (!string.IsNullOrEmpty(AppSetting("SPOCredentialManagerLabel")))
            {
                var tempCred = CredentialManager.GetCredential(AppSetting("SPOCredentialManagerLabel"));

                UserName = tempCred.UserName;
                Password = tempCred.SecurePassword;
            }
            else if (!String.IsNullOrEmpty(AppSetting("SPOUserName")) &&
                     !String.IsNullOrEmpty(AppSetting("SPOPassword")))
            {
                UserName = AppSetting("SPOUserName");
                Password = EncryptionUtility.ToSecureString(AppSetting("SPOPassword"));
            }
            else
            {
                if (!String.IsNullOrEmpty(AppSetting("AppId")) &&
                    !String.IsNullOrEmpty(AppSetting("AppSecret")))
                {
                    AppId     = AppSetting("AppId");
                    AppSecret = AppSetting("AppSecret");
                }
                else
                {
                    throw new ConfigurationErrorsException("Tenant credentials in App.config are not set up.");
                }
            }
        }
Ejemplo n.º 17
0
        public Config(bool isReadonly)
        {
            // General
            PhotoKioskId          = new Setting <string>(isReadonly, "PhotoKioskId", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            MemoryCacheSize       = new Setting <int>(isReadonly, "MemoryCacheSize", 100, false, new Setting <int> .SettingChangedHandler(SettingValueChanged));
            SearchProcessDuration = new Setting <int>(isReadonly, "SearchProcessDuration", 7000, false, new Setting <int> .SettingChangedHandler(SettingValueChanged));
            InactivityTimeout     = new Setting <int>(isReadonly, "InactivityTimeout", 420000, false, new Setting <int> .SettingChangedHandler(SettingValueChanged));
            EnableEventLogging    = new Setting <bool>(isReadonly, "EnableEventLogging", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            SourcePaths           = new Setting <string>(isReadonly, "SourcePaths", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            EnableFolderSelection = new Setting <bool>(isReadonly, "EnableFolderSelection", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            PaperSizeUnits        = new Setting <string>(isReadonly, "PaperSizeUnits", Constants.MmUnits, false, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // Bluetooth
            EnableBluetooth = new Setting <bool>(isReadonly, "EnableBluetooth", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            BluetoothHost   = new Setting <string>(isReadonly, "BluetoothHost", RM.GetString("BluetoothHostNameDefValue"), true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            BluetoothFolder = new Setting <string>(isReadonly, "BluetoothFolder", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // Callback
            OnStartCallback    = new Setting <string>(isReadonly, "OnStartCallback", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            OnCancelCallback   = new Setting <string>(isReadonly, "OnCancelCallback", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            OnCompleteCallback = new Setting <string>(isReadonly, "OnCompleteCallback", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // Image Editor
            EnableImageEditor     = new Setting <bool>(isReadonly, "EnableImageEditor", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableRotation        = new Setting <bool>(isReadonly, "EnableRotation", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableFlip            = new Setting <bool>(isReadonly, "EnableFlip", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableCrop            = new Setting <bool>(isReadonly, "EnableCrop", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableColorCorrection = new Setting <bool>(isReadonly, "EnableColorCorrection", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableEffects         = new Setting <bool>(isReadonly, "EnableEffects", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableRedEyeRemoval   = new Setting <bool>(isReadonly, "EnableRedEyeRemoval", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            CropFile = new Setting <string>(isReadonly, "CropFile", GetFullPath("Crop.xml"), false, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // Contact info
            EnableCustomerPhone       = new Setting <bool>(isReadonly, "EnableCustomerPhone", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableCustomerEmail       = new Setting <bool>(isReadonly, "EnableCustomerEmail", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableCustomerOrderId     = new Setting <bool>(isReadonly, "EnableCustomerOrderId", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            EnableCustomerNameOrderId = new Setting <bool>(isReadonly, "EnableCustomerNameOrderId", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            SkipContactInfo           = new Setting <bool>(isReadonly, "SkipContactInfo", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));

            // Photo ordering
            EnablePhotoOrdering = new Setting <bool>(isReadonly, "EnablePhotoOrdering", true, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));

            // Price file
            PriceFile = new Setting <string>(isReadonly, "PriceFile", GetFullPath("Price.xml"), false, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // CDburner
            EnableCDBurning         = new Setting <bool>(isReadonly, "EnableCDBurner", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            CDBurningRequireConfirm = new Setting <bool>(isReadonly, "CDBurnerRequireConfirm", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            DriveLetter             = new Setting <string>(isReadonly, "DriveLetter", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            DiscLabel     = new Setting <string>(isReadonly, "DiscLabel", "Photo_Kiosk", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            CDBurningCost = new Setting <float>(isReadonly, "CDBurningCost", 10.0f, true, new Setting <float> .SettingChangedHandler(SettingValueChanged));
            CDBurningPaymentInstructions = new Setting <string>(isReadonly, "CDBurnerPaymentInstructions", RM.GetString("CDBurningPaymentInstructions"), true, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // PhotoPrinter
            EnablePhotoPrinting              = new Setting <bool>(isReadonly, "EnablePhotoPrinter", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            PhotoPrintingRequireConfirm      = new Setting <bool>(isReadonly, "PhotoPrinterRequireConfirm", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            PhotoPrintingPaymentInstructions = new Setting <string>(isReadonly, "PhotoPrintingPaymentInstructions", RM.GetString("PhotoPrintingPaymentInstructions"), true, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // ReceiptPrinter
            EnableReceiptPrinter = new Setting <bool>(isReadonly, "EnableReceiptPrinter", false, true, new Setting <bool> .SettingChangedHandler(SettingValueChanged));
            ReceiptPrinterName   = new Setting <string>(isReadonly, "ReceiptPrinterName", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            ReceiptTemplateFile  = new Setting <string>(isReadonly, "ReceiptTemplateFile", GetFullPath("ReceiptTemplate.xaml"), false, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            PhotosInReceipt      = new Setting <int>(isReadonly, "PhotosInReceipt", 20, true, new Setting <int> .SettingChangedHandler(SettingValueChanged));

            // Appearance
            ThemeFile        = new Setting <string>(isReadonly, "ThemeFile", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            LocalizationFile = new Setting <string>(isReadonly, "LocalizationFile", GetFullPath("Resources.xml"), false, new Setting <string> .SettingChangedHandler(SettingValueChanged));
            MainBanner       = new Setting <string>(isReadonly, "MainBanner", "", true, new Setting <string> .SettingChangedHandler(SettingValueChanged));

            // Screens
            Screens.Add(new ScreenSetting(isReadonly, "WelcomeScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ChooseUploadWayScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "SelectFoldersScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "UploadingPhotosScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ProgressScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "SelectScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "OrderFormingScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "AdditionalServicesScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ImageEditorScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ConfirmOrderScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ContactInfoScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "OrderIdScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "BurningScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "PrintingScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ThankYouScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));
            Screens.Add(new ScreenSetting(isReadonly, "ThankYouCancelScreen", new Setting <string> .SettingChangedHandler(SettingValueChanged)));

            var configFileMap = new ExeConfigurationFileMap();

            configFileMap.ExeConfigFilename = GetFullPath(RM.GetString("ConfigFileName"));
            _kioskConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            Load();
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            var configfile = "app.config";
            var region     = "";
            var id         = "";
            var status     = "";

            // Get the default AWS Region from the 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 specify a Region 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;

                default:
                    break;
                }

                i++;
            }

            if ((status == "") || (id == "") || ((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);
            var client    = new AmazonDynamoDBClient(newRegion);
            var context   = new DynamoDBContext(client);

            var response = UpdateTableItemAsync(context, id, status);

            // Update the status regardless of whether id identifies an order.
            if (response.Result.Order_Status == status)
            {
                Console.WriteLine("Successfully updated the order's status.");
            }
            else
            {
                Console.WriteLine("Could not update the order's status.");
            }
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            var debug      = false;
            var configfile = "app.config";
            var region     = "";
            var table      = "";

            int i = 0;

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

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

                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;

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

            DebugPrint(debug, "Debugging enabled\n");

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

            Task <bool> exists = DoesTableExistAsync(client, table);

            if (exists.Result)
            {
                Console.WriteLine("Table " + table + " already exists in region " + region);
                return;
            }

            Task <CreateTableResponse> response = MakeTableAsync(client, table);

            Console.WriteLine("Created table " + response.Result.TableDescription.TableName + " in region " + region);
        }
Ejemplo n.º 20
0
        public static async Task Main()
        {
            var configfile = "app.config";
            var region     = string.Empty;
            var table      = string.Empty;
            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;
                id     = appSettings.Settings["ProductID"].Value;

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

            try
            {
                var 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 = await GetProductOrdersAsync(client, table, id);

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

            // Display the orders returned from table scan.
            foreach (var item in response.Items)
            {
                foreach (string attr in item.Keys)
                {
                    if (item[attr].S is not 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(string.Empty);
            }
        }
Ejemplo n.º 21
0
    // </Snippet4>

    // <Snippet9>

    // Access a configuration file using mapping.
    // This function uses the OpenMappedExeConfiguration
    // method to access a new configuration file.
    // It also gets the custom ConsoleSection and
    // sets its ConsoleEment BackgroundColor and
    // ForegroundColor properties to green and red
    // respectively. Then it uses these properties to
    // set the console colors.
    public static void MapExeConfiguration()
    {
        // Get the application configuration file.
        System.Configuration.Configuration config =
            ConfigurationManager.OpenExeConfiguration(
                ConfigurationUserLevel.None);

        Console.WriteLine(config.FilePath);

        if (config == null)
        {
            Console.WriteLine(
                "The configuration file does not exist.");
            Console.WriteLine(
                "Use OpenExeConfiguration to create the file.");
        }

        // Create a new configuration file by saving
        // the application configuration to a new file.
        string appName =
            Environment.GetCommandLineArgs()[0];

        string configFile = string.Concat(appName,
                                          ".2.config");

        config.SaveAs(configFile, ConfigurationSaveMode.Full);

        // Map the new configuration file.
        ExeConfigurationFileMap configFileMap =
            new ExeConfigurationFileMap();

        configFileMap.ExeConfigFilename = configFile;

        // Get the mapped configuration file
        config =
            ConfigurationManager.OpenMappedExeConfiguration(
                configFileMap, ConfigurationUserLevel.None);

        // Make changes to the new configuration file.
        // This is to show that this file is the
        // one that is used.
        string sectionName = "consoleSection";

        ConsoleSection customSection =
            (ConsoleSection)config.GetSection(sectionName);

        if (customSection == null)
        {
            customSection = new ConsoleSection();
            config.Sections.Add(sectionName, customSection);
        }
        else
        {
            // Change the section configuration values.
            customSection =
                (ConsoleSection)config.GetSection(sectionName);
        }

        customSection.ConsoleElement.BackgroundColor =
            ConsoleColor.Green;
        customSection.ConsoleElement.ForegroundColor =
            ConsoleColor.Red;

        // Save the configuration file.
        config.Save(ConfigurationSaveMode.Modified);

        // Force a reload of the changed section. This
        // makes the new values available for reading.
        ConfigurationManager.RefreshSection(sectionName);

        // Set console properties using the
        // configuration values contained in the
        // new configuration file.
        Console.BackgroundColor =
            customSection.ConsoleElement.BackgroundColor;
        Console.ForegroundColor =
            customSection.ConsoleElement.ForegroundColor;
        Console.Clear();

        Console.WriteLine();
        Console.WriteLine("Using OpenMappedExeConfiguration.");
        Console.WriteLine("Configuration file is: {0}",
                          config.FilePath);
    }
        /// <summary>
        ///     Writes the specified settings container.
        /// </summary>
        /// <param name="settingsContainer">The settings container.</param>
        public static void Write(SettingsContainer settingsContainer)
        {
            var sectionName = $"{settingsContainer.Namespace}.{settingsContainer.Name}";
            var solution    = Package.Instance.GetGlobalService <SVsSolution, IVsSolution>();

            solution.GetProjectOfUniqueName(Package.Instance.Dte.ActiveDocument.ProjectItem.ContainingProject.UniqueName,
                                            out var vsHierarchy);

            var appConfigDocData = GetAppConfigDocData(Package.Instance, vsHierarchy, false);

            if (appConfigDocData == null)
            {
                return;
            }

            var exeConfigurationFileMap = new ExeConfigurationFileMap();

            exeConfigurationFileMap.ExeConfigFilename = appConfigDocData.Name;

            var configHelperService = new ConfigurationHelperService();

            var appScopedSettingsPropertyCollection      = new SettingsPropertyCollection();
            var appScopedSettingsPropertyValueCollection = configHelperService.ReadSettings(exeConfigurationFileMap,
                                                                                            ConfigurationUserLevel.None, appConfigDocData, sectionName, false,
                                                                                            appScopedSettingsPropertyCollection);

            var userScopedSettingsPropertyCollection      = new SettingsPropertyCollection();
            var userScopedSettingsPropertyValueCollection = configHelperService.ReadSettings(exeConfigurationFileMap,
                                                                                             ConfigurationUserLevel.None, appConfigDocData, sectionName, true,
                                                                                             userScopedSettingsPropertyCollection);

            foreach (var setting in settingsContainer.Settings)
            {
                var newSettingPropertyValue = new SettingsPropertyValue(new SettingsProperty(setting.Name));
                var exists = false;
                var settingsPropertyValueCollection = setting.Scope == SettingScope.Application ? appScopedSettingsPropertyValueCollection : userScopedSettingsPropertyValueCollection;

                foreach (SettingsPropertyValue settingPropertyValue in settingsPropertyValueCollection)
                {
                    if (!string.Equals(settingPropertyValue.Property.Name, newSettingPropertyValue.Property.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    newSettingPropertyValue = settingPropertyValue;
                    exists = true;
                    break;
                }

                if (!exists)
                {
                    settingsPropertyValueCollection.Add(newSettingPropertyValue);
                }

                // Update
                newSettingPropertyValue.Property.DefaultValue = setting.DefaultValue;
                newSettingPropertyValue.PropertyValue         = setting.Value;
                newSettingPropertyValue.SerializedValue       = setting.Value;
                newSettingPropertyValue.Property.PropertyType = setting.Type;
                newSettingPropertyValue.Property.SerializeAs  = SettingsSerializeAs.String;
            }

            configHelperService.WriteSettings(exeConfigurationFileMap, ConfigurationUserLevel.None, appConfigDocData,
                                              sectionName,
                                              false, appScopedSettingsPropertyValueCollection);

            configHelperService.WriteSettings(exeConfigurationFileMap, ConfigurationUserLevel.None, appConfigDocData,
                                              sectionName,
                                              true, userScopedSettingsPropertyValueCollection);
            appConfigDocData.CheckoutFile(Package.Instance);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Retrieves the configuration file, parses the command line
        /// arguments, and displays the contents. Then it calls the
        /// AddItemsAsync method to add the list of new items to the
        /// DynamoDB table.
        /// </summary>
        /// <param name="args">Command line arguments. The only valid argument
        /// for this application is -d for debug mode.</param>
        public static async Task Main(string[] args)
        {
            var    configfile = "app.config";
            string region;
            string 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 (string.IsNullOrEmpty(region) || string.IsNullOrEmpty(table) || string.IsNullOrEmpty(index) || string.IsNullOrEmpty(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;
                }

                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.
            file.ReadLine();

            string line;
            var    input = 1;

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

            await AddItemsAsync(debug, client, table, inputs, indexVal);

            Console.WriteLine("Done");
        }
Ejemplo n.º 24
0
        private static int Main(string[] args)
        {
            const string generatedWarning = "This file was generated by VersionGenerator.exe. It should NOT be directly modified.";
            const string statusPrefix     = "VersionGenerator.exe: ";
            const string xmlDateFormat    = "yyyy-MM-ddTHH:mm:ss.fffffffzzz";

            FileInfo      versionConfig;
            Configuration customConfig = null;

            if (args.Length == 0)
            {
                Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
                versionConfig = new FileInfo("VersionGenerator.exe.config");
                if (!versionConfig.Exists)
                {
                    // If we don't have the configuration file, bad things are going to happen...
                    Console.Error.WriteLine(statusPrefix + "VersionGenerator.exe.config not found!");
                    return(1);
                }
            }
            else
            {
                // Load alternate configuration file and set current directory relative to this configuration file
                versionConfig = new FileInfo(args[0]);
                if (!versionConfig.Exists)
                {
                    Console.Error.Write(statusPrefix + "Custom configuration file '" + args[0] + "' not found.");
                    return(1);
                }

                Directory.SetCurrentDirectory(versionConfig.DirectoryName);

                ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
                configMap.ExeConfigFilename = versionConfig.FullName;
                customConfig        = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
                Config.CustomConfig = customConfig;
            }

            TemplateConfigurationSection templateSettings = (customConfig != null ? customConfig.GetSection("templateSettings") : ConfigurationManager.GetSection("templateSettings")) as TemplateConfigurationSection;

            if (string.IsNullOrEmpty(templateSettings.LastGenerated))
            {
                // Require historical version control
                Console.Error.Write(statusPrefix + "templateSettings@last must specify a file name for change tracking.");
                return(1);
            }

            string gitCommand = Config.GitCommand;
            int    major;
            int    minor;
            int    build;
            int    revision;
            string hash;

            if (!string.IsNullOrEmpty(gitCommand))
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.UseShellExecute        = false;
                startInfo.FileName               = gitCommand;
                startInfo.Arguments              = Config.GitCommandArgs;
                startInfo.RedirectStandardOutput = true;
                startInfo.CreateNoWindow         = true;

                string gitVer;
                using (Process process = new Process())
                {
                    process.StartInfo = startInfo;
                    process.Start();
                    process.WaitForExit();
                    gitVer = process.StandardOutput.ReadLine();
                }
                GroupCollection groups = Regex.Match(gitVer, @"(?:\D)*(?<major>\d+)\.(?<minor>\d+)\.(?<build>\d+)\.(?<revision>\d+)(?:-g(?<hash>.*?))?$").Groups;
                Group           group;
                string          gitVal;
                major    = ((group = groups["major"]).Success && !string.IsNullOrEmpty(gitVal = group.Value)) ? int.Parse(gitVal) : 0;
                minor    = ((group = groups["minor"]).Success && !string.IsNullOrEmpty(gitVal = group.Value)) ? int.Parse(gitVal) : 0;
                build    = ((group = groups["build"]).Success && !string.IsNullOrEmpty(gitVal = group.Value)) ? int.Parse(gitVal) : 0;
                revision = ((group = groups["revision"]).Success && !string.IsNullOrEmpty(gitVal = group.Value)) ? int.Parse(gitVal) : 0;
                hash     = (group = groups["hash"]).Success ? group.Value : string.Empty;
            }
            else
            {
                major = Config.MajorVersion;
                minor = Config.MinorVersion;
                build = ((Config.ReleaseYearMonth.Year - 2000) * 100) + Config.ReleaseYearMonth.Month;
                hash  = string.Empty;

                DateTime today            = DateTime.Today;
                int      month            = ((today.Year - Config.RevisionStartYearMonth.Year) * 12) + (today.Month - Config.RevisionStartYearMonth.Month) + 1;
                int      monthsAsQuarters = ((today.Year - Config.CountQuartersFromYearMonth.Year) * 12) + (today.Month - Config.CountQuartersFromYearMonth.Month) + 1;
                if (monthsAsQuarters > 0)
                {
                    // This revision mechanism was moving much too quickly, so allow the
                    // option to increment by quarter instead of month. For quarter increments,
                    // days 1-31 are the first month, 34-64 are the second month, and 67-97 are
                    // the third month in the quarter. Months before quarter counting began are
                    // added to the quarter count, giving sequential version numbers.
                    revision = ((month - monthsAsQuarters) + (monthsAsQuarters + 2) / 3) * 100;
                    switch ((monthsAsQuarters - 1) % 3)
                    {
                    case 1:
                        revision += 33;
                        break;

                    case 2:
                        revision += 66;
                        break;
                    }
                }
                else
                {
                    revision = month * 100;
                }
                revision += today.Day;
            }

            string yearMonthString = string.Format("{0:yyyy-MM}", Config.ReleaseYearMonth);

            FileInfo lastGeneratedXml = new FileInfo(templateSettings.LastGenerated);

            if (lastGeneratedXml.Exists)
            {
                // Read the last time the files were processed and short circuit generation if nothing has changed.
                bool upToDate = false;
                using (StreamReader streamReader = lastGeneratedXml.OpenText())
                {
                    using (XmlReader reader = XmlReader.Create(streamReader))
                    {
                        while (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Element)
                            {
                                upToDate = reader.GetAttribute("major") == major.ToString() &&
                                           reader.GetAttribute("minor") == minor.ToString() &&
                                           reader.GetAttribute("build") == build.ToString() &&
                                           reader.GetAttribute("revision") == revision.ToString() &&
                                           reader.GetAttribute("hash") == hash &&
                                           reader.GetAttribute("yearMonth") == yearMonthString &&
                                           reader.GetAttribute("buildType") == Config.ReleaseType &&
                                           reader.GetAttribute("configChange") == versionConfig.LastWriteTimeUtc.ToString(xmlDateFormat);
                                break;
                            }
                        }
                    }
                }
                if (upToDate)
                {
                    Console.WriteLine(statusPrefix + "Generated version files already up to date.");
                    return(0);
                }
            }

            foreach (TemplateElement template in templateSettings.Templates)
            {
                FileInfo outputInfo   = new FileInfo(template.Output);
                object[] replacements = new object[8];
                int      index        = template.Major;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = major;
                }
                index = template.Minor;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = minor;
                }
                index = template.Build;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = build;
                }
                index = template.Revision;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = revision;
                }
                index = template.Hash;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = hash;
                }
                index = template.YearMonth;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = yearMonthString;
                }
                index = template.BuildType;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = Config.ReleaseType;
                }
                index = template.Warning;
                if (index >= 0 && index < 8)
                {
                    replacements[index] = generatedWarning;
                }

                using (StreamWriter writer = outputInfo.CreateText())
                {
                    writer.Write(string.Format(template.Content, replacements));
                }

                Console.WriteLine(statusPrefix + "Generated " + template.Output + ".");
            }

            // We checked this earlier but don't want to rewrite it until everything else succeeds.
            using (StreamWriter writer = lastGeneratedXml.CreateText())
            {
                writer.WriteLine(string.Format("<version major='{0}' minor='{1}' build='{2}' revision='{3}' hash='{4}' yearMonth='{5}' buildType='{6}' configChange='{7}' />", major, minor, build, revision, hash, yearMonthString, Config.ReleaseType, versionConfig.LastWriteTimeUtc.ToString(xmlDateFormat)));
            }
            Console.WriteLine(statusPrefix + "Generated " + templateSettings.LastGenerated + ".");

            Console.WriteLine("VersionGenerator.exe finished successfully.");
            return(0);
        }
Ejemplo n.º 25
0
        private void LoadCobieMaps()
        {
            var tmpFile = _configFileName;

            if (_configFileName == null)
            {
                tmpFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";

                var asss = Assembly.GetExecutingAssembly();

                using (var input = asss.GetManifestResourceStream("Xbim.COBieLite.COBieAttributes.config"))
                    using (var output = File.Create(tmpFile))
                    {
                        if (input != null)
                        {
                            input.CopyTo(output);
                        }
                    }
            }


            Configuration      config;
            AppSettingsSection cobiePropertyMaps;

            _cobieFieldMap = new Dictionary <string, string[]>();

            if (!File.Exists(tmpFile))
            {
                var directory = new DirectoryInfo(".");
                throw new Exception(
                          string.Format(
                              @"Error loading configuration file ""{0}"". App folder is ""{1}"".", tmpFile,
                              directory.FullName)
                          );
            }

            try
            {
                var configMap = new ExeConfigurationFileMap {
                    ExeConfigFilename = tmpFile
                };
                config            = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
                cobiePropertyMaps = (AppSettingsSection)config.GetSection("COBiePropertyMaps");
            }
            catch (Exception ex)
            {
                var directory = new DirectoryInfo(".");
                throw new Exception(
                          @"Error loading configuration file ""COBieAttributes.config"". App folder is " + directory.FullName,
                          ex);
            }

            if (cobiePropertyMaps != null)
            {
                foreach (KeyValueConfigurationElement keyVal in cobiePropertyMaps.Settings)
                {
                    var values = keyVal.Value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    _cobieFieldMap.Add(keyVal.Key, values);
                    foreach (var cobieProperty in values)
                    {
                        //used to keep a list of properties that are reserved for COBie and not written out as attributes
                        _cobieProperties.Add(cobieProperty);
                    }
                }
            }


            var ifcElementInclusion = (AppSettingsSection)config.GetSection("IfcElementInclusion");

            if (ifcElementInclusion != null)
            {
                foreach (KeyValueConfigurationElement keyVal in ifcElementInclusion.Settings)
                {
                    if (String.Compare(keyVal.Value, "YES", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        var includedType = IfcMetaData.IfcType(keyVal.Key.ToUpper());
                        if (includedType != null)
                        {
                            _includedTypes.Add(includedType);
                        }
                    }
                }
            }

            if (_configFileName == null)
            {
                File.Delete(tmpFile);
            }
        }
Ejemplo n.º 26
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtUri.Text))
                {
                    MainForm.StaticWriteToLog("The connection string of the Service Bus namespace cannot be null.");
                    return;
                }
                ServiceBusConnectionStringBuilder serviceBusConnectionStringBuilder;
                try
                {
                    serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(txtUri.Text);
                }
                catch (Exception)
                {
                    MainForm.StaticWriteToLog("The format of the connection string is invalid.");
                    return;
                }

                if (serviceBusConnectionStringBuilder.Endpoints == null ||
                    serviceBusConnectionStringBuilder.Endpoints.Count == 0)
                {
                    MainForm.StaticWriteToLog("The connection string does not contain any endpoint.");
                    return;
                }

                var host = serviceBusConnectionStringBuilder.Endpoints.ToArray()[0].Host;

                var index = host.IndexOf(".", StringComparison.Ordinal);

                var key = index > 0 ? CultureInfo.CurrentCulture.TextInfo.ToTitleCase(host.Substring(0, index)) : "MyNamespace";

                using (var parameterForm = new ParameterForm("Enter the key for the Service Bus namespace",
                                                             new List <string> {
                    "Key"
                },
                                                             new List <string> {
                    key
                },
                                                             new List <bool> {
                    false
                }))
                {
                    if (parameterForm.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }
                    key = parameterForm.ParameterValues[0];
                    if (string.IsNullOrWhiteSpace(key))
                    {
                        MainForm.StaticWriteToLog("The key of the Service Bus namespace cannot be null.");
                        return;
                    }
                    var value                = txtUri.Text;
                    var configuration        = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    var configurationSection = configuration.Sections["serviceBusNamespaces"];
                    var directory            = Path.GetDirectoryName(configuration.FilePath);
                    if (string.IsNullOrEmpty(directory))
                    {
                        MainForm.StaticWriteToLog("The directory of the configuration file cannot be null.");
                        return;
                    }
                    var appConfig = Path.Combine(directory, "..\\..\\App.config");
                    configurationSection.SectionInformation.ForceSave = true;
                    var xml         = configurationSection.SectionInformation.GetRawXml();
                    var xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(xml);
                    var node = xmlDocument.CreateElement("add");
                    node.SetAttribute("key", key);
                    node.SetAttribute("value", value);
                    xmlDocument.DocumentElement?.AppendChild(node);
                    configurationSection.SectionInformation.SetRawXml(xmlDocument.OuterXml);
                    configuration.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("serviceBusNamespaces");

                    if (File.Exists(appConfig))
                    {
                        var exeConfigurationFileMap = new ExeConfigurationFileMap()
                        {
                            ExeConfigFilename = appConfig
                        };
                        configuration        = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                        configurationSection = configuration.Sections["serviceBusNamespaces"];
                        configurationSection.SectionInformation.ForceSave = true;
                        xml         = configurationSection.SectionInformation.GetRawXml();
                        xmlDocument = new XmlDocument();
                        xmlDocument.LoadXml(xml);
                        node = xmlDocument.CreateElement("add");
                        node.SetAttribute("key", key);
                        node.SetAttribute("value", value);
                        xmlDocument.DocumentElement?.AppendChild(node);
                        configurationSection.SectionInformation.SetRawXml(xmlDocument.OuterXml);
                        configuration.Save(ConfigurationSaveMode.Modified);
                        ConfigurationManager.RefreshSection("serviceBusNamespaces");
                    }

                    serviceBusHelper.ServiceBusNamespaces.Add(key, MainForm.GetServiceBusNamespace(key, value));
                    cboServiceBusNamespace.Items.Clear();
                    // ReSharper disable once CoVariantArrayConversion
                    cboServiceBusNamespace.Items.AddRange(serviceBusHelper.ServiceBusNamespaces.Keys.OrderBy(s => s).ToArray());
                    cboServiceBusNamespace.Text = key;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Retrieves the configuration information using the Microsoft
        /// ConfigurationManager, initializes the DynamoDB client, retrieves the
        /// items in the table using GetItemsAsync, and finally, displays the
        /// list of items in the table.
        /// </summary>
        public static async Task Main()
        {
            var configfile = "app.config";
            var region     = string.Empty;
            var table      = string.Empty;

            // Get default AWS 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;
            }
            else
            {
                Console.WriteLine($"Could not find {configfile}");
                return;
            }

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

            if (table == string.Empty)
            {
                empty = true;
                sb.Append("table name (-t TABLE), ");
            }

            if (region == string.Empty)
            {
                empty = true;
                sb.Append("region -r (REGION)");
            }

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

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

            var response = await GetItemsAsync(client, table);

            Console.WriteLine($"Found {response.Items.Count} items in {table} table in region {region}\n");

            StringBuilder output;

            foreach (var item in response.Items)
            {
                output = new StringBuilder();

                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        output.Append(attr + ": " + item[attr].S + ", ");
                    }
                    else if (item[attr].N != null)
                    {
                        output.Append(attr + ": " + item[attr].N + ", ");
                    }
                }

                Console.WriteLine(output.ToString());
            }
        }
Ejemplo n.º 28
0
        private static void SetProvider(string appConfigPath)
        {
            //clear the providers and reset
            DataService.Provider  = new SqlDataProvider();
            DataService.Providers = new DataProviderCollection();


            //if present, get the connection strings and the SubSonic config
            if (File.Exists(appConfigPath))
            {
                ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                AddLogEntry(LogState.Information, "Building configuration from " + Path.Combine(Directory.GetCurrentDirectory(), appConfigPath));
                fileMap.ExeConfigFilename = appConfigPath;

                // Open another config file
                Configuration subConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

                try
                {
                    SubSonicSection section = (SubSonicSection)subConfig.GetSection(ConfigurationSectionName.SUB_SONIC_SERVICE);

                    if (section != null)
                    {
                        DataService.ConfigSection = section;
                        string argTemplateDirectory    = GetArg(ConfigurationPropertyName.TEMPLATE_DIRECTORY);
                        string activeTemplateDirectory = String.IsNullOrEmpty(argTemplateDirectory) ? section.TemplateDirectory : argTemplateDirectory;


                        string argTraceFlag    = GetArg(ConfigurationPropertyName.ENABLE_TRACE);
                        string activeTraceFlag = String.IsNullOrEmpty(argTraceFlag) ? section.EnableTrace : argTraceFlag;

                        if (!String.IsNullOrEmpty(activeTraceFlag))
                        {
                            DataService.EnableTrace = Convert.ToBoolean(activeTraceFlag);
                        }

                        if (!String.IsNullOrEmpty(activeTemplateDirectory))
                        {
                            AddLogEntry(LogState.Information, "Overriding default templates with those from " + section.TemplateDirectory);
                            CodeService.TemplateDirectory = activeTemplateDirectory;
                        }

                        //initialize
                        //need to pull out the default connection string
                        //since this application doesn't have a config file, the target one does
                        //so reconciling connection string won't work
                        string connectionStringName = section.Providers[0].Parameters["connectionStringName"];
                        if (connectionStringName == null)
                        {
                            throw new ConfigurationErrorsException("The Parameter 'connectionStringName' was not specified");
                        }

                        ConnectionStringSettings connSettings = subConfig.ConnectionStrings.ConnectionStrings[connectionStringName];
                        if (connSettings == null)
                        {
                            throw new ConfigurationErrorsException(string.Format("ConnectionStrings section missing connection string with the name '{0}'", connectionStringName));
                        }

                        string connString = subConfig.ConnectionStrings.ConnectionStrings[connectionStringName].ConnectionString;
                        //DataService.ConnectionString = connString;


                        System.Web.Configuration.ProvidersHelper.InstantiateProviders(section.Providers, DataService.Providers, typeof(DataProvider));

                        //this is a tad backwards, but it's what needs to happen since our application
                        //is configuring another application's providers
                        //go back and reset the provider's connection strings

                        //int counter = 0;
                        foreach (DataProvider provider in DataService.Providers)
                        {
                            AddLogEntry(LogState.Information, "Adding connection to " + provider.Name);

                            provider.SetDefaultConnectionString(subConfig.ConnectionStrings.ConnectionStrings[provider.ConnectionStringName].ConnectionString);
                            //provider.ConnectionString = subConfig.ConnectionStrings.ConnectionStrings[provider.ConnectionStringName].ConnectionString;
                        }

                        //reset the default provider
                        string providerName = GetArg("provider");
                        if (providerName != string.Empty)
                        {
                            try
                            {
                                DataService.Provider = DataService.Providers[providerName];
                            }
                            catch (Exception e)
                            {
                                AddLogEntry(LogState.Error, string.Format("ERROR: There is no provider with the name '{0}'. Exception: {1}", providerName, e));
                            }
                        }
                        else
                        {
                            DataService.Provider = DataService.Providers[section.DefaultProvider];
                        }
                    }
                }
                catch (ConfigurationErrorsException x)
                {
                    //let the user know the config was problematic...
                    Console.WriteLine("Can't set the configuration for the providers. There is an error with your config setup (did you remember to configure SubSonic in your config file?). '{0}'", x.Message);
                }
            }
            else
            {
                throw new Exception("There's no config file present at " + appConfigPath);
            }
        }
Ejemplo n.º 29
0
        private ClientSettingsSection GetUserSettings(out Configuration config, bool tryAlternates)

        {
            config = null;

            string[] files;

            if (tryAlternates)
            {
                files = new string[] { this.FileName, this.BackupFileName }
            }
            ;

            else
            {
                files = new string[] { this.FileName }
            };



            for (int i = 0; i < files.Length; i++)

            {
                string p = files[i];

                if (tryAlternates)
                {
                    if (!System.IO.File.Exists(p))
                    {
                        continue;
                    }
                }



                try

                {
                    ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();

                    fileMap.ExeConfigFilename = p;

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

                    ConfigurationSection configSection = config.GetSection(USER_SETTINGS_SECTION_NAME);

                    ClientSettingsSection clientSettings = null;

                    if (configSection != null)

                    {
                        clientSettings = (ClientSettingsSection)configSection;
                    }

                    else

                    {
                        clientSettings = new ClientSettingsSection();

                        config.Sections.Add(USER_SETTINGS_SECTION_NAME, clientSettings);
                    }



                    // make a backup copy just in case

                    MakeBackup();



                    return(clientSettings);
                }

                catch

                {
                    // file is corrupt

                    if (!tryAlternates)

                    {
                        System.IO.File.Delete(p);

                        return(GetUserSettings(out config, tryAlternates));
                    }

                    else
                    {
                        continue;
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 30
0
        public static void LoadProp(Type theClass, string configPath)
        {
            ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();

            configFile.ExeConfigFilename = configPath;

            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
            AppSettingsSection section = config.GetSection("constant.classes/" + theClass.FullName) as AppSettingsSection;

            PropertyInfo[] props = theClass.GetProperties();
            foreach (PropertyInfo p in props)
            {
                KeyValueConfigurationElement e = section.Settings[p.Name];
                if (null != e)
                {
                    string v        = e.Value;
                    string typeName = p.PropertyType.FullName;

                    if (string.IsNullOrEmpty(v))
                    {
                        p.SetValue(null, null, null);
                    }
                    else if (typeName.Contains(typeof(string).Name))
                    {
                        p.SetValue(null, v, null);
                    }
                    else if (typeName.Contains(typeof(Int16).Name))
                    {
                        p.SetValue(null, Int16.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Int32).Name))
                    {
                        p.SetValue(null, Int32.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Int64).Name))
                    {
                        p.SetValue(null, Int64.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Single).Name))
                    {
                        p.SetValue(null, Single.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Double).Name))
                    {
                        p.SetValue(null, Double.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Decimal).Name))
                    {
                        p.SetValue(null, Decimal.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(DateTime).Name))
                    {
                        try
                        {
                            p.SetValue(null, DateTime.ParseExact(v, "d/m/yyyy", null), null);
                            continue;
                        }
                        catch { }

                        try
                        {
                            p.SetValue(null, DateTime.ParseExact(v, "yyyy/m/d", null), null);
                            continue;
                        }
                        catch { }

                        p.SetValue(null, DateTime.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Byte).Name))
                    {
                        p.SetValue(null, Byte.Parse(v), null);
                    }
                    else if (typeName.Contains(typeof(Boolean).Name))
                    {
                        p.SetValue(null, Boolean.Parse(v), null);
                    }
                }
            }
        }
Ejemplo n.º 31
0
        public App()
        {
            Configuration config1   = null;
            string        directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

            if (Directory.Exists(directory))
            {
                string filename = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                foreach (string s in from s in Directory.EnumerateFiles(directory, "*.config", SearchOption.TopDirectoryOnly) where filename.Equals(Path.GetFileNameWithoutExtension(s)) select s)
                {
                    ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();

                    exeConfigurationFileMap.ExeConfigFilename = s;
                    config1 = ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
                }
            }

            if (config1 == null)
            {
                config1 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                if (config1.AppSettings.Settings["Scripts"] != null)
                {
                    directory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                    List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                    foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value) ? config1.AppSettings.Settings["Scripts"].Value : Path.Combine(directory, config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                            }
                    }

                    Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                }
            }
            else
            {
                Configuration config2 = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                if (config1.AppSettings.Settings["Scripts"] != null)
                {
                    ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                    List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                    foreach (string filename in Directory.EnumerateFiles(Path.IsPathRooted(config1.AppSettings.Settings["Scripts"].Value) ? config1.AppSettings.Settings["Scripts"].Value : Path.Combine(directory, config1.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                    {
                        using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                            }
                    }

                    Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                }
                else if (config2.AppSettings.Settings["Scripts"] != null)
                {
                    if (Path.IsPathRooted(config2.AppSettings.Settings["Scripts"].Value))
                    {
                        ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                        List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                        foreach (string filename in Directory.EnumerateFiles(config2.AppSettings.Settings["Scripts"].Value, "*.csx", SearchOption.TopDirectoryOnly))
                        {
                            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                                using (StreamReader sr = new StreamReader(fs))
                                {
                                    taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                                }
                        }

                        Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                    }
                    else
                    {
                        string        path          = Path.Combine(directory, config2.AppSettings.Settings["Scripts"].Value);
                        ScriptOptions scriptOptions = ScriptOptions.Default.WithReferences(System.Reflection.Assembly.GetExecutingAssembly());
                        List <Task <ScriptState <object> > > taskList = new List <Task <ScriptState <object> > >();

                        foreach (string filename in Directory.EnumerateFiles(Directory.Exists(path) ? path : Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), config2.AppSettings.Settings["Scripts"].Value), "*.csx", SearchOption.TopDirectoryOnly))
                        {
                            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                                using (StreamReader sr = new StreamReader(fs))
                                {
                                    taskList.Add(CSharpScript.RunAsync(sr.ReadToEnd(), scriptOptions));
                                }
                        }

                        Task <ScriptState <object> > .WaitAll(taskList.ToArray());
                    }
                }
            }
        }
	public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel) {}
Ejemplo n.º 33
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;
            }

            // check working folder ends with trailing slash
            if (workingFolder.Last() != '\\')
            {
                workingFolder += '\\';
            }

            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,
                OldestCommitDate   = appSettings.Settings["OldestCommitDate"].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
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            bool debug      = false;
            var  configfile = "app.config";
            var  region     = "";
            var  table      = "";

            // 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;
            }
            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;

                case "-r":
                    i++;
                    region = args[i];
                    break;

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

                default:
                    break;
                }

                i++;
            }

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

            if (table == "")
            {
                empty = true;
                sb.Append("table name (-t TABLE), ");
            }
            else
            {
                DebugPrint(debug, "Table: " + table + "\n");
            }

            if (region == "")
            {
                empty = true;
                sb.Append("region -r (REGION)");
            }
            else
            {
                DebugPrint(debug, "Region: " + region);
            }

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

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

            var response = GetItemsAsync(client, table);

            Console.WriteLine("Found " + response.Result.Items.Count.ToString() + " items in table " + table + " in region " + region + ":\n");

            StringBuilder output;

            foreach (var item in response.Result.Items)
            {
                output = new StringBuilder();

                foreach (string attr in item.Keys)
                {
                    if (item[attr].S != null)
                    {
                        output.Append(attr + ": " + item[attr].S + ", ");
                    }
                    else if (item[attr].N != null)
                    {
                        output.Append(attr + ": " + item[attr].N.ToString() + ", ");
                    }
                }

                Console.WriteLine(output.ToString());
            }
        }
    protected void btnSendEmail_Click(object sender, EventArgs e)
    {
        lblSucess.Text = "";
        var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = Server.MapPath("~/config/app.config") };
        var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        var section = (AppSettingsSection)config.GetSection("appSettings");
        var strUseSSL = section.Settings["UseSSL"].Value;
        var strPort = section.Settings["Port"].Value;

        var dvEmail = (OdsNewsletter.Select() as DataView);
        var strHost = section.Settings["Host"].Value;
        int n;
        var isNumeric = int.TryParse(strPort, out n);
        var iPort = isNumeric ? n : 0;
        var strMailFrom = section.Settings["Email"].Value;
        var strDisplayName = "News & Orders";
        var strUserName = section.Settings["UserName"].Value;
        var strPassword = MD5Hash.Decrypt(section.Settings["Password"].Value, true);
        var bEnableSsl = strUseSSL.ToLower() == "true";
        var strMailTo = "";
        var strCC = "";
        var strSubject = txtSubject.Text.Trim();
        var strBody = txtContent.Content;
        if (RadGrid1.SelectedItems.Count == 0)
        {
            //strMailTo = (from DataRowView drv in dvEmail select drv["Email"].ToString()).ToList<string>().Aggregate((a, b) => a + ',' + b);
            if (dvEmail != null && dvEmail.Count > 0)
            {
                foreach (DataRow drv in dvEmail.Table.Rows)
                {
                    strMailTo = drv["Email"].ToString();
                    Common.SendMail(
                    strHost,
                    iPort,
                    strMailFrom,
                    strDisplayName,
                    strUserName,
                    strPassword,
                    strMailTo,
                    strCC,
                    strSubject,
                    strBody,
                    bEnableSsl
                    );
                }
            }
        }
        else
        {
            foreach (GridDataItem item in RadGrid1.SelectedItems)
            {
                strMailTo = item["Email"].Text;
                Common.SendMail(
                strHost,
                iPort,
                strMailFrom,
                strDisplayName,
                strUserName,
                strPassword,
                strMailTo,
                strCC,
                strSubject,
                strBody,
                bEnableSsl
                );
            }
        }
        clearText();
        lblSucess.Text = "Email has been send.";
    }
Ejemplo n.º 36
0
        /// <summary>
        /// 构造方法
        /// </summary>
        public FrmAutoUpdate()
        {
            InitializeComponent();

            string configFilePath = Environment.CurrentDirectory + "\\" + AutoUpdateCoeus.LocalConfigFileName;

            if (!File.Exists(configFilePath))
            {
                MessageBox.Show("不存在配置文件:" + configFilePath + ",升级失败");
                Environment.Exit(0);
                return;
            }
            AppSettingsSection configSection = null;
            var fileMap = new ExeConfigurationFileMap()
            {
                ExeConfigFilename = configFilePath
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            foreach (var loopSectionKey in config.Sections.Keys)
            {
                if (loopSectionKey.ToString() == "appSettings")
                {
                    configSection = (AppSettingsSection)config.GetSection("appSettings");
                    break;
                }
            }
            if (configSection != null)
            {
                if (configSection.Settings.AllKeys.Contains("UpgradeFtpUrl"))
                {
                    AutoUpdateCoeus.UrlOfUpgrade = configSection.Settings["UpgradeFtpUrl"].Value;
                }
                if (configSection.Settings.AllKeys.Contains("UpgradeFtpUserName"))
                {
                    AutoUpdateCoeus.UserNameOfUpgrade = configSection.Settings["UpgradeFtpUserName"].Value;
                }
                if (configSection.Settings.AllKeys.Contains("UpgradeFtpPwd"))
                {
                    AutoUpdateCoeus.PasswordOfUpgrade = configSection.Settings["UpgradeFtpPwd"].Value;
                }
            }
            if (string.IsNullOrEmpty(AutoUpdateCoeus.UrlOfUpgrade))
            {
                MessageBox.Show("未配置 FTP升级地址:appSettings->UpgradeFtpUrl,升级失败");
                Environment.Exit(0);
                return;
            }
            if (string.IsNullOrEmpty(AutoUpdateCoeus.UserNameOfUpgrade))
            {
                MessageBox.Show("未配置 FTP升级用户名:appSettings->UpgradeFtpUserName,升级失败");
                Environment.Exit(0);
                return;
            }
            if (string.IsNullOrEmpty(AutoUpdateCoeus.PasswordOfUpgrade))
            {
                MessageBox.Show("未配置 FTP升级密码:appSettings->UpgradeFtpPwd,升级失败");
                Environment.Exit(0);
                return;
            }
        }
Ejemplo n.º 37
0
        protected static void LoadContainer(IUnityContainer unityContainer,
                                            string configFile,
                                            string containerName,
                                            ref RecursionData data)
        {
            var fileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = configFile
            };
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

            // Parent configs to load.
            KeyValueConfigurationElement baseFiles = configuration.AppSettings.Settings["base"];

            if (baseFiles != null)
            {
                string[] files = baseFiles.Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string file in files)
                {
                    string baseFile = Path.Combine(Path.GetDirectoryName(configFile), file.Trim());
                    if (!File.Exists(baseFile))
                    {
                        throw new FileNotFoundException(string.Format("Configuration file '{0}' not found", baseFile));
                    }

                    // Recursively load parent files.
                    LoadContainer(unityContainer, baseFile, containerName, ref data);
                }
            }

            UnityConfigurationSection unitySection = (UnityConfigurationSection)configuration.GetSection("unity");

            // Copy aliases.
            IList <AliasElement> aliasElements = data.Aliases?.Where(x => unitySection.TypeAliases.All(y => y.Alias != x.Alias)).ToList();

            if (aliasElements != null)
            {
                foreach (AliasElement aliasElement in aliasElements)
                {
                    unitySection.TypeAliases.Add(new AliasElement {
                        Alias = aliasElement.Alias, TypeName = aliasElement.TypeName
                    });
                }
            }

            // Copy namespaces.
            IList <NamespaceElement> namespaceElements = data.Namespaces?.Where(x => unitySection.Namespaces.All(y => y.Name != x.Name)).ToList();

            if (namespaceElements != null)
            {
                foreach (NamespaceElement namespaceElement in namespaceElements)
                {
                    unitySection.Namespaces.Add(new NamespaceElement {
                        Name = namespaceElement.Name
                    });
                }
            }

            // Copy assemblies.
            IList <AssemblyElement> assembliesElements = data.Assemblies?.Where(x => unitySection.Assemblies.All(y => y.Name != x.Name)).ToList();

            if (assembliesElements != null)
            {
                foreach (AssemblyElement assemblyElement in assembliesElements)
                {
                    unitySection.Assemblies.Add(new AssemblyElement {
                        Name = assemblyElement.Name
                    });
                }
            }

            data.Aliases    = unitySection.TypeAliases;
            data.Assemblies = unitySection.Assemblies;
            data.Namespaces = unitySection.Namespaces;

            if (unitySection.Containers.Any(x => x.Name == containerName))
            {
                unityContainer.LoadConfiguration(unitySection, containerName);
            }
        }
Ejemplo n.º 38
0
        static void Main(string[] args)
        {
            ///System.Diagnostics.Debugger.Launch();
            DAapp.Generic.ProcessMessage = "DA Setup Started at:" + DateTime.Now + ".";

            //DAapp.Program.module = args[0];

            //arguments = new Helper();
            //arguments.Parse(args);
            DAapp.Generic.OutputMessage = "step1";
            ReadConfig();
            DAapp.Generic.OutputMessage = "step12";
            int count = 0;

            if (DAapp.Program.sDAScriptsPath.Contains('\"'))
            {
                DAapp.Generic.OutputMessage = "step3";
                count = DAapp.Program.sDAScriptsPath.LastIndexOf('\"');
                /// count = DAapp.Program.sDAScriptsPath.LastIndexOf('\\');
                DAapp.Program.sBinpath       = DAapp.Program.sDAScriptsPath.Substring(0, count);
                DAapp.Program.sDAScriptsPath = DAapp.Program.sDAScriptsPath.Replace('"', '\\');
            }
            else
            {
                DAapp.Generic.OutputMessage = "step4";
                count = DAapp.Program.sDAScriptsPath.LastIndexOf('\\');
                DAapp.Program.sBinpath = DAapp.Program.sDAScriptsPath.Substring(0, count);
            }
            int count2 = DAapp.Program.sBinpath.LastIndexOf('\\');

            DAapp.Program.sBinpath = DAapp.Program.sBinpath.Substring(0, count2) + "\\";

            DAapp.Program.smodulePath = DAapp.Program.sDAScriptsPath + DAapp.Program.module + "\\";
            DAapp.Program.sExePath    = DAapp.Program.sDAScriptsPath + "DA_EXE'S\\";

            count = DAapp.Program.sBinpath.LastIndexOf('\\');
            DAapp.Program.sWCFPath = DAapp.Program.sBinpath.Substring(0, count);
            count2 = DAapp.Program.sWCFPath.LastIndexOf('\\');
            DAapp.Program.sWCFPath = DAapp.Program.sWCFPath.Substring(0, count2) + "\\";

            count = DAapp.Program.sWCFPath.LastIndexOf('\\');
            DAapp.Program.sRmxinstallpath = DAapp.Program.sWCFPath.Substring(0, count);
            count2 = DAapp.Program.sRmxinstallpath.LastIndexOf('\\');
            DAapp.Program.sRmxinstallpath = DAapp.Program.sRmxinstallpath.Substring(0, count2);

            DAapp.Program.orcldriver = string.Empty;  // If connection is sql mark this as empty;

            GetConnectionStringInfo();

            try
            {
                if (DAapp.Program.module == "MMSEA")
                {
                    sATLFileName       = "MMSEA_Medicare.atl";
                    sDataStoreFileName = "MMSEA_Datastores.xml";
                    sJOBxmlFileName    = "MMSEAJOB.xml";
                    sSUB_JOB_NAME      = "MMSEA";
                    sTaskname          = "MMSEA";
                    sjobname           = "J_MMSEA";
                }
                else if (DAapp.Program.module == "PPY")
                {
                    sATLFileName       = "PositivePay.atl";
                    sDataStoreFileName = "PPY_Datastores.xml";
                    sJOBxmlFileName    = "PPYJOB.xml";
                    sSUB_JOB_NAME      = "PPY";
                    sTaskname          = "PositivePay";
                    sjobname           = "J_POSITVE_PAY";
                }
                else if (DAapp.Program.module == "1099")
                {
                    sATLFileName       = "RM1099.atl";
                    sDataStoreFileName = "1099_Datastores.xml";
                    sJOBxmlFileName    = "1099JOB.xml";
                    sSUB_JOB_NAME      = "1099";
                    sTaskname          = "1099-MISC";
                    sjobname           = "J_1099";
                }
                else if (DAapp.Program.module == "SICS")
                {
                    sATLFileName       = "DA_SICS.atl";
                    sDataStoreFileName = "SICS_Datastores.xml";
                    sJOBxmlFileName    = "SICSJOB.xml";
                    sSUB_JOB_NAME      = "SICS";
                    sTaskname          = "SICS";
                    sjobname           = "J_SICS";
                }
                else if (DAapp.Program.module == "ACH")
                {
                    sATLFileName       = "ACH.atl";
                    sDataStoreFileName = "ACH_Datastores.xml";
                    sJOBxmlFileName    = "ACHJOB.xml";
                    sSUB_JOB_NAME      = "ACH";
                    sTaskname          = "ACH";
                    sjobname           = "J_ACH";
                }

                bool bRMlocVal   = false;
                bool blnS3locval = false;
                // mkaur24 RM WCF/Bin setup starts
                CheckDBConnection(); // Check taskmanager connection  and security db connection
                int[] DSNDetails = new int[2];
                iDSNID       = docpathtype(sDsnName, sSecurityDBconn)[0];
                DSNValidated = checkconnfordsn(DAapp.Program.sDsnName);
                DAapp.Generic.ProcessMessage = "DSNValidated:" + DSNValidated + ".";
                // sjobname = "J_" + module + "_" + iDSNID;


                ///// mkaur24 createdb function commented isliye start
                //DAapp.Program.sDsndb = "Driver={SQL Server};Server=20.198.139.104;Database=RM19_mk;UID=sa;PWD=Enter@789;";
                //DAapp.Program.sRMDBServer = "20.198.139.104";
                //DAapp.Program.sRepoDatabaseName = "Repo_MMSEA_12";
                //DAapp.Program.sStagingDB = "MMSEA_STAG_12";
                //DAapp.Program.sStagingDBconn = "Driver={SQL Server};Server=20.198.139.104;Database=MMSEA_STAG_12;UID=sa;pwd=Enter@789;";
                //DAapp.Program.sRepoServername = "20.198.139.104";
                //DAapp.Program.sRepoUsername = "******";
                //DAapp.Program.sRepoPassword = "******";
                //DAapp.Program.sStagingDBServer = "20.198.139.104";
                //DAapp.Program.sStagingDBUser = "******";
                //DAapp.Program.sStagingDBPwd = "Enter@789";
                //DAapp.Program.sRMXStagingDBServer = "20.198.139.104";
                //DAapp.Program.sRMXStagingDBUser = "******";
                //DAapp.Program.sRMXStagingDBPwd = "Enter@789";
                ///// mkaur24 createdb function commented isliye endsv (remove this)



                // RM Setup commented as of now starts

                sDocAttachNameDelimeter = "/";                    //hardcoded rahega;
                /// sDocumentManagementEnabled = "true";//this should not be given in case of mmsea. The job is faLLING DOWN
                srmADocumentPoolPath   = DAapp.Program.sFilePath; //this is mandatory. Has to be on rmserver
                sKeepJobFilesOnSuccess = "true";



                bRMlocVal = CheckRMloc(DAapp.Program.sDAScriptsPath);

                blnS3locval = CheckS3loc(); // check if s3 location is accessible.
                CreateWSDURL();

                //if (blnS3locval || bRMlocVal)
                //    ErrorEnc = true;
                RMExpressSetup();
                GetExeConfigFiles();
                UpdateConfigFiles();


                if (!ModuleExist)
                {
                    // FUNCTION TO DELETE DB IF ANY ERROR OCCURS

                    Helper objHelper = new Helper();

                    /// DA Setup Starts


                    sS3XMLFileName = "AmazonS3.xml";
                    sTemplatePath  = DAapp.Program.sDAScriptsPath + module;
                    sATLFilePath   = sTemplatePath + sATLFileName;     /// not used

                    int sJobServerapp = Convert.ToInt32(GetConfigKey("JobserverLastused"));
                    sJobServerapp = sJobServerapp + 1;
                    string appPath    = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                    string configFile = System.IO.Path.Combine(appPath, "DAapp.EXE.config");
                    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                    configFileMap.ExeConfigFilename = configFile;
                    System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
                    config.AppSettings.Settings["JobserverLastused"].Value = sJobServerapp.ToString();
                    config.Save();
                    sJSPort        = sJobServerapp.ToString(); // job server -1025 to 32766  ///49151
                    sJobServerName = "JS_" + module + "_" + sJSPort;
                    DAapp.Generic.ProcessMessage = "JobServerName Created" + sJobServerName + ".";

                    /// If password has $ in it. Handling for powershell start
                    if (DAapp.Program.sRMDBPwd.Contains("$"))
                    {
                        DAapp.Program.sRMDBPwd = DAapp.Program.sRMDBPwd.Replace("$", "`$");
                    }
                    if (DAapp.Program.sSecurityDBPwd.Contains("$"))
                    {
                        DAapp.Program.sSecurityDBPwd = DAapp.Program.sSecurityDBPwd.Replace("$", "`$");
                    }
                    if (DAapp.Program.sStagingDBPwd.Contains("$"))
                    {
                        DAapp.Program.sStagingDBPwd = DAapp.Program.sStagingDBPwd.Replace("$", "`$");
                    }
                    if (DAapp.Program.sRMXStagingDBPwd.Contains("$"))
                    {
                        DAapp.Program.sRMXStagingDBPwd = DAapp.Program.sRMXStagingDBPwd.Replace("$", "`$");
                    }



                    /// If password has $ in it. Handling for powershell startends



                    string DAServer       = DAapp.Program.sDAServer;
                    string username       = DAapp.Program.sDAServerUserName;
                    string password       = DAapp.Program.sDAServerPwd;
                    string sModuleName    = DAapp.Program.module;
                    string RMTemplatePath = DAapp.Program.smodulePath;
                    string RMFileName     = sATLFileName;
                    string DSFileName     = sDataStoreFileName;
                    string S3FileName     = sS3XMLFileName;
                    string DATemplatePath = @"C:\DA_SCRIPTS\";
                    string sUsername      = DAapp.Program.sRepoUsername; // use yhi horhe hain.  username pwd and servername. As per real time everything will be on same server so we can use this.has to be becuase servname seggregation is not done in atl ds
                    string sPassword      = DAapp.Program.sRepoPassword;
                    string sServername    = DAapp.Program.sRepoServername;
                    string sDatabaseName  = DAapp.Program.sRepoDatabaseName;
                    string sRMDBPwd       = DAapp.Program.sRMDBPwd; // see this ye kaha se ayega
                    string sRMDBName      = DAapp.Program.sRiskMasterDB;
                    string sRMDBUser      = DAapp.Program.sRMDBUser;
                    string sSecPwd        = DAapp.Program.sSecurityDBPwd;
                    string sSecDBName     = DAapp.Program.sSecurityDB;
                    string sSecUser       = DAapp.Program.sSecurityDBUser;
                    string sSecServer     = DAapp.Program.sSecurityDBServer;
                    string sStagPwd       = DAapp.Program.sStagingDBPwd;
                    string sStagDBName    = DAapp.Program.sStagingDB;
                    string sStagUser      = DAapp.Program.sStagingDBUser;
                    string sRMXStagPwd    = DAapp.Program.sRMXStagingDBPwd;
                    string sRMXStagDBName = DAapp.Program.sRMXStagingDB;
                    string sRMXStagUser   = DAapp.Program.sRMXStagingDBUser;
                    string BucketName     = DAapp.Program.sBucketName;
                    string S3AccessKey    = DAapp.Program.sAccessKey;
                    string S3SecretKey    = DAapp.Program.sSecretKey;
                    string DSJobFileName  = sJOBxmlFileName;
                    string JobName        = sjobname;
                    string FilePath       = sFilePath;


                    // as of now code because 172.31.43.96 IS PRIVATE IP AND IT WILL NOT BE ACCESSED FROM 232 DA SERVER SO REPLACEING IT WITH public ip
                    if (DAapp.Program.sRMDBServer == "172.31.37.15")
                    {
                        sSecServer = sServername = GetConfigKey("rmdbseverasofnow");
                    }
                    //string publicIp = "20.198.154.160";
                    //string username = @"Asiapac\mkaur24";
                    //string password = "******";
                    //string sModuleName = "MMSEA";
                    //string RMTemplatePath = @"E:\rmcode6\Riskmaster\WCFService\bin\DA_SCRIPTS\MMSEA\";
                    //string RMFileName = "MMSEA_Medicare.atl";
                    //string DSFileName = "MMSEA_Datastores.xml";
                    //string S3FileName = "AmazonS3.xml";
                    //string DATemplatePath = @"C:\DA_SCRIPTS\";
                    //string sUsername = "******";
                    //string sPassword = "******";
                    //string sServername = "20.198.139.11";
                    //string sDatabaseName = "Repomk21";
                    //string sJobServerName = "JSmeamk213";
                    //string sJSPort = "4594";
                    //string sRMDBPwd = "Enter@789";
                    //string sRMDBName = "RM19_mk";
                    //string sRMDBUser = "******";
                    //string sSecPwd = "Enter@789";
                    //string sSecDBName = "Security_mk";
                    //string sSecUser = "******";
                    //string sStagPwd = "Enter@789";
                    //string sStagDBName = "MMSEA_STAG_12";
                    //string sStagUser = "******";
                    //string sRMXStagPwd = "Enter@789";
                    //string sRMXStagDBName = "MMSEA_STAG_12";
                    //string sRMXStagUser = "******";
                    //string BucketName = "rmadebucket1";
                    //string S3AccessKey = "AKIA4IBYFUZMUHMMKYT6";
                    //string S3SecretKey = "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";
                    //string FilePath="C:\Filepath"

                    if (DAapp.Program.module == "SICS")
                    {
                        sStagDBName = DAapp.Program.sRMXStagingDB;
                    }

                    string[] test = { DAServer,  username,    password,    sModuleName,   RMTemplatePath, RMFileName,   DSFileName, S3FileName,  DATemplatePath,
                                      sUsername, sPassword,   sServername, sDatabaseName, sJobServerName, sJSPort,      sRMDBPwd,   sRMDBName,   sRMDBUser,     sSecPwd,     sSecDBName,    sSecUser,
                                      sStagPwd,  sStagDBName, sStagUser,   sRMXStagPwd,   sRMXStagDBName, sRMXStagUser, BucketName, S3AccessKey, S3SecretKey,   sSecServer,  DSJobFileName, JobName, FilePath };

                    // mkaur24 start powershell exexcution starts

                    DAapp.Generic.ProcessMessage = DAServer + " , " + username + " , " + password + " , " + sModuleName + " , " + RMTemplatePath + " , " + RMFileName + " , " + DSFileName + " , " + S3FileName + " , " + DATemplatePath + " , " +
                                                   sUsername + " , " + sPassword + " , " + sServername + " , " + sDatabaseName + " , " + sJobServerName + " , " + sJSPort + " , " + sRMDBPwd + " , " + sRMDBName + " , " + sRMDBUser + " , " + sSecPwd + " , " + sSecDBName + " , " + sSecUser + " , " +
                                                   sStagPwd + " , " + sStagDBName + " , " + sStagUser + " , " + sRMXStagPwd + " , " + sRMXStagDBName + " , " + sRMXStagUser + " , " + BucketName + " , " + S3AccessKey + " , " + S3SecretKey + " , " + sSecServer;
                    var scriptfile = DAapp.Program.sDAScriptsPath + "DASetupScript.ps1";

                    String line = string.Empty;
                    Collection <PSObject> results = null;
                    using (StreamReader sr = new StreamReader(scriptfile))
                    {
                        line = sr.ReadToEnd();
                    }
                    using (var powershell = PowerShell.Create())
                    {
                        powershell.AddScript(line, false);
                        powershell.Invoke();
                        powershell.Commands.Clear();
                        ////  powershell.AddCommand("GetParams").AddParameter("password", "foo");
                        powershell.AddCommand("GetParameter").AddParameter("arr", test);
                        results = powershell.Invoke();
                    }
                    DAapp.Generic.ProcessMessage = "DA setup ends.";

                    //StringBuilder stringBuilder = new StringBuilder();
                    //foreach (PSObject obj in results)
                    //{
                    //    try
                    //    {
                    //        if (!string.IsNullOrEmpty(obj.ToString()))
                    //            stringBuilder.AppendLine(obj.ToString());
                    //    }
                    //    catch (Exception ex)
                    //    {

                    //    }

                    //}

                    //  WriteDAProcessLog(stringBuilder.ToString());



                    ///// Now moved this work to Power Shell Start


                    ///// Create DA Repository
                    //objHelper.ExectueAutomationCommands("R", sRepoUsername, sRepoPassword, sRepoServername, sRepoDatabaseName, null, null, null, null, null, null, null, null);
                    //Console.WriteLine("DA Repo Created.Successful.");

                    ///// Import ATL
                    //objHelper.ExectueAutomationCommands("A", sRepoUsername, sRepoPassword, sRepoServername, sRepoDatabaseName, sATLFilePath, null, null, null, null, null, null, null);
                    //Console.WriteLine("ATL Imported.Successful");

                    /////Create Job Server
                    //objHelper.ExectueAutomationCommands("J", sRepoUsername, sRepoPassword, sRepoServername, sRepoDatabaseName, sATLFilePath, sJobServerName, sJSPort, null, null, null, null, null);
                    //Console.WriteLine("Job Server Created.Successful");

                    ///// Stop Services
                    //objHelper.ExectueAutomationCommands("Stop", null, null, null, null, null, null, null, null, null, null, null, null);
                    //Console.WriteLine("SAP Services Stopped.");

                    ///// Start Services
                    //objHelper.ExectueAutomationCommands("Start", null, null, null, null, null, null, null, null, null, null, null, null);
                    //Console.WriteLine("SAP Services Started.");

                    ///// Get SAP Encrypted Password for RMDB
                    //objHelper.ExectueAutomationCommands("RMDBPWD", null, null, null, null, null, null, null, sRMDBPwd, null, null, null, null);

                    //// Get SAP Encrypted Password for StagingDB
                    //objHelper.ExectueAutomationCommands("StagPWD", null, null, null, null, null, null, null, null, null, sStagingDBPwd, null, null);
                    //// Get SAP Encrypted Password for SecurityDB
                    //objHelper.ExectueAutomationCommands("SecPWD", null, null, null, null, null, null, null, null, sSecurityDBPwd, null, null, null);


                    ///// Update DataStore Configuration
                    //objHelper.AddDataStoreConfiguration(sTemplatePath, sDataStoreFileName, sRiskMasterDB, sRMDBServer, sRMDBUser, EncryptRMDBPwd, sSecurityDB, sSecurityDBServer, sSecurityDBUser, EncryptSecPwd, sStagingDB, sStagingDBServer, sStagingDBUser, EncryptStagPwd);

                    ///// Import DataStore XML
                    //objHelper.ExectueAutomationCommands("X", sRepoUsername, sRepoPassword, sRepoServername, sRepoDatabaseName, XMLFilePathMod, null, null, null, null, null, null, null);
                    //Console.WriteLine("DataStore Configuration.Successful");

                    ///// Get SAP Encrypted Password for S3AccessKey
                    //objHelper.ExectueAutomationCommands("S3AccessKey", null, null, null, null, null, null, null, null, null, null, sAccessKey, null);

                    ///// Get SAP Encrypted Password for S3SecretKey
                    //objHelper.ExectueAutomationCommands("S3SecretKey", null, null, null, null, null, null, null, null, null, null, null, sSecretKey);

                    ///// Update Amazon S3 XML
                    //objHelper.AddS3FileLocation(sTemplatePath, sS3XMLFileName, sBucketName, S3SecretKey, S3AccessKey);

                    ///// Import Amazon S3 XML
                    //objHelper.ExectueAutomationCommands("X", sRepoUsername, sRepoPassword, sRepoServername, sRepoDatabaseName, S3XMLFilePathMod, null, null, null, null, null, null, null);
                    //Console.WriteLine("Amazon S3 Configuration.Successful");

                    ///// Now moved this work to Power Shell Ends



                    //            }
                    //catch (Exception ex)
                    //{
                    //    if (ErrorEnc)
                    //        CreateDB("", "Drop");
                    //}
                    //finally
                    //{

                    //}
                }
                else

                {
                    DAapp.Generic.OutputMessage = "The module already exists." + DAapp.Program.module;
                    DAapp.Generic.writeLog(DAapp.Generic.OutputMessage, Path.Combine(DAapp.Program.logfilepath));
                    /// CreateDB(module, "Drop");
                    Environment.Exit(0);
                }
            }
            catch (Exception e)
            {
                DAapp.Generic.OutputMessage = "Exe completed with error.Error Message:" + e.Message;
                DAapp.Generic.writeLog(DAapp.Generic.OutputMessage, Path.Combine(DAapp.Program.logfilepath));
                //Environment.Exit(0);
            }
            finally
            {
                if (ErrorEnc)
                {
                    CreateDB(module, "Drop");
                    Environment.Exit(0);
                }
                DAapp.Generic.writeLog(DAapp.Generic.ProcessMessage, Path.Combine(DAapp.Program.processlogPath));
            }
        }
        static void Main(string[] args)
        {
            var configfile = "app.config";
            var region     = "";
            var table      = "";
            var partition  = "";
            var sort       = "";

            // 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 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 "-p":
                    i++;
                    partition = args[i];
                    break;

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

                default:
                    break;
                }

                i++;
            }

            if ((partition == "") || (sort == ""))
            {
                Console.WriteLine("You must supply a partition key (-p KEY) and sort key (-s KEY)");
                return;
            }

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

            var resp = RemoveItemAsync(client, table, partition, sort);

            if (resp.Result.HttpStatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Removed item from " + table + " table in " + region + " region");
            }
        }