コード例 #1
4
ファイル: Startup.cs プロジェクト: ArmedGuy/ptOS2
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            app.MapSignalR();

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => JsonSerializer.Create(new JsonSerializerSettings
            {
                ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
            }));

            IpDatabase = new DatabaseReader(HostingEnvironment.MapPath("/App_Data/GeoLite2-City.mmdb"));

            CrunchDispatcher.Crunchers.Add(new SystemEventsPerHour());
            CrunchDispatcher.Crunchers.Add(new ServerEventsPerHour());
        }
コード例 #2
1
        private async Task<DatabaseReader> GetDatabaseAsync(CancellationToken cancellationToken) {
            // Try to load the new database from disk if the current one is an hour old.
            if (_database != null && _databaseLastChecked.HasValue && _databaseLastChecked.Value < DateTime.UtcNow.SubtractHours(1)) {
                _database.Dispose();
                _database = null;
            }

            if (_database != null)
                return _database;

            if (_databaseLastChecked.HasValue && _databaseLastChecked.Value >= DateTime.UtcNow.SubtractSeconds(30))
                return null;

            _databaseLastChecked = DateTime.UtcNow;

            if (!await _storage.ExistsAsync(GEO_IP_DATABASE_PATH).AnyContext()) {
                Logger.Warn().Message("No GeoIP database was found.").Write();
                return null;
            }

            Logger.Info().Message("Loading GeoIP database.").Write();
            try {
                using (var stream = await _storage.GetFileStreamAsync(GEO_IP_DATABASE_PATH, cancellationToken).AnyContext())
                    _database = new DatabaseReader(stream);
            } catch (Exception ex) {
                Logger.Error().Exception(ex).Message("Unable to open GeoIP database.").Write();
            }

            return _database;
        }
コード例 #3
0
        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";
            }
            
        }
コード例 #4
0
ファイル: RuneSlot.cs プロジェクト: kumouri/RiotControl
        public RuneSlot(DatabaseReader reader)
        {
            Slot = reader.Integer();
            Rune = reader.Integer();

            reader.SanityCheck(Fields);
        }
コード例 #5
0
ファイル: Nullable.cs プロジェクト: walrus7521/code
    public static void Main()
    {
        DatabaseReader dr = new DatabaseReader();

        int? i = dr.GetIntFromDatabase();
        if (i.HasValue)
            Console.WriteLine("Value of 'i' is: {0}", i.Value);
        else
            Console.WriteLine("Value of 'i' is undefined");

        // Get the bool
        bool? b = dr.GetBoolFromDatabase();
        if (b.HasValue)
            Console.WriteLine("Value of 'b' is: {0}", b.Value);
        else
            Console.WriteLine("Value of 'b' is undefined");

        // Now use ?? to suplement null with a default
        // if the value is null
        // assign local variable to 100.
        int myData = dr.GetIntFromDatabase() ?? 100;
        Console.WriteLine("Value of myData: {0}", myData);

        // Long hand notation not using ?? syntax.
        int? moreData = dr.GetIntFromDatabase();
        if (!moreData.HasValue)
            moreData = 100;
        Console.WriteLine("Value of moreData: {0}", moreData);

        Console.ReadLine();
    }
コード例 #6
0
        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;
        }
コード例 #7
0
ファイル: GeoLookupService.cs プロジェクト: sounj142/aaabbb
        /// <summary>
        /// Lấy thông tin country của 1 ip address
        /// </summary>
        protected virtual CountryResponse GetInformation(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress)) return null;

            try
            {
                // sẽ chỉ tạo duy nhất 1 đối tượng _databaseReader cho mỗi thể hiện IGeoLookupService, tức là per request
                if (_databaseReader == null)
                {
                    var webHelper = EngineContext.Current.Resolve<IWebHelper>();
                    string filePath = webHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
                    _databaseReader = new DatabaseReader(filePath);
                }
                return _databaseReader.Country(ipAddress);
            }
            catch (GeoIP2Exception)
            {
                //address is not found
                //do not throw exceptions
                return null;
            }
            catch (Exception ex)
            {
                var logger = EngineContext.Current.Resolve<ILogger>();
                logger.Warning("Không thể load MaxMind.GeoIP2", ex);
                return null;
            }
        }
コード例 #8
0
 protected virtual OmniResponse GetInformation(string ipAddress)
 {
     try
     {
         var databasePath = _webHelper.MapPath("~/App_Data/GeoLite2-Country.mmdb");
         var reader = new DatabaseReader(databasePath);
         var omni = reader.Omni(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 exc)
     {
         //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;
     }
 }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MaxMindGeolocationService"/> class.
        /// </summary>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        public MaxMindGeolocationService(ILogger logger, IPrivateConfiguration configuration)
        {
            this.logger = logger;
            this.databasePath = configuration.MaxMindDatabasePath;

            var file = this.databasePath + "/GeoLite2-City.mmdb";
            this.reader = new DatabaseReader(file);
        }
コード例 #10
0
 public void HasIPAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.CityIspOrg("81.2.69.160");
         Assert.That(resp.Traits.IPAddress, Is.EqualTo("81.2.69.160"));
     }
 }
