Esempio n. 1
0
        // Store an ip in Database
        private async Task <string> AddIpDetailsToDb(string ip, IPDetails details)
        {
            var item = new Api.Entities.IpDetail
            {
                IpAddress = ip,
                City      = details.City,
                Continent = details.Continent,
                Country   = details.Country,
                Latitude  = (float)details.Latitude,
                Longitude = (float)details.Longitude
            };

            _dbContext.IpDetails.Add(item);

            try
            {
                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                return($"Something bad has happened while updating db. {ex}");
            }

            return($"Ip details inserted successfully.");
        }
Esempio n. 2
0
        // Update an IP details record in the database. Using IP as identifier
        public async Task <IPDetails> UpdateAsync(IPDetails details)
        {
            IPDetailsEntity        entity;
            List <IPDetailsEntity> iPDetailsEntitiesList = await repository.FindByIPAsync(details.IP);

            if (iPDetailsEntitiesList.Any())
            {
                // Found one
                if (iPDetailsEntitiesList.Count == 1)
                {
                    entity           = iPDetailsEntitiesList.First();
                    entity.City      = details.City;
                    entity.Continent = details.Continent;
                    entity.Country   = details.Country;
                    entity.Latitude  = details.Latitude;
                    entity.Longitude = details.Longitude;

                    repository.UpdateAsync(entity);

                    return(details);
                }
                else    // Found multiple. Irregular behaviour as IP should be unique
                {
                    throw new DuplicateIPAddressException(String.Format("Duplicate detected for IP: {0}", details.IP));
                }
            }
            else
            {
                throw new Exception($"IP details are missing for IP: {details.IP}");
            }
        }
Esempio n. 3
0
        public async Task UpdateAsync_ShouldUpdate_WhenExists()
        {
            // Arrange
            string ip        = "10.10.10.10";
            string city      = "Naxxar";
            string continent = "Europe";
            string country   = "Malta";
            double longitude = 1.123;
            double latitude  = 1.123;
            List <IPDetailsEntity> iPDetailsEntities = new List <IPDetailsEntity>()
            {
                new IPDetailsEntity()
                {
                    Id        = 1,
                    IP        = ip,
                    City      = city,
                    Continent = continent,
                    Country   = country,
                    Latitude  = latitude,
                    Longitude = longitude,
                },
                new IPDetailsEntity()
                {
                    Id        = 2,
                    IP        = "20.20.20.20",
                    City      = city,
                    Continent = continent,
                    Country   = country,
                    Latitude  = latitude,
                    Longitude = longitude,
                }
            };
            IPDetailsEntity inputIPDetailsEntity = new IPDetailsEntity()
            {
                Id        = 1,
                IP        = ip,
                City      = "Mosta",
                Continent = continent,
                Country   = country,
                Latitude  = latitude,
                Longitude = longitude,
            };
            IPDetails inputIPDetails = IPDetailsMapper.ToModel(inputIPDetailsEntity);


            // Expected
            List <IPDetailsEntity> expectedIPDetails = new List <IPDetailsEntity>()
            {
                inputIPDetailsEntity
            };

            _ipManagerRepoMock.Setup(x => x.FindByIPAsync(ip)).ReturnsAsync(expectedIPDetails);
            _ipManagerRepoMock.Setup(x => x.UpdateAsync(inputIPDetailsEntity)).Returns(inputIPDetailsEntity);

            // Act
            var details = await _sut.UpdateAsync(inputIPDetails);

            // Assert
            Assert.AreEqual(inputIPDetails, details);
        }
Esempio n. 4
0
        public async Task <IPDetails> Execute(string ip)
        {
            var dbIpDetails    = new IPDetails();
            var details        = new IPDetails();
            var cacheIpDetails = this.FetchIpDetailsFromCache(ip);

            if (cacheIpDetails == null)
            {
                dbIpDetails = await this.FetchIpDetailsFromDb(ip);

                if (dbIpDetails != null)
                {
                    return(dbIpDetails);
                }
            }
            else
            {
                return(cacheIpDetails);
            }

            if (cacheIpDetails == null && dbIpDetails == null)
            {
                IIPInfoProvider ipProvider = IPInfoProviderFactory.GetProvider();
                details = await ipProvider.GetDetails(ip);

                // Store data to Db
                await this.AddIpDetailsToDb(ip, details);

                // Store data to cache
                this.AddIpDetailsToCache(ip, details);
            }

            return(details);
        }
