Ejemplo n.º 1
0
        public Task HandleAsync(OperationContext context, OperationError <Exception> error, CancellationToken cancellationToken)
        {
#if DEBUG
            Console.WriteLine($"{nameof(OperationErrorHandler)} : {error?.Exception?.Message}");
#endif
            return(Task.FromResult(0));
        }
        public Task HandleAsync(OperationContext context, OperationError <Exception> error, CancellationToken cancellationToken)
        {
            if (error.Handled)
            {
                return(Task.CompletedTask);
            }

            switch (error.Exception)
            {
            case InternetConnectionException _:
                Debug.WriteLine(error.Exception.Message);
                break;

            case AuthenticationException _:
                Debug.WriteLine(error.Exception.Message);
                break;

            case WebException _:
                Debug.WriteLine(error.Exception.Message);
                break;

            case Exception _:
                Debug.WriteLine(error.Exception.Message);
                break;
            }

            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var component = virtualStudio.FindStudioComponentById(componentId);

            if (component is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Component with ID {componentId} not found.");
                return(false);
            }
            if (component is PlaceholderStudioComponent placeholderStudioComponent)
            {
                var input = placeholderStudioComponent.Inputs.FirstOrDefault(i => i.Id == endpointId);
                if (input is null)
                {
                    Error = new OperationError(ErrorType.NotFound, $"Input with ID {endpointId} not found on component with ID {componentId}.");
                    return(false);
                }
                placeholderStudioComponent.RemoveInput(input);
                return(true);
            }
            else
            {
                Error = new OperationError(ErrorType.InvalidOperation, $"Component with ID {componentId} is not of type PlaceholderComponent.");
                return(false);
            }
        }
Ejemplo n.º 4
0
        private IActionResult ToActionResult(OperationResult result)
        {
            if (result.IsValid)
            {
                return(Ok());
            }

            OperationError firstError = result.Errors.FirstOrDefault();

            if (firstError == null)
            {
                return(BadRequest(new BasicError("An unknown error occured")));
            }

            var errorDescription = new BasicError(firstError.Description);

            switch (firstError.Type)
            {
            case OperationError.ErrorType.General:
                return(BadRequest(errorDescription));

            case OperationError.ErrorType.NotFound:
                return(NotFound(errorDescription));

            case OperationError.ErrorType.ProcessingError:
                return(StatusCode(500, errorDescription));

            default:
                throw new ArgumentOutOfRangeException($"Unexpected [{typeof(OperationError.ErrorType).Name}] enum value");
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Отсылка сообщения
        /// </summary>
        private void SendMessage()
        {
            if (IsWhispering)
            {
                if (SelectedPerson == null)
                {
                    LogError("Не выбран пользователь для отправки сообщения");
                    return;
                }

                if (CurrentPerson.Equals(SelectedPerson))
                {
                    LogError("Нельзя отправлять личные сообщения самому себе");
                    return;
                }
            }

            Common.Messages.TextMessage mess = IsWhispering ?
                                               new Common.Messages.PersonalTextMessage(CurrentPerson, SelectedPerson, UserMessageText) :
                                               new Common.Messages.TextMessage(CurrentPerson, UserMessageText);

            OperationResult opRes = new OperationResult {
                Success = true
            };

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    opRes = _communicationManager.SendMessage(IsWhispering, mess);
                }
                catch (Exception ex)
                {
                    opRes.Success      = false;
                    OperationError err = new OperationError();

                    ///Если при отсылке сообщения обнаруживается разрыв соединения с сервером завершаем подключение
                    if (ex.GetType() == typeof(System.ServiceModel.CommunicationObjectFaultedException))
                    {
                        err.ErrorMessage = "Не получилось соединиться с сервером";
                        Disconnect(shoudClearInfo: true);
                    }
                    else
                    {
                        err.ErrorMessage = ex.Message;
                    }

                    opRes.Errors.Add(err);
                }

                if (!opRes.Success)
                {
                    LogError(opRes);
                }
            });

            UserMessageText = string.Empty;
        }
 public void SetGuildUpdateError(OperationError error)
 => MockCharacterGuildsRepository
 .Setup(x => x.UpdateAsync(
            It.IsAny <long>(),
            It.IsAny <long>(),
            It.IsAny <Optional <string> >(),
            It.IsAny <Optional <bool> >(),
            It.IsAny <CancellationToken>()))
 .ReturnsAsync(error);
Ejemplo n.º 7
0
        private IActionResult BuildErrorResult(OperationError operationError)
        {
            var payload = new Payload <object>(null, operationError);

            return(new JsonResult(payload)
            {
                StatusCode = (int)HttpStatusCode.BadRequest
            });
        }
