public static KeyValuePair<string, string> GetCodeFromIP(string ipaddress)
        {
            var databasePath = Sitecore.Configuration.Settings.GetSetting(Constants.Settings.MaxMindDatabasePath);
            var foundCountry = new KeyValuePair<string, string>();

            try
            {
                //First try and get the response that matches the IP from cache
                var countryResponse = CacheHelper.RedirectCache.GetObject(ipaddress) as CountryResponse;

                if (countryResponse != null)
                {
                    foundCountry = new KeyValuePair<string, string>(countryResponse.Continent.Code, countryResponse.Country.IsoCode);
                }

                //Else, let's grab it from the database
                using (var reader = new DatabaseReader(databasePath))
                {
                    var dbResponse = reader.Country(ipaddress);
                    //Add to cache
                    CacheHelper.RedirectCache.SetObject(ipaddress, dbResponse);
                    foundCountry = new KeyValuePair<string, string>(dbResponse.Continent.Code, dbResponse.Country.IsoCode);
                }
            }
            catch (Exception error)
            {
                Log.Error(string.Format("[SharedSource.RedirectModule.MaxMind.DatabaseHelper] {0}", error.Message), typeof(DatabaseHelper));
            }

            return foundCountry;
        }
        public static string GetCountry(string ClientIP)
        {
            //shortcut for local
            if (ClientIP == "127.0.0.1")
            {
                return "US";
            }

            // future licensed webservice call
            //int _userId = int.Parse(Sitecore.Configuration.Settings.GetSetting(Constants.GeoIPLookup.GeoIPUserId));
            //string _licenseKey = Sitecore.Configuration.Settings.GetSetting(Constants.GeoIPLookup.GeoIPLicenseKey);

            //var client = new WebServiceClient(_userId, _licenseKey);
            //var omni = client.Country(ClientIP);

            //return omni.Country.IsoCode;

            // temporary free database
            string _database = Sitecore.Configuration.Settings.GetSetting(Constants.GeoIPLookup.GeoIPDatabaseName);
            string _dataFolder = Sitecore.Configuration.Settings.DataFolder;


            try
            {
                var reader = new DatabaseReader(_dataFolder + "\\" + _database);

                var country = reader.Country(ClientIP);
                return country.Country.IsoCode;
            }
            catch (Exception)
            {
                return "US";
            }
            
        }
 public void TestCountry()
 {
     using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Country-Test.mmdb")))
     {
         var resp = reader.Country("81.2.69.160");
         Assert.That(resp.Country.IsoCode, Is.EqualTo("GB"));
     }
 }
        public void InvalidCountryMethodForCityDatabase_ExceptionThrown()
        {
            using var reader = new DatabaseReader(_cityDatabaseFile);
            var exception = Record.Exception(() => reader.Country("10.10.10.10"));

            Assert.NotNull(exception);
            Assert.Contains("A GeoIP2-City database cannot be opened with the", exception.Message);
            Assert.IsType <InvalidOperationException>(exception);
        }
Example #5
0
 public string CountryIsoByIp(string ip)
 {
     try
     {
         var response = reader.Country(ip);
         if (response != null)
         {
             return(response.Country.IsoCode.ToLowerInvariant());
         }
         else
         {
             return("NA");
         }
     }
     catch (Exception e)
     {
         return("NA");
     }
 }
        public void Country_ValidResponse()
        {
            using var reader = new DatabaseReader(_countryDatabaseFile);
            var response = reader.Country("81.2.69.160");

            Assert.Equal("GB", response.Country.IsoCode);
            Assert.False(response.Country.IsInEuropeanUnion);
            Assert.False(response.RegisteredCountry.IsInEuropeanUnion);
            Assert.False(response.RepresentedCountry.IsInEuropeanUnion);
            Assert.Equal("81.2.69.160/27", response.Traits.Network?.ToString());
        }
 public void Country_ValidResponse()
 {
     using (var reader = new DatabaseReader(_countryDatabaseFile))
     {
         var response = reader.Country("81.2.69.160");
         Assert.Equal("GB", response.Country.IsoCode);
         Assert.True(response.Country.IsInEuropeanUnion);
         Assert.False(response.RegisteredCountry.IsInEuropeanUnion);
         Assert.False(response.RepresentedCountry.IsInEuropeanUnion);
     }
 }
