public void Initialize(IServiceProvider serviceProvider)
 {
     if (Instance == null)
     {
         Instance = Factory(serviceProvider);
     }
 }
        private static DispatchMiddlewareContext CreateContext(TaskOrchestration activity)
        {
            var context = (DispatchMiddlewareContext)Activator.CreateInstance(typeof(DispatchMiddlewareContext), true);

            context.SetProperty(activity);
            return(context);
        }
        public void Create_WrapperCreated()
        {
            var descriptor = TaskOrchestrationDescriptor.Create <TestOrchestration>();
            var creator    = new OrchestrationObjectCreator(descriptor);
            TaskOrchestration Orchestration = creator.Create();

            Orchestration.Should().NotBeNull();
            Orchestration.Should().BeOfType <WrapperOrchestration>()
            .Which.Descriptor.Should().Be(descriptor);
        }
        async Task <T> Execute <T>(FakeOrchestrationContext context, string name, string version, object input)
        {
            OrchestrationInstance  instance = context.OrchestrationInstance;
            SynchronizationContext prevCtx  = SynchronizationContext.Current;

            try
            {
                TaskOrchestration definition = orchestrationObjectManager.GetObject(name, version);
                if (definition == null)
                {
                    throw new OrchestrationFrameworkException("Orchestration not found");
                }

                string        serializedInput      = dataConverter.Serialize(input);
                Task <string> serializedResultTask = definition.Execute(context, serializedInput);
                currentExecutions.Add(instance.InstanceId, definition);

                string serializedResult = null;
                try
                {
                    serializedResult = await serializedResultTask;
                }
                catch (OrchestrationFailureException e)
                {
                    Exception cause = Utils.RetrieveCause(e.Details, dataConverter);
                    var       subOrchestrationFailedException = new SubOrchestrationFailedException(0, 0, name, version,
                                                                                                    e.Message, cause);
                    throw subOrchestrationFailedException;
                }
                catch (Exception e)
                {
                    var subOrchestrationFailedException = new SubOrchestrationFailedException(0, 0, name, version,
                                                                                              e.Message, e);
                    throw subOrchestrationFailedException;
                }

                return(dataConverter.Deserialize <T>(serializedResult));
            }
            finally
            {
                SynchronizationContext.SetSynchronizationContext(prevCtx);
                TaskOrchestration orchestration = null;
                if (currentExecutions.TryGetValue(instance.InstanceId, out orchestration))
                {
                    currentExecutions.Remove(instance.InstanceId);
                    completedExecutions.Add(instance, orchestration);
                }
            }
        }
        public async Task DispatchMiddlewareContextBuiltInProperties()
        {
            TaskOrchestration         orchestration = null;
            OrchestrationRuntimeState state         = null;
            OrchestrationInstance     instance1     = null;

            TaskActivity          activity           = null;
            TaskScheduledEvent    taskScheduledEvent = null;
            OrchestrationInstance instance2          = null;

            this.worker.AddOrchestrationDispatcherMiddleware((context, next) =>
            {
                orchestration = context.GetProperty <TaskOrchestration>();
                state         = context.GetProperty <OrchestrationRuntimeState>();
                instance1     = context.GetProperty <OrchestrationInstance>();

                return(next());
            });

            this.worker.AddActivityDispatcherMiddleware((context, next) =>
            {
                activity           = context.GetProperty <TaskActivity>();
                taskScheduledEvent = context.GetProperty <TaskScheduledEvent>();
                instance2          = context.GetProperty <OrchestrationInstance>();

                return(next());
            });

            var instance = await this.client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), null);

            TimeSpan timeout = TimeSpan.FromSeconds(Debugger.IsAttached ? 1000 : 10);

            await this.client.WaitForOrchestrationAsync(instance, timeout);

            Assert.IsNotNull(orchestration);
            Assert.IsNotNull(state);
            Assert.IsNotNull(instance1);

            Assert.IsNotNull(activity);
            Assert.IsNotNull(taskScheduledEvent);
            Assert.IsNotNull(instance2);

            Assert.AreNotSame(instance1, instance2);
            Assert.AreEqual(instance1.InstanceId, instance2.InstanceId);
        }
        public void RaiseEvent(OrchestrationInstance instance, string eventName, object eventData)
        {
            if (instance == null || string.IsNullOrWhiteSpace(instance.InstanceId))
            {
                throw new ArgumentException("instance");
            }

            TaskOrchestration execution = null;

            if (!currentExecutions.TryGetValue(instance.InstanceId, out execution))
            {
                throw new OrchestrationFrameworkException("Unknown orchestration instance.  Id: " + instance.InstanceId);
            }

            string serializedInput = dataConverter.Serialize(eventData);

            execution.RaiseEvent(null, eventName, serializedInput);
        }
        public async Task InvokeAsync_NotWrapped_Continues()
        {
            // arrange
            var activity        = new TestOrchestration();
            var serviceProvider = new Mock <IServiceProvider>();
            DispatchMiddlewareContext context = CreateContext(activity);
            var middleware = new ServiceProviderOrchestrationMiddleware(serviceProvider.Object);

            // act
            await middleware.InvokeAsync(context, () => Task.CompletedTask);

            // assert
            TaskOrchestration actual = context.GetProperty <TaskOrchestration>();

            actual.Should().NotBeNull();
            actual.Should().Be(activity);
            serviceProvider.Verify(m => m.GetService(It.IsAny <Type>()), Times.Never);
        }
        public T GetStatus <T>(OrchestrationInstance instance)
        {
            if (instance == null || string.IsNullOrWhiteSpace(instance.InstanceId))
            {
                throw new ArgumentException("instance");
            }

            TaskOrchestration execution = null;

            if (!(currentExecutions.TryGetValue(instance.InstanceId, out execution) ||
                  completedExecutions.TryGetValue(instance, out execution)))
            {
                throw new OrchestrationFrameworkException("Unknown orchestration instance.  Id: " + instance.InstanceId);
            }

            string status = execution.GetStatus();

            return(dataConverter.Deserialize <T>(status));
        }
        public async Task InvokeAsync_Wrapped_SetsOrchestration()
        {
            // arrange
            var serviceProvider = new Mock <IServiceProvider>();

            serviceProvider.Setup(m => m.GetService(typeof(TestOrchestration))).Returns(new TestOrchestration());
            var wrapper = new WrapperOrchestration(new TaskOrchestrationDescriptor(typeof(TestOrchestration)));
            DispatchMiddlewareContext context = CreateContext(wrapper);
            var middleware = new ServiceProviderOrchestrationMiddleware(serviceProvider.Object);

            // act
            await middleware.InvokeAsync(context, () => Task.CompletedTask);

            // assert
            TaskOrchestration activity = context.GetProperty <TaskOrchestration>();

            activity.Should().NotBeNull();
            activity.Should().Be(wrapper.InnerOrchestration);
            serviceProvider.Verify(m => m.GetService(typeof(TestOrchestration)), Times.Once);
        }
        /// <inheritdoc />
        public async Task InvokeAsync(DispatchMiddlewareContext context, Func <Task> next)
        {
            Check.NotNull(context, nameof(context));
            Check.NotNull(next, nameof(next));

            TaskOrchestration taskOrchestration = context.GetProperty <TaskOrchestration>();

            if (taskOrchestration is WrapperOrchestration wrapper)
            {
                wrapper.Initialize(_serviceProvider);

                // update the context task orchestration with the real one.
                context.SetProperty(wrapper.InnerOrchestration);
                await next().ConfigureAwait(false);

                return;
            }

            await next().ConfigureAwait(false);
        }
