Esempio n. 1
0
        public IActionResult Transfer(long id, int enrollmentNumber, [FromBody] StudentTransferDto dto)
        {
            var command = new TransferCommand(id, enrollmentNumber, dto.Course, dto.Grade);
            var result  = _messages.Dispatch(command);

            return(FromResult(result));
        }
Esempio n. 2
0
        public TransferPipe(TransferCommand _command, TransferEndpoint _fromOrigin, TransferEndpoint _toDestination, Transformation[] _throughTransformations = null)
        {
            this.Origin = _fromOrigin;
            this.Origin.TransferEndpointType = TransferEndpointType.ORIGIN;
            this.Origin.TransferCommand      = _command;

            this.Destination = _toDestination;
            this.Destination.TransferEndpointType = TransferEndpointType.DESTINATION;

            this.TransformationList = _throughTransformations;

            if (Origin is CollectionTransferEndpoint && Destination is CollectionTransferEndpoint)
            {
                CollectionTransferEndpoint o = Origin as CollectionTransferEndpoint;
                o.ConnectTo(Destination);
                o.TransformationList = this.TransformationList;
            }
            else if (Origin is ItemTransferEndpoint && Destination is ItemTransferEndpoint)
            {
                if (this.TransformationList == null)
                {
                    Origin.ConnectTo(Destination);
                }
                else
                {
                    Origin.ConnectTo(this.TransformationList[0]);
                    this.LinkAllTheTransformations();
                    this.TransformationList[this.TransformationList.Length - 1].ConnectTo(Destination);
                }
            }
        }
Esempio n. 3
0
        public async Task <IActionResult> Transfer(
            [FromBody] TransferRequest request,
            CancellationToken token)
        {
            var query = new TransferCommand(
                request.AccountNumberFrom,
                request.AccountNumberTo,
                request.Amount,
                CorrelationContext.Get());
            var response = await _mediator
                           .Send(
                query,
                token);

            if (!response
                .ValidationResult
                .IsValid)
            {
                var errors = string.Empty;
                response
                .ValidationResult
                .Errors
                .ToList()
                .ForEach(e => { errors += $"{e}//r//n"; });
                return(BadRequest(errors));
            }

            return(Ok(new TransferView(
                          response.AccountNumberTo,
                          response.Balance)));
        }
Esempio n. 4
0
        public void Setup_OkState()
        {
            _tagIds = new List <int> {
                TagId1, TagId2
            };
            _tagIdsWithRowVersion = new List <IdAndRowVersion>
            {
                new IdAndRowVersion(TagId1, RowVersion1),
                new IdAndRowVersion(TagId2, RowVersion2)
            };
            _projectValidatorMock = new Mock <IProjectValidator>();
            _projectValidatorMock.Setup(p => p.AllTagsInSameProjectAsync(_tagIds, default)).Returns(Task.FromResult(true));
            _tagValidatorMock = new Mock <ITagValidator>();
            _tagValidatorMock.Setup(r => r.ExistsAsync(TagId1, default)).Returns(Task.FromResult(true));
            _tagValidatorMock.Setup(r => r.ExistsAsync(TagId2, default)).Returns(Task.FromResult(true));
            _tagValidatorMock.Setup(r => r.IsReadyToBeTransferredAsync(TagId1, default)).Returns(Task.FromResult(true));
            _tagValidatorMock.Setup(r => r.IsReadyToBeTransferredAsync(TagId2, default)).Returns(Task.FromResult(true));
            _rowVersionValidatorMock = new Mock <IRowVersionValidator>();
            _rowVersionValidatorMock.Setup(r => r.IsValid(RowVersion1)).Returns(true);
            _rowVersionValidatorMock.Setup(r => r.IsValid(RowVersion2)).Returns(true);

            _command = new TransferCommand(_tagIdsWithRowVersion);

            _dut = new TransferCommandValidator(
                _projectValidatorMock.Object,
                _tagValidatorMock.Object,
                _rowVersionValidatorMock.Object);
        }
