/// <summary>
        /// Reads a configuration using the specified encryption engine from the specified path
        /// </summary>
        /// <param name="encryptionEngine">The encryption engine to use while reading the configuration, null if no decryption is desired</param>
        /// <param name="configuration">The configuration to be read into</param>
        /// <param name="path">The path to be read from</param>
        /// <returns></returns>
        public static bool ReadConfiguration(FileEncryptionEngine encryptionEngine, out XmlConfiguration configuration, string path)
        {
            Stream stream = null;

            _lastException = null;

            try
            {
                configuration = new XmlConfiguration();
                stream        = (encryptionEngine != null ? encryptionEngine.CreateDecryptorStream(path) : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None));
                XmlConfigurationReader reader = new XmlConfigurationReader();
                configuration      = reader.Read(stream);
                configuration.Path = path;
                configuration.SetHasUnpersistedChanges(false);

                return(true);
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex);
                _lastException = ex;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            configuration = null;
            return(false);
        }
        /// <summary>
        /// Writes a configuration using the specified encryption engine to the specified path
        /// </summary>
        /// <param name="encryptionEngine">The encryption engine to use while writing the configuration, null if no encryption is desired</param>
        /// <param name="configuration">The confiruration to write</param>
        /// <param name="path">The path to write it to</param>
        /// <returns></returns>
        public static bool WriteConfiguration(FileEncryptionEngine encryptionEngine, XmlConfiguration configuration, string path)
        {
            Stream stream = null;

            _lastException = null;

            try
            {
                if (configuration != null)
                {
                    if (configuration.HasUnpersistedChanges())
                    {
                        configuration.AcceptChanges();
                        stream = (encryptionEngine != null ? encryptionEngine.CreateEncryptorStream(path) : new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None));
                        XmlConfigurationWriter writer = new XmlConfigurationWriter();
                        writer.Write(configuration, stream, false);
                        configuration.SetHasUnpersistedChanges(false);
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex);
                _lastException = ex;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            return(false);
        }
示例#3
0
        public void MixingLoaders()
        {
            string xml =
                @"<nhv-configuration xmlns='urn:nhv-configuration-1.0'>
		<mapping assembly='NHibernate.Validator.Tests' resource='NHibernate.Validator.Tests.Base.Address.nhv.xml'/>
	</nhv-configuration>"    ;
            XmlDocument cfgXml = new XmlDocument();

            cfgXml.LoadXml(xml);
            XmlTextReader    xtr = new XmlTextReader(xml, XmlNodeType.Document, null);
            XmlConfiguration cfg = new XmlConfiguration(xtr);
            XmlMappingLoader ml  = new XmlMappingLoader();

            ml.LoadMappings(cfg.Mappings);

            string tmpf = Path.GetTempFileName();

            using (StreamWriter sw = new StreamWriter(tmpf))
            {
                sw.WriteLine("<?xml version='1.0' encoding='utf-8' ?>");
                sw.WriteLine("<nhv-mapping xmlns='urn:nhibernate-validator-1.0'>");
                sw.WriteLine("<class name='Boo'>");
                sw.WriteLine("<property name='field'><notnullorempty/></property>");
                sw.WriteLine("</class>");
                sw.WriteLine("</nhv-mapping>");
                sw.Flush();
            }
            ml.AddFile(tmpf);
            Assert.AreEqual(2, ml.Mappings.Length);
        }
示例#4
0
        protected override void ProcessRecord()
        {
            var configurationFile = this.ToAbsolutePath(ConfigurationFile);
            this.deltasDirectory = this.ToAbsolutePath(DeltasDirectory);

            if (!string.IsNullOrEmpty(configurationFile) && File.Exists(configurationFile))
            {
                this.config = new XmlConfiguration(configurationFile);

                if (string.IsNullOrEmpty(this.DatabaseType) || this.DatabaseType == DatabaseTypeDefault)
                    this.DatabaseType = this.config.DbType;

                if (string.IsNullOrEmpty(this.ConnectionString))
                    this.ConnectionString = this.config.DbConnectionString;

                if (string.IsNullOrEmpty(this.TableName) || this.TableName == TableNameDefault)
                    this.TableName = this.config.TableName;
            }

            if (string.IsNullOrEmpty(this.ConnectionString))
            {
                throw new InvalidDataException(
                    "Missing connection string. It must either be in the config file or passed as a parameter");
            }
        }
示例#5
0
        protected override void Configure(NHibernate.Cfg.Configuration configuration)
        {
            // The ValidatorInitializer and the ValidateEventListener share the same engine

            // Initialize the SharedEngine
            fortest = new NHibernateSharedEngineProvider();
            Cfg.Environment.SharedEngineProvider = fortest;
            ValidatorEngine ve = Cfg.Environment.SharedEngineProvider.GetEngine();

            ve.Clear();

            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Cfg.Environment.ApplyToDDL]               = "true";
            nhvc.Properties[Cfg.Environment.AutoregisterListeners]    = "true";
            nhvc.Properties[Cfg.Environment.ValidatorMode]            = "UseAttribute";
            nhvc.Properties[Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;

            var enversConf = new FluentConfiguration();

            enversConf.Audit <Address>();
            configuration.IntegrateWithEnvers(enversConf);

            ve.Configure(nhvc);

            ValidatorInitializer.Initialize(configuration);
        }
        protected override void Configure(NHibernate.Cfg.Configuration configuration)
        {
            // The ValidatorInitializer and the ValidateEventListener share the same engine

            // Initialize the SharedEngine
            _fortest = new NHibernateSharedEngineProvider();
            Cfg.Environment.SharedEngineProvider = _fortest;
            var ve = Cfg.Environment.SharedEngineProvider.GetEngine();

            ve.Clear();
            var nhvc = new XmlConfiguration
            {
                Properties =
                {
                    [Cfg.Environment.ApplyToDDL] = "true",
                    [Cfg.Environment.AutoGenerateFromMapping]  = "true",
                    [Cfg.Environment.AutoregisterListeners]    = "true",
                    [Cfg.Environment.ValidatorMode]            = "UseAttribute",
                    [Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName
                }
            };

            ve.Configure(nhvc);
            //ve.IsValid(new HibernateAnnotationIntegrationFixture.AnyClass());// add the element to engine for test

            configuration.Initialize();
        }
示例#7
0
        /// <summary>
        /// Loads accounts from XML file and into the TreeView
        /// </summary>
        private void LoadAccounts()
        {
            try
            {
                // Clear tree
                accList.Clear();

                // Read accounts
                xml = new XmlConfiguration("accounts.xml");
                var accounts = xml.ReadAccounts();

                // Add to tree
                foreach (var acc in accounts)
                {
                    accList.Add(new AccListItem(acc));
                }

                accList.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurred while loading accounts.\n" + ex.Message, "Fatal error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
示例#8
0
        /// <summary>
        /// Attempts to increment the RunCount option for the specified version of the specified Type
        /// </summary>
        /// <param name="configuration">The configuration in which the option will be found</param>
        /// <param name="type">The Type for which the RunCount value will be incremented</param>
        /// <returns></returns>
        public static bool IncrementRunCountForVersionOfType(XmlConfiguration configuration, Type type, out DateTime installDate, out int runCount)
        {
            installDate = DateTime.Now;
            runCount    = 0;
            try
            {
                XmlConfigurationCategory category = InstallationEngine.GetExistingCategoryForTypeVersion(configuration, type, CategoryNames.Installed);
                if (category != null)
                {
                    XmlConfigurationOption option = null;

                    option = category.Options[@"InstallDate"];
                    if (option != null)
                    {
                        installDate = (DateTime)option.Value;
                    }

                    option = category.Options[@"RunCount"];
                    if (option != null)
                    {
                        // retrieve, increment, and set the run count
                        runCount = (int)option.Value;
                        runCount++;
                        option.Value = runCount;
                    }
                }
            }
            catch (System.Exception systemException)
            {
                System.Diagnostics.Trace.WriteLine(systemException);
            }
            return(false);
        }
        public void NotDuplicatedItems()
        {
            string xml =
                @"<nhv-configuration xmlns='urn:nhv-configuration-1.0'>
		<property name='apply_to_ddl'>false</property>
		<property name='apply_to_ddl'>true</property>
		<property name='default_validator_mode'>OverrideAttributeWithXml</property>
		<property name='default_validator_mode'>UseXml</property>
		<mapping assembly='aAssembly'/>
		<mapping assembly='aAssembly' resource='TheResource'/>
	</nhv-configuration>"    ;
            XmlDocument cfgXml = new XmlDocument();

            cfgXml.LoadXml(xml);
            XmlTextReader    xtr = new XmlTextReader(xml, XmlNodeType.Document, null);
            XmlConfiguration cfg = new XmlConfiguration(xtr);

            Assert.AreEqual(2, cfg.Properties.Count);
            Assert.AreEqual(1, cfg.Mappings.Count);
            Assert.AreEqual("true", cfg.Properties["apply_to_ddl"]);
            Assert.AreEqual("UseXml", cfg.Properties["default_validator_mode"]);
            Assert.Contains(new MappingConfiguration("aAssembly", ""), (IList)cfg.Mappings);

            // Accept only MappingConfiguration object for Equals comparison
            Assert.IsFalse((new MappingConfiguration("NHibernate.Validator.Tests", "")).Equals("NHibernate.Validator.Tests"));
            Assert.IsFalse((new MappingConfiguration("NHibernate.Validator.Tests", "")).Equals(null));
        }
示例#10
0
        static void Main(string[] args)
        {
            var queue        = new ConcurrentQueue <PresenceContainer>();
            var dataEvent    = new AutoResetEvent(false);
            var config       = new XmlConfiguration();
            var configValues = config.Deserialize();

            var alarm  = AlarmFactory.CreateAlarm(configValues.Alarm);
            var filter = FilterFactory.CreateFilter(configValues.Filter);
            var log    = LogFactory.CreateLog(configValues.Log);

            var producer   = new Producer(queue);
            var consumer   = new Consumer(queue, dataEvent);
            var controller = new CtrlHospitalBed(dataEvent, consumer, alarm, filter, log);

            var consumerThread   = new Thread(consumer.Run);
            var producerThread   = new Thread(producer.Run);
            var controllerThread = new Thread(controller.RunSystem);
            var checkThread      = new Thread(controller.CheckKeyChar);

            consumerThread.Start();
            producerThread.Start();
            controllerThread.Start();
            checkThread.Start();
        }
示例#11
0
        static void Main(string[] args)
        {
            const string url = "http://localhost:8080";

            XmlConfiguration configuration = XmlConfiguration.LoadFrom(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AllGreen\\AllGreen\\AllGreen.config");

            TinyIoCContainer resourceResolver = new TinyIoCContainer();

            resourceResolver.Register <IConfiguration>(configuration);
            CompositeWebResources webResources = new CompositeWebResources();
            DynamicScriptList     scriptList   = new DynamicScriptList(configuration.RootFolder, configuration.ServedFolderFilters, configuration.ExcludeServedFolderFilters, new FileSystem());

            webResources.Add(new WebServerResources(scriptList));
            webResources.Add(new FileSystemResources(configuration.RootFolder, scriptList, new FileSystem()));
            resourceResolver.Register <IWebResources>(webResources);
            resourceResolver.Register <IRunnerHub, RunnerHub>();
            resourceResolver.Register <IRunnerBroadcaster>((ioc, npo) => new RunnerBroadcaster(GlobalHost.ConnectionManager.GetHubContext <RunnerHub>().Clients));
            resourceResolver.Register <IReporter, ConsoleReporter>();

            using (WebApp.Start(url, appBuilder => new OwinStartup(resourceResolver).Configuration(appBuilder)))
            {
                System.Console.WriteLine("Server running at " + url);
                string command = "";
                while (command != "x")
                {
                    command = System.Console.ReadLine();
                    resourceResolver.Resolve <IRunnerBroadcaster>().StartAll();
                }
            }
        }
        public void WorkWithOutSharedEngine()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            string[] mappings =
                new string[]
            {
                "Integration.Address.hbm.xml",
                "Integration.Tv.hbm.xml",
                "Integration.TvOwner.hbm.xml",
                "Integration.Martian.hbm.xml",
                "Integration.Music.hbm.xml"
            };
            foreach (string file in mappings)
            {
                cfg.AddResource("NHibernate.Validator.Tests" + "." + file, Assembly.GetExecutingAssembly());
            }
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode]         = "UseAttribute";

            ValidatorInitializer.Initialize(cfg);
        }
示例#13
0
        protected override void ProcessRecord()
        {
            var configurationFile = ToAbsolutePath(ConfigurationFile);
            _deltasDirectory = ToAbsolutePath(DeltasDirectory);

            if (!string.IsNullOrEmpty(configurationFile) && File.Exists(configurationFile))
            {
                _config = new XmlConfiguration(configurationFile);
                if(string.IsNullOrEmpty(DatabaseType))
                    DatabaseType = _config.DbType;
                if(string.IsNullOrEmpty(ConnectionString))
                    ConnectionString = _config.DbConnectionString;
                if(string.IsNullOrEmpty(DeltaSet))
                    DeltaSet = _config.DbDeltaSet;
                if(string.IsNullOrEmpty(TableName))
                    TableName = _config.TableName;
                if(!CurrentDbVersion.HasValue)
                    CurrentDbVersion = _config.CurrentDbVersion;
            }

            if(string.IsNullOrEmpty(ConnectionString))
            {
                throw new InvalidDataException(
                    "Missing connection string. It must either be in the config file or passed as a parameter");
            }

            _dbmsFactory = new DbmsFactory(DatabaseType, ConnectionString, ForDirectExecution);
            _databaseSchemaVersion = new DatabaseSchemaVersionManager(_dbmsFactory,
                                                                     DeltaSet,
                                                                     CurrentDbVersion,
                                                                     TableName);
        }
        public void ApplyWrongConstraint()
        {
            XmlConfigurator.Configure();
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
            {
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            }
            cfg.AddResource("NHibernate.Validator.Tests.Integration.WrongClass.whbm.xml", Assembly.GetExecutingAssembly());
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode]         = "UseAttribute";

            using (LoggerSpy ls = new LoggerSpy(typeof(ValidatorInitializer), Level.Warn))
            {
                ValidatorInitializer.Initialize(cfg);
                int found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof(WrongClass).FullName));
                Assert.AreEqual(1, found);
                found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof(WrongClass1).FullName));
                Assert.AreEqual(1, found);
            }
        }
