Batch

We found 10 examples in language CSharp for this search. You will see 60 fragments of code.
        [TestMethod]
        public void Constructor1_PropertiesShouldBeSetAndEmpty()
        {
            CompositionBatch batch = new CompositionBatch();

            Assert.IsNotNull(batch.PartsToAdd);
            EnumerableAssert.IsEmpty(batch.PartsToAdd);

            Assert.IsNotNull(batch.PartsToRemove);
            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }


        [TestMethod]
        public void Constructor2_PartsToAddAsNull_PartsToAddShouldBeEmpty()
        {
            ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(null, partsToRemove);

            Assert.AreEqual(0, batch.PartsToAdd.Count);
            Assert.AreEqual(partsToRemove.Length, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void Constructor2_PartsToRemoveAsNull_PartsToRemoveShouldBeEmpty()
        {
            ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(partsToAdd, null);

            Assert.AreEqual(partsToAdd.Length, batch.PartsToAdd.Count);
            Assert.AreEqual(0, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void AddPart_PartIsInPartsToAdd()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.AddPart(part);

            Assert.AreEqual(1, batch.PartsToAdd.Count);
            Assert.AreSame(part, batch.PartsToAdd[0]);

            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }

        [TestMethod]
        public void AddPart_PartAsNull_ShouldThrowArgumentNullException()
        {
            CompositionBatch batch = new CompositionBatch();

            ExceptionAssert.ThrowsArgument<ArgumentNullException>("part", () =>
            {
                batch.AddPart(null);
            });
        }

        [TestMethod]
        public void RemovePart_PartIsInPartsToRemove()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.RemovePart(part);

            Assert.AreEqual(1, batch.PartsToRemove.Count);
            Assert.AreSame(part, batch.PartsToRemove[0]);

            EnumerableAssert.IsEmpty(batch.PartsToAdd);
        }


		DataflowMessageStatus ITargetBlock<T>.OfferMessage (
			DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source,
			bool consumeToAccept)
		{
			return messageBox.OfferMessage (
				messageHeader, messageValue, source, consumeToAccept);
		}

		public IDisposable LinkTo (ITargetBlock<T[]> target, DataflowLinkOptions linkOptions)
		{
			return outgoing.AddTarget (target, linkOptions);
		}

		T[] ISourceBlock<T[]>.ConsumeMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target,
			out bool messageConsumed)
		{
			return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
		}

		void ISourceBlock<T[]>.ReleaseReservation (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			outgoing.ReleaseReservation (messageHeader, target);
		}

		bool ISourceBlock<T[]>.ReserveMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			return outgoing.ReserveMessage (messageHeader, target);
		}

		public bool TryReceive (Predicate<T[]> filter, out T[] item)
		{
			return outgoing.TryReceive (filter, out item);
		}


        [TestMethod]
        public void Import_OptIn_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptIn_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value, "Value should have changed!");
        }

        [TestMethod]
        public void Import_OptOut_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptOut_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_Default_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_Default_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_BothOptInAndOptOutRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_BothOptInAndOptOutRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose values should be 21
            Assert.AreEqual(21, importer.RecomposableValue);
            Assert.AreEqual(21, importer.NonRecomposableValue);

            // Reset value to ensure it doesn't get set to same value again
            importer.NonRecomposableValue = -21;
            importer.RecomposableValue = -21;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.NonRecomposableValue, "Value should NOT have changed!");
            // The batch rejection means that the recomposable value shouldn't change either
            Assert.AreEqual(-21, importer.RecomposableValue, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_OptInRecomposition_Multlple()
        {
            var container = new CompositionContainer();
            var importer = new Class_MultipleOptInRecompositionImportsWithDifferentContracts();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var value1Key = batch.AddExportedValue("Value1", 21);
            var value2Key = batch.AddExportedValue("Value2", 23);
            container.Compose(batch);

            Assert.AreEqual(21, importer.Value1);
            Assert.AreEqual(23, importer.Value2);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value1 = -21;
            importer.Value2 = -23;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(value1Key);
            batch.AddExportedValue("Value1", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value1, "Value should have changed!");
            Assert.AreEqual(-23, importer.Value2, "Value should NOT have changed because Value2 contract should not be updated.");
        }

        [TestMethod]
        public void Recomposition_IntegrationTest()
        {
            var container = new CompositionContainer();
            var batch = new CompositionBatch();

            var me = new Me();
            batch.AddPart(me);
            var namePart = batch.AddPart(new MyName("Blake"));
            batch.AddPart(new Spouse("Barbara"));
            batch.AddPart(new Friend("Steve"));
            batch.AddPart(new Friend("Joyce"));
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blake", "Name in initial composition incorrect");
            Assert.AreEqual(me.Job, null, "Job should have the default value");
            Assert.AreEqual(me.Friends.Length, 3, "Number of friends in initial composition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives in initial composition incorrect");
            Assert.AreEqual(me.Children.Length, 0, "Number of children in initial composition incorrect");

            // Can only have one name
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new MyName("Blayke")));

            batch = new CompositionBatch();
            batch.AddPart(new MyName("Blayke"));
            batch.RemovePart(namePart);
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blayke", "Name after recomposition incorrect");

            batch = new CompositionBatch();
            var jobPart = batch.AddPart(new Job("Architect"));
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Architect", "Job after recomposition incorrect");

            batch = new CompositionBatch();
            batch.AddPart(new Job("Chimney Sweep"));
            container.Compose(batch);
            Assert.IsTrue(me.Job == null, "More than one of an optional import should result in the default value");

            batch = new CompositionBatch();
            batch.RemovePart(jobPart);
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Chimney Sweep", "Job after re-recomposition incorrect");

            batch = new CompositionBatch();

            // Can only have one spouse because they aren't recomposable
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new Spouse("Cameron")));

            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");

            batch = new CompositionBatch();
            batch.AddPart(new Friend("Graham"));
            container.Compose(batch);
            Assert.AreEqual(me.Friends.Length, 4, "Number of friends after recomposition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");
        }

        internal static ArgumentException Argument(string message, string parameterName)
        {
            return Trace(new ArgumentException(message, parameterName));
        }

        internal static InvalidOperationException InvalidOperation(string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        internal static InvalidOperationException InvalidOperation(string message, Exception innerException)
        {
            return Trace(new InvalidOperationException(message, innerException));
        }

        internal static NotSupportedException NotSupported(string message)
        {
            return Trace(new NotSupportedException(message));
        }

        internal static void ThrowObjectDisposed(Type type)
        {
            throw Trace(new ObjectDisposedException(type.ToString()));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801", Justification = "errorCode ignored for code sharing")]
        internal static InvalidOperationException HttpHeaderFailure(int errorCode, string message)
        {
            return Trace(new InvalidOperationException(message));
        }

            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }
            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }

        [TestMethod]
        public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer()
        {
            var container = new CompositionContainer();
            var disposablePart = new AnyPartDisposable();
            var batch = new CompositionBatch();
            batch.AddPart(batch);
            container.Compose(batch);

            container.Dispose();
            Assert.IsFalse(disposablePart.IsDisposed);
        }

        [TestMethod]
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part = AttributedModelServices.CreatePart(disposable);
            var batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports<AnyPartDisposable>();
            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }

        [TestMethod]
        public void AnyPart_Simple_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartSimple));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartSimple>());

            refTracker.CollectAndAssert();

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void AnyPart_Disposable_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartDisposable));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartDisposable>());

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void RepeatedContainerUse()
        {
            var container = ContainerFactory.Create();
            TrivialExporter e = new TrivialExporter();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(e);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(new TrivialImporter());
            container.Compose(batch);

            Assert.IsTrue(e.done, "Initialization of importer should have set the done flag on E");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new RealAddProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(3, c.op(c.a, c.b), "1 + 2 == 3");
        }
        [TestMethod]
        public void FunctionsFieldsAndProperties2()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new SubtractProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(-1, c.op(c.a, c.b), "1 - 2 == -1");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties2_WithCatalog()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            ConsumerOfMultiple c = new ConsumerOfMultiple();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(c);
            container.Compose(batch);

            foreach (var export in c.opInfo)
            {
                if ((string)export.Metadata["Var1"] == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if ((string)export.Metadata["Var1"] == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

#if !SILVERLIGHT
		// Silverlight doesn't support strongly typed metadata
        [TestMethod]
        public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

        [TestMethod]
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
            
            IDictionary<string, object> multMetadata = new Dictionary<string, object>();
            multMetadata["Var1"]= "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func<int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func<int, int, int>)delegate(int a, int b) { return a * b; }));

            CompositionBatch batch = new CompositionBatch();
            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            Assert.AreEqual(3, exports.Count(), "There should be 3 entries for 'Add'");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.AreEqual(2, export.Value(1, 2), "1 * 2 == 2");
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

		[Test]
		public void BasicUsageTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo<int[]> (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			Assert.IsFalse (evt.Wait (100));

			Assert.IsNull (array);

			Assert.IsTrue (buffer.Post (42));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (array);
			CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
		}

		[Test]
		public void TriggerBatchTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			evt.Wait ();

			Assert.IsNotNull (array);
			Assert.IsTrue (buffer.Post (42));
			evt.Wait (1600);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchLateBinding ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			buffer.LinkTo (block);

			evt.Wait ();
			Assert.IsNotNull (array);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void LateTriggerBatchKeepCountTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (15);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));
			buffer.TriggerBatch ();
			Assert.IsTrue (buffer.Post (42));
			buffer.LinkTo (block);

			evt.Wait ();

			Assert.IsNotNull (array);
			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchWhenEmpty ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (5,
				new GroupingDataflowBlockOptions { TaskScheduler = scheduler });
			block.TriggerBatch ();

			scheduler.ExecuteAll ();

			int[] batch;
			Assert.IsFalse (block.TryReceive (out batch));
			Assert.IsNull (batch);
		}

		[Test]
		public void NonGreedyBatchWithBoundedCapacityTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (2,
				new GroupingDataflowBlockOptions
				{ Greedy = false, BoundedCapacity = 2, TaskScheduler = scheduler });
			var source1 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source2 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			Assert.IsNotNull (source1.LinkTo (block));
			Assert.IsNotNull (source2.LinkTo (block));

			Assert.IsTrue (source1.Post (11));
			Assert.IsTrue (source2.Post (21));

			scheduler.ExecuteAll ();

			Assert.IsTrue (source1.Post (12));
			Assert.IsTrue (source2.Post (22));

			scheduler.ExecuteAll ();

			int i;
			Assert.IsTrue (source1.TryReceive (out i));
			Assert.AreEqual (12, i);

			Assert.IsTrue (source1.Post (13));

			int[] batch;
			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);

			scheduler.ExecuteAll ();

			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 13, 22 }, batch);
		}

            public void OnImportsSatisfied()
            {
                this.ImportsSatisfiedInvoked = true;
            }

        [TestMethod]
        public void ImportsSatisfiedOnComponentWithoutImports()
        {
            CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));

            PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
            Assert.IsNotNull(partWithoutImports);

            Assert.IsTrue(partWithoutImports.ImportsSatisfiedInvoked);

        }

        [TestMethod()]
        public void ImportCompletedTest()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");
        }

        [TestMethod]
        public void ImportCompletedWithRecomposing()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");

            // Add another component to verify recomposing
            batch = new CompositionBatch();
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.LowerCaseStrings[1].Value.String, "def");
            Assert.AreEqual(entrypoint.UpperCaseStrings[1], "DEF");

            // Verify that adding a random component doesn't cause
            // the OnImportsSatisfied to be called again.
            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(700940)]
        public void ImportCompletedUsingSatisfyImportsOnce()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();
            var entrypointPart = AttributedModelServices.CreatePart(entrypoint);

            batch.AddParts(new LowerCaseString("abc"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);

            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(2, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(2, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(2, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            Assert.AreEqual("def", entrypoint.LowerCaseStrings[1].Value.String);
            Assert.AreEqual("DEF", entrypoint.UpperCaseStrings[1]);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(654513)]
        public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
        {
            int importSatisfationCount = 0;
            var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
            var importer2 = new MyEventDrivenFullComposedNotifyImporter2();

            Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
            {
                Assert.IsTrue(importer1.AreAllImportsFullyComposed);
                Assert.IsTrue(importer2.AreAllImportsFullyComposed);
                ++importSatisfationCount;
            };

            importer1.ImportsSatisfied += new EventHandler(verificationAction);
            importer2.ImportsSatisfied += new EventHandler(verificationAction);

            // importer1 added first
            var batch = new CompositionBatch();
            batch.AddParts(importer1, importer2);

            var container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);

            // importer2 added first
            importSatisfationCount = 0;
            batch = new CompositionBatch();
            batch.AddParts(importer2, importer1);

            container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);
        }


        public void LoadAllTextures(ContentManager content)
        {
            collectableSpriteSheet = content.Load<Texture2D>("ItemSpriteSheet");
        }

        public ICollectable CreateArrowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableArrowSprite(spriteBatch, location);
        }

        public ICollectable CreateBigHeartSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBigHeartSprite(spriteBatch, location);
        }

        public ICollectable CreateBombSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBombSprite(spriteBatch, location);
        }

        public ICollectable CreateBoomerangSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBoomerangSprite(spriteBatch, location);
        }

        public ICollectable CreateBowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBowSprite(spriteBatch, location);
        }


		/// <summary>
		/// Returns whether a new item can be accepted, and increments a counter if it can.
		/// </summary>
		bool TryAdd ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (options.MaxNumberOfGroups != -1
				    && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
					return false;

				batchCount++;
				return true;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}
		}

		/// <summary>
		/// Decides whether to create a new batch or not.
		/// </summary>
		void SignalTarget ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (batchCount < BatchSize)
					return;

				batchCount -= BatchSize;
				numberOfGroups++;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}

			MakeBatch (BatchSize);
		}

		/// <summary>
		/// Creates a batch of the given size and adds the resulting batch to the output queue.
		/// </summary>
		void MakeBatch (int batchSize)
		{
			if (batchSize == 0)
				return;

			var list1 = new List<T1> ();
			var list2 = new List<T2> ();
			
			// lock is necessary here to make sure items are in the correct order
			bool taken = false;
			try {
				batchLock.Enter (ref taken);

				int i = 0;

				T1 item1;
				while (i < batchSize && target1.Buffer.TryTake (out item1)) {
					list1.Add (item1);
					i++;
				}

				T2 item2;
				while (i < batchSize && target2.Buffer.TryTake (out item2)) {
					list2.Add (item2);
					i++;
				}

				if (i < batchSize)
					throw new InvalidOperationException("Unexpected count of items.");
			} finally {
				if (taken)
					batchLock.Exit ();
			}

			var batch = Tuple.Create<IList<T1>, IList<T2>> (list1, list2);

			outgoing.AddData (batch);

			VerifyMaxNumberOfGroups ();
		}

		/// <summary>
		/// Verifies whether <see cref="GroupingDataflowBlockOptions.MaxNumberOfGroups"/>
		/// has been reached. If it did, <see cref="Complete"/>s the block.
		/// </summary>
		void VerifyMaxNumberOfGroups ()
		{
			if (options.MaxNumberOfGroups == -1)
				return;

			bool shouldComplete;

			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			if (shouldComplete)
				Complete ();
		}

		public void Complete ()
		{
			target1.Complete ();
			target2.Complete ();
			MakeBatch (batchCount);
			outgoing.Complete ();
		}

		void IDataflowBlock.Fault (Exception exception)
		{
			completionHelper.RequestFault (exception);
		}