Esempio n. 5
0
        private static bool ExecuteSellAllItems(SPInventoryVM __instance, ref InventoryLogic ____inventoryLogic, ref CharacterObject ____currentCharacter)
        {
            var golds    = 0;
            var leftGold = __instance.LeftInventoryOwnerGold;

            __instance.IsRefreshed = false;
            for (int i = __instance.RightItemListVM.Count - 1; i >= 0; i--)
            {
                SPItemVM spitemVM = __instance.RightItemListVM[i];
                if (spitemVM != null && !spitemVM.IsFiltered && !spitemVM.IsLocked)
                {
                    golds += spitemVM.ItemCost * spitemVM.ItemRosterElement.Amount;
                    if (__instance.IsTrading && golds > leftGold)
                    {
                        break;
                    }
                    TransferCommand command = TransferCommand.Transfer(spitemVM.ItemRosterElement.Amount, InventoryLogic.InventorySide.PlayerInventory, InventoryLogic.InventorySide.OtherInventory, spitemVM.ItemRosterElement, EquipmentIndex.None, EquipmentIndex.None, ____currentCharacter, !__instance.IsInWarSet);
                    ____inventoryLogic.AddTransferCommand(command);
                }
            }
            Traverse.Create(__instance).Method("RefreshInformationValues").GetValue();
            Traverse.Create(__instance).Method("ExecuteRemoveZeroCounts").GetValue();
            __instance.IsRefreshed = true;

            return(false);
        }
Esempio n. 6
0
        public IActionResult Transfer(TransferViewModel model)
        {
            if (ModelState.IsValid)
            {
                var command = new TransferCommand
                {
                    AccountId_Sender   = model.AccountIdSender,
                    AccountId_Reciever = model.AccountIdReciever,
                    Amount             = model.Amount
                };

                var query = new TransferHandler(new BankContext()).Handler(command);

                if (query.IsCompletedSuccessfully)
                {
                    TempData["Success"] = $"{model.Amount.ToString("C")} transferred from {model.BalanceSender} to {model.AccountIdReciever}";
                    return(View());
                }
                else
                {
                    TempData["Error"] = $"Transfer failed";
                    return(View());
                }
            }

            return(NotFound());
        }
Esempio n. 7
0
        public void AddTransfer(TransferCommand command)
        {
            var barrelFrom = _barrelRepository.GetById(command.BarrelFromId);
            var barrelTo   = _barrelRepository.GetById(command.BarrelToId);

            var transfer = new Transfer(command);

            if ((barrelFrom.CurrentCapacity >= command.Amount) &&
                (barrelTo.Capacity >= barrelTo.CurrentCapacity + command.Amount))
            {
                barrelFrom.RemoveAmount(command.Amount);
                barrelTo.AddAmount(command.Amount);
            }
            else
            {
                throw new Exception("Specified amount can't fit into the barrels");
            }

            using (var scope = new TransactionScope())
            {
                _barrelRepository.UpdateBarrel(command.BarrelFromId, barrelFrom);
                _barrelRepository.UpdateBarrel(command.BarrelToId, barrelTo);
                _transferRepository.AddTransfer(transfer);

                scope.Complete();
            }
        }
Esempio n. 8
0
        public TransferResult MakeTransfer(TransferCommand command)
        {
            EnsureIsValid(command);

            var fromCard = UnitOfWork.BankCardRepository.Find(command.FromCardId);
            var toCard   = UnitOfWork.BankCardRepository.Find(command.ToCardId);

            if (fromCard == null)
            {
                return(TransferResult.FromNotFound);
            }

            if (toCard == null)
            {
                return(TransferResult.ToNotFound);
            }

            var fromBankAccount = UnitOfWork.BankAccountRepository.Find(fromCard.BankAccountId);
            var toBankAccount   = UnitOfWork.BankAccountRepository.Find(toCard.BankAccountId);

            if (fromBankAccount.Money - command.Amount < 0)
            {
                return(TransferResult.NotEnoughMoney);
            }

            fromBankAccount.Money -= command.Amount;
            toBankAccount.Money   += command.Amount;

            return(TransferResult.Success);
        }
