public async Task BroadCastTransaction(Guid operationId, Transaction tx)
        {
            var operation = await _operationMetaRepository.Get(operationId);

            if (operation == null)
            {
                throw new BusinessException("Operation not found", ErrorCode.BadInputParameter);
            }

            if (await _operationEventRepository.Exist(operationId, OperationEventType.Broadcasted))
            {
                throw new BusinessException("Transaction already brodcasted", ErrorCode.TransactionAlreadyBroadcasted);
            }
            var hash = tx.GetHash().ToString();
            await _transactionBlobStorage.AddOrReplaceTransaction(operationId, hash, TransactionBlobType.BeforeBroadcast, tx.ToHex());

            var lastBlockHeight = await _blockChainProvider.GetLastBlockHeight();

            await _blockChainProvider.BroadCastTransaction(tx);

            await _observableOperationRepository.InsertOrReplace(ObervableOperation.Create(operation, BroadcastStatus.InProgress, hash, lastBlockHeight));

            await _unconfirmedTransactionRepository.InsertOrReplace(UnconfirmedTransaction.Create(operationId, hash));

            await _operationEventRepository.InsertIfNotExist(OperationEvent.Create(operationId, OperationEventType.Broadcasted));

            await _spentOutputRepository.InsertSpentOutputs(operationId, tx.Inputs.Select(i => new Output(i.PrevOut)));
        }
Пример #2
0
        public static void Uninstall(string extensionId, bool success)
        {
            var telEvent = new OperationEvent(_namespace + "Uninstall", success ? TelemetryResult.Success : TelemetryResult.Failure);

            telEvent.Properties.Add("id", extensionId);
            TelemetryService.DefaultSession.PostEvent(telEvent);
        }
Пример #3
0
 internal void Update(OperationTask task, TaskProgress progress, OperationEvent sourceEvent, OperationEvent destinationEvent)
 {
     operations[task.OperationID] = new OperationInfo
     {
         Progress             = progress,
         LastSourceEvent      = sourceEvent,
         LastDestinationEvent = destinationEvent,
     };
 }
Пример #4
0
 internal void Store(OperationTask task, OperationEvent sourceEvent, OperationEvent destinationEvent)
 {
     operations[task.OperationID] = new OperationInfo
     {
         Progress             = TaskProgress.Acknowledged,
         LastSourceEvent      = sourceEvent,
         LastDestinationEvent = destinationEvent,
     };
 }
Пример #5
0
 protected TelemetryScopeBase(OperationEvent operationEvent, TelemetryIdentifier telemetryIdentifier, ITelemetryRecorder telemetryRecorder)
 {
     //IL_0008: Unknown result type (might be due to invalid IL or missing references)
     result            = (TelemetryResult)0;
     TelemetryEvent    = (telemetryIdentifier ?? throw new ArgumentNullException("telemetryIdentifier"));
     TelemetryRecorder = (telemetryRecorder ?? throw new ArgumentNullException("telemetryRecorder"));
     endEvent          = new VSTelemetryEvent(operationEvent);
     rootScope         = this;
 }
        private async Task CheckUnconfirmedTransaction(IUnconfirmedTransaction unconfirmedTransaction)
        {
            var operationMeta = await _operationMetaRepository.GetAsync(unconfirmedTransaction.OperationId);

            if (operationMeta == null)
            {
                _log.Warning(unconfirmedTransaction.ToJson(), "OperationMeta not found");

                return;
            }

            var confirmationCount = await _blockChainProvider.GetTxConfirmationCountAsync(unconfirmedTransaction.TxHash);

            var isCompleted = confirmationCount >= _confirmationsSettings.MinConfirmationsToDetectOperation;

            ;
            if (isCompleted)
            {
                //Force update balances
                var fromAddressUpdatedBalance = await operationMeta.Inputs.SelectAsync(async o => await _walletBalanceService.UpdateBtcBalanceAsync(o.Address,
                                                                                                                                                    _confirmationsSettings.MinConfirmationsToDetectOperation))
                ;

                var toAddressUpdatedBalance = await operationMeta.Outputs.SelectAsync(async o =>
                                                                                      await _walletBalanceService.UpdateBtcBalanceAsync(o.Address,
                                                                                                                                        _confirmationsSettings.MinConfirmationsToDetectOperation));


                var operationCompletedLoggingContext = new
                {
                    unconfirmedTransaction.OperationId,
                    unconfirmedTransaction.TxHash,
                    fromAddressUpdatedBalance,
                    toAddressUpdatedBalance
                };

                await _operationEventRepository.InsertIfNotExistAsync(OperationEvent.Create(
                                                                          unconfirmedTransaction.OperationId,
                                                                          OperationEventType.DetectedOnBlockChain, operationCompletedLoggingContext));

                _log.Info(operationCompletedLoggingContext.ToJson(), "Operation completed");


                await _unconfirmedTransactionRepository.DeleteIfExistAsync(unconfirmedTransaction.OperationId);
            }

            var status = isCompleted
                ? BroadcastStatus.Completed
                : BroadcastStatus.InProgress;

            var lastBlockHeight = await _blockChainProvider.GetLastBlockHeightAsync();

            await _observableOperationRepository.InsertOrReplaceAsync(ObervableOperation.Create(operationMeta, status,
                                                                                                unconfirmedTransaction.TxHash,
                                                                                                lastBlockHeight));
        }
