private void InvokeBackofficeCallback(EthereumTransfer transfer, CancellationToken cancellationToken)
        {
            TransferResult transferResult = null;

            do
            {
                try
                {
                    var backofficeRequest = _backofficeTransferHelper.CreateBackofficeTransferRequest(transfer, _options.ConfirmationsRequired);

                    transferResult = TransferCallback.Invoke(backofficeRequest);

                    if (transferResult.HasException)
                    {
                        throw transferResult.Exception;
                    }

                    LogInfo("Withdrawal transfer {@TransferId} with assetId = {@AssetId} and amountEth = {@Amount} to {@ToAddress} failed to be sent",
                            backofficeRequest.TransferId,
                            backofficeRequest.AssetId, backofficeRequest.Amount, backofficeRequest.TargetAccount);
                }
                catch (Exception ex)
                {
                    LogError(ex, "TransferCallback.Invoke failed");
                }
            } while (transferResult == null && !cancellationToken.WaitHandle.WaitOne(InvokeTransferCallbackRetryIntervalMs));
        }
Esempio n. 2
0
        public TransferResult Transfer(int cardFromId, Transfer transfer)
        {
            TransferResult result;
            var            cardFrom = dataBase.GetCardById(cardFromId);
            var            cardTo   = dataBase.GetCardByNumber(transfer.CardToNumber);
            var            amount   = transfer.Amount;

            if (cardFrom.Balance < amount)
            {
                result = new TransferResult {
                    Success = false, Message = "Недостаточный баланс"
                };
            }
            else
            {
                cardFrom.Balance -= amount;
                cardTo.Balance   += amount;
                dataBase.ApplyChanges(cardFrom);
                dataBase.ApplyChanges(cardTo);
                result = new TransferResult {
                    Success = true
                };
            }

            return(result);
        }
        public void Buy_Fails_If_SrcTransfer_Fails()
        {
            var order = NewSimpleSellOrder(Seller, DefaultZeroValue, DefaultPrice, DefaultAmount);

            MockContractState.Setup(x => x.Message).Returns(new Message(ContractAddress, BuyerOne, DefaultCostValue));

            var amountInStratoshis = DefaultAmount * 100_000_000;
            var expectedCallParams = new object[] { Seller, BuyerOne, amountInStratoshis };

            MockInternalExecutor.Setup(x =>
                                       x.Call(It.IsAny <ISmartContractState>(), Token, 0, "TransferFrom", expectedCallParams, 0))
            .Returns(TransferResult.Transferred(false));

            Assert.ThrowsAny <SmartContractAssertException>(() => order.Buy(DefaultAmount));

            MockInternalExecutor.Verify(x =>
                                        x.Call(It.IsAny <ISmartContractState>(), Token, 0, "TransferFrom", expectedCallParams, 0), Times.Once);

            MockInternalExecutor.Verify(x => x.Transfer(It.IsAny <ISmartContractState>(), Seller, DefaultCostValue), Times.Never);

            MockContractLogger.Verify(x => x.Log(It.IsAny <ISmartContractState>(), It.IsAny <Transaction>()), Times.Never);

            MockPersistentState.Verify(x => x.SetUInt64(nameof(Amount), 0), Times.Never);

            MockPersistentState.Verify(x => x.SetBool(nameof(IsActive), false), Times.Never);
        }
Esempio n. 4
0
        public static bool PrintTransferResult(TransferResult res)
        {
            switch (res)
            {
            case TransferResult.SuccessBorrowing:
                WriteLine(Properties.Resources.WithdrawalSuccessBorrow);
                return(true);

            case TransferResult.SuccessNoBorrow:
                WriteLine(Properties.Resources.WithdrawalSuccessNoBorrow);
                return(true);

            case TransferResult.ImmatureFunds:
                WriteLine(Properties.Resources.WithdrawalImmatureFunds);
                break;

            case TransferResult.InsufficientFunds:
                WriteLine(Properties.Resources.WithdrawalInsufficientFunds);
                break;

            default:
                break;
            }
            return(false);
        }
Esempio n. 5
0
        /// <summary>
        /// 购买表情包
        /// </summary>
        /// <param name="nodeid">用户nodeid</param>
        /// <param name="price">价格</param>
        /// <param name="config">购买钱包配置id</param>
        /// <returns></returns>
        private bool Transfer_EmoticonPay(int nodeid, decimal price, int config)
        {
            var purseconfig = db.TnetPurseConfigSet.Where(c => c.Infoid == config).FirstOrDefault();

            if (purseconfig == null)
            {
                Alert("支付配置不存在");
                return(false);
            }

            CurrencyType type      = new CurrencyType(purseconfig.Currencytype);
            Purse        toPurse   = purseFactory.SystemPurseRand(nodeid);
            Purse        fromPurse = new Purse(OwnerType.个人钱包, nodeid, (PurseType)purseconfig.Pursetype, type, wcfProxy);
            Currency     currency  = new Currency(type, price);

            TransferResult tResult = wcfProxy.Transfer(fromPurse, toPurse, currency, 13, "购买表情包");

            if (!tResult.IsSuccess)
            {
                Alert("购买失败:" + tResult.Message);
                return(false);
            }
            _transferid = tResult.TransferId;
            return(true);
        }