コード例 #11
0
 /// <summary>
 /// Reads the table schema and data and returns the INSERT statements
 /// </summary>
 /// <param name="tableName">Name of the table.</param>
 /// <param name="connectionString">The connection string.</param>
 /// <param name="providerName">Name of the provider.</param>
 /// <returns></returns>
 public string ReadTable(string tableName, string connectionString, string providerName)
 {
     using (var dr = new DatabaseReader(connectionString, providerName))
     {
         var databaseTable = dr.Table(tableName);
         if (databaseTable == null) return null;
         return ReadTable(databaseTable, connectionString, providerName);
     }
 }
コード例 #12
0
 public void Domain()
 {
     using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Domain-Test.mmdb")))
     {
         var ipAddress = "1.2.0.0";
         var response = reader.Domain(ipAddress);
         Assert.That(response.Domain, Is.EqualTo("maxmind.com"));
         Assert.That(response.IPAddress, Is.EqualTo(ipAddress));
     }
 }
コード例 #13
0
        public void ConnectionType()
        {
            using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Connection-Type-Test.mmdb")))
            {
                var ipAddress = "1.0.1.0";

                var response = reader.ConnectionType(ipAddress);
                Assert.That(response.ConnectionType, Is.EqualTo("Cable/DSL"));
                Assert.That(response.IPAddress, Is.EqualTo(ipAddress));
            }
        }
コード例 #14
0
ファイル: GeoIP.cs プロジェクト: CH4Code/OpenRA
 public static void Initialize()
 {
     try
     {
         using (var fileStream = new FileStream("GeoLite2-Country.mmdb.gz", FileMode.Open, FileAccess.Read))
             using (var gzipStream = new GZipInputStream(fileStream))
                 database = new DatabaseReader(gzipStream);
     }
     catch (Exception e)
     {
         Log.Write("geoip", "DatabaseReader failed: {0}", e);
     }
 }
コード例 #15
0
ファイル: SummonerRating.cs プロジェクト: Rejna/RiotControl
        public SummonerRating(DatabaseReader reader)
        {
            Map = reader.Map();
            GameMode = reader.GameMode();

            Wins = reader.Integer();
            Losses = reader.Integer();
            Leaves = reader.Integer();

            CurrentRating = reader.MaybeInteger();
            TopRating = reader.MaybeInteger();

            reader.SanityCheck(Fields);
        }
コード例 #16
0
        public void Isp()
        {
            using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-ISP-Test.mmdb")))
            {
                var ipAddress = "1.128.0.0";
                var response = reader.Isp(ipAddress);
                Assert.That(response.AutonomousSystemNumber, Is.EqualTo(1221));
                Assert.That(response.AutonomousSystemOrganization, Is.EqualTo("Telstra Pty Ltd"));
                Assert.That(response.Isp, Is.EqualTo("Telstra Internet"));
                Assert.That(response.Organization, Is.EqualTo("Telstra Internet"));

                Assert.That(response.IPAddress, Is.EqualTo(ipAddress));

            }
        }
コード例 #17
0
ファイル: GeoIP.cs プロジェクト: gavrant/PRMasterServer
        public static void Initialize(Action<string, string> log, string category)
        {
            DatabaseReader reader;

            if (File.Exists("GeoIP2-Country.mmdb")) {
                reader = new DatabaseReader("GeoIP2-Country.mmdb");
                log(category, "Loaded GeoIP2-Country.mmdb");
            } else if (File.Exists("GeoLite2-Country.mmdb")) {
                reader = new DatabaseReader("GeoLite2-Country.mmdb");
                log(category, "Loaded GeoLite2-Country.mmdb");
            } else {
                reader = null;
            }

            _instance = new GeoIP(reader);
        }
コード例 #18
0
        public void AnonymousIP()
        {
            using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Anonymous-IP-Test.mmdb")))
            {
                var ipAddress = "1.2.0.1";

                var response = reader.AnonymousIP(ipAddress);

                Assert.That(response.IsAnonymous, Is.True);
                Assert.That(response.IsAnonymousVpn, Is.True);
                Assert.That(response.IsHostingProvider, Is.False);
                Assert.That(response.IsPublicProxy, Is.False);
                Assert.That(response.IsTorExitNode, Is.False);
                Assert.That(response.IPAddress, Is.EqualTo(ipAddress));
            }
        }
