예제 #1
0
        public static async Task <List <BusinessRules.RuleResponse> > Run(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var data = await context.CallActivityAsync <BusinessRules.CustomersData>("XmlDeserialiser");

            var tasks = new List <Task <List <BusinessRules.RuleResponse> > >();
            var firstOrchestratorTask  = context.CallSubOrchestratorAsync <List <BusinessRules.RuleResponse> >("OPARuleOrchestrator");
            var secondOrchestratorTask = context.CallSubOrchestratorAsync <List <BusinessRules.RuleResponse> >("OPAOrchestrator2");

            tasks.Add(firstOrchestratorTask);
            tasks.Add(secondOrchestratorTask);

            var result1 = await firstOrchestratorTask;

            // var result2 =  await secondOrchestratorTask; -

            // result1.AddRange(result2); -
            // return result1; -
            return(result1);

            // await Task.WhenAll(tasks); -

            // var resultFromOrchestrators = tasks.Select(x=> x.Result).ToList(); -

            // var result = new List<BusinessRules.RuleResponse>(); -
            //foreach (var item in resultFromOrchestrators)
            // {
            //     result.AddRange(item);
            // }

            // return result;

            // return null;
        }
예제 #2
0
        public static async Task <object> ProcessQuoteRequest(
            [OrchestrationTrigger] DurableOrchestrationContext context,
            ILogger log)
        {
            await context.CallSubOrchestratorAsync(
                Constants.WarningLoggingOrchestrator,
                "Orchestator function has started");

            var tags = context.GetInput <List <string> >();

            var quote = await context.CallActivityAsync <string>(Constants.GetQuoteActivityName, tags);

            if (!context.IsReplaying)
            {
                log.LogInformation($"Got quote {quote}");
            }

            var formattedQuote = await context.CallActivityAsync <string>(Constants.FormatQuoteActivity, quote);

            //if (!context.IsReplaying)
            //{
            //    log.LogInformation($"Successfullly formatted quote {formattedQuote}");
            //}
            await context.CallSubOrchestratorAsync(
                Constants.WarningLoggingOrchestrator,
                $"Successfullly formatted quote {formattedQuote}");


            return(new
            {
                Quote = quote,
                Formatted = formattedQuote
            });
        }
예제 #3
0
        public static async Task <string> RunOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var fileId = context.GetInput <string>();

            context.SetCustomStatus("Parsing people...");
            var engineers = await context.CallActivityAsync <List <string> >("FileProcessor_ParseEngineers", fileId);

            context.SetCustomStatus("Gathering grunts...");
            var codeMonkeys = await context.CallSubOrchestratorAsync <ICollection <string> >("FileProcessor_WhoIsACodeMonkey", engineers);

            context.SetCustomStatus("Searching superstars...");
            var microserviceSuperstars = await context.CallSubOrchestratorAsync <ICollection <string> >("FileProcessor_WhoIsAMicroserviceSuperstar", engineers.Where(engineer => !codeMonkeys.Contains(engineer)).ToList());

            context.SetCustomStatus("Leveling lackeys...");
            var levels = await context.CallSubOrchestratorAsync <Dictionary <string, int> >("FileProcessor_GetLevels", engineers);

            context.SetCustomStatus("Transmitting textfile...");
            var resultFileId = await context.CallActivityAsync <string>("FileProcessor_CreateResultsFile", new FileProcessorResult
            {
                AllEngineers           = engineers,
                CodeMonkeys            = codeMonkeys,
                MicroserviceSuperstars = microserviceSuperstars,
                Levels = levels
            });

            // returns ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
            context.SetCustomStatus("Completed");
            return(resultFileId);
        }