Example #8
0
        public Country GetCountryFromIp(string ip)
        {
            var cacheKey   = $"PersonalisationGroups_GeoLocation_Country_{ip}";
            var cachedItem = ApplicationContext.Current.ApplicationCache.RuntimeCache
                             .GetCacheItem(cacheKey,
                                           () =>
            {
                try
                {
                    using (var reader = new DatabaseReader(_pathToCountryDb))
                    {
                        try
                        {
                            var response = reader.Country(ip);
                            var country  =
                                new Country {
                                Code = response.Country.IsoCode, Name = response.Country.Name,
                            };

                            HttpRuntime.Cache.Insert(
                                cacheKey,
                                country,
                                null,
                                Cache.NoAbsoluteExpiration,
                                Cache.NoSlidingExpiration);

                            return(country);
                        }
                        catch (AddressNotFoundException)
                        {
                            return(null);
                        }
                        catch (GeoIP2Exception ex)
                        {
                            if (IsInvalidIpException(ex))
                            {
                                return(null);
                            }

                            throw;
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new FileNotFoundException(
                        $"MaxMind Geolocation database required for locating visitor country from IP address not found, expected at: {_pathToCountryDb}. The path is derived from either the default ({AppConstants.DefaultGeoLocationCountryDatabasePath}) or can be configured using a relative path in an appSetting with key: \"{AppConstants.ConfigKeys.CustomGeoLocationCountryDatabasePath}\"",
                        _pathToCountryDb);
                }
            });

            return(cachedItem as Country);
        }
Example #9
0
        static void Main(string[] args)
        {
            var fi = new FileInfo("GeoLite2-Country.mmdb");

            if (!fi.Exists || (DateTime.Now - fi.LastWriteTime).TotalDays > 30)
            {
                DownloadGeoliteDB();
            }
            var reader   = new DatabaseReader("GeoLite2-Country.mmdb");
            var response = reader.Country("8.8.8.8");

            Console.WriteLine(response.Country.IsoCode);
        }
 public void CountryWithIPAddressClass_ValidResponse()
 {
     using (var reader = new DatabaseReader(_countryDatabaseFile))
     {
         var response = reader.Country(IPAddress.Parse("81.2.69.160"));
         Assert.Equal("GB", response.Country.IsoCode);
         Assert.True(response.Country.IsInEuropeanUnion);
         Assert.Equal("US", response.RegisteredCountry.IsoCode);
         Assert.False(response.RegisteredCountry.IsInEuropeanUnion);
         Assert.False(response.RepresentedCountry.IsInEuropeanUnion);
         Assert.Equal("81.2.69.160/27", response.Traits.Network?.ToString());
     }
 }
Example #11
0
        /// <summary>
        /// Returns the county
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetCountry(this HttpRequestBase request)
        {
            try
            {
                var country = Reader.Country(request.UserHostAddress);

                return(country.Country.Name);
            }
            catch (Exception)
            {
                return(request.UserHostAddress);
            }
        }
Example #12
0
        public void InvalidCountryMethodForCityDatabase_ExceptionThrown()
        {
            using (var reader = new DatabaseReader(_cityDatabaseFile))
            {
                Assert.Throws(Is.TypeOf <InvalidOperationException>()
#if !NETCOREAPP1_0
                              .And.Message.Contains("A GeoIP2-City database cannot be opened with the Country method"),
#else
                              .And.Message.Contains("A GeoIP2-City database cannot be opened with the given method"),
#endif
                              () => reader.Country("10.10.10.10"));
            }
        }
Example #13
0
        public static string GetCityCode(string Hostname)
        {
            if (Hostname.Contains(":"))
            {
                Hostname = Hostname.Split(':')[0];
            }

            string Country;

            try
            {
                var databaseReader = new DatabaseReader("bin\\GeoLite2-Country.mmdb");

                if (IPAddress.TryParse(Hostname, out _))
                {
                    Country = databaseReader.Country(Hostname).Country.IsoCode;
                }
                else
                {
                    var DnsResult = DNS.Lookup(Hostname);

                    if (DnsResult != null)
                    {
                        Country = databaseReader.Country(DnsResult).Country.IsoCode;
                    }
                    else
                    {
                        Country = "Unknown";
                    }
                }
            }
            catch (Exception)
            {
                Country = "Unknown";
            }

            return(Country == null ? "Unknown" : Country);
        }
Example #14
0
        public static string LookupCountry(string ip)
        {
            const string Unknown = "Unknown Location";

            try
            {
                return(database.Country(ip).Country.Name ?? Unknown);
            }
            catch (Exception e)
            {
                Log.Write("geoip", "LookupCountry failed: {0}", e);
                return(Unknown);
            }
        }
Example #15
0
        public Task <string> Geolocate(string host)
        {
            if (!IPAddress.TryParse(host, out var _))
            {
                var addresses = Dns.GetHostAddresses(host);

                if (addresses.Length > 0)
                {
                    host = addresses.First().MapToIPv4().ToString();
                }
            }

            return(Task.FromResult(reader.Country(host).Country.Name));
        }
        public async Task <string> Geolocate(string host)
        {
            if (!IPAddress.TryParse(host, out var _))
            {
                var addresses = await Dns.GetHostAddressesAsync(host);

                if (addresses.Length > 0)
                {
                    host = addresses.First().MapToIPv4().ToString();
                }
            }

            return(reader.Country(host).Country.Name);
        }
Example #17
0
        public static string GetCityCode(string Hostname)
        {
            if (Hostname.Contains(":"))
            {
                Hostname = Hostname.Split(':')[0];
            }

            string?country = null;

            try
            {
                var databaseReader = new DatabaseReader("bin\\GeoLite2-Country.mmdb");

                if (IPAddress.TryParse(Hostname, out _))
                {
                    country = databaseReader.Country(Hostname).Country.IsoCode;
                }
                else
                {
                    var dnsResult = DnsUtils.Lookup(Hostname);

                    if (dnsResult != null)
                    {
                        country = databaseReader.Country(dnsResult).Country.IsoCode;
                    }
                }
            }
            catch
            {
                // ignored
            }

            country ??= "Unknown";

            return(country);
        }
        public void InvalidCountryMethodForCityDatabase_ExceptionThrown()
        {
            using (var reader = new DatabaseReader(_cityDatabaseFile))
            {
                var exception = Record.Exception(() => reader.Country("10.10.10.10"));
                Assert.NotNull(exception);
                Assert.Contains(exception.Message,
#if !NETCOREAPP1_1
                                "A GeoIP2-City database cannot be opened with the Country method");
#else
                                "A GeoIP2-City database cannot be opened with the given method");
#endif
                Assert.IsType <InvalidOperationException>(exception);
            }
        }
 /// <summary>
 /// Determines the Country location of a given IP address.
 /// </summary>
 /// <param name="ipAddress">string IPv4 IP address</param>
 /// <returns>string Country that the IPv4 address belongs to</returns>
 public Country GetCountryMapping(string ipAddress)
 {
     try
     {
         using (var reader = new DatabaseReader(_dbFilePath))
         {
             var country = reader.Country(ipAddress);
             return(country.Country);
         }
     }
     catch (Exception e)
     {
         _logger.LogCritical(e.ToString());
         return(null);
     }
 }
        public string GetCountryFromIp(string ip)
        {
            var cacheKey    = string.Format("PersonalisationGroups_Criteria_Country_GeoLocation_{0}", ip);
            var countryCode = HttpRuntime.Cache[cacheKey];

            if (countryCode == null)
            {
                try
                {
                    using (var reader = new DatabaseReader(_pathToDb))
                    {
                        try
                        {
                            var response = reader.Country(ip);
                            var isoCode  = response.Country.IsoCode;
                            if (!string.IsNullOrEmpty(isoCode))
                            {
                                HttpRuntime.Cache.Insert(cacheKey, isoCode, null, Cache.NoAbsoluteExpiration,
                                                         Cache.NoSlidingExpiration);
                            }

                            return(isoCode);
                        }
                        catch (AddressNotFoundException)
                        {
                            return(string.Empty);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new FileNotFoundException(
                              string.Format(
                                  "MaxMind Geolocation database required for locating visitor country from IP address not found, expected at: {0}. The path is derived from either the default ({1}) or can be configured using a relative path in an appSetting with key: \"{2}\"",
                                  _pathToDb,
                                  AppConstants.DefaultGeoLocationCountryDatabasePath,
                                  AppConstants.ConfigKeys.CustomGeoLocationCountryDatabasePath),
                              _pathToDb);
                }
            }
            else
            {
                return(countryCode.ToString());
            }
        }
Example #21
0
        protected virtual async Task<string> FindLocation(string ipAddress)
        {
            try
            {
                var databasePath = _fileProvider.MapContentPath("~/Country.mmdb");
                var reader = new DatabaseReader(databasePath);
                var response = reader.Country(ipAddress);

                if (response != null && response.Country != null && string.IsNullOrEmpty(response.Country.IsoCode))
                    throw new GeoIP2Exception("Country not found");

                return await Task.FromResult(response.Country?.IsoCode);
            }
            catch (Exception ex)
            {
                _logger.Error("An error occurred while finding country.", ex, ipAddress);
                return null;
            }
        }
Example #22
0
        public string GetCountryLocal(string ip)
        {
            if (string.IsNullOrEmpty(ip))
            {
                return(string.Empty);
            }

            try
            {
                using (var reader = new DatabaseReader(@"IPDatabase\GeoLite2-Country.mmdb"))
                {
                    var country = reader.Country(ip);
                    return(country.Country.Name);
                }
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }
Example #23
0
        public string GetIpLocation(string Ip)
        {
            lock (_dbLock)
            {
                OpenReader();

                try
                {
                    var response = _reader.Country(Ip);
                    Console.WriteLine(response.Country);
                    Console.WriteLine(response.Continent);

                    return($"{response.Country.Name}, {response?.Continent?.Name ?? "Unknown" }");
                }
                catch (Exception)
                {
                    return("Unknown");
                }
            }
        }
Example #24
0
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (String.IsNullOrEmpty(ipAddress))
            {
                return(null);
            }

            try
            {
                //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
                var databasePath = CommonHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                var reader       = new DatabaseReader(databasePath);
                var omni         = reader.Country(ipAddress);
                return(omni);
                //more info: http://maxmind.github.io/GeoIP2-dotnet/
                //more info: https://github.com/maxmind/GeoIP2-dotnet
                //more info: http://dev.maxmind.com/geoip/geoip2/geolite2/
                //Console.WriteLine(omni.Country.IsoCode); // 'US'
                //Console.WriteLine(omni.Country.Name); // 'United States'
                //Console.WriteLine(omni.Country.Names["zh-CN"]); // '美国'
                //Console.WriteLine(omni.MostSpecificSubdivision.Name); // 'Minnesota'
                //Console.WriteLine(omni.MostSpecificSubdivision.IsoCode); // 'MN'
                //Console.WriteLine(omni.City.Name); // 'Minneapolis'
                //Console.WriteLine(omni.Postal.Code); // '55455'
                //Console.WriteLine(omni.Location.Latitude); // 44.9733
                //Console.WriteLine(omni.Location.Longitude); // -93.2323
            }
            //catch (AddressNotFoundException exc)
            catch (GeoIP2Exception)
            {
                //address is not found
                //do not throw exceptions
                return(null);
            }
            catch (Exception exc)
            {
                //do not throw exceptions
                _logger.Warning("Cannot load MaxMind record", exc);
                return(null);
            }
        }
        // ReSharper disable once InconsistentNaming
        /// <summary>
        /// Gets the country ISO code from IP.
        /// </summary>
        /// <param name="ipAddress">The ip address.</param>
        /// <returns></returns>
        public static string GetCountryFromIP(string ipAddress)
        {
            string country;

            try
            {
                using (
                    var reader =
                        new DatabaseReader(HttpContext.Current.Server.MapPath("~/App_Data/GeoLite2-Country.mmdb")))
                {
                    var response = reader.Country(ipAddress);
                    country = response.Country.IsoCode;
                }
            }
            catch (Exception ex)
            {
                country = null;
            }

            return(country);
        }
        public string GetCountryFromIp(string ip)
        {
            var cacheKey   = $"PersonalisationGroups_Criteria_Country_GeoLocation_{ip}";
            var cachedItem = ApplicationContext.Current.ApplicationCache.RuntimeCache
                             .GetCacheItem(cacheKey,
                                           () =>
            {
                try
                {
                    using (var reader = new DatabaseReader(_pathToDb))
                    {
                        try
                        {
                            var response = reader.Country(ip);
                            var isoCode  = response.Country.IsoCode;
                            if (!string.IsNullOrEmpty(isoCode))
                            {
                                HttpRuntime.Cache.Insert(cacheKey, isoCode, null, Cache.NoAbsoluteExpiration,
                                                         Cache.NoSlidingExpiration);
                            }

                            return(isoCode);
                        }
                        catch (AddressNotFoundException)
                        {
                            return(string.Empty);
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new FileNotFoundException(
                        $"MaxMind Geolocation database required for locating visitor country from IP address not found, expected at: {_pathToDb}. The path is derived from either the default ({AppConstants.DefaultGeoLocationCountryDatabasePath}) or can be configured using a relative path in an appSetting with key: \"{AppConstants.ConfigKeys.CustomGeoLocationCountryDatabasePath}\"",
                        _pathToDb);
                }
            });

            return(cachedItem?.ToString() ?? string.Empty);
        }
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (String.IsNullOrEmpty(ipAddress))
                return null;

            try
            {
                //This product includes GeoLite2 data created by MaxMind, available from http://www.maxmind.com
                var databasePath = _webHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                var reader = new DatabaseReader(databasePath);
                var omni = reader.Country(ipAddress);
                return omni;
                //more info: http://maxmind.github.io/GeoIP2-dotnet/
                //more info: https://github.com/maxmind/GeoIP2-dotnet
                //more info: http://dev.maxmind.com/geoip/geoip2/geolite2/
                //Console.WriteLine(omni.Country.IsoCode); // 'US'
                //Console.WriteLine(omni.Country.Name); // 'United States'
                //Console.WriteLine(omni.Country.Names["zh-CN"]); // '美国'
                //Console.WriteLine(omni.MostSpecificSubdivision.Name); // 'Minnesota'
                //Console.WriteLine(omni.MostSpecificSubdivision.IsoCode); // 'MN'
                //Console.WriteLine(omni.City.Name); // 'Minneapolis'
                //Console.WriteLine(omni.Postal.Code); // '55455'
                //Console.WriteLine(omni.Location.Latitude); // 44.9733
                //Console.WriteLine(omni.Location.Longitude); // -93.2323
            }
            //catch (AddressNotFoundException exc)
            catch (GeoIP2Exception)
            {
                //address is not found
                //do not throw exceptions
                return null;
            }
            catch (Exception exc)
            {
                //do not throw exceptions
                _logger.Warning("Cannot load MaxMind record", exc);
                return null;
            }
        }
        private bool IsBlocked(string ipAddress)
        {
            // 1. Check that IP address is blocked
            var isBlocked = _options.BlockedIpAddresses.Contains(ipAddress);

            if (isBlocked)
            {
                return(true);
            }

            CountryResponse country;

            try
            {
                country = _ipDbReader.Country(ipAddress);
            }
            catch (AddressNotFoundException)
            {
                country = null;
            }

            if (_options.BlockedCountries.Count > 0)
            {
                // 2. If user added country to Blocked Countries collection then only those countries
                // are blocked

                isBlocked = country != null && _options.BlockedCountries.Contains(country.Country.IsoCode);
            }
            else if (_options.AllowedCountries.Count > 0)
            {
                // 3. If user added country to Allowed Countries collecction then all countries except allowed
                // are blocked

                isBlocked = country == null || !_options.AllowedCountries.Contains(country.Country.IsoCode);
            }

            return(isBlocked);
        }
Example #29
0
        public static List <Logfileentries> logfilesentry(string dbcountrypath, string dbasnpath, string logpath)
        {
            List <Logfileentries> logentries = new List <Logfileentries>();
            Regex          IPaddress         = new Regex(@"\b(?:\d{1,3}\.){3}\d{1,3}\b");
            Regex          Timestamp         = new Regex(@"\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} (\+|\-)\d{4}");
            Regex          IPandTimestamp    = new Regex(@"\b(?:\d{1,3}\.){3}\d{1,3}\b - - \[\d{2}\/\w{3}\/\d{4}:\d{2}:\d{2}:\d{2} (\+|\-)\d{4}\] ");
            DatabaseReader ipcountry         = new DatabaseReader(dbcountrypath);
            DatabaseReader ipASN             = new DatabaseReader(dbasnpath);
            string         hostname          = "";

            foreach (var line in File.ReadLines(logpath))
            {
                Logfileentries logfileentry = new Logfileentries();
                Match          iptimestamp  = IPandTimestamp.Match(line);
                Match          ipaddress    = IPaddress.Match(iptimestamp.Value);
                Match          timestamp    = Timestamp.Match(iptimestamp.Value);
                //Console.WriteLine(ipaddress.Value);
                CountryResponse countryresponse = ipcountry.Country(ipaddress.Value);
                AsnResponse     ASNresponse     = ipASN.Asn(ipaddress.Value);
                try{ hostname = Dns.GetHostEntry(ipaddress.Value).HostName; }
                catch (SocketException) {}
                if (hostname == "")
                {
                    hostname = "unknown domain";
                }
                string[] logmethod = Regex.Split(line, IPandTimestamp.ToString());
                logfileentry.Logipaddress = ipaddress.Value;
                logfileentry.Logtimestamp = timestamp.Value;
                logfileentry.Logmethod    = logmethod[2];
                logfileentry.Logcountry   = countryresponse.Country.ToString();
                logfileentry.LogASN       = ASNresponse.AutonomousSystemOrganization.ToString();
                logfileentry.LogDNS       = hostname;
                logentries.Add(logfileentry);
                //Console.WriteLine(logfileentry.Logipaddress + "||" + logfileentry.Logtimestamp + "||" + logfileentry.Logmethod + "||" + logfileentry.Logcountry + "||" + logfileentry.LogASN + "||" + logfileentry.LogDNS);
            }
            return(logentries);
        }
        public static CountryResponse GetCountryResponse(string ipAddress)
        {
            var cached = CacheManager.Get <CountryResponse>(ipAddress);

            if (cached != null)
            {
                return(cached);
            }

            var dbPath = Config["Geoip:DatabasePath"];

            //var dbPath = ConfigurationManager.AppSettings["GeoipDbPath"];
            if (dbPath == null)
            {
                throw new Exception("No GeoipDbPath found in appsettings");
            }

            using (var reader = new DatabaseReader(dbPath))
            {
                var response = reader.Country(ipAddress);
                CacheManager.Add(ipAddress, response, DateTime.UtcNow.AddDays(1));
                return(response);
            }
        }
Example #31
0
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress))
            {
                return(null);
            }

            try
            {
                var databasePath = _webHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                var reader       = new DatabaseReader(databasePath);
                var country      = reader.Country(ipAddress);
                return(country);
            }
            catch (GeoIP2Exception)
            {
                return(null);
            }
            catch (Exception exc)
            {
                _logger.Warning("Cannot load MaxMind record", exc);
                return(null);
            }
        }
 public void InvalidMethod()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         reader.Country("10.10.10.10");
     }
 }
 public void TestCountryWithIPAddress()
 {
     using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Country-Test.mmdb")))
     {
         var resp = reader.Country(IPAddress.Parse("81.2.69.160"));
         Assert.That(resp.Country.IsoCode, Is.EqualTo("GB"));
     }
 }