コード例 #19
0
ファイル: IPInfo.cs プロジェクト: svargy/arma3beclient
        public static string GetCountryLocal(string ip)
        {
            if (string.IsNullOrEmpty(ip)) return string.Empty;

            try
            {
                using (var reader = new DatabaseReader(@"IPDatabase\GeoLite2-City.mmdb"))
                {

                    var city = reader.City(ip);
                    return city.Country.Name;
                }
            }
            catch(Exception e)
            {
                return string.Empty;
            }
        }
コード例 #20
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);
            }
        }
コード例 #21
0
    public VotesManager()
    {
        try
        {
            var uri = new Uri("pack://application:,,,/Assets/RuleChanges.txt");
            System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri);

            using (var reader = new StreamReader(resourceStream.Stream))
            {
                string traitsText           = reader.ReadToEnd();
                List <DatabaseEntry> result = DatabaseReader.LoadFromText(traitsText);

                LoadVotesFromDatabase(result);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            //throw;
        }
    }
コード例 #22
0
ファイル: MySql.cs プロジェクト: terrydash/dbschemareader
        public void MySqlViaDevartTest()
        {
            const string providername     = "Devart.Data.MySql";
            var          connectionString = ConnectionStrings.MySqlDevart;

            ProviderChecker.Check(providername, connectionString);

            DatabaseSchemaReader.Utilities.DiscoverProviderFactory.Discover(connectionString, providername);
            var dbReader = new DatabaseReader(connectionString, providername);

            dbReader.Owner = "sakila";
            var schema  = dbReader.ReadAll();
            var country = schema.FindTableByName("country");

            Assert.AreEqual(3, country.Columns.Count);
            Assert.IsNotNull(country.PrimaryKeyColumn);

            var table = dbReader.Table("city");

            Assert.AreEqual(4, table.Columns.Count);
        }
コード例 #23
0
ファイル: GeoIP.cs プロジェクト: kamilion/PRMasterServer
        public static void Initialize(Action <string, string> log, string category)
        {
            DatabaseReader reader;

            if (File.Exists("GeoIP2-Country.mmdb"))
            {
                reader = new DatabaseReader("GeoIP2-Country.mmdb", MaxMind.Db.FileAccessMode.Memory);
                log(category, "Loaded GeoIP2-Country.mmdb");
            }
            else if (File.Exists("GeoLite2-Country.mmdb"))
            {
                reader = new DatabaseReader("GeoLite2-Country.mmdb", MaxMind.Db.FileAccessMode.Memory);
                log(category, "Loaded GeoLite2-Country.mmdb");
            }
            else
            {
                reader = null;
            }

            _instance = new GeoIP(reader);
        }
コード例 #24
0
        public IEnumerable <LogEntry> LoadLogEntries(int?pageNumber = null, int numberPerPage = 10)
        {
            var target = Procedures.ErrorLog.LogEntries.LoadLogEntries;

            var db = new SqlDatabase(target.Connection);

            using (var command = db.GetStoredProcCommand(target.ProcedureName))
            {
                if (pageNumber != null)
                {
                    db.AddInParameter(command, "@PageNumber", DbType.Int32, (int)pageNumber);
                    db.AddInParameter(command, "@NumberPerPage", DbType.Int32, numberPerPage);
                }

                using (var reader = db.ExecuteReader(command))
                {
                    var readerWrapper = new DatabaseReader(reader, target.ProcedureName);
                    return(LogEntryMap.LoadLogEntries(readerWrapper));
                }
            }
        }
コード例 #25
0
ファイル: Address.cs プロジェクト: chunhualiu/DnsServer
        public Task InitializeAsync(IDnsServer dnsServer, string config)
        {
            if (_mmCityReader == null)
            {
                string mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoIP2-City.mmdb");

                if (!File.Exists(mmFile))
                {
                    mmFile = Path.Combine(dnsServer.ApplicationFolder, "GeoLite2-City.mmdb");
                }

                if (!File.Exists(mmFile))
                {
                    throw new FileNotFoundException("MaxMind City file is missing!");
                }

                _mmCityReader = new DatabaseReader(mmFile);
            }

            return(Task.CompletedTask);
        }
コード例 #26
0
ファイル: Armor.cs プロジェクト: wynn-rj/sword-and-bored-game
        public Armor(int inputID)
        {
            DatabaseConnection conn   = new DatabaseConnection();
            DatabaseReader     reader = conn.QueryRowFromTableWithID("Armor", inputID);

            ID = inputID;
            if (reader.NextRow())
            {
                Name        = reader.GetStringFromCol("Name");
                Description = reader.GetStringFromCol("Description");
                FlavorText  = reader.GetStringFromCol("Flavor_Text");

                int statusConditionsResitancesID = reader.GetIntFromCol("Status_Conditions_Resistances_FK");
                StatusConditionsResistances = new StatusConditionsResistances(statusConditionsResitancesID);

                Physical_Defense = reader.GetIntFromCol("Physical_Defense");
                Magic_Defense    = reader.GetIntFromCol("Magic_Defense");
            }
            reader.CloseReader();
            conn.CloseConnection();
        }