예제 #4
0
        public static async Task FullOrchestration([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var payload = context.GetInput <string>();

            await context.CallSubOrchestratorAsync(nameof(ProvisioningOrchestration), payload);

            await context.CallSubOrchestratorAsync(nameof(FirmwareOrchestration), payload);
        }
예제 #5
0
        public async Task Run([OrchestrationTrigger] DurableOrchestrationContext context,
                              ILogger log)
        {
            var teamModel = context.GetInput <TeamModel>();

            teamModel.TimeZoneInfoId ??= await TimeZoneHelper.GetAndUpdateTimeZoneAsync(teamModel.TeamId, _timeZoneService, _scheduleConnectorService, _scheduleSourceService);

            if (!teamModel.Initialized)
            {
                await context.CallSubOrchestratorAsync(nameof(InitializeOrchestrator), teamModel);

                teamModel.Initialized = true;
            }

            // if we haven't got a valid timezone then we cannot sync shifts because we will not be able to properly
            // convert the shift start and end times to UTC
            if (teamModel.TimeZoneInfoId != null)
            {
                try
                {
                    var weeks = context.CurrentUtcDateTime.Date
                                .Range(_options.PastWeeks, _options.FutureWeeks, _options.StartDayOfWeek);

                    var weekTasks = weeks
                                    .Select(startDate => new WeekModel
                    {
                        StartDate      = startDate,
                        StoreId        = teamModel.StoreId,
                        TeamId         = teamModel.TeamId,
                        TimeZoneInfoId = teamModel.TimeZoneInfoId
                    })
                                    .Select(weekModel => context.CallSubOrchestratorAsync(nameof(WeekOrchestrator), weekModel));

                    await Task.WhenAll(weekTasks);
                }
                catch (Exception ex) when(_options.ContinueOnError)
                {
                    log.LogTeamError(ex, teamModel);
                }
            }
            else
            {
                log.LogMissingTimeZoneError(teamModel);
            }

            if (_options.FrequencySeconds < 0)
            {
                return;
            }

            var dueTime = context.CurrentUtcDateTime.AddSeconds(_options.FrequencySeconds);

            await context.CreateTimer(dueTime, CancellationToken.None);

            context.ContinueAsNew(teamModel);
        }
예제 #6
0
        public static async Task HiringProcessOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context, ILogger logger)
        {
            JobApplication jobApplication = context.GetInput <JobApplication>();

            ProcessInterviewRoundInputModel processInterviewRoundOne = new ProcessInterviewRoundInputModel()
            {
                JobApplication         = jobApplication,
                RoundNumber            = 1,
                OrchestratorInstanceId = context.InstanceId
            };
            InterviewRoundResult IsRoundOnePassed = await context.CallSubOrchestratorAsync <InterviewRoundResult>("InterviewRoundOrchestrator", processInterviewRoundOne);


            if (IsRoundOnePassed.IsPassed)
            {
                logger.LogWarning($"{jobApplication.Name} has passed round one, scheduling round {processInterviewRoundOne.RoundNumber + 1}.");

                processInterviewRoundOne.RoundNumber += 1;
                InterviewRoundResult IsRoundTwoPaased = await context.CallSubOrchestratorAsync <InterviewRoundResult>("InterviewRoundOrchestrator", processInterviewRoundOne);

                if (IsRoundTwoPaased.IsPassed)
                {
                    /// Rollout offer
                    ///
                    await context.CallActivityAsync <Notification>("RollOutOffer", processInterviewRoundOne.JobApplication);

                    logger.LogWarning($"Offer rolled out to {processInterviewRoundOne.JobApplication.Name}.");

                    /// Wait for offer approval from candidate
                    /// External Event
                    bool IsOfferAccepted = await context.CallSubOrchestratorAsync <bool>("OfferOrchestrator", processInterviewRoundOne);

                    if (IsOfferAccepted)
                    {
                        /// Fan out processing
                        ///
                        bool finalResult = await context.CallSubOrchestratorAsync <bool>("ReadinessOrchestrator", processInterviewRoundOne.JobApplication);

                        if (finalResult)
                        {
                            logger.LogWarning($"Everything is ready for {processInterviewRoundOne.JobApplication.Name} {finalResult}");
                        }
                        else
                        {
                            logger.LogWarning($"Not all things are ready for {processInterviewRoundOne.JobApplication.Name} {finalResult}");
                        }
                    }
                }
            }
            await context.CallActivityAsync <Notification>("DeclineApplication", processInterviewRoundOne.JobApplication);
        }
        public static async Task <object> ProcessVideo(
            [OrchestrationTrigger] DurableOrchestrationContext ctx,
            TraceWriter log)
        {
            var videoLocation = ctx.GetInput <string>();

            try
            {
                var transcodedLocations = await
                                          ctx.CallSubOrchestratorAsync <string[]>(OrchestratorNames.Transcode,
                                                                                  videoLocation);

                var transcodedLocation = transcodedLocations.First(x => x.Contains(".mp4")); // these are SAS tokens

                var thumbnailLocation = await ctx.CallActivityWithRetryAsync <string>(ActivityNames.ExtractThumbnail,
                                                                                      new RetryOptions(TimeSpan.FromSeconds(5), 4), // {Handle = ex => ex.InnerException is InvalidOperationException}, - currently not possible #84
                                                                                      transcodedLocation);

                var withIntroLocation = await ctx.CallActivityAsync <string>
                                            (ActivityNames.PrependIntro, transcodedLocation);

                // we need to give our suborchestrator its own id so we can send it events
                // could be a new guid, but by basing it on the parent instance id we make it predictable
                var approvalInfo =
                    new ApprovalInfo {
                    OrchestrationId = "XYZ" + ctx.InstanceId, VideoLocation = withIntroLocation
                };
                var approvalResult = await ctx.CallSubOrchestratorAsync <string>(OrchestratorNames.GetApprovalResult, approvalInfo.OrchestrationId, approvalInfo);

                if (approvalResult == "Approved")
                {
                    await ctx.CallActivityAsync(ActivityNames.PublishVideo,
                                                new [] { transcodedLocation, thumbnailLocation, withIntroLocation });

                    return("Approved and published");
                }
                await ctx.CallActivityAsync(ActivityNames.RejectVideo,
                                            new [] { transcodedLocation, thumbnailLocation, withIntroLocation });

                return($"Not published because {approvalResult}");
            }
            catch (Exception e)
            {
                if (!ctx.IsReplaying)
                {
                    log.Error("Failed to process video with error " + e.Message);
                }
                await ctx.CallActivityAsync(ActivityNames.Cleanup, videoLocation);

                return(new { Error = "Failed to process video", e.Message });
            }
        }
