示例#1
0
        public void Test_404()
        {
            var monitor = new HttpMonitor();
            var result  = monitor.CheckHealth(@"https://httpstat.us/404");

            Assert.AreEqual(HealthStatus.NotExists, result.Status);
        }
示例#2
0
        protected override void OnStart(string[] args)
        {
            Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
            Logger.Init();
            MonitorHistory.Init();
            Logger logger = new Logger("service");

            logger.Info("begin start", new object[0]);
            try
            {
                Config          = Config.Load("service.xml");
                Api             = new DnsPodApi(Config, Config.GetLocal());
                Ddns            = new DDns(Config.LastIp, Config.GetLocal());
                Ddns.IPChanged += Ddns_IPChangedNotified;
                Ddns.Start();

                Monitor = new HttpMonitor(Config);
                Monitor.StatusChanged += Monitor_StatusChanged;
                Monitor.Start();

                logger.Info("end start", new object[0]);
            }
            catch (Exception exception)
            {
                logger.Error("start error:{0}", new object[] { exception });
            }
        }
示例#3
0
        public void HttpMonitorWorks()
        {
            var monitor = new HttpMonitor(Network.MainNet);
            var history = monitor.GetAddressHistory("15emqTTjzCVRFWTRyBiQUgBnK3DBhShFBU");

            var recordCount = history.Records.Count;

            Assert.True(recordCount > 16);
            Assert.Equal(history.Records.Last().Amount, 0.03802378m);
            Assert.Equal(history.Records[recordCount - 2].TransactionId,
                         "1798a59c37828db66e8c4d57a90324fa8039aef72b872df5876edfb31b102c5f");
            Assert.Equal(history.Records[recordCount - 3].Amount, -0.06335627m);
            Assert.True(history.Records[recordCount - 3].Confirmed);

            string mnemonic;
            var    safe = Safe.Create(out mnemonic, "", "foo", Network.MainNet);

            safe.DeleteWalletFile();
            var history2 = monitor.GetAddressHistory(safe.GetAddress(2));

            Assert.True(history2.Records.Count == 0);

            var balanceInfo  = monitor.GetAddressBalanceInfo("15emqTTjzCVRFWTRyBiQUgBnK3DBhShFBU");
            var balanceInfo2 = monitor.GetAddressBalanceInfo(safe.GetAddress(2));

            Assert.Equal(balanceInfo.Balance, history.TotalReceived - history.TotalSpent);
            Assert.Equal(balanceInfo2.Balance, history2.TotalReceived - history2.TotalSpent);

            var confirmedBalance   = history.Records.Where(record => record.Confirmed).Sum(record => record.Amount);
            var unconfirmedBalance = history.Records.Where(record => !record.Confirmed).Sum(record => record.Amount);

            Assert.Equal(balanceInfo.Unconfirmed, unconfirmedBalance);
            Assert.Equal(balanceInfo.Confirmed, confirmedBalance);
        }
示例#4
0
        public void Test_503()
        {
            var monitor = new HttpMonitor();
            var result  = monitor.CheckHealth(@"https://httpstat.us/503");

            Assert.AreEqual(HealthStatus.Offline, result.Status);
        }
示例#5
0
        public void Test_200()
        {
            var monitor = new HttpMonitor();
            var result  = monitor.CheckHealth(@"https://httpstat.us/200");

            Assert.AreEqual(HealthStatus.Healthy, result.Status);
        }
 private HttpMonitorChecked GenerateHttpMonitorChecked(HttpMonitor httpMonitor)
 {
     return(httpMonitor
            .CreateCheckHttpEndpoint(HttpMonitorCheckId.Create())
            .CreateHttpMonitorCheck(
                new HttpRequestTiming(DateTime.UtcNow, DateTime.UtcNow.AddSeconds(1)),
                new HttpResponse(HttpStatusCode.OK))
            .CreateHttpMonitorChecked());
 }
        private HttpMonitor GenerateHttpMonitor()
        {
            var entity = new HttpMonitor(
                HttpMonitorId.Create(),
                new HttpRequest(HttpMethod.Get, new Uri("https://example.com")));

            var @event = GenerateHttpMonitorChecked(entity);

            entity.Handle(@event);

            return(entity);
        }
        public async Task <HttpMonitor> CreateHttpMonitorAsync(CreateHttpMonitor command)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var httpMonitor = new HttpMonitor(HttpMonitorId.Create(), command.Request);

            await _repository.PutAsync(httpMonitor);

            return(httpMonitor);
        }
