Ejemplo n.º 1
0
        public async Task InitializeAsync(bool startWorker = true)
        {
            // The initialization requires administrative credentials (default)
            await new SqlOrchestrationService(this.OrchestrationServiceOptions).CreateIfNotExistsAsync();

            // Enable multitenancy to isolate each test using low-privilege credentials
            await this.EnableMultitenancyAsync();

            // The runtime will use low-privilege credentials
            string taskHubConnectionString = await this.CreateTaskHubLoginAsync();

            this.OrchestrationServiceOptions = new SqlOrchestrationServiceSettings(taskHubConnectionString)
            {
                LoggerFactory = this.loggerFactory,
            };

            this.OrchestrationServiceMock = new Mock <SqlOrchestrationService>(this.OrchestrationServiceOptions)
            {
                CallBase = true
            };
            this.worker = new TaskHubWorker(this.OrchestrationServiceMock.Object, this.loggerFactory);
            if (startWorker)
            {
                await this.worker.StartAsync();
            }

            this.client = new TaskHubClient(this.OrchestrationServiceMock.Object, loggerFactory: this.loggerFactory);
        }
Ejemplo n.º 2
0
 /// <inheritdoc/>
 public void RegisterOrchestrations(TaskHubWorker taskHubWorker)
 {
     taskHubWorker
     .AddTaskOrchestrations(this.GetOrchestrationTypes().ToArray())
     .AddTaskOrchestrations(this.GetTaskOrchestrations().Select(instance => new DefaultObjectCreator <TaskOrchestration>(instance.Value)).ToArray())
     .AddTaskActivities(GetActivityTypes().ToArray());
 }
Ejemplo n.º 3
0
        async Task StartAsync()
        {
            try
            {
                EnsureFabricOrchestrationProviderIsInitialized();

                this.worker = new TaskHubWorker(this.fabricOrchestrationProvider.OrchestrationService, this.fabricOrchestrationProviderSettings.LoggerFactory);

                if (this.registerOrchestrations2 != null)
                {
                    this.localClient = new TaskHubClient(this.fabricOrchestrationProvider.OrchestrationServiceClient, loggerFactory: this.fabricOrchestrationProviderSettings.LoggerFactory);
                    this.registerOrchestrations2(this.worker, this.localClient);
                }
                else
                {
                    this.registerOrchestrations(this.worker);
                }

                await this.worker.StartAsync();

                this.worker.TaskActivityDispatcher.IncludeDetails = true;
            }
            catch (Exception exception)
            {
                ServiceFabricProviderEventSource.Tracing.ServiceRequestFailed("RunAsync failed", $"Exception Details Type: {exception.GetType()}, Message: {exception.Message}, StackTrace: {exception.StackTrace}");
                throw;
            }
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            AppSettingsReader reader = new AppSettingsReader();
            string            servicebusConnectionString = reader.GetValue("Microsoft.ServiceBus.ConnectionString", typeof(string)).ToString();
            string            taskHubName = reader.GetValue("TaskHubName", typeof(string)).ToString();

            TaskHubClient taskHubClient = new TaskHubClient(taskHubName, servicebusConnectionString);
            TaskHubWorker taskHub       = new TaskHubWorker(taskHubName, servicebusConnectionString);

            taskHub.DeleteHub();
            taskHub.CreateHubIfNotExists();

            OrchestrationInstance instance = null;

            string instanceId = "TestTaskHub : " + Guid.NewGuid();

            taskHub.AddTaskOrchestrations((typeof(TaskHubProcessingOrchestration)));
            taskHub.AddTaskActivitiesFromInterface <IActivityFunction>(new ActivityImplementor(), true);
            taskHub.AddTaskActivities(new GetUserTask());

            instance = taskHubClient.CreateOrchestrationInstance(typeof(TaskHubProcessingOrchestration), instanceId, "hello");

            taskHub.Start();
            Console.WriteLine("Press any key to quit.");
            Console.ReadLine();
            taskHub.Stop(true);
        }