예제 #8
0
        public static async Task <int> MapReduceOrchestrator([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var mapContainers   = (containerMapIn : "datain", containerMapOut : "dataout");
            var reduceContainer = "dataout";

            // Start the mapping sub-orchestrator
            await context.CallSubOrchestratorAsync("MapOrchestrator", mapContainers);

            // Start the reduce sub orchestrator
            var maximumTemperature = await context.CallSubOrchestratorAsync <int>("ReduceOrchestrator", reduceContainer);

            return(maximumTemperature);
        }
예제 #9
0
        public async Task Run([OrchestrationTrigger] DurableOrchestrationContext context,
                              ILogger log)
        {
            var clearScheduleModel = context.GetInput <ClearScheduleModel>();

            var pastWeeks   = clearScheduleModel.PastWeeks ?? _options.PastWeeks;
            var futureWeeks = clearScheduleModel.FutureWeeks ?? _options.FutureWeeks;

            var timeZoneInfoId = await TimeZoneHelper.GetAndUpdateTimeZoneAsync(clearScheduleModel.TeamId, _timeZoneService, _scheduleConnectorService, _scheduleSourceService);

            timeZoneInfoId ??= _options.TimeZone;

            clearScheduleModel.StartDate = context.CurrentUtcDateTime.Date
                                           .StartOfWeek(_options.StartDayOfWeek)
                                           .AddWeeks(-pastWeeks)
                                           .ApplyTimeZoneOffset(timeZoneInfoId);

            clearScheduleModel.EndDate = context.CurrentUtcDateTime.Date
                                         .StartOfWeek(_options.StartDayOfWeek)
                                         .AddWeeks(futureWeeks + 1)
                                         .ApplyTimeZoneOffset(timeZoneInfoId);

            if (!context.IsReplaying)
            {
                log.LogClearStart(clearScheduleModel);
            }

            var tasks = Enumerable.Range(0, clearScheduleModel.EndDate.Subtract(clearScheduleModel.StartDate).Days)
                        .Select(offset => new ClearScheduleModel
            {
                StartDate = clearScheduleModel.StartDate.AddDays(offset),
                EndDate   = clearScheduleModel.StartDate.AddDays(offset).AddHours(23).AddMinutes(59),
                TeamId    = clearScheduleModel.TeamId
            })
                        .Select(model => context.CallSubOrchestratorAsync(nameof(ClearShiftsDayOrchestrator), model));

            await Task.WhenAll(tasks);

            // at this stage, we should have deleted all the shifts for each of the days in the period, apart from those
            // that span midnight on any day, so we need to execute a final ClearShiftsDayOrchestrator for the full date
            // range plus 24 hours in order to include those remaining shifts
            clearScheduleModel.QueryEndDate = clearScheduleModel.EndDate.AddHours(24);
            await context.CallSubOrchestratorAsync(nameof(ClearShiftsDayOrchestrator), clearScheduleModel);

            if (clearScheduleModel.ClearSchedulingGroups)
            {
                await context.CallActivityAsync(nameof(ClearSchedulingGroupsActivity), clearScheduleModel.TeamId);
            }

            await context.CallActivityAsync(nameof(ClearCacheActivity), clearScheduleModel);
        }
예제 #10
0
        public static async Task <WizardResult> Run([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var coordinates = context.GetInput <Coordinates>();

            var wizardStep = new WizardStep
            {
                Id       = Guid.NewGuid().ToString(),
                Event    = "step-1-answer",
                Question = "What else would you like to do?",
                Answers  = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Food", Value = "food"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Events", Value = "events"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Attractions", Value = "attractions"
                    }
                }
            };

            context.SetCustomStatus(wizardStep);

            var step1Answer = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            WizardResult result = null;

            switch (step1Answer.Value)
            {
            case "food":
                result = await context.CallSubOrchestratorAsync <WizardResult>("WizardFoodFunction", step1Answer.Id, new FoodInputCriteria { VisitorCoordinates = coordinates });

                break;

            case "attractions":
                result = await context.CallSubOrchestratorAsync <WizardResult>("WizardAttractionFunction", step1Answer.Id, new AttractionInputCriteria { VisitorCoordinates = coordinates });

                break;

            case "events":
                result = await context.CallSubOrchestratorAsync <WizardResult>("WizardEventFunction", step1Answer.Id, new EventInputCriteria { VisitorCoordinates = coordinates });

                break;
            }
            return(result);
        }