Esempio n. 6
0
        public async Task <TransferResult> Transfer(int sourceAccountId, int destinationAccountId, decimal amount)
        {
            TransferResult result = new TransferResult();

            using (IDbContextTransaction transaction =
                       _usersAccountsRepository.BeginTransaction(IsolationLevel.ReadUncommitted))
            {
                try
                {
                    UserAccount sourceAccount = await CreatePayment(sourceAccountId, (-1) *amount);

                    UserAccount destinationAccount = await CreatePayment(destinationAccountId, amount);

                    transaction.Commit();

                    result.SourceBalance      = sourceAccount.Balance;
                    result.DestinationBalance = destinationAccount.Balance;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw new InternalErrorException("Не удалось завершить транзакцию перевода средств");
                }
            }

            return(result);
        }
        private async Task RegisterTransferTxsAsync(TransferResult transfer, bool outgoing = true)
        {
            foreach (var transferTransactionResult in transfer.Transactions)
            {
                string historyId = outgoing
                    ? await _walletHistoryService.PublishOutgoingExchangeAsync(Mapper
                                                                               .Map <WalletHistoryOutgoingExchangeCommand>(transferTransactionResult).Map(transfer))
                    : await _walletHistoryService.PublishIncomingExchangeAsync(Mapper
                                                                               .Map <WalletHistoryIncomingExchangeCommand>(transferTransactionResult).Map(transfer));

                await _transactionsService.CreateTransactionAsync(
                    new CreateTransactionCommand
                {
                    Amount                = transferTransactionResult.Amount,
                    Blockchain            = transfer.Blockchain,
                    AssetId               = transferTransactionResult.AssetId,
                    Confirmations         = 0,
                    Hash                  = transferTransactionResult.Hash,
                    IdentityType          = transferTransactionResult.IdentityType,
                    Identity              = transferTransactionResult.Identity,
                    TransferId            = transfer.Id,
                    Type                  = TransactionType.Exchange,
                    SourceWalletAddresses = transferTransactionResult.Sources.ToArray(),
                    ContextData           = new ExchangeTransactonContext {
                        HistoryOperationId = historyId
                    }.ToJson()
                });
            }
        }
        private RefundResult PrepareRefundResult(IPaymentRequest paymentRequest,
                                                 TransferResult transferResult, DateTime refundDueDate)
        {
            var assetIds = transferResult.Transactions.Unique(x => x.AssetId).ToList();

            if (assetIds.MoreThanOne())
            {
                _log.Warning("Multiple assets are not expected", context: new
                {
                    PaymentResuest       = paymentRequest,
                    RefundTransferResult = transferResult
                });
            }

            return(new RefundResult
            {
                Amount = transferResult.GetSuccedeedTxs().Sum(x => x.Amount),
                AssetId = assetIds.Single(),
                PaymentRequestId = paymentRequest.Id,
                PaymentRequestWalletAddress = paymentRequest.WalletAddress,
                Transactions = transferResult.Transactions.Select(x => new RefundTransactionResult
                {
                    Amount = x.Amount,
                    AssetId = x.AssetId,
                    Blockchain = transferResult.Blockchain,
                    Hash = x.Hash,
                    SourceAddress = string.Join(";", x.Sources),
                    DestinationAddress = string.Join(";", x.Destinations)
                }),
                DueDate = refundDueDate,
                Timestamp = transferResult.Timestamp
            });
        }
        public void Success_GetOrderDetails()
        {
            var order = NewSimpleSellOrder(Seller, DefaultZeroValue, DefaultPrice, DefaultAmount);

            MockContractState.Setup(x => x.Message).Returns(new Message(ContractAddress, BuyerOne, DefaultZeroValue));

            var expectedBalance    = DefaultAmount * 100_000_000;
            var expectedCallParams = new object[] { Seller, ContractAddress };

            MockInternalExecutor.Setup(x =>
                                       x.Call(It.IsAny <ISmartContractState>(), Token, 0, "Allowance", expectedCallParams, 0))
            .Returns(TransferResult.Transferred(expectedBalance));

            var actualOrderDetails = order.GetOrderDetails();

            var expectedOrderDetails = new OrderDetails
            {
                Seller    = Seller,
                Token     = Token,
                Price     = DefaultPrice,
                Amount    = DefaultAmount,
                OrderType = nameof(SimpleSellOrder),
                IsActive  = true,
                Balance   = expectedBalance
            };

            Assert.Equal(expectedOrderDetails, actualOrderDetails);
        }
        public static async Task <TransferResult> ExchangeThrowFail(this ITransferService src, string assetId,
                                                                    string sourceAddress, string destAddress, decimal?amount = null)
        {
            TransferResult transferResult = await src.ExecuteAsync(assetId, sourceAddress, destAddress, amount);

            foreach (var transactionResult in transferResult.Transactions)
            {
                if (transactionResult.ErrorType == TransactionErrorType.NotEnoughFunds)
                {
                    throw new InsufficientFundsException(sourceAddress, assetId);
                }
            }

            if (!transferResult.HasSuccess())
            {
                throw new ExchangeOperationFailedException(transferResult.GetErrors());
            }

            if (transferResult.HasError())
            {
                throw new ExchangeOperationPartiallyFailedException(transferResult.GetErrors());
            }

            return(transferResult);
        }
        public void Approve_Succeeds(ulong amountToTransfer, ulong contractBalance)
        {
            var contract = Newcontract(Owner, Owner, 0, StartTime, EndTime);

            MockPersistentState.Setup(s => s.GetString($"Status:{ApplicationId}")).Returns(ApprovedStatus);
            MockPersistentState.Setup(x => x.GetInt32($"{ApplicationId}:Category")).Returns(ApplicationDefaultCategory);
            MockPersistentState.Setup(s => s.GetAddress($"{ApplicationId}")).Returns(Applicant);
            MockPersistentState.Setup(s => s.GetUInt64($"Category:{ApplicationDefaultCategory}")).Returns(amountToTransfer);
            MockContractState.Setup(x => x.GetBalance).Returns(() => contractBalance);

            MockInternalExecutor.Setup(s =>
                                       s.Transfer(
                                           MockContractState.Object,
                                           Applicant,
                                           amountToTransfer))
            .Returns(TransferResult.Transferred(new object()));

            var result = contract.Approve(ApplicationId);

            Assert.True(result);

            MockPersistentState.Verify(x => x.SetString($"Status:{ApplicationId}", ApprovedStatus), Times.Once);
            MockContractLogger.Verify(x => x.Log(It.IsAny <ISmartContractState>(), new StatusLog {
                Id = ApplicationId, Applicant = Applicant, Status = ApprovedStatus
            }), Times.Once);
            MockContractLogger.Verify(x => x.Log(It.IsAny <ISmartContractState>(), new TransactionLog {
                From = ContractAddress, To = Applicant, Amount = amountToTransfer
            }), Times.Once);
        }
        public void Buy_CalculatesStratoshisToSend_Success(ulong amountToBuy, uint fullTokenInStratoshies)
        {
            amountToBuy = DefaultAmount >= amountToBuy ? amountToBuy : DefaultAmount;

            var order = NewSimpleSellOrder(Seller, DefaultZeroValue, DefaultPrice, DefaultAmount, fullTokenInStratoshies);

            ulong orderCost = amountToBuy * DefaultPrice;
            ulong updatedContractBalance = order.Balance - orderCost;

            MockContractState.Setup(x => x.Message).Returns(new Message(ContractAddress, BuyerOne, orderCost));

            var amountInStratoshis = amountToBuy * fullTokenInStratoshies;
            var expectedCallParams = new object[] { Seller, BuyerOne, amountInStratoshis };

            MockInternalExecutor.Setup(x =>
                                       x.Call(It.IsAny <ISmartContractState>(), Token, 0, "TransferFrom", expectedCallParams, 0))
            .Returns(TransferResult.Transferred(true));

            MockInternalExecutor.Setup(x => x.Transfer(It.IsAny <ISmartContractState>(), It.IsAny <Address>(), It.IsAny <ulong>()))
            .Callback(() => MockContractState.Setup(x => x.GetBalance).Returns(() => updatedContractBalance));

            MockPersistentState.Setup(x => x.SetUInt64(nameof(Amount), DefaultAmount - amountToBuy))
            .Callback(() => MockPersistentState.Setup(x => x.GetUInt64(nameof(Amount))).Returns(DefaultAmount - amountToBuy));

            order.Buy(amountToBuy);

            MockInternalExecutor.Verify(x =>
                                        x.Call(It.IsAny <ISmartContractState>(), Token, 0, "TransferFrom", expectedCallParams, 0), Times.Once);

            MockContractState.Verify(x => x.InternalTransactionExecutor
                                     .Transfer(It.IsAny <ISmartContractState>(), Seller, orderCost), Times.Once);
        }
