Ejemplo n.º 1
0
        public void FieldInjectionFromSingleInstanceOfType()
        {
            ImplWithInstanceIndex.instanceCount = 0;

            BindingBuilder bb = new BindingBuilder();

            bb.BindTypeToSingleInstance(typeof(ImplWithInstanceIndex));

            Injector injector = UniInjectUtils.CreateInjector();

            injector.AddBindings(bb);

            NeedsFieldInjection needsInjection1 = injector.CreateAndInject <NeedsFieldInjection>();
            NeedsFieldInjection needsInjection2 = injector.CreateAndInject <NeedsFieldInjection>();
            NeedsFieldInjection needsInjection3 = injector.CreateAndInject <NeedsFieldInjection>();

            // Assert injection was successful
            Assert.NotNull(needsInjection1);
            Assert.NotNull(needsInjection2);
            Assert.NotNull(needsInjection3);
            // Assert only one instance was created
            Assert.AreEqual(1, needsInjection1.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(1, needsInjection2.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(1, needsInjection3.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(1, ImplWithInstanceIndex.instanceCount);
        }
        public void Describe(DescribeSortCriterionContext describe)
        {
            var builder = new BindingBuilder();

            foreach (var bindingProvider in _bindingProviders)
            {
                bindingProvider.GetMemberBindings(builder);
            }

            var groupedMembers = builder.Build().GroupBy(b => b.Property.DeclaringType).ToDictionary(b => b.Key, b => b);

            foreach (var typeMembers in groupedMembers.Keys)
            {
                var descriptor = describe.For(typeMembers.Name, new LocalizedString(typeMembers.Name.CamelFriendly()), T("Members for {0}", typeMembers.Name));
                foreach (var member in groupedMembers[typeMembers])
                {
                    var closureMember = member;
                    descriptor.Element(member.Property.Name, member.DisplayName, member.Description,
                                       context => ApplyFilter(context, closureMember.Property),
                                       context => DisplaySortCriterion(context, closureMember.DisplayName.Text),
                                       SortCriterionFormProvider.FormName
                                       );
                }
            }
        }
Ejemplo n.º 3
0
        public void TestSendAndReceiveWithFanout()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new FanoutExchange("fanout");

            admin.DeclareExchange(exchange);
            this.template.Exchange = exchange.Name;

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange));

            this.template.Execute <object>(
                delegate
            {
                var consumer = this.CreateConsumer(this.template);
                var tag      = consumer.ConsumerTag;
                Assert.IsNotNull(tag);

                try
                {
                    this.template.ConvertAndSend("message");
                    var result = this.GetResult(consumer);
                    Assert.AreEqual("message", result);
                }
                finally
                {
                    consumer.Stop();
                }

                return(null);
            });
        }
Ejemplo n.º 4
0
        public void TestSendAndReceiveWithTopicConsumeInBackground()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new TopicExchange("topic");

            admin.DeclareExchange(exchange);
            this.template.Exchange = exchange.Name;

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange).With("*.end"));

            var template = new RabbitTemplate(new CachingConnectionFactory());

            template.Exchange = exchange.Name;

            var consumer = this.template.Execute(
                delegate
            {
                var consumerinside = this.CreateConsumer(template);
                var tag            = consumerinside.ConsumerTag;
                Assert.IsNotNull(tag);

                return(consumerinside);
            });

            template.ConvertAndSend("foo", "message");
            var result = this.GetResult(consumer);

            Assert.AreEqual(null, result);

            this.template.ConvertAndSend("foo.end", "message");
            result = this.GetResult(consumer);
            Assert.AreEqual("message", result);

            consumer.Stop();
        }