Esempio n. 5
0
        private void UpdateCache(string ip, IPDetails details)
        {
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                                    .SetSlidingExpiration(TimeSpan.FromMinutes(cacheExpirationMins));

            _cache.Set(ip, details, cacheEntryOptions);
        }
Esempio n. 6
0
        /// <summary>
        /// Get the User IP Locator
        /// </summary>
        /// <param name="ipAddress">
        /// The IP Address.
        /// </param>
        /// <returns>
        /// The <see cref="IDictionary"/>.
        /// </returns>
        public IDictionary <string, string> GetUserIpLocator(string ipAddress)
        {
            if (ipAddress.IsNotSet())
            {
                return(null);
            }

            var userIpLocator = new IPDetails().GetData(
                ipAddress,
                "text",
                false,
                YafContext.Current.CurrentForumPage.Localization.Culture.Name,
                string.Empty,
                string.Empty);

            if (userIpLocator == null)
            {
                return(null);
            }

            if (userIpLocator["StatusCode"] == "OK")
            {
                return(userIpLocator);
            }

            this.Get <ILogger>().Log(
                null,
                this,
                $"Geolocation Service reports: {userIpLocator["StatusMessage"]}",
                EventLogTypes.Information);

            return(null);
        }
Esempio n. 7
0
        public async Task <IPDetails> Execute <T>(string ip) where T : new()
        {
            var client    = new RestClient();
            var ipDetails = new IPDetails();

            client.BaseUrl = new Uri(baseUri);
            var request = new RestRequest();

            request.AddParameter("IpAddress", ip, ParameterType.UrlSegment);
            request.Resource = "{IpAddress}";

            request.AddParameter("access_key", _accessKey);

            try
            {
                var response = await client.ExecuteAsync <T>(request);

                ipDetails = this.DeserializeJsonResponse(response.Content);

                return(ipDetails);
            }
            catch (Exception ex)
            {
                throw new IPServiceNotAvailableException(ex.Message, ex.InnerException);
            }
        }
Esempio n. 8
0
        public async Task <Models.IPDetails> GetData(string ip)
        {
            Models.IPDetails result = null;

            string uri = $"{_appSettings.ApiBaseUrl}/{ip}?access_key={_appSettings.ApiAccessKey}";

            _cache.TryGetValue(ip, out result);
            if (result == null)
            {
                IPDetails item = _dataProvider.GetIPDetails(ip);
                result = _mapper.Map <Models.IPDetails> (item);
                if (result != null)
                {
                    _cache.Set(ip, result, TimeSpan.FromSeconds(60));
                }
                else
                {
                    var consumerFactory            = new Lib.Service.IIPInfoProviderFactory();
                    var consumer                   = consumerFactory.Create();
                    Lib.Service.IIPDetails details = await consumer.GetDetails(uri);

                    if (details != null)
                    {
                        result = _mapper.Map <Models.IPDetails> (details);
                        IPDetails newrecord = _mapper.Map <IPDetails> (details);
                        newrecord.Ip = ip;
                        _dataProvider.InsertIPDetails(newrecord);
                        _cache.Set(ip, result, TimeSpan.FromSeconds(60));
                    }
                }
            }
            return(result);
        }
Esempio n. 9
0
 public static Continent ToContinent(this IPDetails ipDetails)
 {
     return(new Continent
     {
         Name = ipDetails.Continent
     });
 }
Esempio n. 10
0
 public static City ToCity(this IPDetails ipDetails)
 {
     return(new City
     {
         Name = ipDetails.City
     });
 }
Esempio n. 11
0
 public static Country ToCountry(this IPDetails ipDetails)
 {
     return(new Country
     {
         Name = ipDetails.Country
     });
 }