示例#15
0
        protected override void ProcessRecord()
        {
            var configurationFile = this.ToAbsolutePath(ConfigurationFile);

            this.deltasDirectory = this.ToAbsolutePath(DeltasDirectory);

            if (!string.IsNullOrEmpty(configurationFile) && File.Exists(configurationFile))
            {
                this.config = new XmlConfiguration(configurationFile);

                if (string.IsNullOrEmpty(this.DatabaseType) || this.DatabaseType == DatabaseTypeDefault)
                {
                    this.DatabaseType = this.config.DbType;
                }

                if (string.IsNullOrEmpty(this.ConnectionString))
                {
                    this.ConnectionString = this.config.DbConnectionString;
                }

                if (string.IsNullOrEmpty(this.TableName) || this.TableName == TableNameDefault)
                {
                    this.TableName = this.config.TableName;
                }
            }

            if (string.IsNullOrEmpty(this.ConnectionString))
            {
                throw new InvalidDataException(
                          "Missing connection string. It must either be in the config file or passed as a parameter");
            }
        }
示例#16
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            //NOTE...IMPORTANT!:
            //This is an example of how-to-change-the-configuration.
            //You should maintain in your code just 1 (one) ValidatorEngine,
            //see SharedEngine: http://nhibernate.info/blog/2009/02/26/diving-in-nhibernate-validator.html

            ValidatorEngine ve = vvtor.ValidatorEngine;

            ve.Clear();

            //Configuration of NHV. You can also configure this stuff using xml, outside of the code
            XmlConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "false";
            nhvc.Properties[Environment.AutoregisterListeners] = "false";
            nhvc.Properties[Environment.ValidatorMode]         = GetMode();
            nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Demo.Winforms", null));
            ve.Configure(nhvc);

            Customer customer = GetCustomerFromUI();

            if (ve.IsValid(customer))
            {
                listBox1.Items.Clear();
                Send();
            }
            else
            {
                InvalidValue[] values = ve.Validate(customer);
                FillErrorsOnListBox(values);
            }
        }
