/// <summary> /// The Live Pricing Service (flight query) returns all the flights available for a specific route and /// date (or single date for one-way searches). /// </summary> /// <param name="flightQuerySettings">Settings for the query</param> /// <param name="interimResultCallback">The callback that is called when interim results are recieved</param> /// <returns>The collection of itineraries from SkyScanner</returns> public async Task <List <Itinerary> > QueryFlight( FlightQuerySettings flightQuerySettings, Action <InterimChangeSet <Itinerary> > interimResultCallback, CancellationToken cancellationToken = default(CancellationToken)) { var interimResultHandler = new InterimResultProvider <FlightResponse, Itinerary>(); var flightService = new Flight(_apiKey, flightQuerySettings); return(await _executionStrategy.Execute(async() => { var pinger = await flightService.SendQuery(cancellationToken); if (interimResultCallback != null) { pinger.OnInterimResultsRecieved += (sender, args) => { interimResultCallback(interimResultHandler.Calculate(args)); }; } var response = await pinger.SendQuery(cancellationToken); return response.Itineraries; }, cancellationToken)); }
/// <summary> /// Executes the strategy /// </summary> public void Execute(object sender, EventArgs args) { if (strategy != null) { if (strategy.Route.IsSendEventArgs) { strategy.Execute(new object[] { CommandParameter, sender, args }); } else { //注入 strategy.Execute(CommandParameter); } } }
/// <summary> /// Executes the strategy /// </summary> public void Execute() { if (strategy != null) { strategy.Execute(CommandParameter); } }
public bool MoveNext() { try { using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection()) { if (_dataReader == null) { if (_executionStrategy == null) { _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create(); } _executionStrategy.Execute(true, InitializeReader, null); } var hasNext = _dataReader.Read(); Current = hasNext ? _shaper(_relationalQueryContext, _dataReader.DbDataReader, _indexMap) : default; return(hasNext); } } catch (Exception exception) { _queryLogger.QueryIterationFailed(_contextType, exception); throw; } }
private void ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report) { // Reset the stop watch. stopWatch.Reset(); stopWatch.Start(); PerformTaskSetup(context, strategy, task, false); bool exceptionWasThrown = false; try { // Execute the task. strategy.Execute(task, context); } catch (Exception exception) { _log.Error("An error occurred when executing task '{0}'.", task.Name); exceptionWasThrown = true; // Got an error reporter? if (task.ErrorReporter != null) { ReportErrors(strategy, task.ErrorReporter, exception); } // Got an error handler? if (task.ErrorHandler != null) { HandleErrors(strategy, task.ErrorHandler, exception); } else { // No error handler defined for this task. // Rethrow the exception and let it propagate. throw; } } finally { if (task.FinallyHandler != null) { strategy.InvokeFinally(task.FinallyHandler); } PerformTaskTeardown(context, strategy, task, stopWatch.Elapsed, false, exceptionWasThrown); } // Add the task results to the report if (IsDelegatedTask(task)) { report.AddDelegated(task.Name, stopWatch.Elapsed); } else { report.Add(task.Name, stopWatch.Elapsed); } }
public bool MoveNext() { try { using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection()) { if (_dataReader == null) { if (_executionStrategy == null) { _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create(); } _executionStrategy.Execute(true, InitializeReader, null); } var hasNext = _resultCoordinator.HasNext ?? _dataReader.Read(); Current = default; if (hasNext) { while (true) { _resultCoordinator.ResultReady = true; _resultCoordinator.HasNext = null; Current = _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _indexMap, _resultCoordinator); if (_resultCoordinator.ResultReady) { // We generated a result so null out previously stored values _resultCoordinator.ResultContext.Values = null; break; } if (!_dataReader.Read()) { _resultCoordinator.HasNext = false; // Enumeration has ended, materialize last element _resultCoordinator.ResultReady = true; Current = _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _indexMap, _resultCoordinator); break; } } } return(hasNext); } } catch (Exception exception) { _logger.QueryIterationFailed(_contextType, exception); throw; } }
/// <summary> /// Executes the strategy /// </summary> public void Execute() { if (strategy == null) { return; //DataGrid的添加操作可能为空 } strategy.Execute(CommandParameter); }
/// <summary> /// Executes the specified operation and returns the result. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-connection-resiliency">Connection resiliency and database retries</see> /// for more information and examples. /// </remarks> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <typeparam name="TResult">The return type of <paramref name="operation" />.</typeparam> /// <returns>The result from the operation.</returns> public static TResult Execute <TResult>( this IExecutionStrategy strategy, Func <TResult> operation) { Check.NotNull(operation, nameof(operation)); return(strategy.Execute(operation, operationScoped => operationScoped())); }
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation">A delegate representing an executable operation that doesn't return any results.</param> public static void Execute( [NotNull] this IExecutionStrategy strategy, [NotNull] Action operation) => strategy.Execute(operationScoped => { operationScoped(); return(true); }, operation);
/// <summary> /// Executes the specified operation and returns the result. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-connection-resiliency">Connection resiliency and database retries</see> /// for more information and examples. /// </remarks> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <param name="verifySucceeded">A delegate that tests whether the operation succeeded even though an exception was thrown.</param> /// <param name="state">The state that will be passed to the operation.</param> /// <typeparam name="TState">The type of the state.</typeparam> /// <typeparam name="TResult">The return type of <paramref name="operation" />.</typeparam> /// <returns>The result from the operation.</returns> /// <exception cref="RetryLimitExceededException"> /// The operation has not succeeded after the configured number of retries. /// </exception> public static TResult Execute <TState, TResult>( this IExecutionStrategy strategy, TState state, Func <TState, TResult> operation, Func <TState, ExecutionResult <TResult> >?verifySucceeded) => strategy.Execute( state, (c, s) => operation(s), verifySucceeded == null ? null : (c, s) => verifySucceeded(s));
public static TResult Execute <TState, TResult>( [NotNull] this IExecutionStrategy strategy, [NotNull] Func <TState, TResult> operation, [CanBeNull] Func <TState, ExecutionResult <TResult> > verifySucceeded, [CanBeNull] TState state) => strategy.Execute( state, operation, verifySucceeded);
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation">A delegate representing an executable operation that doesn't return any results.</param> /// <param name="state">The state that will be passed to the operation.</param> /// <typeparam name="TState">The type of the state.</typeparam> public static void Execute <TState>( [NotNull] this IExecutionStrategy strategy, [NotNull] Action <TState> operation, [CanBeNull] TState state) => strategy.Execute(s => { s.operation(s.state); return(true); }, new { operation, state });
/// <summary> /// Executes the strategy /// </summary> public void Execute() { if (strategy == null) { System.Diagnostics.Debug.Print("CommandBehaviorBinding.Execute: Command or Action undefined."); } else { strategy.Execute(this); } }
/// <summary> /// Executes the strategy /// </summary> public void Execute() { try { strategy.Execute(CommandParameter); } catch (Exception ex) { MessageBox.Show(ex.Message); }; }
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation">A delegate representing an executable operation that doesn't return any results.</param> public static void Execute( [NotNull] this IExecutionStrategy strategy, [NotNull] Action operation) { Check.NotNull(operation, nameof(operation)); strategy.Execute(operation, operationScoped => { operationScoped(); return(true); }); }
/// <summary> /// Executes the specified operation. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="state">The state that will be passed to the operation.</param> /// <param name="operation">A delegate representing an executable operation that doesn't return any results.</param> /// <typeparam name="TState">The type of the state.</typeparam> public static void Execute <TState>( [NotNull] this IExecutionStrategy strategy, [CanBeNull] TState state, [NotNull] Action <TState> operation) { Check.NotNull(operation, nameof(operation)); strategy.Execute(new { operation, state }, s => { s.operation(s.state); return(true); }); }
public void Test2() { IExecutionStrategy strategy = dbContext.Database.CreateExecutionStrategy(); strategy.Execute(() => { using (DbTransaction transaction = dbConnection.BeginTransaction()) { Client client = new Client(); client.ClientId = 3; client.Name = "New Client 3"; dbContext.Database.UseTransaction(transaction); dbContext.Entry <Client>(client).State = EntityState.Modified; List <Client> clients = new List <Client>(); clients.Add(new Client { ClientId = 1, Name = "New Client 1", }); clients.Add(new Client { ClientId = 2, Name = "New Client 2", }); clients.Add(new Client { ClientId = 4, Name = "New Client 4", }); string sql = "UPDATE Client SET Name = @Name WHERE ClientId = @ClientId;"; try { dbContext.SaveChanges(); dbConnection.Execute(sql, clients, transaction: transaction); transaction.Commit(); } catch (System.Exception ex) { } } }); }
/// <summary> /// Executes the specified action in a database transaction and returns a collection of records. /// </summary> /// <typeparam name="T">Result model class</typeparam> /// <param name="collection">Action returning a collection of records</param> public IQueryable <T> Transaction <T>(Func <IQueryable <T> > collection) where T : class { IQueryable <T> result = null; IExecutionStrategy strategy = Database.CreateExecutionStrategy(); // retry on transient exceptions (we have to do it manually because of transactions) strategy.Execute(() => // note: all transient exceptions outside of the BeginTransaction block are handled globally { using (IDbContextTransaction transaction = Database.BeginTransaction()) { result = collection().ToList().AsQueryable();; // cannot iterate through the collection before committing changes transaction.Commit(); } }); return(result); }
/// <summary> /// Executes the strategy /// </summary> public void Execute(string eventName, object eventArgs) { try { if (_strategy == null) { return; } _strategy.Execute(CommandParameter, eventName, eventArgs); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private void ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report) { // Reset the stop watch. stopWatch.Reset(); stopWatch.Start(); try { // Execute the task. strategy.Execute(task, context); } catch (Exception exception) { _log.Error("An error occured when executing task.", task.Name); // Got an error reporter? if (task.ErrorReporter != null) { ReportErrors(strategy, task.ErrorReporter, exception); } // Got an error handler? if (task.ErrorHandler != null) { HandleErrors(strategy, task.ErrorHandler, exception); } else { // No error handler defined for this task. // Rethrow the exception and let it propagate. throw; } } finally { if (task.FinallyHandler != null) { strategy.InvokeFinally(task.FinallyHandler); } } // Add the task results to the report. report.Add(task.Name, stopWatch.Elapsed); }
/// <summary> /// Executes the specified operation in a transaction and returns the result after commiting it. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <param name="verifySucceeded"> /// A delegate that tests whether the operation succeeded even though an exception was thrown when the /// transaction was being committed. /// </param> /// <param name="state"> The state that will be passed to the operation. </param> /// <param name="context"> The context that will be used to start the transaction. </param> /// <typeparam name="TState"> The type of the state. </typeparam> /// <typeparam name="TResult"> The return type of <paramref name="operation" />. </typeparam> /// <returns> The result from the operation. </returns> /// <exception cref="RetryLimitExceededException"> /// Thrown if the operation has not succeeded after the configured number of retries. /// </exception> public static TResult ExecuteInTransaction <TState, TResult>( [NotNull] this IExecutionStrategy strategy, [NotNull] Func <TState, TResult> operation, [CanBeNull] Func <TState, bool> verifySucceeded, [CanBeNull] TState state, [NotNull] DbContext context) => strategy.Execute(s => { using (var transaction = s.Context.Database.BeginTransaction()) { s.CommitFailed = false; s.Result = s.Operation(s.State); s.CommitFailed = true; transaction.Commit(); } return(s.Result); }, s => new ExecutionResult <TResult>(s.CommitFailed && s.VerifySucceeded != null && s.VerifySucceeded(s.State), s.Result), new ExecutionState <TState, TResult>(operation, verifySucceeded, state, context));
/// <summary> /// Executes the strategy /// </summary> public void Execute(object sender, object eventArgs) { bool isExecutionAllowed = false; // No EventFilter, so just pass it through freely... if (EventFilter == null) { isExecutionAllowed = true; } // ...otherwise test if EventFilter allows this concrete event or not else if (EventFilter is IEventFilter && (EventFilter as IEventFilter).IsMatchingEvent(sender, eventArgs)) { isExecutionAllowed = true; } if (isExecutionAllowed) { strategy.Execute(CommandParameter); } }
public void UseExplicitTransactionWithExecutionStrategy() { var context = CreateContext(useDefaultRetry: true); IExecutionStrategy strategy = context.Database.CreateExecutionStrategy(); strategy.Execute(() => { using (var transaction = context.Database.BeginTransaction()) { var count = context.Product.Count(); var product1 = TestHelpers.CreateProduct("1"); context.Product.Add(product1); var product2 = TestHelpers.CreateProduct("2"); context.Product.Add(product2); context.SaveChanges(); transaction.Rollback(); } }); }
public void ApplyMigrations(Type contextType) { this.logger.LogInformation($"Applying Pending EF Data Migrations for {contextType.Name}"); var dataContext = this.serviceProvider.CreateScope().ServiceProvider.GetService(contextType); var ctx = dataContext as DbContext ?? throw new ArgumentNullException(nameof(dataContext), "must derive from DbContext"); var conn = ctx.Database.GetDbConnection(); this.dataContextConnectionString = conn.ConnectionString; this.dataContextDbName = conn.Database; EnsureDatabase(); // make sure the semaphore lock table exists in the db EnsureTransactionLockTable(); // create an execution strategy to avoid azure retries if the lock fails IExecutionStrategy strategy = ctx.Database.CreateExecutionStrategy(); strategy.Execute(() => { // start the transaction using (ctx.Database.BeginTransaction(IsolationLevel.ReadCommitted)) { // acquire the distributed lock if (AcquireLock(ctx)) { // anything that happens here will only happen on // a single instance of the application service at one time. // Apply any pending EF migrations RunMigrations(contextType, this.serviceProvider); // Release the lock ReleaseLock(); this.logger.LogInformation($"EF Data Migrations for {contextType.Name} has completed."); } } }); }
public bool MoveNext() { if (_buffer == null) { if (_executionStrategy == null) { _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create(); } return(_executionStrategy.Execute(_executionStrategy.RetriesOnFailure, _bufferlessMoveNext, null)); } if (_buffer.Count > 0) { Current = _shaper.Shape(_relationalQueryContext, _buffer.Dequeue()); return(true); } return(false); }
/// <summary> /// Executes the specified operation in a transaction and returns the result. Allows to check whether /// the transaction has been rolled back if an error occurs during commit. /// </summary> /// <param name="strategy"> The strategy that will be used for the execution. </param> /// <param name="state"> The state that will be passed to the operation. </param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <param name="verifySucceeded"> /// A delegate that tests whether the operation succeeded even though an exception was thrown when the /// transaction was being committed. /// </param> /// <param name="beginTransaction"> A delegate that begins a transaction using the given context. </param> /// <typeparam name="TState"> The type of the state. </typeparam> /// <typeparam name="TResult"> The return type of <paramref name="operation" />. </typeparam> /// <returns> The result from the operation. </returns> /// <exception cref="RetryLimitExceededException"> /// The operation has not succeeded after the configured number of retries. /// </exception> public static TResult ExecuteInTransaction <TState, TResult>( [NotNull] IExecutionStrategy strategy, [CanBeNull] TState state, [NotNull] Func <TState, TResult> operation, [NotNull] Func <TState, bool> verifySucceeded, [NotNull] Func <DbContext, IDbContextTransaction> beginTransaction) => strategy.Execute( new ExecutionState <TState, TResult>( Check.NotNull(operation, nameof(operation)), Check.NotNull(verifySucceeded, nameof(verifySucceeded)), state), (c, s) => { Check.NotNull(beginTransaction, nameof(beginTransaction)); using (var transaction = beginTransaction(c)) { s.CommitFailed = false; s.Result = s.Operation(s.State); s.CommitFailed = true; transaction.Commit(); } return(s.Result); }, (c, s) => new ExecutionResult <TResult>(s.CommitFailed && s.VerifySucceeded(s.State), s.Result));
public bool MoveNext() { try { using (_relationalQueryContext.ConcurrencyDetector.EnterCriticalSection()) { if (_dataReader == null) { if (_executionStrategy == null) { _executionStrategy = _relationalQueryContext.ExecutionStrategyFactory.Create(); } _executionStrategy.Execute(true, InitializeReader, null); } var hasNext = _dataReader.Read(); Current = default; if (hasNext) { _resultCoordinator.ResultContext.Values = null; _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); _relatedDataLoaders?.Invoke(_relationalQueryContext, _executionStrategy, _resultCoordinator); Current = _shaper( _relationalQueryContext, _dataReader.DbDataReader, _resultCoordinator.ResultContext, _resultCoordinator); } return(hasNext); } } catch (Exception exception) { _queryLogger.QueryIterationFailed(_contextType, exception); throw; } }
private void ProcessSubmission(Submission submission) { // TODO: Check for N+1 queries problem this.logger.InfoFormat("Work on submission №{0} started.", submission.Id); IExecutionStrategy executionStrategy = this.CreateExecutionStrategy(submission.SubmissionType.ExecutionStrategyType); var context = new ExecutionContext { AdditionalCompilerArguments = submission.SubmissionType.AdditionalCompilerArguments, CheckerAssemblyName = submission.Problem.Checker.DllFile, CheckerParameter = submission.Problem.Checker.Parameter, CheckerTypeName = submission.Problem.Checker.ClassName, FileContent = submission.Content, AllowedFileExtensions = submission.SubmissionType.AllowedFileExtensions, CompilerType = submission.SubmissionType.CompilerType, MemoryLimit = submission.Problem.MemoryLimit, TimeLimit = submission.Problem.TimeLimit, }; context.Tests = submission.Problem.Tests.ToList().Select(x => new TestContext { Id = x.Id, Input = x.InputDataAsString, Output = x.OutputDataAsString, IsTrialTest = x.IsTrialTest }); ExecutionResult executionResult; try { executionResult = executionStrategy.Execute(context); } catch (Exception exception) { this.logger.ErrorFormat("executionStrategy.Execute on submission №{0} has thrown an exception: {1}", submission.Id, exception); submission.ProcessingComment = string.Format("Exception in executionStrategy.Execute: {0}", exception.Message); return; } submission.IsCompiledSuccessfully = executionResult.IsCompiledSuccessfully; submission.CompilerComment = executionResult.CompilerComment; if (!executionResult.IsCompiledSuccessfully) { return; } foreach (var testResult in executionResult.TestResults) { var testRun = new TestRun { CheckerComment = testResult.CheckerComment, ExecutionComment = testResult.ExecutionComment, MemoryUsed = testResult.MemoryUsed, ResultType = testResult.ResultType, TestId = testResult.Id, TimeUsed = testResult.TimeUsed, }; submission.TestRuns.Add(testRun); } this.logger.InfoFormat("Work on submission №{0} ended.", submission.Id); }
/// <summary> /// Executes the specified operation and returns the result. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-connection-resiliency">Connection resiliency and database retries</see> /// for more information and examples. /// </remarks> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="state">The state that will be passed to the operation.</param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <typeparam name="TState">The type of the state.</typeparam> /// <typeparam name="TResult">The return type of <paramref name="operation" />.</typeparam> /// <returns>The result from the operation.</returns> public static TResult Execute <TState, TResult>( this IExecutionStrategy strategy, TState state, Func <TState, TResult> operation) => strategy.Execute(state, operation, verifySucceeded: null);
/// <summary> /// Executes the specified operation and returns the result. /// </summary> /// <param name="strategy">The strategy that will be used for the execution.</param> /// <param name="state">The state that will be passed to the operation.</param> /// <param name="operation"> /// A delegate representing an executable operation that returns the result of type <typeparamref name="TResult" />. /// </param> /// <typeparam name="TState">The type of the state.</typeparam> /// <typeparam name="TResult">The return type of <paramref name="operation" />.</typeparam> /// <returns>The result from the operation.</returns> public static TResult Execute <TState, TResult>( [NotNull] this IExecutionStrategy strategy, [CanBeNull] TState state, [NotNull] Func <TState, TResult> operation) => strategy.Execute(operation, verifySucceeded: null, state: state);