Пример #7
0
        public async Task DetectUnconfirmedTransactions()
        {
            var unconfirmedTxs = await _unconfirmedTransactionRepository.GetAll();

            foreach (var unconfirmedTransaction in unconfirmedTxs)
            {
                var operationMeta = await _operationMetaRepository.Get(unconfirmedTransaction.OperationId);

                if (operationMeta == null)
                {
                    await _log.WriteWarningAsync(nameof(UpdateObservableOperations), nameof(DetectUnconfirmedTransactions),
                                                 unconfirmedTransaction.ToJson(), "OperationMeta not found");

                    continue;
                }

                var confirmationCount = await _blockChainProvider.GetTxConfirmationCount(unconfirmedTransaction.TxHash);

                var isCompleted = confirmationCount >= _confirmationsSettings.MinConfirmationsToDetectOperation;
                ;
                if (isCompleted)
                {
                    //Force update balances
                    var fromAddressUpdatedBalance = await _walletBalanceService.UpdateBalance(operationMeta.FromAddress);

                    var toAddressUpdatedBalance = await _walletBalanceService.UpdateBalance(operationMeta.ToAddress);


                    var operationCompletedLoggingContext = new
                    {
                        unconfirmedTransaction.OperationId,
                        unconfirmedTransaction.TxHash,
                        fromAddressUpdatedBalance,
                        toAddressUpdatedBalance
                    };

                    await _operationEventRepository.InsertIfNotExist(OperationEvent.Create(unconfirmedTransaction.OperationId,
                                                                                           OperationEventType.DetectedOnBlockChain, operationCompletedLoggingContext));

                    await _log.WriteInfoAsync(nameof(UpdateBalanceFunctions), nameof(DetectUnconfirmedTransactions),
                                              operationCompletedLoggingContext.ToJson(),
                                              "Operation completed");


                    await _unconfirmedTransactionRepository.DeleteIfExist(unconfirmedTransaction.OperationId);
                }

                var status = isCompleted
                    ? BroadcastStatus.Completed
                    : BroadcastStatus.InProgress;

                await _observableOperationRepository.InsertOrReplace(ObervableOperation.Create(operationMeta, status,
                                                                                               unconfirmedTransaction.TxHash));
            }
        }
 public BlockResultVoid Fail(OperationEvent error)
 {
     return(new BlockResultVoid
     {
         Target = new BlockResultTarget
         {
             FlowTarget = BlockFlowTarget.Fail,
             Error = error
         }
     });
 }
Пример #9
0
        public static void TrackOperation(string name, params KeyValuePair <string, object>[] properties)
        {
            string actualName = name.Replace(" ", "_");
            var    task       = new OperationEvent(_namespace + actualName, TelemetryResult.None);

            foreach (KeyValuePair <string, object> property in properties)
            {
                task.Properties.Add(property);
            }

            TelemetryService.DefaultSession.PostEvent(task);
        }