예제 #11
0
        public static async Task <WizardResult> GetResult(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var inputCriteria = context.GetInput <FoodInputCriteria>();

            var wizardStep = new WizardStep
            {
                Id       = Guid.NewGuid().ToString(),
                Event    = "step-food",
                Question = "What kind of food do you like?",
                Answers  = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "American", Value = "american"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Italian", Value = "italian"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Greek", Value = "greek"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Chinese", Value = "chinese"
                    },
                }
            };

            context.SetCustomStatus(wizardStep);

            var stepFoodContext = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            inputCriteria.Category = stepFoodContext.Text;

            return(await context.CallSubOrchestratorAsync <WizardResult>("FoodGeoLocationFunction", stepFoodContext.Id, inputCriteria));
        }
예제 #12
0
        public static async Task Run([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var input = context.GetInput <EarningsInput>();

            var result = new List <LearnerOutput>();

            var earningsByLearner = input.Earnings.GroupBy(x => x.LearnerReferenceNumber).Select(x => x);

            try
            {
                foreach (var learner in earningsByLearner)
                {
                    var learnerCommitments = input.Commitments.Where(x => x.LearnerReferenceNumber == learner.Key).ToList();
                    var learnerAccounts    = input.Accounts.Where(l => learnerCommitments.Select(x => x.Id).Contains(l.Id)).ToList();
                    var earningInput       = new EarningsInput(input.Ukprn, learnerCommitments, learner.ToList(), learnerAccounts);
                    result.Add(await context.CallSubOrchestratorAsync <LearnerOutput>(nameof(EarningsOrchestrator), earningInput));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine(JsonConvert.SerializeObject(result));
        }
        public static async Task <ResponseObject> DeviceSleepCheck(
            [OrchestrationTrigger] DurableOrchestrationContext context, Microsoft.Azure.WebJobs.ExecutionContext executionContext, ILogger log)
        {
            var devAddr           = context.GetInput <string>();
            var jsonTempaltesPath = Path.Combine(executionContext.FunctionDirectory, @"..\json_templates");
            var json = File.ReadAllText(jsonTempaltesPath + @"\enumerate.json");

            json = json.Replace("#DEV_ADDR#", $"{devAddr}");

            while (true)
            {
                var resEnum = await context.CallSubOrchestratorAsync <string>("GWSendCommandWithResponse", json);


                var errorMessage = Utils.CheckResponse(resEnum, out dynamic resEnumJObject);
                if (errorMessage != "" && resEnumJObject.data.statusStr != "info missing")
                {
                    log.LogInformation("Enumerate error: " + errorMessage);
                    return(new ResponseObject(ResultMessages.ErrorResult, ResultMessages.DiscoveryError, errorMessage));
                }

                if (resEnumJObject.data.statusStr != "info missing")
                {
                    return(new ResponseObject(ResultMessages.Success, ResultMessages.EnumerateSuccess, resEnum));
                }
                else
                {
                    // Orchestration sleeps until this time.
                    var nextCheck = context.CurrentUtcDateTime.AddSeconds(10);
                    await context.CreateTimer(nextCheck, CancellationToken.None);
                }
            }
        }
        public async Task RenewCertificates([OrchestrationTrigger] DurableOrchestrationContext context, ILogger log)
        {
            var activity = context.CreateActivityProxy <ISharedFunctions>();

            var certificates = await activity.GetCertificates(context.CurrentUtcDateTime);

            if (certificates.Count == 0)
            {
                log.LogInformation("Certificates are not found");

                return;
            }

            foreach (var certificate in certificates)
            {
                log.LogInformation($"{certificate.Id} - {certificate.Attributes.Expires}");

                string frontdoorName = "";
                if (certificate.Tags.ContainsKey("FrontDoor"))
                {
                    frontdoorName = certificate.Tags["FrontDoor"];
                }

                await context.CallSubOrchestratorAsync(nameof(SharedFunctions.IssueCertificate), (certificate.Policy.X509CertificateProperties.SubjectAlternativeNames.DnsNames, frontdoorName));
            }
        }
예제 #15
0
        public static async Task <object> ProcessRequest([OrchestrationTrigger] DurableOrchestrationContext ctx, TraceWriter log)
        {
            var requestPayload = ctx.GetInput <RequestPayload>();

            if (!ctx.IsReplaying)
            {
                log.Info("About to call Process Document Orchestrator");
            }

            var documents = await ctx.CallSubOrchestratorAsync <Document[]>("ProcessDocumentOrchestrator", requestPayload);

            //if (!ctx.IsReplaying)
            //    log.Info("About to call extract thumbanil activity");

            //var thumbnailLocation = await ctx.CallActivityAsync<string>("A_ExtractThumbnail", transcodedLocation);

            //if (!ctx.IsReplaying)
            //    log.Info("About to call prepend intro activity");

            //var withIntroLocation = await ctx.CallActivityAsync<string>("A_PrependIntro", transcodedLocation);

            return(new
            {
                Documets = documents
            });
        }
        public async Task <string> StartTestOrchestrators([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var testSettings = context.GetInput <TestSettings>();

            var regionTasks = new List <Task <RegionSettings> >();

            foreach (var(location, count) in testSettings.Regions)
            {
                for (var i = 0; i < count; i++)
                {
                    regionTasks.Add(
                        context.CallSubOrchestratorAsync <RegionSettings>(nameof(RunTestInRegionOrchestrator),
                                                                          new RegionSettings
                    {
                        TestId   = testSettings.TestId,
                        Region   = location,
                        FileName = testSettings.FileName
                    }));
                }
            }

            var results = await Task.WhenAll(regionTasks);

            var mergeReportUrl = await context.CallActivityAsync <string>(nameof(GatlingActivities.GenerateMergedReport),
                                                                          results);

            var deleteTasks = results.Select(result =>
                                             context.CallActivityAsync(nameof(AciActivities.DeleteAciInRegion), result.ContainerName)).ToList();

            await Task.WhenAll(deleteTasks);

            return(mergeReportUrl);
        }
예제 #17
0
        public static async Task RunOrchestrator([OrchestrationTrigger] DurableOrchestrationContext context, ILogger log)
        {
            // 期限切れまで 30 日以内の証明書を取得する
            var certificates = await context.CallActivityAsync <IList <CertificateBundle> >(nameof(SharedFunctions.GetCertificates), context.CurrentUtcDateTime);

            // 更新対象となる証明書がない場合は終わる
            if (certificates.Count == 0)
            {
                log.LogInformation("Certificates are not found");

                return;
            }

            var tasks = new List <Task>();

            // 証明書の更新を行う
            foreach (var certificate in certificates)
            {
                log.LogInformation($"{certificate.Id} - {certificate.Attributes.Expires}");

                // 証明書の更新処理を開始
                tasks.Add(context.CallSubOrchestratorAsync(nameof(SharedFunctions.IssueCertificate), certificate.Policy.X509CertificateProperties.SubjectAlternativeNames.DnsNames));
            }

            // サブオーケストレーターの完了を待つ
            await Task.WhenAll(tasks);
        }
예제 #18
0
        public static async Task <WizardResult> GetResult(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var inputCriteria = context.GetInput <EventInputCriteria>();

            var wizardStep = new WizardStep
            {
                Id       = Guid.NewGuid().ToString(),
                Event    = "step-event-geolocation",
                Question = "In what range do you wanna get results?",
                Answers  = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "1 kilometer", Value = "1000"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "5 kilometer", Value = "5000"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "10 kilometer", Value = "10000"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "50 kilometer", Value = "50000"
                    },
                }
            };

            context.SetCustomStatus(wizardStep);

            var stepGeoLocationContext = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            inputCriteria.Range = double.Parse(stepGeoLocationContext.Value);

            return(await context.CallSubOrchestratorAsync <WizardResult>("EventDateRangeFunction", stepGeoLocationContext.Id, inputCriteria));
        }
        public static async Task StartApprovalFlowAsync(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var application = context.GetInput <ApplicationEntity>();

            try
            {
                var tweetId = await context.CallActivityAsync <long>(nameof(RequestApprovalAsync), application);

                var isFavorited = await context.CallSubOrchestratorAsync <bool>(nameof(TweetMonitoringFunction.StartTweetMonitoringAsync), tweetId);

                if (isFavorited)
                {
                    await context.CallActivityAsync(nameof(MarkApprovedAsync), application);
                }
                else
                {
                    await context.CallActivityAsync(nameof(MarkRejectedAsync), application);
                }
            }
            catch (Exception)
            {
                await context.CallActivityAsync(nameof(MarkFailedAsync), application);
            }
        }
예제 #20
0
        public async Task <ScopeCreepActivityResponse> ScopeCreepOrchestrator([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var request = context.GetInput <ScopeCreepActivityRequest>();

            var response = await context.CallActivityAsync <ScopeCreepActivityResponse>("ScopeCreepActivity", request);

            if (response.Depth < request.DepthRequested)
            {
                request = new ScopeCreepActivityRequest()
                {
                    Depth          = request.Depth + 1,
                    DepthRequested = request.DepthRequested
                };

                response = await context.CallSubOrchestratorAsync <ScopeCreepActivityResponse>("ScopeCreepOrchestrator", request);

                if (response.Depth < request.DepthRequested)
                {
                    context.ContinueAsNew(request, true);
                }
            }

            await context.CreateTimer(context.CurrentUtcDateTime.AddSeconds(5), CancellationToken.None);

            return(response);
        }
        public static async Task Orchestrate(
            [OrchestrationTrigger] DurableOrchestrationContext ctx)
        {
            var inpaintRequest = ctx.GetInput <InpaintRequest>();

            // TODO: get the setting from parameters
            var settings = new InpaintSettings();

            // TODO: downscale the input image
            // TODO: crop the input image

            var pyramid = await ctx.CallActivityAsync <CloudPyramid>(PyramidsGenerateActivity.Name, inpaintRequest);

            settings.MaxInpaintIterations = 20;
            //settings.PatchMatch.IterationsAmount = 2;
            //var kStep = settings.MeanShift.KDecreaseStep;
            //var minK = settings.MeanShift.MinK;

            for (byte levelIndex = 0; levelIndex < pyramid.LevelsAmount; levelIndex++)
            {
                var imageName   = pyramid.GetImageName(levelIndex);
                var mapping     = pyramid.GetMapping(levelIndex);
                var nnf         = pyramid.GetNnf(levelIndex);
                var inpaintArea = pyramid.GetInpaintArea(levelIndex);
                var mappings    = pyramid.GetSplittedMappings(levelIndex);
                var nnfs        = pyramid.GetSplittedNnfs(levelIndex);

                // TODO: this looks ugly
                var input = NnfInputData.From(nnf, inpaintRequest.Container, imageName, settings, mapping, inpaintArea, false, levelIndex, settings.MeanShift.K, nnfs, mappings);
                await ctx.CallSubOrchestratorAsync(InpaintLevelFunction.Name, input);
            }
        }
예제 #22
0
        public static async Task <WizardResult> GetResult(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var inputCriteria = context.GetInput <EventInputCriteria>();

            var wizardStep = new WizardStep
            {
                Id       = Guid.NewGuid().ToString(),
                Event    = "step-event",
                Question = "What kind of events do you like?",
                Answers  = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Music", Value = "music"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Multicultural", Value = "multicultural"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Comedy", Value = "comedy"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Art", Value = "art"
                    },
                }
            };

            context.SetCustomStatus(wizardStep);

            var stepFoodContext = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            inputCriteria.Category = stepFoodContext.Text;

            return(await context.CallSubOrchestratorAsync <WizardResult>("EventGeoLocationFunction", stepFoodContext.Id, inputCriteria));
        }
        public static async Task <WizardResult> GetResult(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var inputCriteria = context.GetInput <EventInputCriteria>();

            var wizardStep = new WizardStep
            {
                Id             = Guid.NewGuid().ToString(),
                Event          = "step-event-daterage",
                Question       = "Which events do you want to find",
                IsLastQuestion = true,
                Answers        = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Passed events", Value = "PassedEvents"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Upcoming events", Value = "UpcomingEvents"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "All events", Value = "AllEvents"
                    },
                }
            };

            context.SetCustomStatus(wizardStep);

            var stepDateRangeContext = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            inputCriteria.DateCriteria = stepDateRangeContext.Value;

            return(await context.CallSubOrchestratorAsync <WizardResult>("GetEventResultFunction", stepDateRangeContext.Id, inputCriteria));
        }
        public static async Task <bool> Run(
            [OrchestrationTrigger] DurableOrchestrationContext context,
            TraceWriter log)
        {
            log.Info("ValidateSiteContent Orchestrator called");

            string rootDirectory = context.GetInput <string>()?.Trim();

            if (string.IsNullOrEmpty(rootDirectory))
            {
                throw new ArgumentNullException(
                          nameof(rootDirectory),
                          "A directory path input is required.");
            }

            string[] files = await context.CallActivityAsync <string[]>(
                "GetFileList",
                rootDirectory);

            var tasks = new Task[files.Length];

            for (int i = 0; i < files.Length; i++)
            {
                tasks[i] = context.CallSubOrchestratorAsync("ValidateAndCopyFiles", files[i]);
            }

            await Task.WhenAll(tasks);

            return(true);
        }