Ejemplo n.º 5
0
        public async Task MockSuborchestrationTest()
        {
            LocalOrchestrationService orchService = new LocalOrchestrationService();

            TaskHubWorker worker = new TaskHubWorker(orchService);
            TaskHubClient client = new TaskHubClient(orchService);

            await worker.AddTaskOrchestrations(typeof(ParentWorkflow), typeof(ChildWorkflow))
            .StartAsync();

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(ParentWorkflow), true);

            OrchestrationState result = await client.WaitForOrchestrationAsync(id,
                                                                               TimeSpan.FromSeconds(40), CancellationToken.None);

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);
            Assert.AreEqual(
                "Child '0' completed.Child '1' completed.Child '2' completed.Child '3' completed.Child '4' completed.",
                ParentWorkflow.Result, "Orchestration Result is wrong!!!");

            ParentWorkflow.Result = string.Empty;

            id = await client.CreateOrchestrationInstanceAsync(typeof(ParentWorkflow), false);

            result = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(40), CancellationToken.None);

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);
            Assert.AreEqual(
                "Child '0' completed.Child '1' completed.Child '2' completed.Child '3' completed.Child '4' completed.",
                ParentWorkflow.Result, "Orchestration Result is wrong!!!");

            await worker.StopAsync(true);
        }
Ejemplo n.º 6
0
        public async Task MockGenerationTest()
        {
            GenerationBasicOrchestration.Result = 0;
            GenerationBasicTask.GenerationCount = 0;

            LocalOrchestrationService orchService = new LocalOrchestrationService();

            TaskHubWorker worker = new TaskHubWorker(orchService);
            TaskHubClient client = new TaskHubClient(orchService);

            await worker.AddTaskOrchestrations(typeof(GenerationBasicOrchestration))
            .AddTaskActivities(new GenerationBasicTask())
            .StartAsync();

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(GenerationBasicOrchestration), 4);

            // strip out the eid so we wait for the latest one always
            OrchestrationInstance masterid = new OrchestrationInstance {
                InstanceId = id.InstanceId
            };

            OrchestrationState result1 = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(10), CancellationToken.None);

            OrchestrationState result2 = await client.WaitForOrchestrationAsync(masterid, TimeSpan.FromSeconds(20), CancellationToken.None);

            Assert.AreEqual(OrchestrationStatus.ContinuedAsNew, result1.OrchestrationStatus);
            Assert.AreEqual(OrchestrationStatus.Completed, result2.OrchestrationStatus);

            Assert.AreEqual(4, GenerationBasicOrchestration.Result, "Orchestration Result is wrong!!!");
        }
Ejemplo n.º 7
0
        public async Task MockRecreateOrchestrationTest()
        {
            LocalOrchestrationService orchService = new LocalOrchestrationService();

            TaskHubWorker worker = new TaskHubWorker(orchService);

            await worker.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration))
            .AddTaskActivities(typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask))
            .StartAsync();

            TaskHubClient client = new TaskHubClient(orchService);

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), null);

            OrchestrationState result = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(30), new CancellationToken());

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);

            await Assert.ThrowsExceptionAsync <OrchestrationAlreadyExistsException>(() => client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), id.InstanceId, null));

            await Assert.ThrowsExceptionAsync <OrchestrationAlreadyExistsException>(() => client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), id.InstanceId, null, new OrchestrationStatus[] { OrchestrationStatus.Completed }));

            SimplestGreetingsOrchestration.Result = String.Empty;

            OrchestrationInstance id2 = await client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), id.InstanceId, null, new OrchestrationStatus[] {});

            result = await client.WaitForOrchestrationAsync(id2, TimeSpan.FromSeconds(30), new CancellationToken());

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);

            Assert.AreEqual("Greeting send to Gabbar", SimplestGreetingsOrchestration.Result,
                            "Orchestration Result on Re-Create is wrong!!!");

            await worker.StopAsync(true);
        }
Ejemplo n.º 8
0
        private static async Task Start(TaskHubWorker taskHubWorker)
        {
            _ = await taskHubWorker.StartAsync().ConfigureAwait(true);

            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Worker Initialized ....");
        }
Ejemplo n.º 9
0
        public void TestInitialize()
        {
            client = TestHelpers.CreateTaskHubClient();

            taskHub = TestHelpers.CreateTaskHub();
            taskHub.orchestrationService.CreateAsync(true).Wait();
        }
Ejemplo n.º 10
0
        public async Task MockTimerTest()
        {
            LocalOrchestrationService orchService = new LocalOrchestrationService();

            TaskHubWorker worker = new TaskHubWorker(orchService);

            await worker.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration))
            .AddTaskActivities(typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask))
            .StartAsync();

            TaskHubClient client = new TaskHubClient(orchService);

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), "6");

            Stopwatch          sw     = Stopwatch.StartNew();
            OrchestrationState result = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(40), new CancellationToken());

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);

            Assert.IsTrue(sw.Elapsed.Seconds > 6);

            Assert.AreEqual("Greeting send to Gabbar", SimplestGreetingsOrchestration.Result,
                            "Orchestration Result is wrong!!!");

            await worker.StopAsync(true);
        }