示例#17
0
        internal static void LoadConfig_impl(string trinity_config_file)
        {
            lock (config_load_lock)
            {
                if (!File.Exists(trinity_config_file))
                {
                    //TODO log warning
                    return;
                }

                var config = XmlConfiguration.Load(trinity_config_file);

                s_clusterConfigurations.Clear();
                s_localConfigurationSection.Clear();

                if (config.RootConfigVersion == ConfigurationConstants.Values.LEGACYVER)
                {
                    LoadConfigLegacy(trinity_config_file);
                }
                else if (config.RootConfigVersion == ConfigurationConstants.Values.CURRENTVER)
                {
                    LoadConfigCurrrentVer(config);
                }
                else
                {
                    throw new TrinityConfigException("Unrecognized " + ConfigurationConstants.Attrs.CONFIG_VERSION);
                }

                ApplyConfigurationSettings(GetLocalConfiguration());

                is_config_loaded = true;
            }
        }
        public void LoadMappingsSpecific()
        {
            var nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ValidatorMode]      = "useExternal";
            nhvc.Properties[Environment.MappingLoaderClass] = "NHibernate.Validator.Cfg.Loquacious.FluentMappingLoader, NHibernate.Validator";
            nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests",
                                                       "NHibernate.Validator.Tests.Configuration.Loquacious.AddressValidationDef"));
            nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests",
                                                       "NHibernate.Validator.Tests.Configuration.Loquacious.BooValidationDef"));
            var ve = new ValidatorEngine();

            ve.Configure(nhvc);
            var a = new Address {
                Country = string.Empty
            };
            var b = new Boo();

            Assert.That(ve.IsValid(a));
            Assert.That(!ve.IsValid(b));
            a.Country = "bigThan5Chars";
            Assert.That(!ve.IsValid(a));
            b.field = "whatever";
            Assert.That(ve.IsValid(b));
        }
示例#19
0
        protected void Application_Startup(object sender, StartupEventArgs e)
        {
            //XmlConfiguration configuration = XmlConfiguration.LoadFrom(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\AllGreen\\AllGreen\\AllGreen.config");
            XmlConfiguration configuration = GetDummyConfig();

            TinyIoCContainer resourceResolver = new TinyIoCContainer();

            resourceResolver.Register <IConfiguration>(configuration);
            CompositeWebResources webResources = new CompositeWebResources();
            DynamicScriptList     scriptList   = new DynamicScriptList(configuration.RootFolder, configuration.ServedFolderFilters, configuration.ExcludeServedFolderFilters, new FileSystem());

            webResources.Add(new WebServerResources(scriptList));
            webResources.Add(new FileSystemResources(configuration.RootFolder, scriptList, new FileSystem()));
            resourceResolver.Register <IWebResources>(webResources);
            resourceResolver.Register <IRunnerHub, RunnerHub>();
            resourceResolver.Register <IRunnerBroadcaster>((ioc, npo) => new RunnerBroadcaster(GlobalHost.ConnectionManager.GetHubContext <RunnerHub>().Clients));
            resourceResolver.Register <IServerStarter>(new OwinServerStarter(resourceResolver));
            resourceResolver.Register <IFileViewer, ExternalFileViewer>();
            resourceResolver.Register <IFileLocationParser>(new FileLocationParser(configuration.ServerUrl, webResources));
            resourceResolver.Register <IFileLocationMapper>(new JsMapFileMapper(new FileSystem()));
            resourceResolver.Register <IClipboard>(new ClipboardProxy());

            _FileWatcher = new FileWatcher(resourceResolver, configuration.WatchedFolderFilters.Select(ff =>
                                                                                                       new FolderWatcher(Path.GetFullPath(Path.Combine(configuration.RootFolder, ff.Folder)), ff.FilePattern, ff.IncludeSubfolders)));

            MainWindow mainWindow = new MainWindow()
            {
                DataContext = new MainViewModel(resourceResolver)
            };

            mainWindow.Show();
        }
        /// <summary>
        /// Reads properties for the window from the configuration. Properties include Size, Location, and WindowState.
        /// </summary>
        /// <param name="window">The window whose properties were previously persisted</param>
        /// <param name="configuration">The configuration to read from</param>
        public static void Read(Form window, XmlConfiguration configuration)
        {
            if (window != null)
            {
                if (configuration != null)
                {
                    string categoryName = @"Persisted Objects\Windows\" + window.GetType().FullName;
                    XmlConfigurationCategory category = null;

                    // load the category
                    if ((category = configuration.Categories[categoryName]) != null)
                    {
                        XmlConfigurationOption option = null;

                        // load the location
                        if ((option = category.Options["Location"]) != null)
                        {
                            window.Location = (Point)option.Value;
                        }

                        if ((option = category.Options["Size"]) != null)
                        {
                            window.Size = (Size)option.Value;
                        }

                        if ((option = category.Options["WindowState"]) != null)
                        {
                            window.WindowState = (FormWindowState)option.Value;
                        }
                    }
                }
            }
        }
示例#21
0
文件: Statsd.cs 项目: Elders/StatsD
 public Statsd(XmlConfiguration xml)
 {
     StatsDConfigurationSection cfg = (StatsDConfigurationSection)ConfigurationManager.GetSection("statsD");
     UdpChannel channel = new UdpChannel(cfg.Server.Host, cfg.Server.Port);
     this.prefix = cfg.Server.Prefix;
     hasPrefix = !String.IsNullOrEmpty(prefix);
     Current = this;
 }