예제 #25
0
        public static async Task <List <string> > RunOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var outputs = new List <string>();
            // Create Branch
            var translationContext =
                await context.CallActivityAsync <OrchestrationContext>("CreateBranchActivity",
                                                                       context.GetInput <OrchestrationContext>());

            // Search Md Files
            translationContext = await context.CallActivityAsync <OrchestrationContext>("SearchMdActivity",
                                                                                        translationContext);

            // Update All MdFiles
            var tasks = new List <Task <string> >();

            foreach (var path in translationContext.Paths)
            {
                tasks.Add(context.CallSubOrchestratorAsync <string>("TranslationSubOrchestrator",
                                                                    translationContext.ConvertSubOrchestrationContext(path)));
                // In case you've got throttling. You might get an conflict. It covered by retry.
                //var waitTime = context.CurrentUtcDateTime.Add(TimeSpan.FromSeconds(3));
                //await context.CreateTimer(waitTime, CancellationToken.None);
            }

            await Task.WhenAll(tasks);

            return(tasks.Select(p => p.Result).ToList());
        }
예제 #26
0
        public static async Task <string> RunOrchestrator(
            [OrchestrationTrigger] DurableOrchestrationContext context
            , ExecutionContext contex
            , ILogger log)
        {
            var session = context.GetInput <UserSession>();

            var compute = await context.CallActivityAsync <Compute>("CreateCompute", session.CaseNumber);

            var startState = new CustomState();

            startState.CaseNumber = session.CaseNumber;
            startState.userId     = session.userId;
            startState.Compute    = compute;
            startState.InstanceId = context.InstanceId;
            context.SetCustomStatus(startState);

            log.LogInformation("Saved Compute State");
            var eventsOrchestratorEventId = GetEventListenerInstanceId(context.InstanceId);
            await context.CallSubOrchestratorAsync <string>("EngineInstanceEvents", eventsOrchestratorEventId, null);

            log.LogInformation("Completed eventListnerOrchestrator");

            return(context.InstanceId);
        }
        public static async Task <WizardResult> GetResult(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            var inputCriteria = context.GetInput <AttractionInputCriteria>();

            var wizardStep = new WizardStep
            {
                Id       = Guid.NewGuid().ToString(),
                Event    = "step-attration",
                Question = "What would you like to visit?",
                Answers  = new[]
                {
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Museum", Value = "museum"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Cinema", Value = "cinema"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Church", Value = "church"
                    },
                    new Answer {
                        Id = Guid.NewGuid().ToString(), Text = "Club", Value = "club"
                    },
                }
            };

            context.SetCustomStatus(wizardStep);

            var stepFoodContext = await context.WaitForExternalEvent <Answer>(wizardStep.Event);

            inputCriteria.Category = stepFoodContext.Text;

            return(await context.CallSubOrchestratorAsync <WizardResult>("AttractionGeoLocationFunction", stepFoodContext.Id, inputCriteria));
        }