GlobalLink.Connect.TargetServiceRef.Batch : INotifyPropertyChanged

Constructors :

public Batch()

Methods :

public String get_name()
public Void set_name(String value = )
public String[] get_targetLanguages()
public Void set_targetLanguages(String[] value = )
public WorkflowDefinition get_workflowDefinition()
public Void set_workflowDefinition(WorkflowDefinition value = )
public Void add_PropertyChanged(PropertyChangedEventHandler value = )
public Void remove_PropertyChanged(PropertyChangedEventHandler value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods

Batch

We found 10 examples in language CSharp for this search. You will see 60 fragments of code.
        [TestMethod]
        public void Constructor1_PropertiesShouldBeSetAndEmpty()
        {
            CompositionBatch batch = new CompositionBatch();

            Assert.IsNotNull(batch.PartsToAdd);
            EnumerableAssert.IsEmpty(batch.PartsToAdd);

            Assert.IsNotNull(batch.PartsToRemove);
            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }


        [TestMethod]
        public void Constructor2_PartsToAddAsNull_PartsToAddShouldBeEmpty()
        {
            ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(null, partsToRemove);

            Assert.AreEqual(0, batch.PartsToAdd.Count);
            Assert.AreEqual(partsToRemove.Length, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void Constructor2_PartsToRemoveAsNull_PartsToRemoveShouldBeEmpty()
        {
            ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(partsToAdd, null);

            Assert.AreEqual(partsToAdd.Length, batch.PartsToAdd.Count);
            Assert.AreEqual(0, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void AddPart_PartIsInPartsToAdd()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.AddPart(part);

            Assert.AreEqual(1, batch.PartsToAdd.Count);
            Assert.AreSame(part, batch.PartsToAdd[0]);

            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }

        [TestMethod]
        public void AddPart_PartAsNull_ShouldThrowArgumentNullException()
        {
            CompositionBatch batch = new CompositionBatch();

            ExceptionAssert.ThrowsArgument<ArgumentNullException>("part", () =>
            {
                batch.AddPart(null);
            });
        }

        [TestMethod]
        public void RemovePart_PartIsInPartsToRemove()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.RemovePart(part);

            Assert.AreEqual(1, batch.PartsToRemove.Count);
            Assert.AreSame(part, batch.PartsToRemove[0]);

            EnumerableAssert.IsEmpty(batch.PartsToAdd);
        }


		DataflowMessageStatus ITargetBlock<T>.OfferMessage (
			DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source,
			bool consumeToAccept)
		{
			return messageBox.OfferMessage (
				messageHeader, messageValue, source, consumeToAccept);
		}

		public IDisposable LinkTo (ITargetBlock<T[]> target, DataflowLinkOptions linkOptions)
		{
			return outgoing.AddTarget (target, linkOptions);
		}

		T[] ISourceBlock<T[]>.ConsumeMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target,
			out bool messageConsumed)
		{
			return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
		}

		void ISourceBlock<T[]>.ReleaseReservation (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			outgoing.ReleaseReservation (messageHeader, target);
		}

		bool ISourceBlock<T[]>.ReserveMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			return outgoing.ReserveMessage (messageHeader, target);
		}

		public bool TryReceive (Predicate<T[]> filter, out T[] item)
		{
			return outgoing.TryReceive (filter, out item);
		}


        [TestMethod]
        public void Import_OptIn_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptIn_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value, "Value should have changed!");
        }

        [TestMethod]
        public void Import_OptOut_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptOut_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_Default_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_Default_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_BothOptInAndOptOutRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_BothOptInAndOptOutRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose values should be 21
            Assert.AreEqual(21, importer.RecomposableValue);
            Assert.AreEqual(21, importer.NonRecomposableValue);

            // Reset value to ensure it doesn't get set to same value again
            importer.NonRecomposableValue = -21;
            importer.RecomposableValue = -21;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.NonRecomposableValue, "Value should NOT have changed!");
            // The batch rejection means that the recomposable value shouldn't change either
            Assert.AreEqual(-21, importer.RecomposableValue, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_OptInRecomposition_Multlple()
        {
            var container = new CompositionContainer();
            var importer = new Class_MultipleOptInRecompositionImportsWithDifferentContracts();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var value1Key = batch.AddExportedValue("Value1", 21);
            var value2Key = batch.AddExportedValue("Value2", 23);
            container.Compose(batch);

            Assert.AreEqual(21, importer.Value1);
            Assert.AreEqual(23, importer.Value2);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value1 = -21;
            importer.Value2 = -23;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(value1Key);
            batch.AddExportedValue("Value1", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value1, "Value should have changed!");
            Assert.AreEqual(-23, importer.Value2, "Value should NOT have changed because Value2 contract should not be updated.");
        }

        [TestMethod]
        public void Recomposition_IntegrationTest()
        {
            var container = new CompositionContainer();
            var batch = new CompositionBatch();

            var me = new Me();
            batch.AddPart(me);
            var namePart = batch.AddPart(new MyName("Blake"));
            batch.AddPart(new Spouse("Barbara"));
            batch.AddPart(new Friend("Steve"));
            batch.AddPart(new Friend("Joyce"));
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blake", "Name in initial composition incorrect");
            Assert.AreEqual(me.Job, null, "Job should have the default value");
            Assert.AreEqual(me.Friends.Length, 3, "Number of friends in initial composition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives in initial composition incorrect");
            Assert.AreEqual(me.Children.Length, 0, "Number of children in initial composition incorrect");

            // Can only have one name
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new MyName("Blayke")));

            batch = new CompositionBatch();
            batch.AddPart(new MyName("Blayke"));
            batch.RemovePart(namePart);
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blayke", "Name after recomposition incorrect");

            batch = new CompositionBatch();
            var jobPart = batch.AddPart(new Job("Architect"));
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Architect", "Job after recomposition incorrect");

            batch = new CompositionBatch();
            batch.AddPart(new Job("Chimney Sweep"));
            container.Compose(batch);
            Assert.IsTrue(me.Job == null, "More than one of an optional import should result in the default value");

            batch = new CompositionBatch();
            batch.RemovePart(jobPart);
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Chimney Sweep", "Job after re-recomposition incorrect");

            batch = new CompositionBatch();

            // Can only have one spouse because they aren't recomposable
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new Spouse("Cameron")));

            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");

            batch = new CompositionBatch();
            batch.AddPart(new Friend("Graham"));
            container.Compose(batch);
            Assert.AreEqual(me.Friends.Length, 4, "Number of friends after recomposition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");
        }

            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }
            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }

        [TestMethod]
        public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer()
        {
            var container = new CompositionContainer();
            var disposablePart = new AnyPartDisposable();
            var batch = new CompositionBatch();
            batch.AddPart(batch);
            container.Compose(batch);

            container.Dispose();
            Assert.IsFalse(disposablePart.IsDisposed);
        }

        [TestMethod]
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part = AttributedModelServices.CreatePart(disposable);
            var batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports<AnyPartDisposable>();
            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }

        [TestMethod]
        public void AnyPart_Simple_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartSimple));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartSimple>());

            refTracker.CollectAndAssert();

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void AnyPart_Disposable_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartDisposable));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartDisposable>());

            GC.KeepAlive(container);
        }

        internal static ArgumentException Argument(string message, string parameterName)
        {
            return Trace(new ArgumentException(message, parameterName));
        }

        internal static InvalidOperationException InvalidOperation(string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        internal static InvalidOperationException InvalidOperation(string message, Exception innerException)
        {
            return Trace(new InvalidOperationException(message, innerException));
        }

        internal static NotSupportedException NotSupported(string message)
        {
            return Trace(new NotSupportedException(message));
        }

        internal static void ThrowObjectDisposed(Type type)
        {
            throw Trace(new ObjectDisposedException(type.ToString()));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801", Justification = "errorCode ignored for code sharing")]
        internal static InvalidOperationException HttpHeaderFailure(int errorCode, string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        [TestMethod]
        public void RepeatedContainerUse()
        {
            var container = ContainerFactory.Create();
            TrivialExporter e = new TrivialExporter();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(e);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(new TrivialImporter());
            container.Compose(batch);

            Assert.IsTrue(e.done, "Initialization of importer should have set the done flag on E");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new RealAddProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(3, c.op(c.a, c.b), "1 + 2 == 3");
        }
        [TestMethod]
        public void FunctionsFieldsAndProperties2()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new SubtractProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(-1, c.op(c.a, c.b), "1 - 2 == -1");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties2_WithCatalog()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            ConsumerOfMultiple c = new ConsumerOfMultiple();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(c);
            container.Compose(batch);

            foreach (var export in c.opInfo)
            {
                if ((string)export.Metadata["Var1"] == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if ((string)export.Metadata["Var1"] == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

#if !SILVERLIGHT
		// Silverlight doesn't support strongly typed metadata
        [TestMethod]
        public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

        [TestMethod]
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
            
            IDictionary<string, object> multMetadata = new Dictionary<string, object>();
            multMetadata["Var1"]= "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func<int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func<int, int, int>)delegate(int a, int b) { return a * b; }));

            CompositionBatch batch = new CompositionBatch();
            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            Assert.AreEqual(3, exports.Count(), "There should be 3 entries for 'Add'");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.AreEqual(2, export.Value(1, 2), "1 * 2 == 2");
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

		[Test]
		public void BasicUsageTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo<int[]> (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			Assert.IsFalse (evt.Wait (100));

			Assert.IsNull (array);

			Assert.IsTrue (buffer.Post (42));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (array);
			CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
		}

		[Test]
		public void TriggerBatchTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			evt.Wait ();

			Assert.IsNotNull (array);
			Assert.IsTrue (buffer.Post (42));
			evt.Wait (1600);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchLateBinding ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			buffer.LinkTo (block);

			evt.Wait ();
			Assert.IsNotNull (array);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void LateTriggerBatchKeepCountTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (15);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));
			buffer.TriggerBatch ();
			Assert.IsTrue (buffer.Post (42));
			buffer.LinkTo (block);

			evt.Wait ();

			Assert.IsNotNull (array);
			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchWhenEmpty ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (5,
				new GroupingDataflowBlockOptions { TaskScheduler = scheduler });
			block.TriggerBatch ();

			scheduler.ExecuteAll ();

			int[] batch;
			Assert.IsFalse (block.TryReceive (out batch));
			Assert.IsNull (batch);
		}

		[Test]
		public void NonGreedyBatchWithBoundedCapacityTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (2,
				new GroupingDataflowBlockOptions
				{ Greedy = false, BoundedCapacity = 2, TaskScheduler = scheduler });
			var source1 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source2 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			Assert.IsNotNull (source1.LinkTo (block));
			Assert.IsNotNull (source2.LinkTo (block));

			Assert.IsTrue (source1.Post (11));
			Assert.IsTrue (source2.Post (21));

			scheduler.ExecuteAll ();

			Assert.IsTrue (source1.Post (12));
			Assert.IsTrue (source2.Post (22));

			scheduler.ExecuteAll ();

			int i;
			Assert.IsTrue (source1.TryReceive (out i));
			Assert.AreEqual (12, i);

			Assert.IsTrue (source1.Post (13));

			int[] batch;
			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);

			scheduler.ExecuteAll ();

			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 13, 22 }, batch);
		}

            public void OnImportsSatisfied()
            {
                this.ImportsSatisfiedInvoked = true;
            }

        [TestMethod]
        public void ImportsSatisfiedOnComponentWithoutImports()
        {
            CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));

            PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
            Assert.IsNotNull(partWithoutImports);

            Assert.IsTrue(partWithoutImports.ImportsSatisfiedInvoked);

        }

        [TestMethod()]
        public void ImportCompletedTest()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");
        }

        [TestMethod]
        public void ImportCompletedWithRecomposing()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");

            // Add another component to verify recomposing
            batch = new CompositionBatch();
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.LowerCaseStrings[1].Value.String, "def");
            Assert.AreEqual(entrypoint.UpperCaseStrings[1], "DEF");

            // Verify that adding a random component doesn't cause
            // the OnImportsSatisfied to be called again.
            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(700940)]
        public void ImportCompletedUsingSatisfyImportsOnce()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();
            var entrypointPart = AttributedModelServices.CreatePart(entrypoint);

            batch.AddParts(new LowerCaseString("abc"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);

            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(2, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(2, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(2, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            Assert.AreEqual("def", entrypoint.LowerCaseStrings[1].Value.String);
            Assert.AreEqual("DEF", entrypoint.UpperCaseStrings[1]);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(654513)]
        public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
        {
            int importSatisfationCount = 0;
            var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
            var importer2 = new MyEventDrivenFullComposedNotifyImporter2();

            Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
            {
                Assert.IsTrue(importer1.AreAllImportsFullyComposed);
                Assert.IsTrue(importer2.AreAllImportsFullyComposed);
                ++importSatisfationCount;
            };

            importer1.ImportsSatisfied += new EventHandler(verificationAction);
            importer2.ImportsSatisfied += new EventHandler(verificationAction);

            // importer1 added first
            var batch = new CompositionBatch();
            batch.AddParts(importer1, importer2);

            var container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);

            // importer2 added first
            importSatisfationCount = 0;
            batch = new CompositionBatch();
            batch.AddParts(importer2, importer1);

            container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);
        }


        public void LoadAllTextures(ContentManager content)
        {
            collectableSpriteSheet = content.Load<Texture2D>("ItemSpriteSheet");
        }

        public ICollectable CreateArrowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableArrowSprite(spriteBatch, location);
        }

        public ICollectable CreateBigHeartSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBigHeartSprite(spriteBatch, location);
        }

        public ICollectable CreateBombSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBombSprite(spriteBatch, location);
        }

        public ICollectable CreateBoomerangSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBoomerangSprite(spriteBatch, location);
        }

        public ICollectable CreateBowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBowSprite(spriteBatch, location);
        }


		/// <summary>
		/// Returns whether a new item can be accepted, and increments a counter if it can.
		/// </summary>
		bool TryAdd ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (options.MaxNumberOfGroups != -1
				    && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
					return false;

				batchCount++;
				return true;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}
		}

		/// <summary>
		/// Decides whether to create a new batch or not.
		/// </summary>
		void SignalTarget ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (batchCount < BatchSize)
					return;

				batchCount -= BatchSize;
				numberOfGroups++;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}

			MakeBatch (BatchSize);
		}

		/// <summary>
		/// Creates a batch of the given size and adds the resulting batch to the output queue.
		/// </summary>
		void MakeBatch (int batchSize)
		{
			if (batchSize == 0)
				return;

			var list1 = new List<T1> ();
			var list2 = new List<T2> ();
			
			// lock is necessary here to make sure items are in the correct order
			bool taken = false;
			try {
				batchLock.Enter (ref taken);

				int i = 0;

				T1 item1;
				while (i < batchSize && target1.Buffer.TryTake (out item1)) {
					list1.Add (item1);
					i++;
				}

				T2 item2;
				while (i < batchSize && target2.Buffer.TryTake (out item2)) {
					list2.Add (item2);
					i++;
				}

				if (i < batchSize)
					throw new InvalidOperationException("Unexpected count of items.");
			} finally {
				if (taken)
					batchLock.Exit ();
			}

			var batch = Tuple.Create<IList<T1>, IList<T2>> (list1, list2);

			outgoing.AddData (batch);

			VerifyMaxNumberOfGroups ();
		}

		/// <summary>
		/// Verifies whether <see cref="GroupingDataflowBlockOptions.MaxNumberOfGroups"/>
		/// has been reached. If it did, <see cref="Complete"/>s the block.
		/// </summary>
		void VerifyMaxNumberOfGroups ()
		{
			if (options.MaxNumberOfGroups == -1)
				return;

			bool shouldComplete;

			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			if (shouldComplete)
				Complete ();
		}

		public void Complete ()
		{
			target1.Complete ();
			target2.Complete ();
			MakeBatch (batchCount);
			outgoing.Complete ();
		}

		void IDataflowBlock.Fault (Exception exception)
		{
			completionHelper.RequestFault (exception);
		}