示例#9
0
        public void GetTransactionInfoWorks()
        {
            var monitor         = new HttpMonitor(Network.MainNet);
            var transactionInfo = monitor.GetTransactionInfo("2d0a108be81fe0d807a0cdd65233158bac1642081033c21b379d776f278015a4");

            Assert.True(transactionInfo.AllInOutsAdded);
            Assert.True(transactionInfo.Confirmed);
            Assert.Equal(transactionInfo.Network, Network.MainNet);
            Assert.True(transactionInfo.Fee > 0);
            Assert.True(transactionInfo.Inputs.Count > 10);
            Assert.Equal(transactionInfo.TotalOutputAmount, 15m);
            Assert.Equal(transactionInfo.Outputs.First().Address, "1EDt6Pe5psPLrAKmq7xawCFo9LxtKoJz7g");
        }
示例#10
0
        private HealthReport InternalCheckHealth()
        {
            var result = new HealthReport();

            //calculate httpMonitor timeout based on the check interval (1 minute for instance) substracted with 5 seconds
            var timeout = TimeSpan.FromMinutes(_endpoint.CheckInterval).Subtract(TimeSpan.FromSeconds(5)).TotalSeconds;

            var monitor = new HttpMonitor(_endpoint.Id.ToString(), _httpClientFactory, _tokenService, timeout, _logger);
            var sw      = Stopwatch.StartNew();
            var info    = monitor.CheckHealth(_endpoint.Url);

            result.TimeStamp = DateTime.UtcNow;
            sw.Stop();

            result.ResponseTime = sw.ElapsedMilliseconds;
            result.Message      = string.Empty;
            if (info.Details != null && info.Details.Any())
            {
                if (info.Details.ContainsKey("code"))
                {
                    result.Status = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), info.Details["code"]);
                }

                if (info.Details.ContainsKey("content"))
                {
                    result.Message = info.Details["content"];
                }

                if (info.Details.ContainsKey("contentType"))
                {
                    if (info.Details["contentType"].Contains("html"))
                    {
                        result.Message = "Unexpected html content";
                    }
                }
            }

            if (_endpoint.CheckType == (int)CheckType.AvailabilityCheck)
            {
                Validate(result);
            }
            else if (_endpoint.CheckType == (int)CheckType.ContentCheck)
            {
                ValidateCustom(result);
            }

            return(result);
        }
示例#11
0
 private void ShowOrHideQuickOpsForm(object sender, MouseEventArgs e)
 {
     if (e.Button == MouseButtons.Left)
     {
         if (quickOpsForm.Visible)
         {
             quickOpsForm.Visible = false;
             monitor?.Dispose();
         }
         else
         {
             quickOpsForm.Visible = true;
             monitor = new HttpMonitor();
         }
     }
 }
        public static HttpMonitorDto CreateFrom(HttpMonitor httpMonitor)
        {
            if (httpMonitor == null)
            {
                throw new ArgumentNullException(nameof(httpMonitor));
            }

            return(new HttpMonitorDto
            {
                Id = httpMonitor.Id.Value.ToString(),
                Request = new HttpRequestDto()
                {
                    Method = httpMonitor.Request.Method.Method,
                    Url = httpMonitor.Request.Url
                }
            });
        }