예제 #28
0
        public static async Task Run(
            [OrchestrationTrigger] DurableOrchestrationContext context)
        {
            OrdiniAcquistoModel ordineAcquisto = context.GetInput <OrdiniAcquistoModel>();

            // Utilizzo un Id di esempio.
            ordineAcquisto.IdOrdine = context.InstanceId;

            // Invia notifica ordine via SMS
            string smsInstance = await context.CallActivityAsync <string>(
                Workflow.NotificaSmsOrdineCliente,
                ordineAcquisto);

            // Il SubOrchestrator non è necessario, è un esempio
            await context.CallSubOrchestratorAsync(Workflow.AttendiOrdineCliente, ordineAcquisto);

            // Utilizzo l'orario di start della funzione
            DateTime startManagerDatetime = context.CurrentUtcDateTime;
            await context.CallActivityAsync(Workflow.OrdineConfermato, new OrdiniAcquistoTable
            {
                PartitionKey             = ordineAcquisto.IdOrdine,
                RowKey                   = $"{smsInstance}-{context.InstanceId}",
                Ordine                   = ordineAcquisto,
                NotificaSmsOrdineCliente = smsInstance,
                InviaMailOrdineCliente   = context.InstanceId,
                Elaborazione             = startManagerDatetime
            });
        }
        public static async Task <string> RunGWManagementAction(
            [OrchestrationTrigger] DurableOrchestrationContext context, Microsoft.Azure.WebJobs.ExecutionContext executionContext, ILogger log)
        {
            string  result            = "";
            string  reqBody           = context.GetInput <string>();
            dynamic reqBodyJsonObject = JsonConvert.DeserializeObject(reqBody);

            var    jsonTempaltesPath = System.IO.Path.Combine(executionContext.FunctionDirectory, @"..\json_templates");
            string json;

            switch ($"{ reqBodyJsonObject.requestType}")
            {
            case "unbondDevice":

                //1. Wait for device to wake up
                //Setting custom status
                context.SetCustomStatus("{\"Status\":\"Device is Sleeping\"}");
                await context.CallSubOrchestratorAsync <ResponseObject>("DeviceSleepCheck", reqBodyJsonObject.devAddr);

                context.SetCustomStatus("{\"Status\":\"Device has woken up\"}");

                //2. Remove bonded sensor from GW
                context.SetCustomStatus($"{{\"Status\":\"Removing device from GW\"}}");
                json = System.IO.File.ReadAllText(jsonTempaltesPath + @"\remove_bonded_device.json");
                json = json.Replace("#DEV_ADDR#", $"{reqBodyJsonObject.devAddr}");

                result = await context.CallSubOrchestratorAsync <string>("GWSendCommandWithResponse", json);

                //3. Update DB
                context.SetCustomStatus($"{{\"Status\":\"Updating DB entry\"}}");
                string unbondQuery = "UPDATE dbo.Sensor " +
                                     $"SET [GatewayIndex] = NULL, [GatewayID] = NULL WHERE ID = {reqBodyJsonObject.sensorID}";
                await context.CallActivityAsync <string>("InvokeDatabaseOperation", unbondQuery);

                break;

            case "testCommand":
                result = await context.CallSubOrchestratorAsync <string>("GWSendCommandWithResponse", "testCommand");

                break;

            default:
                break;
            }

            return(result);
        }
