예제 #1
0
        static void Main(string[] args)
        {
            // Nice docs (although Java): http://reactivex.io/RxJava/javadoc/rx/Observable.html
            // The challenge:
            // The ChangeReceiver will fire an event every time a change is received.
            // Events can be:
            // "Ignore!" -> don't do anything
            // "Change!" -> send notification to staff and customers
            // "StaffOnly!" -> send notification to staff
            // "CustomerOnly!" -> send notification to customer only
            //
            // Staff must be notified within 3 seconds.
            // Customers most be notified between 5 and 7 seconds.
            using (var pub = new ChangeReceiver("tcp://*:5555"))
            {
                Console.WriteLine("Listening...");

                var staffSender    = new NotificationSender("tcp://localhost:5556");
                var customerSender = new NotificationSender("tcp://localhost:5557");

                var obs = Observable.FromEventPattern <Tuple <Guid, string> >(pub, "ChangeRecieved").Select(ep => ep.EventArgs);
                obs.Subscribe <Tuple <Guid, string> >(Handler);
                obs.Select(t => t.Item1).Subscribe(guid => customerSender.Send(guid));

                //var err = Observable.FromEventPattern<Exception>(pub, "OnError").Select(ep => ep.EventArgs);
                //err.Subscribe<Exception>(Error);

                pub.Start();
                Console.ReadLine();
                Console.WriteLine("Closing down.");
            }
        }
예제 #2
0
        public override void OnReceive(Context context, Intent intent)
        {
            File currentSummary       = new File(context.FilesDir, CurrentSummaryFile);
            File sentSummary          = new File(context.FilesDir, SentSummaryFile);
            NotificationSender sender = new NotificationSender(context, SummaryCategory);

            if (currentSummary.Exists())
            {
                try
                {
                    string text;
                    using (StreamReader reader = new StreamReader(context.OpenFileInput(CurrentSummaryFile)))
                    {
                        text = reader.ReadToEnd();
                    }
                    Log.Debug(nameof(AlarmReceiver), text);
                    sender.PutNormalizeExtra(ExtraSummaryText, text);
                    sender.Send(NotificationType.SummaryNotification, text);
                    if (sentSummary.Exists())
                    {
                        sentSummary.Delete();
                    }
                    currentSummary.RenameTo(sentSummary);
                }
                catch (Exception e)
                {
                    Log.Error(nameof(AlarmReceiver), e.StackTrace);
                }
            }
            else
            {
                Log.Debug(nameof(AlarmReceiver), $"File {currentSummary.AbsolutePath} not exist");
            }
        }
        public void SendNotification()
        {
            // We just resend the notifications which have not been seen before by its target user
            var notifications = db.Notifications.Where(n => n.Status == NotificationStatus.NEW);


            if (notifications.Any())
            {
                foreach (var notification in notifications)
                {
                    //we want to make sure that we send notification to an active session
                    var userSessions = notification.User.Sessions.Where(s => s.State == SessionState.ACTIVE);

                    // we send the notification to all active sessions of its target user
                    foreach (var userSession in userSessions)
                    {
                        var fcmToken = userSession.FCMToken;
                        if (fcmToken != null)
                        {
                            // Here we create the notification Object based on the type of notification
                            NotificationObject notificationObject;

                            switch (notification.Type)
                            {
                            case NotificationType.ADVERTISEMENT:

                                notificationObject = new AdNotification()
                                {
                                    Id              = notification.Id,
                                    Avatar          = localDomain + notification.Avatar.ImagePath,
                                    AdvertisementId = notification.AdvertisementId,
                                    Message         = notification.Message,
                                    Title           = notification.Title
                                };
                                NotificationSender.Send(fcmToken, notificationObject);
                                break;

                            case NotificationType.CASUAL:
                                notificationObject = new CasualNotification()
                                {
                                    Id      = notification.Id,
                                    Avatar  = localDomain + notification.Avatar.ImagePath,
                                    Message = notification.Message,
                                    Title   = notification.Title
                                };
                                NotificationSender.Send(fcmToken, notificationObject);
                                break;
                            }

                            notification.Status = NotificationStatus.SENT;
                        }
                    }
                }
                db.SaveChanges();
            }
        }