Example #34
0
        /// <summary>
        ///		获取备注
        /// </summary>
        /// <returns>备注</returns>
        public override string ToString()
        {
            if (string.IsNullOrWhiteSpace(Remark))
            {
                Remark = $"{Hostname}:{Port}";
            }

            if (Country == null)
            {
                try
                {
                    var databaseReader = new DatabaseReader("bin\\GeoLite2-Country.mmdb");

                    if (IPAddress.TryParse(Hostname, out _) == true)
                    {
                        Country = databaseReader.Country(Hostname).Country.IsoCode;
                    }
                    else
                    {
                        var DnsResult = DNS.Lookup(Hostname);

                        if (DnsResult != null)
                        {
                            Country = databaseReader.Country(DnsResult).Country.IsoCode;
                        }
                        else
                        {
                            Country = "UN";
                        }
                    }
                }
                catch (Exception)
                {
                    Country = "UN";
                }
            }

            Group = Group.Equals("None") || Group.Equals("") ? "NONE" : Group;

            switch (Type)
            {
            case "Socks5":
                return($"[S5][{Country}][{Group}] {Remark}");

            case "SS":
                return($"[SS][{Country}][{Group}] {Remark}");

            case "SSR":
                return($"[SR][{Country}][{Group}] {Remark}");

            case "VMess":
                return($"[V2][{Country}][{Group}] {Remark}");

            case "Trojan":
                return($"[TR][{Country}][{Group}] {Remark}");

            case "FakeServer":
                return($"TCP同款节点");

            default:
                return("WTF");
            }
        }