Esempio n. 12
0
        public async Task SaveAsync_ShouldReturnException_WhenExists()
        {
            // Arrange
            string    ip             = "30.30.30.30";
            string    city           = "Naxxar";
            string    continent      = "Europe";
            string    country        = "Malta";
            double    longitude      = 1.123;
            double    latitude       = 1.123;
            IPDetails inputIPDetails = new IPDetails()
            {
                IP        = ip,
                City      = city,
                Continent = continent,
                Country   = country,
                Latitude  = latitude,
                Longitude = longitude,
            };
            IPDetailsEntity inputIPDetailsEntity = IPDetailsMapper.ToEntity(inputIPDetails);

            // Expected
            List <IPDetailsEntity> expectedIPDetails = new List <IPDetailsEntity>()
            {
                inputIPDetailsEntity
            };

            _ipManagerRepoMock.Setup(x => x.FindByIPAsync(ip)).ReturnsAsync(expectedIPDetails);
            _ipManagerRepoMock.Setup(x => x.AddAsync(inputIPDetailsEntity)).ReturnsAsync(inputIPDetailsEntity);

            // Act
            var details = await _sut.SaveAsync(inputIPDetails);

            // Assert
            Assert.AreEqual(inputIPDetails, details);
        }
Esempio n. 13
0
        private async Task InsertIPDetails(IPDetails details, string ip)
        {
            IPDetailsExtended model = new IPDetailsExtended(details, ip);

            await _ctx.IPDetails.AddAsync(model).ConfigureAwait(false);

            await _ctx.SaveChangesAsync();
        }
 public IPProfile(IPDetails details)
 {
     city      = details.City;
     country   = details.Country;
     continent = details.Continent;
     latitude  = details.Latitude;
     longitude = details.Longitude;
 }
Esempio n. 15
0
        private async Task SaveInDB(string ip, IPDetails details)
        {
            IPDetailsDTO det = details.ToDetailsDTO(ip);

            await _ipDetailsRepository.Insert(det);

            await _uow.Save();
        }
Esempio n. 16
0
 private void SaveInCache(string ip, IPDetails details)
 {
     if (!_cache.TryGetValue(ip, out IPDetails cacheEntry))
     {
         var cacheEntryOptions = new MemoryCacheEntryOptions()
                                 .SetSlidingExpiration(TimeSpan.FromMinutes(cacheExpirationMins));
         _cache.Set(ip, details, cacheEntryOptions);
     }
 }
Esempio n. 17
0
        public async Task <Ip> AddIpAsync(IPDetails clientIpDetail, string ipAddress)
        {
            var ipDetail = await IpDetails(clientIpDetail, ipAddress);

            await _dbContext.IpAddressess.AddAsync(ipDetail);

            await _dbContext.SaveChangesAsync();

            return(ipDetail);
        }
Esempio n. 18
0
        public void UpdateIPDetails(IPDetails details)
        {
            var jsonObj = JsonConvert.DeserializeObject <Dictionary <string, IPDetails> > (System.IO.File.ReadAllText(_appSettings.FileDbName));

            jsonObj.Remove(details.Ip);
            jsonObj.Add(details.Ip, details);
            string newJsonResult = JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);

            System.IO.File.WriteAllText(_appSettings.FileDbName, newJsonResult);
        }
Esempio n. 19
0
 public IPDetailsExtended(IPDetails details, string ip)
 {
     Ip             = ip;
     Created        = DateTime.UtcNow;
     Latitude       = details.Latitude;
     Longitude      = details.Longitude;
     Continent_name = details.Continent_name;
     Country_name   = details.Country_name;
     City           = details.City;
 }