Ejemplo n.º 5
0
        public void FieldInjectionFromNewInstancesOfType()
        {
            ImplWithInstanceIndex.instanceCount = 0;

            BindingBuilder bb = new BindingBuilder();

            bb.BindTypeToNewInstances(typeof(ImplWithInstanceIndex));

            Injector injector = UniInjectUtils.CreateInjector();

            injector.AddBindings(bb);

            NeedsFieldInjection needsInjection1 = injector.CreateAndInject <NeedsFieldInjection>();
            NeedsFieldInjection needsInjection2 = injector.CreateAndInject <NeedsFieldInjection>();
            NeedsFieldInjection needsInjection3 = injector.CreateAndInject <NeedsFieldInjection>();

            // Assert injection was successful
            Assert.NotNull(needsInjection1);
            Assert.NotNull(needsInjection2);
            Assert.NotNull(needsInjection3);
            // Assert that different instances were injected.
            Assert.AreEqual(1, needsInjection1.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(2, needsInjection2.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(3, needsInjection3.implWithInstanceCounter.instanceIndex);
            Assert.AreEqual(3, ImplWithInstanceIndex.instanceCount);
        }
Ejemplo n.º 6
0
        // ------------------------------------------------------------
        // IBindingRoot
        // ------------------------------------------------------------

        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IBindingToSyntax <T> Bind <T>()
        {
            var builder = new BindingBuilder <T>(typeof(T));

            bindingFactories.Add(builder);
            return(builder);
        }
Ejemplo n.º 7
0
        /// <inheritdoc/>
        public IBindingCollection DiscoverAndSetupBindings()
        {
            _logger.Trace("Discover and setup bindings");
            var bindingCollections = new ConcurrentBag <IBindingCollection>();

            var allTypes = _typeFinder.All;

            _logger.Trace("Find all binding conventions");
            var conventionTypes = _typeFinder.FindMultiple <IBindingConvention>();

            _scheduler.PerformForEach(conventionTypes, (Action <Type>)(conventionType =>
            {
                _logger.Trace((string)$"Handle convention type {conventionType.AssemblyQualifiedName}");

                var convention        = _bootContainer.Get(conventionType) as IBindingConvention;
                var servicesToResolve = allTypes.Where(service => convention.CanResolve(service));

                var bindings = new ConcurrentBag <Binding>();

                _scheduler.PerformForEach(servicesToResolve, service =>
                {
                    var bindingBuilder = new BindingBuilder(Binding.For(service));
                    convention.Resolve(service, bindingBuilder);
                    bindings.Add(bindingBuilder.Build());
                });

                var bindingCollection = new BindingCollection(bindings);
                bindingCollections.Add(bindingCollection);
            }));

            var aggregatedBindingCollection = new BindingCollection(bindingCollections.ToArray());

            return(aggregatedBindingCollection);
        }
Ejemplo n.º 8
0
 public IList <IBindingBuilder> CreateBuildersFromString(object target, string bindingExpression, IList <object> sources = null, IDataContext context = null)
 {
     Should.NotBeNull(target, nameof(target));
     Should.NotBeNull(bindingExpression, nameof(bindingExpression));
     try
     {
         var parserResult = Parser.Parse(target, bindingExpression, sources, context);
         var result       = new IBindingBuilder[parserResult.Count];
         for (int index = 0; index < parserResult.Count; index++)
         {
             var builder = new BindingBuilder(parserResult[index]);
             builder.Add(BindingBuilderConstants.BuildDelegate, _buildDelegate);
             result[index] = builder;
         }
         return(result);
     }
     catch (Exception exception)
     {
         exception = new InvalidOperationException(exception.Message, exception);
         var builder = new BindingBuilder();
         builder.Add(BindingBuilderConstants.Target, target);
         builder.Add(ProviderConstant, this);
         builder.Add(ExceptionConstant, exception);
         builder.Add(BindingBuilderConstants.BuildDelegate, CreateInvalidaDataBindingDelegate);
         return(new IBindingBuilder[] { builder });
     }
 }
Ejemplo n.º 9
0
        private void RebindQueue(string routingKey)
        {
            var ctx     = ContextRegistry.GetContext();
            var factory =
                ctx.GetObject("ConnectionFactory") as IConnectionFactory;

            try
            {
                IAmqpAdmin amqpAdmin = new RabbitAdmin(factory);

                TopicExchange mktDataExchange = new TopicExchange("APP.STOCK.MARKETDATA", false, false);
                Spring.Messaging.Amqp.Core.Queue mktDataQueue = new Spring.Messaging.Amqp.Core.Queue("APP.STOCK.MARKETDATA");

                if (!string.IsNullOrEmpty(_currentBinding))
                {
                    amqpAdmin.RemoveBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                }

                _currentBinding = routingKey;
                if (!string.IsNullOrEmpty(_currentBinding))
                {
                    amqpAdmin.DeclareBinding(BindingBuilder.Bind(mktDataQueue).To(mktDataExchange).With(_currentBinding));
                    txtRoutingKey.Text = _currentBinding;
                }
            }
            catch (Exception ex)
            {
                log.ErrorFormat("Uncaught application exception.", ex);
            }
        }
		private void ReadScope(XElement element, BindingBuilder<object> builder)
		{
			XAttribute scopeAttribute = element.Attribute("scope");

			if (scopeAttribute == null || String.IsNullOrEmpty(scopeAttribute.Value))
			{
				builder.InTransientScope();
				return;
			}

			string value = scopeAttribute.Value.ToLower();

			switch (value)
			{
				case "transient":
					builder.InTransientScope();
					break;

				case "singleton":
					builder.InSingletonScope();
					break;

				case "thread":
					builder.InThreadScope();
					break;

				case "request":
					builder.InRequestScope();
					break;

				default:
					throw new ConfigurationErrorsException(String.Format("The 'bind' element has an unknown value '{0}' for its 'scope' attribute. Valid values are transient, singleton, thread, and request.", value));
			}
		}
Ejemplo n.º 11
0
    public List <IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        bb.BindTypeToNewInstances(typeof(DeleteNotesAction));
        bb.BindTypeToNewInstances(typeof(SplitNotesAction));
        bb.BindTypeToNewInstances(typeof(MergeNotesAction));
        bb.BindTypeToNewInstances(typeof(SetNoteTypeAction));
        bb.BindTypeToNewInstances(typeof(AddNoteAction));
        bb.BindTypeToNewInstances(typeof(MoveNoteToAjacentSentenceAction));
        bb.BindTypeToNewInstances(typeof(MoveNotesToOtherVoiceAction));
        bb.BindTypeToNewInstances(typeof(MoveNotesAction));
        bb.BindTypeToNewInstances(typeof(ExtendNotesAction));

        bb.BindTypeToNewInstances(typeof(ToggleNoteTypeAction));

        bb.BindTypeToNewInstances(typeof(DeleteSentencesAction));
        bb.BindTypeToNewInstances(typeof(MergeSentencesAction));
        bb.BindTypeToNewInstances(typeof(SentenceFitToNoteAction));

        bb.BindTypeToNewInstances(typeof(SetMusicGapAction));
        bb.BindTypeToNewInstances(typeof(SetVideoGapAction));
        bb.BindTypeToNewInstances(typeof(ChangeBpmAction));
        return(bb.GetBindings());
    }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public IBindingToSyntax <object> Bind(Type type)
        {
            var builder = new BindingBuilder <object>(type);

            bindingFactories.Add(builder);
            return(builder);
        }
Ejemplo n.º 13
0
        public static void DslBindingExpression(this BindingBuilder builder, IEnumerable <Declaration> declarations, LambdaExpression expression)
        {
            var rewriter            = new ExpressionRewriter(declarations);
            var rewrittenExpression = rewriter.Rewrite(expression);

            builder.BindingExpression(rewrittenExpression);
        }
Ejemplo n.º 14
0
    public List <IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        bb.BindExistingInstance(ApplicationManager.Instance);
        bb.BindExistingInstance(SceneNavigator.Instance);
        bb.BindExistingInstance(SettingsManager.Instance);
        bb.BindExistingInstance(SongMetaManager.Instance);
        bb.BindExistingInstance(ThemeManager.Instance);
        bb.BindExistingInstance(CursorManager.Instance);
        bb.BindExistingInstance(UiManager.Instance);
        bb.BindExistingInstance(MidiManager.Instance);
        bb.BindExistingInstance(AudioManager.Instance);
        bb.BindExistingInstance(I18NManager.Instance);

        EventSystem eventSystem = GameObjectUtils.FindComponentWithTag <EventSystem>("EventSystem");

        bb.BindExistingInstance(eventSystem);

        // Lazy binding of settings, because they are not needed in every scene and loading the settings takes time.
        bb.BindExistingInstanceLazy(() => SettingsManager.Instance.Settings);
        bb.BindExistingInstanceLazy(() => StatsManager.Instance.Statistics);

        return(bb.GetBindings());
    }
