public async Task <string> CashOut(Guid id, string coinAddress, string fromAddress, string toAddress, BigInteger amount, string sign)
        {
            await ThrowOnExistingId(id);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            var operation = new PendingOperation()
            {
                OperationId        = id.ToString(),
                Amount             = amount.ToString(),
                CoinAdapterAddress = coinAddress,
                FromAddress        = fromAddress,
                OperationType      = OperationTypes.Cashout,
                SignFrom           = sign,
                SignTo             = null,
                ToAddress          = toAddress,
                MainExchangeId     = id,
            };
            var opId = await CreateOperation(operation);

            var signResult = await GetAndCheckSign(id, coinAddress, fromAddress, toAddress, amount, sign);

            sign               = signResult.Sign;
            amount             = signResult.Amount;
            operation.SignFrom = sign;
            operation.Amount   = amount.ToString();

            await StartProcessing(operation);

            return(opId);
        }
        public async Task <string> CreateOperation(IPendingOperation operation)
        {
            var op = new PendingOperation()
            {
                OperationId        = operation.OperationId,
                Amount             = operation.Amount,
                CoinAdapterAddress = operation.CoinAdapterAddress,
                FromAddress        = operation.FromAddress,
                OperationType      = operation.OperationType,
                SignFrom           = operation.SignFrom,
                SignTo             = operation.SignTo,
                ToAddress          = operation.ToAddress,
                Change             = operation.Change
            };

            var match = new OperationToHashMatch()
            {
                OperationId     = op.OperationId,
                TransactionHash = ""
            };

            await _operationToHashMatchRepository.InsertOrReplaceAsync(match);

            await _pendingOperationRepository.InsertOrReplace(op);

            return(op.OperationId);
        }
Exemple #3
0
        public async Task MonitoringOperationJobUnitTest_SkipIfNoBalance()
        {
            string operationId = Guid.NewGuid().ToString();
            OperationHashMatchMessage message = new OperationHashMatchMessage()
            {
                OperationId     = operationId,
                PutDateTime     = DateTime.UtcNow,
                TransactionHash = null
            };

            #region Arrange Mocks
            IPendingOperation pendingOperation = new PendingOperation()
            {
                Amount             = "1000000000000000000",
                FromAddress        = "fromAddress",
                OperationId        = operationId,
                OperationType      = OperationTypes.Transfer,
                ToAddress          = "toAddress",
                CoinAdapterAddress = "coinAdapter",
            };

            _pendingOperationService.Setup(x => x.GetOperationAsync(pendingOperation.OperationId)).Returns(Task.FromResult(pendingOperation));
            _transferContractService.Setup(x => x.GetBalanceOnAdapter(pendingOperation.CoinAdapterAddress, pendingOperation.FromAddress, true))
            .Returns(Task.FromResult(new BigInteger(0)));
            _coinEventService.Setup(x => x.PublishEvent(It.IsAny <ICoinEvent>(), It.IsAny <bool>())).Returns(Task.FromResult(0)).Verifiable();

            #endregion

            MonitoringOperationJob job = GetJob();
            await job.Execute(message, new Lykke.JobTriggers.Triggers.Bindings.QueueTriggeringContext(DateTimeOffset.UtcNow));

            _coinEventService.Verify(x => x.PublishEvent(It.IsAny <ICoinEvent>(), It.IsAny <bool>()), Times.Never);
        }
        Task <Message> SendMesageToActorAsync(ActorTargetHeader actorTargetHeader, IOperationContext operation)
        {
            var  msg       = operation.Message;
            Guid requestId = Guid.NewGuid();

            var continuation = new PendingOperation(requestId);

            if (!PendingOperationsByRequestId.TryAdd(requestId, continuation))
            {
                throw new Exception("RequestId has collided!!!");
            }

            var expiration = Task.Delay(TimeSpan.FromSeconds(_config.SendTimeoutSec), continuation.Expiration.Token);

            expiration.ContinueWith(_ =>
            {
                PendingOperation dummy;
                if (PendingOperationsByRequestId.TryRemove(continuation.RequestId, out dummy))
                {
                    continuation.TCS.SetException(
                        new TimeoutException($"SendMesageToActorAsync<{requestId}, {msg}> has Expired after {_config.SendTimeoutSec} s"));
                }
            });

            msg.AttachHeader(new ActorDirectReplyHeader(new ActorRef(_serverNode.Address, actorTargetHeader.ActorKey)));

            SendToEventHub(actorTargetHeader, msg, requestId, operation);

            return(continuation.TCS.Task);
        }
Exemple #5
0
        public IEntryState <TId, TData> Store(IEntryState <TId, TData> entry, TData data, long transactionId)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(nameof(entry));
            }

            if (!entry.PendingTransactions.Contains(transactionId))
            {
                throw new InvalidOperationException();
            }

            if (entry.PendingOperations.Any(p => p.TransactionId == transactionId))
            {
                throw new InvalidOperationException("A single transaction must modify an entry with a single operation only.");
            }

            var lastWriteTime     = _dateTimeProvider.GetCurrentTime();
            var pendingOperation  = new PendingOperation(transactionId, originalData: ToSnapshot(entry), lastWriteTime);
            var pendingOperations = entry.PendingOperations.Add(pendingOperation);

            return(new Entry(entry.Id,
                             data,
                             entry.DataVersion + 1,
                             entry.Version + 1,
                             entry.CreatingTransaction,
                             pendingOperations,
                             entry.PendingTransactions,
                             entry.CreationTime,
                             lastWriteTime));
        }
