Add() публичный Метод

public Add ( ConnectionStringSettings settings ) : void
settings ConnectionStringSettings
Результат void
Пример #1
0
        /// <summary>
        /// Tony.2014.09.11
        /// 获取到连接字符串,如果配置了XCode.ConnConfigFile项则优先使用,否则使用ConnectionStrings节
        /// </summary>
        /// <returns></returns>
        private static ConnectionStringSettingsCollection GetConnectionStrings()
        {
            String connFile = Config.GetConfig<String>("XCode.ConnConfigFile");
            if (String.IsNullOrWhiteSpace(connFile))
            {
                return ConfigurationManager.ConnectionStrings;
            }
            else
            {
                ConnectionStringSettingsCollection cnsc = new ConnectionStringSettingsCollection();
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(connFile);

                    foreach (XmlNode conn in xmlDoc.SelectNodes("/connectionStrings/add"))
                    {
                        ConnectionStringSettings css = new ConnectionStringSettings();
                        css.Name = conn.Attributes["name"] == null ? String.Empty : conn.Attributes["name"].Value;
                        css.ConnectionString = conn.Attributes["connectionString"] == null ? String.Empty : conn.Attributes["connectionString"].Value;
                        css.ProviderName = conn.Attributes["providerName"] == null ? String.Empty : conn.Attributes["providerName"].Value;

                        cnsc.Add(css);
                    }
                }
                catch (Exception ex)
                {
                    XTrace.WriteLine("无法从XCode.ConnConfigFile配置节中获取到ConnectionStrings,异常详情:{0}", ex.ToString());
                }

                return cnsc;
            }
        }
Пример #2
0
 public void LoadConfigurations()
 {
     appSettings = new NameValueCollection();
     connSettings = new ConnectionStringSettingsCollection();
     var areaDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Modules"));
     if(areaDir.Exists)
     {
         foreach(var dir in areaDir.GetDirectories())
         {
             var file = dir.GetFiles("web.config").FirstOrDefault();
             if(file != null)
             {
                 var config = WebConfigurationManager.OpenWebConfiguration(string.Format("/Modules/{0}/web.config", dir.Name));
                 var settings = config.AppSettings.Settings;
                 foreach(var key in settings.AllKeys)
                 {
                     appSettings.Add(string.Format("{0}.{1}", dir.Name, key), settings[key] == null ? "" :  settings[key].ToString());
                 }
                 var conns = config.ConnectionStrings.ConnectionStrings;
                 foreach(ConnectionStringSettings conn in conns)
                 {
                     ConnectionStringSettings c = new ConnectionStringSettings(conn.Name, conn.ConnectionString, conn.ProviderName);
                     connSettings.Add(c);
                 }
             }
         }
     }
 }