Ejemplo n.º 11
0
        public async Task SimpleGreetingOrchestration()
        {
            var orchestrationService = TestHelpers.GetTestOrchestrationService(nameof(SimpleGreetingOrchestration));

            var worker = new TaskHubWorker(orchestrationService);

            try
            {
                await worker.AddTaskOrchestrations(typeof(SimplestGreetingsOrchestration))
                .AddTaskActivities(typeof(SimplestGetUserTask), typeof(SimplestSendGreetingTask))
                .StartAsync();

                var client = new TaskHubClient(orchestrationService);

                OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(SimplestGreetingsOrchestration), null);

                OrchestrationState result = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(Debugger.IsAttached ? 300 : 20), new CancellationToken());

                Assert.Equal(OrchestrationStatus.Completed, result.OrchestrationStatus);

                Assert.Equal("Greeting send to Gabbar", SimplestGreetingsOrchestration.Result);
            }
            finally
            {
                await worker.StopAsync(true);

                await orchestrationService.DeleteAsync();
            }
        }
        /// <summary>
        /// Builds and returns a <see cref="TaskHubWorker"/> using the configurations from this instance.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <returns>A new <see cref="TaskHubWorker"/>.</returns>
        public TaskHubWorker Build(IServiceProvider serviceProvider)
        {
            Check.NotNull(serviceProvider, nameof(serviceProvider));

            if (OrchestrationService == null)
            {
                throw new InvalidOperationException(Strings.OrchestrationInstanceNull);
            }

            var worker = new TaskHubWorker(
                OrchestrationService,
                new WrapperObjectManager <TaskOrchestration>(_orchestrations, type => new WrapperOrchestration(type)),
                new WrapperObjectManager <TaskActivity>(_activities, type => new WrapperActivity(type)));

            // The first middleware added begins the service scope for all further middleware, the orchestration, and activities.
            worker.AddOrchestrationDispatcherMiddleware(BeginMiddlewareScope(serviceProvider));
            worker.AddOrchestrationDispatcherMiddleware(WrapMiddleware(typeof(ServiceProviderOrchestrationMiddleware)));
            foreach (Type middlewareType in _orchestrationsMiddleware)
            {
                worker.AddOrchestrationDispatcherMiddleware(WrapMiddleware(middlewareType));
            }

            worker.AddActivityDispatcherMiddleware(BeginMiddlewareScope(serviceProvider));
            worker.AddActivityDispatcherMiddleware(WrapMiddleware(typeof(ServiceProviderActivityMiddleware)));
            foreach (Type middlewareType in _activitiesMiddleware)
            {
                worker.AddActivityDispatcherMiddleware(WrapMiddleware(middlewareType));
            }

            return(worker);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            eventListener = new ObservableEventListener();
            eventListener.LogToConsole();
            eventListener.EnableEvents(DefaultEventSource.Log, EventLevel.LogAlways);

            TraceSource source = new TraceSource("DurableTask");

            source.Listeners.AddRange(Trace.Listeners);

            IOrchestrationServiceInstanceStore instanceStore = new AzureTableInstanceStore(TaskHubName, StorageConnectionString);

            ServiceBusOrchestrationService orchestrationServiceAndClient =
                new ServiceBusOrchestrationService(ServiceBusConnectionString, TaskHubName, instanceStore, null, null);

            orchestrationServiceAndClient.CreateIfNotExistsAsync().Wait();

            TaskHubClient taskHubClient = new TaskHubClient(orchestrationServiceAndClient);
            TaskHubWorker taskHub       = new TaskHubWorker(orchestrationServiceAndClient);

            taskHub.AddTaskOrchestrations(typeof(CounterOrchestration));
            taskHub.AddTaskActivities(typeof(Task1), typeof(Task2));

            var instance = taskHubClient.CreateOrchestrationInstanceAsync(typeof(CounterOrchestration), Guid.NewGuid().ToString(), new TestOrchestrationInput()).Result;

            taskHub.StartAsync().Wait();

            //taskHubClient.WaitForOrchestrationAsync(instance, TimeSpan.MaxValue).Wait();

            Thread.Sleep(int.MaxValue);
        }
Ejemplo n.º 14
0
 public TestOrchestrationHost(AzureStorageOrchestrationService service)
 {
     this.worker = new TaskHubWorker(service);
     this.client = new TaskHubClient(service);
     this.addedOrchestrationTypes = new HashSet <Type>();
     this.addedActivityTypes      = new HashSet <Type>();
 }
        public ExceptionHandlingIntegrationTests()
        {
            var service = new LocalOrchestrationService();

            this.worker = new TaskHubWorker(service);
            this.client = new TaskHubClient(service);
        }
 public WorkerHostedService(
     IOrchestrationService orchestrationService,
     TaskHubWorker taskHubWorker)
 {
     _orchestrationService = orchestrationService;
     _taskHubWorker        = taskHubWorker;
 }