Exemple #6
0
 private void sendPendingOperations()
 {
     while (pendingOperations.Count > 0)
     {
         PendingOperation pendingOperation = pendingOperations.Dequeue();
         sendOperation(pendingOperation.Operation, pendingOperation.Parameters);
     }
 }
Exemple #7
0
 private bool setupEncryption(PendingOperation pendingOperation)
 {
     if (generatingKeyPair || requestingEncryptionKey)
     {
         pendingOperations.Enqueue(pendingOperation);
         return(false);
     }
     if (!haveKeyPair())
     {
         pendingOperations.Enqueue(pendingOperation);
         generatingKeyPair = true;
         clubPenguinClient.GenerateKeyPair(delegate(RSAParameters rsaParams)
         {
             generatingKeyPair = false;
             clubPenguinClient.CPKeyValueDatabase.SetRsaParameters(rsaParams);
             sendPendingOperations();
         }, delegate
         {
             generatingKeyPair = false;
             failPendingOperations();
         });
         return(false);
     }
     if (!haveEncryptionKey())
     {
         pendingOperations.Enqueue(pendingOperation);
         requestingEncryptionKey = true;
         RSAParameters rsaParameters     = clubPenguinClient.CPKeyValueDatabase.GetRsaParameters().Value;
         string        publicKeyExponent = Convert.ToBase64String(rsaParameters.Exponent);
         string        publicKeyModulus  = Convert.ToBase64String(rsaParameters.Modulus);
         APICall <GetEncryptionKeyOperation> encryptionKey = clubPenguinClient.EncryptionApi.GetEncryptionKey(publicKeyExponent, publicKeyModulus);
         encryptionKey.OnResponse += delegate(GetEncryptionKeyOperation op, HttpResponse resp)
         {
             requestingEncryptionKey = false;
             try
             {
                 string keyId                  = op.ResponseBody.keyId;
                 byte[] ciphertext             = Convert.FromBase64String(op.ResponseBody.encryptedSymmetricKey);
                 byte[] symmetricEncryptionKey = RsaEncryptor.Decrypt(ciphertext, rsaParameters);
                 updateEncryptionKey(keyId, symmetricEncryptionKey);
                 sendPendingOperations();
             }
             catch (Exception ex)
             {
                 Log.LogErrorFormatted(this, "Failed to decrypt symmetric key from server. Operations requiring encryption will fail. Exception: {0}", ex);
                 failPendingOperations();
             }
         };
         encryptionKey.OnError += delegate
         {
             requestingEncryptionKey = false;
             failPendingOperations();
         };
         encryptionKey.Execute();
         return(false);
     }
     return(true);
 }
Exemple #8
0
        /// <summary>
        /// Builds the list of operations to execute
        /// </summary>
        /// <param type="parameters" name="parameters">The parameters to build the chain of the builder.</param>
        /// <returns>This <see cref="FhirPathPatchBuilder"/>.</returns>
        public FhirPathPatchBuilder Build(Parameters parameters)
        {
            foreach (var param in parameters.Parameter)
            {
                operations.Add(PendingOperation.FromParameterComponent(param));
            }

            return(this);
        }
Exemple #9
0
        /// <summary>
        /// Creates a new node or updates an existing or delete a node.
        /// </summary>
        /// <param name="kind">Kind of operation.</param>
        /// <param name="key">Key of the node.</param>
        /// <param name="value">Value of the node.</param>
        /// <param name="onCommit">Action performed when the replication is completed.</param>
        /// <param name="onFailure">Action performed when the replication is failed.</param>
        internal void Write(NodeOperation.OperationKind kind, string key, ArraySegment <byte> value, Action onCommit, Action onFailure)
        {
            var nodeOp    = new NodeOperation(kind, this.lastSequenceNumber, key, value);
            var pendingOp = new PendingOperation {
                Operation = nodeOp, OnCommit = onCommit, OnFailure = onFailure,
            };

            this.pendingOperations.Add(pendingOp);
        }