Пример #3
0
        /// <summary>
        /// 添加连接字符串
        /// </summary>
        /// <param name="connStrings"><see cref="ConnectionStringSettingsCollection"/> 实例</param>
        internal static void AddConnectionStrings(ConnectionStringSettingsCollection connStrings)
        {
            if (connStrings == null || connStrings.Count == 0)
                return;

            var newCollection = new ConnectionStringSettingsCollection();

            foreach (ConnectionStringSettings connStr in connStrings)
            {
                newCollection.Add(connStr);
            }

            foreach (ConnectionStringSettings connStr in instance.collection)
            {
                if (newCollection[connStr.Name] == null)
                    newCollection.Add(new ConnectionStringSettings(connStr.Name, connStr.ConnectionString, connStr.ProviderName));
            }

            instance.collection = newCollection;
        }
        public override ConnectionStringSettingsCollection GetConnectionStrings(string[] names)
        {
            Cat.LogEvent("LoadDataSource.Source", "service");
            logger.Info("Load data source from service.");
            ConnectionStringSettingsCollection coll = new ConnectionStringSettingsCollection();

            try
            {
                var json = DynamicJson.Parse(SendRequest(names));
                Cat.LogEvent("LoadDataSource.StatusCode", json.status);
                logger.Info("Response data status code is " + json.status);

                if (json.status != "200")
                    throw new Exception("The status code returned from data source service is " + json.status);

                foreach (var item in json.data)
                {
                    if (item.IsDefined("errorCode") && Convert.ToString(item.errorCode) != "200")
                    {
                        var name = Convert.ToString(item.name);
                        var errorCode = Convert.ToString(item.errorCode);
                        var message = Convert.ToString(item.errorMessage);

                        Cat.LogEvent("LoadDataSource.Entry", name, errorCode, message);
                        Cat.LogEvent("LoadDataSource.Entry.StatusCode", errorCode);
                        logger.Error("Data source - " + name, string.Format("ErrorCode:{0}, Message:{1}", errorCode, message));
                    }
                    else
                    {
                        var name = Convert.ToString(item.name);

                        coll.Add(new ConnectionStringSettings(name, Decrypt(name, Convert.ToString(item.connectionString)), Convert.ToString(item.providerName)));
                        Cat.LogEvent("LoadDataSource.Entry", name);
                        Cat.LogEvent("LoadDataSource.Entry.StatusCode", "200");
                        logger.Info("Data source - " + name, "ok");
                    }
                }

                succeed = true;
                return coll;
            }
            catch (Exception ex)
            {
                if (!ConfigHelper.UseLocalOnServiceNotAvailable || succeed)
                    throw;

                var msg = "Error occured during loading data from service, attempts to read local file.";
                Cat.LogError(msg, ex);
                logger.Error(msg, ex);
            }

            coll = DataSourceProvider.GetProvider(DataSourceType.Local).GetConnectionStrings(names);
            return coll;
        }
        public void TestInitialize()
        {
            Mock.SetupStatic(typeof(HttpContext));
            Mock.SetupStatic(typeof(ConfigurationManager));

            var connectionStrings = new ConnectionStringSettingsCollection();
            connectionStrings.Add(new ConnectionStringSettings(CONNECTION_STRING_NAME, CONNECTION_STRING));

            Mock.Arrange(() => ConfigurationManager.ConnectionStrings)
                .Returns(connectionStrings)
                .MustBeCalled();
        }
Пример #6
0
        public override ConnectionStringSettingsCollection GetConnectionStrings(string[] names)
        {
            if (succeed)
                return new ConnectionStringSettingsCollection();

            Cat.LogEvent("LoadDataSource.Source", "local");
            logger.Info("Load data source from local.");
            var coll = new ConnectionStringSettingsCollection();
            var nameList = new List<string>(names).ConvertAll(n => n.ToLower());

            var settings = new XmlReaderSettings();
            settings.ConformanceLevel = ConformanceLevel.Fragment;
            settings.IgnoreWhitespace = true;
            settings.IgnoreComments = true;
            settings.IgnoreProcessingInstructions = true;
            using (var reader = XmlReader.Create(filePath, settings))
            {
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "add")
                    {
                        string name = reader.GetAttribute("name");
                        if (name != null)
                        {
                            int index = nameList.IndexOf(name.ToLower());
                            if (index > -1)
                            {
                                var connStr = FetchConnectionString(name, reader);
                                connStr.ConnectionString = decryptor.DecryptConnectionString(connStr.Name, connStr.ConnectionString);
                                coll.Add(connStr);

                                Cat.LogEvent("LoadDataSource.Entry", name);
                                logger.Info("Data source - " + name, "ok");

                                nameList.RemoveAt(index);
                                if (nameList.Count == 0)
                                    break;
                            }
                        }
                    }
                }
            }

            succeed = true;
            return coll;
        }
 public static void ClassInitialize(TestContext context)
 {
     ServiceLocator.Initialize();
     manager1 = Isolate.Fake.Instance<IConfigurationManager>();
     NameValueCollection appSettings1 = new NameValueCollection();
     appSettings1.Add("Test1", "Value1");
     manager1.AppSettings = appSettings1;
     ServiceLocator.RegisterInstance<IConfigurationManager>("manager1", manager1);
     manager2 = Isolate.Fake.Instance<IConfigurationManager>();
     NameValueCollection appSettings2 = new NameValueCollection();
     appSettings2.Add("Test2", "Value2");
     manager2.AppSettings = appSettings2;
     ConnectionStringSettingsCollection connectionStrings2 = new ConnectionStringSettingsCollection();
     connectionStrings2.Add(new ConnectionStringSettings("ConnectionString", "ConnectionStringTest"));
     manager2.ConnectionStrings = connectionStrings2;
     ServiceLocator.RegisterInstance<IConfigurationManager>("manager2", manager2);
 }
        protected override ConfigurationSection Arrange_GetLocalSourceSection()
        {
            ConnectionStringSettingsCollection localConnectionStrings = new ConnectionStringSettingsCollection();
            localConnectionStrings.Add(new ConnectionStringSettings("name1", "overwrite"));
            localConnectionStrings.Add(new ConnectionStringSettings("name3", "connstr3"));
            localConnectionStrings.EmitClear = true;

            return new DummySectionWithCollections
            {
                ConnectionStringSettingsCollection = localConnectionStrings
            };
        }
        protected override ConfigurationSection Arrange_GetParentSourceSection()
        {
            ConnectionStringSettingsCollection parentConnectionStrings = new ConnectionStringSettingsCollection();
            parentConnectionStrings.Add(new ConnectionStringSettings("name1", "connstr1"));
            parentConnectionStrings.Add(new ConnectionStringSettings("name2", "connstr2"));

            return new DummySectionWithCollections
            {
                ConnectionStringSettingsCollection = parentConnectionStrings
            };
        }