Ejemplo n.º 8
0
 public OperationStateBase(OperationError error, double progress, bool isCancelled, ModelSource source = ModelSource.Unknown, ModelIdentifierBase id = null, double resultProgress = 0)
 {
     Error            = error;
     Progress         = progress;
     IsCancelled      = isCancelled;
     ResultSource     = source;
     ResultIdentifier = id;
     ResultProgress   = resultProgress;
 }
Ejemplo n.º 9
0
        protected IHttpActionResult FromOperationError(OperationError failure)
        {
            var statusCode = failure.FailureType.ToHttpStatusCode();

            return(ResponseMessage(new HttpResponseMessage(statusCode)
            {
                Content = new StringContent(failure.Message.GetValueOrFallback(statusCode.ToString("G")))
            }));
        }
 public void OutputOperationError(OperationError dataObject)
 {
     if (null != dataObject)
     {
         OutputStatusMessage(string.Format("Code: {0}", dataObject.Code));
         OutputStatusMessage(string.Format("Details: {0}", dataObject.Details));
         OutputStatusMessage(string.Format("Message: {0}", dataObject.Message));
     }
 }
Ejemplo n.º 11
0
        public static double ThrowIf_Zero(this double value, OperationError operationError)
        {
            if (value == 0)
            {
                throw new OperationUniformException(operationError);
            }

            return(value);
        }
Ejemplo n.º 12
0
        private IActionResult BuildPayloadResult <TData>(TData data, OperationError operationError)
        {
            if (operationError != null)
            {
                return(BuildErrorResult(operationError));
            }

            var payload = new Payload <TData>(data, null);

            return(new JsonResult(payload));
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new <see cref="Payload{TData}"/>.
 /// </summary>
 /// <param name="data">The <see cref="Data"/>.</param>
 /// <param name="error">The <see cref="Error"/>.</param>
 public Payload(TData data, OperationError error)
 {
     if (error != null)
     {
         Error = error;
     }
     else
     {
         Data = data;
     }
 }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var component = virtualStudio.FindStudioComponentById(componentId);

            if (component is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Component with ID {componentId} not found.");
                return(false);
            }

            return(ChangeProperty(component, propertyName, value));
        }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var connection = virtualStudio.Connections.FirstOrDefault(c => c.Id == connectionId);

            if (connection is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Connection with ID {connectionId} not found.");
                return(false);
            }
            virtualStudio.RemoveConnection(connection);
            return(true);
        }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var inputComponent = virtualStudio.Components.FirstOrDefault(c => c.Id == inputComponentId);

            if (inputComponent == null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Cannot find component with ID {inputComponentId}.");
                return(false);
            }
            var input = inputComponent.Inputs.FirstOrDefault(i => i.Id == inputId);

            if (input is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Cannot find input with ID {inputId} on component with ID {inputComponentId}.");
                return(false);
            }
            if (virtualStudio.Connections.FirstOrDefault(c => c.Input == input) != null)
            {
                Error = new OperationError(ErrorType.InvalidOperation, $"Input with ID {inputId} on component with ID {inputComponentId} is already connected.");
                return(false);
            }
            var outputComponent = virtualStudio.Components.FirstOrDefault(c => c.Id == outputComponentId);

            if (outputComponent == null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Cannot find component with ID {outputComponentId}.");
                return(false);
            }
            var output = outputComponent.Outputs.FirstOrDefault(o => o.Id == outputId);

            if (output is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Cannot find output with ID {outputId} on component with ID {outputComponentId}.");
                return(false);
            }
            if ((input.DataKind & output.DataKind) == DataKind.Nothing)
            {
                Error = new OperationError(ErrorType.InvalidOperation, "DataKind of output and input does not match.");
                return(false);
            }
            if (output.ConnectionType != input.ConnectionType)
            {
                Error = new OperationError(ErrorType.InvalidOperation, "ConnectionType of output and input does not match.");
                return(false);
            }

            if (virtualStudio.CreateConnection(output, input) is null)
            {
                Error = new OperationError(ErrorType.InvalidOperation, $"Cannot create connection for: Output {outputComponentId}:{outputId}, Input {inputComponentId}:{inputId}");
                return(false);
            }
            return(true);
        }
Ejemplo n.º 17
0
        public Task HandleAsync(OperationContext context, OperationError <Exception> error, CancellationToken cancellationToken)
        {
            switch (error.Exception)
            {
            }

            Debug.WriteLine("oops...");

            Debug.WriteLine(error.Exception);

            return(Task.CompletedTask);
        }