コード例 #27
0
ファイル: AdoSource.cs プロジェクト: laredoza/.NetScaffolder
        /// <summary>
        /// The return schemas.
        /// </summary>
        /// <param name="options">
        /// The options.
        /// </param>
        /// <returns>
        /// The <see cref="List"/>.
        /// </returns>
        public List <string> ReturnSchemas(object options)
        {
            this.Schemas.Clear();
            AdoSourceOptions adoOptions = options as AdoSourceOptions;
            var databaseReader          = new DatabaseReader(adoOptions.ConnectionString, adoOptions.ProviderName);

            this.Schemas.Clear();
            IList <DatabaseTable> tables = databaseReader.TableList();

            foreach (var table in tables)
            {
                if (!this.Schemas.Any(s => s == table.SchemaOwner))
                {
                    this.Schemas.Add(table.SchemaOwner);
                }
            }

            this.Schemas = this.Schemas.OrderBy(s => s).ToList();

            return(this.Schemas);
        }
コード例 #28
0
        protected virtual OmniResponse 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 omni         = reader.Omni(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);
            }
        }
コード例 #29
0
ファイル: DatabaseInfo.cs プロジェクト: wangfujia/7Pass
        /// <summary>
        /// Opens the database using the specified password.
        /// </summary>
        /// <param name="dispatcher">The dispatcher.</param>
        /// <param name="password">The password.</param>
        /// <param name="savePassword">set to <c>true</c> to save user password.</param>
        /// <returns>Open result.</returns>
        public OpenDbResults Open(Dispatcher dispatcher,
                                  string password, bool savePassword)
        {
            using (var store = IsolatedStorageFile
                               .GetUserStoreForApplication())
            {
                using (var fs = store.OpenFile(
                           DatabasePath, FileMode.Open))
                {
                    DbPersistentData xml;

                    try
                    {
                        xml = DatabaseReader.GetXml(fs,
                                                    password, GetKeyFile(store));
                    }
                    catch
                    {
                        return(OpenDbResults.CorruptedFile);
                    }

                    if (xml == null)
                    {
                        return(OpenDbResults.IncorrectPassword);
                    }

                    if (savePassword)
                    {
                        Save(store, xml);
                    }
                    else
                    {
                        ClearPassword();
                    }

                    Open(store, xml, dispatcher);
                    return(OpenDbResults.Success);
                }
            }
        }
コード例 #30
0
        public IpGeoBlockMiddleware(
            OwinMiddleware next, 
            IpGeoBlockOptions options,
            RemoteIdAddressFunc getRemoteIpAddress = null) : base(next)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // Check if MaxMind GeoLite2 database is available
            if (string.IsNullOrEmpty(options.GeoLite2Path))
            {
                throw new ArgumentNullException(nameof(options.GeoLite2Path));
            }

            if (!File.Exists(options.GeoLite2Path))
            {
                throw new FileNotFoundException($"MaxMind GeoLit2 Country database is not found at {options.GeoLite2Path}. Please download the database from https://dev.maxmind.com/geoip/geoip2/geolite2/.");
            }

            // Check that user added only denied countries or only allowed countries
            if (options.AllowedCountries.Count > 0 && options.BlockedCountries.Count > 0)
            {
                throw new InvalidOperationException("You have to choose only allowed contries or only blocked countries.");
            }

            _options = options;
            _ipDbReader = new DatabaseReader(_options.GeoLite2Path);

            if (getRemoteIpAddress != null)
            {
                _getRemoteIpAddress = getRemoteIpAddress;
            }
        }
コード例 #31
0
ファイル: DatabaseVerifier.cs プロジェクト: mroddy/8Pass
        public static VerifyResults VerifyUnattened(Stream file)
        {
            if (file.Length == 0)
            {
                return(new VerifyResults
                {
                    Message = Resources.EmptyFile,
                    Result = VerifyResultTypes.Error,
                });
            }

            if (!DatabaseReader.CheckSignature(file))
            {
                return(new VerifyResults
                {
                    Message = Resources.NotKdbx,
                    Result = VerifyResultTypes.Error,
                });
            }

            var oddTransforms = DatabaseReader
                                .LargeTransformRounds(file);

            if (oddTransforms)
            {
                return(new VerifyResults
                {
                    Message = Properties.Resources
                              .LargeTransforms,
                    Result = VerifyResultTypes.Warning,
                });
            }

            file.Position = 0;

            return(new VerifyResults
            {
                Result = VerifyResultTypes.Pass,
            });
        }