예제 #4
0
 static void sh_Closed(object sender, EventArgs e)
 {
     try
     {
         Counters.IncrementCounter(CountersConstants.ExceptionMessages);
         string[] cc = SystemConfigurations.GetAppSetting("SupportMailCC").Split(',');
         NotificationSender.Send(true, true, false, SystemConfigurations.GetAppSetting("SupportMailFrom"), SystemConfigurations.GetAppSetting("SupportMailTo"), cc, "Fix Orders Service Closed", "Fix Orders Service Closed",
                                 string.Format("Fix Orders Service has been closed on machine {0} at {1}", SystemConfigurations.GetMachineIP(), DateTime.Now.ToString()), null);
     }
     catch (Exception ex)
     {
         SystemLogger.WriteOnConsoleAsync(true, "Sending Mail Error: " + ex.Message, ConsoleColor.Red, ConsoleColor.Black, true);
     }
 }
        private void WriteAndSend(NotificationSender sender, string path, FileObserverEvents events)
        {
            string message     = string.Format(GetString(Resource.String.category_system_notif_modification_detected), events, path);
            string fullMessage = $"{new Date().GetFormattedDateTime()} : {message}";

            using (StreamWriter writer = new StreamWriter(OpenFileOutput(LogFile, FileCreationMode.Append)))
            {
                writer.WriteLine(fullMessage);
            }

            using (StreamWriter writer = new StreamWriter(OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(fullMessage);
            }

            sender.PutNormalizeExtra(ExtraFilePath, path);
            sender.PutNormalizeExtra(ExtraFileEvent, events.ToString());
            sender.Send(NotificationType.WarningNotification, message);
        }
예제 #6
0
        private void OnOutgoingCall(Context context, string phoneNumber)
        {
            var telephonyManager = TelephonyManager.FromContext(context);

            if (phoneNumber == null)
            {
                Log.Error(Tag, "Can't proceed outgoing call, caller phone number is null!");
                return;
            }

            var myPhoneNumber = new string(telephonyManager.Line1Number.Where(char.IsDigit).ToArray());

            if (myPhoneNumber.Length == 0)
            {
                Log.Error(Tag, "Can't proceed outgoing call, your phone number is null!");
                return;
            }

            var         phoneNumberUtils = PhoneNumberUtil.GetInstance();
            PhoneNumber callerPhoneNumber;

            try
            {
                callerPhoneNumber =
                    phoneNumberUtils.Parse(phoneNumber, context.Resources.Configuration.Locale.Country);
            }
            catch (Exception e)
            {
                Log.Error(nameof(PhoneCallReceiver), e.Message);
                return;
            }
            var thisPhoneNumber =
                phoneNumberUtils.Parse(myPhoneNumber, context.Resources.Configuration.Locale.Country);

            if (callerPhoneNumber.CountryCode == thisPhoneNumber.CountryCode)
            {
                Log.Debug(Tag,
                          $"Same for {phoneNumberUtils.Format(callerPhoneNumber, PhoneNumberFormat.INTERNATIONAL)}," +
                          $" {phoneNumberUtils.Format(thisPhoneNumber, PhoneNumberFormat.INTERNATIONAL)}");
                return;
            }

            if (new File(context.FilesDir, PhoneUtils.ExcludedOutCountryCodesFile).Exists())
            {
                string text;
                using (var reader =
                           new StreamReader(context.OpenFileInput(PhoneUtils.ExcludedOutCountryCodesFile)))
                {
                    text = reader.ReadToEnd();
                }

                foreach (var line in text.Split())
                {
                    if (int.TryParse(line, out var lineCode) && callerPhoneNumber.CountryCode == lineCode)
                    {
                        Log.Debug(Tag, $"Found {lineCode} in excluded outgoing country codes");
                        return;
                    }
                }
            }

            var warningMessage = string.Format(
                context.GetString(Resource.String.category_phone_notification_suspicious_call_to),
                callerPhoneNumber.GetInternationalNumber());

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(PhoneUtils.SuspiciousCallsFile, FileCreationMode.Append)))
            {
                writer.WriteLine(warningMessage);
            }

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(warningMessage);
            }

            var sender = new NotificationSender(context, DataHolder.PhoneCategory);

            sender.PutNormalizeExtra(PhoneUtils.CountryCodeKey, callerPhoneNumber.CountryCode);
            sender.PutNormalizeExtra(PhoneUtils.IsOutgoingKey, true);
            sender.Send(NotificationType.WarningNotification, warningMessage);
            MainActivity.Adapter?.Refresh();
        }