示例#22
0
        public void CreateEngine()
        {
            var conf = new XmlConfiguration();

            conf.Properties[Environment.ValidatorMode] = "UseExternal";
            conf.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Tests", "NHibernate.Validator.Tests.Engine.Tagging.EntityXml.nhv.xml"));
            ve = new ValidatorEngine();
            ve.Configure(conf);
        }
示例#23
0
        /// <summary>
        /// Configure nhibernate validator
        /// </summary>
        private void ConfigureValidator()
        {
            INHVConfiguration nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode]         = ValidatorMode.UseExternal.ToString();
            nhvc.Mappings.Add(new MappingConfiguration("BFFLayer", null));
            _ve.Configure(nhvc);
        }
示例#24
0
        public static Type[] GetExtraTypes()
        {
            Type [] BaseTypes  = XmlConfiguration.GetXmlTypes();
            Type [] ExtraTypes = new Type[BaseTypes.Length + 1];

            BaseTypes.CopyTo(ExtraTypes, 0);
            ExtraTypes[BaseTypes.Length + 0] = typeof(TestConfiguration);

            return(ExtraTypes);
        }
        public void WhenExceptionWithResourceManager_ValidatorConfigurationException()
        {
            var ve   = new ValidatorEngine();
            var nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.CustomResourceManager] = "Whatever.Messages, Whatever";
            var exception = Assert.Throws <ValidatorConfigurationException>(() => ve.Configure(nhvc));

            Assert.That(exception.Message, Text.Contains("resource manager"));
        }
        /// <summary>
        /// Allows a client to retrieve all of the configurations to be displayed in a configuration properties window, or for other purposes. All SnapIns should listen for the for the EnumeratingConfigurations event, and add any configurations to the event as needed.
        /// </summary>
        /// <param name="configurations">An array of configurations that can be initially added so that the event listeners may filter them.</param>
        /// <returns></returns>
        public static XmlConfiguration[] EnumConfigurations(params XmlConfiguration[] configurations)
        {
            if (configurations == null)
                configurations = new XmlConfiguration[] { };

            XmlConfigurationManagerEventArgs e = new XmlConfigurationManagerEventArgs(configurations);
            OnEnumeratingConfigurations(null, e);

            return e.Configurations.ToArray();
        }
示例#27
0
        public frmMain()
        {
            InitializeComponent();

            downloader                     = new SpotifyDownloader();
            configuration                  = new XmlConfiguration("config.xml");
            downloader.OnLoginResult      += OnLoginResult;
            downloader.OnDownloadComplete += downloader_OnDownloadComplete;
            downloader.OnDownloadProgress += downloader_OnDownloadProgress;
        }
示例#28
0
        public frmMain()
        {
            InitializeComponent();

            downloader = new SpotifyDownloader();
            configuration = new XmlConfiguration("config.xml");
            downloader.OnLoginResult += OnLoginResult;
            downloader.OnDownloadComplete += downloader_OnDownloadComplete;
            downloader.OnDownloadProgress += downloader_OnDownloadProgress;
        }
示例#29
0
        /// <summary>
        /// Writes the data for the window we are listening to, to the appropriate category in the specified configuration
        /// </summary>
        private void WriteWindowData()
        {
            try
            {
                XmlConfigurationEventArgs e = new XmlConfigurationEventArgs(null, XmlConfigurationElementActions.None);
                this.OnNeedsConfiguration(this, e);
                if (e.Element == null)
                {
                    return;
                }

                // retrive the configuration where this listener will read and write
                XmlConfiguration configuration = e.Element;
                if (configuration != null)
                {
                    XmlConfigurationCategory category = configuration.Categories[_path, true];
                    if (category != null)
                    {
                        XmlConfigurationOption option = null;

                        if ((option = category.Options["Size"]) == null)
                        {
                            option                      = category.Options["Size", true, _size];
                            option.Description          = "The size of the window (Width & Height)";
                            option.Category             = "Layout";
                            option.ShouldSerializeValue = true;
                        }
                        option.Value = _size;

                        if ((option = category.Options["Location"]) == null)
                        {
                            option                      = category.Options["Location", true, _location];
                            option.Description          = "The location of the top left corner of the window (Left & Top)";
                            option.Category             = "Layout";
                            option.ShouldSerializeValue = true;
                        }
                        option.Value = _location;

                        if ((option = category.Options["WindowState"]) == null)
                        {
                            option             = category.Options["WindowState", true, _state];
                            option.Description = "The state of the window (Normal, Maximized, or Minimized)";
                            option.Category    = "Layout";
//							option.ShouldSerializeValue = true;
                        }
                        option.Value = _state;
                    }
                }
            }
            catch (System.Exception systemException)
            {
                System.Diagnostics.Trace.WriteLine(systemException);
            }
        }
        private List <Node> GetNodeList(string resource)
        {
            Workflow    workflow = XmlConfiguration.ParseflowXml <Workflow>(resource);
            List <Node> elements = new List <Node>();

            elements.Add(workflow.StartNode);
            elements.AddRange(workflow.ChildNode);
            elements.AddRange(workflow.ChildDecisionNode);
            elements.Add(workflow.EndNode);
            return(elements);
        }
		public int Add(XmlConfiguration configuration)
		{
			if (this.Contains(configuration))
				throw new ArgumentException("ElementName already exists. ElementName in collection: " + configuration.ElementName + " ElementName being added: " + configuration.ElementName);

			int index = base.InnerList.Add(configuration);
			
			/// bind to events 

			return 0;
		}
        public override ValidatorEngine GetValidatorEngine()
        {
            var ve  = new ValidatorEngine();
            var cfg = new XmlConfiguration();

            cfg.Properties[Environment.ValidatorMode] = "UseExternal";
            cfg.Properties[Environment.ConstraintValidatorFactoryClass] =
                typeof(TestConstraintValidatorFactory).AssemblyQualifiedName;
            ve.Configure(cfg);
            return(ve);
        }
示例#33
0
        /// <summary>
        /// Configure NHibernate.Validator using the specified <see cref="XmlReader"/>.
        /// </summary>
        /// <param name="configReader">The <see cref="XmlReader"/> that contains the Xml to configure NHibernate.Validator.</param>
        /// <remarks>
        /// Calling Configure(XmlReader) will overwrite the values set in app.config or web.config
        /// </remarks>
        public virtual void Configure(XmlReader configReader)
        {
            if (configReader == null)
            {
                throw new ValidatorConfigurationException("Could not configure NHibernate.Validator.",
                                                          new ArgumentNullException("configReader"));
            }

            INHVConfiguration nhvc = new XmlConfiguration(configReader);

            Configure(nhvc);
        }