Esempio n. 13
0
        private async Task <RefundResult> PrepareRefundResult(IPaymentRequest paymentRequest,
                                                              TransferResult transferResult, DateTime refundDueDate)
        {
            var assetIds = transferResult.Transactions.Unique(x => x.AssetId).ToList();

            if (assetIds.MoreThanOne())
            {
                await _log.WriteWarningAsync(nameof(PaymentRequestService), nameof(PrepareRefundResult), new
                {
                    PaymentResuest       = paymentRequest,
                    RefundTransferResult = transferResult
                }.ToJson(), "Multiple assets are not expected");
            }

            return(new RefundResult
            {
                Amount = transferResult.Transactions
                         .Where(x => string.IsNullOrEmpty(x.Error))
                         .Sum(x => x.Amount),
                AssetId = assetIds.Single(),
                PaymentRequestId = paymentRequest.Id,
                PaymentRequestWalletAddress = paymentRequest.WalletAddress,
                Transactions = transferResult.Transactions.Select(x => new RefundTransactionResult
                {
                    Amount = x.Amount,
                    AssetId = x.AssetId,
                    Blockchain = transferResult.Blockchain,
                    Hash = x.Hash,
                    SourceAddress = string.Join(";", x.Sources),
                    DestinationAddress = string.Join(";", x.Destinations)
                }),
                DueDate = refundDueDate,
                Timestamp = transferResult.Timestamp
            });
        }