Exemple #10
0
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="filename">文件名</param>
        public void OpenFile(string filename)
        {
            openningFile = filename;
            //Debug.WriteLine("已调用BassEngine.OpenFile()");
            Stop();
            pendingOperation = PendingOperation.None;

            var flag   = (Un4seen.Bass.BASSFlag)Enum.Parse(typeof(Un4seen.Bass.BASSFlag), ConfigurationManager.AppSettings["Bass.OpenFileConfig"]);
            int handle = Un4seen.Bass.Bass.BASS_StreamCreateFile(filename, 0, 0, flag);

            if (handle != 0)
            {
                ActiveStreamHandle = handle;
                ChannelLength      = TimeSpan.FromSeconds(Un4seen.Bass.Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Un4seen.Bass.Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0)));
                Un4seen.Bass.BASS_CHANNELINFO info = new Un4seen.Bass.BASS_CHANNELINFO();
                Un4seen.Bass.Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                sampleFrequency = info.freq;

                int syncHandle = Un4seen.Bass.Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                                       Un4seen.Bass.BASSSync.BASS_SYNC_END,
                                                                       0,
                                                                       endTrackSyncProc,
                                                                       IntPtr.Zero);

                if (syncHandle == 0)
                {
                    throw new ArgumentException("Error establishing End Sync on file stream.", "filename");
                }

                CanPlay = true;
                RaiseOpenSucceededEvent();

                switch (pendingOperation)
                {
                case PendingOperation.None:
                    break;

                case PendingOperation.Play:
                    Play();
                    break;

                case PendingOperation.Pause:
                    Pause();
                    break;

                default:
                    break;
                }
            }
            else
            {
                RaiseOpenFailedEvent();
            }
        }
 void OnPropertyChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs)
 {
     Delighting.ProcessStep fromStep;
     if (autoCompute &&
         s_PropertiesTriggeringProcess.TryGetValue(propertyChangedEventArgs.PropertyName, out fromStep) &&
         m_Service.ValidateInputs() == Delighting.ErrorCode.NoErrors)
     {
         SetProcessStep(fromStep);
         pendingOperation |= PendingOperation.Process;
     }
 }
Exemple #12
0
        private void failPendingOperations()
        {
            string         text       = "Failed to resolve recoverable error conditions. Pending operations will not be sent.";
            HttpStatusCode statusCode = HttpStatusCode.PreconditionFailed;

            while (pendingOperations.Count > 0)
            {
                PendingOperation pendingOperation = pendingOperations.Dequeue();
                HttpResponse     httpResponse     = new HttpResponse(pendingOperation.Operation.Request, 0f, new Dictionary <string, string>(), text, text, null, statusCode);
                pendingOperation.Operation.InvokeUserAction("on-complete", pendingOperation.Operation, httpResponse);
            }
        }
Exemple #13
0
        /// <summary>
        /// Asynchronously submits a <see cref="SharedMemMessage"/> request message to the server
        /// and waits for and returns the response <see cref="SharedMemMessage"/>.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="timeout">The optional timeout to override the <see cref="Timeout"/> property.
        /// </param>
        /// <returns>The response <see cref="SharedMemMessage"/>.</returns>
        public Task <SharedMemMessage> CallAsync(SharedMemMessage request, TimeSpan?timeout = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            if (request.InternalRequestId != Guid.Empty)
            {
                throw new InvalidOperationException("Cannot reuse a [SharedMemMessage] request instance previously submitted for a call operation.");
            }

            request.InternalRequestId   = Guid.NewGuid();
            request.InternalClientInbox = this.ClientName;

            if (!timeout.HasValue)
            {
                timeout = this.Timeout;
            }

            var operation = new PendingOperation(request, new TaskCompletionSource <SharedMemMessage>(), stopwatch.Elapsed + timeout.Value);

            lock (syncLock)
            {
                pendingOperations.Add(request.InternalRequestId, operation);
            }

            try
            {
                using (var output = new EnhancedMemoryStream(request.SerializedCapacityHint))
                {
                    output.WriteInt32(request.TypeCode);
                    request.InternalWriteTo(output);
                    request.WriteTo(output);

                    // This call is synchronous but should execute very quickly (microseconds).

                    outbox.Send(ServerName, output.ToArray());
                }
            }
            catch (Exception e)
            {
                lock (syncLock)
                {
                    pendingOperations.Remove(operation.RequestMessage.InternalRequestId);
                }

                operation.Tcs.TrySetException(e);
            }

            return(operation.Tcs.Task);
        }
Exemple #14
0
 private void sensorSetupLine_SensorSet(int obj)
 {
     if (_pendingOperation == PendingOperation.None)
     {
         if (DialogResult.OK == MessageBox.Show("Make sure only one unassigned sensor is connected.", "Verify", MessageBoxButtons.OKCancel))
         {
             _device.SetSensorId(-1, obj);
         }
         _pendingOperation   = PendingOperation.Add;
         _pendingSensorIndex = obj;
         addRemWorker.RunWorkerAsync();
     }
 }
Exemple #15
0
 private void sensorSetupLine_SensorRemove(int obj)
 {
     if (_pendingOperation == PendingOperation.None)
     {
         if (DialogResult.Yes == MessageBox.Show("Are you sure you wish to remove this sensor?", "Confirm", MessageBoxButtons.YesNoCancel))
         {
             _device.SetSensorId(obj, -1);
         }
         _pendingOperation   = PendingOperation.Rem;
         _pendingSensorIndex = obj;
         addRemWorker.RunWorkerAsync();
     }
 }
Exemple #16
0
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="filename">文件名</param>
        public void OpenFile(string filename)
        {
            openningFile = filename;
            Stop();
            pendingOperation = PendingOperation.None;
            int handle = CreateLocalFileStream(filename);

            handle = SetEQ(handle);
            if (handle != 0)
            {
                ActiveStreamHandle = handle;
                ChannelLength      = TimeSpan.FromSeconds(Un4seen.Bass.Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Un4seen.Bass.Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0)));
                Un4seen.Bass.BASS_CHANNELINFO info = new Un4seen.Bass.BASS_CHANNELINFO();
                Un4seen.Bass.Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                sampleFrequency = info.freq;

                int syncHandle = Un4seen.Bass.Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                                       Un4seen.Bass.BASSSync.BASS_SYNC_END, 0, endTrackSyncProc, IntPtr.Zero);

                if (syncHandle == 0)
                {
                    throw new ArgumentException("Error establishing End Sync on file stream.", "path");
                }

                CanPlay = true;
                RaiseOpenSucceededEvent();

                switch (pendingOperation)
                {
                case PendingOperation.None:
                    break;

                case PendingOperation.Play:
                    Play();
                    break;

                case PendingOperation.Pause:
                    Pause();
                    break;

                default:
                    break;
                }
            }
            else
            {
                RaiseOpenFailedEvent();
            }
        }