Esempio n. 9
0
        public async Task <IActionResult> transfer([FromBody] TransferCommand command)
        {
            var response = new BaseResponse();

            try
            {
                var walletDes = (from p in _context.WalletType
                                 join c in _context.Wallets
                                 on p.WalletTypeId equals c.WalletTypeId
                                 where p.WalletTypeName == command.AccountDes
                                 select new
                {
                    WalletId = c.WalletId,
                    WalletType = p.WalletTypeName
                }).FirstOrDefault();



                var walletSource = (from p in _context.WalletType
                                    join c in _context.Wallets
                                    on p.WalletTypeId equals c.WalletTypeId
                                    where p.WalletTypeName == command.AccountSource
                                    select new
                {
                    WalletId = c.WalletId,
                    WalletType = p.WalletTypeName,
                    Balance = c.Balance
                }).FirstOrDefault();
                if (walletSource == null || walletDes == null)
                {
                    response.Code    = ErrorCode.GetError(ErrorCode.AccountNotFound).Key;
                    response.Message = ErrorCode.GetError(ErrorCode.AccountNotFound).Value;
                    return(Ok(response));
                }

                var transactionType = _context.TransactionType.Where(s => s.TransactionTypeName == TransactionTypeEnum.TRANSFER.ToString()).FirstOrDefault();
                if (command.Amount + transactionType.Fee > walletSource.Balance)
                {
                    response.Code    = ErrorCode.GetError(ErrorCode.AmountNotEnough).Key;
                    response.Message = ErrorCode.GetError(ErrorCode.AmountNotEnough).Value;
                    return(Ok(response));
                }

                command.Fee = transactionType.Fee;
                command.TransactionTypeId = transactionType.TransactionTypeId;
                command.WalletSourceId    = walletSource.WalletId;
                command.WalletDesId       = walletDes.WalletId;

                response = await _mediator.Send(command);
            }
            catch (Exception ex)
            {
                response.Code    = ErrorCode.GetError(ErrorCode.SystemError).Key;
                response.Message = ErrorCode.GetError(ErrorCode.SystemError).Value;
                Logger.Error($"Exception: {ex} , Method:transfer");
            }

            return(Ok(response));
        }
Esempio n. 10
0
 public static BlockchainTransferCommand ToBlockchainTransfer(this TransferCommand src)
 {
     return(new BlockchainTransferCommand
     {
         AssetId = src.AssetId,
         Amounts = src.Amounts
     });
 }
        public static async Task <ActivityResult <ProducerResult> > ProduceTransferCommandAsync(
            TransactionItem item, IDurableOrchestrationContext context, ILogger log)
        {
            TransferCommand command      = CommandFactory.BuildTransferCommand(item);
            string          functionName = nameof(ProducerActivity.TransferCommandProducerActivity);

            return(await RunProducerActivityAsync(functionName, command, context, log));
        }
Esempio n. 12
0
        public static async Task <ProducerResult> TransferCommandProducerActivity(
            [EventHub(@"%TransferEventHubName%", Connection = @"EventHubsNamespaceConnection")] IAsyncCollector <EventData> messagesCollector,
            [ActivityTrigger] TransferCommand command,
            ILogger log)
        {
            Producer producer = new Producer(messagesCollector, log);

            return(await producer.ProduceCommandWithRetryAsync(command));
        }
Esempio n. 13
0
        static void Main(string[] args)
        {
            var tc = new TransferCommand(
                new Customer("John", "123456"),
                new Customer("Chad", "12345"),
                1000);

            new TransferCommandHandler <TransferCommand>()
            .Handle(tc);
        }
Esempio n. 14
0
        public void Validate_ShouldFail_WhenNoTagsGiven()
        {
            var command = new TransferCommand(new List <IdAndRowVersion>());

            var result = _dut.Validate(command);

            Assert.IsFalse(result.IsValid);
            Assert.AreEqual(1, result.Errors.Count);
            Assert.IsTrue(result.Errors[0].ErrorMessage.StartsWith("At least 1 tag must be given!"));
        }
Esempio n. 15
0
        public void Constructor_ShouldSetProperties()
        {
            var idAndRowVersion = new IdAndRowVersion(17, "AAAAAAAAABA=");
            var dut             = new TransferCommand(new List <IdAndRowVersion> {
                idAndRowVersion
            });

            Assert.AreEqual(1, dut.Tags.Count());
            Assert.AreEqual(idAndRowVersion, dut.Tags.First());
        }
Esempio n. 16
0
        string BuildTransferCommand()
        {
            var order = new TransferCommand()
            {
                FromAccountId   = "test1",
                ToAccountId     = "test2",
                TransfertAmount = 500
            };

            return(JsonConvert.SerializeObject(order));
        }
        public IActionResult MakeTransfer([FromBody] TransferCommand command)
        {
            var result = _paymentService.MakeTransfer(command);

            if (result != TransferResult.Success)
            {
                return(BadRequest(result.GetStringValue()));
            }

            return(Ok(result.GetStringValue()));
        }
Esempio n. 18
0
        public async Task <IActionResult> Post([FromBody] TransferCommand transfer)
        {
            var response = await _mediator.Send(transfer);

            if (response.HasError)
            {
                return(BadRequest(response.Data));
            }

            return(Ok(response.Data));
        }