Ejemplo n.º 18
0
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            IStudioComponent studioComponent = virtualStudio.Components.FirstOrDefault(c => c.Id == componentId);

            if (studioComponent is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Component with ID {componentId} not found.");
                return(false);
            }
            virtualStudio.RemoveComponent(studioComponent);
            return(true);
        }
Ejemplo n.º 19
0
 public Task <VirtualStudioWithArrangementDto> Process(VirtualStudio virtualStudio)
 {
     if (virtualStudio is VirtualStudioWithArrangement virtualStudioWithArrangement)
     {
         var dto = virtualStudioWithArrangement.ToDto();
         return(Task.FromResult(dto));
     }
     else
     {
         Error = new OperationError(ErrorType.NotFound, "A VirtualStudioWithArrangement was not found.");
         return(Task.FromResult <VirtualStudioWithArrangementDto>(null));
     }
 }
Ejemplo n.º 20
0
 public ServiceResult <Usuario> Update(Usuario usuario)
 {
     try
     {
         _usuarioRepository.Update(usuario);
         _context.SaveChanges();
         return(new ServiceSucceedResult <Usuario>(usuario));
     }
     catch (Exception ex)
     {
         OperationError error = new OperationError(ErrorType.Exception, "No se realizó la actualización", ex);
         return(new ServiceSucceedResult <Usuario>(usuario));
     }
 }
Ejemplo n.º 21
0
        public ServiceResult <Usuario> Create(CreateUsuarioDto createUsuario)
        {
            ServiceResult <Usuario> result;

            try
            {
                IdentityResult idenityResult = null;
                Usuario        usuario       = null;
                var            user          = new BitUser {
                    UserName = createUsuario.Email, Email = createUsuario.Email, EmailConfirmed = createUsuario.EmailConfirmed
                };
                //adding roles
                if (createUsuario.RolesIds.Length > 0)
                {
                    foreach (var roleId in createUsuario.RolesIds)
                    {
                        user.Roles.Add(new BitUserRole {
                            RoleId = roleId
                        });
                    }
                }
                var            securityContext = new BitSecurityContext();
                BitUserManager userManager     = new BitUserManager(new BitUserStore(securityContext));
                using (var scope = new TransactionScope(TransactionScopeOption.Required))
                {
                    idenityResult = userManager.Create(user, createUsuario.Password);
                    if (idenityResult.Succeeded)
                    {
                        usuario = new Usuario {
                            Id = user.Id, Email = user.Email
                        };
                        _usuarioRepository.Insert(usuario);
                        _context.SaveChanges();
                    }
                    else
                    {
                        result = new ServiceErrorResult <Usuario>(new OperationError(ErrorType.Validation, string.Join(",", idenityResult.Errors)));
                    }
                    scope.Complete();
                }

                result = new ServiceSucceedResult <Usuario>(usuario);
            }
            catch (Exception ex)
            {
                OperationError error = new OperationError(ErrorType.Exception, "No se realizó la inserción", ex);
                result = new ServiceErrorResult <Usuario>(ErrorType.Exception, "No se insertó", ex);
            }
            return(result);
        }
Ejemplo n.º 22
0
 private bool ProcessSync(VirtualStudio virtualStudio)
 {
     if (virtualStudio is VirtualStudioWithArrangement studioArrangement)
     {
         ComponentNode node = studioArrangement.ComponentNodes.FirstOrDefault(c => c.Id == componentId);
         if (node is null)
         {
             Error = new OperationError(ErrorType.NotFound, $"ComponentNode with ID {componentId} not found.");
             return(false);
         }
         node.Position = new Position2D(x, y);
         return(true);
     }
     return(false);
 }
Ejemplo n.º 23
0
        public async Task <IActionResult> Register([FromBody] RegistrationModel model)
        {
            if (!ModelState.IsValid)
            {
                var error = new OperationError
                {
                    Name        = "Invalid",
                    Description = "Model is not valid"
                };

                return(BadRequest(OperationResult.Failed(error)));
            }

            var registrationResult = await _accountService.RegisterAsync(model);

            return(ApiHelper.ActionFromOperationResult(registrationResult));
        }
