Giter Site home page Giter Site logo

maxmind / geoip2-dotnet Goto Github PK

View Code? Open in Web Editor NEW
336.0 31.0 76.0 4.68 MB

MaxMind GeoIP2 .NET API

Home Page: https://www.nuget.org/packages/MaxMind.GeoIP2

License: Apache License 2.0

C# 99.31% PowerShell 0.63% Dockerfile 0.06%
geoip mmdb geoip2 maxmind

geoip2-dotnet's Introduction

GeoIP2 .NET API

NuGet API Docs

Description

This distribution provides an API for the GeoIP2 and GeoLite2 web services and databases.

Installation

NuGet

We recommend installing this library with NuGet. To do this, type the following into the Visual Studio Package Manager Console:

install-package MaxMind.GeoIP2

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center of the population. Any location provided by a GeoIP2 database or web service should not be used to identify a particular address or household.

Web Service Usage

To use the web service API, first create a new WebServiceClient object with your account ID and license key:

var client = new WebServiceClient(42, "license_key1");

To query the GeoLite2 web service, you must set the host to geolite.info:

var client = new WebServiceClient(42, "license_key1", host: "geolite.info");

To query the Sandbox GeoIP2 web service, you must set the host to sandbox.maxmind.com:

var client = new WebServiceClient(42, "license_key1", host: "sandbox.maxmind.com");

You may also specify the fall-back locales, the host, or the timeout as optional parameters. See the API docs for more information.

This object is safe to share across threads. If you are making multiple requests, the object should be reused to so that new connections are not created for each request. Once you have finished making requests, you should dispose of the object to ensure the connections are closed and any resources are promptly returned to the system.

You may then call the sync or async method corresponding to the specific end point, passing it the IP address you want to look up or no parameters if you want to look up the current device.

If the request succeeds, the method call will return a response class for the endpoint you called. This response in turn contains multiple model classes, each of which represents part of the data returned by the web service.

See the API documentation for more details.

ASP.NET Core Usage

To use the web service API with HttpClient factory pattern as a Typed client you need to do the following:

  1. Add the following lines to Startup.cs ConfigureServices method:
// Configure to read configuration options from MaxMind section
services.Configure<WebServiceClientOptions>(Configuration.GetSection("MaxMind"));

// Configure dependency injection for WebServiceClient
services.AddHttpClient<WebServiceClient>();
  1. Add configuration in your appsettings.json with your account ID and license key.
...
  "MaxMind": {
    "AccountId": 123456,
    "LicenseKey": "1234567890",

    // Optionally set a timeout. The default is 3000 ms.
    // "Timeout": 3000,

    // Optionally set host. "geolite.info" will use the GeoLite2
    // web service instead of GeoIP2. "sandbox.maxmind.com" will use the
    // Sandbox GeoIP2 web service instead of the production GeoIP2 web
    // service.
    //
    // "Host": "geolite.info"
  },
...
  1. Inject the WebServiceClient where you need to make the call and use it.
[ApiController]
[Route("[controller]")]
public class MaxMindController : ControllerBase
{
    private readonly WebServiceClient _maxMindClient;

    public MaxMindController(WebServiceClient maxMindClient)
    {
        _maxMindClient = maxMindClient;
    }

    [HttpGet]
    public async Task<string> Get()
    {
        var location = await _maxMindClient.CountryAsync();

        return location.Country.Name;
    }
}

Web Service Example

Country Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.Country("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'
}

Country Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.CountryAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'
}