Esempio n. 20
0
        // Store an ip in cache
        private string AddIpDetailsToCache(string ip, IPDetails details)
        {
            ObjectCache     cache  = MemoryCache.Default;
            CacheItemPolicy policy = new CacheItemPolicy();

            policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0);
            cache.Set(ip, details, policy);

            return($"Ip details inserted successfully.");
        }
        public IPDetailsModel GetByIPAddress(string ip)
        {
            IPDetailsModel result;

            try
            {
                _cacheLock.Wait();
                if (!_cache.TryGetValue(key: ip, out result))
                {
                    _logger.LogDebug($"Did not find ip: {ip} in cache.");
                    result = _repository.GetByIPAddress(ip);
                    if (result != null)
                    {
                        _cache.Set(key: result.IP, value: result, options: _memoryCacheEntryOptions);
                        _logger.LogDebug($"Found ip: {ip} in database");
                        return(result);
                    }

                    _logger.LogDebug($"Did not find ip: {ip} in database. Will try to get it via the IPStack API.");
                    IPDetails dets = _IIPInfoProvider.GetDetails(ip);
                    result = new IPDetailsModel()
                    {
                        City             = dets.City,
                        Continent        = dets.Continent,
                        Country          = dets.Country,
                        IP               = ip,
                        Latitude         = dets.Latitude,
                        Longitude        = dets.Longitude,
                        DateCreated      = DateTime.UtcNow,
                        DateLastModified = DateTime.UtcNow
                    };

                    Task <IPDetailsModel> ipDetailsModelAddTask = new Task <IPDetailsModel>(() =>
                    {
                        return(AddAsync(result).Result);
                    });

                    ipDetailsModelAddTask.RunSynchronously();

                    return(ipDetailsModelAddTask.Result);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"Could not get ip: {ip} in any of the three ways possible (IPStack API, Caching or Repository). Exception message: {ex.Message}");
                throw ex;
            }
            finally
            {
                _cacheLock.Release();
            }

            _logger.LogDebug($"Found ip: {ip} in memory cache.");
            return(result);
        }
 public void SaveIPDetails(IPDetails details)
 {
     if (GetIPDetails(details.Ip) != null)
     {
         UpdateIPDetails(details);
     }
     else
     {
         InsertIPDetails(details);
     }
 }
Esempio n. 23
0
        public IPDetails GetIPDetails(string ip)
        {
            IPDetails result    = null;
            var       ipDetails = JsonConvert.DeserializeObject <Dictionary <string, IPDetails> > (System.IO.File.ReadAllText(_appSettings.FileDbName));

            if (ipDetails != null && ipDetails.ContainsKey(ip))
            {
                result = ipDetails[ip];
            }
            return(result);
        }
        public async Task <ActionResult <Location> > SearchLocation([FromBody] IPDetails ip)
        {
            var location = await _locationService.SearchIpLocation(ip);

            if (location == null)
            {
                return(BadRequest("Data not found."));
            }

            return(Ok(location));
        }
Esempio n. 25
0
 public static Ip ToIp(this IPDetails ipDetails, string ipAddress, int cityId, int countryId, int continentId)
 {
     return(new Ip
     {
         CityId = cityId,
         CountryId = countryId,
         ContinentId = continentId,
         Latitude = ipDetails.Latitude,
         Longitude = ipDetails.Longitude,
         IpAddress = ipAddress,
     });
 }
Esempio n. 26
0
 public static IPDetailsEntity ToEntity(IPDetails model)
 {
     return(new IPDetailsEntity()
     {
         IP = model.IP,
         City = model.City,
         Continent = model.Continent,
         Country = model.Country,
         Latitude = model.Latitude,
         Longitude = model.Longitude
     });
 }
Esempio n. 27
0
        private async Task <Ip> IpDetails(IPDetails clientIpDetail, string ipAddress)
        {
            var continent = await GetOrAddContinent(clientIpDetail);

            var country = await GetOrAddCountry(clientIpDetail);

            var city = await GetOrAddCity(clientIpDetail);

            var ip = clientIpDetail.ToIp(ipAddress, city.Id, country.Id, continent.Id);

            return(ip);
        }
Esempio n. 28
0
        // Add new IP details in database
        public async Task <IPDetails> SaveAsync(IPDetails details)
        {
            List <IPDetailsEntity> existingIPDetails = await repository.FindByIPAsync(details.IP);

            if (existingIPDetails.Any())
            {
                throw new Exception("IP already exists within the database");
            }

            await repository.AddAsync(IPDetailsMapper.ToEntity(details));

            return(details);
        }
Esempio n. 29
0
        public static IPDetailsDTO ToDetailsDTO(this IPDetails model, string ip)
        {
            IPDetailsDTO details = new IPDetailsDTO
            {
                IP        = ip,
                City      = model.City,
                Continent = model.Continent,
                Country   = model.Country,
                Latitude  = model.Latitude,
                Longitude = model.Longitude
            };

            return(details);
        }
Esempio n. 30
0
        private IPDetails DeserializeJsonResponse(string json)
        {
            dynamic data = JObject.Parse(json);

            var ipDetails = new IPDetails
            {
                City      = (string)data.city,
                Continent = (string)data.continent_name,
                Country   = (string)data.country_name,
                Latitude  = (double)data.latitude,
                Longitude = (double)data.longitude
            };

            return(ipDetails);
        }