public void CreateFlowAndExecute() { var flow = Flow <FlowContext <States, Action>, States, Action> .create(States.First) .When(States.First, (c) => c.State = States.Second) .To(States.Second, Action.Tick, States.First) .On(States.First, (state) => { state .Catch(typeof(MyException), States.Error, terminate: true) .Catch((ctx, e) => Console.WriteLine("ERROR:{0}", e.Message)) .When(Action.Tick, (ctx) => { Console.WriteLine("Tick in First"); }).When(Action.Error, (ctx) => { throw new MySubException(); }); }) .Catch(typeof(Exception), (context) => { Console.WriteLine("Exception"); }) .Build(); var myContext = new FlowContext <States, Action>(); flow.Execute(myContext, Action.Tick); flow.Execute(myContext, Action.Error); Assert.AreEqual(myContext.State, States.Error); }
/// <summary> /// Request Account Access /// /// Manual process: /// You have to go manually to the bankURL, authenticate there and grant the permission to access the account(s) /// The bank will then redirect you, you must copy the query string and put it back in the application to continue /// /// FlowId: /// In this particular case, Crelan ask for a fixed FlowId /// Most of the time, you need to provide a unique identifier /// </summary> static async Task RequestAccountsAccessAsync(IBankingConnector bankConnector) { // Initialize account access request BankingResult <string> bankingResult = await bankConnector.RequestAccountsAccessAsync(new AccountsAccessRequest { FlowId = "STATE", //Guid.NewGuid().ToString() FrequencyPerDay = 2, RedirectUrl = RedirectURL, }); if (bankingResult.GetStatus() == ResultStatus.REDIRECT) { // FlowContext must be reused FlowContext flowContext = bankingResult.GetFlowContext(); // Ask the user to manually go to the redirect URL and enter the result string bankURL = bankingResult.GetData(); Console.WriteLine($"URL: {bankURL}"); Console.Write("Enter code: "); string queryString = Console.ReadLine(); Console.Write(flowContext); // Finalize authentication BankingResult <IUserContext> result = await bankConnector.RequestAccountsAccessFinalizeAsync(flowContext, queryString); if (result.GetStatus() == ResultStatus.DONE) { Console.WriteLine("RequestAccountsAccess succeeded"); return; } } throw new Exception("RequestAccountsAccess failed"); }
public void LogActivityResponse(FlowContext flowContext, object activityResponse, long elapsedMilliseconds) { _logger.LogDebug(flowContext, "{ActivityResponseTypeName}({ActivityResponseSummary}) in {ActivityMillis}ms", _logger.EvalIfDebug(() => activityResponse.GetType().Name), _logger.EvalIfDebug(() => GetPublicPropertySummary(activityResponse)), elapsedMilliseconds); }
public override void OnFlow(FlowContext flowContext) { for (int i = 0; i < flowContext.Messages; i++) { AMQPMessage data; if (_messages.TryTake(out data)) { if (data.Stop.HasValue && data.Stop.Value) { _end.SetException(new StopTestSignalException()); } var message = new Message(data.Body); message.Properties = new Properties() { Subject = "Message" + Interlocked.Increment(ref this._id) }; flowContext.Link.SendMessage(message); if (!data.Batched) { return; } } else { var message = new Message(); message.Properties = new Properties() { Subject = "Message" + Interlocked.Increment(ref this._id) }; flowContext.Link.SendMessage(message); } } }
/// <summary> /// 更新通道 /// </summary> /// <param name="deviceContext">数据库实例</param> /// <param name="updateChannel">更新的通道</param> /// <returns>更新成功时返回true,如果未找到通道返回false</returns> public static bool UpdateChannel(FlowContext deviceContext, FlowChannel updateChannel) { FlowChannel channel = deviceContext.Channels .Include(c => c.Lanes) .SingleOrDefault(c => c.ChannelId == updateChannel.ChannelId); if (channel == null) { return(false); } else { channel.ChannelName = updateChannel.ChannelName; channel.ChannelType = updateChannel.ChannelType; channel.ChannelIndex = updateChannel.ChannelIndex; channel.RtspUser = updateChannel.RtspUser; channel.RtspPassword = updateChannel.RtspPassword; channel.RtspProtocol = updateChannel.RtspProtocol; channel.IsLoop = updateChannel.IsLoop; channel.SectionId = updateChannel.SectionId; channel.RoadSection = null; channel.CrossingId = updateChannel.CrossingId; channel.RoadCrossing = null; channel.Lanes = updateChannel.Lanes; deviceContext.Channels.Update(channel); return(true); } }
public async Task <BankingResult <string> > CreatePaymentInitiationRequestAsync(PaymentInitiationRequest model) { try { var paymentRequest = new KbcPaymentRequest { creditorAccount = new Models.Requests.KbcCreditorAccount { iban = model.Recipient.Iban }, creditorName = model.Recipient.Name, debtorAccount = new Models.Requests.KbcDebtorAccount { iban = model.Debtor.Iban, currency = model.Debtor.Currency }, instructedAmount = new Models.Requests.KbcInstructedAmount { amount = model.Amount.ToString("0.00", CultureInfo.InvariantCulture), currency = model.Currency }, endToEndIdentification = model.EndToEndId, requestedExecutionDate = model.RequestedExecutionDate?.ToString("yyyy-MM-dd"), remittanceInformationUnstructured = model.RemittanceInformationUnstructured }; var content = new StringContent(JsonConvert.SerializeObject(paymentRequest), Encoding.UTF8, "application/json"); var client = GetClient(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("PSU-IP-Address", model.PsuIp); client.DefaultRequestHeaders.Add("TPP-Redirect-URI", $"{model.RedirectUrl}?flowId={model.FlowId}"); var url = $"/psd2/v2/payments/sepa-credit-transfers"; var result = await client.PostAsync(url, content); var rawData = await result.Content.ReadAsStringAsync(); var paymentResult = JsonConvert.DeserializeObject <KbcPaymentInit>(rawData); var flowContext = new FlowContext { Id = model.FlowId, ConnectorType = ConnectorType, FlowType = FlowType.Payment, PaymentProperties = new PaymentProperties { PaymentId = paymentResult.paymentId } }; return(new BankingResult <string>(ResultStatus.REDIRECT, url, paymentResult._links.scaRedirect, rawData, flowContext: flowContext)); } catch (ApiCallException e) { throw e; } catch (SdkUnauthorizedException e) { throw e; } catch (Exception e) { await LogAsync(apiUrl, 500, Http.Get, e.ToString()); throw e; } }
/// <summary> /// 添加通道 /// </summary> /// <param name="deviceContext">数据库上下文</param> /// <param name="newChannel">新通道</param> public static void AddChannel(FlowContext deviceContext, FlowChannel newChannel) { newChannel.ChannelStatus = (int)DeviceStatus.异常; newChannel.RoadSection = null; newChannel.RoadCrossing = null; deviceContext.Channels.Add(newChannel); }
private void AddPermissoesSuperUser(FlowContext db) { var userManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db)); var user = userManager.FindByName("*****@*****.**"); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db)); if (!userManager.IsInRole(user.Id, "Criar")) { userManager.AddToRole(user.Id, "Criar"); } if (!userManager.IsInRole(user.Id, "Visualizar")) { userManager.AddToRole(user.Id, "Visualizar"); } if (!userManager.IsInRole(user.Id, "Editar")) { userManager.AddToRole(user.Id, "Editar"); } if (!userManager.IsInRole(user.Id, "Deletar")) { userManager.AddToRole(user.Id, "Deletar"); } if (!userManager.IsInRole(user.Id, "Corporativo")) { userManager.AddToRole(user.Id, "Corporativo"); } if (!userManager.IsInRole(user.Id, "Administrador")) { userManager.AddToRole(user.Id, "Administrador"); } }
public void LogFlowInnerException(FlowContext flowContext, Exception ex) { _logger.LogError(flowContext, ex, "Inner exception", ex.GetType().Name); _logger.LogError("{ExceptionType}: {ExceptionMessage}", ex.GetType().Name, ex.Message); _logger.LogError("{ExceptionStackTrace}", ex.StackTrace); }
public override void Execute(FlowContext <T> context) { if (action != null) { action.Invoke(context); } }
public void TwentyQuestions_returns_expected_guess( string hasLegsAnswer, string legCountAnswer, string eatsHayAnswer, string canFlyAnswer, string hasScalesAnswer, string expectedGuess) { var serviceCollection = new ServiceCollection() .AddMediatR(typeof(TwentyQuestionsRequest).Assembly); using (var serviceProvider = serviceCollection.BuildServiceProvider()) { var flowContext = new FlowContext() .MockQuestionActivity("AskHasLegs", hasLegsAnswer) .MockQuestionActivity("AskLegCount", legCountAnswer) .MockQuestionActivity("AskEatsHay", eatsHayAnswer) .MockQuestionActivity("AskCanFly", canFlyAnswer) .MockQuestionActivity("AskHasScales", hasScalesAnswer) .MockGuessActivity(); var mediator = serviceProvider.GetService <IMediator>(); var response = mediator.Send(new TwentyQuestionsRequest { FlowContext = flowContext }) .GetAwaiter().GetResult(); Assert.Equal(expectedGuess, response.Guess); } }
public async void Can_only_mock_root_flow(bool isMocked) { // Arrange var(mediator, _) = GetMediator <MockActivityViaFlowRFlowRequest>(); var flowContext = new FlowContext(null, null); if (isMocked) { flowContext .MockActivity <CanMockOnlyRootSetValueRequest, CanMockOnlyRootSetValueResponse>( request => new CanMockOnlyRootSetValueResponse { Value = false }); } // Act var response = await mediator.Send(new CanMockOnlyRootFlowRequest { FlowContext = flowContext }); // Assert Assert.True(response.Value, "response.Value"); }
private void CriarRoles(FlowContext db) { var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(db)); if (!roleManager.RoleExists("Criar")) { roleManager.Create(new IdentityRole("Criar")); } if (!roleManager.RoleExists("Visualizar")) { roleManager.Create(new IdentityRole("Visualizar")); } if (!roleManager.RoleExists("Editar")) { roleManager.Create(new IdentityRole("Editar")); } if (!roleManager.RoleExists("Deletar")) { roleManager.Create(new IdentityRole("Deletar")); } if (!roleManager.RoleExists("Corporativo")) { roleManager.Create(new IdentityRole("Corporativo")); } if (!roleManager.RoleExists("Administrador")) { roleManager.Create(new IdentityRole("Administrador")); } }
public void BaseTests_ApplyDiscount_FromVariables() { var flow = new Flow <BaseTestsModel>(); flow.Actions .If(c => c.Model.Type == "Gold", g => g.Action("20%", ctx => ctx.Model.Discount = ctx.Variables.Get <Decimal>("GoldDiscount")), "Type?", "Gold") .ElseIf(c => c.Model.Type == "Silver", s => s.Action("10%", ctx => ctx.Model.Discount = ctx.Variables.Get <Decimal>("SilverDiscount")), "Silver") .Else(e => e.Action("Other", ctx => ctx.Model.Discount = ctx.Variables.Get <Decimal>("OtherDiscount"))); var context = new FlowContext <BaseTestsModel>(new BaseTestsModel()); context.Variables.Set("GoldDiscount", .20M); context.Variables.Set("SilverDiscount", .10M); context.Variables.Set("OtherDiscount", .30M); context.Model.Type = "Gold"; flow.Execute(context); Assert.IsTrue(context.Model.Discount == .20M, "Gold discount is 20%"); context.Model.Type = "Silver"; flow.Execute(context); Assert.IsTrue(context.Model.Discount == .10M, "Silver discount is 10%"); context.Model.Type = "Other"; flow.Execute(context); Assert.IsTrue(context.Model.Discount == .30M, "Steel discount is 30%"); }
Flow LoadFlow() { var flow = ReadInstance(); FlowContext.Bind(flow, _key, _metadata.Position, TimelinePosition.None); return(flow); }
public static void ResetDatabase(IServiceProvider serviceProvider) { using (FlowContext context = serviceProvider.CreateScope().ServiceProvider.GetRequiredService <FlowContext>()) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); } }
void BindFlow(TimelinePosition position) { _flow = ReadData(); FlowContext.Bind(_flow, _key, position, TimelinePosition.None); _areaCheckpoint = position.ToInt64(); }
public void ReceiveMessage(FlowContext <string> flowContext) { System.Diagnostics.Debug.WriteLine("----- [C] message received: " + DateTime.Now); var nextMessage = string.Join(" -> ", flowContext.Messge, "C"); _capBus.Publish("B1", flowContext.Forward(nextMessage)); }
Task <FlowResumeInfo> StartAndResume() { var flow = _key.Type.New(); FlowContext.Bind(flow, _key); return(Resume(flow)); }
public LocalSymbolProvider(ISymbolProvider /*!*/ model, FlowContext /*!*/ ctx) { Debug.Assert(model != null); Debug.Assert(ctx != null); _model = model; _ctx = ctx; }
Query GetDefaultContent(FlowKey key) { var query = (Query)key.Type.New(); FlowContext.Bind(query, key); return(query); }
public AbstractState StartSsoLoginFlow() { var initialState = _stateFactory.CreateInitialState(); var flowContext = new FlowContext(initialState); flowContext.HandleLoginCompleted(); return(flowContext.CurrentState); }
public override void OnFlow(FlowContext flowContext) { for (int i = 0; i < flowContext.Messages; i++) { var message = new Message("test message"); flowContext.Link.SendMessage(message, message.Encode()); } }
public override void Execute(FlowContext <T> context) { Flow <T> conditionFlow = new Flow <T>(); GroupActions(conditionFlow.Actions); conditionFlow.Execute(context); }
public IActionResult PublishMessage2() { _capBus.Publish("D", FlowContext <List <string> > .Start(new List <string>() { "D" })); return(Ok(DateTime.Now)); }
public static FlowContext MockIdentityCheck(this FlowContext flowContext, IdentityCheckResult identityCheckResult) { flowContext.MockActivity <CheckIdentity, CheckIdentity.Response>( req => new CheckIdentity.Response { IdentityCheckResult = identityCheckResult }); return(flowContext); }
public void LogFlowException(FlowContext flowContext, IFlowStepRequest flowRequest, Exception ex) { _logger.LogError(flowContext, ex, "{ExceptionTypeName} occurred handling {RequestTypeName}({RequestSummary})", ex.GetType().Name, flowRequest.GetType().Name, _logger?.EvalIfError(() => GetPublicPropertySummary(flowRequest))); _logger.LogError("{ExceptionType}: {ExceptionMessage}", ex.GetType().Name, ex.Message); _logger.LogError("{ExceptionStackTrace}", ex.StackTrace); }
public override void OnFlow(FlowContext flowContext) { CancelFlowTask(); _flowTask = new CancellationTokenSource(); CancellationToken cancellationToken = _flowTask.Token; Task.Run(() => SendMessages(flowContext, cancellationToken)); }
public void Process_local_output(IMessage outputMsg) { var corrId = Guid.NewGuid(); var ctx = new FlowContext {Path = outputMsg.Port.Path, StandInOperationName = outputMsg.Port.OperationName, CorrelationId = outputMsg.CorrelationId, Priority = outputMsg.Priority, Causalities = outputMsg.Causalities, FlowStack = outputMsg.FlowStack}; _cache.Add(corrId, ctx); var input = new HostInput {Portname = outputMsg.Port.OutputPortToRemotePortname(), Data = outputMsg.Data.Serialize(), CorrelationId = corrId, StandInEndpointAddress = _standInEndpointAddress}; Translated_output(input); }
public static FlowContext MockCheckEligibility(this FlowContext flowContext, bool isEligible) { flowContext.MockActivity <CheckEligibility, CheckEligibility.Response>( req => new CheckEligibility.Response { IsEligible = isEligible }); return(flowContext); }
public static FlowContext MockSendEmail(this FlowContext flowContext, List <string> actualTemplateNames = null) { flowContext.MockActivity <SendEmail, SendEmail.Response>(req => { actualTemplateNames?.Add(req.TemplateName); return(new SendEmail.Response()); }); return(flowContext); }