Ejemplo n.º 15
0
    public List <IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        bb.BindExistingInstance(this);
        return(bb.GetBindings());
    }
Ejemplo n.º 16
0
    public List <UniInject.IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        bb.BindExistingInstance(uiDoc);
        return(bb.GetBindings());
    }
Ejemplo n.º 17
0
        public void TestSendAndReceiveWithNonDefaultExchange()
        {
            var admin    = new RabbitAdmin(this.connectionFactory);
            var exchange = new TopicExchange("topic");

            admin.DeclareExchange(exchange);

            admin.DeclareBinding(BindingBuilder.Bind(queue).To(exchange).With("*.end"));

            this.template.Execute <object>(
                delegate
            {
                var consumer = this.CreateConsumer(this.template);
                var tag      = consumer.ConsumerTag;
                Assert.IsNotNull(tag);

                this.template.ConvertAndSend("topic", "foo", "message");

                try
                {
                    var result = this.GetResult(consumer);
                    Assert.AreEqual(null, result);

                    this.template.ConvertAndSend("topic", "foo.end", "message");
                    result = this.GetResult(consumer);
                    Assert.AreEqual("message", result);
                }
                finally
                {
                    consumer.Channel.BasicCancel(tag);
                }

                return(null);
            });
        }
Ejemplo n.º 18
0
 /// <summary>
 ///     Creates a series of instances of <see cref="IBindingBuilder" />.
 /// </summary>
 /// <param name="target">The specified binding target.</param>
 /// <param name="bindingExpression">The specified binding expression.</param>
 /// <param name="sources">The specified sources, if any.</param>
 /// <returns>An instance of <see cref="IBindingBuilder" />.</returns>
 public IList <IBindingBuilder> CreateBuildersFromString(object target, string bindingExpression, IList <object> sources = null)
 {
     Should.NotBeNull(target, "target");
     Should.NotBeNullOrWhitespace(bindingExpression, "bindingExpression");
     try
     {
         var parserResult = Parser.Parse(bindingExpression, sources.IsNullOrEmpty()
             ? DataContext.Empty
             : new DataContext(1)
         {
             { BindingBuilderConstants.RawSources, sources }
         });
         var result = new IBindingBuilder[parserResult.Count];
         for (int index = 0; index < parserResult.Count; index++)
         {
             var builder = new BindingBuilder(parserResult[index]);
             builder.Add(BindingBuilderConstants.Target, target);
             builder.Add(BindingBuilderConstants.BuildDelegate, _buildDelegate);
             result[index] = builder;
         }
         return(result);
     }
     catch (Exception exception)
     {
         exception = new InvalidOperationException(exception.Message, exception);
         var builder = new BindingBuilder();
         builder.Add(BindingBuilderConstants.Target, target);
         builder.Add(ProviderConstant, this);
         builder.Add(ExceptionConstant, exception);
         builder.Add(BindingBuilderConstants.BuildDelegate, CreateInvalidaDataBindingDelegate);
         return(new IBindingBuilder[] { builder });
     }
 }
