Example #1
0
        public static void CheckDomainForHttps(WebCheck check)
        {
            string domain = check.Domain;

            var request = (HttpWebRequest)WebRequest.Create("https://" + domain);

            try
            {
                using (WebResponse response = request.GetResponse())
                {
                    // Success
                    Console.WriteLine("------------------------ ok ------------------------");
                }
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (var streamReader = new StreamReader(response.GetResponseStream()))
                        Console.WriteLine(streamReader.ReadToEnd());
                }
            }
        }
Example #2
0
        public static void UpdateRecurringEvent(WebCheck check)
        {
            // update existing event
            string checkID = check.WebCheckID.ToString();

            RecurringJob.AddOrUpdate(checkID, () => CheckDomainForHttps(check), Cron.MinuteInterval(check.Delay));
        }
Example #3
0
        public static void DeleteRecurringEvent(WebCheck check)
        {
            // Delete existing event
            string checkID = check.WebCheckID.ToString();

            RecurringJob.RemoveIfExists(checkID);
        }
Example #4
0
        public async Task <IActionResult> Edit(Guid id, [Bind("WebCheckID,Name,Domain,Delay,CreateDate,AccountID")] WebCheck webCheck)
        {
            if (id != webCheck.WebCheckID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    // Set DateTime new
                    webCheck.CreateDate = DateTime.Now;

                    _context.Update(webCheck);
                    await _context.SaveChangesAsync();

                    WebCheckHelper.UpdateRecurringEvent(webCheck);
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!WebCheckExists(webCheck.WebCheckID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AccountID"] = new SelectList(_context.Accounts, "AccountID", "Password", webCheck.AccountID);
            return(View(webCheck));
        }
        static void Main(string[] args)
        {
            Console.WriteLine("API server initializing...");

            config = new XmlDocument();
            config.Load("config.xml");

            var cancel = new CancellationTokenSource();

            var appender = new log4net.Appender.ManagedColoredConsoleAppender();

            appender.Threshold = log4net.Core.Level.All;
            var x = (XmlElement)config.SelectSingleNode("//backend/log4net");

            if (x == null)
            {
                Console.WriteLine("Error: log4net configuration node not found. Check your config.xml");
                Console.ReadKey();
                return;
            }
            XmlConfigurator.Configure(x);

            api     = new APIServer();
            auth    = new FDOAuthServerCheck();
            iw4m    = new Iw4mCheck(auth);
            iw5m    = new Iw5mCheck(auth);
            forum   = new WebCheck("http://fourdeltaone.net/index.php", 60);
            kmshost = new KmshostCheck();

            auth.TestUsername = config.SelectSingleNode("//backend/auth-username").InnerText;
            auth.TestPassword = config.SelectSingleNode("//backend/auth-password").InnerText;

            BackendName = config.SelectSingleNode("//backend/backend-name").InnerText;

            api.Content.Add("login", auth);
            api.Content.Add("iw4m", iw4m);
            api.Content.Add("iw5m", iw5m);
            api.Content.Add("forum", forum);
            api.Content.Add("kmshost", kmshost);
            api.Content.Add("backend-name", BackendName);
            api.ServerLists.Add("iw4m", iw4m.AccessibleMasterServers[0].ServersListed);
            api.ServerLists.Add("iw5m", iw5m.ListedServers);
            api.StatusIndicators.Add("iw4m", new Iw4mStatusIndicator(ref iw4m));
            api.StatusIndicators.Add("iw5m", new Iw5mStatusIndicator(ref iw5m));
            api.StatusIndicators.Add("login", new LoginStatusIndicator(ref auth));
            api.StatusIndicators.Add("forum", new WebStatusIndicator(ref forum));
            api.StatusIndicators.Add("kmshost", new KmshostStatusIndicator(ref kmshost));

            api.Start();

            Console.WriteLine("API server starting, regular checks are now enabled.");

            while (true)
            {
                var task = Task.Factory.StartNew(() => CheckNow(), cancel.Token);
                Thread.Sleep(30 * 1000);
                task.Wait();
                task.Dispose();
            }
        }
Example #6
0
 /// <summary>
 /// Return result for check.
 /// </summary>
 /// <param name="check">The check.</param>
 /// <returns>The result.</returns>
 public WebCheckResult AtomicGetResultForCheck(WebCheck check)
 {
     lock (_lock)
     {
         return(_results.ContainsKey(check.Id)
             ? _results[check.Id]
             : null);
     }
 }
Example #7
0
        public static async void ProcessAlertNeedOnTracker(TrackedProduct tracker)
        {
            try
            {
                Log.Verbose("Processing alert for tracker", tracker);
                WebCheck attempt1 = (await Communication.WebCheckForKeyword(tracker.PageURL, tracker.Keyword));
                if (attempt1 == null)
                {
                    Log.Verbose("Attempt1 page is empty, not alerting");
                    return;
                }
                WebCheck attempt2 = (await Communication.WebCheckForKeyword(tracker.PageURL, tracker.Keyword));
                if (attempt2 == null)
                {
                    Log.Verbose("Attempt2 page is empty, not alerting");
                    return;
                }

                if (attempt1.KeywordExists == attempt2.KeywordExists)
                {
                    if ((attempt1.KeywordExists && !tracker.AlertOnKeywordNotExist) || (!attempt1.KeywordExists && tracker.AlertOnKeywordNotExist))
                    {
                        if (!tracker.Triggered)
                        {
                            Log.Verbose("Alerting on tracker as logic matches", tracker, attempt1.KeywordExists);
                            ProcessAlertToSend(tracker);
                        }
                    }
                    else
                    {
                        if (tracker.Triggered)
                        {
                            Log.Verbose("Resetting on tracker as logic matches", tracker, attempt1.KeywordExists);
                            ProcessAlertToReset(tracker);
                        }
                    }
                }
                else
                {
                    Log.Verbose("Keyword found [{KWFound}] and Validation [{KWValidation}] don't match, not alerting", attempt1.KeywordExists, attempt2.KeywordExists);
                }
            }
            catch (Exception ex)
            {
                Log.Error("Error on tracker: [{Tracker}]{Error}", tracker.FriendlyName, ex.Message);
                Handler.NotifyError(ex, tracker.FriendlyName);
            }
        }
Example #8
0
        public async Task <IActionResult> Create([Bind("WebCheckID,Name,Domain,Delay,CreateDate,AccountID")] WebCheck webCheck)
        {
            if (ModelState.IsValid)
            {
                var userAccount = GetUserAccountAsync().Result;
                webCheck.WebCheckID = Guid.NewGuid();
                webCheck.CreateDate = DateTime.Now;
                webCheck.AccountID  = userAccount.AccountID;

                _context.Add(webCheck);
                await _context.SaveChangesAsync();

                WebCheckHelper.CreateRecurringEvent(webCheck);

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AccountID"] = new SelectList(_context.Accounts, "AccountID", "Password", webCheck.AccountID);
            return(View(webCheck));
        }
Example #9
0
        private static void ShowMenuTestKeywordOnWebpage()
        {
            bool menuClose = false;

            while (!menuClose)
            {
                Prompts.PromptMenuAction("Test Keyword On Webpage");
                var      webpage  = Prompts.PromptQuestion("Enter the webpage URL");
                var      keyword  = Prompts.PromptQuestion("Enter the keyword");
                WebCheck webCheck = null;

                try
                {
                    webCheck = Communication.WebCheckForKeyword(webpage, keyword).WaitAndUnwrapException();
                    Console.WriteLine("The webpage that was returned was empty/blank");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error from webpage: {ex.Message}");
                }

                if (webCheck != null)
                {
                    if (webCheck.KeywordExists)
                    {
                        Console.WriteLine("The keyword was found!");
                    }
                    else
                    {
                        Console.WriteLine($"Webpage Response StatusCode: {webCheck.ResponseCode}");
                        Console.WriteLine("The keyword wasn't found on the webpage :(");
                    }
                }
                var tryAgain = Prompts.PromptYesNo("Would you like to do another test?");
                if (!tryAgain)
                {
                    menuClose = true;
                }
                Console.Clear();
            }
            Log.Information("Exited Menu TestKeywordOnWebpage");
        }
Example #10
0
        public StateViewModel(IRecordDirectoryObserver recordObserver,
                              IEventAggregator eventAggregator,
                              IAppConfiguration appConfiguration,
                              ICaptureService captureService)
        {
            _recordObserver   = recordObserver;
            _eventAggregator  = eventAggregator;
            _appConfiguration = appConfiguration;
            _captureService   = captureService;

            IsDirectoryObserving = true;
            IsCaptureModeActive  = false;

            UpdateHpyerlinkText = $"New version available on GitHub: v{WebCheck.GetWebVersion(WebCheck.VersionSourceFileUrl)}";

            _recordObserver.HasValidSourceStream
            .Subscribe(state => IsDirectoryObserving = state);

            _captureService.IsCaptureModeActiveStream
            .Subscribe(state => IsCaptureModeActive = state);
        }
Example #11
0
        //another method to handle testing a connection
        //this one's here for logging purposes and such, and is used
        //solely by the Server Manager
        private static WebCheck TestConnection(Server svr)
        {
            var value = new WebCheck();

            try
            {
                var uri = ConnectionLink(svr);

                //UIMessages.Info(uri);

                var testUrl = WebCheck.TestUrl(uri);

                value = testUrl;
            }
            catch (Exception ex)
            {
                LoggingHelpers.RecordGeneralEntry($"Couldn't connect to \"{svr.address}:{svr.port}\"");
                LoggingHelpers.RecordException(ex.Message, "ConnectionTestError");
            }

            return(value);
        }
Example #12
0
        /// <summary>
        /// Execute the given web-check and return the result.
        /// </summary>
        /// <param name="webCheck">The web-check in question.</param>
        /// <returns>Tuple with request, response and result.</returns>
        public async Task <(HttpRequest request, HttpResponse response, WebCheckResult result)> Execute(
            WebCheck webCheck)
        {
            _logger.LogDebug($"HTTP_TIMEOUT / PROBE_INTERVAL set to {Interval}");
            _logger.LogDebug(
                $"Executing web-check '{webCheck.Name}' (id: {webCheck.Id}) to url '{webCheck.Url}' with {webCheck.ResponseTests?.Count} tests.");

            try
            {
                var watch         = new Stopwatch();
                var clientRequest = webCheck.HttpRequest;

                watch.Start();
                var clientResponse = Client.SendAsync(clientRequest).Result;
                watch.Stop();

                var httpRequest  = new HttpRequest(clientRequest);
                var httpResponse = await HttpResponse.CreateFromResponse(
                    clientResponse,
                    watch.ElapsedMilliseconds);

                if (webCheck.ResponseTests == null || webCheck.ResponseTests.Count <= 0)
                {
                    _logger.LogInformation(
                        $"WebCheck '{webCheck.Name}' (id: {webCheck.Id}) has no response tests, using status-code '{httpResponse.StatusCode}'.");
                    return(httpRequest, httpResponse, new WebCheckResult
                    {
                        Result = httpResponse.IsSuccess,
                        Reasons = new[] { $"Response status code {httpResponse.StatusCode}" },
                        Duration = httpResponse.CallDuration,
                        StatusCode = httpResponse.StatusCode,
                        WebCheckId = webCheck.Id
                    });
                }

                var result  = true;
                var reasons = new List <string>();
                var logs    = new List <(string Name, IList <string> Messages)>();

                foreach (var test in webCheck.ResponseTests)
                {
                    try
                    {
                        var sw = new Stopwatch();
                        _logger.LogDebug($"Execute response test '{test.Name}'");
                        sw.Start();
                        var testResult = await _nodeServices.InvokeAsync <NodeResult>(
                            "Node/responseTest.js",
                            httpRequest,
                            httpResponse,
                            test.Script);

                        sw.Stop();
                        _logger.LogDebug(
                            $"ResponseTest '{test.Name}' returned '{testResult}' and needed {sw.ElapsedMilliseconds}ms for execution.");

                        if (testResult.Logs.Length > 0)
                        {
                            _logger.LogInformation($"ResponseTest '{test.Name}' had log messages.");
                            _logger.LogDebug(
                                $"ResponseTest '{test.Name}' wrote the following logs:\n{testResult.Logs.Join("\n")}");
                            logs.Add((test.Name, Messages: testResult.Logs));
                        }

                        if (!testResult.Result)
                        {
                            reasons.Add($"ResponseTest '{test.Name}' returned 'false'");
                        }

                        result = result && testResult.Result;
                    }
                    catch (Exception e)
                    {
                        _logger.LogWarning(
                            e,
                            $"ResponseTest '{test.Name}' of WebCheck '{webCheck.Name}' (id: {webCheck.Id}) threw an Exception.");
                        result = false;
                        reasons.Add($"ResponseTest '{test.Name}' threw an Exception: {e.Message}");
                    }
                }

                _logger.LogInformation(
                    $"WebCheck '{webCheck.Name}' (id: {webCheck.Id}): Call was successful, Test results returned {result}.");
                return(httpRequest, httpResponse, new WebCheckResult
                {
                    Result = result,
                    Reasons = reasons,
                    TestLogMessages = logs,
                    Duration = httpResponse.CallDuration,
                    StatusCode = httpResponse.StatusCode,
                    WebCheckId = webCheck.Id
                });
            }
            catch (TaskCanceledException)
            {
                _logger.LogWarning(
                    $"WebCheck '{webCheck.Name}' (id: {webCheck.Id}) ran into timeout after {Interval} seconds.");
                return(null, null, new WebCheckResult
                {
                    Result = false,
                    Reasons = new[] { $"HTTP client timeout after {Interval} seconds" },
                    Duration = Interval * 1000,
                    StatusCode = -1,
                    WebCheckId = webCheck.Id
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(
                    ex,
                    $"WebCheck '{webCheck.Name}' (id: {webCheck.Id}) produced an exception during the execution.");
                return(null, null, new WebCheckResult
                {
                    Result = false,
                    Reasons = new[] { $"Exception during execution: {ex.Message}" },
                    Duration = -1,
                    StatusCode = -1,
                    WebCheckId = webCheck.Id
                });
            }
        }
Example #13
0
        private void InsertSMSClick()
        {
            var email   = new EmailAddressAttribute();
            var website = new UrlAttribute();

            if (email.IsValid(TBoxSender))
            {
                string[] Body = TBoxBody.Split(' ');
                foreach (string word in Body)
                {
                    WebCheck = word;
                    if (website.IsValid(word) || word.Contains("www"))
                    {
                        ListAdd Quarantine = new ListAdd();
                        {
                            Quarantine.ListType = word;
                            Quarantine.Count    = "1";
                        }
                        ListType = "Q";
                        ListQuarantine.Add(Quarantine);

                        SaveToList Q = new SaveToList();

                        if (!Q.WriteToCSV(ListQuarantine, ListType))
                        {
                            MessageBox.Show("Error while saving\n" + Q.ErrorCode);
                        }
                        else
                        {
                            Q = null;
                        }

                        WebCheck = WebCheck.Replace(WebCheck, "<URL Quarantined>");
                        MessageBox.Show(WebCheck);
                        for (int x = 0; x < Body.Length; x++)
                        {
                            if (Body[x] == word)
                            {
                                Body[x] = Body[x].Replace(word, WebCheck);
                            }
                        }
                    }
                }
                TBoxBody = string.Join(" ", Body);
                MessageBox.Show(TBoxBody);

                EmailAdd AddEmail = new EmailAdd();
                {
                    AddEmail.MessageID = "E" + TBoxMID;
                    AddEmail.Sender    = TBoxSender;
                    try
                    {
                        AddEmail.Subject = "SIR " + DPickerContent.ToString();
                        check            = true;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Please Select a date");
                        check = false;
                    }
                    AddEmail.Body = CentreCode + "" + Incident + "" + TBoxBody;
                }

                if (check == true)
                {
                    ListEmail.Add(AddEmail);

                    SaveToFile save = new SaveToFile();

                    if (!save.EmailToCSV(ListEmail, MessageType))
                    {
                        MessageBox.Show("Error while saving\n" + save.ErrorCode);
                    }
                    else
                    {
                        save = null;
                    }

                    ListAdd SIRList = new ListAdd();
                    {
                        SIRList.ListType = AddEmail.Subject;
                        SIRList.Count    = "66-666-99";
                    }

                    ListType = "S";
                    ListSIR.Add(SIRList);

                    SaveToList SIR = new SaveToList();
                    if (!SIR.WriteToCSV(ListSIR, ListType))
                    {
                        MessageBox.Show("Error while saving\n" + SIR.ErrorCode);
                    }
                    else
                    {
                        SIR = null;
                    }
                    MessageBox.Show("Order saved");
                }
            }
            else
            {
                MessageBox.Show("Wrong");
            }
        }
 public WebStatusIndicator(ref WebCheck web)
 {
     this.web = web;
 }
Example #15
0
        public void CheckWebUpdate_CorrecState()
        {
            string url = "https://raw.githubusercontent.com/DevTechProfile/CapFrameX/develop/feature/rtss_client_implementation/version/Version.txt";

            Assert.IsTrue(WebCheck.IsCXUpdateAvailable(url, () => "1.3.0"));
        }