Пример #10
0
 private ConnectionStringSettingsCollection GetConnectionStrings()
 {
     var result = new ConnectionStringSettingsCollection();
     var section = GetSection("connectionStrings") as ConnectionStringsSection;
     if (section != null)
     {
         foreach (ConnectionStringSettings settings in section.ConnectionStrings)
             result.Add(settings);
     }
     return result;
 }
Пример #11
0
        /// <summary>
        /// Gets all the values stored in the connectionStrings.
        /// This will provide a single collection containing the defaults or 
        /// overrides as appropriate.
        /// </summary>
        /// <returns>The collection of all connection strings.</returns>
        public ConnectionStringSettingsCollection GetConnectionStrings()
        {
            ConnectionStringSettingsCollection allConnections =
                new ConnectionStringSettingsCollection();

            // Put in all the default values
            foreach (ConnectionStringSettings connSetting in
                ConfigurationManager.ConnectionStrings)
            {
                allConnections.Add(connSetting);
            }

            if (m_overridenConfig.HasFile)
            {
                foreach (ConnectionStringSettings connSetting in
                    m_overridenConfig.ConnectionStrings.ConnectionStrings)
                {
                    // Remove the default if already present
                    if (allConnections[connSetting.Name] != null)
                    {
                        allConnections.Remove(connSetting.Name);
                    }
                    allConnections.Add(connSetting);
                }
            }

            return allConnections;
        }
        public void GetConnectionStringForNonExistingConnectionStringThrowsArgumentException()
        {
            var connectionStrings = new ConnectionStringSettingsCollection();
            connectionStrings.Add(new ConnectionStringSettings("AnotherConnectionString", CONNECTION_STRING));

            Mock.Arrange(() => ConfigurationManager.ConnectionStrings)
                .Returns(connectionStrings)
                .MustBeCalled();

            MethodInfo method = typeof(CurrentUserDataProvider)
                .GetMethod("GetConnectionString", BindingFlags.Static | BindingFlags.NonPublic);

            try
            {
                method.Invoke(null, new object[] {});
            }
            catch (TargetInvocationException ex)
            {
                Assert.IsTrue(ex.GetBaseException().GetType() == typeof(ArgumentException));
            }

            Mock.Assert(() => ConfigurationManager.ConnectionStrings);
        }
Пример #13
0
        public static Configure DefineSagaPersister(this Configure config, string persister)
        {
            if (string.IsNullOrEmpty(persister))
                return config.InMemorySagaPersister();

            var type = Type.GetType(persister);

            if (type == typeof(InMemorySagaPersister))
                return config.InMemorySagaPersister();

            if (type == typeof(RavenSagaPersister))
            {
                config.RavenPersistence(() => "url=http://localhost:8080");
                return config.RavenSagaPersister();

            }

            if (type == typeof(SagaPersister))
            {
                NHibernateSettingRetriever.ConnectionStrings = () =>
                {
                    var c = new ConnectionStringSettingsCollection();

                    c.Add(new ConnectionStringSettings("NServiceBus/Persistence", NHibernateConnectionString));
                    return c;

                };
                return config.UseNHibernateSagaPersister();
            }

            throw new InvalidOperationException("Unknown persister:" + persister);
        }