Exemple #17
0
 private bool setupAuthentication(PendingOperation pendingOperation)
 {
     if (refreshingAccessToken)
     {
         pendingOperations.Enqueue(pendingOperation);
         return(false);
     }
     if (!haveAccessToken())
     {
         pendingOperations.Enqueue(pendingOperation);
         refreshingAccessToken = true;
         return(false);
     }
     return(true);
 }
Exemple #18
0
 /// <summary>
 /// 暂停当前音频
 /// </summary>
 public void Pause()
 {
     //Debug.WriteLine("已调用BassEngine.Pause()");
     if (IsPlaying && CanPause)
     {
         Un4seen.Bass.Bass.BASS_ChannelPause(ActiveStreamHandle);
         IsPlaying        = false;
         CanPlay          = true;
         CanPause         = false;
         pendingOperation = PendingOperation.None;
     }
     else
     {
         pendingOperation = PendingOperation.Pause;
     }
 }
        void Update()
        {
            if (m_LoadAssetFolderOperation != null && !m_LoadAssetFolderOperation.MoveNext())
            {
                m_LoadAssetFolderOperation = null;
            }

            if (m_ProcessOperation != null && !m_ProcessOperation.MoveNext())
            {
                if (m_ProcessOperation.error != null)
                {
                    m_PendingOperations &= ~PendingOperation.RenderPreview;

                    var errors = GetErrorMessagesFrom(((Delighting.ProcessException)m_ProcessOperation.error).errorCode);
                    for (int i = 0; i < errors.Count; i++)
                    {
                        Debug.LogError(errors[i]);
                    }
                }
                else
                {
                    if (m_FitToPreviewAfterProcess)
                    {
                        m_PendingOperations       |= PendingOperation.FitPreviewToWindow;
                        m_FitToPreviewAfterProcess = false;
                    }
                    m_PendingOperations |= PendingOperation.RenderPreview;
                }
                m_ProcessOperation = null;
                // Trigger the process operation with current process step
                SetProcessStep(m_FromProcessStep);
            }

            if ((m_PendingOperations & PendingOperation.RenderPreview) != 0)
            {
                m_PendingOperations &= ~PendingOperation.RenderPreview;
                if (m_Service.ValidateInputs() == Delighting.ErrorCode.NoErrors)
                {
                    m_Service.RenderPreview();
                }
            }
            if ((m_PendingOperations & PendingOperation.FitPreviewToWindow) != 0)
            {
                m_PendingOperations &= ~PendingOperation.FitPreviewToWindow;
                fitCanvasToWindow    = true;
            }
        }
        public async Task <string> TransferWithChange(Guid id, string coinAddress, string fromAddress, string toAddress,
                                                      BigInteger amount, string signFrom, BigInteger change, string signTo)
        {
            if (amount <= change)
            {
                throw new ClientSideException(ExceptionType.WrongParams, "Amount can't be less or equal than change");
            }

            await ThrowOnExistingId(id);

            var operation = new PendingOperation()
            {
                OperationId        = id.ToString(),
                Change             = change.ToString(),
                Amount             = amount.ToString(),
                CoinAdapterAddress = coinAddress,
                FromAddress        = fromAddress,
                OperationType      = OperationTypes.TransferWithChange,
                SignFrom           = signFrom,
                SignTo             = signTo,
                ToAddress          = toAddress,
                MainExchangeId     = id,
            };
            var opId = await CreateOperation(operation);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            var signFromResult = await GetAndCheckSign(id, coinAddress, fromAddress, toAddress, amount, signFrom);

            signFrom = signFromResult.Sign;
            amount   = signFromResult.Amount;

            var signToResult = await GetAndCheckSign(id, coinAddress, toAddress, fromAddress, change, signTo);

            signTo = signToResult.Sign;
            change = signToResult.Amount;

            operation.SignFrom = signFrom;
            operation.SignTo   = signTo;
            operation.Change   = change.ToString();
            operation.Amount   = amount.ToString();

            await StartProcessing(operation);

            return(opId);
        }
Exemple #21
0
 /// <summary>
 /// 播放当前音频
 /// </summary>
 public void Play()
 {
     //Debug.WriteLine("已调用BassEngine.Play()");
     if (CanPlay)
     {
         PlayCurrentStream();
         IsPlaying        = true;
         CanPause         = true;
         CanPlay          = false;
         CanStop          = true;
         pendingOperation = PendingOperation.None;
     }
     else
     {
         pendingOperation = PendingOperation.Play;
     }
 }