City Plus Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.City("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

City Plus Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. Set the named host argument to "geolite.info" to use the GeoLite2
// web service instead of GeoIP2. Set the named host argument to
// "sandbox.maxmind.com" to use the Sandbox GeoIP2 web service instead of
// the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.CityAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Insights Service (Sync)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights. Set the named
// host argument to "sandbox.maxmind.com" to use the Sandbox GeoIP2 web
// service instead of the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = client.Insights("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Insights Service (Async)

// If you are making multiple requests, a single WebServiceClient
// should be shared across requests to allow connection reuse. The
// class is thread safe.
//
// Replace "42" with your account ID and "license_key" with your license
// key. The GeoLite2 web service does not support Insights. Set the named
// host argument to "sandbox.maxmind.com" to use the Sandbox GeoIP2 web
// service instead of the production GeoIP2 web service.
using (var client = new WebServiceClient(42, "license_key"))
{
    // Do the lookup
    var response = await client.InsightsAsync("128.101.101.101");

    Console.WriteLine(response.Country.IsoCode);        // 'US'
    Console.WriteLine(response.Country.Name);           // 'United States'
    Console.WriteLine(response.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(response.MostSpecificSubdivision.Name);    // 'Minnesota'
    Console.WriteLine(response.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(response.City.Name); // 'Minneapolis'

    Console.WriteLine(response.Postal.Code); // '55455'

    Console.WriteLine(response.Location.Latitude);  // 44.9733
    Console.WriteLine(response.Location.Longitude); // -93.2323
}

Database Usage

To use the database API, you must create a new DatabaseReader with a string representation of the path to your GeoIP2 database. You may also specify the file access mode. You may then call the appropriate method (e.g., city) for your database, passing it the IP address you want to look up.

If the lookup succeeds, the method call will return a response class for the GeoIP2 lookup. This class in turn contains multiple model classes, each of which represents part of the data returned by the database.

We recommend reusing the DatabaseReader object rather than creating a new one for each lookup. The creation of this object is relatively expensive as it must read in metadata for the file.

See the API documentation for more details.

Database Examples

Anonymous IP Database

using (var reader = new DatabaseReader("GeoIP2-Anonymous-IP.mmdb"))
{
    var response = reader.AnonymousIP("85.25.43.84");
    Console.WriteLine(response.IsAnonymous);        // true
    Console.WriteLine(response.IsAnonymousVpn);     // false
    Console.WriteLine(response.IsHostingProvider);  // false
    Console.WriteLine(response.IsPublicProxy);      // false
    Console.WriteLine(response.IsResidentialProxy); // false
    Console.WriteLine(response.IsTorExitNode);      // true
    Console.WriteLine(response.IPAddress);          // '85.25.43.84'
}

ASN

using (var reader = new DatabaseReader("GeoLite2-ASN.mmdb"))
{
    var response = reader.Asn("85.25.43.84");
    Console.WriteLine(response.AutonomousSystemNumber); // 217
    Console.WriteLine(response.AutonomousSystemOrganization); // 'University of Minnesota'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

City Database

// This creates the DatabaseReader object, which should be reused across
// lookups.
using (var reader = new DatabaseReader("GeoIP2-City.mmdb"))
{
    // Replace "City" with the appropriate method for your database, e.g.,
    // "Country".
    var city = reader.City("128.101.101.101");

    Console.WriteLine(city.Country.IsoCode); // 'US'
    Console.WriteLine(city.Country.Name); // 'United States'
    Console.WriteLine(city.Country.Names["zh-CN"]); // '美国'

    Console.WriteLine(city.MostSpecificSubdivision.Name); // 'Minnesota'
    Console.WriteLine(city.MostSpecificSubdivision.IsoCode); // 'MN'

    Console.WriteLine(city.City.Name); // 'Minneapolis'

    Console.WriteLine(city.Postal.Code); // '55455'

    Console.WriteLine(city.Location.Latitude); // 44.9733
    Console.WriteLine(city.Location.Longitude); // -93.2323
}

Connection-Type Database

using (var reader = new DatabaseReader("GeoIP2-Connection-Type.mmdb"))
{
    var response = reader.ConnectionType("128.101.101.101");
    Console.WriteLine(response.ConnectionType); // 'Corporate'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Domain Database

using (var reader = new DatabaseReader("GeoIP2-Domain.mmdb"))
{
    var response = reader.Domain("128.101.101.101");
    Console.WriteLine(response.Domain); // 'umn.edu'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Enterprise Database

using (var reader = new DatabaseReader("/path/to/GeoIP2-Enterprise.mmdb"))
{
    //  Use the Enterprise(ip) method to do a lookup in the Enterprise database
    var response = reader.enterprise("128.101.101.101");

    var country = response.Country;
    Console.WriteLine(country.IsoCode);            // 'US'
    Console.WriteLine(country.Name);               // 'United States'
    Console.WriteLine(country.Names["zh-CN"]);     // '美国'
    Console.WriteLine(country.Confidence);         // 99

    var subdivision = response.MostSpecificSubdivision;
    Console.WriteLine(subdivision.Name);           // 'Minnesota'
    Console.WriteLine(subdivision.IsoCode);        // 'MN'
    Console.WriteLine(subdivision.Confidence);     // 77

    var city = response.City;
    Console.WriteLine(city.Name);       // 'Minneapolis'
    Console.WriteLine(city.Confidence); // 11

    var postal = response.Postal;
    Console.WriteLine(postal.Code); // '55455'
    Console.WriteLine(postal.Confidence); // 5

    var location = response.Location;
    Console.WriteLine(location.Latitude);       // 44.9733
    Console.WriteLine(location.Longitude);      // -93.2323
    Console.WriteLine(location.AccuracyRadius); // 50
}

ISP Database

using (var reader = new DatabaseReader("GeoIP2-ISP.mmdb"))
{
    var response = reader.Isp("128.101.101.101");
    Console.WriteLine(response.AutonomousSystemNumber); // 217
    Console.WriteLine(response.AutonomousSystemOrganization); // 'University of Minnesota'
    Console.WriteLine(response.Isp); // 'University of Minnesota'
    Console.WriteLine(response.Organization); // 'University of Minnesota'
    Console.WriteLine(response.IPAddress); // '128.101.101.101'
}

Exceptions

Database

If the database is corrupt or otherwise invalid, a MaxMind.Db.InvalidDatabaseException will be thrown.

If an address is not available in the database, a AddressNotFoundException will be thrown.

Web Service

For details on the possible errors returned by the web service itself, see the GeoIP2 web service documentation.

If the web service returns an explicit error document, this is thrown as a AddressNotFoundException, a AuthenticationException, a InvalidRequestException, or a OutOfQueriesException.

If some sort of transport error occurs, an HttpException is thrown. This is thrown when some sort of unanticipated error occurs, such as the web service returning a 500 or an invalid error document. If the web service request returns any status code besides 200, 4xx, or 5xx, this also becomes a HttpException.

Finally, if the web service returns a 200 but the body is invalid, the client throws a GeoIP2Exception. This exception also is the parent exception to the above exceptions.

Values to use for Database or Dictionary Keys

We strongly discourage you from using a value from any Names property as a key in a database or dictionary.

These names may change between releases. Instead we recommend using one of the following:

  • MaxMind.GeoIP2.Model.City - City.GeoNameId
  • MaxMind.GeoIP2.Model.Continent - Continent.Code or Continent.GeoNameId
  • MaxMind.GeoIP2.Model.Country and MaxMind.GeoIP2.Model.RepresentedCountry
    • Country.IsoCode or Country.GeoNameId
  • MaxMind.GeoIP2.Model.Subdivision - Subdivision.IsoCode or Subdivision.GeoNameId

Multi-Threaded Use

This API fully supports use in multi-threaded applications. When using the DatabaseReader in a multi-threaded application, we suggest creating one object and sharing that among threads.

What data is returned?

While many of the end points return the same basic records, the attributes which can be populated vary between end points. In addition, while an end point may offer a particular piece of data, MaxMind does not always have every piece of data for any given IP address.

Because of these factors, it is possible for any end point to return a record where some or all of the attributes are unpopulated.

See the GeoIP2 web services documentations for details on what data each end point may return.

The only piece of data which is always returned is the ipAddress attribute in the MaxMind.GeoIP2.Traits record.

Integration with GeoNames

GeoNames offers web services and downloadable databases with data on geographical features around the world, including populated places. They offer both free and paid premium data. Each feature is unique identified by a geonameId, which is an integer.

Many of the records returned by the GeoIP2 web services and databases include a geonameId property. This is the ID of a geographical feature (city, region, country, etc.) in the GeoNames database.

Some of the data that MaxMind provides is also sourced from GeoNames. We source things like place names, ISO codes, and other similar data from the GeoNames premium data set.

Reporting data problems

If the problem you find is that an IP address is incorrectly mapped, please submit your correction to MaxMind.

If you find some other sort of mistake, like an incorrect spelling, please check the GeoNames site first. Once you've searched for a place and found it on the GeoNames map view, there are a number of links you can use to correct data ("move", "edit", "alternate names", etc.). Once the correction is part of the GeoNames data set, it will be automatically incorporated into future MaxMind releases.

If you are a paying MaxMind customer and you're not sure where to submit a correction, please contact MaxMind support for help.

Other Support

Please report all issues with this code using the GitHub issue tracker.

If you are having an issue with a MaxMind service that is not specific to the client API, please see our support page.

Contributing

Patches and pull requests are encouraged. Please include unit tests whenever possible.

Versioning

The API uses Semantic Versioning. However, adding new methods to IGeoIP2Provider, IGeoIP2DatabaseReader, and IGeoIP2WebServicesClient will not be considered a breaking change. These interfaces only exist to facilitate unit testing and dependency injection. They will be updated to match additional methods added to the DatabaseReader and WebServiceClient. Such additions will be accompanied by a minor version bump (e.g., 1.2.x to 1.3.0).

Copyright and License

This software is Copyright (c) 2013-2023 by MaxMind, Inc.

This is free software, licensed under the Apache License, Version 2.0.

geoip2-dotnet's People

Contributors

2shortplanks avatar am11 avatar andyjack avatar artfulhacker avatar autarch avatar bmsullivan avatar borisz avatar btecu avatar danbyrne84 avatar dependabot-preview[bot] avatar dependabot[bot] avatar eilara avatar faktas2 avatar gturri avatar horgh avatar kevcenteno avatar mailaender avatar mihai-netvision avatar najiobeid avatar nazsoogund avatar nchelluri avatar nikolic-bojan avatar oalders avatar oschwald avatar patrickcronin avatar rafl avatar shadromani avatar supaham avatar ugexe avatar wesrice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geoip2-dotnet's Issues

Mockable Metadata

Hi,

Is there any chance to define the Metadata property also on the IGeoIP2DatabaseReader interface?
It would serve well in unit testing.

Removing RestSharp as a dependency for in-memory database use

When using the in-memory database only, RestSharp shouldn't be a dependency. I understand this might mean maintaining two different ports of the library, but i wouldn't want unnecessary dependencies cluttering in my own library which uses MaxMind.

DatabaseInfo

Hello,
we need something like the old method getDatabaseInfo to check availability of the databaseFile and confirmation of working geoIp environment.
Kind regards,

City returns empty for GeoLite2 database

I'm getting no City value when I lookup anything. I do get Country information though. Is this just not provided in the Lite database?


    [TestClass]
    public class DatabaseReaderTests
    {
        private DatabaseReader reader;

        [TestInitialize]
        public void Setup()
        {
            this.reader = new DatabaseReader("GeoLite2-City.mmdb", new[] { "en" }, FileAccessMode.Memory);
        }

        [DataTestMethod]
        [DataRow("213.171.195.48", "GB", "Gloucester")]
        [DataRow("31.13.65.36", "IE", "Dublin")]
        [DataRow("217.160.86.40", "DE", "Karlsruhe")]
        [DataRow("64.233.162.100", "US", "Mountain View")]
        [DataRow("13.77.161.179", "US", "Quincy")]
        public void City_IpAddressReturnsExpectedCountryAndCIty(string ipAddress, string expectedCountryCode, string expectedCity)
        {
            CityResponse city = this.reader.City(ipAddress);

            Assert.IsNotNull(city);
            Assert.AreEqual(expectedCountryCode, city.Country.IsoCode);
            Assert.AreEqual(expectedCity, city.City.Name);
        }
    }

Code not reflecting on NuGet

Hello, not too sure if its just me but i downloaded the NuGet package, just as the readme said in this file "install-package MaxMind.GeoIP2" upon trying to use the ASN database it does not exist, yet in this project it says it does. Is there anything missing? As i needed to use the ASN database for a project of mine but isnt coming up in my NuGet package. Would it be updated soon or how else can i install?
Thanks in advance.

Cache the database

Hi,

Is there any suggested practice to cache the database (the one I'm using is GeoIP2-Country.mmdb)?

What I would like to do is, when my web applications launch, I cache the database so that for every coming requests, I can look up the cache directly instead of instantiate DatabaseReader every time. And if there's updated database, I can overwrite the old one while my applications are still running.

Would that be possible? Thanks.

Load all databases (City, Country, ASN) on startup

I am currently trying to implement a backend service which in the end should be able to do IP lookups with the three databases "City", "Country" and "ASN".

For performance reasons, I'd like to initiate the DatabaseReader on startup and then utilize it whenever I want to do a Query, so that the DB-File does not need to be accessed for every lookup.

To do so, I tried to add this to "Program.cs":
builder.Services.AddSingleton(maxmindASN => new DatabaseReader("GeoLite2-ASN.mmdb"));

This works and I'm able to query data. However, when I want to add the "City" and "Country" databases, I am unable to register them the same way, as only one of the 3 DBs is initiated.

Is there any recommended way on how to initiate the 3 DBs in the same application on startup, so that they can be shared?

Thanks in advance!

Not working with RestSharp 105.0.1

I have updated my project using NuGet to the latest MaxMind.db & MaxMind.GeoIP2 and RestSharp.

When I executing the code:

MaxMind.GeoIP2.Responses.CountryResponse country;
country = DBReader.Country(ipAddress);

I get the following exception:

[System.IO.FileNotFoundException] = {"Could not load file or assembly 'RestSharp, Version=105.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.":"RestSharp, Version=105.0.0.0, Culture=neutral, PublicKeyToken=null"}

I have downgraded RestSharp back to 105.0.0 which is working ok.

Issue with dependency on Microsoft.Threading.Tasks DLL

I have created a .Net CLR user defined function to make the API call to the GeoIP2 webservice so that I can integrate directly into SQL Server 2014.

When I attempt to load the assembly, it blows up on Microsoft.Threading.Tasks.DLL because this has a dependency on mscorlib 2.0.5.0. I can't load mscorlib 2.0.5.0 into the database as it already has 4.o.x in its stack, so I am at an impasse. Is there any way you can remove this dependency?

The current version of the DLL in question is 1.0.168 and that has the following reference in it

// Assembly Reference mscorlib

Version: 2.0.5.0
Name: mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes

Now System.Threading.Tasks.dll has the correct reference of;

// Assembly Reference mscorlib

Version: 4.0.0.0
Name: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

HELP!!!

Thanks,
Colm

DatabaseReader is IDisposable for no reason

When I look at the code, I see that the DatabaseReader is IDisposable. The implementation of Dispose simply disposes the sub reader here

Then, the Reader calls the Dispose of the buffer https://github.com/maxmind/MaxMind-DB-Reader-dotnet/blob/e229436fb61a15a545ecaae400060e9af2dbd54d/MaxMind.Db/Reader.cs#L225.

The Buffer is an ArrayBuffer that is also IDisposable but the implementation of Dispose has nothing to do since it only keeps data in memory: https://github.com/maxmind/MaxMind-DB-Reader-dotnet/blob/e229436fb61a15a545ecaae400060e9af2dbd54d/MaxMind.Db/ArrayBuffer.cs#L113

So, if my understanding is right, all this chain of IDisposable does nothing in the end and complexifies all the consumers that must properly Dispose the DatabaseReader. If possible, please consider removing IDisposable from DatabaseReader.

Installation doesn't work

Running PowerShell 7, and 5.1
NuGet repo is set to api.nuget.org/v3

install-package MaxMind.GeoIP2 gives errors:
`Install-Package : The current environment doesn't have a solution open.
At line:1 char:1

  • Install-Package MaxMind.GeoIP2
  •   + CategoryInfo          : InvalidOperation: (:) [Install-Package], InvalidOperationException
      + FullyQualifiedErrorId : NuGetNoActiveSolution,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand`
    
    

Downloading the nupkg and installing doesn't work either. The nupgk site lists v2 api endpoint, and using v3 I can't find nor install the package.

Documentation confusion about multi-threading City calls

In the documentation at http://maxmind.github.io/GeoIP2-dotnet/, under the "City Service (Sync)" section, it states this:

This creates a WebServiceClient object that can be reused across requests.

But the example shows this code sample:

using (var client = new WebServiceClient(42, "license_key"))

That obviously does not create a reusable WebServiceClient object, as it is disposed of at the end of the using statement, so what does the comment mean that it can be "reused across requests"?

We were interested in creating one WebServiceClient object and using that to convert all IPs to geo, but we're assuming one WebServiceClient can't handle multiple threads using one object to check IPs, correct?

Retrieving "parent" CIDR block for an IP

Is there a way to retrieve the parent CIDR block for an IP address? In other words, the largest CIDR block where every address in that block has the same geolocation and ownership information of the IP being looked up.

Thanks!

The type or namespace name 'GeoIP2' does not exist in the namespace 'MaxMind' when targeting .NET 4.0

Hi,

For some reason, I can't use the MaxMind.GeoIP2 namespace, I get the error saying it doesn't exist.
The type or namespace name 'GeoIP2' does not exist in the namespace 'MaxMind' (are you missing an assembly reference?)

I obviously had the dll referenced and checked in the object browser that the namespace exists in the DLL.

This is my code:

using MaxMind.GeoIP2;

namespace jifiti.Common.Location
{
    public class MaxMindGeoLocation
    {
        public GeoLocationResults GetGeoLocationData(string ipAddress)
        {
            using (var client = new WebServiceClient(11111, "AAAAA"))
            {
                // Do the lookup
                var response = client.City(ipAddress);

                return new GeoLocationResults
                           {
                               Country = response.Country.IsoCode,
                               CountryConfidence = response.Country.Confidence,
                               State = response.MostSpecificSubdivision.Name,
                               StateConfidence = response.MostSpecificSubdivision.Confidence,
                               City = response.City.Name,
                               CityConfidence = response.City.Confidence,
                               PostalCode = response.Postal.Code,
                               PostalCodeConfidence = response.Postal.Confidence
                           };
            }
        }
    }
}

Running latest nuget on throws MethodAccessException

System.MethodAccessException: Method MaxMind.Db.Metadata:get_DatabaseType ()' is inaccessible from methodMaxMind.GeoIP2.DatabaseReader:Execute<MaxMind.GeoIP2.Responses.CountryResponse> (string,bool,string)
at MaxMind.GeoIP2.DatabaseReader.get_Metadata()
at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipAddress, Boolean hasTraits, String type)
at MaxMind.GeoIP2.DatabaseReader.Country(String ipAddress)

NuGet package versions installed are:
MaxMind.Db 1.0.0.0 (though dll version shows 0.2.1.0 ??)
MaxMind.GeoIP2 2.1.0.0

Thoughts?

How to consume geoip .net api or webservice from C# 2.0 based app

Hi Team,

We have bought licence of maxmind to use geoip to get location details of user registering on our website.
As part of integration with maxmind geoip's .net api with our .net based client, we understand we have to use these 2 nuget packages, which can be added to app done in .net framework 4.5, but in our case we have to consume geoip from webservice done in .net 2.0 and we can't migrate it to higher version, at least not soon.
Nugets:
https://www.nuget.org/packages/MaxMind.GeoIP2/
https://www.nuget.org/packages/MaxMind.Db/

Hence please let us know how can we consume maxmind geoip api in .net 2.0 app, either using any older version of your nuget packages or any direct webservice urls for instance of maxmind(also any documentation location for same for C# client).

If issue is not right place for such queries/concerns, then please move it to right place and please give us your inputs/solutions for issues we are facing. Thanks.

Json Serialization Drops Name fields

When I create a DatabaseReader object and complete a search for an IP that exists in the database, the CityResponse object contains values for the .Name fields. For example, CityResponse.City.Name =SomeCity. When I serialize this object using JsonConvert.SerializeObject(CityResponse) (part of Newtonsoft.Json.dll), the Name properties are not serialized. If I then use JsonConvert.DeserializeObject(jsonstring) to deserialize back to the object the .Name fields are null. Is there a way to ensure that the .Name fields are serialized with the rest of the object?

Example:
var city = loReader.City(lstrIP); // city.City.Name = cityname
var json = JsonConvert.SerializeObject(city);
var city2 = JsonConvert.DeserializeObject<MaxMind.GeoIP2.Responses.CityResponse>(json); //city2.City.Name = null

Versioning of dependency on Microsoft.Extensions.Options

Right now dependency on Microsoft.Extensions.Options is set to version 5.0.0 for all target frameworks.
This makes it impossible to use in Azure Functions as Azure Functions runtime is not yet updated to .NET 5.
Would it be possible to set this reference to lowest supported LTS version per target framework:

  • 2.1.1 for netstandard2.0
  • 3.1.11 for netstandard2.1
  • 5.0.0 for net5.0

NuGet package, C#

Im facing an issue with the Webclient from the GeoIP2 nuget package, getting the error:
"The request was aborted: Could not create SSL/TLS secure channel.".

The error is not constantly occuring. It's very periodic, half a day - then just a few requests, then a few hours nonstop.

I'm using the nuget package without any modifications, tried switching from async to sync to eliminate any issues.

Any hint where i could look for potential issues on my side? Networking erros i could eliminate... no other SSL-encrypted request fails.

No Async support in DatabaseReader?

I'm adding GeoIP2 (city database) lookup support in asp.net webapi, but don't see any async methods? Async is a much more efficient programming paradigm for server environments, so how come there is no async support?

Performance under scale for 'not found'

From documentation:
If an address is not available in the database, a AddressNotFoundException will be thrown.

If you have a hit rate that is high, throwing an exception for an IP city not found would probably be negligble. But, depending on your miss rate, an exception can be an unnecessary overhead expense on your code performance. Should a way to receive a result that indicates 'not found' vs an exception be supported?

Average lookup time for GeoIP2 vs Legacy

Using the Database in memory, we are seeing an average IP lookup time of 25ms for GeoIP2 vs 11ms for Legacy geoIP (for the country database). Has there been any performance optimization done yet on this library; or any planned before release? We also would be willing to help in any way.

Databasereader Not enough storage not solved

I downloaded the latest version and although some of the code has been changed, when I create a new reader on every client request it still throws this exception. I understand that you advise to use only 1 instance, but in a WEB API environment (which is stateless) it is not advisable to share instances. In a WEB API environment I would strongly suggest to move to an MS SQL Database and use Entity Framework to solve the memory issue. I will export the Maxmind csv to my SQL DB and work from there. Hopefully the GEOIP2 sees an update in the future to be more WEB API compatible.

async/await version

Hi,

Please add a non-blocking async/await version, so we can call it this way:

var client = new WebServiceClient(42, "abcdef12345");
var omni = await client.OmniAsync("128.101.101.101");

It's very important for programs that using .NET 4.5 or a later version.

DatabaseReader overload that takes a stream and mapping mode.

I have been storing my geoip database in azure blob storage and passing a stream of that database file to the database reader. However, I just realized that all my calls to the database are slow... And the default mode is MemoryMapped instead of in memory. Can you please add an overload that allows me to load the entire database in memory.

AddressNotFoundException error

Hello,

I am trying to that code https://pastebin.com/pa8LWXsA but when the IP is 103.8.195.34 i am getting an error.

Error Message:

Plugin MaxMind.GeoIP2.dll caused an error
 
 MaxMind.GeoIP2.Exceptions.AddressNotFoundException: The address 103.8.195.34 is not in the database.
   at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipStr, IPAddress ipAddress, String type, Boolean throwOnNullResponse)
   at MaxMind.GeoIP2.DatabaseReader.Execute[T](String ipStr, String type, Boolean throwOnNullResponse)
   at MaxMind.GeoIP2.DatabaseReader.Country(String ipAddress)
   at GeoIP2CountryPlugin.GeoIP2CountryPlugin.GeoIPIdentifier(RegisteredIdentifierArgs argument)

Any idea how to fix this error in the above code?

  • Thanks!

RestSharp 105.1.0.0

Hello there,

I have downloaded GeoIP2-dotnet by nuget with depended assemblies. When I execute the following code:

int userID = "_";
string licenseKey = "
_";
string ip = "***";

private readonly WebServiceClient client;
client = new WebServiceClient(userID, licenseKey);

CountryResponse response = client.Country(ip);

I get following exception at the last line of the code:

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in ***.Framework.Localization.dll

[System.IO.FileNotFoundException] = {"Could not load file or assembly 'RestSharp, Version=105.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.":"RestSharp, Version=105.1.0.0, Culture=neutral, PublicKeyToken=null"}

I have checked the bin if the assembly is there. And I have seen assembly is there and there is no error in references and packages.config. What is the problem?

Thanks

Microsoft BCL Build warnings

Ever since updating to the latest nuget package I'm seeing:

Severity Code Description Project File Line
Warning All projects referencing Exceptionless.Core.csproj must install nuget package Microsoft.Bcl.Build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317569. Exceptionless.Insulation

Please remove this dependency for 4.5+ projects...

Does not support DNX project

MaxMind.GeoIP2 package currently can't be used in ASP.NET 5 vNext project. This is the output after installing it to a fresh new project:

NU1002  The dependency MaxMind.Db 1.2.0 in project WebApplication1 does not support framework DNXCore,Version=v5.0. WebApplication1 D:\Desktop\WebApplication1\src\WebApplication1\project.json 1   
NU1002  The dependency MaxMind.GeoIP2 2.5.0 in project WebApplication1 does not support framework DNXCore,Version=v5.0. WebApplication1 D:\Desktop\WebApplication1\src\WebApplication1\project.json 11  
NU1002  The dependency MaxMind.GeoIP2 2.5.0 in project WebApplication1 does not support framework DNX,Version=v4.5.1.   WebApplication1 D:\Desktop\WebApplication1\src\WebApplication1\project.json 11  

install Problem(install-package MaxMind.GeoIP2)

error

I will try install the maxmind.geoIP but not install maxmind.geoip show on the error. That error screen short herewith attached,so kindly verify the problem and also I am using only asp.net 4.5 frame work (visual studio 2012)only.

already added the elmah reference also.

Proper use of WebServiceClient in .NET Core

Hi,

I would like to have a sample of proper use of WebServiceClient in .NET Core.

If we use it with using (client = new WebServiceClient()), that is not good as we will have a bunch of connections opened too long, not doing anything.
You suggest in documentation to reuse it. OK, usually it is done with AddSingleton with DI, but there is an issue with DNS refreshing. In "old" Framework, you could deal with that with DnsRefreshTimeout. Also ConnectionLeaseTimeout etc.
There is no such thinsg in .NET Core. Therefore, they introduced IHttpClientFactory in 2.1 and it is dealing with those issues.

Now, how I do I achieve having a proper implementation in .NET Core?

BR,
Bojan

Could not load type 'RestSharp.HttpBasicAuthenticator' from assembly

I just installed the client from Nuget and I get a failure that looks like this:

Could not load type 'RestSharp.HttpBasicAuthenticator' from assembly 'RestSharp, Version=105.2.2.0, Culture=neutral, PublicKeyToken=null'.":"RestSharp.HttpBasicAuthenticator"}

on the line in my code that does this:
var webResponse = webServiceClient.City(ipAddress);

I believe your issue is related to RestSharp and sounds a lot like the same problem that Twilio describes here: http://stackoverflow.com/questions/32067529/twilio-restsharp-dependency

request for constructing CityResponse members for unit testing

Hello,

There are quite a few optional parameters for the MaxMind.GeoIP2.Responses.CityResponse constructor. I would like to construct a CityResponse so I can provide it to a mock setup return call which will allow me to uni test mapping between objects in a .Net 4.6 c# environment. Can you please provide some examples for what parameters are needed for the following members:

City (I need to get City.Name)
Country (I need to get Country.IsoCode)
MostSpecificSubdivision (I need to get MostSpecificSubdivision.IsoCode)
Postal (I need to get Postal.Code)
Location (I need to get Location.Latitude and Location.Longitude)

This would be greatly appreciated.

Thanks,

Scott

Private setters prevent unit testing

All of the properties of the response objects seem to have private setters. When trying to unit test functionality in my site that hits the MaxMind service, I can mock (using Moq) the interface behind the client (IGeoIP2Provider) to simulate responses, but I'm unable to manually create response objects because none of the setters are available.

Ideally, the setters would be public for testing purposes. Either that, or the response objects would be interfaces that could also be mocked for testing purposes.

Here is an example of what I would like to mock:

var response = new CityResponse
{
    Postal = new Postal {Code = "12345"}    //not possible because of private setters
};
Mock<IGeoIP2Provider> GeoProvider = new Mock<IGeoIP2Provider>();
GeoProvider.Setup(x => x.City(It.IsAny<string>())).Returns(response);

Stop throwing AddressNotFoundException when an address can't be found.

It might sound like a good idea to throw an AddressNotFoundException when a lookup can't be found but you should favor returning null or doing something else. Throwing one exception is fine but if you use this library in a high throughput system, there are performance issues you will run into....

"As MusiGenesis said, "Exceptions are slow in .NET if they are thrown"

So, yes, you don't want to throw too many of them. On my computer, a simple throw inside a loop, it took 9.5 seconds to throw 1000 exceptions, but that time would increase, were the exception to be buried inside a large stack.

That is why flow control should NOT be done by exceptions (I know your question didn't ask for anything other than the speed, but you can work that out yourself with a timed test). Sure, you should throw exceptions whenever something goes wrong. However, you should keep the number of things going wrong to a minimum. E.g. don't pass bad data to a function.

Ha, and every answer so far (including this) is talking about when to, and when not to throw exceptions. Ironic." http://stackoverflow.com/questions/161942/how-slow-are-net-exceptions

Expose Routing Prefix as Provided by MaxMind-DB-Reader-dotnet

I wanted to provide a pull request to add the RoutingPrefix provided by MaxMind-DB-Reader-dotnet in version 2.0.0-beta3 to this library.

I was thinking it could be added as an additional overloaded version of TryIsp

 public bool TryIsp(IPAddress ipAddress, out IspResponse response, out int routingPrefix)

Would that work for y ou? Would you have a different preference for how to accomplish this?

powershell-core issue

Works fine in powershell 5.1.
However, in version 7.1 of the PowerShell-core, the following error occurs.

'[MaxMind.Db.Reader]::new($Database)
Exception calling ".ctor" with "1" argument(s): "Could not load type 'System.IO.MemoryMappedFiles.MemoryMappedFileSecurity' from
| assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."

Separate local database and Web API in different DLLs

We are using your cool GeoLite2 databases in our Open Source RTS game engine recreation project @OpenRA since version 1 of your .NET API:

Thanks for that already!

We now depend on Newtonsoft.Json.dll and RestSharp.dll although we don't use any JSON or REST anywhere in the game. It is just a hard dependency of your GeoIP2 library. Therefore I suggest to separate the local database parsing and the Web API into separate DLLs of the same project so we and others can avoid unnecessary dependencies.

DatabaseReader slow

Judging from the published Benchmarks, the DatabaseReader appears to be quite slow. Actually by several orders of magnitude slower than the Java API.

I've wrote a test against GeoLite2-Country.mmdb. And on my Core i7 Development machine I was only to perform approx. 20k queries/sec. At first I thought that initializing the reader with a stream rather than a file which turns off caching. Picture my surprise when switching to a reader using memory-mapped-file based caching resulted in barely 11k queries/sec.

Max Mind GeoIP2 0.3.0.0 only deploys through MSBuild with Rest Sharp version 104.3.3

Not sure if this is a bug but if you're using a new version of RestSharp it will not deploy correctly using MSBuild, either via the command or through the Publish feature inside Visual Studio.

Steps to recreate.

  1. Install the latest version of RestSharp, should be something like 104.4.0 but anything greater than 104.3.3 via Nuget.
  2. Install MaxMind GeoIP2 via Nuget.
  3. Use MSBuild from command line or the "Publish..." feature inside Visual Studio and the RestSharp.dll will not be packaged as part of the output. This can be confirmed via the build output window inside Visual Studio with the "diagnostic" level set:

1> ResolveAssemblyReference: Could not resolve this reference. Could not locate the assembly "RestSharp, Version=104.3.3.0, Culture=neutral, PublicKeyToken=null". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.

Result: Examine the bin folder of your output and note that the RestSharp.dll is not there.
Expected result: RestSharp.dll should be in the bin.
Humble Suggestion Rather than have the dependency of RestSharp >= 104.3 in your nuget package file, make it a specific version requirement: RestSharp == 104.3.3 since that is what MSBuild will look for.
Note: Not sure, but this might be an issue on Microsoft's side (either MSBuild or Nuget).
Workaround:

PM> Install-Package RestSharp -Version 104.3.3

I have a sample test project that can be provided, if necessary.

Can't install nuget package

I can't seem to get the nuget package to install. The Solution is .net 4.5. Any ideas?

Added file 'packages.config'.
Successfully added 'Newtonsoft.Json 7.0.1' to newproject.
For adding package 'Newtonsoft.Json 7.0.1' to project 'newproject' that targets 'net45',
>> PowerShell scripts are being executed from 'tools' (not framework-specific)
Executing script file 'C:\Blah\packages\Newtonsoft.Json.7.0.1\tools\install.ps1'.
Adding 'MaxMind.Db 1.2.0' to newproject.
For adding package 'MaxMind.Db 1.2.0' to project 'newproject' that targets 'net45',
>> Assembly references are being added from 'lib\net40'
Added reference 'MaxMind.Db' to project 'newproject'
Added file 'packages.config'.
Successfully added 'MaxMind.Db 1.2.0' to newproject.
Adding 'Microsoft.Bcl.Async 1.0.168' to newproject.
For adding package 'Microsoft.Bcl.Async 1.0.168' to project 'newproject' that targets 'net45',
>> Assembly references are being added from 'lib\net40'
Install failed. Rolling back...
System call failed. (Exception from HRESULT: 0x80010100 (RPC_E_SYS_CALL_FAILED))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.