Пример #14
0
        static void Main(string[] args)
        {
            var numberOfThreads = int.Parse(args[0]);
            bool volatileMode = (args[4].ToLower() == "volatile");
            bool suppressDTC = (args[4].ToLower() == "suppressdtc");
            bool twoPhaseCommit = (args[4].ToLower() == "twophasecommit");
            bool saga = (args[5].ToLower() == "sagamessages");
            bool nhibernate = (args[6].ToLower() == "nhibernate");
            int concurrency = int.Parse(args[7]);

            TransportConfigOverride.MaximumConcurrencyLevel = numberOfThreads;

            var numberOfMessages = int.Parse(args[1]);

            var endpointName = "PerformanceTest";

            if (volatileMode)
                endpointName += ".Volatile";

            if (suppressDTC)
                endpointName += ".SuppressDTC";

            var config = Configure.With()
                                  .DefineEndpointName(endpointName)
                                  .DefaultBuilder();

            switch (args[2].ToLower())
            {
                case "xml":
                    Configure.Serialization.Xml();
                    break;

                case "json":
                    Configure.Serialization.Json();
                    break;

                case "bson":
                    Configure.Serialization.Bson();
                    break;

                case "bin":
                    Configure.Serialization.Binary();
                    break;

                default:
                    throw new InvalidOperationException("Illegal serialization format " + args[2]);
            }

            Configure.Features.Disable<Audit>();

            //Configure.Instance.UnicastBus().IsolationLevel(IsolationLevel.Snapshot);
            //Console.Out.WriteLine("Snapshot");

            if (saga)
            {
                Configure.Features.Enable<Sagas>();

                if (nhibernate)
                {
                    NHibernateSettingRetriever.ConnectionStrings = () =>
                    {
                        var c = new ConnectionStringSettingsCollection();

                        c.Add(new ConnectionStringSettings("NServiceBus/Persistence", SqlServerConnectionString));
                        return c;

                    };
                    config.UseNHibernateSagaPersister();

                }
                else
                {
                    config.RavenSagaPersister();
                }
            }

            if (volatileMode)
            {
                Configure.Endpoint.AsVolatile();
            }

            if (suppressDTC)
            {
                Configure.Transactions.Advanced(settings => settings.DisableDistributedTransactions());
            }

            switch (args[3].ToLower())
            {
                case "msmq":
                    config.UseTransport<Msmq>();
                    break;

                //todo: dynamically load the transports or autodetect like we do in the acceptance tests
                //case "sqlserver":
                //    config.UseTransport<SqlServer>( () => SqlServerConnectionString);
                //    break;

                //case "activemq":
                //    config.UseTransport<ActiveMQ>(() => "ServerUrl=activemq:tcp://localhost:61616?nms.prefetchPolicy.all=100");
                //    break;
                //case "rabbitmq":
                //    config.UseTransport<RabbitMQ>(() => "host=localhost");
                //    break;

                default:
                    throw new InvalidOperationException("Illegal transport " + args[2]);
            }

            using (var startableBus = config.InMemoryFaultManagement().UnicastBus().CreateBus())
            {
                Configure.Instance.ForInstallationOn<NServiceBus.Installation.Environments.Windows>().Install();

                if (saga)
                {
                    SeedSagaMessages(numberOfMessages, endpointName, concurrency);
                }
                else
                {
                    Statistics.SendTimeNoTx = SeedInputQueue(numberOfMessages / 2, endpointName, numberOfThreads, false, twoPhaseCommit, saga, true);
                    Statistics.SendTimeWithTx = SeedInputQueue(numberOfMessages / 2, endpointName, numberOfThreads, true, twoPhaseCommit, saga, true);
                }

                Statistics.StartTime = DateTime.Now;

                startableBus.Start();

                while (Interlocked.Read(ref Statistics.NumberOfMessages) < numberOfMessages)
                    Thread.Sleep(1000);

                DumpSetting(args);
                Statistics.Dump();

            }
        }