Esempio n. 14
0
        /// <summary>
        /// Constructs a result when a transfer from a contract succeeded and a return value is expected.
        /// </summary>
        /// <param name="returnValue">The object that was returned from the executor.</param>
        public static TransferResult Transferred(object returnValue)
        {
            var result = new TransferResult(true)
            {
                ReturnValue = returnValue
            };

            return(result);
        }
Esempio n. 15
0
        public static Task AssertTrezorResult(TransferResult responseData, IDevice device)
        {
            //Specify the response part of the Message Contract
            var expectedResult = new byte[] { 63, 35, 35 };

            //Assert that the response part meets the specification
            Assert.IsTrue(expectedResult.SequenceEqual(responseData.Data.Take(3)));

            return(Task.FromResult(true));
        }
        public async Task <ExchangeResult> ExecuteAsync(ExchangeCommand cmd)
        {
            BlockchainType network = await _assetSettingsService.GetNetworkAsync(cmd.SourceAssetId);

            if (await _assetSettingsService.GetNetworkAsync(cmd.DestAssetId) != network)
            {
                throw new ExchangeOperationNotSupportedException("Assets are being served by different blockchains");
            }

            IAssetPairRate rate = await _assetRatesService.GetCurrentRateAsync(cmd.SourceAssetId, cmd.DestAssetId);

            if (cmd.ExpectedRate != null && rate.BidPrice != cmd.ExpectedRate)
            {
                throw new ExchangeRateChangedException(rate.BidPrice);
            }

            string hotwallet = _bcnSettingsResolver.GetExchangeHotWallet(network);

            string sourceAddress = await GetSourceAddressAsync(cmd);

            decimal exchangeAmount = cmd.SourceAmount * rate.BidPrice;

            await _walletBalanceValidator.ValidateTransfer(sourceAddress, cmd.SourceAssetId, cmd.SourceAmount);

            await _walletBalanceValidator.ValidateTransfer(hotwallet, cmd.DestAssetId, exchangeAmount);

            TransferResult toHotWallet = await _retryPolicy
                                         .ExecuteAsync(() => _transferService.ExchangeThrowFail(
                                                           cmd.SourceAssetId,
                                                           sourceAddress,
                                                           hotwallet,
                                                           cmd.SourceAmount));

            await RegisterTransferTxsAsync(toHotWallet);

            string destAddress = await GetDestAddressAsync(cmd);

            TransferResult fromHotWallet = await _retryPolicy
                                           .ExecuteAsync(() => _transferService.ExchangeThrowFail(
                                                             cmd.DestAssetId,
                                                             hotwallet,
                                                             destAddress,
                                                             exchangeAmount));

            await RegisterTransferTxsAsync(fromHotWallet, false);

            return(new ExchangeResult
            {
                SourceAssetId = cmd.SourceAssetId,
                SourceAmount = cmd.SourceAmount,
                DestAssetId = cmd.DestAssetId,
                DestAmount = exchangeAmount,
                Rate = rate.BidPrice
            });
        }
Esempio n. 17
0
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            UrlHelper urlHelper = new UrlHelper(context.RequestContext);
            string url = urlHelper.RouteUrl(this.RouteName, this.RouteValues);

            TransferResult actualResult = new TransferResult(url);
            actualResult.ExecuteResult(context);
        }
Esempio n. 18
0
        protected override void Redirect(ActionExecutedContext filterContext)
        {
            PlaceInItemDictionary("Error", filterContext.Exception, filterContext);
            PlaceInItemDictionary("Controller", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext);
            PlaceInItemDictionary("Action", filterContext.ActionDescriptor.ActionName, filterContext);
            filterContext.ExceptionHandled = true;
            //filterContext.HttpContext.Server.Transfer(Url, true);
            var transferResult = new TransferResult(Url);

            transferResult.ExecuteResult(filterContext.Controller.ControllerContext);
        }
Esempio n. 19
0
        protected Result <T> Success(T context, TransferResult result)
        {
            var r = Pass(context);

            r.Status = new WorkerStatus {
                Code        = WorkerStatus.SUCCESS,
                Description = "Transfer success",
                Result      = result
            };
            return(r);
        }
Esempio n. 20
0
 protected void SetupTransfer(Address to, ulong value, TransferResult result)
 {
     _mockInternalExecutor
     .Setup(x => x.Transfer(_mockContractState.Object, to, value))
     .Returns(result)
     .Callback(() =>
     {
         var balance = _mockContractState.Object.GetBalance();
         _mockContractState.Setup(x => x.GetBalance).Returns(() => checked (balance - value));
     });
 }
Esempio n. 21
0
        public ContentResult Transfer([FromForm] TransferAction action, [FromForm] string orderId, [FromForm] decimal money)
        {
            TransferResult result = APIAgent.Instance().Transfer(this.SiteInfo, this.GameInfo, this.UserInfo, action, orderId, money);

            return(new ContentResult()
            {
                ContentType = "application/json",
                StatusCode = 200,
                Content = result.ToString()
            });
        }