Ejemplo n.º 19
0
    public List <IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        // Note that the SceneData and SongMeta are loaded on access here if not done yet.
        bb.BindExistingInstance(SceneData);
        bb.BindExistingInstance(SongMeta);
        bb.BindExistingInstance(songAudioPlayer);
        bb.BindExistingInstance(songVideoPlayer);
        bb.BindExistingInstance(noteArea);
        bb.BindExistingInstance(noteAreaDragHandler);
        bb.BindExistingInstance(songEditorLayerManager);
        bb.BindExistingInstance(microphonePitchTracker);
        bb.BindExistingInstance(songEditorNoteRecorder);
        bb.BindExistingInstance(selectionController);
        bb.BindExistingInstance(editorNoteDisplayer);
        bb.BindExistingInstance(canvas);
        bb.BindExistingInstance(graphicRaycaster);
        bb.BindExistingInstance(historyManager);
        bb.BindExistingInstance(songMetaChangeEventStream);
        bb.BindExistingInstance(lyricsArea);
        bb.BindExistingInstance(midiFileImporter);
        bb.BindExistingInstance(this);
        return(bb.GetBindings());
    }
Ejemplo n.º 20
0
        public static void BindAllSystemsInAssemblies(this IApplication application, params Assembly[] assemblies)
        {
            if (null == application)
            {
                throw new ArgumentNullException(nameof(application));
            }

            var systemType        = typeof(ISystem);
            var applicableSystems = assemblies
                                    .SelectMany(assembly => assembly.GetTypes())
                                    .Where(type =>
            {
                if (type.IsInterface || type.IsAbstract)
                {
                    return(false);
                }

                return(systemType.IsAssignableFrom(type));
            })
                                    .ToList();

            if (false == applicableSystems.Any())
            {
                return;
            }

            var container = application.Container;

            foreach (var system in applicableSystems)
            {
                var configuration = new BindingBuilder().AsSingleton().WithName(system.Name).Build();
                container.Bind(systemType, system, configuration);
            }
        }
		private void ReadName(XElement element, BindingBuilder<object> builder)
		{
			var nameAttribute = element.Attribute("name");

			if (nameAttribute != null)
				builder.Named(nameAttribute.Value);
		}
Ejemplo n.º 22
0
 private static void ConfigureMediaBindings(BindingBuilder builder)
 {
     builder.HandleCommand <VideoConvertedCommand>()
     .WithHandle <MediaHelper>()
     .WithHandle <EventsService>()
     .WithHandle <NewsService>()
     .WithHandle <BulletinsService>();
 }
Ejemplo n.º 23
0
        internal static async Task <IBindingBuilder> GetBindingBuilder(HTMLViewEngine viewEngine, object viewModel, JavascriptBindingMode mode, object additional = null, IJavascriptObjectBuilderStrategyFactory strategyFactory = null)
        {
            var mapper         = viewEngine.GetMapper(viewModel, mode, strategyFactory);
            var bindingBuilder = new BindingBuilder(mapper, viewEngine.Logger, additional);
            await bindingBuilder.Init();

            return(bindingBuilder);
        }
Ejemplo n.º 24
0
        static Binding Bind(Type type, object target)
        {
            var containerBindingBuilder = new BindingBuilder(Binding.For(type));
            var scope = containerBindingBuilder.To(target);

            scope.Singleton();
            return(containerBindingBuilder.Build());
        }
