/// <summary> /// Serializes the specified <see cref="IDbProvider"/> into an <see cred="IConfiguration" /> node.对数据库驱动类的序列化处理 /// </summary> public static IConfiguration Serialize(IDbProvider dbProvider) { IConfiguration providerConfig = new MutableConfiguration("provider", dbProvider.Id, dbProvider.Id); providerConfig.Attributes[DataConstants.ATTRIBUTE_NAME] = dbProvider.Id; providerConfig.Attributes[DataConstants.ATTRIBUTE_ASSEMBLYNAME] = dbProvider.AssemblyName; providerConfig.Attributes[DataConstants.ATTRIBUTE_COMMANDBUILDERCLASS] = dbProvider.CommandBuilderClass; providerConfig.Attributes[DataConstants.ATTRIBUTE_COMMANDCLASS] = dbProvider.DbCommandClass; providerConfig.Attributes[DataConstants.ATTRIBUTE_CONNECTIONCLASS] = dbProvider.DbConnectionClass; providerConfig.Attributes[DataConstants.ATTRIBUTE_DESCRIPTION] = dbProvider.Description; providerConfig.Attributes[DataConstants.ATTRIBUTE_DEFAULT] = dbProvider.IsDefault.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_ENABLED] = dbProvider.IsEnabled.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERDBTYPECLASS] = dbProvider.ParameterDbTypeClass; providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERDBTYPEPROPERTY] = dbProvider.ParameterDbTypeProperty; providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERPREFIX] = dbProvider.ParameterPrefix; providerConfig.Attributes[DataConstants.ATTRIBUTE_PARAMETERPREFIX] = dbProvider.ParameterPrefix; providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERPRECISION] = dbProvider.SetDbParameterPrecision.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERSCALE] = dbProvider.SetDbParameterScale.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_SETDBPARAMETERSIZE] = dbProvider.SetDbParameterSize.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_USEDERIVEPARAMETERS] = dbProvider.UseDeriveParameters.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPARAMETERPREFIXINPARAMETER] = dbProvider.UseParameterPrefixInParameter.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPARAMETERPREFIXINSQL] = dbProvider.UseParameterPrefixInSql.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_USEPOSITIONALPARAMETERS] = dbProvider.UsePositionalParameters.ToString().ToLower(); providerConfig.Attributes[DataConstants.ATTRIBUTE_ALLOWMARS] = dbProvider.AllowMARS.ToString().ToLower(); return(providerConfig); }
/// <summary> /// Applies the configuration node. /// </summary> /// <param name = "configuration">The configuration.</param> public override void ApplyTo(IConfiguration configuration) { var node = new MutableConfiguration(Name); node.Children.Add(configNode); configuration.Children.Add(node); }
public void OneToOneWorks() { var config = new MutableConfiguration(ConnectionString); config.Add <OneToOneLeft>(); config.Add <OneToOneRight>(); var migrator = MakeMigrator(config); IEnumerable <string> errors; IEnumerable <string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock <ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [OneToOneLefts] ([OneToOneLeftId] int not null identity(1,1) primary key, [RightId] int null, [Name] nvarchar(255) null); create table [OneToOneRights] ([OneToOneRightId] int not null identity(1,1) primary key, [LeftId] int null, [Name] nvarchar(255) null); alter table [OneToOneLefts] add constraint fk_OneToOneLeft_OneToOneRight_Right foreign key ([RightId]) references [OneToOneRights]([OneToOneRightId]); alter table [OneToOneRights] add constraint fk_OneToOneRight_OneToOneLeft_Left foreign key ([LeftId]) references [OneToOneLefts]([OneToOneLeftId]); create index [idx_OneToOneLeft_Right] on [OneToOneLefts] ([RightId]); create index [idx_OneToOneRight_Left] on [OneToOneRights] ([LeftId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void PairWorks() { var config = new MutableConfiguration(ConnectionString); config.Add <Pair>(); var migrator = MakeMigrator(config); IEnumerable <string> errors; IEnumerable <string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock <ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Pairs] ([PairId] int not null identity(1,1) primary key, [ReferencesId] int null, [ReferencedById] int null); alter table [Pairs] add constraint fk_Pair_Pair_References foreign key ([ReferencesId]) references [Pairs]([PairId]); alter table [Pairs] add constraint fk_Pair_Pair_ReferencedBy foreign key ([ReferencedById]) references [Pairs]([PairId]); create index [idx_Pair_References] on [Pairs] ([ReferencesId]); create index [idx_Pair_ReferencedBy] on [Pairs] ([ReferencedById]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void ConstructorWithListParameterAndCustomType() { var confignode = new MutableConfiguration("key"); IConfiguration parameters = new MutableConfiguration("parameters"); confignode.Children.Add(parameters); IConfiguration services = new MutableConfiguration("services"); parameters.Children.Add(services); var list = new MutableConfiguration("list"); services.Children.Add(list); list.Attributes.Add("type", "ICommon"); list.Children.Add(new MutableConfiguration("item", "${commonservice1}")); list.Children.Add(new MutableConfiguration("item", "${commonservice2}")); Kernel.ConfigurationStore.AddComponentConfiguration("key", confignode); Kernel.Register(Component.For(typeof(ClassWithListConstructor)).Named("key")); Kernel.Register(Component.For(typeof(ICommon)).ImplementedBy(typeof(CommonImpl1)).Named("commonservice1")); Kernel.Register(Component.For(typeof(ICommon)).ImplementedBy(typeof(CommonImpl2)).Named("commonservice2")); var instance = Kernel.Resolve <ClassWithListConstructor>("key"); Assert.IsNotNull(instance.Services); Assert.AreEqual(2, instance.Services.Count); Assert.AreEqual("CommonImpl1", instance.Services[0].GetType().Name); Assert.AreEqual("CommonImpl2", instance.Services[1].GetType().Name); }
public void AddFactory <TService, TFactory>(string serviceKey, string factoryCreateMethodName, string factoryId) { var cfg = new MutableConfiguration(serviceKey); cfg.Attributes["factoryCreate"] = factoryCreateMethodName; AddFactoryComponent <TService, TFactory>(cfg, factoryId, serviceKey); }
public void ConstructorWithArrayParameter() { var confignode = new MutableConfiguration("key"); IConfiguration parameters = new MutableConfiguration("parameters"); confignode.Children.Add(parameters); IConfiguration hosts = new MutableConfiguration("hosts"); parameters.Children.Add(hosts); IConfiguration array = new MutableConfiguration("array"); hosts.Children.Add(array); array.Children.Add(new MutableConfiguration("item", "castle")); array.Children.Add(new MutableConfiguration("item", "uol")); array.Children.Add(new MutableConfiguration("item", "folha")); Kernel.ConfigurationStore.AddComponentConfiguration("key", confignode); Kernel.Register(Component.For(typeof(ClassWithConstructors)).Named("key")); var instance = Kernel.Resolve <ClassWithConstructors>("key"); Assert.IsNotNull(instance); Assert.IsNull(instance.Host); Assert.AreEqual("castle", instance.Hosts[0]); Assert.AreEqual("uol", instance.Hosts[1]); Assert.AreEqual("folha", instance.Hosts[2]); }
public void ConstructorWithArrayParameterAndCustomType() { var confignode = new MutableConfiguration("key"); IConfiguration parameters = new MutableConfiguration("parameters"); confignode.Children.Add(parameters); IConfiguration services = new MutableConfiguration("services"); parameters.Children.Add(services); var array = new MutableConfiguration("array"); services.Children.Add(array); array.Children.Add(new MutableConfiguration("item", "${commonservice1}")); array.Children.Add(new MutableConfiguration("item", "${commonservice2}")); Kernel.ConfigurationStore.AddComponentConfiguration("key", confignode); Kernel.Register(Component.For <ClassWithArrayConstructor>().Named("key"), Component.For <ICommon>().ImplementedBy <CommonImpl1>().Named("commonservice1"), Component.For <ICommon>().ImplementedBy <CommonImpl2>().Named("commonservice2")); var instance = Kernel.Resolve <ClassWithArrayConstructor>("key"); Assert.IsNotNull(instance.Services); Assert.AreEqual(2, instance.Services.Length); Assert.AreEqual("CommonImpl1", instance.Services[0].GetType().Name); Assert.AreEqual("CommonImpl2", instance.Services[1].GetType().Name); }
public IConfiguration ToIConfiguration() { var config = new MutableConfiguration("rhino.esb"); var busConfig = config.CreateChild("bus") .Attribute("endpoint", Endpoint) .Attribute("threadCount", ThreadCount.ToString()) .Attribute("numberOfRetries", NumberOfRetries.ToString()); if (string.IsNullOrEmpty(Name) == false) { busConfig.Attribute("name", Name); } if (string.IsNullOrEmpty(LoadBalancerEndpoint) == false) { busConfig.Attribute("loadBalancerEndpoint", LoadBalancerEndpoint); } if (string.IsNullOrEmpty(LogEndpoint) == false) { busConfig.Attribute("logEndpoint", LogEndpoint); } var messagesConfig = config.CreateChild("messages"); foreach (var message in Messages) { messagesConfig.CreateChild("add") .Attribute("name", message.Key) .Attribute("endpoint", message.Value); } return(config); }
public void DictionaryWithDifferentValueTypes() { var config = new MutableConfiguration("dictionary"); config.CreateChild("entry") .Attribute("key", "intentry") .Attribute("valueType", "System.Int32, mscorlib") .Value = "123"; config.CreateChild("entry") .Attribute("key", "values") .Attribute("valueType", "System.Int32[], mscorlib") .CreateChild("array") .Attribute("type", "System.Int32, mscorlib") .CreateChild("item", "400"); var dict = (IDictionary)converter.PerformConversion(config, typeof(IDictionary)); Assert.IsNotNull(dict); Assert.AreEqual(123, dict["intentry"]); var values = (int[])dict["values"]; Assert.IsNotNull(values); Assert.AreEqual(1, values.Length); Assert.AreEqual(400, values[0]); }
public void ParametersAndServicesBestCase() { var store = new DefaultConfigurationStore(); var config = new MutableConfiguration("component"); var parameters = new MutableConfiguration("parameters"); config.Children.Add(parameters); parameters.Children.Add(new MutableConfiguration("name", "hammett")); parameters.Children.Add(new MutableConfiguration("port", "120")); store.AddComponentConfiguration("service", config); Kernel.ConfigurationStore = store; Container.Register(Component.For <A>().Named("a"), Component.For <ServiceUser2>().Named("service")); var service = Container.Resolve <ServiceUser2>("service"); Assert.IsNotNull(service); Assert.IsNotNull(service.AComponent); Assert.IsNull(service.BComponent); Assert.IsNull(service.CComponent); Assert.AreEqual("hammett", service.Name); Assert.AreEqual(120, service.Port); }
public void LifestyleSetThroughExternalConfig() { IConfiguration confignode = new MutableConfiguration("component"); confignode.Attributes.Add("lifestyle", "transient"); Kernel.ConfigurationStore.AddComponentConfiguration("a", confignode); Kernel.Register(Component.For(typeof(TrivialComponent)).Named("a")); var handler = Kernel.GetHandler("a"); Assert.AreEqual(LifestyleType.Transient, handler.ComponentModel.LifestyleType); confignode = new MutableConfiguration("component"); confignode.Attributes.Add("lifestyle", "singleton"); Kernel.ConfigurationStore.AddComponentConfiguration("b", confignode); Kernel.Register(Component.For(typeof(TrivialComponent)).Named("b")); handler = Kernel.GetHandler("b"); Assert.AreEqual(LifestyleType.Singleton, handler.ComponentModel.LifestyleType); confignode = new MutableConfiguration("component"); confignode.Attributes.Add("lifestyle", "thread"); Kernel.ConfigurationStore.AddComponentConfiguration("c", confignode); Kernel.Register(Component.For(typeof(TrivialComponent)).Named("c")); handler = Kernel.GetHandler("c"); Assert.AreEqual(LifestyleType.Thread, handler.ComponentModel.LifestyleType); #if !(SILVERLIGHT || CLIENTPROFILE) confignode = new MutableConfiguration("component"); confignode.Attributes.Add("lifestyle", "perWebRequest"); Kernel.ConfigurationStore.AddComponentConfiguration("d", confignode); Kernel.Register(Component.For(typeof(TrivialComponent)).Named("d")); handler = Kernel.GetHandler("d"); Assert.AreEqual(LifestyleType.PerWebRequest, handler.ComponentModel.LifestyleType); #endif }
public void DropPropertyWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Simple2.Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, null, new Mock<ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace(Regex.Replace(@"declare @OBDCommandca45edee90bb4cc68430f8540d28aa99 nvarchar(1000); select @OBDCommandca45edee90bb4cc68430f8540d28aa99 = 'ALTER TABLE [PostComments] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'PostComments' and c.name = 'Rating'; execute(@OBDCommandca45edee90bb4cc68430f8540d28aa99); alter table [PostComments] drop column [Rating];", @"@\w+\b", "@Foo"), @"(?<!\r)\n", Environment.NewLine), Regex.Replace(script.Trim(), @"@\w+\b", "@Foo")); }
public void OperationsLocked() { IConfigurationStore configurationStore = new DefaultConfigurationStore(); MutableConfiguration facNode = new MutableConfiguration("facility"); facNode.Attributes["id"] = "slow"; facNode.Attributes["type"] = "Castle.Windsor.Tests.Facilities.SlowlyInitFacility, Castle.Windsor.Tests"; configurationStore.AddFacilityConfiguration("slow", facNode); MutableConfiguration compNode = new MutableConfiguration("component"); compNode.Attributes["id"] = "a"; compNode.Attributes["type"] = "Castle.Windsor.Tests.Components.CalculatorService, Castle.Windsor.Tests"; configurationStore.AddComponentConfiguration("a", compNode); AsyncInitializationContainer container = new AsyncInitializationContainer(configurationStore); Assert.AreEqual(1, container.Kernel.GraphNodes.Length); Assert.AreEqual(1, container.Kernel.GraphNodes.Length); CalculatorService service = (CalculatorService) container[typeof(CalculatorService)]; Assert.IsNotNull(service); service = (CalculatorService) container[typeof(CalculatorService)]; }
public void AddComponent_ListConfigurationParameters_WorksFine() { var list = new MutableConfiguration("list"); list.Attributes.Add("type", typeof(ICommon).AssemblyQualifiedName); list.Children.Add(new MutableConfiguration("item", "${common1}")); list.Children.Add(new MutableConfiguration("item", "${common2}")); Kernel.Register( Component.For <ICommon>() .Named("common1") .ImplementedBy <CommonImpl1>(), Component.For <ICommon>() .Named("common2") .ImplementedBy <CommonImpl2>(), Component.For <ClassWithListConstructor>() .DependsOn( Parameter.ForKey("services").Eq(list) ) ); var common1 = Kernel.Resolve <ICommon>("common1"); var common2 = Kernel.Resolve <ICommon>("common2"); var component = Kernel.Resolve <ClassWithListConstructor>(); Assert.AreEqual(2, component.Services.Count); Assert.AreSame(common1, component.Services[0]); Assert.AreSame(common2, component.Services[1]); }
public void ComplexDomainBuilds() { var config = new MutableConfiguration(ConnectionString); config.AddNamespaceOf <Post>(); var migrator = MakeMigrator(config); IEnumerable <string> errors; IEnumerable <string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock <ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Blogs] ([BlogId] int not null identity(1,1) primary key, [Title] nvarchar(255) null, [CreateDate] datetime not null default (current_timestamp), [Description] nvarchar(255) null); create table [Categories] ([CategoryId] int not null identity(1,1) primary key, [ParentId] int null, [Name] nvarchar(255) null); create table [Comments] ([CommentId] int not null identity(1,1) primary key, [Content] nvarchar(255) null, [PostId] int null, [UserId] int null, [CommentDate] datetime not null default (current_timestamp)); create table [Likes] ([LikeId] int not null identity(1,1) primary key, [UserId] int null, [CommentId] int null); create table [OneToOneLefts] ([OneToOneLeftId] int not null identity(1,1) primary key, [RightId] int null, [Name] nvarchar(255) null); create table [OneToOneRights] ([OneToOneRightId] int not null identity(1,1) primary key, [LeftId] int null, [Name] nvarchar(255) null); create table [Pairs] ([PairId] int not null identity(1,1) primary key, [ReferencesId] int null, [ReferencedById] int null); create table [Posts] ([PostId] int not null identity(1,1) primary key, [Title] nvarchar(255) null, [Content] nvarchar(255) null, [Rating] decimal(18,10) not null default (0), [AuthorId] int null, [BlogId] int null, [DoNotMap] bit not null default (0)); create table [PostTags] ([PostTagId] int not null identity(1,1) primary key, [PostId] int null, [TagId] int null); create table [SimpleClasses] ([SimpleClassId] int not null identity(1,1) primary key, [Name] nvarchar(255) null, [CreatedDate] datetime not null default (current_timestamp)); create table [Tags] ([TagId] int not null identity(1,1) primary key, [Content] nvarchar(255) null); create table [Users] ([UserId] int not null identity(1,1) primary key, [Username] nvarchar(255) null, [EmailAddress] nvarchar(255) null, [Password] nvarchar(255) null, [IsEnabled] bit not null default (0), [HeightInMeters] decimal(18,10) not null default (0)); alter table [Categories] add constraint fk_Category_Category_Parent foreign key ([ParentId]) references [Categories]([CategoryId]); alter table [Comments] add constraint fk_Comment_Post_Post foreign key ([PostId]) references [Posts]([PostId]); alter table [Comments] add constraint fk_Comment_User_User foreign key ([UserId]) references [Users]([UserId]); alter table [Likes] add constraint fk_Like_User_User foreign key ([UserId]) references [Users]([UserId]); alter table [Likes] add constraint fk_Like_Comment_Comment foreign key ([CommentId]) references [Comments]([CommentId]); alter table [OneToOneLefts] add constraint fk_OneToOneLeft_OneToOneRight_Right foreign key ([RightId]) references [OneToOneRights]([OneToOneRightId]); alter table [OneToOneRights] add constraint fk_OneToOneRight_OneToOneLeft_Left foreign key ([LeftId]) references [OneToOneLefts]([OneToOneLeftId]); alter table [Pairs] add constraint fk_Pair_Pair_References foreign key ([ReferencesId]) references [Pairs]([PairId]); alter table [Pairs] add constraint fk_Pair_Pair_ReferencedBy foreign key ([ReferencedById]) references [Pairs]([PairId]); alter table [Posts] add constraint fk_Post_User_Author foreign key ([AuthorId]) references [Users]([UserId]); alter table [Posts] add constraint fk_Post_Blog_Blog foreign key ([BlogId]) references [Blogs]([BlogId]); alter table [PostTags] add constraint fk_PostTag_Post_Post foreign key ([PostId]) references [Posts]([PostId]); alter table [PostTags] add constraint fk_PostTag_Tag_Tag foreign key ([TagId]) references [Tags]([TagId]); create index [idx_Category_Parent] on [Categories] ([ParentId]); create index [idx_Comment_Post] on [Comments] ([PostId]); create index [idx_Comment_User] on [Comments] ([UserId]); create index [idx_Like_User] on [Likes] ([UserId]); create index [idx_Like_Comment] on [Likes] ([CommentId]); create index [idx_OneToOneLeft_Right] on [OneToOneLefts] ([RightId]); create index [idx_OneToOneRight_Left] on [OneToOneRights] ([LeftId]); create index [idx_Pair_References] on [Pairs] ([ReferencesId]); create index [idx_Pair_ReferencedBy] on [Pairs] ([ReferencedById]); create index [idx_Post_Author] on [Posts] ([AuthorId]); create index [idx_Post_Blog] on [Posts] ([BlogId]); create index [idx_PostTag_Post] on [PostTags] ([PostId]); create index [idx_PostTag_Tag] on [PostTags] ([TagId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void ComplexConfigurationParameter() { var key = "key"; var value1 = "value1"; var value2 = "value2"; var confignode = new MutableConfiguration(key); IConfiguration parameters = new MutableConfiguration("parameters"); confignode.Children.Add(parameters); IConfiguration complexParam = new MutableConfiguration("complexparam"); parameters.Children.Add(complexParam); IConfiguration complexNode = new MutableConfiguration("complexparametertype"); complexParam.Children.Add(complexNode); complexNode.Children.Add(new MutableConfiguration("mandatoryvalue", value1)); complexNode.Children.Add(new MutableConfiguration("optionalvalue", value2)); Kernel.ConfigurationStore.AddComponentConfiguration(key, confignode); Kernel.Register(Component.For(typeof(ClassWithComplexParameter)).Named(key)); var instance = Kernel.Resolve <ClassWithComplexParameter>(key); Assert.IsNotNull(instance); Assert.IsNotNull(instance.ComplexParam); Assert.AreEqual(value1, instance.ComplexParam.MandatoryValue); Assert.AreEqual(value2, instance.ComplexParam.OptionalValue); }
public void SimpleCase() { String contents = "import Castle.Facilities.AspectSharp.Tests.Components in Castle.Facilities.AspectSharp.Tests " + "import Castle.Facilities.AspectSharp.Tests.Interceptors in Castle.Facilities.AspectSharp.Tests " + " " + " aspect MyAspect for SimpleService " + " " + " pointcut method|property(*)" + " advice(LoggerInterceptor)" + " end" + " " + " end "; MutableConfiguration config = new MutableConfiguration("facility", contents); DefaultConfigurationStore store = new DefaultConfigurationStore(); store.AddFacilityConfiguration("aop", config); WindsorContainer container = new WindsorContainer(store); container.AddFacility("aop", new AspectSharpFacility()); container.AddComponent("comp1", typeof(SimpleService)); SimpleService service = container[typeof(SimpleService)] as SimpleService; service.DoSomething(); service.DoSomethingElse(); Assert.AreEqual("Enter DoSomething\r\nEnter DoSomethingElse\r\n", LoggerInterceptor.Messages.ToString()); }
public void RenameWithDifferentPrimaryKeyWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Entry>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny<string>(), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Entry", DisplayString = "Entry" }); // change the pk name to.GetMap<Entry>().PrimaryKey.Name = "EntryId"; to.GetMap<Entry>().PrimaryKey.DbName = "EntryId"; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"EXEC sp_RENAME [Posts], [Entries]; EXEC sp_RENAME 'Entries.Id', 'EntryId', 'COLUMN'; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([EntryId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void DisposableJobIsDisposed() { using (var c = new WindsorContainer()) { c.Register(Component.For <DisposableJob>().LifeStyle.Transient); var config = new MutableConfiguration("facility"); config.CreateChild("quartz"); c.Kernel.ConfigurationStore.AddFacilityConfiguration("quartz", config); c.AddFacility("quartz", new QuartzFacility()); var scheduler = c.Resolve <IScheduler>(); var jobDetail = JobBuilder.Create <DisposableJob>().WithIdentity("somejob").Build(); var trigger = TriggerBuilder.Create().WithIdentity("sometrigger").WithSimpleSchedule(s => s.WithIntervalInSeconds(1)).Build(); var task = scheduler.ScheduleJob(jobDetail, trigger); task.Wait(); var dateTimeOffset = task.Result; Assert.IsFalse(DisposableJob.Disposed); scheduler.Start(); Thread.Sleep(1000); Assert.IsTrue(DisposableJob.Disposed); } }
public void ParametersAndServicesBestCase2() { DefaultConfigurationStore store = new DefaultConfigurationStore(); MutableConfiguration config = new MutableConfiguration("component"); MutableConfiguration parameters = (MutableConfiguration) config.Children.Add(new MutableConfiguration("parameters")); parameters.Children.Add(new MutableConfiguration("name", "hammett")); parameters.Children.Add(new MutableConfiguration("port", "120")); parameters.Children.Add(new MutableConfiguration("Scheduleinterval", "22")); store.AddComponentConfiguration("service", config); kernel.ConfigurationStore = store; kernel.AddComponent("a", typeof(A)); kernel.AddComponent("service", typeof(ServiceUser2)); ServiceUser2 service = (ServiceUser2)kernel["service"]; Assert.IsNotNull(service); Assert.IsNotNull(service.AComponent); Assert.IsNull(service.BComponent); Assert.IsNull(service.CComponent); Assert.AreEqual("hammett", service.Name); Assert.AreEqual(120, service.Port); Assert.AreEqual(22, service.ScheduleInterval); }
public void RenameAndChangeWorks() { var from = new MutableConfiguration().AddNamespaceOf <Post>(); var to = new MutableConfiguration().AddNamespaceOf <Port>(); var migrater = MakeMigrator(from); IEnumerable <string> warnings; IEnumerable <string> errors; var answerProvider = new Mock <IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny <string>(), It.IsAny <IEnumerable <MultipleChoice <string> > >())) .Returns(new MultipleChoice <string> { Choice = "Port", DisplayString = "Port" }); var script = migrater.GenerateSqlDiff( from.Maps, to.Maps, answerProvider.Object, new String[0], new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"EXEC sp_RENAME [Posts], [Ports]; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; drop index [idx_PostComment_Post] on [PostComments]; EXEC sp_RENAME 'PostComments.PostId', 'PortId', 'COLUMN'; alter table [Ports] add [Foo] nvarchar(255) null; alter table [PostComments] add constraint fk_PostComment_Port_Port foreign key ([PortId]) references [Ports]([Id]); create index [idx_PostComment_Port] on [PostComments] ([PortId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void TriggerListeners() { using (var c = new WindsorContainer()) { var config = new MutableConfiguration("facility"); config.CreateChild("quartz").CreateChild("item", "qwe").Attribute("key", "qq"); var listenerConfig = config.CreateChild("triggerListeners"); listenerConfig .CreateChild("job") .Attribute("name", "someJob") .CreateChild("listener", "${trigli}"); c.Kernel.ConfigurationStore.AddFacilityConfiguration("quartz", config); c.Register(Component.For <ITriggerListener>().ImplementedBy <SomeTriggerListener>().Named("trigli")); c.AddFacility("quartz", new QuartzFacility()); var scheduler = (QuartzNetScheduler)c.Resolve <IScheduler>(); foreach (var l in scheduler.ListenerManager.GetTriggerListeners()) { Console.WriteLine(l); } var trigli = scheduler.ListenerManager.GetTriggerListener(typeof(SomeTriggerListener).AssemblyQualifiedName); Assert.IsNotNull(trigli); } }
public void DontRenameWorksAndNoWarningWithNoCurrentData() { var from = new MutableConfiguration().AddNamespaceOf <Post>(); var to = new MutableConfiguration().AddNamespaceOf <Entry>(); var migrator = MakeMigrator(from); IEnumerable <string> warnings; IEnumerable <string> errors; var answerProvider = new Mock <IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny <string>(), It.IsAny <IEnumerable <MultipleChoice <string> > >())) .Returns(new MultipleChoice <string> { Choice = "__NOTRENAMED", DisplayString = "Foo" }); var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; drop table [Posts]; create table [Entries] ([Id] int not null identity(1,1) primary key, [Content] nvarchar(255) null); alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([Id]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void RenameWithIdPrimaryKeyWorks() { var from = new MutableConfiguration().AddNamespaceOf <Post>(); var to = new MutableConfiguration().AddNamespaceOf <Entry>(); var migrator = MakeMigrator(from); IEnumerable <string> warnings; IEnumerable <string> errors; var answerProvider = new Mock <IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny <string>(), It.IsAny <IEnumerable <MultipleChoice <string> > >())) .Returns(new MultipleChoice <string> { Choice = "Entry", DisplayString = "Entry" }); var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"EXEC sp_RENAME [Posts], [Entries]; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([Id]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void GenericDictionary() { var config = new MutableConfiguration("dictionary"); config.Attributes["keyType"] = "System.String"; config.Attributes["valueType"] = "System.Int32"; var firstItem = new MutableConfiguration("item", "1"); firstItem.Attributes["key"] = "key1"; config.Children.Add(firstItem); var secondItem = new MutableConfiguration("item", "2"); secondItem.Attributes["key"] = "key2"; config.Children.Add(secondItem); var thirdItem = new MutableConfiguration("item", "3"); thirdItem.Attributes["key"] = "key3"; config.Children.Add(thirdItem); Assert.IsTrue(converter.CanHandleType(typeof(IDictionary <string, string>))); Assert.IsTrue(converter.CanHandleType(typeof(Dictionary <string, int>))); var dict = (IDictionary <string, int>)converter.PerformConversion(config, typeof(IDictionary <string, int>)); Assert.IsNotNull(dict); Assert.AreEqual(1, dict["key1"]); Assert.AreEqual(2, dict["key2"]); Assert.AreEqual(3, dict["key3"]); }
public void AddNewNotNullRelationshipToTableWithData() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf <Simple2.Post>(); var to = new MutableConfiguration(ConnectionString); to.AddNamespaceOf <Simple3.Post>(); to.Setup <Simple3.Post>().Property(p => p.Blog).IsNullable = false; var migrator = MakeMigrator(from, true); var answerProvider = new Mock <IAnswerProvider>(); answerProvider.Setup(a => a.GetAnswer <int>(It.IsAny <string>())).Returns(99); IEnumerable <string> warnings; IEnumerable <string> errors; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock <ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Blogs] ([Id] int not null identity(1,1) primary key, [Title] nvarchar(255) null); alter table [Posts] add [BlogId] int not null default (99); alter table [Posts] add constraint fk_Post_Blog_Blog foreign key ([BlogId]) references [Blogs]([Id]); create index [idx_Post_Blog] on [Posts] ([BlogId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public static IConfiguration GetDeserializedNode(XmlNode node) { var configChilds = new ConfigurationCollection(); var configValue = new StringBuilder(); if (node.HasChildNodes) { foreach (XmlNode child in node.ChildNodes) { if (IsTextNode(child)) { configValue.Append(child.Value); } else if (child.NodeType == XmlNodeType.Element) { configChilds.Add(GetDeserializedNode(child)); } } } var config = new MutableConfiguration(node.Name, GetConfigValue(configValue.ToString())); foreach (XmlAttribute attribute in node.Attributes) { config.Attributes.Add(attribute.Name, attribute.Value); } config.Children.AddRange(configChilds); return config; }
public void RenameWithDifferentPrimaryKeyTypeAndDropRecreateWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf <Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf <RenamePkTypeChange.Entry>(); var migrator = MakeMigrator(from); IEnumerable <string> warnings; IEnumerable <string> errors; var answerProvider = new Mock <IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny <string>(), It.IsAny <IEnumerable <MultipleChoice <string> > >())) .Returns(new MultipleChoice <string> { Choice = "Entry", DisplayString = "Entry" }); answerProvider.Setup(a => a.GetBooleanAnswer(It.IsAny <string>())).Returns(false); // change the pk name to.GetMap <RenamePkTypeChange.Entry>().PrimaryKey.Name = "EntryId"; to.GetMap <RenamePkTypeChange.Entry>().PrimaryKey.DbName = "EntryId"; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock <ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( Regex.Replace(@"EXEC sp_RENAME [Posts], [Entries]; declare @OBDCommande51728c6d92c4851aa3b01e8a5a12adb nvarchar(1000); select @OBDCommande51728c6d92c4851aa3b01e8a5a12adb = 'ALTER TABLE [Posts] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'Posts' and c.name = 'Id'; execute(@OBDCommande51728c6d92c4851aa3b01e8a5a12adb); alter table [Posts] drop column [Id]; alter table [Entries] add [EntryId] uniqueidentifier not null DEFAULT NEWSEQUENTIALID() primary key; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; declare @OBDCommand934ba0aed0634856ab81048df9205176 nvarchar(1000); select @OBDCommand934ba0aed0634856ab81048df9205176 = 'ALTER TABLE [PostComments] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'PostComments' and c.name = 'PostId'; execute(@OBDCommand934ba0aed0634856ab81048df9205176); alter table [PostComments] drop column [PostId]; alter table [PostComments] add [PostId] uniqueidentifier null; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([EntryId]);", @"@\w+\b", "@Foo"), @"(?<!\r)\n", Environment.NewLine), Regex.Replace(script.Trim(), @"@\w+\b", "@Foo")); }
public void TestComponentWithNoInterface() { kernel.ComponentCreated += OnNoInterfaceStartableComponentStarted; var compNode = new MutableConfiguration("component"); compNode.Attributes["id"] = "b"; compNode.Attributes["startable"] = "true"; compNode.Attributes["startMethod"] = "Start"; compNode.Attributes["stopMethod"] = "Stop"; kernel.ConfigurationStore.AddComponentConfiguration("b", compNode); kernel.AddFacility <StartableFacility>(); kernel.Register(Component.For <NoInterfaceStartableComponent>().Named("b")); Assert.IsTrue(startableCreatedBeforeResolved, "Component was not properly started"); var component = kernel.Resolve <NoInterfaceStartableComponent>("b"); Assert.IsNotNull(component); Assert.IsTrue(component.Started); Assert.IsFalse(component.Stopped); kernel.ReleaseComponent(component); Assert.IsTrue(component.Stopped); }
public void DropPropertyWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf <Simple2.Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf <Post>(); var migrator = MakeMigrator(from); IEnumerable <string> warnings; IEnumerable <string> errors; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, null, new Mock <ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace(Regex.Replace(@"declare @OBDCommandca45edee90bb4cc68430f8540d28aa99 nvarchar(1000); select @OBDCommandca45edee90bb4cc68430f8540d28aa99 = 'ALTER TABLE [PostComments] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'PostComments' and c.name = 'Rating'; execute(@OBDCommandca45edee90bb4cc68430f8540d28aa99); alter table [PostComments] drop column [Rating];", @"@\w+\b", "@Foo"), @"(?<!\r)\n", Environment.NewLine), Regex.Replace(script.Trim(), @"@\w+\b", "@Foo")); }
public static IConfiguration GetDeserializedNode(XmlNode node) { var configChilds = new ConfigurationCollection(); var configValue = new StringBuilder(); if (node.HasChildNodes) { foreach (XmlNode child in node.ChildNodes) { if (IsTextNode(child)) { configValue.Append(child.Value); } else if (child.NodeType == XmlNodeType.Element) { configChilds.Add(GetDeserializedNode(child)); } } } var config = new MutableConfiguration(node.Name, GetConfigValue(configValue.ToString())); foreach (XmlAttribute attribute in node.Attributes) { config.Attributes.Add(attribute.Name, attribute.Value); } config.Children.AddRange(configChilds); return(config); }
/// <summary> /// Mappings to the specified Argument. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public ArgumentExpression MappingArgument(string name) { Contract.Require.That(name, Is.Not.Null & Is.Not.Empty).When("retrieving name argument in MappingArgument method"); //if (parentConfiguration == null) //{ // argumentExpression = new ArgumentExpression(builder); // parentConfiguration = builder.RegisterConfiguration(); // argumentExpression.parentConfiguration = parentConfiguration; //} //if (argumentExpression == null) //{ // argumentExpression = new ArgumentExpression(builder); // argumentExpression.parentConfiguration = parentConfiguration; //} //currentArgument = new MutableConfiguration(ConfigConstants.ELEMENT_ARGUMENT, name); //currentArgument.CreateAttribute(ConfigConstants.ATTRIBUTE_ARGUMENTNAME, name); //parentConfiguration.Children.Add(currentSubMap); MutableConfiguration configArgument = new MutableConfiguration(ConfigConstants.ELEMENT_ARGUMENT, name); configArgument.CreateAttribute(ConfigConstants.ATTRIBUTE_ARGUMENTNAME, name); builder.CurrentConfiguration.Children.Add(configArgument); ArgumentExpression argumentExpression = new ArgumentExpression(builder, parentConfiguration, configArgument); return(argumentExpression); }
/// <summary> /// Returns a Configuration object for the connection string that can be fluently configured /// </summary> /// <param name="connectionStringSettings">connection string settings for the database to be used</param> /// <param name="types">Enumerable of types to be mapped</param> /// <returns>Mutable configuration object</returns> public static MutableConfiguration Configure(ConnectionStringSettings connectionStringSettings, IEnumerable<Type> types) { if (connectionStringSettings == null) { throw new ArgumentNullException("connectionStringSettings"); } var configuration = new MutableConfiguration(connectionStringSettings); configuration.Add(types); return configuration; }
public void AddPropertyWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Simple2.Post>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var script = migrator.GenerateSqlDiff(@from.Maps, to.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(@"alter table [PostComments] add [Rating] int not null default (0);", script.Trim()); }
public void DropEntityWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).Add<Post>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var script = migrator.GenerateSqlDiff(@from.Maps, to.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(@"drop table [PostComments];", script.Trim()); }
public void CanReadNHConfigFileAsTheSourceOfSessionFactory() { IConfiguration castleConfiguration = new MutableConfiguration("myConfig"); castleConfiguration.Attributes["nhibernateConfigFile"] = @"Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities106/factory1.xml"; XmlConfigurationBuilder b = new XmlConfigurationBuilder(); NHibernate.Cfg.Configuration cfg = b.GetConfiguration(castleConfiguration); Assert.IsNotNull(cfg); string str = cfg.Properties["connection.provider"]; Assert.AreEqual("DummyProvider", str); }
public void ExistingIndexNotRecreated() { var config = new MutableConfiguration( new ConnectionStringSettings("Default", "Data Source=(localdb)\\v11.0;Integrated Security=true", "System.Data.SqlClient")) .AddNamespaceOf<Post>(); var postMap = config.GetMap<Post>(); postMap.Index(p => new { p.Blog }); Assert.Equal(2, postMap.ForeignKeys.Count()); Assert.Equal(2, postMap.Indexes.Count()); Assert.Equal("Blog", postMap.Indexes.First().Columns.First().Name); }
public void ForeignKeyIndexesAddedAutomatically() { var config = new MutableConfiguration( new ConnectionStringSettings("Default", "Data Source=(localdb)\\v11.0;Integrated Security=true", "System.Data.SqlClient")) .AddNamespaceOf<Post>(); var postMap = config.GetMap<Post>(); var blogMap = config.GetMap<Blog>(); Assert.Equal(2, postMap.ForeignKeys.Count()); Assert.Equal(2, postMap.Indexes.Count()); Assert.Equal("Blog", postMap.Indexes.Last().Columns.First().Name); }
public void AddEntityWorks() { var from = new MutableConfiguration(ConnectionString).Add<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var script = migrator.GenerateSqlDiff(@from.Maps, to.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [PostComments] ([Id] int not null identity(1,1) primary key, [Content] nvarchar(255) null, [PostId] int null); alter table [PostComments] add constraint fk_PostComment_Post_Post foreign key ([PostId]) references [Posts]([Id]); create index [idx_PostComment_Post] on [PostComments] ([PostId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
private void RegisterFacilities() { // AddFacility("nhibernate", new NHibernateFacility()); // AddFacility("transactions", new TransactionFacility()); //init logging MutableConfiguration confignode = new MutableConfiguration("facility"); confignode.Attributes.Add("loggingApi", LoggerImplementation.Log4net.ToString()); confignode.Attributes.Add("customLoggerFactory", String.Empty); this.Kernel.ConfigurationStore.AddFacilityConfiguration("logging", confignode); AddFacility("logging", new LoggingFacility()); }
public void SelfReferencingWorks() { var config = new MutableConfiguration(ConnectionString); config.Add<Category>(); var migrator = MakeMigrator(config); IEnumerable<string> errors; IEnumerable<string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Categories] ([CategoryId] int not null identity(1,1) primary key, [ParentId] int null, [Name] nvarchar(255) null); alter table [Categories] add constraint fk_Category_Category_Parent foreign key ([ParentId]) references [Categories]([CategoryId]); create index [idx_Category_Parent] on [Categories] ([ParentId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void AddNewRelationshipToTableWithNoData() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Simple2.Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Simple3.Post>(); var migrator = MakeMigrator(from); var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetAnswer<int>(It.IsAny<string>())).Returns(99); IEnumerable<string> warnings; IEnumerable<string> errors; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Blogs] ([Id] int not null identity(1,1) primary key, [Title] nvarchar(255) null); alter table [Posts] add [BlogId] int null; alter table [Posts] add constraint fk_Post_Blog_Blog foreign key ([BlogId]) references [Blogs]([Id]); create index [idx_Post_Blog] on [Posts] ([BlogId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void PairWorks() { var config = new MutableConfiguration(ConnectionString); config.Add<Pair>(); var migrator = MakeMigrator(config); IEnumerable<string> errors; IEnumerable<string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Pairs] ([PairId] int not null identity(1,1) primary key, [ReferencesId] int null, [ReferencedById] int null); alter table [Pairs] add constraint fk_Pair_Pair_References foreign key ([ReferencesId]) references [Pairs]([PairId]); alter table [Pairs] add constraint fk_Pair_Pair_ReferencedBy foreign key ([ReferencedById]) references [Pairs]([PairId]); create index [idx_Pair_References] on [Pairs] ([ReferencesId]); create index [idx_Pair_ReferencedBy] on [Pairs] ([ReferencedById]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void RenameWithDifferentPrimaryKeyTypeAndAttemptChangeWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<RenamePkTypeChange.Entry>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny<string>(), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Entry", DisplayString = "Entry" }); answerProvider.Setup(a => a.GetBooleanAnswer(It.IsAny<string>())).Returns(true); // change the pk name to.GetMap<RenamePkTypeChange.Entry>().PrimaryKey.Name = "EntryId"; to.GetMap<RenamePkTypeChange.Entry>().PrimaryKey.DbName = "EntryId"; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"EXEC sp_RENAME [Posts], [Entries]; EXEC sp_RENAME 'Entries.Id', 'EntryId', 'COLUMN'; alter table [Entries] alter column [EntryId] uniqueidentifier not null NEWSEQUENTIALID() primary key; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; alter table [PostComments] alter column [PostId] uniqueidentifier null; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([EntryId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); Assert.NotEmpty(warnings); Assert.Equal("Changing DB Type is not guaranteed to work: Post on PostComment", warnings.First()); }
public void ComplexDomainBuilds() { var config = new MutableConfiguration(ConnectionString); config.AddNamespaceOf<Post>(); var migrator = MakeMigrator(config); IEnumerable<string> errors; IEnumerable<string> warnings; var script = migrator.GenerateSqlDiff( new IMap[] { }, config.Maps, null, new Mock<ILogger>().Object, new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"create table [Blogs] ([BlogId] int not null identity(1,1) primary key, [Title] nvarchar(255) null, [CreateDate] datetime not null default (current_timestamp), [Description] nvarchar(255) null); create table [Categories] ([CategoryId] int not null identity(1,1) primary key, [ParentId] int null, [Name] nvarchar(255) null); create table [Comments] ([CommentId] int not null identity(1,1) primary key, [Content] nvarchar(255) null, [PostId] int null, [UserId] int null, [CommentDate] datetime not null default (current_timestamp)); create table [Likes] ([LikeId] int not null identity(1,1) primary key, [UserId] int null, [CommentId] int null); create table [OneToOneLefts] ([OneToOneLeftId] int not null identity(1,1) primary key, [RightId] int null, [Name] nvarchar(255) null); create table [OneToOneRights] ([OneToOneRightId] int not null identity(1,1) primary key, [LeftId] int null, [Name] nvarchar(255) null); create table [Pairs] ([PairId] int not null identity(1,1) primary key, [ReferencesId] int null, [ReferencedById] int null); create table [Posts] ([PostId] int not null identity(1,1) primary key, [Title] nvarchar(255) null, [Content] nvarchar(255) null, [Rating] decimal(18,10) not null default (0), [AuthorId] int null, [BlogId] int null, [DoNotMap] bit not null default (0)); create table [PostTags] ([PostTagId] int not null identity(1,1) primary key, [PostId] int null, [TagId] int null); create table [SimpleClasses] ([SimpleClassId] int not null identity(1,1) primary key, [Name] nvarchar(255) null, [CreatedDate] datetime not null default (current_timestamp)); create table [Tags] ([TagId] int not null identity(1,1) primary key, [Content] nvarchar(255) null); create table [Users] ([UserId] int not null identity(1,1) primary key, [Username] nvarchar(255) null, [EmailAddress] nvarchar(255) null, [Password] nvarchar(255) null, [IsEnabled] bit not null default (0), [HeightInMeters] decimal(18,10) not null default (0)); alter table [Categories] add constraint fk_Category_Category_Parent foreign key ([ParentId]) references [Categories]([CategoryId]); alter table [Comments] add constraint fk_Comment_Post_Post foreign key ([PostId]) references [Posts]([PostId]); alter table [Comments] add constraint fk_Comment_User_User foreign key ([UserId]) references [Users]([UserId]); alter table [Likes] add constraint fk_Like_User_User foreign key ([UserId]) references [Users]([UserId]); alter table [Likes] add constraint fk_Like_Comment_Comment foreign key ([CommentId]) references [Comments]([CommentId]); alter table [OneToOneLefts] add constraint fk_OneToOneLeft_OneToOneRight_Right foreign key ([RightId]) references [OneToOneRights]([OneToOneRightId]); alter table [OneToOneRights] add constraint fk_OneToOneRight_OneToOneLeft_Left foreign key ([LeftId]) references [OneToOneLefts]([OneToOneLeftId]); alter table [Pairs] add constraint fk_Pair_Pair_References foreign key ([ReferencesId]) references [Pairs]([PairId]); alter table [Pairs] add constraint fk_Pair_Pair_ReferencedBy foreign key ([ReferencedById]) references [Pairs]([PairId]); alter table [Posts] add constraint fk_Post_User_Author foreign key ([AuthorId]) references [Users]([UserId]); alter table [Posts] add constraint fk_Post_Blog_Blog foreign key ([BlogId]) references [Blogs]([BlogId]); alter table [PostTags] add constraint fk_PostTag_Post_Post foreign key ([PostId]) references [Posts]([PostId]); alter table [PostTags] add constraint fk_PostTag_Tag_Tag foreign key ([TagId]) references [Tags]([TagId]); create index [idx_Category_Parent] on [Categories] ([ParentId]); create index [idx_Comment_Post] on [Comments] ([PostId]); create index [idx_Comment_User] on [Comments] ([UserId]); create index [idx_Like_User] on [Likes] ([UserId]); create index [idx_Like_Comment] on [Likes] ([CommentId]); create index [idx_OneToOneLeft_Right] on [OneToOneLefts] ([RightId]); create index [idx_OneToOneRight_Left] on [OneToOneRights] ([LeftId]); create index [idx_Pair_References] on [Pairs] ([ReferencesId]); create index [idx_Pair_ReferencedBy] on [Pairs] ([ReferencedById]); create index [idx_Post_Author] on [Posts] ([AuthorId]); create index [idx_Post_Blog] on [Posts] ([BlogId]); create index [idx_PostTag_Post] on [PostTags] ([PostId]); create index [idx_PostTag_Tag] on [PostTags] ([TagId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void RenameWithDifferentPrimaryKeyTypeAndDropRecreateWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<RenamePkTypeChange.Entry>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny<string>(), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Entry", DisplayString = "Entry" }); answerProvider.Setup(a => a.GetBooleanAnswer(It.IsAny<string>())).Returns(false); // change the pk name to.GetMap<RenamePkTypeChange.Entry>().PrimaryKey.Name = "EntryId"; to.GetMap<RenamePkTypeChange.Entry>().PrimaryKey.DbName = "EntryId"; var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( Regex.Replace(@"EXEC sp_RENAME [Posts], [Entries]; declare @OBDCommande51728c6d92c4851aa3b01e8a5a12adb nvarchar(1000); select @OBDCommande51728c6d92c4851aa3b01e8a5a12adb = 'ALTER TABLE [Posts] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'Posts' and c.name = 'Id'; execute(@OBDCommande51728c6d92c4851aa3b01e8a5a12adb); alter table [Posts] drop column [Id]; alter table [Entries] add [EntryId] uniqueidentifier not null NEWSEQUENTIALID() primary key; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; declare @OBDCommand934ba0aed0634856ab81048df9205176 nvarchar(1000); select @OBDCommand934ba0aed0634856ab81048df9205176 = 'ALTER TABLE [PostComments] drop constraint ' + d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = 'PostComments' and c.name = 'PostId'; execute(@OBDCommand934ba0aed0634856ab81048df9205176); alter table [PostComments] drop column [PostId]; alter table [PostComments] add [PostId] uniqueidentifier null; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([EntryId]);", @"@\w+\b", "@Foo"), @"(?<!\r)\n", Environment.NewLine), Regex.Replace(script.Trim(), @"@\w+\b", "@Foo")); }
public void DontRenameWorksAndWarningWithCurrentData() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Entry>(); var migrator = MakeMigrator(from, true); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny<string>(), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "__NOTRENAMED", DisplayString = "Foo" }); var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; drop table [Posts]; create table [Entries] ([Id] int not null identity(1,1) primary key, [Content] nvarchar(255) null); alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([Id]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); Assert.NotEmpty(warnings); Assert.Equal( @"Property Post on PostComment has changed type but the column was not dropped. There is data in that table, please empty that column if necessary", warnings.First()); }
public void RenameWithPropertyRename() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<RenameTypeChangeAndColumn.Entry>(); var migrator = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup( a => a.GetMultipleChoiceAnswer(It.Is<string>(s => s.StartsWith("The entity")), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Entry", DisplayString = "Entry" }); answerProvider.Setup( a => a.GetMultipleChoiceAnswer(It.Is<string>(s => s.StartsWith("The property")), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Comments", DisplayString = "Comments" }); var script = migrator.GenerateSqlDiff( @from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new string[0], new string[0], out warnings, out errors); Assert.Equal( Regex.Replace( @"EXEC sp_RENAME [Posts], [Entries]; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; EXEC sp_RENAME 'PostComments.Content', 'Comments', 'COLUMN'; alter table [PostComments] add constraint fk_PostComment_Entry_Post foreign key ([PostId]) references [Entries]([Id]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
public void RenameAndChangeWorks() { var from = new MutableConfiguration(ConnectionString).AddNamespaceOf<Post>(); var to = new MutableConfiguration(ConnectionString).AddNamespaceOf<Port>(); var migrater = MakeMigrator(from); IEnumerable<string> warnings; IEnumerable<string> errors; var answerProvider = new Mock<IAnswerProvider>(); answerProvider.Setup(a => a.GetMultipleChoiceAnswer(It.IsAny<string>(), It.IsAny<IEnumerable<MultipleChoice<string>>>())) .Returns(new MultipleChoice<string> { Choice = "Port", DisplayString = "Port" }); var script = migrater.GenerateSqlDiff( from.Maps, to.Maps, answerProvider.Object, new Mock<ILogger>().Object, new String[0], new string[0], out warnings, out errors); Assert.Equal(Regex.Replace(@"EXEC sp_RENAME [Posts], [Ports]; alter table [PostComments] drop constraint [fk_PostComment_Post_Post]; drop index [idx_PostComment_Post] on [PostComments]; EXEC sp_RENAME 'PostComments.PostId', 'PortId', 'COLUMN'; alter table [Ports] add [Foo] nvarchar(255) null; alter table [PostComments] add constraint fk_PostComment_Port_Port foreign key ([PortId]) references [Ports]([Id]); create index [idx_PostComment_Port] on [PostComments] ([PortId]);", @"(?<!\r)\n", Environment.NewLine), script.Trim()); }
/// <summary> /// Registers <see cref="DefaultSessionManager"/> as the session manager. /// </summary> protected void RegisterSessionManager() { string defaultFlushMode = FacilityConfig.Attributes[DefaultFlushModeConfigurationKey]; if (!string.IsNullOrEmpty(defaultFlushMode)) { MutableConfiguration confignode = new MutableConfiguration(SessionManagerKey); IConfiguration properties = new MutableConfiguration("parameters"); confignode.Children.Add(properties); properties.Children.Add(new MutableConfiguration("DefaultFlushMode", defaultFlushMode)); Kernel.ConfigurationStore.AddComponentConfiguration(SessionManagerKey, confignode); } Kernel.Register(Component.For<ISessionManager>().ImplementedBy<DefaultSessionManager>().Named(SessionManagerKey)); }