Esempio n. 22
0
        public void CreateContract_Throws_InvalidGovernanceAddress()
        {
            SetupBalance(0);
            SetupBlock(10);

            SetupCall(StakingToken, 0, "get_MiningGovernance", null, TransferResult.Transferred(Address.Zero));

            this.Invoking(p => p.BlankMiningPool())
            .Should()
            .Throw <SmartContractAssertException>()
            .WithMessage("OPDEX: INVALID_GOVERNANCE_ADDRESS");
        }
Esempio n. 23
0
        protected IOpdexMiningPool CreateNewMiningPool(ulong block = 10)
        {
            _mockContractState.Setup(x => x.Message).Returns(new Message(MiningPool1, Pool1, 0));

            SetupBalance(0);
            SetupBlock(block);

            SetupCall(StakingToken, 0, "get_MiningGovernance", null, TransferResult.Transferred(MiningGovernance));
            SetupCall(MiningGovernance, 0, "get_MiningDuration", null, TransferResult.Transferred(BlocksPerMonth));

            return(new OpdexMiningPool(_mockContractState.Object, StakingToken, Pool1));
        }
        public async Task <uint> WriteReportAsync(byte[] data, byte reportId, CancellationToken cancellationToken = default)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (DataReceiver.HasData)
            {
                Logger.LogWarning("Writing to device but data has already been received that has not been read");
            }

            var tranformedData = _writeTransferTransform(data, reportId);

            var buffer = tranformedData.AsBuffer();

            //We pass the report id. All this does is sets the array at index zero to the report id
            //This gets overwritten by the tranform anyway
            //It would probably be nice to set the values in outReport.Data from index 1-Length but it doesn't seem possible to do that
            var outReport = ConnectedDevice.CreateOutputReport(reportId);

            outReport.Data = buffer;

            try
            {
                var operation = ConnectedDevice.SendOutputReportAsync(outReport);
                var count     = await operation.AsTask(cancellationToken);

                if (count == tranformedData.Length)
                {
                    //Get the actual data sent, and the actual number of bytes written and log them
                    var transferResult = new TransferResult(outReport.Data.ToArray(), count);
                    Logger.LogDataTransfer(new Trace(true, transferResult));
                }
                else
                {
                    Logger.LogError(Messages.GetErrorMessageInvalidWriteLength(tranformedData.Length, count) + "{length} {count}", tranformedData.Length, count, GetType().Name);
                    throw new IOException(Messages.GetErrorMessageInvalidWriteLength(tranformedData.Length, count));
                }

                return(count);
            }
            catch (ArgumentException ex)
            {
                //TODO: Check the string is nasty. Validation on the size of the array being sent should be done earlier anyway
                if (string.Equals(ex.Message, "Value does not fall within the expected range.", StringComparison.Ordinal))
                {
                    throw new IOException("It seems that the data being sent to the device does not match the accepted size. Try specifying a write transfer transform", ex);
                }
                throw;
            }
        }
Esempio n. 25
0
        public void CreateContract_Throws_InvalidDurationAmount()
        {
            SetupBalance(0);
            SetupBlock(10);

            SetupCall(StakingToken, 0, "get_MiningGovernance", null, TransferResult.Transferred(MiningGovernance));
            SetupCall(MiningGovernance, 0, "get_MiningDuration", null, TransferResult.Transferred(0ul));

            this.Invoking(p => p.BlankMiningPool())
            .Should()
            .Throw <SmartContractAssertException>()
            .WithMessage("OPDEX: INVALID_DURATION_AMOUNT");
        }
Esempio n. 26
0
        public Task <TransferResult> ReadAsync(uint bufferLength, CancellationToken cancellationToken = default)
        {
            return(Task.Run(async() =>
            {
                try
                {
                    //TODO: validate here
                    var endpoint = ((AndroidUsbEndpoint)ReadEndpoint).UsbEndpoint;

                    using var logScope = Logger.BeginScope(
                              "UsbInterface: {usbInterface} Call: {call} Endpoint Id: {endpointId}",
                              UsbInterface.Id,
                              nameof(ReadAsync),
                              endpoint.EndpointNumber);
                    var byteBuffer = ByteBuffer.Allocate((int)bufferLength);
                    var request = _androidFactory.CreateUsbRequest();
                    _ = request.Initialize(_UsbDeviceConnection, endpoint);
#pragma warning disable CS0618
                    _ = request.Queue(byteBuffer, (int)bufferLength);
#pragma warning restore CS0618

                    _ = _timeout.HasValue
                        //Note: two versions here in case they have different functionality. When both code paths are tested it's probably possible to remove one
                        ? await _UsbDeviceConnection.RequestWaitAsync(_timeout.Value).ConfigureAwait(false)
                        : await _UsbDeviceConnection.RequestWaitAsync().ConfigureAwait(false);

                    //TODO: Get the actual length of the data read instead of just returning the length of the array

                    var buffers = new TransferResult(new byte[bufferLength], bufferLength);

                    _ = byteBuffer.Rewind();

                    //Ouch. Super nasty
                    for (var i = 0; i < bufferLength; i++)
                    {
                        buffers.Data[i] = (byte)byteBuffer.Get();
                    }

                    //Marshal.Copy(byteBuffer.GetDirectBufferAddress(), buffers, 0, ReadBufferLength);

                    Logger.LogDataTransfer(new Trace(false, buffers));

                    return buffers;
                }
                catch (Exception ex)
                {
                    Logger.LogError(Messages.ErrorMessageRead);
                    throw new IOException(Messages.ErrorMessageRead, ex);
                }
            }, cancellationToken));
        }