Пример #10
0
        public void PostOperation(TelemetryIdentifier telemetryIdentifier, TelemetryResult result, IEnumerable <DataPoint> properties)
        {
            //IL_0014: Unknown result type (might be due to invalid IL or missing references)
            //IL_0016: Unknown result type (might be due to invalid IL or missing references)
            //IL_001c: Expected O, but got Unknown
            if (telemetryIdentifier == null)
            {
                throw new ArgumentNullException("telemetryIdentifier");
            }
            OperationEvent val = (OperationEvent)(object)new OperationEvent(telemetryIdentifier.Value, result, (string)null);

            DataPointCollection.AddCollectionToDictionary(properties, ((TelemetryEvent)val).Properties);
            telemetryRecorder.RecordEvent((TelemetryEvent)(object)val);
        }
Пример #11
0
    public async void AddToOperationLog(OperationEvent EventType, string newText)
    {
        if (!isInited)
        {
            return;
        }
        string textLog = string.Empty;

        var timeNow = System.DateTime.Now;

        textLog = "\n[" + timeNow.Day + "/" + timeNow.Month + "/" + timeNow.Year + " " + timeNow.Hour.ToString("d2") + ":" + timeNow.Minute.ToString("d2") + ":" + timeNow.Second.ToString("d2") + "] " + EventType.ToString() + ": " + newText + "\n";
        Debug.Log(textLog);
#if WINDOWS_UWP
        await FileIO.AppendTextAsync(OperationFile, textLog, Windows.Storage.Streams.UnicodeEncoding.Utf8);
#endif
    }
Пример #12
0
        public void PostOperation(TelemetryIdentifier telemetryIdentifier, TelemetryResult result)
        {
            //IL_0014: Unknown result type (might be due to invalid IL or missing references)
            //IL_0016: Unknown result type (might be due to invalid IL or missing references)
            //IL_001c: Expected O, but got Unknown
            //IL_002b: Unknown result type (might be due to invalid IL or missing references)
            //IL_0030: Unknown result type (might be due to invalid IL or missing references)
            if (telemetryIdentifier == null)
            {
                throw new ArgumentNullException("telemetryIdentifier");
            }
            OperationEvent val = (OperationEvent)(object)new OperationEvent(telemetryIdentifier.Value, result, (string)null);

            EndEvent.Correlate(((TelemetryEvent)val).Correlation);
            TelemetryRecorder.RecordEvent((TelemetryEvent)(object)val);
        }
Пример #13
0
        private void OperationEventLoggedCorrectly(OperationEvent opEvent, FolderConfig folderConfig)
        {
            //using (var stream = new MemoryStream())
            //using (var eventsLogger = new FolderEventsLoggerInFile(folderConfig, CreateStreamWriter(stream)))
            //{
            //    eventsLogger.LogOperation(opEvent);

            //    //Check if two equals
            //    string actual = Encoding.Default.GetString(stream.ToArray());

            //    if (folderConfig.IsValid(opEvent, Constants.TextLogFileName))
            //    {
            //        string expected = $"{opEvent}{Environment.NewLine}";
            //        Assert.AreEqual(expected, actual);
            //    }
            //    else Assert.AreEqual(string.Empty, actual);
            //}
        }
Пример #14
0
        public void EventsErrorsExceptionsTest()
        {
            var os = new OperationStackBuilder().Build()
                     .Then(op =>
            {
                throw new Exception();
                return(op.Return());
            })
                     .OnErrors(h =>
            {
                Assert.False(h.Errors.All(e => e.IsHandled));
                foreach (var e in h.Errors)
                {
                    e.Handle();
                }
            })
                     .OnExceptions(h =>
            {
                Assert.True(h.ExceptionErrors.All(e => e.Error.IsHandled));
                return(h.Return());
            })
                     .Then(op =>
            {
                var oe = new OperationEvent("Test event");
                //op.Throw(oe);
            })
                     .OnEvents(h =>
            {
                Assert.True(h.Events.All(e => e.IsHandled));
                return(h.Return());
            })
                     .Then(op =>
            {
                var oe = new OperationEvent(new Exception());
                op.Throw(oe);
            })
                     .OnEvents(h =>
            {
                Assert.True(h.Events.All(e => e.IsHandled));
                return(h.Return());
            })
                     .Then(op =>
            {
                var oe = new OperationEvent("Test event");
                oe.Throw();     // Should throw an exception because the OperationEvent is not an error
                return(op.Return());
            })
                     .OnErrors(h =>
            {
                Assert.False(h.Errors.All(e => e.IsHandled));
                return(h.Return());
            })
                     .OnExceptions(h =>
            {
                foreach (var e in h.ExceptionErrors)
                {
                    e.Error.Handle();
                }
            });

            var r = os.Execute();

            Assert.True(r.Events.All(e => e.IsHandled));
        }