示例#13
0
        private static void TemporarilyTestHttpMonitor()
        {
            var monitor = new HttpMonitor(Network.TestNet);

            // var privateKey = "tprv8f3GDAef8nhKvQbC5KGEerqDGB2s2KgMNHS4kLDXXP7c8M6ZcxyEzyvsVA9C1ss9Fj5QEiCiKbyEfD97duhXjc2he58dDicMtLs3YfwNJb2";
            var address = "miLGbZvQ5sEd5BKCPXjEJzknMdENuFEzCy";

            var bal = monitor.GetAddressBalanceInfo(address);
            var his = monitor.GetAddressHistory(address);

            WriteLine($"Balance: {bal.Balance}");
            WriteLine($"Confirmed balance: {bal.Confirmed}");
            WriteLine($"Unconfirmed balance: {bal.Unconfirmed}");
            WriteLine($"TotalReceived: {his.TotalReceived}");
            WriteLine($"TotalSpent: {his.TotalSpent}");
            WriteLine($"TotalReceived - TotalSpent: {his.TotalReceived - his.TotalSpent}");
            WriteLine($"TotalReceived - TotalSpent == Balance: {his.TotalReceived - his.TotalSpent == bal.Balance}");
            WriteLine();
            WriteLine("RECORDS:");

            foreach (var record in his.Records)
            {
                WriteLine();
                WriteLine($"DateTime: {record.DateTime}");
                WriteLine($"Amount: {record.Amount}");
                WriteLine($"Confirmed: {record.Confirmed}");
            }

            //var spender = new HttpBuilder(Network.TestNet);
            //var tx = spender.BuildTransaction(
            //    new List<string> { privateKey },
            //    new List<AddressAmountPair>
            //    {
            //        new AddressAmountPair
            //        {
            //            //Address = "miLGbZvQ5sEd5BKCPXjEJzknMdENuFEzCy",
            //            Address = "miNu2YVQLSqFcw91fRVuNHMmGkStMd5SFj",
            //            Amount = 1
            //        }
            //    });
            //Console.WriteLine();
            //Console.WriteLine("Transaction created");
            //spender.Send(tx.Id);
            //Console.WriteLine("Transaction sent");
        }
        public Task PutAsync(HttpMonitor httpMonitor)
        {
            if (httpMonitor == null)
            {
                throw new ArgumentNullException(nameof(httpMonitor));
            }

            var documentCollectionUri = _configs.DocumentCollectionUri;

            var jObject = JObject.FromObject(httpMonitor, JsonSerializer.Create(Constants.JsonSerializerSettings));

            // add type
            jObject.Add("_type", JValue.CreateString(DocumentType));

            var document = JsonSerializable.LoadFrom <Document>(new MemoryStream(Encoding.UTF8.GetBytes(jObject.ToString())));

            return(_client.UpsertDocumentAsync(documentCollectionUri, document, null, true));
        }
示例#15
0
 public MenuViewController(SSController controller)
 {
     this.controller      = controller;
     this.monitor         = controller.monitor;
     quickOpsForm         = new QuickOpsForm(controller);
     quickOpsForm.Name    = "QuickOpsForm";
     quickOpsForm.Text    = "Quick Ops Form";
     quickOpsForm.Visible = false;
     exitItem             = new MenuItem("Exit", Exit);
     runAutoRouteItem     = new MenuItem("Run AutoRoute", RunAutoConfig);
     contextMenu          = new ContextMenu(new MenuItem[] { runAutoRouteItem, exitItem });
     notifyIcon           = new NotifyIcon
     {
         Visible     = true,
         Icon        = Resources.plane,
         ContextMenu = contextMenu
     };
     notifyIcon.MouseClick += new MouseEventHandler(ShowOrHideQuickOpsForm);
 }
示例#16
0
        private static void LoadModules()
        {
            modList = new List <BackendModule> ();
            List <BackendModule>  loadQueue       = new List <BackendModule> ();
            Queue <BackendModule> processingQueue = new Queue <BackendModule> ();

            httpModule = new HttpMonitor();
            userModule = new UserModule();

            loadQueue.Add(httpModule);
            loadQueue.Add(userModule);
            loadQueue.Add(new TcpConsole());
            loadQueue.Add(new MetaModule());
            loadQueue.Add(new PostsModule());

            GetCompatibleMods(loadQueue, modList, ref processingQueue);

            while (processingQueue.Count > 0)
            {
                while (processingQueue.Count > 0)
                {
                    BackendModule mod = processingQueue.Dequeue();
                    mod.Load();
                    modList.Add(mod);
                    loadQueue.Remove(mod);
                    Console.WriteLine("[I] Enabled " + mod.MODNAME);
                }
                GetCompatibleMods(loadQueue, modList, ref processingQueue);
            }
            if (loadQueue.Count > 0)
            {
                foreach (BackendModule mod in loadQueue)
                {
                    Console.WriteLine("[W] Disabled " + mod.MODNAME + " Reason: Missing or disabled dependency");
                }
            }


            Console.WriteLine("Started");
            httpModule.HttpStart();
        }