Exemple #22
0
        public IEntryState <TId, TData> Create(TId id, TData data, long transactionId)
        {
            var creationTime     = _dateTimeProvider.GetCurrentTime();
            var pendingOperation = new PendingOperation(transactionId,
                                                        originalData: new EntrySnapshot(id, null, 0, null),
                                                        operationTime: creationTime);
            var pendingOperations   = _noPendingOperations.Add(pendingOperation);
            var pendingTransactions = _noPendingTransactions.Add(transactionId);

            return(new Entry(id,
                             data,
                             dataVersion: 1,
                             version: 1,
                             creationTransaction: transactionId,
                             pendingOperations,
                             pendingTransactions,
                             creationTime,
                             lastWriteTime:
                             creationTime));
        }
        public void Update()
        {
            for (int i = m_pendingOperations.Count - 1; i >= 0; i--)
            {
                PendingOperation pendingOperation = m_pendingOperations[i];

                // Check if a response has arrived
                if (pendingOperation.WWW.isDone)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(pendingOperation.WWW.error))
                        {
                            // Run the completion handler if there was no error
                            pendingOperation.OnCompletion(pendingOperation.WWW.text);
                        }
                        else
                        {
                            // Otherwise run the exception handler
                            pendingOperation.OnException(new WWWRequestError(pendingOperation.WWW.error));
                        }
                    }
                    catch (Exception ex)
                    {
                        pendingOperation.OnException(ex);
                    }

                    m_pendingOperations[i].WWW.Dispose();
                    m_pendingOperations.RemoveAt(i);
                }
                else if (DateTime.Now - pendingOperation.StartTime > pendingOperation.Timeout)
                {
                    // Handle operation time out
                    pendingOperation.OnException(new TimeoutException(pendingOperation.WWW.url));

                    m_pendingOperations[i].WWW.Dispose();
                    m_pendingOperations.RemoveAt(i);
                }
            }
        }
Exemple #24
0
        /// <summary>
        /// 停止当前音频,并释放资源
        /// </summary>
        public void Stop()
        {
            //Debug.WriteLine("已调用BassEngine.Stop()");

            if (canStop)
            {
                ChannelPosition = TimeSpan.Zero;
                if (ActiveStreamHandle != 0)
                {
                    Un4seen.Bass.Bass.BASS_ChannelStop(ActiveStreamHandle);
                    Un4seen.Bass.Bass.BASS_ChannelSetPosition(ActiveStreamHandle, ChannelPosition.TotalSeconds);
                    //Debug.WriteLine("已调用BASS_ChannelStop()");
                }
                IsPlaying = false;
                CanStop   = false;
                CanPlay   = false;
                CanPause  = false;
            }

            FreeCurrentStream();
            pendingOperation = PendingOperation.None;
        }
        /// <summary>
        /// Make a GET request
        /// </summary>
        /// <typeparam name="T">The response type expected</typeparam>
        /// <param name="endpoint">The URL to make the GET request to</param>
        /// <param name="parameters">Any additional parameters to add to the url that receives the GET request.</param>
        public Future <T> Get <T>(Uri endpoint, object parameters) where T : class
        {
            Future <T> future = new Future <T>();

            string finalEndpoint = parameters != null?BuildUrlString(endpoint, parameters) : endpoint.ToString();

            WWW www = new WWW(finalEndpoint);

            PendingOperation operation = new PendingOperation(
                /* WWW */
                www,
                /* Completion handler */
                response => RequestCompletionHandler(future, finalEndpoint, response),
                /* Exception handler */
                exception => future.SetException(exception),
                /* Timeout */
                TimeSpan.FromMilliseconds(m_operationTimeoutMilliseconds));

            m_pendingOperations.Add(operation);

            return(future);
        }
Exemple #26
0
        private void addRemWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ISensor sensor = _device.GetSensor(_pendingSensorIndex);

            MessageBoxIcon resultIcon;
            string         resultTitle;
            string         resultMessage            = "Operation";
            bool           sensorIsDesiredToBeFound = true;

            if (_pendingOperation == PendingOperation.Add)
            {
                resultMessage = "Sensor assignment";
            }
            else if (_pendingOperation == PendingOperation.Rem)
            {
                resultMessage            = "Sensor removal";
                sensorIsDesiredToBeFound = false;
            }

            Thread.Sleep(500);             // wait for the sensor to be active

            var sensorFound = null != sensor && sensor.IsValid;

            if (sensorFound == sensorIsDesiredToBeFound)
            {
                resultTitle    = "Success";
                resultMessage += " successful";
                resultIcon     = MessageBoxIcon.Information;
            }
            else
            {
                resultTitle    = "Failure";
                resultMessage += " failed";
                resultIcon     = MessageBoxIcon.Error;
            }

            _pendingOperation = PendingOperation.None;
            MessageBox.Show(this, resultTitle, resultMessage, MessageBoxButtons.OK, resultIcon);
        }
        public async Task <string> TransferWithNoChecks(Guid id, string coinAddress, string fromAddress,
                                                        string toAddress, BigInteger amount, string sign)
        {
            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            var operation = new PendingOperation()
            {
                OperationId        = id.ToString(),
                Amount             = amount.ToString(),
                CoinAdapterAddress = coinAddress,
                FromAddress        = fromAddress,
                OperationType      = OperationTypes.Transfer,
                SignFrom           = sign,
                SignTo             = null,
                ToAddress          = toAddress,
                MainExchangeId     = id,
            };
            var opId = await CreateOperation(operation);

            await StartProcessing(operation);

            return(opId);
        }