Esempio n. 27
0
        public override TransferResult Withdraw(decimal amount)
        {
            TransferResult res  = TransferResult.SuccessNoBorrow;
            decimal        diff = Balance - amount;

            if (diff < 0)
            {
                Balance += (diff * Bank.InterestRate);
                res      = TransferResult.SuccessBorrowing;
            }
            Balance -= amount;
            Transactions.Add(new Transaction(TransactionType.TransferOutOf, amount, res));
            return(res);
        }
        public void NotifyDistribution_Throws_InvalidMiningPool()
        {
            var pools = new[] { Pool1, Pool2, Pool3, Pool4 };
            var gov   = CreateNewOpdexMiningGovernance();

            SetupMessage(MiningGovernance, ODX);

            SetupCall(Pool1, 0, GetMiningPoolMethod, null, TransferResult.Transferred(Address.Zero));

            gov
            .Invoking(g => g.NotifyDistribution(pools[0], pools[1], pools[2], pools[3]))
            .Should()
            .Throw <SmartContractAssertException>()
            .WithMessage("OPDEX: INVALID_MINING_POOL");
        }
Esempio n. 29
0
        public static Report ToReadReport(this TransferResult tr, ILogger logger)
        {
            //Grab the report id
            var reportId = tr.Data[0];

            logger.LogDebug("Got the report id {reportId} from transfer result at index zero", reportId);

            //Create a new array and copy the data to it without the report id
            var data = tr.Data.TrimFirstByte(logger);

            logger.LogDebug("Returning the report based on the data and the Report Id", reportId);

            //Convert to a read report
            return(new Report(reportId, new TransferResult(data, tr.BytesTransferred)));
        }
Esempio n. 30
0
        public void DataReceived(TransferResult bytes)
        {
            _logger.LogTrace("{infoMessage}{trace}",
                             _readChunkTaskCompletionSource != null ? "Setting completion source..." : "Enqueuing data..."
                             , new Trace(false, bytes));

            if (_readChunkTaskCompletionSource != null)
            {
                _readChunkTaskCompletionSource.SetResult(bytes);
            }
            else
            {
                _readQueue.Enqueue(bytes);
            }
        }
 private void NewFolderSuccess(TransferResult result, string name)
 {
     if (result != TransferResult.Ok)
     {
         WindowManager.ShowMessage(Resx.AddNewFolder, string.Format(Resx.FolderAlreadyExists, name));
         return;
     }
     SourcePane.Refresh(false, () =>
     {
         var newFolder = SourcePane.Items.SingleOrDefault(item => item.Name == name);
         if (newFolder != null)
         {
             SourcePane.CurrentRow = newFolder;
         }
     });
 }
Esempio n. 32
0
        private void FtpSession_BeginPutFile(object sender, KCommon.Net.FTP.IFtpFileTransferArgs args)
        {
            #region Send Upload_Begin_Event
            long TotalDownloadPercentage = 0;
            //System.Math.DivRem((long)TotalFileSize,args.TotalBytesTransfered,out TotalDownloadPercentage);

            TransferDirection e = TransferDirection.Upload;
            if(args.TransferDirection == KCommon.Net.FTP.TransferDirection.Download)
                e = TransferDirection.Download;

            TransferResult TR = new TransferResult();
            OysterTransferArguments ota = new OysterTransferArguments(args.LocalFileName,
                args.RemoteFileName,(double)args.TotalBytes,0,TotalFileSize,TotalTransferProgress,
                e,args.TransferedPercentage,(int)TotalDownloadPercentage,TR);
            if(On_Upload_Begin != null)
                On_Upload_Begin(this,ota);
            #endregion

            LTransfer = 0;
            Msg(args.LocalFileName + ":" + " upload started...");
            Application.DoEvents();
        }
Esempio n. 33
0
        public static void ShowResults(string title, TransferResult result)
        {
            ShowHeader(title);
            Console.WriteLine("SessionId     {0}", result.SessionId);
            Console.WriteLine("SessionDate   {0}", result.SessionDate);
            Console.WriteLine("AccountNumber {0}", result.AccountNumber);
            Console.WriteLine("Source        {0}", result.SourceAccountNumber);
            Console.WriteLine("Destination   {0}", result.DestinationAccountNumber);
            Console.WriteLine("ExecutionDate {0}", result.ExecutionDate);
            Console.WriteLine("Amount        {0}", result.Amount.ToString("#,##0.00"));
            Console.WriteLine("IsSuccessful  {0}", result.Success);
            Console.WriteLine();

            if (result.Exceptions != null)
                foreach (ExceptionMessage ex in result.Exceptions) {
                    Console.WriteLine("    Exception: [{0}] - {1}, {2}", ((int)ex.ExceptionType), ex.ExceptionType, ex.Message);
                }
            Console.WriteLine();
        }