Пример #15
0
 public VSTelemetryEvent(OperationEvent operationEvent)
 {
     endEvent         = (operationEvent ?? throw new ArgumentNullException("operationEvent"));
     sharedProperties = new DataPointCollection();
 }
Пример #16
0
 private void OnOperationEvent(OperationEventArgs e) => OperationEvent?.Invoke(this, e);
        public void PostSuccessfulOperation(string eventName, Dictionary <string, object> additionalProperties = null)
        {
            OperationEvent telemetryEvent = new OperationEvent(eventName, TelemetryResult.Success);

            PostEventInternal(telemetryEvent, additionalProperties);
        }
 public BlockResultVoid Fail(OperationEvent error)
 {
     return(resultDispather.Fail(error));
 }
Пример #19
0
        public static bool AddFolderToRootFolder(this FolderViewModel rootFolder, OperationEvent opEvent)
        {
            var currFolder = rootFolder;
            var splitted   = SplitWithSlashes(opEvent.FilePath);

            if (rootFolder.Name != opEvent.FilePath.Substring(0, rootFolder.Name.Length))
            {
                return(false);
            }

            for (int i = SplitWithSlashes(rootFolder.Name).Length; i < splitted.Length - 1; i++)
            {
                var fold = currFolder.Folders.FirstOrDefault(f => f.Name == splitted[i]);
                if (fold == null)
                {
                    currFolder.Folders.Add(new FolderViewModel(splitted[i]));
                    currFolder = currFolder.Folders[currFolder.Folders.Count - 1];
                }
                else
                {
                    currFolder = fold;
                }
            }

            string folderName = splitted[splitted.Length - 1];
            var    folder     = currFolder.Folders.FirstOrDefault(fold => fold.Name == folderName);

            if (opEvent is RenameOperationEvent renOpEvent)
            {
                var oldFolder = currFolder.Folders.FirstOrDefault(fold => fold.Name == renOpEvent.OldFileName);
                if (oldFolder != null)
                {
                    oldFolder.Name = folderName;
                    //oldFolder.OperationEvents = opEvent;
                    if (!oldFolder.OperationEvents.Any(op => op.EventType == EventType.Create || op.EventType == EventType.Edit))
                    {
                        oldFolder.AddOperationEvent(opEvent);
                    }
                }
                else
                {
                    currFolder.Folders.Add(new FolderViewModel(folderName).AddOperationEvent(opEvent));
                }
            }
            else
            {
                if (folder == null)
                {
                    currFolder.Folders.Add(new FolderViewModel(folderName).AddOperationEvent(opEvent));
                }
                else
                {
                    switch (opEvent)
                    {
                    //case RenameOperationEvent renOpEvent:
                    //    folder.Name = renOpEvent.FileName;
                    //    folder.OperationEvent = renOpEvent;
                    //    break;
                    case DeleteOperationEvent deleteOpEvent:
                        if (folder.OperationEvents.Any(op => op.EventType == EventType.Create))
                        {
                            folder.OperationEvents = new List <OperationEvent>();
                        }
                        else
                        {
                            folder.OperationEvents = new List <OperationEvent>();
                            folder.AddOperationEvent(deleteOpEvent);
                        }
                        break;

                    default: throw new NotImplementedException("CreateOperationEvent or EditOperationEvent not implemented");
                    }
                }
            }

            return(true);

            string[] SplitWithSlashes(string str) => str.Split(new[] { "\\" }, StringSplitOptions.None);
        }
Пример #20
0
        private object SendEvent(OperationType operType, object operObj)
        {
            OperationEvent operEvent = new OperationEvent(operType, operObj);
            m_operEvents.Enqueue(operEvent);
            m_waitHandle.Set();

            //synchronously wait for the result
            return operEvent.WaitUntilProcessed();
        }