Ejemplo n.º 25
0
 private static void ConfigureMediaBindings(BindingBuilder builder)
 {
     builder.HandleCommand <VideoConvertedCommand>()
     .WithHandle <VideoHandler>()
     .WithHandle <EventHandler>()
     .WithHandle <NewsHandler>()
     .WithHandle <SocialHandler>();
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Bind using a builder for fluent configuration
        /// </summary>
        /// <param name="container">container to act on</param>
        /// <param name="builderAction">configuration handler</param>
        /// <typeparam name="T">Type to bind to</typeparam>
        public static void Bind <T>(this IDependencyContainer container, Action <BindingBuilder <T> > builderAction)
        {
            var builder = new BindingBuilder <T>();

            builderAction(builder);
            var config = builder.Build();

            container.Bind <T>(config);
        }
Ejemplo n.º 27
0
        private static void ConfigureLikeBindings(BindingBuilder builder)
        {
            builder.HandleCommand <AddLikeCommand>()
            .WithHandle <LikeHandle>()
            .WithHandle <LikeNotificationHandle>();

            builder.HandleCommand <RemoveLikeCommand>()
            .WithHandle <LikeHandle>();
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Bind using a builder for fluent configuration
        /// </summary>
        /// <param name="container">container to act on</param>
        /// <param name="builderAction">configuration handler</param>
        /// <typeparam name="TFrom">Type to bind from</typeparam>
        /// <typeparam name="TTo">Type to bind to</typeparam>
        public static void Bind <TFrom, TTo>(this IDependencyContainer container, Action <BindingBuilder> builderAction) where TTo : TFrom
        {
            var builder = new BindingBuilder();

            builderAction(builder);
            var config = builder.Build();

            container.Bind <TFrom, TTo>(config);
        }
Ejemplo n.º 29
0
        protected async Task <BindingInContext> BindInContext(HtmlViewEngine engine, object dataContext, JavascriptBindingMode mode = JavascriptBindingMode.TwoWay)
        {
            var cacher  = new SessionCacher();
            var mapper  = new BidirectionalMapper(dataContext, engine, null, null, mode, engine.Logger, cacher);
            var builder = new BindingBuilder(mapper, engine.Logger) as IBindingBuilder;
            var binding = await builder.CreateBinding(false);

            return(new BindingInContext(binding, cacher));
        }
Ejemplo n.º 30
0
        public ConesForm()
        {
            InitializeComponent();
            var set = BindingSet <BaseForm <ConesViewModel>, ConesViewModel> .Create(this, ViewModel);

            this.Bind(BindingBuilder.BindOn(Cone1).For("Text").To("Cone1").Build <ConesForm, ConesViewModel>());
            this.Bind(BindingBuilder.BindOn(Cone2).For("Text").To("Cone2").Build <ConesForm, ConesViewModel>());
            this.Bind(BindingBuilder.BindOn(Cone3).For("Text").To("Cone3").Build <ConesForm, ConesViewModel>());
            this.Bind(BindingBuilder.BindOn(Cone4).For("Text").To("Cone4").Build <ConesForm, ConesViewModel>());
        }
Ejemplo n.º 31
0
        private static void ConfigureGroupBindings(BindingBuilder builder)
        {
            builder.HandleCommand <HideGroupCommand>()
            .WithHandle <GroupHandle>()
            .WithHandle <GroupActivitiesHandle>();

            builder.HandleCommand <UnhideGroupCommand>()
            .WithHandle <GroupHandle>()
            .WithHandle <GroupActivitiesHandle>();
        }
		private void ReadMetadata(XElement element, BindingBuilder<object> builder)
		{
			foreach (XElement metadataElement in element.Elements("metadata"))
			{
				XAttribute keyAttribute = metadataElement.RequiredAttribute("key");
				XAttribute valueAttribute = metadataElement.RequiredAttribute("value");

				builder.WithMetadata(keyAttribute.Value, valueAttribute.Value);
			}
		}
Ejemplo n.º 33
0
    public List <IBinding> GetBindings()
    {
        BindingBuilder bb = new BindingBuilder();

        bb.BindExistingInstance(this);
        bb.BindExistingInstance(songRouletteController);
        bb.BindExistingInstance(songAudioPlayer);
        bb.BindExistingInstance(songVideoPlayer);
        return(bb.GetBindings());
    }
        public void BuilderShouldUseTargetBindingContextForSource4()
        {
            const string sourcePath = "IntProperty";
            var targetObj = new BindingSourceEventNotifierModel();
            var builder = new BindingBuilder();
            builder.Bind(targetObj, () => model => model.ObjectProperty).To<BindingSourceModel>(() => model => model.IntProperty);

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, sourcePath);
            var sourceObj = new BindingSourceModel();
            BindingServiceProvider.ContextManager.GetBindingContext(targetObj).Value = sourceObj;
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, sourcePath);
        }
        public void BuilderShouldUseTargetBindingContextForSource2()
        {
            const string targetPath = "Text";
            const string sourcePath = "IntProperty";
            var targetObj = new object();
            var builder = new BindingBuilder();
            builder.Bind(targetObj, targetPath).To<BindingSourceModel>(() => (model, ctx) => model.IntProperty);

            IList<Func<IDataContext, IObserver>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IObserver source = sources.Single().Invoke(builder);
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, sourcePath);
            var sourceObj = new BindingSourceModel();
            BindingServiceProvider.ContextManager.GetBindingContext(targetObj).Value = sourceObj;
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, sourcePath);
        }
Ejemplo n.º 36
0
        public void ParserShouldParseSingleExpression2()
        {
            const string targetPath = "Text";
            const string sourcePath = "SourceText";
            const string binding = "Text $context.SourceText";
            var target = new object();
            IBindingParser bindingParser = CreateBindingParser();

            var context = new BindingBuilder(bindingParser.Parse(binding, EmptyContext, target, null).Single());
            IBindingPath path = context.GetData(BindingBuilderConstants.TargetPath);
            path.Path.ShouldEqual(targetPath);

            var sources = context.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(context);
            BindingSourceShouldBeValid(source, AttachedMemberConstants.DataContext + "." + sourcePath, target);
        }
        public void ParserShouldParseSingleExpression1()
        {
            const string targetPath = "Text";
            const string sourcePath = "SourceText";
            const string binding = "Text SourceText";
            var target = new object();
            IBindingParser bindingParser = CreateBindingParser();

            var context = new BindingBuilder(bindingParser.Parse(target, binding, null, null).Single());
            IBindingPath path = context.GetData(BindingBuilderConstants.TargetPath);
            path.Path.ShouldEqual(targetPath);

            var sources = context.GetData(BindingBuilderConstants.Sources);
            IObserver source = sources.Single().Invoke(context);
            BindingSourceShouldBeValidDataContext(target, source, sourcePath);
        }
	    public void Handle(XmlModule module, XElement element)
		{
			XAttribute serviceAttribute = element.RequiredAttribute("service");

			Type service = GetTypeFromAttributeValue(serviceAttribute);

			var binding = new Binding(service);
			var builder = new BindingBuilder<object>(binding, _kernel);

			module.AddBinding(binding);

			if (!HandleTarget(element, builder))
				throw new ConfigurationErrorsException("The 'bind' element does not define either a 'to' or 'toProvider' attribute.");

			ReadName(element, builder);
			ReadMetadata(element, builder);
			ReadScope(element, builder);
		}