示例#17
0
        public static async Task SendAsync(string baseAddress, ConnectionType connectionType, TransactionInfo transactionInfo, int tryTimes = 1)
        {
            var monitor = new HttpMonitor(baseAddress, transactionInfo.Network);

            if (connectionType == ConnectionType.Http)
            {
                var client      = new QBitNinjaClient(baseAddress, transactionInfo.Network.ToNBitcoinNetwork());
                var transaction = FindTransaction(transactionInfo);

                var broadcastResponse = await client.Broadcast(transaction).ConfigureAwait(false);

                if (!broadcastResponse.Success)
                {
                    throw new Exception($"ErrorCode: {broadcastResponse.Error.ErrorCode}" + Environment.NewLine
                                        + broadcastResponse.Error.Reason);
                }
            }
            if (connectionType == ConnectionType.RandomNode)
            {
                var parameters = new NodeConnectionParameters();
                var group      = new NodesGroup(transactionInfo.Network.ToNBitcoinNetwork(), parameters, new NodeRequirement
                {
                    RequiredServices = NodeServices.Nothing
                })
                {
                    MaximumNodeConnection = 1
                };
                group.Connect();

                while (group.ConnectedNodes.Count == 0)
                {
                    await Task.Delay(100).ConfigureAwait(false);
                }

                var transaction = FindTransaction(transactionInfo);
                var payload     = new TxPayload(transaction);
                group.ConnectedNodes.First().SendMessage(payload);
            }

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    var result = await monitor.GetTransactionInfoAsync(transactionInfo.Id);
                }
                catch (NullReferenceException exception)
                {
                    if (exception.Message != "Transaction does not exists")
                    {
                        throw;
                    }
                    await Task.Delay(1000).ConfigureAwait(false);

                    continue;
                }
                if (i == 10)
                {
                    if (tryTimes == 1)
                    {
                        throw new Exception("Transaction has not been broadcasted, try again!");
                    }
                    await SendAsync(baseAddress, connectionType, transactionInfo, tryTimes - 1)
                    .ConfigureAwait(false);
                }
                break;
            }
        }
        private Task GenerateAsync()
        {
            var httpMonitor = new HttpMonitor(HttpMonitorId.Create(), new HttpRequest(HttpMethod.Get, new Uri("http://example.com/sdfsd/sdfsdfsd/sdffsd")));

            return(_repository.PutAsync(httpMonitor));
        }
示例#19
0
        private static void Part2Lesson1()
        {
            var network = Network.MainNet;

            // HttpMonitor can monitor The Blockchain through HTTP (QBitNinja)
            var httpMonitor = new HttpMonitor(network);

            // Checking address balances
            var balanceInfo = httpMonitor.GetAddressBalanceInfo("1ENCTCkqoJqy2XZ2m2Dy1bRax7hsSnC5Fc");
            WriteLine($"Address balance: {balanceInfo.Balance}"); // 0,05474889
            WriteLine($"Confirmed balance: {balanceInfo.Confirmed}"); // 0
            WriteLine($"Unconfirmed balance: {balanceInfo.Unconfirmed}"); // 0,05474889

            // Get history of an address
            var history = httpMonitor.GetAddressHistory("1ENCTCkqoJqy2XZ2m2Dy1bRax7hsSnC5Fc");

            WriteLine("Number of transactions: " + history.Records.Count);

            // Exercise: are all transaction confirmed?
            var allTransactionsConfirmed = true;
            foreach (var record in history.Records)
            {
                WriteLine(record.TransactionId + " : " + record.Amount);
                allTransactionsConfirmed = allTransactionsConfirmed && record.Confirmed;
            }
            WriteLine("All transactions are confirmed: " + allTransactionsConfirmed);

            // Exercise: get the balance of the address
            WriteLine("Total received - Total spent = Balance");
            WriteLine(history.TotalReceived + " - " + history.TotalSpent + " = " +
                      (history.TotalReceived - history.TotalSpent));

            // Get some data from the transaction
            var transactionInfo1 = httpMonitor.GetTransactionInfo(history.Records.First().TransactionId);

            WriteLine("txid: " + transactionInfo1.Id);
            WriteLine("Network: " + transactionInfo1.Network);
            WriteLine("Confirmed: " + transactionInfo1.Confirmed);
            WriteLine("Total amount of all inputs: " + transactionInfo1.TotalInputAmount);
            WriteLine("Total amount of all outputs: " + transactionInfo1.TotalOutputAmount);
            WriteLine("Fee : " + transactionInfo1.Fee);

            WriteLine(Environment.NewLine + "Input addresses and amounts: ");
            foreach (var input in transactionInfo1.Inputs)
            {
                WriteLine(input.Amount + " " + input.Address);
            }
            WriteLine(Environment.NewLine + "Output addresses and amounts: ");
            foreach (var output in transactionInfo1.Outputs)
            {
                WriteLine(output.Amount + " " + output.Address);
            }

            // Sometimes my API can't fully process a transaction, because it has OP_RETURN for example
            // It should not be a concern for a Bitcoin wallet that purely handles money, if a transaction output or input has not been added
            // that means it has some other purpose, a wallet API can dismiss it
            // This tx is exotic (has OP_RETURN)
            var transactionInfo2 =
                httpMonitor.GetTransactionInfo("8bae12b5f4c088d940733dcd1455efc6a3a69cf9340e17a981286d3778615684");
            WriteLine(transactionInfo2.Id);
            WriteLine("There are exotic inputs or outputs, so not all of them have been added successfully: "
                      + Environment.NewLine + !transactionInfo2.AllInOutsAdded);
        }