Exemple #28
0
 /// <summary>
 /// 播放当前音频
 /// </summary>
 public void Play()
 {
     //Debug.WriteLine("已调用BassEngine.Play()");
     if (CanPlay)
     {
         PlayCurrentStream();
         IsPlaying = true;
         CanPause = true;
         CanPlay = false;
         CanStop = true;
         pendingOperation = PendingOperation.None;
     }
     else
     {
         pendingOperation = PendingOperation.Play;
     }
 }
Exemple #29
0
 /// <summary>
 /// 暂停当前音频
 /// </summary>
 public void Pause()
 {
     //Debug.WriteLine("已调用BassEngine.Pause()");
     if (IsPlaying && CanPause)
     {
         Un4seen.Bass.Bass.BASS_ChannelPause(ActiveStreamHandle);
         IsPlaying = false;
         CanPlay = true;
         CanPause = false;
         pendingOperation = PendingOperation.None;
     }
     else
     {
         pendingOperation = PendingOperation.Pause;
     }
 }
Exemple #30
0
        /// <summary>
        /// 打开网络地址
        /// </summary>
        /// <param name="url">URL地址</param>
        public void OpenUrlAsync(string url)
        {
            openningFile = url;
            //Debug.WriteLine("已调用BassEngine.OpenUrlAsync()");

            Stop();
            pendingOperation = PendingOperation.None;

            onlineFileWorker = new Thread(new ThreadStart(() =>
                {
                    int handle = Un4seen.Bass.Bass.BASS_StreamCreateURL(url, 0, Un4seen.Bass.BASSFlag.BASS_DEFAULT, null, IntPtr.Zero);

                    Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            if (handle != 0)
                            {
                                if (openningFile == url)		//该文件为正在打开的文件
                                {
                                    ActiveStreamHandle = handle;
                                    ChannelLength = TimeSpan.FromSeconds(Un4seen.Bass.Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Un4seen.Bass.Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0)));
                                    Un4seen.Bass.BASS_CHANNELINFO info = new Un4seen.Bass.BASS_CHANNELINFO();
                                    Un4seen.Bass.Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                                    sampleFrequency = info.freq;

                                    int syncHandle = Un4seen.Bass.Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                         Un4seen.Bass.BASSSync.BASS_SYNC_END,
                                         0,
                                         endTrackSyncProc,
                                         IntPtr.Zero);

                                    if (syncHandle == 0)
                                        throw new ArgumentException("Error establishing End Sync on file stream.", "path");

                                    CanPlay = true;
                                    RaiseOpenSucceededEvent();

                                    switch (pendingOperation)
                                    {
                                        case PendingOperation.None:
                                            break;
                                        case PendingOperation.Play:
                                            Play();
                                            break;
                                        case PendingOperation.Pause:
                                            Pause();
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                else		//该文件不是正在打开的文件(即文件已过时,可能的原因是UI线程较忙,调用onlineFileWorker.Abort()时BeginInvoke的内容已提交,但还未执行)
                                {
                                    if (!Un4seen.Bass.Bass.BASS_StreamFree(handle))
                                    {
                                        Debug.WriteLine("BASS_StreamFree失败:" + Un4seen.Bass.Bass.BASS_ErrorGetCode());
                                    }
                                    //Debug.WriteLine("已调用BASS_StreamFree()");
                                }
                            }
                            else
                            {
                                Debug.WriteLine(Un4seen.Bass.Bass.BASS_ErrorGetCode());
                                RaiseOpenFailedEvent();
                            }
                        }));
                    onlineFileWorker = null;
                }));
            onlineFileWorker.IsBackground = true;
            onlineFileWorker.Start();
        }
Exemple #31
0
        /// <summary>
        /// 打开文件
        /// </summary>
        /// <param name="filename">文件名</param>
        public void OpenFile(string filename)
        {
            openningFile = filename;
            //Debug.WriteLine("已调用BassEngine.OpenFile()");
            Stop();
            pendingOperation = PendingOperation.None;

            int handle = Un4seen.Bass.Bass.BASS_StreamCreateFile(filename, 0, 0, Un4seen.Bass.BASSFlag.BASS_DEFAULT);

            if (handle != 0)
            {
                ActiveStreamHandle = handle;
                ChannelLength = TimeSpan.FromSeconds(Un4seen.Bass.Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Un4seen.Bass.Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0)));
                Un4seen.Bass.BASS_CHANNELINFO info = new Un4seen.Bass.BASS_CHANNELINFO();
                Un4seen.Bass.Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                sampleFrequency = info.freq;

                int syncHandle = Un4seen.Bass.Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                     Un4seen.Bass.BASSSync.BASS_SYNC_END,
                     0,
                     endTrackSyncProc,
                     IntPtr.Zero);

                if (syncHandle == 0)
                    throw new ArgumentException("Error establishing End Sync on file stream.", "path");

                CanPlay = true;
                RaiseOpenSucceededEvent();

                switch (pendingOperation)
                {
                    case PendingOperation.None:
                        break;
                    case PendingOperation.Play:
                        Play();
                        break;
                    case PendingOperation.Pause:
                        Pause();
                        break;
                    default:
                        break;
                }
            }
            else
            {
                RaiseOpenFailedEvent();
            }
        }