Esempio n. 34
0
 private void NewFolderSuccess(TransferResult result, string name)
 {
     if (result != TransferResult.Ok)
     {
         WindowManager.ShowMessage(Resx.AddNewFolder, string.Format(Resx.FolderAlreadyExists, name));
         return;
     }
     SourcePane.Refresh(() =>
                            {
                                SourcePane.CurrentRow = SourcePane.Items.Single(item => item.Name == name);
                            });
 }
Esempio n. 35
0
        private void FtpSession_EndPutFile(object sender, KCommon.Net.FTP.IFtpFileTransferArgs args)
        {
            #region Send Upload_Begin_Event

            long TotalDownloadPercentage = 0;
            try
            {
                TotalDownloadPercentage	= CalculatePercentage(TotalTransferProgress,TotalFileSize);
            }
            catch(Exception Err)
            {
                string peekError = Err.Message;
            }
            try
            {
                if(args.TransferResult != null)
                {
                    bTransferSuccess = args.TransferResult.IsSuccess;
                }
                else if(args.TransferedPercentage > 90)
                {
                    bTransferSuccess = true;
                }
                else
                {
                    bTransferSuccess = false;
                }
            }
            catch(Exception CErr)
            {
                string peekThisErr = CErr.Message;
            }

            try
            {
                TransferDirection e = TransferDirection.Upload;

                TransferResult TR = null;
                if(args.TransferDirection == KCommon.Net.FTP.TransferDirection.Download)
                    e = TransferDirection.Download;

                if(args.TransferResult != null)
                {
                    TR = new TransferResult(args.TransferResult.FtpResponseCode,
                        args.TransferResult.IsAborted,args.TransferResult.IsFailed,args.TransferResult.IsSuccess,
                        args.TransferResult.Message);
                }
                else
                {
                    TR = new TransferResult(0,false,false,false,"No transfer result received");
                }
                OysterTransferArguments ota = new OysterTransferArguments(args.LocalFileName,
                    args.RemoteFileName,(double)args.TotalBytes,TransferProgress,TotalFileSize,TotalTransferProgress,
                    e,args.TransferedPercentage,(int)TotalDownloadPercentage,TR);
                if(On_Upload_Complete != null)
                    On_Upload_Complete(this,ota);
            }
            catch(Exception PostError)
            {
                string peekError = PostError.Message;
                OysterTransferArguments Eota = new OysterTransferArguments(args);
                if(On_Upload_Complete != null)
                    On_Upload_Complete(this,Eota);
            }
            #endregion

            Msg("Upload complete.");
            TransferProgress = 0;
            //UploadingFile = false;
            m_ThreadTransferCompleteEvent.Set();
        }
Esempio n. 36
0
        private void FtpSession_FileTransferProgress(object sender, KCommon.Net.FTP.IFtpFileTransferArgs args)
        {
            try
            {
                double TotalSize = args.TotalBytes;
                TransferProgress = args.TotalBytesTransfered;
                if(LTransfer != 0)
                {
                    TotalTransferProgress += (TransferProgress - LTransfer);
                }
                LTransfer = TransferProgress;

            //				frmTS.pbCBar.Maximum = 100;
            //				frmTS.pbCBar.Minimum = 0;
            //				frmTS.pbTBar.Minimum = 0;
            //
            //				frmTS.pbCBar.Value = CalculatePercentage(TransferProgress,TotalSize);
            //				frmTS.pbTBar.Value =  CalculatePercentage(TotalTransferProgress,TotalFileSize);//ConvertBytesToProgressBarInt(TotalTransferProgress);
                int TotalDownloadPercentage = 0;

                try
                {
                    TotalDownloadPercentage	= CalculatePercentage(TotalTransferProgress,TotalFileSize);
                }
                catch(Exception Err)
                {
                    string peekError = Err.Message;
                }

                TransferDirection e = TransferDirection.Upload;
                if(args.TransferDirection == KCommon.Net.FTP.TransferDirection.Download)
                    e = TransferDirection.Download;

                TransferResult TR = new TransferResult();
                OysterTransferArguments ota = new OysterTransferArguments(args.LocalFileName,
                    args.RemoteFileName,(double)args.TotalBytes,TransferProgress,TotalFileSize,TotalTransferProgress,
                    e,args.TransferedPercentage,(int)TotalDownloadPercentage,TR);

                if(On_TransferProgress != null)
                    On_TransferProgress(this,ota);

                string sCurrent = ConvertByteToString(TransferProgress);
                string sTotal = ConvertByteToString(TotalSize);
            //				frmTS.pbTBar.Refresh();

                string sDirection = "Download";

                if(args.TransferDirection == KCommon.Net.FTP.TransferDirection.Upload)
                    sDirection = "Upload";
            //				Msg(sDirection + " progress: " + ((double)(TransferProgress / 1024 / 1024)).ToString() + " of " + ((double)(TotalSize / 1024 / 1024)).ToString());
                Msg(sDirection + " progress: " + sCurrent + " of " + sTotal);

                Application.DoEvents();
            }
            catch(Exception Err)
            {
                //MessageBox.Show(Err.Message,"File Transfer Progress");
                string p = Err.Message;
            }
        }
