Beispiel #1
0
        /// <summary>
        /// Checks the requesting IP address in the collection
        /// and bannes the IP if required.
        /// </summary>
        private static void CheckIpAddress(string ip)
        {
            try
            {
                if (!_IpAdresses.ContainsKey(ip))
                {
                    _IpAdresses[ip] = 1;
                }
                else if (_IpAdresses[ip] == BANNED_REQUESTS)
                {
                    if (_Banned.Count > 0)
                    {
                        _Banned.Push(ip);
                    }

                    _IpAdresses.Remove(ip);
                }
                else
                {
                    _IpAdresses[ip]++;
                }
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(string.Concat(ex.Message, "-->", "DosAttackModule"));
            }
        }
Beispiel #2
0
        private void SendSensibleEarthquakeNotification(Earthquake earthquake)
        {
            try
            {
                PushNotification.PushNotification pn = new PushNotification.PushNotification();
                var devices = Repository.DbContext.RegistrationDevices.OrderBy(e => e.Date).ToList();

                //--------------------------------------------------------------------------------------

                int elementsByList = 20000;
                int numberOfLists  = (devices.Count / elementsByList) + 1;
                List <List <RegistrationDevice> > listOfLists = new List <List <RegistrationDevice> >();


                for (int i = 0; i < numberOfLists; i++)
                {
                    List <RegistrationDevice> newList = new List <RegistrationDevice>();
                    newList = devices.Skip(i * elementsByList).Take(elementsByList).ToList();
                    listOfLists.Add(newList);

                    Task task4 = new Task(() =>
                    {
                        NotificateMultipleDevices(newList, earthquake);
                    });

                    task4.Start();
                }
                //--------------------------------------------------------------------------------------
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #3
0
        public HtmlDocument GetDocument(string webSiteUrl)
        {
            try

            {
                //-------------------------------------------------
                // var urlInpres1 = "D:\\pendrive\\02\\Instituto Nacional de Prevención Sísmica.htm";
                //webSiteUrl = urlInpres1;
                //ExceptionUtility.Warn(" codigo solo para test! " + this.GetType());

                //catch a web exception
                WebRequest = new MyWebRequest(webSiteUrl);
                var asd = WebRequest.GetResponse();
                //-----------------------------------------------------------------



                // Load the html document
                HtmlWeb htmlWeb = new HtmlWeb();
                return(htmlWeb.Load(webSiteUrl));
            }

            catch (WebException webExcp)
            {
                ExceptionUtility.Error(string.Concat(webExcp.InnerException.Message, " ", this.GetType(), webSiteUrl));
                return(new HtmlDocument());
            }

            catch (Exception ex) {
                ExceptionUtility.Error(ex, this.GetType());
                return(new HtmlDocument());
            }
        }
Beispiel #4
0
        public void CollectTwitterData()
        {
            try
            {
                List <Tweet> tweets = TwitterCollector.GetTwitters();

                foreach (Tweet tweet in tweets)
                {
                    var existing = Repository.DbContext.Tweets.Where(t => t.Tweeter.Contains(tweet.Tweeter)).ToList();

                    if (existing.Count <= 0)
                    {
                        Repository.DbContext.Tweets.Add(tweet);
                    }
                    if (existing.Count >= 2)
                    {
                        var duplicatesTweets = existing.OrderByDescending(t => t.DateTime);
                        var deleteThis       = duplicatesTweets.Skip(1);
                        foreach (Tweet tw in deleteThis)
                        {
                            Repository.DbContext.Tweets.Remove(tw);
                        }
                    }
                }
                Repository.Save();
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #5
0
        public IEnumerable <Earthquake> Search(EarthquakeModel model)
        {
            try
            {
                var predicate = PredicateBuilder.True <Earthquake>();

                if (model.LocationModel.IsByCountry)
                {
                    predicate = GetLocationPredicate(predicate, model);
                    predicate = GetMagnitudePredicate(predicate, model);
                    predicate = GetDateTimePredicate(predicate, model);
                    return(this.DbContext.Set <Earthquake>()
                           .Include(e => e.Place)
                           .Include(e => e.MagnitudeType)
                           .Include(e => e.Source)
                           .AsExpandable().Where(predicate));
                }

                predicate = GetMagnitudePredicate(predicate, model);
                predicate = GetDateTimePredicate(predicate, model);

                return(model.LocationModel.NearEarthquakes
                       .AsQueryable().Where(predicate).ToList());
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(new List <Earthquake>());
            }
        }
Beispiel #6
0
        public void DeleteUnusedLogs()
        {
            try
            {
                var logs         = Repository.DbContext.MyLogs.Where(l => l.Id > 0).ToList();
                var utcNow       = GlobalWebData.ToUniversalTime();
                var utcPast24    = new DateTime(GlobalWebData.ToUniversalTime().Ticks).Add(System.TimeSpan.FromHours(System.Convert.ToDouble((24 * -1))));
                var log24        = logs.Where(l => l.Date >= utcPast24 && l.Date <= utcNow).ToList();
                var logBefore24  = logs.Except(log24);
                var logsABorrrar = logBefore24.ToList();

                if (logsABorrrar.Count > 0)
                {
                    foreach (MyLogs log in logsABorrrar)
                    {
                        MylogRepository.Delete(log);
                    }
                    MylogRepository.DetectChanges();
                    MylogRepository.Save();
                    ExceptionUtility.Info("Se borraron antiguos logs...");
                }
            }
            catch (Exception ex) {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #7
0
        private Expression <Func <Earthquake, bool> > GetLocationPredicate(Expression <Func <Earthquake, bool> > predicate, EarthquakeModel model)
        {
            try
            {
                /*decimal latitude = Convert.ToDecimal(model.LocationModel.Latitude);
                 * decimal longitude = Convert.ToDecimal(model.LocationModel.Longitude);
                 *
                 *
                 *  bool isfirstCountryParameter = true;
                 *  for (int i = 0; i < model.LocationModel.Country.Length; i++)
                 *  {
                 *      string country = model.LocationModel.Country[i].ToString();
                 *
                 *      if (country != CountryEnum.EMPTY.ToString())
                 *      {
                 *          if (isfirstCountryParameter)
                 *          {
                 *              //que de chile solo se muestre los sensibles
                 *              if (country == CountryEnum.CHILE.ToString())
                 *              {
                 *                  predicate = predicate.And(e => e.Place.Country.Contains(country) && e.IsSensible == true);
                 *              }
                 *              else if (country == CountryEnum.WORLD.ToString())
                 *              {
                 *                  predicate = predicate.And(e => e.Place.Country != string.Empty);
                 *              }
                 *              else
                 *              {
                 *                  predicate = predicate.And(e => e.Place.Country.Contains(country));
                 *              }
                 *              isfirstCountryParameter = false;
                 *          }
                 *          else
                 *          {
                 *              //que de chile solo se muestre los sensibles
                 *              if (country == CountryEnum.CHILE.ToString())
                 *              {
                 *                  predicate = predicate.Or(e => e.Place.Country.Contains(country) && e.IsSensible == true);
                 *              }
                 *              else if (country == CountryEnum.WORLD.ToString())
                 *              {
                 *                  predicate = predicate.Or(e => e.Place.Country != string.Empty);
                 *              }
                 *              else
                 *              {
                 *                  predicate = predicate.Or(e => e.Place.Country.Contains(country));
                 *              }
                 *          }
                 *      }
                 *  }*/

                return(predicate);
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(predicate);
            }
        }
Beispiel #8
0
        public bool RegisterIfNotExist(string registerId, String deviceId)
        {
            try{
                return(registrationManager.RegisterIfNotExist(registerId, deviceId));
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(false);
            }
        }
Beispiel #9
0
        public void ResetMailCount()
        {
            try
            {
                MailManagment.MailManagement.ResetCount();
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #10
0
 public IEnumerable <Tweet> GetTweets(DateTime datetTime)
 {
     try
     {
         return(this.DbContext.Tweets.Where(t => t.DateTime >= datetTime));
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(ex, this.GetType());
         return(new List <Tweet>());
     }
 }
Beispiel #11
0
 private List <string> CreateTweeterKeyWords()
 {
     try
     {
         var file = GlobalWebData.GetRootPath() + "tweeterKeyWords.xml";
         return(CreateXmlFile(file, "TweeterKeyWords", GetDefaultTweeterKeyWords()));
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(ex, this.GetType());
         return(GetDefaultTweeterKeyWords());
     }
 }
Beispiel #12
0
        public void Log(string log, string deviceId)
        {
            try
            {
                DeviceLogManager deviceLogManager = new DeviceLogManager(earthquakeRepository);
                deviceLogManager.SaveLog(log, deviceId);
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #13
0
        public bool Unregister(string deviceId)
        {
            try
            {
                return(registrationManager.Unregister(deviceId));
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(false);
            }
        }
Beispiel #14
0
 /// <summary>
 /// Creates the timer that substract a request
 /// from the _IpAddress dictionary.
 /// </summary>
 private static Timer CreateTimer()
 {
     try
     {
         Timer timer = GetTimer(REDUCTION_INTERVAL);
         timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
         return(timer);
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(string.Concat(ex.Message, "-->", "DosAttackModule"));
         return(new Timer());
     }
 }
Beispiel #15
0
        public IList <Earthquake> GetLast24HoursEarthquakes(IList <Earthquake> allEarthquakes)
        {
            try
            {
                var utcNow    = GlobalWebData.ToUniversalTime();
                var utcPast24 = new DateTime(GlobalWebData.ToUniversalTime().Ticks).Add(TimeSpan.FromHours(System.Convert.ToDouble((24 * -1))));
                return(allEarthquakes.Where(e => e.UTCDateTime >= utcPast24 && e.UTCDateTime <= utcNow).ToList());
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(new List <Earthquake>());
            }
        }
Beispiel #16
0
        public static void KeepWakeUp()
        {
            try
            {
                WebRequest request = WebRequest.Create("http://argentinasismos.com/Home/WakeUp");
                using (WebResponse resp = request.GetResponse())
                {
                }
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex.Message);
            }
        }
Beispiel #17
0
        public IList <Tweet> GetEarliesTweets(IList <Tweet> allTweets)
        {
            try
            {
                var utcNow       = GlobalWebData.ToUniversalTime();
                var utcMonthPast = new DateTime(GlobalWebData.ToUniversalTime().Ticks).Add(TimeSpan.FromHours(System.Convert.ToDouble((720 * -1))));
                return(allTweets.Where(t => t.DateTime < utcMonthPast).ToList());
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(new List <Tweet>());
            }
        }
Beispiel #18
0
        /// <summary>
        /// Creates a simple timer instance and starts it.
        /// </summary>
        /// <param name="interval">The interval in milliseconds.</param>
        private static Timer GetTimer(int interval)
        {
            try
            {
                Timer timer = new Timer();
                timer.Interval = interval;
                timer.Start();

                return(timer);
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(string.Concat(ex.Message, "-->", "DosAttackModule"));
                return(new Timer());
            }
        }
Beispiel #19
0
 public IList <Earthquake> GetEarthquakesBeforeTwoWeeks(IList <Earthquake> allEarthquakes)
 {
     try
     {
         var utcNow               = GlobalWebData.ToUniversalTime();
         var utcPastSevenDays     = new DateTime(GlobalWebData.ToUniversalTime().Ticks).Add(System.TimeSpan.FromHours(System.Convert.ToDouble((336 * -1))));
         var pastSevenDays        = allEarthquakes.Where(e => e.UTCDateTime >= utcPastSevenDays).ToList();
         var earthBeforeSevenDays = allEarthquakes.Except(pastSevenDays);
         return(earthBeforeSevenDays.ToList());
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(ex, this.GetType());
         return(new List <Earthquake>());
     }
 }
Beispiel #20
0
 private void FetchApplicationUrl()
 {
     try
     {
         HttpWebRequest request = HttpWebRequest.Create(this._applicationUrl) as HttpWebRequest;
         using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
         {
             HttpStatusCode status = response.StatusCode;
             //log status
         }
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(ex.Message);
     }
 }
Beispiel #21
0
        public void RunScheduledTasks()
        {
            try
            {
                lock (lockCollectionEarthquakes)
                {
                    earthquakeExpert.CollectData();
                }

                lock (lockNotification)
                {
                    earthquakeExpert.NotifySensibleEarthquakes();
                }

                lock (lockCollectionTweeters)
                {
                    earthquakeExpert.CollectTwitterData();
                }

                lock (lockDeleteEarthquakes)
                {
                    earthquakeExpert.DeleteEarthquakesBeforeTwoWeeks();
                }

                /*lock (lockDeleteDuplicatesEarthquakes)
                 * {
                 *  earthquakeExpert.DeleteDuplicateEarthQuakes();
                 * }*/

                lock (lockDeleteLogs)
                {
                    earthquakeExpert.DeleteUnusedLogs();
                }

                lock (lockDeleteTweeters)
                {
                    earthquakeExpert.DeleteEarliesTweeters();
                }

                ExceptionUtility.Info("ciclo completo..." + GlobalWebData.ToUniversalTime());
            }

            catch (Exception ex) {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #22
0
        public XDocument GetDocument(string webSiteUrl)
        {
            try
            {
                return(XDocument.Load(webSiteUrl));
            }
            catch (WebException webExcp)
            {
                ExceptionUtility.Error(webExcp, this.GetType());
                return(new XDocument());
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(new XDocument());
            }
        }
Beispiel #23
0
        /// <summary>
        /// Send Push Message to Device
        /// </summary>
        /// <param name="RegistrationID">RegistrationID or Token</param>
        /// <param name="Message">Message to be sent on device</param>
        /// <param name="AuthString">Authentication string</param>
        public String SendMessage(string RegistrationID, string Message /*, string AuthString*/)
        {
            string apiKey     = "AIzaSyB-F65OMBU7Uz7oFV6c8xCw2hbR5fmcaaw";
            string browserKey = "AIzaSyAUjsENtFuYc7y8JrEhAA3JV0HBJE7rtK0";

            try
            {
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
                Request.Method    = "POST";
                Request.KeepAlive = false;
                string postData  = "{ \"registration_ids\": [ \"" + RegistrationID + "\" ], \"data\": {\"message\": \"" + Message + "\"}}";
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                Request.ContentType = "application/json";
                Request.Headers.Add(HttpRequestHeader.Authorization, string.Concat("key=", browserKey));
                //-- Create Stream to Write Byte Array --//
                Stream dataStream = Request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                //-- Post a Message --//
                WebResponse    Response     = Request.GetResponse();
                HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
                if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
                {
                    var text = "Unauthorized - need new token";
                }
                else if (!ResponseCode.Equals(HttpStatusCode.OK))
                {
                    var text = "Response from web service isn't OK";
                }

                StreamReader Reader       = new StreamReader(Response.GetResponseStream());
                string       responseLine = Reader.ReadLine();
                Reader.Close();

                return(responseLine);
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(ExceptionUtility.NotificationErrorMessage);
            }
        }
Beispiel #24
0
 /// <summary>
 /// Creates the timer that removes 1 banned IP address
 /// everytime the timer is elapsed.
 /// </summary>
 /// <returns></returns>
 private static Timer CreateBanningTimer()
 {
     try
     {
         Timer timer = GetTimer(RELEASE_INTERVAL);
         timer.Elapsed += delegate {
             if (_Banned.Count > 0)
             {
                 _Banned.Pop();
             }
         };
         return(timer);
     }
     catch (Exception ex)
     {
         ExceptionUtility.Error(string.Concat(ex.Message, "-->", "DosAttackModule"));
         return(new Timer());
     }
 }
Beispiel #25
0
        private const int RELEASE_INTERVAL   = 5 * 60 * 1000; // 5 minutes

        private void context_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                string tempIp = HttpContext.Current.Request.UserHostAddress;
                string ip     = IPAddress.Parse(tempIp).ToString();
                if (_Banned.Contains(ip))
                {
                    HttpContext.Current.Response.StatusCode = 403;
                    HttpContext.Current.Response.End();
                    ExceptionUtility.Warn(string.Concat("attacking request :", ip, this.GetType()));
                }

                CheckIpAddress(ip);
            }
            catch (Exception ex) {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #26
0
        private void CollectData(string colectorName)
        {
            try
            {
                EarthquakeCollector collector = null;
                Collectors.TryGetValue(colectorName, out collector);
                var earthquakeFromColector = FilterDuplicate(collector.Collect());

                foreach (Earthquake earthquake in earthquakeFromColector)
                {
                    if (!EarthquakeExist(earthquake))
                    {
                        if (earthquake.MagnitudeType != null && earthquake.MagnitudeType.Id != Guid.Empty)
                        {
                            earthquake.MagnitudeType = Repository.DbContext.MagtitudesTypes.Where(p => p.Id == earthquake.MagnitudeType.Id).FirstOrDefault();
                        }

                        if (earthquake.Source != null && earthquake.Source.Id != Guid.Empty)
                        {
                            earthquake.Source = Repository.DbContext.Sources.Where(p => p.Id == earthquake.Source.Id).FirstOrDefault();
                        }

                        if (earthquake.Place != null && earthquake.Place.Id != Guid.Empty)
                        {
                            earthquake.Place = Repository.DbContext.Places.Where(p => p.Id == earthquake.Place.Id).FirstOrDefault();
                        }

                        Repository.DbContext.Earthquakes.Add(earthquake);
                    }
                }

                Repository.Save();
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbevex)
            {
                ExceptionUtility.Error(dbevex, this.GetType());
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #27
0
        /// <summary>
        /// Create Query String From Name Value Pair
        /// </summary>
        /// <param name="postFieldNameValue"></param>
        /// <returns></returns>
        private string GetPostStringFrom(NameValueCollection postFieldNameValue)
        {
            try
            {
                //throw new NotImplementedException();
                List <string> items = new List <string>();

                foreach (String name in postFieldNameValue)
                {
                    items.Add(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(postFieldNameValue[name])));
                }

                return(String.Join("&", items.ToArray()));
            }
            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
                return(ExceptionUtility.NotificationErrorMessage);
            }
        }
Beispiel #28
0
        private void NotificateMultipleDevices(List <RegistrationDevice> devices, Earthquake earthquake)
        {
            PushNotification.PushNotification pn = new PushNotification.PushNotification();

            foreach (var device in devices)
            {
                //------------------------Send Notification----------------------------
                var ok = pn.Android(device.RegistrationId, earthquake.GetNotificationData());
                //--------------------------------------------------------------------

                if (ok.Contains("success\":0"))
                {
                    ExceptionUtility.Error(new Exception(device.RegistrationId), this.GetType());
                    Repository.DeleteDevice(device);
                    Repository.Save();
                }
            }

            ExceptionUtility.Info(string.Concat("send notification to GCM ", GlobalWebData.ToUniversalTime()));
        }
Beispiel #29
0
        public void DeleteDuplicateEarthQuakes()
        {
            try
            {
                var all      = Repository.FindAll().ToList();
                var toDelete = GetDuplicateEarthQuakes(all);

                foreach (Earthquake earthq in toDelete)
                {
                    Repository.Delete(earthq);
                    ExceptionUtility.Warn("Borrando duplicado..." + earthq);
                }
                Repository.Save();
            }

            catch (Exception ex)
            {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }
Beispiel #30
0
        public void CollectData()
        {
            try
            {
                ResetContext();

                CollectData("EMSCEarthquakeCollectorXML");

                ResetContext();

                CollectData("InpresEarthquakeCollectorHtml");

                ResetContext();

                CollectData("SSUCHEarthquakeCollectorHtml");
            }

            catch (Exception ex) {
                ExceptionUtility.Error(ex, this.GetType());
            }
        }