Пример #15
0
        public object GetSection(string configKey)
        {
            if (configKey == "appSettings")
            {
                if (_appSettings != null)
                    return _appSettings;
            }
            else if (configKey == "connectionStrings")
            {
                if (_connectionStrings != null)
                    return _connectionStrings;
            }


            // get the section from the default location (web.config or app.config)
            object section = _clientConfigSystem.GetSection(configKey);
            

            switch (configKey)
            {
                case "appSettings":
                    if (section is NameValueCollection)
                    {
                        // create a new collection because the underlying collection is read-only
                        var cfg = new NameValueCollection((NameValueCollection)section);
                        _appSettings = cfg;
                        
                        // merge the settings from core with the local appsettings
                        _appSettings = cfg.Merge(System.Configuration.ConfigurationManager.AppSettings);
                        section = _appSettings;
                    }
                    break;

                case "connectionStrings":
                    // Cannot simply return our ConnectionStringSettingsCollection as the calling routine expects a ConnectionStringsSection result
                    ConnectionStringsSection connectionStringsSection = new ConnectionStringsSection();
                    _connectionStrings = connectionStringsSection;

                    // create a new collection because the underlying collection is read-only
                    var cssc = new ConnectionStringSettingsCollection();

                    // copy the existing connection strings into the new collection
                    foreach (ConnectionStringSettings connectionStringSetting in ((ConnectionStringsSection)section).ConnectionStrings)
                    {
                        cssc.Add(connectionStringSetting);
                    }

                    //// merge the settings from core with the local connectionStrings
                    cssc = cssc.Merge(System.Configuration.ConfigurationManager.ConnectionStrings);
                    
                    // Add our merged connection strings to the new ConnectionStringsSection
                    foreach (ConnectionStringSettings connectionStringSetting in cssc)
                    {
                        connectionStringsSection.ConnectionStrings.Add(connectionStringSetting);
                    }

                    _connectionStrings = connectionStringsSection;
                    section = _connectionStrings;
                    break;
            }

            return section;
        }
Пример #16
0
        static MyConfigurationSettings()
        {
            ConfigurationServiceClient configurationServiceClient = null;
            //ServiceHost configurationServiceClient = null;
            Dictionary<string, string> settings = null;

            String endPointHost = ConfigurationManager.AppSettings["endPointHost"];

            //String baseAddress = ConfigurationManager.AppSettings["endPointServer"];
            //configurationServiceClient.Endpoint.Address

            //var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //var serviceModel = configFile.SectionGroups["system.serviceModel"];
            //var clientSection = serviceModel.Sections["client"];

            //var serviceModelClient = ConfigurationManager.GetSection("system.serviceModel/client");

            //ClientSection serviceModelClient = ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;
            //foreach (ChannelEndpointElement cs in serviceModelClient.Endpoints)
            //{
            //    var address = cs.Address;
            //}

            //String serviceName = "BasicHttpBinding_IConfigurationService";

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ServiceModelSectionGroup serviceModelSection = ServiceModelSectionGroup.GetSectionGroup(config);
            ClientSection serviceModelClientSection = serviceModelSection.Client;
            if (serviceModelClientSection.Endpoints[0].Address.Host != endPointHost)
            {
                foreach (ChannelEndpointElement endPoint in serviceModelClientSection.Endpoints)
                {
                    var uri = new Uri(endPoint.Address.Scheme + "://" + endPointHost + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);
                    endPoint.Address = uri;
                    //endPoint.Address = new Uri(endPoint.Address.Scheme + "://" + endPointAddress + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);
                }
                //serviceModelClientSection.Endpoints.Cast<ChannelEndpointElement>()
                    //                                         .Select(endpoint => { endpoint.Address.Host = endPointHost; return endpoint; });

                //ChannelEndpointElement endPoint = serviceModelClientSection.Endpoints[0];
                //var uri = new Uri(endPoint.Address.Scheme + "://" + endPointHost + ":" + endPoint.Address.Port + endPoint.Address.PathAndQuery);

                //serviceModelClientSection.Endpoints[0].Address = uri;
                config.Save();

                ConfigurationManager.RefreshSection(serviceModelClientSection.SectionInformation.SectionName);
            }

            configurationServiceClient = new ConfigurationServiceClient();

            //configurationServiceClient = new ConfigurationServiceClient(serviceName, endPointAddress);
            //configurationServiceClient = new ServiceHost(typeof(ConfigurationServiceClient), new Uri(baseAddress));

            appSettingsCollection = new NameValueCollection();

            settings = configurationServiceClient.AppSettings();
            foreach (var key in settings.Keys)
            {
                appSettingsCollection.Add(key, settings[key]);
            }

            settings.Clear();

            connectionStringCollection = new ConnectionStringSettingsCollection();

            settings = configurationServiceClient.ConnectionStrings();
            foreach (var key in settings.Keys)
            {
                connectionStringCollection.Add(new ConnectionStringSettings(key, settings[key]));
            }
        }