GlobalLink.Connect.SubmissionServiceRef.Batch : INotifyPropertyChanged

Constructors :

public Batch()

Methods :

public String get_name()
public Void set_name(String value = )
public String[] get_targetLanguages()
public Void set_targetLanguages(String[] value = )
public WorkflowDefinition get_workflowDefinition()
public Void set_workflowDefinition(WorkflowDefinition value = )
public Void add_PropertyChanged(PropertyChangedEventHandler value = )
public Void remove_PropertyChanged(PropertyChangedEventHandler value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Batch

We found 10 examples in language CSharp for this search. You will see 60 fragments of code.

Other methods

        [TestMethod]
        public void Constructor1_PropertiesShouldBeSetAndEmpty()
        {
            CompositionBatch batch = new CompositionBatch();

            Assert.IsNotNull(batch.PartsToAdd);
            EnumerableAssert.IsEmpty(batch.PartsToAdd);

            Assert.IsNotNull(batch.PartsToRemove);
            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }


        [TestMethod]
        public void Constructor2_PartsToAddAsNull_PartsToAddShouldBeEmpty()
        {
            ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(null, partsToRemove);

            Assert.AreEqual(0, batch.PartsToAdd.Count);
            Assert.AreEqual(partsToRemove.Length, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void Constructor2_PartsToRemoveAsNull_PartsToRemoveShouldBeEmpty()
        {
            ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(partsToAdd, null);

            Assert.AreEqual(partsToAdd.Length, batch.PartsToAdd.Count);
            Assert.AreEqual(0, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void AddPart_PartIsInPartsToAdd()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.AddPart(part);

            Assert.AreEqual(1, batch.PartsToAdd.Count);
            Assert.AreSame(part, batch.PartsToAdd[0]);

            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }

        [TestMethod]
        public void AddPart_PartAsNull_ShouldThrowArgumentNullException()
        {
            CompositionBatch batch = new CompositionBatch();

            ExceptionAssert.ThrowsArgument<ArgumentNullException>("part", () =>
            {
                batch.AddPart(null);
            });
        }

        [TestMethod]
        public void RemovePart_PartIsInPartsToRemove()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.RemovePart(part);

            Assert.AreEqual(1, batch.PartsToRemove.Count);
            Assert.AreSame(part, batch.PartsToRemove[0]);

            EnumerableAssert.IsEmpty(batch.PartsToAdd);
        }

            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }
            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }

        [TestMethod]
        public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer()
        {
            var container = new CompositionContainer();
            var disposablePart = new AnyPartDisposable();
            var batch = new CompositionBatch();
            batch.AddPart(batch);
            container.Compose(batch);

            container.Dispose();
            Assert.IsFalse(disposablePart.IsDisposed);
        }

        [TestMethod]
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part = AttributedModelServices.CreatePart(disposable);
            var batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports<AnyPartDisposable>();
            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }

        [TestMethod]
        public void AnyPart_Simple_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartSimple));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartSimple>());

            refTracker.CollectAndAssert();

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void AnyPart_Disposable_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartDisposable));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartDisposable>());

            GC.KeepAlive(container);
        }

        internal static ArgumentException Argument(string message, string parameterName)
        {
            return Trace(new ArgumentException(message, parameterName));
        }

        internal static InvalidOperationException InvalidOperation(string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        internal static InvalidOperationException InvalidOperation(string message, Exception innerException)
        {
            return Trace(new InvalidOperationException(message, innerException));
        }

        internal static NotSupportedException NotSupported(string message)
        {
            return Trace(new NotSupportedException(message));
        }

        internal static void ThrowObjectDisposed(Type type)
        {
            throw Trace(new ObjectDisposedException(type.ToString()));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801", Justification = "errorCode ignored for code sharing")]
        internal static InvalidOperationException HttpHeaderFailure(int errorCode, string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        [TestMethod]
        public void RepeatedContainerUse()
        {
            var container = ContainerFactory.Create();
            TrivialExporter e = new TrivialExporter();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(e);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(new TrivialImporter());
            container.Compose(batch);

            Assert.IsTrue(e.done, "Initialization of importer should have set the done flag on E");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new RealAddProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(3, c.op(c.a, c.b), "1 + 2 == 3");
        }
        [TestMethod]
        public void FunctionsFieldsAndProperties2()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new SubtractProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(-1, c.op(c.a, c.b), "1 - 2 == -1");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties2_WithCatalog()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            ConsumerOfMultiple c = new ConsumerOfMultiple();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(c);
            container.Compose(batch);

            foreach (var export in c.opInfo)
            {
                if ((string)export.Metadata["Var1"] == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if ((string)export.Metadata["Var1"] == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

#if !SILVERLIGHT
		// Silverlight doesn't support strongly typed metadata
        [TestMethod]
        public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

        [TestMethod]
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
            
            IDictionary<string, object> multMetadata = new Dictionary<string, object>();
            multMetadata["Var1"]= "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func<int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func<int, int, int>)delegate(int a, int b) { return a * b; }));

            CompositionBatch batch = new CompositionBatch();
            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            Assert.AreEqual(3, exports.Count(), "There should be 3 entries for 'Add'");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.AreEqual(2, export.Value(1, 2), "1 * 2 == 2");
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

		[Test]
		public void BasicUsageTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo<int[]> (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			Assert.IsFalse (evt.Wait (100));

			Assert.IsNull (array);

			Assert.IsTrue (buffer.Post (42));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (array);
			CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
		}

		[Test]
		public void TriggerBatchTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			evt.Wait ();

			Assert.IsNotNull (array);
			Assert.IsTrue (buffer.Post (42));
			evt.Wait (1600);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchLateBinding ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			buffer.LinkTo (block);

			evt.Wait ();
			Assert.IsNotNull (array);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void LateTriggerBatchKeepCountTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (15);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));
			buffer.TriggerBatch ();
			Assert.IsTrue (buffer.Post (42));
			buffer.LinkTo (block);

			evt.Wait ();

			Assert.IsNotNull (array);
			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchWhenEmpty ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (5,
				new GroupingDataflowBlockOptions { TaskScheduler = scheduler });
			block.TriggerBatch ();

			scheduler.ExecuteAll ();

			int[] batch;
			Assert.IsFalse (block.TryReceive (out batch));
			Assert.IsNull (batch);
		}

		[Test]
		public void NonGreedyBatchWithBoundedCapacityTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (2,
				new GroupingDataflowBlockOptions
				{ Greedy = false, BoundedCapacity = 2, TaskScheduler = scheduler });
			var source1 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source2 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			Assert.IsNotNull (source1.LinkTo (block));
			Assert.IsNotNull (source2.LinkTo (block));

			Assert.IsTrue (source1.Post (11));
			Assert.IsTrue (source2.Post (21));

			scheduler.ExecuteAll ();

			Assert.IsTrue (source1.Post (12));
			Assert.IsTrue (source2.Post (22));

			scheduler.ExecuteAll ();

			int i;
			Assert.IsTrue (source1.TryReceive (out i));
			Assert.AreEqual (12, i);

			Assert.IsTrue (source1.Post (13));

			int[] batch;
			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);

			scheduler.ExecuteAll ();

			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 13, 22 }, batch);
		}

            public void OnImportsSatisfied()
            {
                this.ImportsSatisfiedInvoked = true;
            }

        [TestMethod]
        public void ImportsSatisfiedOnComponentWithoutImports()
        {
            CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));

            PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
            Assert.IsNotNull(partWithoutImports);

            Assert.IsTrue(partWithoutImports.ImportsSatisfiedInvoked);

        }

        [TestMethod()]
        public void ImportCompletedTest()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");
        }

        [TestMethod]
        public void ImportCompletedWithRecomposing()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");

            // Add another component to verify recomposing
            batch = new CompositionBatch();
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.LowerCaseStrings[1].Value.String, "def");
            Assert.AreEqual(entrypoint.UpperCaseStrings[1], "DEF");

            // Verify that adding a random component doesn't cause
            // the OnImportsSatisfied to be called again.
            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(700940)]
        public void ImportCompletedUsingSatisfyImportsOnce()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();
            var entrypointPart = AttributedModelServices.CreatePart(entrypoint);

            batch.AddParts(new LowerCaseString("abc"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);

            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(2, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(2, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(2, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            Assert.AreEqual("def", entrypoint.LowerCaseStrings[1].Value.String);
            Assert.AreEqual("DEF", entrypoint.UpperCaseStrings[1]);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(654513)]
        public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
        {
            int importSatisfationCount = 0;
            var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
            var importer2 = new MyEventDrivenFullComposedNotifyImporter2();

            Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
            {
                Assert.IsTrue(importer1.AreAllImportsFullyComposed);
                Assert.IsTrue(importer2.AreAllImportsFullyComposed);
                ++importSatisfationCount;
            };

            importer1.ImportsSatisfied += new EventHandler(verificationAction);
            importer2.ImportsSatisfied += new EventHandler(verificationAction);

            // importer1 added first
            var batch = new CompositionBatch();
            batch.AddParts(importer1, importer2);

            var container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);

            // importer2 added first
            importSatisfationCount = 0;
            batch = new CompositionBatch();
            batch.AddParts(importer2, importer1);

            container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);
        }


        public void LoadAllTextures(ContentManager content)
        {
            collectableSpriteSheet = content.Load<Texture2D>("ItemSpriteSheet");
        }

        public ICollectable CreateArrowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableArrowSprite(spriteBatch, location);
        }

        public ICollectable CreateBigHeartSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBigHeartSprite(spriteBatch, location);
        }

        public ICollectable CreateBombSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBombSprite(spriteBatch, location);
        }

        public ICollectable CreateBoomerangSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBoomerangSprite(spriteBatch, location);
        }

        public ICollectable CreateBowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBowSprite(spriteBatch, location);
        }


		/// <summary>
		/// Returns whether a new item can be accepted, and increments a counter if it can.
		/// </summary>
		bool TryAdd ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (options.MaxNumberOfGroups != -1
				    && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
					return false;

				batchCount++;
				return true;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}
		}

		/// <summary>
		/// Decides whether to create a new batch or not.
		/// </summary>
		void SignalTarget ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (batchCount < BatchSize)
					return;

				batchCount -= BatchSize;
				numberOfGroups++;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}

			MakeBatch (BatchSize);
		}

		/// <summary>
		/// Creates a batch of the given size and adds the resulting batch to the output queue.
		/// </summary>
		void MakeBatch (int batchSize)
		{
			if (batchSize == 0)
				return;

			var list1 = new List<T1> ();
			var list2 = new List<T2> ();
			
			// lock is necessary here to make sure items are in the correct order
			bool taken = false;
			try {
				batchLock.Enter (ref taken);

				int i = 0;

				T1 item1;
				while (i < batchSize && target1.Buffer.TryTake (out item1)) {
					list1.Add (item1);
					i++;
				}

				T2 item2;
				while (i < batchSize && target2.Buffer.TryTake (out item2)) {
					list2.Add (item2);
					i++;
				}

				if (i < batchSize)
					throw new InvalidOperationException("Unexpected count of items.");
			} finally {
				if (taken)
					batchLock.Exit ();
			}

			var batch = Tuple.Create<IList<T1>, IList<T2>> (list1, list2);

			outgoing.AddData (batch);

			VerifyMaxNumberOfGroups ();
		}

		/// <summary>
		/// Verifies whether <see cref="GroupingDataflowBlockOptions.MaxNumberOfGroups"/>
		/// has been reached. If it did, <see cref="Complete"/>s the block.
		/// </summary>
		void VerifyMaxNumberOfGroups ()
		{
			if (options.MaxNumberOfGroups == -1)
				return;

			bool shouldComplete;

			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			if (shouldComplete)
				Complete ();
		}

		public void Complete ()
		{
			target1.Complete ();
			target2.Complete ();
			MakeBatch (batchCount);
			outgoing.Complete ();
		}

		void IDataflowBlock.Fault (Exception exception)
		{
			completionHelper.RequestFault (exception);
		}


		/// <summary>
		/// Returns whether a new item can be accepted, and increments a counter if it can.
		/// </summary>
		bool TryAdd ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (options.MaxNumberOfGroups != -1
				    && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
					return false;

				batchCount++;
				return true;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}
		}

		/// <summary>
		/// Decides whether to create a new batch or not.
		/// </summary>
		void SignalTarget ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (batchCount < BatchSize)
					return;

				batchCount -= BatchSize;
				numberOfGroups++;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			MakeBatch (BatchSize);
		}

		/// <summary>
		/// Creates a batch of the given size and adds the resulting batch to the output queue.
		/// </summary>
		void MakeBatch (int batchSize)
		{
			if (batchSize == 0)
				return;

			var list1 = new List<T1> ();
			var list2 = new List<T2> ();
			var list3 = new List<T3> ();

			// lock is necessary here to make sure items are in the correct order
			bool taken = false;
			try {
				batchLock.Enter (ref taken);

				int i = 0;

				T1 item1;
				while (i < batchSize && target1.Buffer.TryTake (out item1)) {
					list1.Add (item1);
					i++;
				}

				T2 item2;
				while (i < batchSize && target2.Buffer.TryTake (out item2)) {
					list2.Add (item2);
					i++;
				}

				T3 item3;
				while (i < batchSize && target3.Buffer.TryTake (out item3)) {
					list3.Add (item3);
					i++;
				}

				if (i < batchSize)
					throw new InvalidOperationException ("Unexpected count of items.");
			} finally {
				if (taken)
					batchLock.Exit ();
			}

			var batch = Tuple.Create<IList<T1>, IList<T2>, IList<T3>> (list1, list2,
				list3);

			outgoing.AddData (batch);

			VerifyMaxNumberOfGroups ();
		}

		/// <summary>
		/// Verifies whether <see cref="GroupingDataflowBlockOptions.MaxNumberOfGroups"/>
		/// has been reached. If it did, <see cref="Complete"/>s the block.
		/// </summary>
		void VerifyMaxNumberOfGroups ()
		{
			if (options.MaxNumberOfGroups == -1)
				return;

			bool shouldComplete;

			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			if (shouldComplete)
				Complete ();
		}

		public void Complete ()
		{
			target1.Complete ();
			target2.Complete ();
			target3.Complete ();
			MakeBatch (batchCount);
			outgoing.Complete ();
		}

		void IDataflowBlock.Fault (Exception exception)
		{
			completionHelper.RequestFault (exception);
		}

        [TestMethod]
        public void SimpleConstructorInjection()
        {
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(PartFactory.CreateAttributed(typeof(SimpleConstructorInjectedObject)));
            batch.AddExportedValue("CISimpleValue", 42);
            container.Compose(batch);

            SimpleConstructorInjectedObject simple = container.GetExportedValue<SimpleConstructorInjectedObject>();

            Assert.AreEqual(42, simple.CISimpleValue);
        }

        [TestMethod]
        public void OptionalConstructorArgument()
        {
            var container = GetContainerWithCatalog();
            var a = container.GetExportedValue<AWithOptionalParameter>();

            // A should verify that it receieved optional arugments properly
            Assert.IsNotNull(a);
        }

        [TestMethod]
        public void RebindingShouldNotHappenForConstructorArguments()
        {
            var container = GetContainerWithCatalog();
            CompositionBatch batch = new CompositionBatch();

            var p1 = batch.AddExportedValue("MyConstructorCollectionItem", 1);
            batch.AddExportedValue("MyConstructorCollectionItem", 2);
            batch.AddExportedValue("MyConstructorCollectionItem", 3);
            container.Compose(batch);

            var a = container.GetExportedValue<AWithCollectionArgument>();

            EnumerableAssert.AreEqual(a.Values, 1, 2, 3);

            batch = new CompositionBatch();
            batch.AddExportedValue("MyConstructorCollectionItem", 4);
            batch.AddExportedValue("MyConstructorCollectionItem", 5);
            batch.AddExportedValue("MyConstructorCollectionItem", 6);
            // After rejection changes that are incompatible with existing assumptions are no
            // longer silently ignored.  The batch attempting to make this change is rejected
            // with a ChangeRejectedException
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport,() =>
            {
                container.Compose(batch);
            });

            // The collection which is a constructor import should not be rebound
            EnumerableAssert.AreEqual(a.Values, 1, 2, 3);

            batch.RemovePart(p1);
            // After rejection changes that are incompatible with existing assumptions are no
            // longer silently ignored.  The batch attempting to make this change is rejected
            // with a ChangeRejectedException
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            // The collection which is a constructor import should not be rebound
            EnumerableAssert.AreEqual(a.Values, 1, 2, 3);
        }

        [TestMethod]
        public void MissingConstructorArgsWithAlreadyCreatedInstance()
        {
            var container = GetContainerWithCatalog();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new ClassWithNotFoundConstructorArgs(21));
            container.Compose(batch);
        }

        [TestMethod]
        public void MissingConstructorArgsWithTypeFromCatalogMissingArg()
        {
            var container = GetContainerWithCatalog();

            // After rejection part definitions in catalogs whose dependencies cannot be
            // satisfied are now silently ignored, turning this into a cardinality
            // exception for the GetExportedValue call
            ExceptionAssert.Throws<ImportCardinalityMismatchException>(() =>
            {
                container.GetExportedValue<ClassWithNotFoundConstructorArgs>();
            });
        }

        [TestMethod]
        public void MissingConstructorArgsWithWithTypeFromCatalogWithArg()
        {
            var container = GetContainerWithCatalog();
            CompositionBatch batch = new CompositionBatch();
            batch.AddExportedValue("ContractThatDoesntExist", 21);
            container.Compose(batch);

            Assert.IsTrue(container.IsPresent<ClassWithNotFoundConstructorArgs>());
        }