Exemple #32
0
        /// <summary>
        /// 打开网络地址
        /// </summary>
        /// <param name="url">URL地址</param>
        public void OpenUrlAsync(string url)
        {
            openningFile = url;
            //Debug.WriteLine("已调用BassEngine.OpenUrlAsync()");

            Stop();
            pendingOperation = PendingOperation.None;

            onlineFileWorker = new Thread(new ThreadStart(() =>
            {
                int handle = Un4seen.Bass.Bass.BASS_StreamCreateURL(url, 0, Un4seen.Bass.BASSFlag.BASS_DEFAULT, null, IntPtr.Zero);

                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (handle != 0)
                    {
                        if (openningFile == url)                                                        //该文件为正在打开的文件
                        {
                            ActiveStreamHandle = handle;
                            ChannelLength      = TimeSpan.FromSeconds(Un4seen.Bass.Bass.BASS_ChannelBytes2Seconds(ActiveStreamHandle, Un4seen.Bass.Bass.BASS_ChannelGetLength(ActiveStreamHandle, 0)));
                            Un4seen.Bass.BASS_CHANNELINFO info = new Un4seen.Bass.BASS_CHANNELINFO();
                            Un4seen.Bass.Bass.BASS_ChannelGetInfo(ActiveStreamHandle, info);
                            sampleFrequency = info.freq;

                            int syncHandle = Un4seen.Bass.Bass.BASS_ChannelSetSync(ActiveStreamHandle,
                                                                                   Un4seen.Bass.BASSSync.BASS_SYNC_END,
                                                                                   0,
                                                                                   endTrackSyncProc,
                                                                                   IntPtr.Zero);

                            if (syncHandle == 0)
                            {
                                throw new ArgumentException("Error establishing End Sync on file stream.", "path");
                            }

                            CanPlay = true;
                            RaiseOpenSucceededEvent();

                            switch (pendingOperation)
                            {
                            case PendingOperation.None:
                                break;

                            case PendingOperation.Play:
                                Play();
                                break;

                            case PendingOperation.Pause:
                                Pause();
                                break;

                            default:
                                break;
                            }
                        }
                        else                                                    //该文件不是正在打开的文件(即文件已过时,可能的原因是UI线程较忙,调用onlineFileWorker.Abort()时BeginInvoke的内容已提交,但还未执行)
                        {
                            if (!Un4seen.Bass.Bass.BASS_StreamFree(handle))
                            {
                                Debug.WriteLine("BASS_StreamFree失败:" + Un4seen.Bass.Bass.BASS_ErrorGetCode());
                            }
                            //Debug.WriteLine("已调用BASS_StreamFree()");
                        }
                    }
                    else
                    {
                        Debug.WriteLine(Un4seen.Bass.Bass.BASS_ErrorGetCode());
                        RaiseOpenFailedEvent();
                    }
                }));
                onlineFileWorker = null;
            }));
            onlineFileWorker.IsBackground = true;
            onlineFileWorker.Start();
        }
Exemple #33
0
        private void addRemWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ISensor sensor = _device.GetSensor(_pendingSensorIndex);

            MessageBoxIcon resultIcon;
            string resultTitle;
            string resultMessage = "Operation";
            bool sensorIsDesiredToBeFound = true;

            if (_pendingOperation == PendingOperation.Add) {
                resultMessage = "Sensor assignment";
            }
            else if (_pendingOperation == PendingOperation.Rem) {
                resultMessage = "Sensor removal";
                sensorIsDesiredToBeFound = false;
            }

            Thread.Sleep(500); // wait for the sensor to be active

            var sensorFound = null != sensor && sensor.IsValid;

            if (sensorFound == sensorIsDesiredToBeFound) {
                resultTitle = "Success";
                resultMessage += " successful";
                resultIcon = MessageBoxIcon.Information;
            }
            else {
                resultTitle = "Failure";
                resultMessage += " failed";
                resultIcon = MessageBoxIcon.Error;
            }

            _pendingOperation = PendingOperation.None;
            MessageBox.Show(this, resultTitle, resultMessage, MessageBoxButtons.OK, resultIcon);
        }
		/// <summary>
		/// Closes/Hides the progress window.
		/// </summary>
		private void CloseProgressWindow() {
			Gtk.Application.Invoke (delegate {
				m_windowProgressInfo.Hide ();
				m_pendingOperation = PendingOperation.NOTHING;
			});
		}
 public void CmdRenderPreview()
 {
     pendingOperation |= PendingOperation.RenderPreview;
 }