Example #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            string Костыль = "Log" + rnd.Next(1, 1000000).ToString();             // костыль;( для названия базы

            if (textBox1.Text == "" && textBox2.Text == "")
            {
                MessageBox.Show("Путь пуст:(");
            }
            else
            {
                StreamReader sr = new StreamReader(textBox1.Text); // Считывание файла логов
                ds = new DataSet();                                //создание таблицы и "подгонка" её под файл логов
                ds.Tables.Add("Logs");
                ds.Tables[0].Columns.Add("1");
                ds.Tables[0].Columns.Add("2");
                ds.Tables[0].Columns.Add("3");
                ds.Tables[0].Columns.Add("4");
                ds.Tables[0].Columns.Add("5");
                ds.Tables[0].Columns.Add("6");
                ds.Tables[0].Columns.Add("7");
                ds.Tables[0].Columns.Add("Dates");
                ds.Tables[0].Columns.Add("Times");
                ds.Tables[0].Columns.Add("Keys");
                ds.Tables[0].Columns.Add("11");
                ds.Tables[0].Columns.Add("IP");
                ds.Tables[0].Columns.Add("URL");
                ds.Tables[0].Columns.Add("Country");
                string row1 = sr.ReadLine();
                while (row1 != null)
                {
                    string[] val = System.Text.RegularExpressions.Regex.Split(row1, " ");
                    ds.Tables[0].Rows.Add(val);                    //заполнение таблицы
                    row1 = sr.ReadLine();
                }
                dataGridView1.DataSource = ds.Tables[0];                //Заполнение объекта DataGridViev для наглядности
                for (int i = 1; i < 8; i++)
                {
                    dataGridView1.Columns.Remove(i.ToString());                    //удаление пустых и не используемых столбцов
                }
                dataGridView1.Columns.Remove("11");
                using (var reader = new DatabaseReader("GeoLite2-Country.mmdb"))
                {                // Использование библиотеки MaxMIne для определения страных по IP
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        try
                        {
                            string a    = row.Cells[3].Value.ToString();
                            var    city = reader.Country(a);
                            row.Cells[5].Value = city.Country.Name;
                        }
                        catch
                        {
                            row.Cells[5].Value = "Unknown country";                            // Некторые Ip не входят в базу т.к это Lite версия
                        }
                    }
                }
                String        str;
                SqlConnection myConn = new SqlConnection(" Data Source = (LocalDB)\\MSSQLLocalDB;" +
                                                         "Integrated Security = True;  " +
                                                         "Connect Timeout = 30;database=master");                                               //создание подключения к ms sql
                str = "CREATE DATABASE " + Костыль + " ON PRIMARY " +
                      "(NAME = MyDatabase_Data, " +
                      "FILENAME ='" + textBox2.Text + ".mdf', " +
                      "SIZE = 3MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
                      "LOG ON (NAME = MyDatabase_Log, " +
                      "FILENAME ='" + textBox2.Text + ".ldf', " +
                      "SIZE = 1MB, " +
                      "MAXSIZE = 5MB, " +
                      "FILEGROWTH = 10%)"; //запрос для создания базы данных
                SqlCommand myCommand = new SqlCommand(str, myConn);
                try                        //попытка создания базы данных
                {
                    myConn.Open();
                    myCommand.ExecuteNonQuery();
                }
                finally
                {
                    if (myConn.State == ConnectionState.Open)
                    {
                        myConn.Close();
                    }
                }
                str = "create table Logs(Dates Date not null, Times TIME not null, " +
                      "Keys varchar(max) not null, IP varchar(max) not null, " +
                      "URL varchar(max) not null , Country varchar(max))";                    // запрос на создание таблицы
                SqlConnection myConn1 = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;" +
                                                          "AttachDbFilename=" + textBox2.Text + ".mdf;" +
                                                          "Integrated Security=True;Connect Timeout=30");
                SqlCommand myCommand1 = new SqlCommand(str, myConn1);
                str = "INSERT INTO Logs (Dates, Times, Keys, IP, URL,Country) " +
                      "VALUES(@Dates, @Times, @Keys, @IP,@URL,@Country)";                     // запрос для заполния таблицы
                SqlCommand sc = new SqlCommand(str, myConn1);
                try
                {
                    myConn1.Open();
                    myCommand1.ExecuteNonQuery();
                    foreach (DataRow row in ds.Tables[0].Rows)                    // запись из объекта DataGrid в таблицу MS sql
                    {
                        sc.Parameters.Clear();
                        sc.Parameters.AddWithValue("@Dates", row["Dates"]);
                        sc.Parameters.AddWithValue("@Times", row["Times"]);
                        sc.Parameters.AddWithValue("@Keys", row["Keys"]);
                        sc.Parameters.AddWithValue("@IP", row["IP"]);
                        sc.Parameters.AddWithValue("@URL", row["URL"]);
                        sc.Parameters.AddWithValue("@Country", row["Country"]);
                        sc.ExecuteNonQuery();
                    }
                    myConn1.Close();
                    MessageBox.Show("База MS SQL создана");
                }
                catch { MessageBox.Show("Таблица не создана"); }
            }
        }