예제 #7
0
        public override void OnReceive(Context context, Intent intent)
        {
            Log.Debug(nameof(ScreenUnlockReceiver), intent.Action);

            var notificationSender = new NotificationSender(context, DataHolder.ScreenLocksCategory);

            if (_mPreferences == null)
            {
                _mPreferences = PreferenceManager.GetDefaultSharedPreferences(context);
            }

            var now = new Date();

            long monitoringStartTime;

            if ((monitoringStartTime = _mPreferences.GetLong(ScreenUtils.MonitoringLastStartTime, -1)) == -1)
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(now);
                _mPreferences.Edit().PutLong(ScreenUtils.MonitoringLastStartTime, monitoringStartTime).Apply();
                using (var writer = new StreamWriter(
                           context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                {
                    writer.WriteLine($"----Monitoring u start Time: {now.GetFormattedDateTime()}----");
                }
            }
            else
            {
                monitoringStartTime = ScreenUtils.GetMonitoringStartTime(new Date(monitoringStartTime));
            }

            if (_lastDayUnlocked == -1)
            {
                int tmpDay;
                if ((tmpDay = _mPreferences.GetInt(ScreenUtils.LastUnlockDay, -1)) != -1)
                {
                    _lastDayUnlocked = tmpDay;
                    UnlockedTimes    = _mPreferences.GetInt(ScreenUtils.UnlocksToday, 0);
                }
                else
                {
                    _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                    _mPreferences.Edit().PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked).Apply();
                }
            }

            if (_unlockMillis == null)
            {
                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();
            }

            if (TimeUnit.Milliseconds.ToDays(now.Time - monitoringStartTime) >= 1)
            {
                var unlocksToPut = UnlockedTimes;
                int u;

                if ((u = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", -1)) != -1)
                {
                    unlocksToPut = (int)Math.Ceiling((u + unlocksToPut) / 2d);
                }

                var tmpDay = _lastDayUnlocked;
                _lastDayUnlocked = Calendar.Instance.Get(CalendarField.DayOfWeek);
                UnlockedTimes    = 1;

                var thisDay = _mPreferences.GetInt($"{ScreenUtils.UnlocksDayNumber}{_lastDayUnlocked}", 0);
                _todayNormalSpeedValue = Math.Max(
                    _abnormalUnlockMinCount,
                    (int)(thisDay * _abnormalUnlockPercentage / 100d));
                _unlockMillis = new List <long>();

                _mPreferences.Edit()
                .PutInt($"{ScreenUtils.UnlocksDayNumber}{tmpDay}", unlocksToPut)
                .PutInt(ScreenUtils.LastUnlockDay, _lastDayUnlocked)
                .PutLong(ScreenUtils.MonitoringLastStartTime, ScreenUtils.GetMonitoringStartTime(now))
                .PutInt(ScreenUtils.UnlocksToday, UnlockedTimes)
                .PutInt(ScreenUtils.UnlocksNewNormalCount, -1)
                .Apply();

                MainActivity.Adapter?.Refresh();
                return;
            }

            Log.Debug("AbScreenReceiver",
                      $"Not new day. Was {new Date(monitoringStartTime).GetFormattedDateTime()}, now {now.GetFormattedDateTime()}");

            _mPreferences.Edit().PutInt(ScreenUtils.UnlocksToday, ++UnlockedTimes).Apply();

            var mode = 0;

            if (UnlockedTimes > GetNormalUnlocksCount(_mPreferences) * 1.1)
            {
                mode = 1;
            }

            _abnormalUnlockInterval = _mPreferences.GetInt(AbnormalUnlocksTimeInterval, _abnormalUnlockInterval);

            if (_unlockMillis.Count > _todayNormalSpeedValue)
            {
                var s = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);

                if (s <= _abnormalUnlockInterval && s > 0)
                {
                    mode = 2;
                    using (var writer = new StreamWriter(
                               context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                    {
                        writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                        foreach (var unlock in _unlockMillis)
                        {
                            writer.WriteLine($"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                        }

                        writer.WriteLine("-----End1-----");
                    }
                }
                else
                {
                    var  tmpList = new List <long>();
                    long sec;
                    foreach (var time in _unlockMillis)
                    {
                        sec = TimeUnit.Milliseconds.ToSeconds(now.Time - time);
                        if (sec <= _abnormalUnlockInterval && sec > 0)
                        {
                            tmpList.Add(time);
                        }
                    }

                    _unlockMillis = tmpList;
                    sec           = TimeUnit.Milliseconds.ToSeconds(now.Time - _unlockMillis[0]);
                    if (_unlockMillis.Count > _todayNormalSpeedValue && sec <= _abnormalUnlockInterval && sec > 0)
                    {
                        mode = 2;
                        using (var writer = new StreamWriter(
                                   context.OpenFileOutput(DebugFile, FileCreationMode.Append)))
                        {
                            writer.WriteLine($"----Time: {new Date().GetFormattedDateTime()}----");
                            foreach (var unlock in _unlockMillis)
                            {
                                writer.WriteLine(
                                    $"Unlock at {new Date(unlock).GetFormattedDateTime()}, val = {unlock}");
                            }

                            writer.WriteLine("-----End2-----");
                        }
                    }
                }
            }

            _unlockMillis.Add(now.Time);

            string notificationText;

            switch (mode)
            {
            case 1:
                Status           = ScreenStatus.Many;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_daily_overflow),
                                  UnlockedTimes, NormalCount);
                notificationSender.PutNormalizeExtra(ScreenUtils.UnlocksNewNormalCount,
                                                     (int)(UnlockedTimes * 1.2));

                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            case 2:
                var tmpInterval = (int)(.9 * _abnormalUnlockInterval);
                if (tmpInterval >= _abnormalUnlockInterval)
                {
                    if (tmpInterval > 1)
                    {
                        tmpInterval--;
                    }
                }

                Status           = ScreenStatus.Speed;
                notificationText =
                    string.Format(context.GetString(Resource.String.category_screen_notif_west_fast_hand),
                                  _unlockMillis.Count,
                                  TimeUnit.Milliseconds.ToSeconds(_unlockMillis.Last() - _unlockMillis.First()));

                notificationSender.PutNormalizeExtra(AbnormalUnlocksTimeInterval, tmpInterval);
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                break;

            default:
                Status = ScreenStatus.OK;
                CategoriesAdapter.Refresh(DataHolder.ScreenCategory);
                return;
            }

            using (var writer =
                       new StreamWriter(context.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
            {
                writer.WriteLine(notificationText);
            }

            notificationSender.Send(NotificationType.WarningNotification, notificationText);
        }
예제 #8
0
        protected void OnStartInternally(object arguments)
        {
            string[] args = (string[])arguments;

            try
            {
                /*if (!IsAdministrator())
                 * {
                 *  // Restart program and run as admin
                 *  var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                 *  ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
                 *  startInfo.Verb = "runas";
                 *  System.Diagnostics.Process.Start(startInfo);
                 *  Environment.Exit(0);
                 *  return;
                 * }*/



                // check multiple processes
                //commented by khazbak to avoid requirement to start in admin mode

                /*
                 * if (bool.Parse(SystemConfigurations.GetAppSetting("CheckMultipleInstances")))
                 * {
                 *  string currProcName = Process.GetCurrentProcess().ProcessName;
                 *  int currProcID = Process.GetCurrentProcess().Id;
                 *  Process[] processes = Process.GetProcessesByName(currProcName);
                 *  if (processes.Length > 1)
                 *  {
                 *      foreach (Process p in processes)
                 *      {
                 *          if (p.Id != currProcID)
                 *          {
                 *              int id = p.Id;
                 *              p.Kill();
                 *              SystemLogger.WriteOnConsoleAsync(true, "Process has been killed ID: " + id, ConsoleColor.Gray, ConsoleColor.White, false);
                 *          }
                 *      }
                 *  }
                 * }*/

                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

                SystemLogger.LogEventAsync("Starting FIX Service...");

                try
                {
                    if (bool.Parse(SystemConfigurations.GetAppSetting("ReinitializeCounters")))
                    {
                        Counters.ReInitialize();
                    }
                    else
                    {
                        Counters.Initialize();
                    }
                }
                catch (Exception ex)
                {
                    SystemLogger.WriteOnConsoleAsync(true, "Error initializing counters, Error: " + ex.ToString(), ConsoleColor.Red, ConsoleColor.Black, true);
                }


                DatabaseMethods db = new DatabaseMethods();
                if (!db.IsTodaySequenceReset()) // reset the counters only if the service starts for first time today
                {
                    Counters.ResetCounters();
                }
                // Check queue existance
                if (bool.Parse(SystemConfigurations.GetAppSetting("CheckQueueExistance")))
                {
                    CheckAndSetPermissionsToQueues();
                }
                FixExchangesInfo.Initialize();
                Currencies.Initialize();
                StocksDefinitions.Initialize();
                Lookups.Initialize();
                string seqFilePath = SystemConfigurations.GetAppSetting("SequenceFilePath");
                if (!db.IsTodaySequenceReset())
                {
                    SystemLogger.LogEventAsync("Resetting FIX sequence..");
                    db.UpdateTodaySequenceReset();
                    SystemLogger.LogEventAsync("Sequence reset successfully");
                    //try
                    //{
                    //    System.IO.File.Delete(seqFilePath);
                    //}
                    //catch (Exception ex)
                    //{
                    //    Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                    //    SystemLogger.WriteOnConsoleAsync(true, "Deleting Sequence File Error: " + ex.Message, ConsoleColor.Red, ConsoleColor.Black, true);
                    //}
                }


                Router responsesRouter = new Router(typeof(ResponsesProcessor), int.Parse(SystemConfigurations.GetAppSetting("ResponsesRouterProcessorsNum")));

                m_FixSessionStatusChangedDelegate = new FixSessionStatusChangedDelegate(OnFixStatusChange);


                bool AllowMcsdAllocation = Convert.ToBoolean(SystemConfigurations.GetAppSetting("AllowMcsdAllocation")); // maghrabi

                if (AllowMcsdAllocation)                                                                                 //MCSD
                {
                    Router mcsdResponsesRouter = new Router(typeof(ResponsesProcessorMcsd), int.Parse(SystemConfigurations.GetAppSetting("McsdResponsesRouterProcessorsNum")));
                    McsdGatwayManager.Initialize(mcsdResponsesRouter); // maghrabi
                    McsdGatwayManager.LoginToMCSD();                   // maghrabi
                }

                string fixClientSettings = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixClientSettingsFile");
                string fixServerSettings = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixServerSettingsFile");
                MarketFixClient.Initialize(fixClientSettings, responsesRouter, m_FixSessionStatusChangedDelegate);
                SvcFixServer.InitializeServer(fixServerSettings);
                OrdersManager.Initialize();
                Sessions.Initialize();
                //RepSessions.Initialize();
                InitializeService();

                if (_resetSequenceNumber)
                {
                    //  MarketFixClient.ResetSequence();
                }

                MarketFixClient.Logon();



                SystemLogger.WriteOnConsoleAsync(true, "Awaiting for Fix server response ...", ConsoleColor.Yellow, ConsoleColor.Black, false);
                System.Windows.Forms.Application.Run(new frmMonitor()); //maghrabi
                //while (true) { Console.ReadKey(); }
                //StopService();
            }
            catch (Exception ex)
            {
                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                SystemLogger.WriteOnConsoleAsync(true, "Main Error: " + ex.ToString(), ConsoleColor.Red, ConsoleColor.Black, true);

                try
                {
                    string[] cc = SystemConfigurations.GetAppSetting("SupportMailCC").Split(',');
                    NotificationSender.Send(true, true, false, SystemConfigurations.GetAppSetting("SupportMailFrom"), SystemConfigurations.GetAppSetting("SupportMailTo"), cc, "Fix Service Down", "Fix Service Down",
                                            string.Format("Service startup error state on machine {0} at {1}, Error : {2}", SystemConfigurations.GetMachineIP(), DateTime.Now.ToString(), ex.ToString()), null);
                }
                catch (Exception inex)
                {
                    Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                    SystemLogger.WriteOnConsoleAsync(true, "Sending Mail Error: " + inex.Message, ConsoleColor.Red, ConsoleColor.Black, false);
                }

                //Console.ReadKey();
            }
        }
예제 #9
0
        public static async void GetLastLocationFromDevice()
        {
            if (_fusedLocationProviderClient == null)
            {
                Log.Debug("LastAbLocation", "fu is null!");
                return;
            }

            var location = await _fusedLocationProviderClient.GetLastLocationAsync();

            if (location == null)
            {
                return;
            }
            var res            = new float[2];
            var bigDestination = true;
            var entered        = false;

            if (new File(mContext.FilesDir, LocationCoordinatesFile).Exists())
            {
                using (var reader =
                           new StreamReader(mContext.OpenFileInput(LocationCoordinatesFile)))
                {
                    foreach (var line in reader.ReadToEnd().Split("\n"))
                    {
                        if (!line.Contains("Latitude"))
                        {
                            continue;
                        }

                        var latString = line.Substring(line.AfterIndex("Latitude = "),
                                                       line.IndexOf(", Long") - line.AfterIndex("Latitude = "));
                        var    longString = line.Substring(line.AfterIndex("Longitude = "));
                        double latDouble;
                        double longDouble;
                        try
                        {
                            latDouble  = double.Parse(latString);
                            longDouble = double.Parse(longString);
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        Location.DistanceBetween(latDouble,
                                                 longDouble, location.Latitude, location.Longitude, res);
                        entered = true;
                        if (res[0] < 10 * 1000)
                        {
                            bigDestination = false;
                            break;
                        }
                    }
                }
            }

            if (entered && bigDestination)
            {
                var notPrevious = true;
                if (PreviousLocation != null)
                {
                    var prevRes = new float[2];
                    Location.DistanceBetween(PreviousLocation.Latitude,
                                             PreviousLocation.Longitude, location.Latitude, location.Longitude, prevRes);
                    if (prevRes[0] < 500)
                    {
                        notPrevious = false;
                    }
                }
                if (notPrevious)
                {
                    var sender = new NotificationSender(mContext, DataHolder.LocationCategory);
                    sender.PutNormalizeExtra(LocationLatitude, location.Latitude);
                    sender.PutNormalizeExtra(LocationLongitude, location.Longitude);

                    var distance =
                        string.Format(mContext.GetString(Resource.String.category_location_notif_big_distance),
                                      res[0] / 1000);

                    sender.Send(NotificationType.WarningNotification, distance);
                    using (StreamWriter writer = new StreamWriter(mContext.OpenFileOutput(AlarmReceiver.CurrentSummaryFile, FileCreationMode.Append)))
                    {
                        writer.WriteLine(distance);
                    }

                    PreviousLocation = location;
                    DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level = DataHolder.CheckStatus.Dangerous;
                }
            }
            else
            {
                if (DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level == DataHolder.CheckStatus.Dangerous)
                {
                    DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Level = DataHolder.CheckStatus.Warning;
                }
            }

            if (!new File(mContext.FilesDir, LocationCoordinatesFile).Exists())
            {
                using (var writer =
                           new StreamWriter(mContext.OpenFileOutput(LocationCoordinatesFile,
                                                                    FileCreationMode.Private)))
                {
                    writer.WriteLine("Known locations:");
                    writer.WriteLine($"Latitude = {location.Latitude}, Longitude = {location.Longitude}");
                }
            }

            DataHolder.CategoriesDictionary[DataHolder.LocationCategory].Data = FormatLocation(mContext, location);
            if (MainActivity.Adapter != null)
            {
                int pos = MainActivity.Adapter.categories.FindIndex(s => s == DataHolder.LocationCategory);
                MainActivity.Adapter.Refresh(pos);
            }
        }