示例#34
0
        /// <summary>
        /// Load XML and accounts, start League client.
        /// </summary>
        private void FrmWidget_Load(object sender, EventArgs e)
        {
            // Setup XML
            if (!System.IO.File.Exists("accounts.xml"))
            {
                var launchDir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                xml = XmlConfiguration.CreateConfiguration(launchDir + "/accounts.xml");
            }
            else
            {
                xml = new XmlConfiguration("accounts.xml");
            }

            // Load accounts
            LoadAccounts();

            // Load position data
            // Currently hard-coded positional data for the regular window size (1280x720) and the next 2 available options.
            positionData    = new PositionData[3];
            positionData[0] = new PositionData(1280, 720, 67, 284, 67, 348, 188, 495, 66, 56);
            positionData[1] = new PositionData(1024, 576, 53, 225, 53, 278, 150, 397, 53, 45);
            positionData[2] = new PositionData(1600, 900, 84, 355, 84, 435, 233, 621, 82, 70);

            // Focus on the label to avoid ugly selection
            this.ActiveControl = btnClose;

            // Read shortcutInfo and run the LeagueClient executable.
            string shortcutInfoFile = Application.StartupPath + "/shortcutInfo.txt";
            string leagueClientFile = string.Empty;

            try
            {
                leagueClientFile = System.IO.File.ReadAllText(shortcutInfoFile)
                                   .Replace("\n", string.Empty).Replace("\r", string.Empty);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while trying to read the shortcutInfo.txt file.\n" + ex.Message);
                Application.Exit();
            }

            try
            {
                Process.Start(leagueClientFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occured while trying to launch the LeagueClient executable.\n" + ex.Message);
            }

            // Start looking for process
            tmrCheckProcess.Start();
        }
示例#35
0
        public static ValidatorEngine Get_Engine_Configured_for_Xml()
        {
            var vtor = new ValidatorEngine();
            var nhvc = new XmlConfiguration();

            nhvc.Properties[Environment.ApplyToDDL]            = "false";
            nhvc.Properties[Environment.AutoregisterListeners] = "false";
            nhvc.Properties[Environment.ValidatorMode]         = "UseExternal";
            nhvc.Mappings.Add(new MappingConfiguration("NHibernate.Validator.Demo.Ev", null));
            vtor.Configure(nhvc);
            return(vtor);
        }
示例#36
0
        public virtual Type[] GetExtraTypes()
        {
            Type [] BaseTypes  = XmlConfiguration.GetXmlTypes();
            Type [] ExtraTypes = new Type[BaseTypes.Length + 3];

            BaseTypes.CopyTo(ExtraTypes, 0);
            ExtraTypes[BaseTypes.Length + 0] = typeof(ChartLegendDescription);
            ExtraTypes[BaseTypes.Length + 1] = typeof(ChartLegendItem);
            ExtraTypes[BaseTypes.Length + 2] = typeof(ChartDescription);

            return(ExtraTypes);
        }
		public void Add(XmlConfiguration[] configurations)
		{
			if (configurations != null)
			{
				//				throw new ArgumentNullException("configuration");

				foreach(XmlConfiguration configuration in configurations)
				{
					try
					{
						this.Add(configuration);
					}
					catch(Exception ex)
					{
						Debug.WriteLine(ex);
					}
				}
			}
		}
 internal ConfigurationWriter(XmlConfiguration xmlConfiguration, string filePath)
 {
     XmlConfiguration = xmlConfiguration;
     FilePath = filePath;
 }
		/// <summary>
		/// Writes an entire configuration file using the specified configuration and stream.
		/// </summary>
		/// <param name="configuration"></param>
		/// <param name="stream"></param>
		/// <param name="alwaysPersist"></param>
		public void Write(XmlConfiguration configuration, Stream stream, bool alwaysPersist)
		{
			try
			{
				/// create a new xml document
				XmlDocument doc = new XmlDocument();

				/// create the root element
				XmlElement root = doc.CreateElement(@"ConfigurationFile");
				
				/// append the root element as the first element
				doc.AppendChild(root);
								
				/// mark the xml as version 1.0 compliant
				XmlDeclaration versionDeclaration = doc.CreateXmlDeclaration(@"1.0", null, null);
				
				/// insert the version element as the first element
				doc.InsertBefore(versionDeclaration, root);
				
				this.WriteConfiguration(doc, root, configuration, alwaysPersist);
																
				/// save the xml document to the stream
				doc.Save(stream);
			}
			catch(Exception ex)
			{
				System.Diagnostics.Debug.Write(ex);
			}
		}
示例#40
0
 public FontConfiguration(XmlConfiguration configuration)
 {
     this._configuration = configuration;
 }
		/// <summary>
		/// Writes a configuration to the XmlDocument
		/// </summary>
		/// <param name="doc"></param>
		/// <param name="parent"></param>
		/// <param name="configuration"></param>
		/// <param name="alwaysPersist"></param>
		private void WriteConfiguration(XmlDocument doc, XmlElement parent, XmlConfiguration configuration, bool alwaysPersist)
		{
			try
			{
				if (configuration.Persistent || alwaysPersist)
				{
//					System.Diagnostics.Debug.WriteLine("Writing configuration '" + configuration.ElementName + "'");

					/// create an element for the category				
					XmlElement child = doc.CreateElement(@"Configuration");

					/// write the properties of this category
					child.SetAttribute(@"ElementName", configuration.ElementName);
					child.SetAttribute(@"HasChanges", XmlConvert.ToString(configuration.HasChanges));
					child.SetAttribute(@"Category", configuration.Category);
					child.SetAttribute(@"Description", configuration.Description);
					child.SetAttribute(@"DisplayName", configuration.DisplayName);
					child.SetAttribute(@"Hidden", XmlConvert.ToString(configuration.Hidden));
				
					/// append the child to our parent
					parent.AppendChild(child);

					this.WriteCategories(doc, child, configuration.Categories, alwaysPersist);
				}
			}
			catch(Exception ex)
			{
				Debug.WriteLine(ex);
			}
		}
        /// <summary>
        /// Reads or creates an XmlConfiguration from a name, path, and/or a handler function to provide structure to a new configuration.
        /// </summary>
        /// <param name="name">The name that will be given to the configuration</param>
        /// <param name="path">The path to the file where the configuration is stored</param>
        /// <param name="configuration">The configuration that will be returned after creation or reading has finished</param>
        /// <param name="encryptionEngine">The encryption engine to use when reading the file</param>
        /// <param name="handler">The event handler to call if structure is needed for a new configuration</param>
        /// <returns>True if a configuration was created or read</returns>
        public static bool ReadOrCreateConfiguration(
            bool verbose,
            string name,
            string path,
            out XmlConfiguration configuration,
            FileEncryptionEngine encryptionEngine,
            XmlConfigurationEventHandler handler)
        {
            configuration = null;

            Log.WriteLineIf(verbose, "Checking to see if the path '" + path + "' exists.");

            /// if the file exists, we need to try and read it
            if (System.IO.File.Exists(path))
            {
                Log.WriteLineIf(verbose, "The path '" + path + "' exists.");

                try
                {
                    /// but first see if we have permissions to read it
                    using (SecurityAccessRight right = new SecurityAccessRight(path))
                    {
                        Log.WriteLineIf(verbose, "Checking to see if the path '" + path + "' has read access.");

                        /// if we don't have rights to the file
                        if (!right.AssertReadAccess())
                        {
                            Log.WriteLineIf(verbose, "The path '" + path + "' does not have write access.");
                            Log.WriteLineIf(verbose, "Prompting for user intervention for the path '" + path + "'.");

                            /// prompt to see what we should do about this
                            DialogResult result = ExceptionUtilities.DisplayException(
                                null,
                                "Read access denied - Unable to read from file",
                                MessageBoxIcon.Error,
                                MessageBoxButtons.AbortRetryIgnore,
                                null,
                                "Read access has been denied for the '" + name + "'.",
                                "Ignoring this exception will result in a default set of options to be loaded in the '" + name + "' for this application instance.",
                                "If the file has write access enabled, it will be overwritten with the loaded options when the application exits.",
                                "WARNING: Aborting this operation will exit the application!");

                            switch (result)
                            {
                                case DialogResult.Abort:
                                    Log.WriteLineIf(verbose, "Aborting attempt to read from the path '" + path + "' because of user intervention.");
                                    return false;

                                case DialogResult.Retry:
                                    Log.WriteLineIf(verbose, "Retrying attempt to read from the path '" + path + "' because of user intervention.");
                                    return ReadOrCreateConfiguration(verbose, name, path, out configuration, encryptionEngine, handler);

                                case DialogResult.Ignore:
                                    Log.WriteLineIf(verbose, "Ignoring attempt to read from the path '" + path + "' because of user intervention.");
                                    return true;
                                //break;					
                            };
                        }
                        else
                        {
                            Log.WriteLineIf(verbose, "The path '" + path + "' has read access, preparing to read the configuration.");

                            /// rights to read the file
                            /// ask the configuration engine to read our configuration file for us into our configuration 
                            if (!ReadConfiguration(encryptionEngine, out configuration, path))
                            {
                                Log.WriteLineIf(verbose, "Failed to write the configuration, throwing exception from the last operation.");
                                throw _lastException;
                            }

                            /// let the configuration know where it lives							
                            //							configuration.Path = path;

                            /// ensure that the configuration has no changes visible
                            if (configuration != null)
                            {
                                Log.WriteLineIf(verbose, "Succeeded in reading the configuration, accepting changes .");
                                configuration.AcceptChanges();
                            }

                            return true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLineIf(verbose, "An unexpected exception was encountered while reading the configuration, dumping exception.");
                    Log.WriteLine(ex);
                    Log.WriteLineIf(verbose, "Prompting for user intervention for the path '" + path + "'.");

                    /// failed for some reason reading the file
                    /// prompt to see what we should do about this
                    DialogResult result = ExceptionUtilities.DisplayException(
                        null,
                        "Exception encountered - Unable to read from file",
                        MessageBoxIcon.Error,
                        MessageBoxButtons.AbortRetryIgnore,
                        ex,
                        "An exception was encountered while trying to read '" + name + "'.",
                        "Ignoring this exception will result in a default set of options to be loaded in the '" + name + "' for this application instance.",
                        "If the file has write access enabled, it will be overwritten with the loaded options when the application exits.",
                        "WARNING: Aborting this operation will exit the application!");

                    switch (result)
                    {
                        case DialogResult.Abort:
                            Log.WriteLineIf(verbose, "Aborting attempt to read from the path '" + path + "' because of user intervention.");
                            return false;

                        case DialogResult.Retry:
                            Log.WriteLineIf(verbose, "Retrying attempt to read from the path '" + path + "' because of user intervention.");
                            return ReadOrCreateConfiguration(verbose, name, path, out configuration, encryptionEngine, handler);

                        case DialogResult.Ignore:
                            Log.WriteLineIf(verbose, "Ignoring attempt to read from the path '" + path + "' because of user intervention.");
                            break;
                    };
                }
            }
            else
            {
                Log.WriteLineIf(verbose, "The path '" + path + "' does not exist.");
            }

            /// if for some reason the configuration hasn't been loaded yet
            if (configuration == null)
            {
                Log.WriteLineIf(verbose, "Creating new configuration named '" + name + "'.");
                configuration = new XmlConfiguration();
                configuration.ElementName = name;

                Log.WriteLineIf(verbose, "Checking for formatting callback for the configuration named '" + name + "'.");

                if (handler != null)
                {
                    Log.WriteLineIf(verbose, "Formatting callback found for the configuration named '" + name + "', calling formatting callback to apply structure to the configuration.");
                    try
                    {
                        XmlConfigurationEventArgs e = new XmlConfigurationEventArgs(configuration, XmlConfigurationElementActions.None);
                        handler(null, e);
                        configuration = e.Element;
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLineIf(verbose, "An unexpected exception was encountered while reading the configuration named '" + name + "', dumping exception.");
                        Log.WriteLine(ex);
                    }
                }
            }

            Log.WriteLineIf(verbose, "Setting the path for the configuration named '" + name + "' and accepting changes to the configuration.");

            /// let the configuration know where it lives
            configuration.Path = path;

            /// ensure that the configuration has no changes visible
            configuration.AcceptChanges();

            return true;
        }     
        /// <summary>
        /// Reads a configuration using the specified encryption engine from the specified path
        /// </summary>
        /// <param name="encryptionEngine">The encryption engine to use while reading the configuration, null if no decryption is desired</param>
        /// <param name="configuration">The configuration to be read into</param>
        /// <param name="path">The path to be read from</param>
        /// <returns></returns>
        public static bool ReadConfiguration(FileEncryptionEngine encryptionEngine, out XmlConfiguration configuration, string path)
        {
            Stream stream = null;
            _lastException = null;

            try
            {
                configuration = new XmlConfiguration();
                stream = (encryptionEngine != null ? encryptionEngine.CreateDecryptorStream(path) : new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None));
                XmlConfigurationReader reader = new XmlConfigurationReader();
                configuration = reader.Read(stream);
                configuration.Path = path;
                configuration.SetHasUnpersistedChanges(false);

                return true;
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex);
                _lastException = ex;
            }
            finally
            {
                if (stream != null) 
                    stream.Close();
            }
            configuration = null;
            return false;
        }
        protected override void Configure(Configuration configuration)
        {
            // The ValidatorInitializer and the ValidateEventListener share the same engine

            // Initialize the SharedEngine
            fortest = new NHibernateSharedEngineProvider();
            Cfg.Environment.SharedEngineProvider = fortest;
            ValidatorEngine ve = Cfg.Environment.SharedEngineProvider.GetEngine();
            ve.Clear();
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Cfg.Environment.ApplyToDDL] = "true";
            nhvc.Properties[Cfg.Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Cfg.Environment.ValidatorMode] = "UseAttribute";
            nhvc.Properties[Cfg.Environment.MessageInterpolatorClass] = typeof(PrefixMessageInterpolator).AssemblyQualifiedName;
            ve.Configure(nhvc);
            ve.IsValid(new AnyClass());// add the element to engine for test

            ValidatorInitializer.Initialize(configuration);
        }
 public void SetUp()
 {
     _log = new GraphLog();
     builder = new XmlConfiguration();
     DataMother.BackupStructureMapConfig();
 }
		/// <summary>
		/// Reads a configuration using the specified XPathNavigator
		/// </summary>
		/// <param name="navigator"></param>
		/// <returns></returns>
		private XmlConfiguration ReadConfiguration(XPathNavigator navigator, XmlConfiguration configuration)
		{
			if (navigator.MoveToFirstChild())
			{
				if (string.Compare(navigator.Name, @"Configuration", true) == 0)
				{
					// does the cateogry have attributes, it should!
					if (navigator.HasAttributes)
					{
						// break off yet another clone to navigate the attributes of this element
						XPathNavigator attributesNavigator = navigator.Clone();
						if (attributesNavigator.MoveToFirstAttribute())
						{
							configuration.ElementName = attributesNavigator.Value;

							while(attributesNavigator.MoveToNextAttribute())
							{
								switch(attributesNavigator.Name)
								{
								case @"HasChanges":
									configuration.HasChanges = XmlConvert.ToBoolean(attributesNavigator.Value);
									break;
								case @"Category":
									configuration.Category = attributesNavigator.Value;
									break;
								case @"Description":
									configuration.Description = attributesNavigator.Value;
									break;
								case @"DisplayName":
									configuration.DisplayName = attributesNavigator.Value;
									break;
								case @"Hidden":
									configuration.Hidden = XmlConvert.ToBoolean(attributesNavigator.Value);
									break;
								};						
							}
						}
					}
				}
			}

			// recursively read the categories within this configuration file
			this.ReadCategories(navigator, configuration.Categories);

			return configuration;
		}
		/// <summary>
		/// Gets an XmlConfiguration using a elementName, optionally creates a new or loads an existing configuration (.xml) file using the path specified, and optionally adds it to the collection if new 
		/// </summary>
		/// <param name="elementName">The elementName by which this collection will be accessed</param>
		/// <param name="createIfNotFound">A flag indicating whether the configuration should be created if it does not exist</param>
		/// <param name="path">The path to the configuration</param>		
		public XmlConfiguration this[string elementName, bool createIfNotFound, bool addToCollectionIfNew, string path]
		{
			get
			{
				/// try and find the configuration in the collection
				XmlConfiguration configuration = this[elementName];
				
				/// if it's not in the collection
				if (configuration == null)
				{
					/// perhaps it does in the filesystem, if so then read it, and optionally add it to the collection
					if (File.Exists(path))
					{
						try
						{
							FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
							XmlConfigurationReader reader = new XmlConfigurationReader();
							configuration = reader.Read(stream);
							configuration.Path = path;								
							stream.Close();

							if (addToCollectionIfNew)
								this.Add(configuration);

							return configuration;
						} 
						catch (Exception ex)
						{
							Debug.WriteLine(ex);
						}
					}

					/// apparently it doesnt' exist in the filesystem
					if (createIfNotFound)
					{
						/// so create a new file
						configuration = new XmlConfiguration();						
						configuration.Path = path;	
						configuration.ElementName = elementName;

						/// save the blank config
						Directory.CreateDirectory(path);
						FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
						XmlConfigurationWriter writer = new XmlConfigurationWriter();
						writer.Write(configuration, stream, false);
						stream.Close();						

						/// add it to the config if so instructed
						if (addToCollectionIfNew)
							this.Add(configuration);
					}
				}
				return configuration;
			}
		}		
        /// <summary>
        /// Writes a configuration using the specified encryption engine to the specified path
        /// </summary>
        /// <param name="encryptionEngine">The encryption engine to use while writing the configuration, null if no encryption is desired</param>
        /// <param name="configuration">The confiruration to write</param>
        /// <param name="path">The path to write it to</param>
        /// <returns></returns>
        public static bool WriteConfiguration(FileEncryptionEngine encryptionEngine, XmlConfiguration configuration, string path)
        {
            Stream stream = null;
            _lastException = null;

            try
            {
                if (configuration != null)
                {
                    if (configuration.HasUnpersistedChanges())
                    {
                        configuration.AcceptChanges();
                        stream = (encryptionEngine != null ? encryptionEngine.CreateEncryptorStream(path) : new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None));
                        XmlConfigurationWriter writer = new XmlConfigurationWriter();
                        writer.Write(configuration, stream, false);
                        configuration.SetHasUnpersistedChanges(false);
                    }
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex);
                _lastException = ex;
            }
            finally
            {
                if (stream != null) 
                    stream.Close();
            }
            return false;
        }
		public void Remove(XmlConfiguration configuration)
		{
			if (this.Contains(configuration))
			{
				base.InnerList.Remove(configuration);
			}
		}
		public bool Contains(XmlConfiguration configuration)
		{
			foreach(XmlConfiguration config in base.InnerList)
				if (config.ElementName == configuration.ElementName)
					return true;
			return false;
		}
		/// <summary>
		/// Reads an XmlConfiguration from a System.IO.Stream
		/// </summary>
		/// <param name="stream">The stream that contains the XmlConfiguration file</param>
		/// <returns></returns>
		public XmlConfiguration Read(Stream stream)
		{
			try
			{
				// create a new xml document
				XmlDocument doc = new XmlDocument();
				
				// load it from the stream
				doc.Load(stream);

				// create a new xpath navigator so that we can traverse the elements inside the xml
				XPathNavigator navigator = doc.CreateNavigator();
				
				// move to the version element
				navigator.MoveToFirstChild(); 

				// move to the file format description element
				navigator.MoveToNext();						

				// create a new configuration
				XmlConfiguration configuration = new XmlConfiguration();
				
				// begin initialization so that events do not fire inside the configuration
				configuration.BeginInit();

				// using the xpath navigator, read the xml document and turn it into a configuration
				this.ReadConfiguration(navigator, configuration);
				
				// end initialization
				configuration.EndInit();

				return configuration;
			}
			catch(Exception ex)
			{
				Debug.WriteLine(ex);
			}		
			return null;
		}
		/// <summary>
		/// Reads an XmlConfiguration from a System.IO.Stream
		/// </summary>
		/// <param name="stream">The stream that contains the XmlConfiguration file</param>
		/// <param name="configuration">The configuration to load into</param>
		/// <returns></returns>
		public XmlConfiguration Read(Stream stream, XmlConfiguration configuration)
		{
			try
			{
				/// create a new xml document
				XmlDocument doc = new XmlDocument();

				/// load it from the stream
				doc.Load(stream);

				/// create a new xpath navigator so that we can traverse the elements inside the xml
				XPathNavigator navigator = doc.CreateNavigator();
				
				/// move to the version element
				navigator.MoveToFirstChild(); 

				/// move to the file format description element
				navigator.MoveToNext();	
					
				this.ReadConfiguration(navigator, configuration);

				return configuration;
			}
			catch(Exception ex)
			{
				Debug.WriteLine(ex);
			}		
			return null;
		}
		public void RemoveConfiguration(XmlConfiguration configuration, bool keepLocationIfPossible)
		{
			_xmlConfigurationView.RemoveConfiguration(configuration, keepLocationIfPossible);
		}