Пример #21
0
        private bool ProcessOperationEvent(OperationEvent operEvent)
        {
            bool result = true;
            bool acquiredLock = false;
            try
            {
                Monitor.Enter(operEvent.ProcessedLock, ref acquiredLock);
                if (acquiredLock)
                {
                    result = DoProcessOperationEvent(operEvent);
                }
            }
            finally
            {
                if (acquiredLock)
                {
                    operEvent.Processed = true;
                    Monitor.PulseAll(operEvent.ProcessedLock);
                    Monitor.Exit(operEvent.ProcessedLock);
                }
            }

            return result;
        }
Пример #22
0
        private bool DoProcessOperationEvent(OperationEvent operEvent)
        {
            bool shouldContinue = true;
            switch (operEvent.OperType)
            {
                case OperationType.OP_ADD:
                    {
                        shouldContinue = DoAdd(operEvent.OperObject as CacheItem);
                    }
                    break;

                case OperationType.OP_ADD_OR_GET:
                    {
                        shouldContinue = DoGetOrAdd(operEvent);
                    }
                    break;

                case OperationType.OP_REMOVE:
                    {
                        shouldContinue = DoRemove(operEvent.OperObject as CacheItem);
                    }
                    break;

                case OperationType.OP_CLEAR:
                    {
                        Clear();
                    }
                    break;

                case OperationType.OP_STOP:
                    {
                        m_running = false;
                        shouldContinue = false;
                    }
                    break;

                default:
                    {
                        LogManager.Warn("CacheManager:ProcessUserAction", "Unsupported operation: " + (int)operEvent.OperType);
                    }
                    break;
            }

            return shouldContinue;
        }
Пример #23
0
        private bool DoGetOrAdd(OperationEvent operEvent)
        {
            CacheItem ci = operEvent.OperObject as CacheItem;
            if (ci == null)
            {
                LogManager.Warn("CacheManager:Assert Failure", "DoGetOrAdd a null item");
                return true;
            }

            //Cache Item
            bool added = m_cacheItems.TryAdd(ci.Key, ci);
            if (added)
            {
                //Add the SchedulerKey at the same time
                SchedulerKey sk = new SchedulerKey(ci.NextExpirationTime, ci.Key);
                if (m_heap.ContainsKey(sk))
                {
                    //This should not happen. If it does, then this is a critial bug!
                    LogManager.Warn("CacheManager:Assert Failure", string.Format("The SchedulerKey key[{0}] is already exising", sk.ToString()));
                }
                else
                {
                    m_heap.Add(sk, DUMMY);
                }

                operEvent.OperResult = ci;

                LogManager.Info("CacheManager:DoGetOrAdd", string.Format("The key [{0}] is added, value=[{1}]", ci.Key, ci.ToString()));
            }
            else
            {
                CacheItem existingItem = null;
                if (!m_cacheItems.TryGetValue(ci.Key, out existingItem))
                {
                    //This should not happen. If it does, then this is a critial bug!
                    LogManager.Warn("CacheManager:Assert Failure", string.Format("The expected existing key[{0}] doesn't exist", ci.Key));
                }
                else if (existingItem == null)
                {
                    //This should not happen. If it does, then this is a critial bug!
                    LogManager.Warn("CacheManager:Assert Failure", string.Format("The expected existing key[{0}] is null", ci.Key));
                }
                else
                {
                    operEvent.OperResult = existingItem;
                    //LogManager.Debug("CacheManager:DoGetOrAdd", string.Format("The key [{0}] is already existing, value=[{1}]",
                    //    ci.Key, existingItem.ToString()));
                }
            }

            return true;
        }
Пример #24
0
 protected TelemetryScopeBase(OperationEvent operationEvent, TelemetryIdentifier telemetryIdentifier, ITelemetryRecorder telemetryRecorder, ITelemetryScope parentScope)
     : this(operationEvent, telemetryIdentifier, telemetryRecorder)
 {
     this.parentScope = parentScope;
     rootScope        = (this.parentScope.Root ?? this.parentScope);
 }
Пример #25
0
 public void Repeater(Operation op, T obj)
 {
     OperationEvent?.Invoke(op, obj);
 }