Пример #11
0
        public string ReplayOrchestration(string name, string version, string serializedHistoryEvents)
        {
            TaskOrchestration taskOrchestration = this.orchestrationObjectManager.GetObject(name, version);

            IList <HistoryEvent> replayEvents = this.DeserializeHistoryEvents(serializedHistoryEvents);

            if (replayEvents.Any(re => re.EventType == EventType.GenericEvent))
            {
                throw new InvalidOperationException("Cannot replay with GenericEvent");
            }

            var runtimeState = new OrchestrationRuntimeState(this.DeserializeHistoryEvents(serializedHistoryEvents));

            TaskOrchestrationExecutor executor = new TaskOrchestrationExecutor(runtimeState, taskOrchestration);

            return(JsonConvert.SerializeObject(executor.Execute(), new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All,
                Formatting = Formatting.Indented
            }));
        }
Пример #12
0
        /// <summary>
        /// Creates the inner orchestration, setting <see cref="InnerOrchestration" />.
        /// </summary>
        /// <param name="serviceProvider">The service provider. Not null.</param>
        public void Initialize(IServiceProvider serviceProvider)
        {
            Check.NotNull(serviceProvider, nameof(serviceProvider));

            if (!s_factories.TryGetValue(Descriptor, out Func <IServiceProvider, TaskOrchestration> factory))
            {
                if (serviceProvider.GetService(Descriptor.Type) is TaskOrchestration orchestration)
                {
                    InnerOrchestration = orchestration;
                    s_factories.TryAdd(Descriptor, sp => (TaskOrchestration)sp.GetRequiredService(Descriptor.Type));
                    return; // already created it this time, so just return now.
                }
                else
                {
                    ObjectFactory objectFactory = ActivatorUtilities.CreateFactory(
                        Descriptor.Type, Array.Empty <Type>());
                    factory = s_factories.GetOrAdd(
                        Descriptor, sp => (TaskOrchestration)objectFactory.Invoke(sp, Array.Empty <object>()));
                }
            }

            InnerOrchestration = factory.Invoke(serviceProvider);
            return;
        }