Exemple #36
0
 private void sensorSetupLine_SensorSet(int obj)
 {
     if (_pendingOperation == PendingOperation.None) {
         if (DialogResult.OK == MessageBox.Show("Make sure only one unassigned sensor is connected.", "Verify", MessageBoxButtons.OKCancel)) {
             _device.SetSensorId(-1, obj);
         }
         _pendingOperation = PendingOperation.Add;
         _pendingSensorIndex = obj;
         addRemWorker.RunWorkerAsync();
     }
 }
		private void PreviewButtonClicked() {
			if(this.m_pendingOperation != PendingOperation.NOTHING)
				return;
			this.m_pendingOperation = PendingOperation.GENERATE_PREVIEW;
			m_windowProgressInfo.Show();

			// read settings while handling errors
			Settings settings = new Settings ();
			try {
				// read all required information to class/struct, so that off-gtk-thread computation is possible
				settings = new Settings ();
				ReadGui (settings);

				// quickly decide whether these inputs can be used for a run
				IsSettingsValid (settings);

			} catch(Exception e) {
				SetErrorMessage (e.Message);
				CloseProgressWindow ();
				return;
			}

			m_previewSettings = settings;


			Thread compuationThread = new Thread(() => ComputationThreadSafe(settings));
			compuationThread.Start();

		}
		/// <summary>
		/// Opens the progress window and sets the current pending operation.
		/// </summary>
		/// <returns><c>true</c>, if progress window was opened, <c>false</c>, if there already is an operation pending.</returns>
		/// <param name="thisOperation">This operation.</param>
		private bool OpenProgressWindow(PendingOperation thisOperation) {
			// do not start another operation when there is already one
			if (m_pendingOperation != PendingOperation.NOTHING)
				return false;


			m_pendingOperation = thisOperation;

			m_windowProgressInfo.Show ();
			return true;
		}
Exemple #39
0
        /// <summary>
        /// 停止当前音频,并释放资源
        /// </summary>
        public void Stop()
        {
            //Debug.WriteLine("已调用BassEngine.Stop()");

            if (canStop)
            {
                ChannelPosition = TimeSpan.Zero;
                if (ActiveStreamHandle != 0)
                {
                    Un4seen.Bass.Bass.BASS_ChannelStop(ActiveStreamHandle);
                    Un4seen.Bass.Bass.BASS_ChannelSetPosition(ActiveStreamHandle, ChannelPosition.TotalSeconds);
                    //Debug.WriteLine("已调用BASS_ChannelStop()");
                }
                IsPlaying = false;
                CanStop = false;
                CanPlay = false;
                CanPause = false;
            }

            FreeCurrentStream();
            pendingOperation = PendingOperation.None;
        }
Exemple #40
0
 private void sensorSetupLine_SensorRemove(int obj)
 {
     if (_pendingOperation == PendingOperation.None) {
         if (DialogResult.Yes == MessageBox.Show("Are you sure you wish to remove this sensor?", "Confirm", MessageBoxButtons.YesNoCancel)) {
             _device.SetSensorId(obj, -1);
         }
         _pendingOperation = PendingOperation.Rem;
         _pendingSensorIndex = obj;
         addRemWorker.RunWorkerAsync();
     }
 }
Exemple #41
0
 /// <summary>
 /// Add operation to pending queue
 /// </summary>
 /// <param name="op">The operation to execute</param>
 static void AddOperation(PendingOperation op)
 {
     lock (State.GlobalSync)
     {
         pending.Add(op);
         RefreshFromIrc();
     }
 }
        void UpdatePendingOperations()
        {
            m_UpdateRequested = false;
            if ((m_PendingOperations & PendingOperation.LoadInputFolder) != 0)
            {
                m_PendingOperations &= ~PendingOperation.LoadInputFolder;
                if (m_LoadAssetFolderOperation != null)
                {
                    Debug.LogWarning("A folder is already being loaded, ignoring request to load a folder");
                }
                else
                {
                    m_LoadAssetFolderOperation = m_Service.LoadInputFolderAsync(inputFolderPath);
                    m_LoadAssetFolderOperation.OnProgress(progress =>
                    {
                        loadingShow     = true;
                        loadingProgress = progress;
                        loadingContent  = string.Format("Loading folder: {0:P2}", progress);
                    });
                    m_LoadAssetFolderOperation.OnComplete(result =>
                    {
                        m_Service.Reset();
                        m_Service.SetInput(result);

                        m_FitToPreviewAfterProcess = true;

                        SetProcessStep(Delighting.ProcessStep.Gather);
                        pendingOperation |= PendingOperation.Process;
                    });
                    m_LoadAssetFolderOperation.OnError(e =>
                    {
                        loadingShow = false;
                        Debug.LogException(e);
                    });
                }
            }
            if ((m_PendingOperations & PendingOperation.Process) != 0 && m_ProcessOperation == null)
            {
                m_PendingOperations &= ~PendingOperation.Process;
                if (m_FromProcessStep != Delighting.ProcessStep.None)
                {
                    m_ProcessOperation = m_Service.ProcessAsync(new Delighting.ProcessArgs {
                        fromStep = m_FromProcessStep, calculateResult = false
                    });
                    m_FromProcessStep = Delighting.ProcessStep.None;

                    m_ProcessOperation.OnProgress(progress =>
                    {
                        loadingShow     = true;
                        loadingProgress = progress;
                        loadingContent  = string.Format("De-Lighting: {0:P2}", progress);
                    });
                    m_ProcessOperation.OnComplete(result =>
                    {
                        loadingShow     = false;
                        loadingProgress = 1;
                    });
                    m_ProcessOperation.OnError(e =>
                    {
                        loadingShow     = false;
                        loadingProgress = 1;
                        Debug.LogException(e);
                    });
                }
            }
        }