public void Main(string argument, UpdateType updateSource) { if (Me.CustomData == FirstWeaponlack) { DriveEntity.RArm.myMotor1.MyMotor.CustomData = "1,-5,20"; DriveEntity.RArm.myMotor2.MyMotor.CustomData = "1,-2,20"; DriveEntity.RArm.myMotor3.MyMotor.CustomData = "1,0,20"; } else if (Me.CustomData == Standstr) { DriveEntity.RArm.myMotor1.MyMotor.CustomData = "1,0,20"; DriveEntity.RArm.myMotor2.MyMotor.CustomData = "1,5,20"; DriveEntity.RArm.myMotor3.MyMotor.CustomData = "1,0,20"; } else if (Me.CustomData == SecondWeaponlack) { DriveEntity = new Arm1Class(Arm1, Arm2); } //else if (Me.CustomData == SecondWeaponlack) //{ // DriveEntity = new Arm2Class(Arm1, Arm2); //} else //if(Me.CustomData == Shootstr) { DriveEntity.AimTarget_sensor(mySensor); } DriveEntity.Drive(); }
private async Task AssertRetryThenSuccessAsync(OperationBase op, Exception exp) { var retryOrchestrator = CreateRetryOrchestrator(); var bucketMock = new Mock <BucketBase>("fake", new ClusterContext(), new Mock <IScopeFactory>().Object, retryOrchestrator, new Mock <ILogger>().Object, new Mock <IRedactor>().Object, new Mock <IBootstrapperFactory>().Object, NoopRequestTracer.Instance, new Mock <IOperationConfigurator>().Object, new BestEffortRetryStrategy()); bucketMock.Setup(x => x.SendAsync(op, It.IsAny <CancellationTokenPair>())).Callback((IOperation op, CancellationTokenPair ct) => { if (op.Completed.IsCompleted) { Assert.True(false, "operation result should be reset before retry"); } // complete the operation (ResponseStatus does not matter for this test) op.HandleOperationCompleted(AsyncState.BuildErrorResponse(op.Opaque, ResponseStatus.TemporaryFailure)); if (op.Attempts == 1) { throw exp; } }).Returns(op.Completed.AsTask()); var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(2500)); try { await retryOrchestrator.RetryAsync(bucketMock.Object, op, CancellationTokenPair.FromInternalToken(tokenSource.Token)).ConfigureAwait(false); } catch (Exception) { Assert.True(false, "Expected operation to succeed after retry"); } Assert.True(op.Attempts > 1); }
public static OperationException CreateFromOperation(OperationBase operation) { return null; /* return operation.IsKnownError() ? new KnownOperationException(operation.Error, operation) : new OperationException(operation.Error, operation);*/ }
public void ProcessRequest(IOrganizationService service, OperationBase operation, Func <IOrganizationService, OrganizationRequest, OrganizationRequest> undoFunction = null) { if (!IsTransactionInEffect()) { throw new Exception("No transaction in effect!"); } try { // get request from operation var request = operation.Request; // get the undo request corresponding to the given request operation.UndoRequest = undoFunction == null ? UndoHelper.GenerateReverseRequest(service, request) : undoFunction(service, request); // register this response as the starting point of the latest transaction transactionsStack.Peek().StartingPoint = transactionsStack.Peek().StartingPoint ?? operation; operationsStack.Push(operation); } catch (Exception ex) { throw new Exception("Failed to create undo request for the given request! => " + ex.Message, ex); } }
internal async Task PerformOperationExecuteTestAsSubordinateWithCallback(OperationBase operation, CallbackMessage cbMessage, bool cancelAndCheckStateOnExit = true) { _manualResetEvent.Reset(); _callbackMessageUponRequest = cbMessage; HookOperationEvent(operation); var connOp = await PerformOperationExecuteTestAsPrimary(new ConnectionOperation(), false); await connOp.AddAndExecuteSubordinate(operation); operation.State.Should().Be(OperationState.Executing); if (await WaitForCallback()) { GetComparisonValuesFromMessage(cbMessage).Equals(CallbackValues).Should().Be(true); } else { throw new Exception("Timeout waiting for callback message"); } ThrowIfConnectorClosed(); if (cancelAndCheckStateOnExit) { await operation.CancelAsync(); operation.State.Should().Be(OperationState.Canceled); await connOp.CancelAsync(); connOp.State.Should().Be(OperationState.Canceled); } }
public void Query_MaximumUriLengthExceeded() { OperationBase op = null; Exception error = null; this.EnqueueCallback(() => { this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2066)); // --> 2083, the max length op = this.CityDomainContext.Load( this.CityDomainContext.GetCitiesQuery(), (lo) => WebDomainClientTests.HandleError(lo, ref error), null); }); this.EnqueueCompletion(() => op); this.EnqueueCallback(() => { // Expect a 'Not Found' Assert.IsInstanceOfType(error, typeof(DomainOperationException)); Assert.IsInstanceOfType(error.InnerException, typeof(CommunicationException)); StringAssert.Contains(error.InnerException.InnerException?.Message, "404"); this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2067)); // --> 2084, one over the max length ExceptionHelper.ExpectException <InvalidOperationException>(() => this.CityDomainContext.Load(this.CityDomainContext.GetCitiesQuery())); }); this.EnqueueTestComplete(); }
private async Task AssertRetryThenSuccessAsync(OperationBase op, Exception exp) { var retryOrchestrator = CreateRetryOrchestrator(); var bucketMock = new Mock <BucketBase>("fake", new ClusterContext(), new Mock <IScopeFactory>().Object, retryOrchestrator, new Mock <ILogger>().Object, new Mock <IRedactor>().Object, new Mock <IBootstrapperFactory>().Object, NullRequestTracer.Instance); var handleOperationCompletedMethod = op.GetType().GetMethod("HandleOperationCompleted", (BindingFlags.Instance | BindingFlags.NonPublic)); bucketMock.Setup(x => x.SendAsync(op, It.IsAny <CancellationToken>())).Callback((IOperation op, CancellationToken ct) => { if (op.Completed.IsCompleted) { Assert.True(false, "operation result should be reset before retry"); } // complete the operation (ResponseStatus does not matter for this test) handleOperationCompletedMethod.Invoke(op, new object[] { null, ResponseStatus.TemporaryFailure }); if (op.Attempts == 1) { throw exp; } }).Returns(op.Completed); var tokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(2500)); try { await retryOrchestrator.RetryAsync(bucketMock.Object, op, tokenSource.Token).ConfigureAwait(false); } catch (Exception e) { Assert.True(false, "Expected operation to succeed after retry"); } Assert.True(op.Attempts > 1); }
public void Invoke_MaximumUriLengthExceeded() { OperationBase op = null; Exception error = null; this.EnqueueCallback(() => { this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2071)); // --> 2083, the max length op = this.CityDomainContext.Echo( "", (io) => WebDomainClientTests.HandleError(io, ref error), null); }); this.EnqueueCompletion(() => op); this.EnqueueCallback(() => { Assert.IsInstanceOfType(error, typeof(DomainOperationException)); Assert.IsInstanceOfType(error.InnerException, typeof(CommunicationException)); var webException = error.InnerException.InnerException as System.Net.WebException; StringAssert.Contains(webException?.Message, "404"); this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2072)); // --> 2084, one over the max length ExceptionHelper.ExpectException <InvalidOperationException>(() => this.CityDomainContext.Echo("")); }); this.EnqueueTestComplete(); }
public void Invoke_MaximumUriLengthExceeded() { OperationBase op = null; Exception error = null; this.EnqueueCallback(() => { this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2071)); // --> 2083, the max length op = this.CityDomainContext.Echo( "", (io) => WebDomainClientTests.HandleError(io, ref error), null); }); this.EnqueueConditional(() => op.IsComplete); this.EnqueueCallback(() => { // Expect a 'Not Found' Assert.IsInstanceOfType(error, typeof(DomainOperationException)); Assert.IsInstanceOfType(error.InnerException, typeof(CommunicationException)); this.CreateDomainContext(WebDomainClientTests.GenerateUriBase(2072)); // --> 2084, one over the max length ExceptionHelper.ExpectException <InvalidOperationException>(() => this.CityDomainContext.Echo("")); }); this.EnqueueTestComplete(); }
private string GetExpression(List <OperationBase> checkedOperations, int numbers) { string exp = string.Empty; int[] arr = new int[numbers]; for (int i = 0; i < numbers; i++) { OperationBase operation = GetOperation(checkedOperations, checkedOperations.Count); if (i == 0) { arr[i] = operation.GenerateFirstNumber(); exp += arr[i]; continue; } int start = arr[i - 1]; int value = operation.GenerateNextNumber(start); exp += (operation.Operator + value); arr[i] = Convert.ToInt32(new DataTable().Compute(exp.Replace('x', '*'), null)); if (i == numbers - 1) { exp += "="; } } return(exp); }
private static void HandleError(OperationBase op, ref Exception error) { if (op.HasError) { error = op.Error; op.MarkErrorAsHandled(); } }
public void Start() { index = 0; expected = steps.FirstOrDefault(); AllOperationTypes(Poison); Setup(expected); }
public OperationBase GetOperation() { if (Operation == null) { Operation = CreateOperation(); } return(Operation); }
/// <summary> /// Initializes a new instance of <see cref="JsonPatchError"/>. /// </summary> /// <param name="affectedObject">The object that is affected by the error.</param> /// <param name="operation">The <see cref="Operation"/> that caused the error.</param> /// <param name="errorMessage">The error message.</param> public JsonPatchError( object affectedObject, OperationBase operation, string errorMessage) { AffectedObject = affectedObject; Operation = operation; ErrorMessage = errorMessage; }
void Kill(OperationBase operation) { if (!operation.IsProcessCreated || !operation.Process.IsRunning() || operation.Process.HasExited) { return; } _logger?.Info($"Killing {operation.Name}."); operation.Kill(); }
private void OnLoadCompleted(LoadOperation op) { this.Operation = null; if (!op.HasError && !op.IsCanceled) { this.Data = op.Entities; } this.RaiseLoadCompleted(op); }
public void InvalidOperationType_SetsOperationTypeInvalid(string op, OperationType operationType) { // Arrange var operationBase = new OperationBase(); operationBase.op = op; // Act & Assert Assert.Equal(operationType, operationBase.OperationType); }
/// <summary> /// Binds UI so that controls will look disabled and activity will be /// displayed while operation is in progress. For simplicity Cancel button /// will be disabled during the operation even if it is cancellable /// </summary> /// <param name="operation"></param> private void BindUIToOperation(OperationBase operation) { Binding isActivityActiveBinding = operation.CreateOneWayBinding("IsComplete", new NotOperatorValueConverter()); Binding isEnabledBinding = operation.CreateOneWayBinding("IsComplete"); this.activity.SetBinding(Activity.IsActiveProperty, isActivityActiveBinding); this.registerForm.SetBinding(Control.IsEnabledProperty, isEnabledBinding); this.registerButton.SetBinding(Control.IsEnabledProperty, isEnabledBinding); this.registerCancel.SetBinding(Control.IsEnabledProperty, isEnabledBinding); this.backToLogin.SetBinding(Control.IsEnabledProperty, isEnabledBinding); }
private void CleanAfterOperation(OperationBase operation) { operation.Finished -= operation_Finished; if (operation.IsComplexOperation) { operation.Progressed -= operation_Progressed; } WpfUtilities.ThreadSafeInvoke(() => Pending.Remove(operation)); CheckOngoingOperations(); }
/// <summary> /// Parses custom parameters passed in different operation (for example {"read" : { "query": "key1=value1&key2=>value2" } }). /// </summary> /// <param name="operation">Operation base - read, write.</param> /// <param name="state">Unchange, Insert, Update or Delete.</param> /// <returns>Returns dictionary of parsed values.</returns> private Dictionary <string, object> ParseAdditionalParameters(OperationBase operation, EDataState state = EDataState.Unchanged) { Dictionary <string, object> resultDictionary = new Dictionary <string, object>(); string parseText = null; if (operation is Read read) { parseText = read?.Select?.Query ?? null; } if (operation is Write write) { if (state == EDataState.Deleted && (write?.Delete?.Query ?? null) != null) { parseText = write.Delete.Query; } if (state == EDataState.Insert && (write?.Insert?.Query ?? null) != null) { parseText = write.Insert.Query; } if (state == EDataState.Deleted && (write?.Update?.Query ?? null) != null) { parseText = write.Update.Query; } } if (string.IsNullOrWhiteSpace(parseText)) { return(resultDictionary); } string[] keyValues = parseText.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); foreach (string keyValue in keyValues) { string[] values = keyValue.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (values.Length == 2) { if (resultDictionary.ContainsKey(values[0])) { resultDictionary[values[0]] = values[1]; } else { resultDictionary.Add(values[0], values[1]); } } } return(resultDictionary); }
private void OnOperationPropertyChanged(OperationBase oldOperation, OperationBase newOperation) { if (oldOperation != null) { oldOperation.Completed -= OnOperationCompleted; progressIndicator.Visibility = Visibility.Collapsed; } if (newOperation != null) { newOperation.Completed += OnOperationCompleted; progressIndicator.Visibility = Visibility.Visible; } }
public ActionResult GetByFilter(string filter) { try { var result = OperationBase.GetByFilter(filter); return(Ok(result.Adapt <IEnumerable <TDTO> >())); } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, e)); } }
public ActionResult GetById(int id) { try { var result = OperationBase.GetById(id); return(Ok(result.Adapt <TDTO>())); } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, e)); } }
public ActionResult Delete(int id) { try { var sucess = OperationBase.Delete(id); return(Ok(sucess)); } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, e)); } }
protected bool TryInitResponse <T>(SubCode subCode, IMClientPeer peer, OperationBase operation, out Dictionary <string, object> parameters, string key, out T model) { parameters = InitParameters(subCode); if (!operation.Parameters.TryGetParameter(key, out model) || model == null) { mLogger.ErrorFormat("消息错误!客户端{0},OperationCode:{1},SubCode:{2},ParameterKeys:{3}", peer, OperationCode, subCode, key); peer.SendResponse(ReturnCode.ParameterException, parameters.AddParameter(ParameterKeys.PARAMETER_KEY, key)); return(false); } return(true); }
private void OnInvokeCompleted(object sender, EventArgs e) { this.Operation = null; InvokeOperation op = (InvokeOperation)sender; if (!op.HasError && !op.IsCanceled) { this.Data = (IEnumerable)op.Value; } this.RaiseLoadCompleted(op); }
private void OnOperationCompleted(object sender, EventArgs e) { OperationBase operation = (OperationBase)sender; progressIndicator.Visibility = Visibility.Collapsed; operation.Completed -= OnOperationCompleted; if (operation.HasError && (operation.IsErrorHandled == false)) { MessageBox.Show(operation.Error.Message, "Error", MessageBoxButton.OK); operation.MarkErrorAsHandled(); } }
/// <summary> /// Handles completion of the underlying operation in the <see cref="DomainContext"/>. /// </summary> /// <param name="operation">The operation that completed</param> private void HandleOperationComplete(OperationBase operation) { WebAsyncResult result = ((WebAsyncResult)operation.UserState); if (operation.HasError) { operation.MarkErrorAsHandled(); } if (!operation.IsCanceled) { result.Complete(); } }
public void ExecuteOp(OperationBase op) { if (LastSavedOp > UndoStack.Count) { LastSavedOp = -1; } RedoStack.Clear(); UndoStack.Push(op); op.Execute(); Unsaved = true; ApplicationSettings.Instance.SystemLog.Add($"Execute Operation: {op.GetType().Name} with parameter {op.Parameter}."); }
public void ExecuteOperation(OperationBase operation) { Pending.Add(operation); operation.Finished += operation_Finished; operation.Error += operation_Error; if (operation.IsComplexOperation) { operation.Progressed += operation_Progressed; } AreAnyOperationsOngoing = true; operation.Start(); }
private void RaiseLoadCompleted(OperationBase op) { if (op.HasError) { op.MarkErrorAsHandled(); } AsyncCompletedEventHandler handler = this.LoadCompleted; if (handler != null) { handler(this, new AsyncCompletedEventArgs(op.Error, op.IsCanceled, op.UserState)); } }
private void ReorderPlugins(OperationBase operation) { if (operation?.CustomPlugins != null) { operation.BeforeNodeActionPlugins = new List <CustomPlugin>(operation.CustomPlugins.OrderBy(p => p.Executionorder).Where(p => p.BeforeNodeAction == true)); operation.AfterNodeActionPlugins = new List <CustomPlugin>(operation.CustomPlugins.OrderBy(p => p.Executionorder).Where(p => p.AfterNodeAction == true)); operation.AfterNodeChildrenPlugins = new List <CustomPlugin>(operation.CustomPlugins.OrderBy(p => p.Executionorder).Where(p => p.AfterNodeChildren == true)); operation.CustomPlugins.Clear(); } }
private void OnOperationPropertyChanged(OperationBase oldOperation, OperationBase newOperation) { if (oldOperation != null) { oldOperation.Completed -= OnOperationCompleted; this.IsBusy = false; } if (newOperation != null) { newOperation.Completed += OnOperationCompleted; SetOperationMessage(newOperation.GetType()); this.IsBusy = true; } }
public KnownOperationException(Exception innerException, OperationBase operation) : base(innerException, operation) { }
public void Refresh() { if ((this.DomainContext != null) & !string.IsNullOrEmpty(this.OperationName)) { Type domainContextType = this.DomainContext.GetType(); MethodInfo operationInfo = domainContextType.GetMethods().Where( m => (m.Name == this.OperationName) && (m.GetParameters().Count() == this.Parameters.Count)).FirstOrDefault(); if (operationInfo == null) { System.Diagnostics.Debug.WriteLine( "Could not find a method named " + this.OperationName + " with the specified parameters (" + string.Join(",", this.Parameters.Select(p => p.ParameterName)) + ")."); } else { if (typeof(EntityQuery).IsAssignableFrom(operationInfo.ReturnType)) { // Query if (!DesignerProperties.IsInDesignTool) { EntityQuery query = (EntityQuery)operationInfo.Invoke(this.DomainContext, this.Parameters.Select(p => p.Value).ToArray()); this.Operation = this.DomainContext.Load(query, LoadBehavior.KeepCurrent, this.OnLoadCompleted, null); } } else if (typeof(InvokeOperation).IsAssignableFrom(operationInfo.ReturnType)) { // Invoke if (!operationInfo.ReturnType.IsGenericType || !typeof(IEnumerable).IsAssignableFrom(operationInfo.ReturnType.GetGenericArguments()[0])) { throw new NotImplementedException("Support non-enumerable InvokeOperation return types is not implemented."); } if (!DesignerProperties.IsInDesignTool) { this.Operation = (InvokeOperation)operationInfo.Invoke(this.DomainContext, this.Parameters.Select(p => p.Value).ToArray()); this.Operation.Completed += this.OnInvokeCompleted; } } else { throw new NotImplementedException("Support for return types other than EntityQuery and InvokeOperation is not implemented."); } } } }
public KnownOperationException( Exception innerException, string additionalMessage, OperationBase operation) : base(innerException, additionalMessage, operation) { }
/// <summary> /// Initializes a new instance of the <see cref="OperationException"/> class. /// </summary> /// <param name="innerException">The inner exception.</param> /// <param name="operation">The operation.</param> public OperationException(Exception innerException, OperationBase operation) : base(innerException.Message, innerException) { Operation = operation; }
public OperationException(Exception innerException, string additionalMessage, OperationBase operation) : base(innerException.Message + ' ' + additionalMessage, innerException) { Operation = operation; }
void UnPoison(OperationBase op) { op.Poison(device, () => {}); }
void Poison(OperationBase op) { op.Poison(device, () => { if (expected == null) { throw new InvalidOperationException( $"Executed an unexpected action of type {op.Operation} after the last step"); } throw new InvalidOperationException( $"Executed an unexpected action of type {op.Operation} expecting a {expected.Operation} at step {index}"); }); }
void Setup(OperationBase op) { op.Setup(device, MoveNext); }
private void AssertOperationCompleted(OperationBase operation, bool cancelled) { Assert.IsTrue(operation.IsComplete); Assert.AreEqual(cancelled, operation.IsCanceled); }
private void AssertInProgress(OperationBase operation) { Assert.IsFalse(operation.IsComplete); }
private void AssertCompletedWithError(OperationBase operation, string errorMessage) { Assert.IsTrue(operation.IsComplete, "Expected operation to complete."); Assert.IsFalse(operation.IsCanceled, "Expected operation to complete without cancelling."); Assert.IsTrue(operation.HasError, "Expected operation to complete with an error."); Assert.IsNotNull(operation.Error, "Expected operation to complete with an error."); Assert.AreEqual(errorMessage, operation.Error.Message); }
void MoveNext() { Poison(expected); index = index + 1; if (index < steps.Count) { expected = steps[index]; Setup(expected); } else { expected = null; } }
private bool ProcessError(OperationBase op) { if (op.HasError) { op.MarkErrorAsHandled(); Error = op.Error; return true; } return false; }
/// <summary> /// Notifies the <see cref="LoginRegistrationWindow"/> window that it can only close if <paramref name="operation"/> is finished or can be cancelled. /// </summary> /// <param name="operation">The pending operation to monitor</param> public void AddPendingOperation(OperationBase operation) { this.possiblyPendingOperations.Add(operation); }
private void AssertCompletedWithoutErrors(OperationBase operation) { Assert.IsTrue(operation.IsComplete, "Expected operation to complete."); Assert.IsFalse(operation.IsCanceled, "Expected operation to complete without cancelling."); Assert.IsFalse(operation.HasError, "Expected operation to complete without errors."); Assert.IsNull(operation.Error, "Expected operation to complete without errors."); }