Esempio n. 19
0
        public override Command[] Process()
        {
            TradingTransferCommand tradingTransferCommand = _command;
            TransferCommand        transferCommand        = new TransferCommand();

            transferCommand.TransferId = tradingTransferCommand.TransferId;
            transferCommand.Action     = tradingTransferCommand.Action;
            transferCommand.RemitterId = tradingTransferCommand.RemitterId;
            transferCommand.PayeeId    = tradingTransferCommand.PayeeId;
            return(new Command[] { transferCommand });
        }
        public async Task <TransferResult> ExecuteAsync(TransferCommand transferCommand)
        {
            BlockchainType blockchainType = await _assetSettingsService.GetNetworkAsync(transferCommand.AssetId);

            IBlockchainApiClient blockchainClient = _blockchainClientProvider.Get(blockchainType);

            BlockchainTransferCommand cmd = new BlockchainTransferCommand(transferCommand.AssetId);

            string lykkeAssetId = transferCommand.AssetId.IsGuid()
                ? transferCommand.AssetId
                : await _lykkeAssetsResolver.GetLykkeId(transferCommand.AssetId);

            foreach (var transferCommandAmount in transferCommand.Amounts)
            {
                decimal balance = await blockchainClient.GetBalanceAsync(transferCommandAmount.Source, lykkeAssetId);

                if (transferCommandAmount.Amount == null)
                {
                    if (balance > 0)
                    {
                        cmd.Amounts.Add(new TransferAmount
                        {
                            Amount      = balance,
                            Source      = transferCommandAmount.Source,
                            Destination = transferCommandAmount.Destination
                        });

                        continue;
                    }

                    throw new InsufficientFundsException(transferCommandAmount.Source, transferCommand.AssetId);
                }

                if (transferCommandAmount.Amount > balance)
                {
                    throw new InsufficientFundsException(transferCommandAmount.Source, transferCommand.AssetId);
                }

                cmd.Amounts.Add(transferCommandAmount);
            }

            BlockchainTransferResult blockchainTransferResult = await blockchainClient.TransferAsync(cmd);

            ITransfer transfer = await _transferRepository.AddAsync(new Transfer
            {
                AssetId      = transferCommand.AssetId,
                Blockchain   = blockchainTransferResult.Blockchain,
                CreatedOn    = DateTime.UtcNow,
                Amounts      = transferCommand.Amounts,
                Transactions = Mapper.Map <IEnumerable <TransferTransaction> >(blockchainTransferResult.Transactions)
            });

            return(Mapper.Map <TransferResult>(transfer));
        }
Esempio n. 21
0
        public void Validate_ShouldFail_WhenTagsNotUnique()
        {
            var command = new TransferCommand(new List <IdAndRowVersion> {
                new IdAndRowVersion(1, null), new IdAndRowVersion(1, null)
            });

            var result = _dut.Validate(command);

            Assert.IsFalse(result.IsValid);
            Assert.AreEqual(1, result.Errors.Count);
            Assert.IsTrue(result.Errors[0].ErrorMessage.StartsWith("Tags must be unique!"));
        }
        public async Task <CommandHandlingResult> Handle(Commands.SaveTransferOperationStateCommand command, IEventPublisher eventPublisher)
        {
            var message       = command.QueueMessage;
            var transactionId = message.Id;

            var transaction = await _transactionsRepository.FindByTransactionIdAsync(transactionId);

            if (transaction == null)
            {
                _log.Error(nameof(Commands.SaveManualOperationStateCommand), new Exception($"unknown transaction {transactionId}"), context: command);
                return(CommandHandlingResult.Ok());
            }

            var amountNoFee = await _feeCalculationService.GetAmountNoFeeAsync(message);

            var context = await _transactionService.GetTransactionContext <TransferContextData>(transactionId) ??
                          TransferContextData.Create(
                message.FromClientId,
                new TransferContextData.TransferModel
            {
                ClientId = message.ToClientid
            },
                new TransferContextData.TransferModel
            {
                ClientId = message.FromClientId
            });

            context.Transfers[0].OperationId = Guid.NewGuid().ToString();
            context.Transfers[1].OperationId = Guid.NewGuid().ToString();

            var destWallet = await _walletCredentialsRepository.GetAsync(message.ToClientid);

            var sourceWallet = await _walletCredentialsRepository.GetAsync(message.FromClientId);

            var contextJson = context.ToJson();
            var cmd         = new TransferCommand
            {
                Amount             = amountNoFee,
                AssetId            = message.AssetId,
                Context            = contextJson,
                SourceAddress      = sourceWallet?.MultiSig,
                DestinationAddress = destWallet?.MultiSig,
                TransactionId      = Guid.Parse(transactionId)
            };

            await SaveState(cmd, context);

            eventPublisher.PublishEvent(new TransferOperationStateSavedEvent {
                TransactionId = transactionId, QueueMessage = message, AmountNoFee = (double)amountNoFee
            });

            return(CommandHandlingResult.Ok());
        }