Ejemplo n.º 17
0
        public void TestInitialize()
        {
            client = TestHelpers.CreateTaskHubClient();

            taskHub = TestHelpers.CreateTaskHub();
            taskHub.CreateHub();
        }
Ejemplo n.º 18
0
        public static async Task StartWorker(TaskHubWorker worker)
        {
            worker.AddTaskOrchestrations(typeof(MockOrchestration));
            worker.AddTaskActivities(new MockActivity());
            await worker.StartAsync();

            Counter.Start();
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskHubBackgroundService"/> class.
 /// </summary>
 /// <param name="worker">The task hub worker. Not null.</param>
 /// <param name="logger">The logger. Not null.</param>
 /// <param name="options">The task hub options.</param>
 public TaskHubBackgroundService(
     TaskHubWorker worker,
     ILogger <TaskHubBackgroundService> logger,
     IOptions <TaskHubOptions> options)
 {
     _worker  = Check.NotNull(worker, nameof(worker));
     _logger  = Check.NotNull(logger, nameof(logger));
     _options = Check.NotNull(options, nameof(options));
 }
Ejemplo n.º 20
0
        public void TestInitialize()
        {
            client = TestHelpers.CreateTaskHubClient();

            taskHub = TestHelpers.CreateTaskHub();

            taskHub.DeleteHub();
            taskHub.CreateHubIfNotExists();
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Internal initialization call from the WebJobs host.
        /// </summary>
        /// <param name="context">Extension context provided by WebJobs.</param>
        void IExtensionConfigProvider.Initialize(ExtensionConfigContext context)
        {
            ConfigureLoaderHooks();

            // Functions V1 has it's configuration initialized at startup time (now).
            // For Functions V2 (and for some unit tests) configuration happens earlier in the pipeline.
            if (!this.isOptionsConfigured)
            {
                this.InitializeForFunctionsV1(context);
            }

            // Throw if any of the configured options are invalid
            this.Options.Validate();

            // For 202 support
            if (this.Options.NotificationUrl == null)
            {
#pragma warning disable CS0618 // Type or member is obsolete
                this.Options.NotificationUrl = context.GetWebhookHandler();
#pragma warning restore CS0618 // Type or member is obsolete
            }

            this.TraceConfigurationSettings();

            var bindings = new BindingHelper(this, this.TraceHelper);

            // Note that the order of the rules is important
            var rule = context.AddBindingRule <DurableClientAttribute>()
                       .AddConverter <string, StartOrchestrationArgs>(bindings.StringToStartOrchestrationArgs)
                       .AddConverter <JObject, StartOrchestrationArgs>(bindings.JObjectToStartOrchestrationArgs)
                       .AddConverter <IDurableClient, string>(bindings.DurableOrchestrationClientToString);

            rule.BindToCollector <StartOrchestrationArgs>(bindings.CreateAsyncCollector);
            rule.BindToInput <IDurableOrchestrationClient>(this.GetClient);
            rule.BindToInput <IDurableEntityClient>(this.GetClient);
            rule.BindToInput <IDurableClient>(this.GetClient);

            string storageConnectionString = null;
            var    providerFactory         = this.durabilityProviderFactory as AzureStorageDurabilityProviderFactory;
            if (providerFactory != null)
            {
                storageConnectionString = providerFactory.GetDefaultStorageConnectionString();
            }

            context.AddBindingRule <OrchestrationTriggerAttribute>()
            .BindToTrigger(new OrchestrationTriggerAttributeBindingProvider(this, context, storageConnectionString, this.TraceHelper));

            context.AddBindingRule <ActivityTriggerAttribute>()
            .BindToTrigger(new ActivityTriggerAttributeBindingProvider(this, context, storageConnectionString, this.TraceHelper));

            context.AddBindingRule <EntityTriggerAttribute>()
            .BindToTrigger(new EntityTriggerAttributeBindingProvider(this, context, storageConnectionString, this.TraceHelper));

            this.taskHubWorker = new TaskHubWorker(this.defaultDurabilityProvider, this, this);
            this.taskHubWorker.AddOrchestrationDispatcherMiddleware(this.EntityMiddleware);
            this.taskHubWorker.AddOrchestrationDispatcherMiddleware(this.OrchestrationMiddleware);
        }
Ejemplo n.º 22
0
        public void TestInitialize()
        {
            this.client = TestHelpers.CreateTaskHubClient();

            this.taskHub = TestHelpers.CreateTaskHub();

            this.taskHub.orchestrationService.CreateAsync(true).Wait();

            this.taskHubNoCompression = TestHelpers.CreateTaskHubNoCompression();
        }
        public void TestInitialize()
        {
            if (!TestContext.TestName.Contains("TestHost"))
            {
                client = TestHelpers.CreateTaskHubClient();

                taskHub = TestHelpers.CreateTaskHub(TimeSpan.FromSeconds(30));
                taskHub.orchestrationService.CreateAsync(true).Wait();
            }
        }
Ejemplo n.º 24
0
 public void TestInitialize()
 {
     if (!TestContext.TestName.Contains("TestHost"))
     {
         client  = TestHelpers.CreateTaskHubClient();
         taskHub = TestHelpers.CreateTaskHub();
         taskHubNoCompression = TestHelpers.CreateTaskHubNoCompression();
         taskHub.orchestrationService.CreateAsync(true).Wait();
     }
 }
        public void TestInitialize()
        {
            this.client = TestHelpers.CreateTaskHubClient();
            this.orchestrationService = this.client.ServiceClient as ServiceBusOrchestrationService;
            this.queryClient          = this.orchestrationService?.InstanceStore as AzureTableInstanceStore;

            this.taskHub = TestHelpers.CreateTaskHub();

            this.taskHub.orchestrationService.CreateAsync(true).Wait();
        }
Ejemplo n.º 26
0
        public async Task SimpleFanOutOrchestration_DurabilityTest()
        {
            int numToIterateTo       = 500;
            var orchestrationService = TestHelpers.GetTestOrchestrationService(nameof(SimpleFanOutOrchestration_DurabilityTest));
            var worker = new TaskHubWorker(orchestrationService);

            try
            {
                await worker.AddTaskOrchestrations(typeof(FanOutOrchestration))
                .AddTaskActivities(typeof(SquareIntTask), typeof(SumIntTask))
                .StartAsync();

                var client = new TaskHubClient(orchestrationService);

                int[] numsToSum = new int[numToIterateTo];
                for (int i = 0; i < numToIterateTo; i++)
                {
                    numsToSum[i] = i + 1;
                }
                OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(typeof(FanOutOrchestration), numsToSum);

                try
                {
                    await client.WaitForOrchestrationAsync(id, TimeSpan.FromMilliseconds(500), new CancellationToken());
                }
                catch
                {
                    //Timeout is expected in this case. 500 activities can't finish that fast.
                    await worker.StopAsync(true);
                }

                // Resume orchestration on "new" client
                orchestrationService = TestHelpers.GetTestOrchestrationService(nameof(SimpleFanOutOrchestration_DurabilityTest));
                worker = new TaskHubWorker(orchestrationService);
                await worker.AddTaskOrchestrations(typeof(FanOutOrchestration))
                .AddTaskActivities(typeof(SquareIntTask), typeof(SumIntTask))
                .StartAsync();

                client = new TaskHubClient(orchestrationService);

                OrchestrationState result = await client.WaitForOrchestrationAsync(id, TimeSpan.FromSeconds(Debugger.IsAttached ? 20 : 20), new CancellationToken());

                Assert.Equal(OrchestrationStatus.Completed, result.OrchestrationStatus);

                // Sum of square numbers 1 to n = n * (n+1) * (2n+1) / 6
                int expectedResult = (numToIterateTo * (numToIterateTo + 1) * (2 * numToIterateTo + 1)) / 6;
                Assert.Equal(expectedResult, FanOutOrchestration.Result);
            }
            finally
            {
                await worker.StopAsync(true);

                await orchestrationService.DeleteAsync();
            }
        }
Ejemplo n.º 27
0
        public async Task MockRaiseEventTest()
        {
            LocalOrchestrationService orchService = new LocalOrchestrationService();

            TaskHubWorker worker = new TaskHubWorker(orchService);
            TaskHubClient client = new TaskHubClient(orchService);

            await worker.AddTaskOrchestrations(typeof(GenerationSignalOrchestration))
            .StartAsync();

            OrchestrationInstance id = await client.CreateOrchestrationInstanceAsync(
                typeof(GenerationSignalOrchestration), 5);

            var signalId = new OrchestrationInstance {
                InstanceId = id.InstanceId
            };

            await Task.Delay(2 * 500);

            await client.RaiseEventAsync(signalId, "Count", "1");

            GenerationSignalOrchestration.signal.Set();

            await Task.Delay(2 * 500);

            GenerationSignalOrchestration.signal.Reset();
            await client.RaiseEventAsync(signalId, "Count", "2");

            await Task.Delay(2 * 500);

            await client.RaiseEventAsync(signalId, "Count", "3"); // will be recieved by next generation

            GenerationSignalOrchestration.signal.Set();

            await Task.Delay(2 * 500);

            GenerationSignalOrchestration.signal.Reset();
            await client.RaiseEventAsync(signalId, "Count", "4");

            await Task.Delay(2 * 500);

            await client.RaiseEventAsync(signalId, "Count", "5"); // will be recieved by next generation

            await client.RaiseEventAsync(signalId, "Count", "6"); // lost

            await client.RaiseEventAsync(signalId, "Count", "7"); // lost

            GenerationSignalOrchestration.signal.Set();

            OrchestrationState result = await client.WaitForOrchestrationAsync(new OrchestrationInstance { InstanceId = id.InstanceId },
                                                                               TimeSpan.FromSeconds(40), CancellationToken.None);

            Assert.AreEqual(OrchestrationStatus.Completed, result.OrchestrationStatus);
            Assert.AreEqual("5", GenerationSignalOrchestration.Result, "Orchestration Result is wrong!!!");
        }
Ejemplo n.º 28
0
        public async Task MultipleConcurrentRoleStartsTestNoInitialHub()
        {
            // Make sure we cleanup we start from scratch
            await this.taskHub.StopAsync(true);

            await this.taskHub.orchestrationService.DeleteAsync();

            const int ConcurrentClientsAndHubs = 4;
            var       rnd = new Random();

            var          clients = new List <TaskHubClient>(ConcurrentClientsAndHubs);
            var          workers = new List <TaskHubWorker>(ConcurrentClientsAndHubs);
            IList <Task> tasks   = new List <Task>();

            for (var i = 0; i < ConcurrentClientsAndHubs; i++)
            {
                clients.Add(TestHelpers.CreateTaskHubClient());
                workers.Add(TestHelpers.CreateTaskHub(new ServiceBusOrchestrationServiceSettings
                {
                    TaskOrchestrationDispatcherSettings = { DispatcherCount = 4 },
                    TrackingDispatcherSettings          = { DispatcherCount = 4 },
                    TaskActivityDispatcherSettings      = { DispatcherCount = 4 }
                }));
                tasks.Add(workers[i].orchestrationService.CreateIfNotExistsAsync());
            }

            await Task.WhenAll(tasks);

            GenerationBasicOrchestration.Result = 0;
            GenerationBasicTask.GenerationCount = 0;

            // ReSharper disable once UnusedVariable
            TaskHubWorker selectedHub    = workers[(rnd.Next(ConcurrentClientsAndHubs))];
            TaskHubClient selectedClient = clients[(rnd.Next(ConcurrentClientsAndHubs))];

            tasks.Clear();
            for (var i = 0; i < ConcurrentClientsAndHubs; i++)
            {
                tasks.Add(workers[i].AddTaskOrchestrations(typeof(GenerationBasicOrchestration))
                          .AddTaskActivities(new GenerationBasicTask())
                          .StartAsync());
            }

            await Task.WhenAll(tasks);

            OrchestrationInstance instance = await selectedClient.CreateOrchestrationInstanceAsync(typeof(GenerationBasicOrchestration), 4);

            OrchestrationState state = await selectedClient.WaitForOrchestrationAsync(instance, TimeSpan.FromSeconds(60), CancellationToken.None);

            Assert.IsNotNull(state);
            Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus, TestHelpers.GetInstanceNotCompletedMessage(this.client, instance, 60));
            Assert.AreEqual(4, GenerationBasicOrchestration.Result, "Orchestration Result is wrong!!!");
            await Task.WhenAll(workers.Select(worker => worker.StopAsync(true)));
        }
Ejemplo n.º 29
0
 public void TestInitialize()
 {
     if (!TestContext.TestName.Contains("TestHost"))
     {
         client  = TestHelpers.CreateTaskHubClient();
         taskHub = TestHelpers.CreateTaskHub();
         taskHubNoCompression = TestHelpers.CreateTaskHubNoCompression();
         taskHub.DeleteHub();
         taskHub.CreateHubIfNotExists();
     }
 }
Ejemplo n.º 30
0
        public TestOrchestrationHost(AzureStorageOrchestrationServiceSettings settings)
        {
            this.service = new AzureStorageOrchestrationService(settings);
            this.service.CreateAsync().GetAwaiter().GetResult();

            this.settings = settings;
            this.worker   = new TaskHubWorker(service, loggerFactory: settings.LoggerFactory);
            this.client   = new TaskHubClient(service, loggerFactory: settings.LoggerFactory);
            this.addedOrchestrationTypes = new HashSet <Type>();
            this.addedActivityTypes      = new HashSet <Type>();
        }
        private static void run()
        {
            string connectionString = ConfigurationManager.AppSettings["SbConnStr"];
            string taskHubName = ConfigurationManager.AppSettings["TaskHubName"];

            TaskHubClient taskHubClient = new TaskHubClient(taskHubName, connectionString);
            TaskHubWorker taskHubWorker = new TaskHubWorker(taskHubName, connectionString);

            taskHubWorker.CreateHub();
            OrchestrationInstance instance = taskHubClient.CreateOrchestrationInstance(typeof(WfTaskOrchestration), "Hello");

            taskHubWorker.AddTaskOrchestrations(typeof(WfTaskOrchestration));
            taskHubWorker.AddTaskActivities(new WOEIDLookupTask(), new WForecastsTask());
            taskHubWorker.Start();

            Console.WriteLine("Press any key to quit.");
            Console.ReadLine();

            taskHubWorker.Stop(true);
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options))
            {
                string servicebusConnectionString = Program.GetSetting("ServiceBusConnectionString");
                string storageConnectionString = Program.GetSetting("StorageConnectionString");
                string taskHubName = ConfigurationManager.AppSettings["taskHubName"];

                TaskHubClient taskHubClient = new TaskHubClient(taskHubName, servicebusConnectionString, storageConnectionString);
                TaskHubWorker taskHub = new TaskHubWorker(taskHubName, servicebusConnectionString, storageConnectionString);

                if (options.CreateHub)
                {
                    taskHub.CreateHub();
                }

                if (!string.IsNullOrWhiteSpace(options.StartInstance))
                {
                    string instanceId = options.InstanceId;
                    OrchestrationInstance instance = null;
                    switch (options.StartInstance)
                    {
                        case "Greetings":
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(GreetingsOrchestration), instanceId, null);
                            break;
                        case "Greetings2":
                            if (options.Parameters == null || options.Parameters.Length != 1)
                            {
                                throw new ArgumentException("parameters");
                            }
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(GreetingsOrchestration2), instanceId, 
                                int.Parse(options.Parameters[0]));
                            break;
                        case "Cron":
                            // Sample Input: "0 12 * */2 Mon"
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(CronOrchestration), instanceId, 
                                (options.Parameters != null && options.Parameters.Length > 0) ? options.Parameters[0] : null);
                            break;
                        case "Average":
                            // Sample Input: "1 50 10"
                            if (options.Parameters == null || options.Parameters.Length != 3)
                            {
                                throw new ArgumentException("parameters");
                            }
                            int[] input = options.Parameters.Select(p => int.Parse(p)).ToArray();
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(AverageCalculatorOrchestration), instanceId, input);
                            break;
                        case "ErrorHandling":
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(ErrorHandlingOrchestration), instanceId, null);
                            break;
                        case "Signal":
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(SignalOrchestration), instanceId, null);
                            break;
                        case "Replat":
                            instance = taskHubClient.CreateOrchestrationInstance(typeof(MigrateOrchestration), instanceId,
                                new MigrateOrchestrationData() { SubscriptionId = "03a1cd39-47ac-4a57-9ff5-a2c2a2a76088", IsDisabled = false });
                            break;
                        default:
                            throw new Exception("Unsupported Orchestration Name: " + options.StartInstance);
                    }

                    Console.WriteLine("Workflow Instance Started: " + instance);
                }
                else if (!string.IsNullOrWhiteSpace(options.Signal))
                {
                    if (string.IsNullOrWhiteSpace(options.InstanceId)) 
                    {
                        throw new ArgumentException("instantceId");
                    }
                    if (options.Parameters == null || options.Parameters.Length != 1)
                    {
                        throw new ArgumentException("parameters");

                    }
                    string instanceId = options.InstanceId;
                    OrchestrationInstance instance = new OrchestrationInstance { InstanceId = instanceId };
                    taskHubClient.RaiseEvent(instance, options.Signal, options.Parameters[0]);
                }

                if (!options.SkipWorker)
                {
                    try
                    {
                        taskHub.AddTaskOrchestrations(typeof(GreetingsOrchestration), typeof(GreetingsOrchestration2), typeof(CronOrchestration),
                                                            typeof (AverageCalculatorOrchestration), typeof (ErrorHandlingOrchestration), typeof (SignalOrchestration));
                        taskHub.AddTaskOrchestrations(typeof(MigrateOrchestration));

                        taskHub.AddTaskActivities(new GetUserTask(), new SendGreetingTask(), new CronTask(), new ComputeSumTask(), new GoodTask(), new BadTask(), new CleanupTask(),
                                                             new EmailTask());
                        taskHub.AddTaskActivitiesFromInterface<IManagementSqlOrchestrationTasks>(new ManagementSqlOrchestrationTasks());
                        taskHub.AddTaskActivitiesFromInterface<IMigrationTasks>(new MigrationTasks());

                        taskHub.Start();

                        Console.WriteLine("Press any key to quit.");
                        Console.ReadLine();

                        taskHub.Stop(true);
                    }
                    catch (Exception)
                    {
                        // silently eat any unhadled exceptions.
                    }
                }
            }
        }