Ejemplo n.º 39
0
        public void ParserShouldUseTargetBindingContextForSource()
        {
            const string targetPath = "Text";
            const string sourcePath = "IntProperty";
            const string binding = "Text IntProperty";
            var target = new object();
            IBindingParser bindingParser = CreateBindingParser();

            var context = new BindingBuilder(bindingParser.Parse(binding, EmptyContext, target, null).Single());
            IBindingPath path = context.GetData(BindingBuilderConstants.TargetPath);
            path.Path.ShouldEqual(targetPath);

            var sources = context.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(context);
            BindingSourceShouldBeValidDataContext(target, source, sourcePath);
            var sourceObj = new BindingSourceModel();
            BindingServiceProvider.ContextManager.GetBindingContext(target).Value = sourceObj;
            BindingSourceShouldBeValidDataContext(target, source, sourcePath);
        }
 public void BuilderShouldUseConverterParameter2()
 {
     Func<IDataContext, object> parameter = context => null;
     var builder = new BindingBuilder();
     builder.Bind(new object(), "test").To("test").WithConverterParameter(parameter);
     builder.GetData(BindingBuilderConstants.ConverterParameter).ShouldEqual(parameter);
 }
 public void BuilderShouldUseConverterParameter1()
 {
     var parameter = new object();
     var builder = new BindingBuilder();
     builder.Bind(new object(), "test").To("test").WithConverterParameter(parameter);
     builder.GetData(BindingBuilderConstants.ConverterParameter).Invoke(builder).ShouldEqual(parameter);
 }
        public void BuilderShouldUseSourceObject1()
        {
            const string targetPath = "Text";
            const string sourcePath = "IntProperty";
            var targetObj = new object();
            var sourceObj = new BindingSourceModel();
            var builder = new BindingBuilder();
            builder.Bind(targetObj, targetPath).To(sourceObj, sourcePath);

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            BindingParserTest.BindingSourceShouldBeValid(source, sourcePath, sourceObj);
        }
        public void BuilderShouldUseDynamicMember5()
        {
            const string targetPath = "Text";
            var targetObj = new object();
            var builder = new BindingBuilder();
            var src = new BindingSourceModel { ObjectProperty = "test" };
            builder.Bind(targetObj, targetPath).To(src, () => model => model.Member<string>("ObjectProperty").Member<int>("Length") + 0);

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            source.Path.Path.ShouldEqual("ObjectProperty.Length");
            source.GetSource(true).ShouldEqual(src);

            var data = builder.GetData(BindingBuilderConstants.MultiExpression);
            data.Invoke(builder, new object[] { ((string)src.ObjectProperty).Length }).ShouldEqual(((string)src.ObjectProperty).Length);
        }
        public void BuilderShouldUseBindingContextExtension4()
        {
            const string targetPath = "Text";
            const string sourcePath = "IntProperty";
            var targetObj = new object();
            var builder = new BindingBuilder();
            builder.Bind(targetObj, targetPath).To<BindingSourceModel>(() => model => BindingSyntaxEx.Self<object>().DataContext<BindingSourceModel>().IntProperty);

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            source.Path.Path.ShouldEqual(AttachedMemberConstants.DataContext + "." + sourcePath);
        }
        public void BuilderShouldUseDynamicMember3()
        {
            const string targetPath = "Text";
            var targetObj = new object();
            var builder = new BindingBuilder();
            var src = new BindingSourceModel { ObjectProperty = new BindingSourceModel { StringProperty = "test" } };
            builder.Bind(targetObj, targetPath).To<BindingSourceModel>(() => model => model.GetObjectProperty().Member<string>("StringProperty").Member<int>("Length"));

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, string.Empty);
            var sourceObj = new BindingSourceModel();
            BindingServiceProvider.ContextManager.GetBindingContext(targetObj).Value = sourceObj;
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, string.Empty);

            var data = builder.GetData(BindingBuilderConstants.MultiExpression);
            data.Invoke(builder, new[] { src }).ShouldEqual(((BindingSourceModel)src.GetObjectProperty()).StringProperty.Length);
        }
        public void BuilderShouldUseLambdaExpression2()
        {
            var builder = new BindingBuilder();
            builder.Bind(new object(), "empty")
                .To<BindingSourceModel>(() => model => model.StringProperty.OfType<char>().Count(c => c == '1') + ((BindingSourceModel)model.ObjectProperty).IntProperty);

            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression.Invoke(builder, new object[] { "1", 10 }).ShouldEqual(11);
            expression.Invoke(builder, new object[] { "", 0 }).ShouldEqual(0);

            var list = builder.GetData(BindingBuilderConstants.Sources);
            list.Count.ShouldEqual(2);
            list[0].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => model.StringProperty));
            list[1].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => ((BindingSourceModel)model.ObjectProperty).IntProperty));
        }
        public void BuilderShouldUseSelfExpression1()
        {
            var builder = new BindingBuilder();
            var sourceModel = new BindingSourceModel();
            builder.Bind(sourceModel, "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.Self<BindingSourceModel>());

            var source = builder.GetData(BindingBuilderConstants.Sources).Single().Invoke(builder);
            builder.GetData(BindingBuilderConstants.MultiExpression).ShouldBeNull();
            source.Path.IsEmpty.ShouldBeTrue();
            source.GetSource(true).ShouldEqual(sourceModel);
            var pathMembers = source.GetPathMembers(true);
            pathMembers.LastMember.GetValue(pathMembers.PenultimateValue, null).ShouldEqual(sourceModel);
        }
        public void BuilderShouldUseElementSource2()
        {
            const string name = "name";
            var builder = new BindingBuilder();
            var targetObj = new BindingSourceModel { ObjectProperty = "test" };
            var relativeObj = new BindingSourceModel();
            bool isInvoked = false;
            IEventListener eventListener = null;
            var memberMock = new BindingMemberInfoMock
            {
                TryObserveMember = (o, listener) =>
                {
                    eventListener = listener;
                    return null;
                }
            };

            var treeManagerMock = new VisualTreeManagerMock
            {
                FindByName = (o, s) =>
                {
                    o.ShouldEqual(targetObj);
                    s.ShouldEqual(name);
                    isInvoked = true;
                    return relativeObj;
                },
                GetRootMember = type => memberMock
            };
            BindingServiceProvider.VisualTreeManager = treeManagerMock;

            builder.Bind(targetObj, "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.Element<BindingSourceModel>(name).ObjectProperty);
            var source = builder.GetData(BindingBuilderConstants.Sources).Single().Invoke(builder);
            builder.GetData(BindingBuilderConstants.MultiExpression).ShouldBeNull();
            source.Path.Path.ShouldEqual(GetMemberPath(targetObj, model => model.ObjectProperty));
            source.GetSource(true).ShouldEqual(relativeObj);
            var pathMembers = source.GetPathMembers(true);
            pathMembers.LastMember.GetValue(pathMembers.PenultimateValue, null).ShouldEqual(relativeObj.ObjectProperty);
            isInvoked.ShouldBeTrue();

            isInvoked = false;
            eventListener.ShouldNotBeNull();
            eventListener.Handle(this, EventArgs.Empty);
            isInvoked.ShouldBeTrue();
        }
        public void BuilderShouldUseEventArgs2()
        {
            var builder = new BindingBuilder();
            builder.Bind(new object(), "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.EventArgs<EventArgs>().GetType().Name);

            builder.Add(BindingConstants.CurrentEventArgs, EventArgs.Empty);
            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression(builder, Empty.Array<object>()).ShouldEqual(EventArgs.Empty.GetType().Name);
        }
        public void BuilderShouldUseGetErrorsMethod4()
        {
            var builder = new BindingBuilder();
            var sourceModel = new BindingSourceModel();
            builder.Bind(sourceModel, "empty").To(sourceModel, () => model => BindingSyntaxEx.GetErrors("1", "2").Concat(BindingSyntaxEx.GetErrors(model.ObjectProperty)));


            var sources = builder.GetData(BindingBuilderConstants.Sources).Select(func => func(builder)).ToArray();
            sources[0].GetSource(true).ShouldEqual(sourceModel);
            sources[1].GetSource(true).ShouldEqual(sourceModel);
            if (sources[0].Path.IsEmpty)
                sources[1].Path.Path.ShouldEqual(GetMemberPath(sourceModel, model => model.ObjectProperty));
            else
                sources[0].Path.Path.ShouldEqual(GetMemberPath(sourceModel, model => model.ObjectProperty));

            var behaviors = builder.GetOrAddBehaviors().OfType<NotifyDataErrorsAggregatorBehavior>().ToArray();
            builder.AddOrUpdate(BindingConstants.Binding, new DataBindingMock { Behaviors = behaviors });
            var behavior = behaviors.Single(b => !b.ErrorPaths.IsNullOrEmpty());
            behavior.ErrorPaths.SequenceEqual(new[] { "1", "2" }).ShouldBeTrue();

            behaviors.ForEach(aggregatorBehavior => aggregatorBehavior.Errors = new[] { "1" });
            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            var errors = (IEnumerable<object>)expression(builder, new object[] { sourceModel, sourceModel });
            errors.SequenceEqual(behaviors[0].Errors.Concat(behaviors[1].Errors)).ShouldBeTrue();
        }
        public void BuilderShouldUseGetErrorsMethod3()
        {
            var builder = new BindingBuilder();
            var sourceModel = new BindingSourceModel();
            builder.Bind(sourceModel, "empty").To(sourceModel, () => model => BindingSyntaxEx.GetErrors("1", "2", model.ObjectProperty));

            var source = builder.GetData(BindingBuilderConstants.Sources).Single().Invoke(builder);
            source.Path.Path.ShouldEqual(GetMemberPath(sourceModel, model => model.ObjectProperty));
            source.GetSource(true).ShouldEqual(sourceModel);

            var behavior = builder.GetOrAddBehaviors().OfType<NotifyDataErrorsAggregatorBehavior>().Single();
            behavior.ErrorPaths.SequenceEqual(new[] { "1", "2" }).ShouldBeTrue();
            builder.AddOrUpdate(BindingConstants.Binding, new DataBindingMock { Behaviors = new[] { behavior } });

            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            behavior.Errors = new List<object> { "test" };
            expression(builder, new object[] { sourceModel }).ShouldEqual(behavior.Errors);
        }
        public void BuilderShouldUseResource2()
        {
            const string key = "key";
            var builder = new BindingBuilder();
            var sourceModel = new BindingSourceModel { ObjectProperty = "test" };
            BindingServiceProvider.ResourceResolver.AddObject(key, sourceModel);
            builder.Bind(sourceModel, "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.Self<BindingSourceModel>().ObjectProperty);

            var source = builder.GetData(BindingBuilderConstants.Sources).Single().Invoke(builder);
            builder.GetData(BindingBuilderConstants.MultiExpression).ShouldBeNull();
            source.Path.Path.ShouldEqual(GetMemberPath(sourceModel, model => model.ObjectProperty));
            source.GetSource(true).ShouldEqual(sourceModel);
            var pathMembers = source.GetPathMembers(true);
            pathMembers.LastMember.GetValue(pathMembers.PenultimateValue, null).ShouldEqual(sourceModel.ObjectProperty);
        }
        public void BuilderShouldUseLambdaExpression3()
        {
            var builder = new BindingBuilder();
            builder.Bind(new object(), "empty")
                .To<BindingSourceModel>(() => model => model.StringProperty.OfType<char>().Select(s => s == null ? 10 + 4 : 3 + 10).FirstOrDefault() == 0 ? false : true || true);

            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression.Invoke(builder, new object[] { "1" }).ShouldEqual("1".OfType<char>().Select(s => s == null ? 10 + 4 : 3 + 10).FirstOrDefault() == 0 ? false : true || true);
            expression.Invoke(builder, new object[] { "2" }).ShouldEqual("2".OfType<char>().Select(s => s == null ? 10 + 4 : 3 + 10).FirstOrDefault() == 0 ? false : true || true);

            var list = builder.GetData(BindingBuilderConstants.Sources);
            list.Count.ShouldEqual(1);
            list[0].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => model.StringProperty));
        }
        public void BuilderShouldUseBindingContextExtension1()
        {
            const string targetPath = "Text";
            var targetObj = new object();
            var builder = new BindingBuilder();
            builder.Bind(targetObj, targetPath).To<BindingSourceModel>(() => model => BindingSyntaxEx.DataContext<BindingSourceModel>());

            IList<Func<IDataContext, IBindingSource>> sources = builder.GetData(BindingBuilderConstants.Sources);
            IBindingSource source = sources.Single().Invoke(builder);
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, string.Empty);
            var sourceObj = new BindingSourceModel();
            BindingServiceProvider.ContextManager.GetBindingContext(targetObj).Value = sourceObj;
            BindingParserTest.BindingSourceShouldBeValidDataContext(targetObj, source, string.Empty);
        }
 public void BuilderShouldUseTargetNullValue()
 {
     var nullValue = new object();
     var builder = new BindingBuilder();
     builder.Bind(new object(), "test").To("test").WithTargetNullValue(nullValue);
     builder.GetData(BindingBuilderConstants.TargetNullValue).ShouldEqual(nullValue);
 }
        public void BuilderShouldUseEventArgs3()
        {
            var builder = new BindingBuilder();
            builder.Bind(new object(), "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.EventArgs<BindingSourceModel>().ObjectProperty);

            var sourceModel = new BindingSourceModel { ObjectProperty = "test" };
            builder.Add(BindingConstants.CurrentEventArgs, sourceModel);
            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression(builder, Empty.Array<object>()).ShouldEqual(sourceModel.ObjectProperty);
        }
        public void BuilderShouldUseResourceMethod2()
        {
            const string key = "key";
            var builder = new BindingBuilder();
            var sourceModel = new BindingSourceModel();
            var result = new BindingSourceModel { ObjectProperty = "Test" };
            BindingServiceProvider.ResourceResolver.AddMethod<string, object, BindingSourceModel>(key, (s1, s2, context) =>
            {
                s1.ShouldEqual(key);
                s2.ShouldEqual(builder);
                context.ShouldEqual(builder);
                return result;
            });
            builder.Bind(sourceModel, "empty").To<BindingSourceModel>(() => model => BindingSyntaxEx.ResourceMethod<BindingSourceModel>(key, key, builder).ObjectProperty);

            var sources = builder.GetData(BindingBuilderConstants.Sources);
            sources.Count.ShouldEqual(1);
            sources[0].Invoke(builder).Path.Path.ShouldEqual(string.Empty);
            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression(builder, Empty.Array<object>()).ShouldEqual(result.ObjectProperty);
        }
        public void BuilderShouldUseLambdaExpression1()
        {
            var builder = new BindingBuilder();
            builder.Bind(new object(), "empty")
                .To<BindingSourceModel>(() => model => model.IntProperty + 100 + model.NestedModel.IntProperty + int.Parse(model.NestedModel["1"]));

            var expression = builder.GetData(BindingBuilderConstants.MultiExpression);
            expression.Invoke(builder, new object[] { 10, 10, "10" }).ShouldEqual(130);
            expression.Invoke(builder, new object[] { -10, 10, "-100" }).ShouldEqual(0);

            var list = builder.GetData(BindingBuilderConstants.Sources);
            list.Count.ShouldEqual(3);
            list[0].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => model.IntProperty));
            list[1].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => model.NestedModel.IntProperty));
            list[2].Invoke(builder).Path.Path.ShouldEqual(GetMemberPath<BindingSourceModel>(model => model.NestedModel["1"]));
        }
 public void BuilderShouldUseConverterCulture3()
 {
     var builder = new BindingBuilder();
     builder.Bind(CultureInfo.InvariantCulture, "test").To("test").WithConverterCulture(() => o => BindingSyntaxEx.Self<CultureInfo>());
     builder.GetData(BindingBuilderConstants.ConverterCulture).Invoke(builder).ShouldEqual(CultureInfo.InvariantCulture);
 }
 public void BuilderShouldUseConverterParameter3()
 {
     var builder = new BindingBuilder();
     builder.Bind(builder, "test").To("test").WithConverterParameter(() => o => BindingSyntaxEx.Self<object>());
     builder.GetData(BindingBuilderConstants.ConverterParameter).Invoke(builder).ShouldEqual(builder);
 }