예제 #30
0
        public static async Task Orchestrator([OrchestrationTrigger] DurableOrchestrationContext context)
        {
            ValueTuple <EventGridEvent, MediaWorkflowManifest> contextInput = context.GetInput <(EventGridEvent, MediaWorkflowManifest)>();
            EventGridEvent        queueMessage     = contextInput.Item1;
            MediaWorkflowManifest workflowManifest = contextInput.Item2;

            string inputFileName = workflowManifest.InputFileName;

            if (string.IsNullOrEmpty(inputFileName))
            {
                inputFileName = Path.GetFileName(queueMessage.Subject);
            }

            if (inputFileName.Equals(Constant.Storage.Blob.WorkflowContainerFiles, _stringComparison))
            {
                List <Task> parallelTasks = new List <Task>();
                string[]    blobNames     = await context.CallActivityAsync <string[]>("MediaWorkflow-BlobList", null);

                foreach (string blobName in blobNames)
                {
                    ValueTuple <MediaWorkflowManifest, string> workflowInput = (workflowManifest, blobName);
                    if (workflowManifest.JobInputMode == MediaJobInputMode.Asset)
                    {
                        Task parallelTask = context.CallSubOrchestratorAsync("MediaWorkflow-InputModeAsset", workflowInput);
                        parallelTasks.Add(parallelTask);
                    }
                    else
                    {
                        Task parallelTask = context.CallSubOrchestratorAsync("MediaWorkflow-InputModeFile", workflowInput);
                        parallelTasks.Add(parallelTask);
                    }
                }
                await Task.WhenAll(parallelTasks);
            }
            else
            {
                ValueTuple <MediaWorkflowManifest, string> workflowInput = (workflowManifest, inputFileName);
                if (workflowManifest.JobInputMode == MediaJobInputMode.Asset)
                {
                    await context.CallSubOrchestratorAsync("MediaWorkflow-InputModeAsset", workflowInput);
                }
                else
                {
                    await context.CallSubOrchestratorAsync("MediaWorkflow-InputModeFile", workflowInput);
                }
            }
        }