コード例 #32
0
        public IpGeoBlockMiddleware(
            OwinMiddleware next,
            IpGeoBlockOptions options,
            RemoteIdAddressFunc getRemoteIpAddress = null) : base(next)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // Check if MaxMind GeoLite2 database is available
            if (string.IsNullOrEmpty(options.GeoLite2Path))
            {
                throw new ArgumentNullException(nameof(options.GeoLite2Path));
            }

            if (!File.Exists(options.GeoLite2Path))
            {
                throw new FileNotFoundException($"MaxMind GeoLit2 Country database is not found at {options.GeoLite2Path}. Please download the database from https://dev.maxmind.com/geoip/geoip2/geolite2/.");
            }

            // Check that user added only denied countries or only allowed countries
            if (options.AllowedCountries.Count > 0 && options.BlockedCountries.Count > 0)
            {
                throw new InvalidOperationException("You have to choose only allowed contries or only blocked countries.");
            }

            _options    = options;
            _ipDbReader = new DatabaseReader(_options.GeoLite2Path);

            if (getRemoteIpAddress != null)
            {
                _getRemoteIpAddress = getRemoteIpAddress;
            }
        }
コード例 #33
0
        public HttpResponseMessage Get()
        {
            try
            {
                MapDTO dto = new MapDTO()
                {
                    latitude  = "37.09024",
                    longitude = "-95.712891"
                };

                string ip_address = this.Request.GetIPAddress();

                //ip_address = "104.185.202.20"; // for testing on localhost, should resolve to Atlanta, GA...

                using (var objGeoIP2DB = new DatabaseReader(string.Concat(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\GeoIP2-City.mmdb")))
                {
                    try
                    {
                        var objGeoIP2 = objGeoIP2DB.City(ip_address);
                        if (objGeoIP2 != null)
                        {
                            dto.latitude  = objGeoIP2.Location.Latitude.ToString();
                            dto.longitude = objGeoIP2.Location.Longitude.ToString();
                        }
                    }
                    catch
                    {
                        // IP address cannot be resolved
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.OK, dto));
            }
            catch (Exception ex)
            {
                Exceptions.LogException(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
コード例 #34
0
    private void DecreaseAffectionOT(int speed)
    {
        long diff = System.DateTime.Now.Date.Minute - curMin;

        UpdatecurMin();
        if (diff == 0)
        {
            return;
        }
        else
        {
            int exp = DatabaseReader.Instance().exp;
            if (exp - speed <= 0)
            {
                DatabaseReader.Instance().exp = 0;
            }
            else
            {
                DatabaseReader.Instance().exp -= speed;
            }
        }
    }
コード例 #35
0
 public static List <T> GetPageList <T>(string sql, DbParameter[] param, string OrderBy, int pageIndex, int pageSize, ref int count)
 {
     try
     {
         StringBuilder strSql = new StringBuilder();
         if (pageIndex == 0)
         {
             pageIndex = 1;
         }
         int num  = (pageIndex - 1) * pageSize;
         int num1 = (pageIndex) * pageSize;
         strSql.Append("Select * From (Select ROW_NUMBER() Over (" + OrderBy + ")");
         strSql.Append("  rowNumber, T.* From (" + sql + ")  T )  N Where rowNumber > " + num + " And rowNumber <= " + num1 + "");
         count = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, "Select Count(1) From (" + sql + ") t", param));
         IDataReader dr = DbHelper.ExecuteReader(CommandType.Text, strSql.ToString(), param);
         return(DatabaseReader.ReaderToList <T>(dr));
     }
     catch (Exception ex)
     {
         throw;
     }
 }
コード例 #36
0
        public void OnGet()
        {
            //Получить местоположение
            // Затем мы напишем некоторый код, который откроет DatabaseReaderэкземпляр,
            //а затем вызовет City()метод, передав IP-адрес, который вы хотите найти.
            //    В приложении ASP.NET Core вы можете определить IP-адрес, используя HttpContext.Connection.RemoteIpAddress.
            // Если мы сможем найти местоположение, мы сохраним его InitialLatitudeи InitialLongitudeполя,
            //а также установите начальный масштаб, который будет увеличен в этом месте.
            //Если по какой - то причине взгляд не сработает, мы просто потерпим неудачу.
            //Нам нужно будет добавить X - Forwarded - For заголовок к нашим запросам.
            //    Я использую Firefox и установил расширение Modify Header Value.
            //    Если вы используете Chrome, вы можете установить расширение ModHeader,
            //    которое позволит вам изменять HTTP-заголовки запросов.
            //    Нам понадобится IP - адрес для тестирования. Самый простой способ - напечатать
            //    «что такое мой IP-адрес» в вашей поисковой системе, и он вам скажет.Я использую DuckDuckGo, но Google сделает то же самое для вас:
            try
            {
                using (var reader = new DatabaseReader(_hostingEnvironment.WebRootPath + "\\GeoLite2-City.mmdb"))
                {
                    // Определение IP-адреса запроса
                    var ipAddress = HttpContext.Connection.RemoteIpAddress;
                    // Получить город по IP-адресу
                    var city = reader.City(ipAddress);

                    if (city?.Location?.Latitude != null && city?.Location?.Longitude != null)
                    {
                        InitialLatitude  = city.Location.Latitude.Value;
                        InitialLongitude = city.Location.Longitude.Value;
                        InitialZoom      = 9;
                    }
                }
            }
            catch (Exception e)
            {
                // Просто подавите ошибки. Если мы не смогли восстановить местоположение по какой-либо причине
                // нет причин уведомлять пользователя. Мы просто не будем знать их текущий
                // расположение и не сможет центрировать карту на нем
            }
        }
コード例 #37
0
ファイル: Form1.cs プロジェクト: zls3201/dbschemareader
        private void ReadSchemaClick(object sender, EventArgs e)
        {
            if (!IsConnectionStringValid())
            {
                return;
            }

            var connectionString = ConnectionString.Text.Trim();
            var providerName     = DataProviders.SelectedValue.ToString();

            StartWaiting();
            var rdr   = new DatabaseReader(connectionString, providerName);
            var owner = SchemaOwner.Text.Trim();

            if (!string.IsNullOrEmpty(owner))
            {
                rdr.Owner = owner;
            }
            toolStripStatusLabel1.Text = "Reading...";

            backgroundWorker1.RunWorkerAsync(rdr);
        }
コード例 #38
0
    public object GetCBCDataByTaxRefNo(int incLocal, string taxRefNo, int year)
    {
        string xml        = "";
        string jsonString = "";

        try
        {
            var dsResults = DatabaseReader.GetCBCDataByTaxRefNo(incLocal, taxRefNo, year);
            if (dsResults.HasRows())
            {
                xml = dsResults.Tables[0].Rows[0][0].ToString();
                var doc = new XmlDocument();
                doc.LoadXml(xml);
                jsonString = JsonConvert.SerializeXmlNode(doc);
            }
        }
        catch (Exception x)
        {
            throw new Exception(x.Message);
        }
        return(jsonString);
    }
コード例 #39
0
ファイル: MainWindow.cs プロジェクト: Uppley/business_planner
        public MainWindow()
        {
            InitializeComponent();
            ToolStripManager.Renderer = new Office2007Renderer.Office2007Renderer();
            toolBar.Renderer          = new Office2007Renderer.Office2007Renderer();
            this.home.TopLevel        = false;
            panel1.Controls.Clear();
            panel1.Controls.Add(this.home);
            this.home.parentForm = this;
            this.home.Show();
            AppUtilities.mainForm = this;
            project_name          = ProjectConfig.projectSettings["Title"].ToString().ToUpper();
            label1.Text           = project_name.ToUpper();
            currency.Text         = ProjectConfig.projectSettings.ContainsKey("Currency") ? ProjectConfig.projectSettings["Currency"].ToString() : "N.A.";
            setTreeNodes();
            DocumentProgressor dpg = new DocumentProgressor();

            label4.Text          = dpg.completedSteps().ToString() + " /";
            label5.Text          = dpg.totalSteps().ToString() + " tasks completed";
            progressBar1.Maximum = dpg.totalSteps();
            progressBar1.Value   = dpg.completedSteps();
            currencyHandler();
            if (dashboard == null)
            {
                activateEditMenus(0);
            }
            meeting_count = DatabaseReader.getMeetingCount();
            button1.Text  = meeting_count == 1 ? meeting_count + " Meeting Today" : meeting_count + " Meetings Today";
            if (meeting_count > 0)
            {
                button1.ImageIndex = 1;
                button1.Enabled    = true;
            }
            else
            {
                button1.ImageIndex = 0;
                button1.Enabled    = false;
            }
        }
コード例 #40
0
        public void OnGet()
        {
            try
            {
                using (var reader = new DatabaseReader(_hostingEnvironment.WebRootPath + "\\GeoLite2-City.mmdb"))
                {
                    var ipAddress = HttpContext.Connection.RemoteIpAddress;

                    var city = reader.City(ipAddress);

                    if (city?.Location?.Latitude != null && city?.Location?.Longitude != null)
                    {
                        InitialLatitude  = city.Location.Latitude.Value;
                        InitialLongitude = city.Location.Longitude.Value;
                        InitialZoom      = 9;
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
コード例 #41
0
    public CircuitManager()
    {
        Instance = this;
        try
        {
            var uri = new Uri("pack://application:,,,/Assets/Locations.txt");
            System.Windows.Resources.StreamResourceInfo resourceStream = Application.GetResourceStream(uri);

            using (var reader = new StreamReader(resourceStream.Stream))
            {
                string traitsText           = reader.ReadToEnd();
                List <DatabaseEntry> result = DatabaseReader.LoadFromText(traitsText);

                LoadCircuitsFromDatabase(result, ClimateManager.Instance);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            //throw;
        }
    }
コード例 #42
0
        public void CacheTest()
        {
            //  <system.data>
            //    <DbProviderFactories>
            //<add name="InterSystems Data Provider"
            //     invariant="InterSystems.Data.CacheClient"
            //     description="InterSystem .Net Data Provider"
            //     type="InterSystems.Data.CacheClient.CacheFactory,
            //   Intersystems.Data.CacheClient, Version=2.0.0.1, Culture=neutral, PublicKeyToken=ad350a26c4a4447c"
            // />
            //    </DbProviderFactories>
            //  </system.data>
            const string providername     = "InterSystems.Data.CacheClient";
            const string connectionString = "Server=localhost; Port=1972; Namespace=SAMPLES;Password=SYS; User ID=_SYSTEM;";

            ProviderChecker.Check(providername, connectionString);

            var dbReader = new DatabaseReader(connectionString, providername);
            var schema   = dbReader.ReadAll();

            Assert.IsTrue(schema.Tables.Count > 0);
        }
コード例 #43
0
 private string GetUserRequestLocation()
 {
     UserIp = DayaxeDal.Ultility.Ip.GetIpAddress();
     if (Session[UserIp] != null)
     {
         return(Session[UserIp].ToString());
     }
     using (var reader = new DatabaseReader(Server.MapPath("/App_Data/GeoLite2-City.mmdb")))
     {
         if (UserIp == "::1")
         {
             UserIp = "134.201.250.155"; // Los Angeles IP Address
         }
         CityResponse response;
         if (reader.TryCity(UserIp, out response))
         {
             Session[UserIp] = response.City.Name;
             return(response.City.Name);
         }
         return(string.Empty);
     }
 }
コード例 #44
0
        public void TestAccess2007()
        {
            const string providername = "System.Data.OleDb";
            const string dir          = @"C:\Data\Nwind.accdb";

            if (!File.Exists(dir))
            {
                Assert.Inconclusive("Access test requires database file " + dir);
            }

            const string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir;

            ProviderChecker.Check(providername, connectionString);

            DiscoverProviderFactory.Discover(connectionString, providername);

            var dbReader = new DatabaseReader(connectionString, providername);
            var schema   = dbReader.ReadAll();
            var table    = schema.FindTableByName("Products");

            Assert.IsTrue(table.Columns.Count > 0);
        }
        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);
        }
コード例 #46
0
        public static IEnumerable <LogEntry> LoadLogEntries(DatabaseReader readerWrapper)
        {
            var returnValue = new List <LogEntry>();

            using (readerWrapper)
            {
                while (readerWrapper.Read())
                {
                    var logEntry = new LogEntry
                    {
                        Id        = readerWrapper.GetInt32("LogId"),
                        Entry     = readerWrapper.GetString("LogEntry"),
                        CreatedOn = readerWrapper.GetDateTime("CreatedOn"),
                        CreatedBy = readerWrapper.GetString("CreatedBy")
                    };

                    returnValue.Add(logEntry);
                }
            }

            return(returnValue);
        }
コード例 #47
0
        public void Enterprise_ValidResponse()
        {
            using var reader = new DatabaseReader(_enterpriseDatabaseFile);
            var ipAddress = "74.209.24.0";
            var response  = reader.Enterprise(ipAddress);

            Assert.Equal(11, response.City.Confidence);
            Assert.Equal(99, response.Country.Confidence);
            Assert.False(response.Country.IsInEuropeanUnion);
            Assert.Equal(6252001, response.Country.GeoNameId);
            Assert.Equal(27, response.Location.AccuracyRadius);
            Assert.False(response.RegisteredCountry.IsInEuropeanUnion);
            Assert.False(response.RepresentedCountry.IsInEuropeanUnion);
            Assert.Equal("Cable/DSL", response.Traits.ConnectionType);
            Assert.True(response.Traits.IsLegitimateProxy);
            Assert.Equal(ipAddress, response.Traits.IPAddress);
            Assert.Equal("74.209.16.0/20", response.Traits.Network?.ToString());

            response = reader.Enterprise("149.101.100.0");
            Assert.Equal("310", response.Traits.MobileCountryCode);
            Assert.Equal("004", response.Traits.MobileNetworkCode);
        }
コード例 #48
0
        static void Main()
        {
            Console.WriteLine("Hello from Nullable Types");
            DatabaseReader dr = new DatabaseReader();
            int?           i  = dr.GetIntFromDatabase();

            if (i != null)
            {
                Console.WriteLine("value of (i) is : {0}", i.Value);
            }
            else
            {
                Console.WriteLine("value of (i) is not defined");
            }

            bool?b = dr.GetBoolFromDatabase();

            if (b != null)
            {
                Console.WriteLine("value of (b) is {0}", b.Value);
            }
            else
            {
                Console.WriteLine("value of (b) is not defined");
            }

            int?myData = dr.GetIntFromDatabase() ?? 100;

            Console.WriteLine("value of myData is {0}", myData.Value);
            Console.ReadLine();

            int?moreData = dr.GetIntFromDatabase();

            if (!moreData.HasValue)
            {
                moreData = 100;
            }
            Console.WriteLine("value of moreData is {0}", moreData.Value);
        }
コード例 #49
0
 public MainWindow(DatabaseReader reader, Uploader uploader)
 {
     InitializeComponent();
     this.DataContext = this;
     _reader          = reader;
     _uploader        = uploader;
     Events           = new ObservableCollection <LogItem>();
     UploadQueue      = new ConcurrentQueue <UploadEvent>();
     ActiveOnly       = true;
     ((CollectionViewSource)this.Resources["FilteredTournaments"]).Filter += (sender, e) =>
     {
         TrackableTournament t = e.Item as TrackableTournament;
         e.Accepted = !ActiveOnly || t.Tournament.Active;
     };
     _worker       = new UploadWorker(this.UploadQueue, this.AddEvent);
     _workerThread = new Thread(_worker.DoUpload);
     _workerThread.IsBackground = true;
     _workerThread.Start();
     Tournaments = new ObservableCollection <TrackableTournament>(from t in _reader.getAllTournaments()
                                                                  select new TrackableTournament(t));
     new CheckTournamentsDelegate(CheckTournaments).BeginInvoke(null, null);
 }
コード例 #50
0
    private void DecreaseHungerOT(int speed)
    {
        long diff = System.DateTime.Now.Date.Minute - curMin;

        UpdatecurMin();
        if (diff == 0)
        {
            return;
        }
        else
        {
            int hunger = DatabaseReader.Instance().hunger;
            if (hunger - speed <= 0)
            {
                DatabaseReader.Instance().hunger = 0;
            }
            else
            {
                DatabaseReader.Instance().hunger -= speed;
            }
        }
    }
コード例 #51
0
 public void TestLocaleList()
 {
     using (var reader = new DatabaseReader(_databaseFile, new List<string> { "xx", "ru", "pt-BR", "es", "en" }))
     {
         var resp = reader.Omni("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("Лондон"));
     }
 }
コード例 #52
0
 public void TestDefaultLocale()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
コード例 #53
0
 public GeoIP()
 {
     Target = "geoip";
     DatabaseFileName = Path.Combine(AssemblyDirectory, "GeoLite2City.mmdb");
     dr = new DatabaseReader(DatabaseFileName);
 }
コード例 #54
0
 public void Metadata()
 {
     using (var reader = new DatabaseReader(Path.Combine(_databaseDir, "GeoIP2-Domain-Test.mmdb")))
     {
         Assert.That(reader.Metadata.DatabaseType, Is.EqualTo("GeoIP2-Domain"));
     }
 }
コード例 #55
0
 public void UnknownAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         reader.City("10.10.10.10");
     }
 }
コード例 #56
0
 public void TestStreamConstructor()
 {
     using (StreamReader streamReader = new StreamReader(_databaseFile))
     {
         using (var reader = new DatabaseReader(streamReader.BaseStream))
         {
             var resp = reader.City("81.2.69.160");
             Assert.That(resp.City.Name, Is.EqualTo("London"));
         }
     }
 }
コード例 #57
0
 public void TestMemoryMode()
 {
     using (var reader = new DatabaseReader(_databaseFile, FileAccessMode.Memory))
     {
         var resp = reader.City("81.2.69.160");
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
コード例 #58
0
 public void InvalidMethod()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         reader.Country("10.10.10.10");
     }
 }
コード例 #59
0
 public void TestWithIPAddress()
 {
     using (var reader = new DatabaseReader(_databaseFile))
     {
         var resp = reader.City(IPAddress.Parse("81.2.69.160"));
         Assert.That(resp.City.Name, Is.EqualTo("London"));
     }
 }
コード例 #60
0
 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"));
     }
 }