Ejemplo n.º 1
0
        public void CreateConfigFile(SampleRunnerOptions options, out string newConfigFilePath)
        {
            newConfigFilePath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".config");
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap {
                ExeConfigFilename = newConfigFilePath
            };
            var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None, options.EnablePreloadConfigFileCheckBox);

            // Create configuration
            var section = new ValidationSampleSection();

            // NOTE: Can really be any name, but the same name must be used when reading.
            config.Sections.Add("validationSampleSection", section);

            var foo = new Samples.Configuration.ValidationSample.Foo();

            foo.Baz     = "I have dots!..."; // Exception will fire here!
            section.Foo = foo;

            config.Save();
        }
        private void RunConfigDemo_Validation(ConfigurationFile configFile)
        {
            try
            {
                //var group = config.GetSectionGroup("SampleConfigurationGroup") as ConfigurationSectionGroup;
                //WriteResult("\tgroup: {0}\r\n", group.Sections[0]);

                // With groups, we MUST find this way!!!
                //var section = group.Sections[0] as ValidationSampleSection; // config.Sections["validationSampleSection"] as ValidationSampleSection;
                //var section = config.Sections["validationSampleSection"] as ValidationSampleSection;

                /** OBSERVATIONS:
                 * + Validation exceptions are thrown in order of property ACCESS. They are not thrown when loading section...
                 *   When not loading section through default config, property validation isn't pre-executed.
                 * */

                // Not working... Manager not used when manually load file. Causes validators to not call on GetSection????
                //WriteResult("\tValidationSampleSection.Instance.anythingButDots: {0}\r\n", ValidationSampleSection.Instance.anythingButDots);
                //ConfigurationManager.OpenMappedExeConfiguration()
                //ValidationSampleSection section = ConfigurationManager.GetSection("validationSampleSection") as ValidationSampleSection;
                ValidationSampleSection section = null;

                /**
                 * Below, there is some custom logic not present in other samples. This logic was used as "an experiment" and
                 * will be better organized into a seperate component.
                 * */
                if (checkBox1.Checked)
                {
                    WriteResult("*** About to use CustomAppConfig.Change to load section as though it were default app.config!");
                    WriteResult("\r\n");

                    // Not working as I was expecting....
                    using (AppConfigRedirector.Change(configFile.ConfigFilePath))
                    {
                        // the app.config in tempFileName is used
                        section = ConfigurationManager.GetSection("validationSampleSection") as ValidationSampleSection;



                        //section = ValidationSampleSection.Instance;

                        WriteResult("*** Now attempting to read properties. If properties were validated during section load, this message would never be shown!");
                        WriteResult("\r\n");

                        WriteResult("\tsection.anythingButDots: {0}\r\n", section.AnythingButDots);
                        WriteResult("\tsection.Foo.Baz: {0}\r\n", section.Foo.Baz);

                        //WriteResult("\tsection.Bars[0].noDots: {0}\r\n", section.Bars[0].noDots);
                    }
                }
                else
                {
                    // IMPORTANT: For this test and all others, validation error handling is NOT the same as what you
                    // would expect, because here, we load config via EXEMAP. Special error handling must be added when loading
                    // config via exemap! In default app.config, all validation errors are collected in a list and are included in
                    // a thrown exception at the end. For manual file load, NO validation exception results until property is accessed (I will
                    // provide detailed document as to why later). However, you still have access to list of errors. You
                    // will need to iterate through the errors and throw your own ConfigurationErrorsException for this
                    // to behave as expected.

                    // Below, I demonstrate how to access this list of errors.
                    WriteResult("\r\n[[ NOTE ]] This sample includes Special validation logic below. See MainForm.cs source for more info.\r\n");

                    //if ((configFile.CurrentConfiguration == null) && configFile.IsTempFile)
                    if (configFile == null)
                    {
                        WriteResult("\r\n[ NOTE ] Configuration could not be loaded! (possible reason) If we were trying to create a temp config file with a bad attribute, it would never be written to file and this NULL would result.\r\n");
                    }
                    section = configFile.CurrentConfiguration.GetSection("validationSampleSection") as ValidationSampleSection;


                    var errs = section.ElementInformation.Errors;

                    if (errs.Count > 0)
                    {
                        WriteResult("\r\n[[ ERROR(s) REPORTED! ]] Config loader returned a list of 1 or more validation errors:\r\n");

                        foreach (ConfigurationErrorsException err in errs)
                        {
                            WriteResult("\r\n* ERROR: {0}\r\n", err.ToString());
                            if (err.Errors.Count > 1)
                            {
                                foreach (ConfigurationErrorsException interr in err.Errors)
                                {
                                    WriteResult("\r\n*** INNER {0}\r\n", interr.ToString());
                                }
                            }
                        }
                    }
                    WriteResult("\r\n*** Now attempting to read properties. If properties were validated during section load, this message would never be shown!");
                    WriteResult("\r\n");

                    WriteResult("\tsection.anythingButDots: {0}\r\n", section.AnythingButDots);
                    WriteResult("\tsection.Foo.Baz: {0}\r\n", section.Foo.Baz);
                    WriteResult("\tsection.Bars[0].noDots: {0}\r\n", section.Bars[0].NoDots);
                }
                // section = config.GetSection("validationSampleSection") as ValidationSampleSection;
                // section.CurrentConfiguration.EvaluationContext.GetSection()
            }
            catch (Exception ex)
            {
                WriteErrorResult(ex);
            }
            finally
            {
                WriteEndResult();
            }
        }