Ejemplo n.º 33
0
 public void TestInitialize()
 {
     client = TestHelpers.CreateTaskHubClient();
     taskHub = TestHelpers.CreateTaskHub();
 }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            string tableConnectionString = ConfigurationManager.AppSettings["StorageConnectionString"];
            if (CommandLine.Parser.Default.ParseArgumentsStrict(args, options))
            {
                string connectionString = ConfigurationManager.ConnectionStrings["Microsoft.ServiceBus.ConnectionString"].ConnectionString;
                string taskHubName = ConfigurationManager.AppSettings["TaskHubName"];

                TaskHubClient taskHubClient = new TaskHubClient(taskHubName, connectionString, tableConnectionString);
                TaskHubWorkerSettings settings = new TaskHubWorkerSettings();
                settings.TaskOrchestrationDispatcherSettings.CompressOrchestrationState = bool.Parse(ConfigurationManager.AppSettings["CompressOrchestrationState"]);
                settings.TaskActivityDispatcherSettings.MaxConcurrentActivities = int.Parse(ConfigurationManager.AppSettings["MaxConcurrentActivities"]);
                settings.TaskOrchestrationDispatcherSettings.MaxConcurrentOrchestrations = int.Parse(ConfigurationManager.AppSettings["MaxConcurrentOrchestrations"]);
                TaskHubWorker taskHub = new TaskHubWorker(taskHubName, connectionString, tableConnectionString, settings);

                if (options.CreateHub)
                {
                    taskHub.CreateHub();
                }

                OrchestrationInstance instance = null;
                string instanceId = options.StartInstance;

                if (!string.IsNullOrWhiteSpace(instanceId))
                {
                    instance = taskHubClient.CreateOrchestrationInstance(typeof(DriverOrchestration), instanceId, new DriverOrchestrationData
                    {
                        NumberOfIteration = int.Parse(ConfigurationManager.AppSettings["DriverOrchestrationIterations"]),
                        NumberOfParallelTasks = int.Parse(ConfigurationManager.AppSettings["DriverOrchestrationParallelTasks"]),
                        SubOrchestrationData = new TestOrchestrationData
                        {
                            NumberOfParallelTasks = int.Parse(ConfigurationManager.AppSettings["ChildOrchestrationParallelTasks"]),
                            NumberOfSerialTasks = int.Parse(ConfigurationManager.AppSettings["ChildOrchestrationSerialTasks"]),
                            MaxDelayInSeconds = int.Parse(ConfigurationManager.AppSettings["TestTaskMaxDelayInMinutes"]),
                        },
                    });
                }
                else
                {
                    instance = new OrchestrationInstance { InstanceId = options.InstanceId };
                }

                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                TestTask testTask = new TestTask();
                taskHub.AddTaskActivities(testTask);
                taskHub.AddTaskOrchestrations(typeof(DriverOrchestration));
                taskHub.AddTaskOrchestrations(typeof(TestOrchestration));
                taskHub.Start();

                int testTimeoutInSeconds = int.Parse(ConfigurationManager.AppSettings["TestTimeoutInSeconds"]);
                OrchestrationState state = WaitForInstance(taskHubClient, instance, testTimeoutInSeconds);
                stopWatch.Stop();
                Console.WriteLine("Orchestration Status: " + state.OrchestrationStatus.ToString());
                Console.WriteLine("Orchestration Result: " + state.Output);
                Console.WriteLine("Counter: " + testTask.counter);

                TimeSpan totalTime = stopWatch.Elapsed;
                string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                    totalTime.Hours, totalTime.Minutes, totalTime.Seconds,
                    totalTime.Milliseconds / 10);
                Console.WriteLine("Total Time: " + elapsedTime);

                taskHub.Stop();
            }

        }