GlobalLink.Connect.DocumentServiceRef.Batch : INotifyPropertyChanged

Constructors :

public Batch()

Methods :

public String get_name()
public Void set_name(String value = )
public String[] get_targetLanguages()
public Void set_targetLanguages(String[] value = )
public WorkflowDefinition get_workflowDefinition()
public Void set_workflowDefinition(WorkflowDefinition value = )
public Void add_PropertyChanged(PropertyChangedEventHandler value = )
public Void remove_PropertyChanged(PropertyChangedEventHandler value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods

Batch

We found 10 examples in language CSharp for this search. You will see 60 fragments of code.
        [TestMethod]
        public void Constructor1_PropertiesShouldBeSetAndEmpty()
        {
            CompositionBatch batch = new CompositionBatch();

            Assert.IsNotNull(batch.PartsToAdd);
            EnumerableAssert.IsEmpty(batch.PartsToAdd);

            Assert.IsNotNull(batch.PartsToRemove);
            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }


        [TestMethod]
        public void Constructor2_PartsToAddAsNull_PartsToAddShouldBeEmpty()
        {
            ComposablePart[] partsToRemove = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(null, partsToRemove);

            Assert.AreEqual(0, batch.PartsToAdd.Count);
            Assert.AreEqual(partsToRemove.Length, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void Constructor2_PartsToRemoveAsNull_PartsToRemoveShouldBeEmpty()
        {
            ComposablePart[] partsToAdd = new ComposablePart[] { PartFactory.Create(), PartFactory.Create(), PartFactory.Create() };

            var batch = new CompositionBatch(partsToAdd, null);

            Assert.AreEqual(partsToAdd.Length, batch.PartsToAdd.Count);
            Assert.AreEqual(0, batch.PartsToRemove.Count);
        }

        [TestMethod]
        public void AddPart_PartIsInPartsToAdd()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.AddPart(part);

            Assert.AreEqual(1, batch.PartsToAdd.Count);
            Assert.AreSame(part, batch.PartsToAdd[0]);

            EnumerableAssert.IsEmpty(batch.PartsToRemove);
        }

        [TestMethod]
        public void AddPart_PartAsNull_ShouldThrowArgumentNullException()
        {
            CompositionBatch batch = new CompositionBatch();

            ExceptionAssert.ThrowsArgument<ArgumentNullException>("part", () =>
            {
                batch.AddPart(null);
            });
        }

        [TestMethod]
        public void RemovePart_PartIsInPartsToRemove()
        {
            CompositionBatch batch = new CompositionBatch();
            ComposablePart part = PartFactory.Create();

            batch.RemovePart(part);

            Assert.AreEqual(1, batch.PartsToRemove.Count);
            Assert.AreSame(part, batch.PartsToRemove[0]);

            EnumerableAssert.IsEmpty(batch.PartsToAdd);
        }


		DataflowMessageStatus ITargetBlock<T>.OfferMessage (
			DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source,
			bool consumeToAccept)
		{
			return messageBox.OfferMessage (
				messageHeader, messageValue, source, consumeToAccept);
		}

		public IDisposable LinkTo (ITargetBlock<T[]> target, DataflowLinkOptions linkOptions)
		{
			return outgoing.AddTarget (target, linkOptions);
		}

		T[] ISourceBlock<T[]>.ConsumeMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target,
			out bool messageConsumed)
		{
			return outgoing.ConsumeMessage (messageHeader, target, out messageConsumed);
		}

		void ISourceBlock<T[]>.ReleaseReservation (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			outgoing.ReleaseReservation (messageHeader, target);
		}

		bool ISourceBlock<T[]>.ReserveMessage (
			DataflowMessageHeader messageHeader, ITargetBlock<T[]> target)
		{
			return outgoing.ReserveMessage (messageHeader, target);
		}

		public bool TryReceive (Predicate<T[]> filter, out T[] item)
		{
			return outgoing.TryReceive (filter, out item);
		}


        [TestMethod]
        public void Import_OptIn_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptIn_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value, "Value should have changed!");
        }

        [TestMethod]
        public void Import_OptOut_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_OptOut_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_Default_AllowRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_Default_AllowRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose Value should be 21
            Assert.AreEqual(21, importer.Value);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value = -21; 

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.Value, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_BothOptInAndOptOutRecomposition()
        {
            var container = new CompositionContainer();
            var importer = new Class_BothOptInAndOptOutRecompositionImports();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var valueKey = batch.AddExportedValue("Value", 21);
            container.Compose(batch);

            // Initial compose values should be 21
            Assert.AreEqual(21, importer.RecomposableValue);
            Assert.AreEqual(21, importer.NonRecomposableValue);

            // Reset value to ensure it doesn't get set to same value again
            importer.NonRecomposableValue = -21;
            importer.RecomposableValue = -21;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(valueKey);
            batch.AddExportedValue("Value", 42);
            // After rejection batch failures throw ChangeRejectedException to indicate that
            // the failure did not affect the container
            CompositionAssert.ThrowsChangeRejectedError(ErrorId.ImportEngine_PreventedByExistingImport, () =>
            {
                container.Compose(batch);
            });

            Assert.AreEqual(-21, importer.NonRecomposableValue, "Value should NOT have changed!");
            // The batch rejection means that the recomposable value shouldn't change either
            Assert.AreEqual(-21, importer.RecomposableValue, "Value should NOT have changed!");
        }

        [TestMethod]
        public void Import_OptInRecomposition_Multlple()
        {
            var container = new CompositionContainer();
            var importer = new Class_MultipleOptInRecompositionImportsWithDifferentContracts();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(importer);
            var value1Key = batch.AddExportedValue("Value1", 21);
            var value2Key = batch.AddExportedValue("Value2", 23);
            container.Compose(batch);

            Assert.AreEqual(21, importer.Value1);
            Assert.AreEqual(23, importer.Value2);

            // Reset value to ensure it doesn't get set to same value again
            importer.Value1 = -21;
            importer.Value2 = -23;

            // Recompose Value to be 42
            batch = new CompositionBatch();
            batch.RemovePart(value1Key);
            batch.AddExportedValue("Value1", 42);
            container.Compose(batch);

            Assert.AreEqual(42, importer.Value1, "Value should have changed!");
            Assert.AreEqual(-23, importer.Value2, "Value should NOT have changed because Value2 contract should not be updated.");
        }

        [TestMethod]
        public void Recomposition_IntegrationTest()
        {
            var container = new CompositionContainer();
            var batch = new CompositionBatch();

            var me = new Me();
            batch.AddPart(me);
            var namePart = batch.AddPart(new MyName("Blake"));
            batch.AddPart(new Spouse("Barbara"));
            batch.AddPart(new Friend("Steve"));
            batch.AddPart(new Friend("Joyce"));
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blake", "Name in initial composition incorrect");
            Assert.AreEqual(me.Job, null, "Job should have the default value");
            Assert.AreEqual(me.Friends.Length, 3, "Number of friends in initial composition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives in initial composition incorrect");
            Assert.AreEqual(me.Children.Length, 0, "Number of children in initial composition incorrect");

            // Can only have one name
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new MyName("Blayke")));

            batch = new CompositionBatch();
            batch.AddPart(new MyName("Blayke"));
            batch.RemovePart(namePart);
            container.Compose(batch);
            Assert.AreEqual(me.Name, "Blayke", "Name after recomposition incorrect");

            batch = new CompositionBatch();
            var jobPart = batch.AddPart(new Job("Architect"));
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Architect", "Job after recomposition incorrect");

            batch = new CompositionBatch();
            batch.AddPart(new Job("Chimney Sweep"));
            container.Compose(batch);
            Assert.IsTrue(me.Job == null, "More than one of an optional import should result in the default value");

            batch = new CompositionBatch();
            batch.RemovePart(jobPart);
            container.Compose(batch);
            Assert.AreEqual(me.Job, "Chimney Sweep", "Job after re-recomposition incorrect");

            batch = new CompositionBatch();

            // Can only have one spouse because they aren't recomposable
            ExceptionAssert.Throws<ChangeRejectedException>(() =>
                container.ComposeParts(new Spouse("Cameron")));

            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");

            batch = new CompositionBatch();
            batch.AddPart(new Friend("Graham"));
            container.Compose(batch);
            Assert.AreEqual(me.Friends.Length, 4, "Number of friends after recomposition incorrect");
            Assert.AreEqual(me.Relatives.Length, 1, "Number of relatives shouldn't be affected by rolled back composition");
        }

        internal static ArgumentException Argument(string message, string parameterName)
        {
            return Trace(new ArgumentException(message, parameterName));
        }

        internal static InvalidOperationException InvalidOperation(string message)
        {
            return Trace(new InvalidOperationException(message));
        }

        internal static InvalidOperationException InvalidOperation(string message, Exception innerException)
        {
            return Trace(new InvalidOperationException(message, innerException));
        }

        internal static NotSupportedException NotSupported(string message)
        {
            return Trace(new NotSupportedException(message));
        }

        internal static void ThrowObjectDisposed(Type type)
        {
            throw Trace(new ObjectDisposedException(type.ToString()));
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801", Justification = "errorCode ignored for code sharing")]
        internal static InvalidOperationException HttpHeaderFailure(int errorCode, string message)
        {
            return Trace(new InvalidOperationException(message));
        }

            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }
            public void Dispose()
            {
                Assert.IsFalse(IsDisposed);
                IsDisposed = true;
            }

        [TestMethod]
        public void PartAddedViaAddExportedValue_ShouldNotBeDisposedWithContainer()
        {
            var container = new CompositionContainer();
            var disposablePart = new AnyPartDisposable();
            var batch = new CompositionBatch();
            batch.AddPart(batch);
            container.Compose(batch);

            container.Dispose();
            Assert.IsFalse(disposablePart.IsDisposed);
        }

        [TestMethod]
        public void PartAddedTwice_AppearsTwice()
        {
            //  You probably shouldn't be adding a part to the container twice, but it's not something we're going to check for and throw an exception on
            var container = new CompositionContainer();
            var disposable = new AnyPartDisposable();
            var part = AttributedModelServices.CreatePart(disposable);
            var batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(part);
            container.Compose(batch);

            var exports = container.GetExports<AnyPartDisposable>();
            Assert.AreEqual(2, exports.Count());

            container.Dispose();
        }

        [TestMethod]
        public void AnyPart_Simple_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartSimple));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartSimple>());

            refTracker.CollectAndAssert();

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void AnyPart_Disposable_ShouldNotBeCollected()
        {
            var catalog = new TypeCatalog(typeof(AnyPartDisposable));
            var container = new CompositionContainer(catalog);

            var refTracker = new ReferenceTracker();

            refTracker.AddReferencesNotExpectedToBeCollected(
                container.GetExportedValue<AnyPartDisposable>());

            GC.KeepAlive(container);
        }

        [TestMethod]
        public void RepeatedContainerUse()
        {
            var container = ContainerFactory.Create();
            TrivialExporter e = new TrivialExporter();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(e);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddPart(new TrivialImporter());
            container.Compose(batch);

            Assert.IsTrue(e.done, "Initialization of importer should have set the done flag on E");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new RealAddProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(3, c.op(c.a, c.b), "1 + 2 == 3");
        }
        [TestMethod]
        public void FunctionsFieldsAndProperties2()
        {
            Consumer c;
            var container = ContainerFactory.Create();

            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(new SubtractProvider());
            batch.AddPart(c = new Consumer());
            container.Compose(batch);

            Assert.AreEqual(-1, c.op(c.a, c.b), "1 - 2 == -1");
        }

        [TestMethod]
        public void FunctionsFieldsAndProperties2_WithCatalog()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            ConsumerOfMultiple c = new ConsumerOfMultiple();
            CompositionBatch batch = new CompositionBatch();
            batch.AddPart(c);
            container.Compose(batch);

            foreach (var export in c.opInfo)
            {
                if ((string)export.Metadata["Var1"] == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if ((string)export.Metadata["Var1"] == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

#if !SILVERLIGHT
		// Silverlight doesn't support strongly typed metadata
        [TestMethod]
        public void FunctionsFieldsAndProperties2_StronglyTypedMetadata()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

        [TestMethod]
        public void InAdditionToCatalogTest()
        {
            var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
            
            IDictionary<string, object> multMetadata = new Dictionary<string, object>();
            multMetadata["Var1"]= "mult";
            multMetadata[CompositionConstants.ExportTypeIdentityMetadataName] = AttributedModelServices.GetTypeIdentity(typeof(Func<int, int, int>));
            var basicValue = ExportFactory.Create("Add", multMetadata, (() => (Func<int, int, int>)delegate(int a, int b) { return a * b; }));

            CompositionBatch batch = new CompositionBatch();
            batch.AddExport(basicValue);
            container.Compose(batch);

            var exports = container.GetExports<Func<int, int, int>, IExportableTest>("Add");

            Assert.AreEqual(3, exports.Count(), "There should be 3 entries for 'Add'");

            foreach (var export in exports)
            {
                if (export.Metadata.Var1 == "mult")
                {
                    Assert.AreEqual(2, export.Value(1, 2), "1 * 2 == 2");
                }
                else if (export.Metadata.Var1 == "add")
                {
                    Assert.AreEqual(3, export.Value(1, 2), "1 + 2 == 3");
                }
                else if (export.Metadata.Var1 == "sub")
                {
                    Assert.AreEqual(-1, export.Value(1, 2), "1 - 2 == -1");
                }
                else
                {
                    Assert.Fail("Unexpected value");
                }
            }
        }

		[Test]
		public void BasicUsageTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo<int[]> (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			Assert.IsFalse (evt.Wait (100));

			Assert.IsNull (array);

			Assert.IsTrue (buffer.Post (42));
			Assert.IsTrue (evt.Wait (100));

			Assert.IsNotNull (array);
			CollectionAssert.AreEqual (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 42 }, array);
		}

		[Test]
		public void TriggerBatchTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});
			buffer.LinkTo (block);

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			evt.Wait ();

			Assert.IsNotNull (array);
			Assert.IsTrue (buffer.Post (42));
			evt.Wait (1600);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchLateBinding ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (10);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));

			buffer.TriggerBatch ();
			buffer.LinkTo (block);

			evt.Wait ();
			Assert.IsNotNull (array);

			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void LateTriggerBatchKeepCountTest ()
		{
			int[] array = null;
			var evt = new ManualResetEventSlim (false);

			var buffer = new BatchBlock<int> (15);
			var block = new ActionBlock<int[]> (i =>
			{
				array = i;
				evt.Set ();
			});

			for (int i = 0; i < 9; i++)
				Assert.IsTrue (buffer.Post (i));
			buffer.TriggerBatch ();
			Assert.IsTrue (buffer.Post (42));
			buffer.LinkTo (block);

			evt.Wait ();

			Assert.IsNotNull (array);
			CollectionAssert.AreEquivalent (new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 },
				array);
		}

		[Test]
		public void TriggerBatchWhenEmpty ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (5,
				new GroupingDataflowBlockOptions { TaskScheduler = scheduler });
			block.TriggerBatch ();

			scheduler.ExecuteAll ();

			int[] batch;
			Assert.IsFalse (block.TryReceive (out batch));
			Assert.IsNull (batch);
		}

		[Test]
		public void NonGreedyBatchWithBoundedCapacityTest ()
		{
			var scheduler = new TestScheduler ();
			var block = new BatchBlock<int> (2,
				new GroupingDataflowBlockOptions
				{ Greedy = false, BoundedCapacity = 2, TaskScheduler = scheduler });
			var source1 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source2 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			Assert.IsNotNull (source1.LinkTo (block));
			Assert.IsNotNull (source2.LinkTo (block));

			Assert.IsTrue (source1.Post (11));
			Assert.IsTrue (source2.Post (21));

			scheduler.ExecuteAll ();

			Assert.IsTrue (source1.Post (12));
			Assert.IsTrue (source2.Post (22));

			scheduler.ExecuteAll ();

			int i;
			Assert.IsTrue (source1.TryReceive (out i));
			Assert.AreEqual (12, i);

			Assert.IsTrue (source1.Post (13));

			int[] batch;
			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 11, 21 }, batch);

			scheduler.ExecuteAll ();

			Assert.IsTrue (block.TryReceive (out batch));
			CollectionAssert.AreEquivalent (new[] { 13, 22 }, batch);
		}

            public void OnImportsSatisfied()
            {
                this.ImportsSatisfiedInvoked = true;
            }

        [TestMethod]
        public void ImportsSatisfiedOnComponentWithoutImports()
        {
            CompositionContainer container = ContainerFactory.CreateWithAttributedCatalog(typeof(PartWithoutImports));

            PartWithoutImports partWithoutImports = container.GetExportedValue<PartWithoutImports>();
            Assert.IsNotNull(partWithoutImports);

            Assert.IsTrue(partWithoutImports.ImportsSatisfiedInvoked);

        }

        [TestMethod()]
        public void ImportCompletedTest()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");
        }

        [TestMethod]
        public void ImportCompletedWithRecomposing()
        {
            var container = ContainerFactory.Create(); 
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();

            batch.AddParts(new LowerCaseString("abc"), entrypoint);
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 1);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 1);
            Assert.AreEqual(entrypoint.LowerCaseStrings[0].Value.String, "abc");
            Assert.AreEqual(entrypoint.UpperCaseStrings[0], "ABC");

            // Add another component to verify recomposing
            batch = new CompositionBatch();
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.LowerCaseStrings[1].Value.String, "def");
            Assert.AreEqual(entrypoint.UpperCaseStrings[1], "DEF");

            // Verify that adding a random component doesn't cause
            // the OnImportsSatisfied to be called again.
            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);

            Assert.AreEqual(entrypoint.LowerCaseStrings.Count, 2);
            Assert.AreEqual(entrypoint.ImportCompletedCallCount, 2);
            Assert.AreEqual(entrypoint.UpperCaseStrings.Count, 2);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(700940)]
        public void ImportCompletedUsingSatisfyImportsOnce()
        {
            var container = ContainerFactory.Create();
            CompositionBatch batch = new CompositionBatch();
            var entrypoint = new UpperCaseStringComponent();
            var entrypointPart = AttributedModelServices.CreatePart(entrypoint);

            batch.AddParts(new LowerCaseString("abc"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);

            batch = new CompositionBatch();
            batch.AddParts(new object());
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);

            Assert.AreEqual(1, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(1, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(1, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            
            batch.AddParts(new LowerCaseString("def"));
            container.Compose(batch);
            container.SatisfyImportsOnce(entrypointPart);
            
            Assert.AreEqual(2, entrypoint.LowerCaseStrings.Count);
            Assert.AreEqual(2, entrypoint.ImportCompletedCallCount);
            Assert.AreEqual(2, entrypoint.UpperCaseStrings.Count);
            Assert.AreEqual("abc", entrypoint.LowerCaseStrings[0].Value.String);
            Assert.AreEqual("ABC", entrypoint.UpperCaseStrings[0]);
            Assert.AreEqual("def", entrypoint.LowerCaseStrings[1].Value.String);
            Assert.AreEqual("DEF", entrypoint.UpperCaseStrings[1]);
        }

        [TestMethod]
        [Ignore]
        [WorkItem(654513)]
        public void ImportCompletedCalledAfterAllImportsAreFullyComposed()
        {
            int importSatisfationCount = 0;
            var importer1 = new MyEventDrivenFullComposedNotifyImporter1();
            var importer2 = new MyEventDrivenFullComposedNotifyImporter2();

            Action<object, EventArgs> verificationAction = (object sender, EventArgs e) =>
            {
                Assert.IsTrue(importer1.AreAllImportsFullyComposed);
                Assert.IsTrue(importer2.AreAllImportsFullyComposed);
                ++importSatisfationCount;
            };

            importer1.ImportsSatisfied += new EventHandler(verificationAction);
            importer2.ImportsSatisfied += new EventHandler(verificationAction);

            // importer1 added first
            var batch = new CompositionBatch();
            batch.AddParts(importer1, importer2);

            var container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);

            // importer2 added first
            importSatisfationCount = 0;
            batch = new CompositionBatch();
            batch.AddParts(importer2, importer1);

            container = ContainerFactory.Create();
            container.ComposeExportedValue<ICompositionService>(container);
            container.Compose(batch);
            Assert.AreEqual(2, importSatisfationCount);
        }


        public void LoadAllTextures(ContentManager content)
        {
            collectableSpriteSheet = content.Load<Texture2D>("ItemSpriteSheet");
        }

        public ICollectable CreateArrowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableArrowSprite(spriteBatch, location);
        }

        public ICollectable CreateBigHeartSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBigHeartSprite(spriteBatch, location);
        }

        public ICollectable CreateBombSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBombSprite(spriteBatch, location);
        }

        public ICollectable CreateBoomerangSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBoomerangSprite(spriteBatch, location);
        }

        public ICollectable CreateBowSprite(SpriteBatch spriteBatch, Vector2 location)
        {
            return new CollectableBowSprite(spriteBatch, location);
        }


		/// <summary>
		/// Returns whether a new item can be accepted, and increments a counter if it can.
		/// </summary>
		bool TryAdd ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (options.MaxNumberOfGroups != -1
				    && numberOfGroups + batchCount / BatchSize >= options.MaxNumberOfGroups)
					return false;

				batchCount++;
				return true;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}
		}

		/// <summary>
		/// Decides whether to create a new batch or not.
		/// </summary>
		void SignalTarget ()
		{
			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				if (batchCount < BatchSize)
					return;

				batchCount -= BatchSize;
				numberOfGroups++;
			} finally {
				if (lockTaken)
					batchCountLock.Exit();
			}

			MakeBatch (BatchSize);
		}

		/// <summary>
		/// Creates a batch of the given size and adds the resulting batch to the output queue.
		/// </summary>
		void MakeBatch (int batchSize)
		{
			if (batchSize == 0)
				return;

			var list1 = new List<T1> ();
			var list2 = new List<T2> ();
			
			// lock is necessary here to make sure items are in the correct order
			bool taken = false;
			try {
				batchLock.Enter (ref taken);

				int i = 0;

				T1 item1;
				while (i < batchSize && target1.Buffer.TryTake (out item1)) {
					list1.Add (item1);
					i++;
				}

				T2 item2;
				while (i < batchSize && target2.Buffer.TryTake (out item2)) {
					list2.Add (item2);
					i++;
				}

				if (i < batchSize)
					throw new InvalidOperationException("Unexpected count of items.");
			} finally {
				if (taken)
					batchLock.Exit ();
			}

			var batch = Tuple.Create<IList<T1>, IList<T2>> (list1, list2);

			outgoing.AddData (batch);

			VerifyMaxNumberOfGroups ();
		}

		/// <summary>
		/// Verifies whether <see cref="GroupingDataflowBlockOptions.MaxNumberOfGroups"/>
		/// has been reached. If it did, <see cref="Complete"/>s the block.
		/// </summary>
		void VerifyMaxNumberOfGroups ()
		{
			if (options.MaxNumberOfGroups == -1)
				return;

			bool shouldComplete;

			bool lockTaken = false;
			try {
				batchCountLock.Enter (ref lockTaken);

				shouldComplete = numberOfGroups >= options.MaxNumberOfGroups;
			} finally {
				if (lockTaken)
					batchCountLock.Exit ();
			}

			if (shouldComplete)
				Complete ();
		}

		public void Complete ()
		{
			target1.Complete ();
			target2.Complete ();
			MakeBatch (batchCount);
			outgoing.Complete ();
		}

		void IDataflowBlock.Fault (Exception exception)
		{
			completionHelper.RequestFault (exception);
		}

GlobalLink.Connect.Model.Batch : Object

Fields :

public String[] targetLanguages
public Workflow workflow

Constructors :

public Batch(Batch batch = )

Methods :

public String get_name()
public Void set_name(String value = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()