Esempio n. 23
0
        private void SetProperties(TransferCommand command)
        {
            if (command.BarrelFromId == command.BarrelToId)
            {
                throw new Exception("Can't transfer wine into the same barrel");
            }

            BarrelFromId = command.BarrelFromId;
            BarrelToId   = command.BarrelToId;
            WineId       = command.WineId;
            Amount       = command.Amount;
            Date         = DateTime.UtcNow;
        }
Esempio n. 24
0
        public async Task <ActionResult <AccountResponse> > AddBalance([FromBody] TransferCommand command)
        {
            var response = await _mediator.Send(command);

            if (response.Status)
            {
                return(Ok(response));
            }
            else
            {
                return(BadRequest(response));
            }
        }
Esempio n. 25
0
        public void MakeTransfer_FromNotFound()
        {
            var command = new TransferCommand
            {
                FromCardId = card1.Id,
                ToCardId   = card2.Id,
                Amount     = 10
            };

            var result = _paymentService.MakeTransfer(command);

            Assert.AreEqual(result, TransferResult.FromNotFound);
        }
Esempio n. 26
0
        /// <summary>
        /// 如果URL中没有参数,则自动转到选人的界面,动态构造流程
        /// </summary>
        protected override void DefaultOperation()
        {
            TransferCommand command = new TransferCommand("SelectUser");

            HttpRequest request = HttpContext.Current.Request;

            NameValueCollection uriParams = UriHelper.GetUriParamsCollection(request.Url.ToString());

            command.NavigateUrl = string.Format("SelectProcessUsers.aspx?ru={0}",
                                                HttpUtility.UrlEncode(UriHelper.CombineUrlParams(request.CurrentExecutionFilePath, uriParams)));

            command.Execute();
        }
        public void TestHandleTransferFromDepositToDeposit()
        {
            var publisher = new Mock <IEventPublisher>();
            var handler   = new TransferCommandHandler();
            var command   = new TransferCommand
            {
                Currency             = Currencies.Dollars.Of(10),
                SourceDepositId      = Guid.NewGuid(),
                DestinationDepositId = Guid.NewGuid()
            };

            handler.Handle(command);
            Assert.False(true);
        }
        public void TestCanHandle()
        {
            var handler = new TransferCommandHandler();
            var command = new TransferCommand
            {
                Currency             = Currencies.Dollars.Of(10),
                SourceDepositId      = Guid.NewGuid(),
                DestinationDepositId = Guid.NewGuid()
            };

            var canHandle = handler.CanHandle(command);

            Assert.True(canHandle);
        }
Esempio n. 29
0
 //command是null的时候不进行发送。
 public void SendData(TransferCommand command)
 {
     if (stream != null && client != null && client.Connected)
     {
         if (stream.CanWrite && command != null)
         {
             ProtoBuf.Serializer.SerializeWithLengthPrefix <TransferCommand>(stream, command, PrefixStyle.Base128);
         }
     }
     else if ((client == null || client.Connected == false) && connectState != ConnectState.isConnecting)
     {
         connectState = ConnectState.disConnected;
         ReConnectServer();
     }
 }
Esempio n. 30
0
        public void Handle(TransferCommand command)
        {
            Console.WriteLine($"Log: Start");

            _customerService
            .ValidateExistingCustomerAsync(command.From)
            .OnFailure(() => Console.WriteLine($"Log: Invalid Client - {command.From.Name}"))
            .OnSuccess(() => _accountService.IsCustomerBalanceEnough(command.From, command.Value)
                       .OnFailure(() => Console.WriteLine($"Log: Not enough balance! {command.From.Name}")));

            //TODO:
            // Check if recipient client id valid;
            // Send Transfer Order;
            // Send emitter balance update order;
            // Notificate both if success;
        }
Esempio n. 31
0
        internal async Task<TransferCommand> GetSwitchboard()
        {

            await @lock.ReaderLockAsync();

            try
            {

                if (closed)
                    throw new ObjectDisposedException(GetType().Name);

                if (!IsLoggedIn)
                    throw new NotLoggedInException();

                Command cmd = new TransferCommand("SB");
                return await responseTracker.GetResponseAsync<TransferCommand>(cmd, defaultTimeout);

            }
            finally
            {
                @lock.ReaderRelease();
            }

        }