Ejemplo n.º 24
0
        public async Task <IActionResult> Profile([FromBody] ProfileModel model)
        {
            if (!ModelState.IsValid)
            {
                var error = new OperationError
                {
                    Name        = "Invalid",
                    Description = "Model is not valid"
                };

                return(BadRequest(OperationResult.Failed(error)));
            }

            var profileResult = await _accountService.UpdateProfileAsync(User.FindFirst(JwtRegisteredClaimNames.UniqueName).Value, model);

            return(ApiHelper.ActionFromOperationResult(profileResult));
        }
        public async Task <IActionResult> Post(Product product)
        {
            if (!ModelState.IsValid)
            {
                var error = new OperationError
                {
                    Name        = "Invalid",
                    Description = "Model is not valid"
                };

                return(BadRequest(OperationResult.Failed(error)));
            }

            var productCreateResult = await _productService.CreateAsync(product);

            return(ApiHelper.ActionFromOperationResult(productCreateResult));
        }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var foundComponent = virtualStudio.ComponentRepository.Find(c => c.Id == componentId);

            if (foundComponent is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"StudioComponent with ID {componentId} not found in ComponentRepository.");
                return(false);
            }
            if (virtualStudio.Components.Contains(foundComponent))
            {
                Error = new OperationError(ErrorType.InvalidOperation, $"The StudioComponent with ID {componentId} was already added.");
                return(false);
            }

            virtualStudio.AddComponent(foundComponent);
            return(true);
        }
Ejemplo n.º 27
0
        public async Task <IOperationResult> RegisterAsync(RegistrationModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var officeLocation = await _officeLocationRepository.ReadAsync(model.OfficeLocationId);

            if (officeLocation == null)
            {
                var error = new OperationError
                {
                    Name        = "Invalid",
                    Description = "Office location not valid"
                };
                return(OperationResult.Failed(error));
            }

            var user = new ApplicationUser
            {
                UserName       = model.Username,
                Email          = model.Email,
                FirstName      = model.FirstName,
                LastName       = model.LastName,
                OfficeLocation = officeLocation,
                PhoneNumber    = model.PhoneNumber,
                Title          = model.Title
                                 // More fields here if needed
            };

            var userManagerResult = await _userManager.CreateAsync(user, model.Password);

            if (!userManagerResult.Succeeded)
            {
                return(OperationResult.Failed(userManagerResult.Errors.Select(ie => new OperationError()
                {
                    Name = "UserManager",
                    Description = ie.Description
                }).ToArray()));
            }

            return(OperationResult.Success);
        }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var component = virtualStudio.FindStudioComponentById(componentId);

            if (component is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"StudioComponent with ID {componentId} not found.");
                return(false);
            }
            if (component is PlaceholderStudioComponent placeholderComponent)
            {
                placeholderComponent.AddOutput(endpoint.Name, endpoint.DataKind, endpoint.ConnectionType);
                return(true);
            }
            else
            {
                Error = new OperationError(ErrorType.NotFound, $"StudioComponent with ID {component} is not a Placeholder.");
                return(false);
            }
        }
        private bool ProcessSync(VirtualStudio virtualStudio)
        {
            var connection = virtualStudio.Connections.FirstOrDefault(c => c.Id == connectionId);

            if (connection is null)
            {
                Error = new OperationError(ErrorType.NotFound, $"Connection with ID {connectionId} not found.");
                return(false);
            }

            if (connection.SetTargetState(state))
            {
                return(true);
            }
            else
            {
                Error = new OperationError(ErrorType.InvalidArgument, $"TargetState cannot be set to {state}.");
                return(false);
            }
        }
        public async Task <IOperationResult <TokenModel> > AuthenticateAsync(LoginModel model)
        {
            var user = await _userManager.Users.ToListAsync();

            var signInResult = await _signInManager.PasswordSignInAsync(model.Username, model.Password, false, false);

            if (!signInResult.Succeeded)
            {
                var error = new OperationError()
                {
                    Name        = "Unauthorized",
                    Description = "Login failed"
                };
                return(OperationResult <TokenModel> .Failed(error));
            }

            var appUser = await _userManager.FindByNameAsync(model.Username);

            return(OperationResult <TokenModel> .Success(new TokenModel(await GetToken(appUser))));
        }
Ejemplo n.º 31
0
		public ErrorPair(string fname, OperationError err)
		{
			filename = fname;
			error = err;
		}
Ejemplo n.º 32
0
	string GetErrorMessage(string filename, OperationError operationError)
	{
		switch (operationError)
		{
			case OperationError.IllegalFileName:
				return string.Format(GetMessageRaw("Message.FileNameRequirements"), filename);
			case OperationError.ItemExists:
				return string.Format("{0} ({1})", GetMessageRaw("Message.TargetItemAlreadyExists"), BXPath.Combine(curPath, filename));
		}
		return string.Empty;
	}