Esempio n. 37
0
 internal OysterTransferArguments(KCommon.Net.FTP.IFtpFileTransferArgs FFTArgs)
 {
     m_LocalFileName = FFTArgs.LocalFileName;
     m_RemoteFileName = FFTArgs.RemoteFileName;
     m_CurrentFile_TotalBytes = FFTArgs.TotalBytes;
     m_CurrentFile_BytesTransfered = FFTArgs.TotalBytesTransfered;
     m_AllFiles_TotalBytes = FFTArgs.TotalBytes;
     m_AllFiles_TotalBytesTransfered = FFTArgs.TotalBytesTransfered;
     m_TransferDirection = (TransferDirection)FFTArgs.TransferDirection;
     m_CurrentFileTransferPercentage = FFTArgs.TransferedPercentage;
     m_TotalDownloadTransferPercentage = FFTArgs.TransferedPercentage;
     if(null == FFTArgs.TransferResult)
         m_TransferResult = null;
     else
         m_TransferResult = (TransferResult)FFTArgs.TransferResult;
 }
Esempio n. 38
0
            internal OysterTransferArguments(string LocalFileName,
				string RemoteFileName, double CurrentFile_TotalBytes,double CurrentFile_BytesTransfered,double AllFiles_TotalBytes,
				double AllFiles_TotalBytesTransfered, TransferDirection TransferDirection,
				int CurrentFileTransferPercentage, int TotalDownloadTransferPercentage,
				TransferResult TransferResult)
            {
                m_LocalFileName = LocalFileName;
                m_RemoteFileName = RemoteFileName;
                m_CurrentFile_TotalBytes = CurrentFile_TotalBytes;
                m_CurrentFile_BytesTransfered = CurrentFile_BytesTransfered;
                m_AllFiles_TotalBytes = AllFiles_TotalBytes;
                m_AllFiles_TotalBytesTransfered = AllFiles_TotalBytesTransfered;
                m_TransferDirection = TransferDirection;
                m_CurrentFileTransferPercentage = CurrentFileTransferPercentage;
                m_TotalDownloadTransferPercentage = TotalDownloadTransferPercentage;
                m_TransferResult = TransferResult;
            }
        /// <summary>
        /// Attaches a groups a subscriptions to a different sesssion.
        /// </summary>
        public void TransferSubscriptions(
            OperationContext             context,
            UInt32Collection             subscriptionIds,
            out TransferResultCollection results,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            results = new TransferResultCollection();
            diagnosticInfos = new DiagnosticInfoCollection();

            for (int ii = 0; ii < subscriptionIds.Count; ii++)
            {
                TransferResult result = new TransferResult();

                // find subscription.
                Subscription subscription = null;

                lock (m_lock)
                {
                    if (!m_subscriptions.TryGetValue(subscriptionIds[ii], out subscription))
                    {
                        result.StatusCode = StatusCodes.BadSubscriptionIdInvalid;
                        continue;
                    }
                }

                result.StatusCode = StatusCodes.BadNotImplemented;
            }
        }
Esempio n. 40
0
 public OperationResult(TransferResult result, string targetPath = null)
 {
     Result = result;
     TargetPath = targetPath;
 }
Esempio n. 41
0
        private void FtpSession_EndGetFile(object sender, KCommon.Net.FTP.IFtpFileTransferArgs args)
        {
            #region Send Download_End_Event

                long TotalDownloadPercentage = 0;

                try
                {
                    //Only used during multiple file downloads/uploads
                    TotalDownloadPercentage	= CalculatePercentage(TotalTransferProgress,TotalFileSize);
                }
                catch(Exception Err)
                {

                    string peekError = Err.Message;
                }
            try
            {
                if(args.TransferResult != null)
                {
                    bTransferSuccess = args.TransferResult.IsSuccess;
                }
                else if(args.TransferedPercentage > 90)
                {
                    bTransferSuccess = true;
                }
                else
                {
                    bTransferSuccess = false;
                }
            }
            catch(Exception CErr)
            {
                string peekThisErr = CErr.Message;
            }
            try
            {

                TransferDirection e = TransferDirection.Upload;
                if(args.TransferDirection == KCommon.Net.FTP.TransferDirection.Download)
                    e = TransferDirection.Download;

                TransferResult TR = new TransferResult();
                OysterTransferArguments ota = new OysterTransferArguments(args.LocalFileName,
                    args.RemoteFileName,(double)args.TotalBytes,TransferProgress,TotalFileSize,TotalTransferProgress,
                    e,args.TransferedPercentage,(int)TotalDownloadPercentage,TR);
                if(On_Download_Complete != null)
                    On_Download_Complete(this,ota);
            }
            catch(Exception PostError)
            {
                string peekError = PostError.Message;
                OysterTransferArguments Eota = new OysterTransferArguments(args);
                if(On_Upload_Complete != null)
                    On_Upload_Complete(this,Eota);
            }

            #endregion
            Msg("Download complete.");
            DownloadingFile = false;
            TransferProgress = 0;
            m_ThreadTransferCompleteEvent.Set();
        }