示例#20
0
        public async Task TestLaunch()
        {
            // Arrange
            var httpMonitor1 = new HttpMonitor(
                HttpMonitorId.Create(),
                new HttpRequest(HttpMethod.Get, _fixture.OpenHttpServer.BaseAddress));

            var httpMonitor2 = new HttpMonitor(
                HttpMonitorId.Create(),
                new HttpRequest(HttpMethod.Delete, _fixture.OpenHttpServer.BaseAddress));

            await _httpMonitorRepository.PutAsync(httpMonitor1);

            await _httpMonitorRepository.PutAsync(httpMonitor2);

            var tcs1          = new TaskCompletionSource <object>();
            var tcs2          = new TaskCompletionSource <object>();
            var combinedTasks = Task.WhenAll(tcs1.Task, tcs2.Task);

            _openHttpServer.Handler = ctx =>
            {
                if (string.Equals(ctx.Request.Method, httpMonitor1.Request.Method.Method,
                                  StringComparison.InvariantCultureIgnoreCase))
                {
                    tcs1.SetResult(null);
                    ctx.Response.StatusCode = 200;
                }
                else if (string.Equals(ctx.Request.Method, httpMonitor2.Request.Method.Method,
                                       StringComparison.InvariantCultureIgnoreCase))
                {
                    tcs2.SetResult(null);
                    ctx.Response.StatusCode = 300;
                }
                else
                {
                    ctx.Response.StatusCode = 404;
                }

                return(Task.CompletedTask);
            };

            // Act
            await _fixture.StartHostAsync();

            await Task.WhenAny(
                combinedTasks,
                Task.Delay(10000));

            // Assert
            Assert.True(combinedTasks.IsCompletedSuccessfully);

            // todo race condition
            await Task.Delay(100);

            var check1 = (await _httpMonitorCheckRepository.GetAsync(httpMonitor1.Id)).SingleOrDefault();

            Assert.NotNull(check1);
            Assert.Equal(200, (int)check1.Response.StatusCode);

            var check2 = (await _httpMonitorCheckRepository.GetAsync(httpMonitor2.Id)).SingleOrDefault();

            Assert.NotNull(check2);
            Assert.Equal(300, (int)check2.Response.StatusCode);
        }
示例#21
0
        public static void Send(ConnectionType connectionType, TransactionInfo transactionInfo, int tryTimes = 1)
        {
            var monitor = new HttpMonitor(transactionInfo.Network);

            if (connectionType == ConnectionType.Http)
            {
                var client      = new QBitNinjaClient(Convert.ToNBitcoinNetwork(transactionInfo.Network));
                var transaction = FindTransaction(transactionInfo);

                var broadcastResponse = client.Broadcast(transaction).Result;
                if (!broadcastResponse.Success)
                {
                    throw new Exception($"ErrorCode: {broadcastResponse.Error.ErrorCode}" + Environment.NewLine
                                        + broadcastResponse.Error.Reason);
                }
            }
            if (connectionType == ConnectionType.RandomNode)
            {
                var parameters = new NodeConnectionParameters();
                var group      = new NodesGroup(Convert.ToNBitcoinNetwork(transactionInfo.Network), parameters, new NodeRequirement
                {
                    RequiredServices = NodeServices.Nothing
                })
                {
                    MaximumNodeConnection = 1
                };
                group.Connect();

                while (group.ConnectedNodes.Count == 0)
                {
                    Thread.Sleep(100);
                }
                var transaction = FindTransaction(transactionInfo);
                var payload     = new TxPayload(transaction);
                group.ConnectedNodes.First().SendMessage(payload);
            }

            for (var i = 0; i < 10; i++)
            {
                try
                {
                    monitor.GetTransactionInfo(transactionInfo.Id);
                }
                catch (NullReferenceException exception)
                {
                    if (exception.Message != "Transaction does not exists")
                    {
                        throw;
                    }
                    Thread.Sleep(1000);
                    continue;
                }
                if (i == 10)
                {
                    if (tryTimes == 1)
                    {
                        throw new Exception("Transaction has not been broadcasted, try again!");
                    }
                    Send(connectionType, transactionInfo, tryTimes - 1);
                }
                break;
            }
        }