示例#54
0
        /// <summary>
        /// <see cref="DirectoryStructure"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="configuration">設定を取得する <see cref="XmlConfiguration"/> オブジェクト。</param>
        public DirectoryStructure(XmlConfiguration configuration)
        {
            this.BaseDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            Environment.SetEnvironmentVariable(
                "BaseDir",
                this.BaseDirectory.FullName,
                EnvironmentVariableTarget.Process
            );
            Environment.SetEnvironmentVariable(
                "DataDir",
                new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData))
                    .CreateSubdirectory("MetaTweet")
                    .FullName,
                EnvironmentVariableTarget.Process
            );
            this.BinaryDirectory = this.GetDirectory(configuration.ResolveValue<String>("binary"));
            this.PrivilegedBinaryDirectory = this.GetDirectory(configuration.ResolveValue<String>("privbinary"));
            this.CacheDirectory = this.GetDirectory(configuration.ResolveValue<String>("cache"));
            this.ConfigDirectory =this.GetDirectory(configuration.ResolveValue<String>("config"));
            this.LibraryDirectory = this.GetDirectory(configuration.ResolveValue<String>("library"));
            this.LogDirectory = this.GetDirectory(configuration.ResolveValue<String>("log"));
            this.ModuleDirectory = this.GetDirectory(configuration.ResolveValue<String>("module"));
            this.RuntimeDirectory = this.GetDirectory(configuration.ResolveValue<String>("runtime"));
            this.TempDirectory = this.GetDirectory(configuration.ResolveValue<String>("temp"));

            this.BaseDirectoryWatcher = new FileSystemWatcher(this.BaseDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.BinaryDirectoryWatcher = new FileSystemWatcher(this.BinaryDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.PrivilegedBinaryDirectoryWatcher = new FileSystemWatcher(this.PrivilegedBinaryDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.CacheDirectoryWatcher = new FileSystemWatcher(this.CacheDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.ConfigDirectoryWatcher = new FileSystemWatcher(this.ConfigDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.LibraryDirectoryWatcher = new FileSystemWatcher(this.LibraryDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.LogDirectoryWatcher = new FileSystemWatcher(this.LogDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.ModuleDirectoryWatcher = new FileSystemWatcher(this.ModuleDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.RuntimeDirectoryWatcher = new FileSystemWatcher(this.RuntimeDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
            this.TempDirectoryWatcher = new FileSystemWatcher(this.TempDirectory.FullName)
            {
                EnableRaisingEvents = true,
                IncludeSubdirectories = true,
            };
        }
		public void AddConfiguration(XmlConfiguration configuration)
		{
			_xmlConfigurationView.AddConfiguration(configuration);
		}
示例#56
0
 public ServerConnector(XmlConfiguration.Entry<ServerConnectorConfiguration> configuration)
     : this()
 {
     this.Configuration = configuration;
     // TODO: Load configurations for Views
 }
        /// <summary>
        /// Writes a configuration to a path using the specified encryption engine. Takes windows security into account and checks for write access before trying to write to the path.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="configuration"></param>
        /// <param name="encryptionEngine"></param>
        /// <returns></returns>
        public static bool WriteConfiguration(bool verbose, string path, XmlConfiguration configuration, FileEncryptionEngine encryptionEngine)
        {
            try
            {
                Log.WriteLineIf(verbose, "Checking to see if the path '" + path + "' exists.");

                /// if the file exists, we need to try and read it
                if (System.IO.File.Exists(path))
                {
                    Log.WriteLineIf(verbose, "The path '" + path + "' exists.");

                    /// but first see if we have permissions to read it
                    using (SecurityAccessRight right = new SecurityAccessRight(path))
                    {
                        Log.WriteLineIf(verbose, "Checking to see if the path '" + path + "' has write access.");

                        /// if we don't have rights to the file						
                        if (!right.AssertWriteAccess())
                        {
                            Log.WriteLineIf(verbose, "The path '" + path + "' does not have write access.");
                            Log.WriteLineIf(verbose, "Prompting for user intervention for the path '" + path + "'.");

                            if (verbose)
                            {
                                /// prompt to see what we should do about this
                                DialogResult result = ExceptionUtilities.DisplayException(
                                    null,
                                    "Write access denied - Unable to write to file",
                                    MessageBoxIcon.Error,
                                    MessageBoxButtons.AbortRetryIgnore,
                                    null,
                                    "Write access has been denied for the file '" + path + "'.",
                                    "Ignoring this exception may result in a loss of data if any options in this file were changed.");

                                switch (result)
                                {
                                    case DialogResult.Abort:
                                        Log.WriteLineIf(verbose, "Aborting attempt to write to the path '" + path + "' because of user intervention.");
                                        return false;

                                    case DialogResult.Retry:
                                        Log.WriteLineIf(verbose, "Retrying attempt to write to the path '" + path + "' because of user intervention.");
                                        return WriteConfiguration(verbose, path, configuration, encryptionEngine);

                                    case DialogResult.Ignore:
                                        Log.WriteLineIf(verbose, "Ignoring attempt to write to the path '" + path + "' because of user intervention.");
                                        return true;
                                    //break;					
                                };
                            }
                            else
                            {
                                /// it failed, but we're not in verbose mode so who cares?
                                return true;
                            }
                        }
                        else
                        {
                            Log.WriteLineIf(verbose, "The path '" + path + "' has write access, preparing to write the configuration.");

                            /// rights to write to the file
                            /// ask the configuration engine to write our configuration file for us into our configuration 
                            if (!WriteConfiguration(encryptionEngine, configuration, path))
                            {
                                Log.WriteLineIf(verbose, "Failed to write the configuration, throwing exception from the last operation.");
                                throw _lastException;
                            }

                            /// ensure that the configuration has no changes visible
                            if (configuration != null)
                            {
                                Log.WriteLineIf(verbose, "Succeeded in writing the configuration, accepting changes .");
                                configuration.AcceptChanges();
                            }

                            return true;
                        }
                    }
                }
                else
                {
                    Log.WriteLineIf(verbose, "The path '" + path + "' does not exist, preparing to write the configuration for the first time.");

                    /// ask the configuration engine to write our configuration file for us into our configuration 
                    if (!WriteConfiguration(encryptionEngine, configuration, path))
                    {
                        Log.WriteLineIf(verbose, "Failed to write the configuration, throwing exception from the last operation.");
                        throw _lastException;
                    }

                    /// ensure that the configuration has no changes visible
                    if (configuration != null)
                    {
                        Log.WriteLineIf(verbose, "Succeeded in writing the configuration, accepting changes .");
                        configuration.AcceptChanges();
                    }

                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.WriteLineIf(verbose, "An unexpected exception was encountered while writing the configuration, dumping exception.");
                Log.WriteLine(ex);
                Log.WriteLineIf(verbose, "Prompting for user intervention for the path '" + path + "'.");

                if (verbose)
                {
                    /// failed for some reason writing the file
                    /// prompt to see what we should do about this
                    DialogResult result = ExceptionUtilities.DisplayException(
                        null,
                        "Exception encountered - Unable to write to file",
                        MessageBoxIcon.Error,
                        MessageBoxButtons.AbortRetryIgnore,
                        ex,
                        "An exception was encountered while trying to write to the file '" + path + "'.",
                        "Ignoring this exception may result in a loss of data if any options in this file were changed");

                    switch (result)
                    {
                        case DialogResult.Abort:
                            Log.WriteLineIf(verbose, "Aborting attempt to write to the path '" + path + "' because of user intervention.");
                            return false;

                        case DialogResult.Retry:
                            Log.WriteLineIf(verbose, "Retrying attempt to write to the path '" + path + "' because of user intervention.");
                            return WriteConfiguration(verbose, path, configuration, encryptionEngine);

                        case DialogResult.Ignore:
                            Log.WriteLineIf(verbose, "Ignoring attempt to write to the path '" + path + "' because of user intervention.");
                            return true;
                    };
                }
            }
            return true;
        }
示例#58
0
 public ServerConnector(XmlConfiguration parent, String name)
     : this()
 {
     this.Configuration = new XmlConfiguration.Entry<ServerConnectorConfiguration>(parent);
     this.Name = name;
 }
		public XmlConfigurationEventArgs(XmlConfiguration configuration, XmlConfigurationElementActions action) : base(configuration, action)
		{
				
		}
示例#60
0
 public void Configure(XmlConfiguration configuration)
 {
     this.Configuration = configuration;
     this.ConfigureHook.Execute(configuration);
 }