GithubHelp home page GithubHelp logo

ngrok-api-dotnet's Introduction

ngrok API client library for .NET

This library wraps the ngrok HTTP API to make it easier to consume in C# and .NET.

Installation

This library is published on nuget

dotnet add package NgrokApi --version <version>

Support

The best place to get support using this library is through the ngrok Slack Community. If you find any bugs, please contribute by opening a new GitHub issue.

Documentation

All objects, methods and properties are documented with the .NET documentation markup tags for integration with an IDE like Visual Studio or Visual Studio Code.

Beyond that, this readme is the best source of documentation for the library. There is no API reference documentation published on the web at this time.

Versioning

This class library is published to Nuget using semantic versioning. Breaking changes to the API will only be release with a bump of the major version number. Each released commit is tagged in this repository.

No compatibility promises are made for versions < 1.0.0.

Quickstart

Create an IP Policy that allows traffic from some subnets

using NgrokApi;

public class Example
{
    public static async Task Main()
    {
        var ngrok = new Ngrok(Environment.GetEnvironmentVariable("NGROK_API_KEY"));
        var policy = await ngrok.IpPolicies.Create(new IpPolicyCreate());

        foreach (var cidr in new string[] { "24.0.0.0/8", "12.0.0.0/8" })
        {
            await ngrok.IpPolicyRules.Create(new IpPolicyRuleCreate
            {
                Cidr = cidr,
                IpPolicyId = policy.Id,
                Action = "allow",
            });
        }
    }
}

List all online tunnels

using NgrokApi;

public class Example
{
    public static async Task Main()
    {
        var ngrok = new Ngrok(Environment.GetEnvironmentVariable("NGROK_API_KEY"));
        await foreach (var t in ngrok.Tunnels.List())
        {
            Console.Out.WriteLine(t.ToString());
        }
    }
}

Conventions

Conventional usage of this package is to construct the root Ngrok API client object with an API key and then to access API resources as properties of that object. Do not construct the individual API resource Client classes in your application code.

// create the root api client
var ngrok = new Ngrok(apiKey);

// clients for all api resources (like ip policies) are acccessible as properties of the root client
var policy = await ngrok.IpPolicies.Get(policyId);

// some api resources are 'namespaced' through another property
var compression = await ngrok.EdgeModules.HttpsEdgeRouteCompression.Get(edgeRouteItem);

Automatic Paging

All list responses from the ngrok API are paged. This library provides an abstraction to make it easier to consume theses paged list resources. Instead of returning the page of results, all List() methods instead return an IAsyncEnumerable that can be iterated over with a foreach loop. The iterator will automatically fetch new pages of results from the API as needed.

using NgrokApi;

public class Example
{
    public static async Task Main()
    {
        var ngrok = new Ngrok(Environment.GetEnvironmentVariable("NGROK_API_KEY"));
        await foreach (var t in ngrok.Tunnels.List())
        {
            Console.Out.WriteLine(t.ToString());
        }
    }
}

Error Handling

All errors returned by the ngrok API are serialized as structured payloads for easy error handling. If a structured error is returned by the ngrok API, this library will throw an NgrokException.

To handle a structured error from the API, catch the NgrokException type in your code. This object will allow you to check the unique ngrok error code and the http status code of a failed response. Use the ErrorCode property to check for unique ngrok error codes returned by the API. All error codes are documented at https://ngrok.com/docs/errors. There is also an IsErrorCode() method on the exception object to check against multiple error codes. The HttpStatusCode property can be used to check not found errors.

Other non-structured errors encountered while making an API call from e.g. networking or serialization failures are not wrapped in any way and will bubble up as normal.

using NgrokApi;

public class Example
{
    public static async Task Main()
    {
        try
        {
            var ngrok = new Ngrok(Environment.GetEnvironmentVariable("NGROK_API_KEY"));
            var domain = await ngrok.ReservedDomains.Create(new ReservedDomainCreate()
            {
                Name = "foo.*.bar.ngrok.io",
                Description = "example domain",
            });
        }
        catch (NgrokException e)
        {
            if (e.IsErrorCode("ERR_NGROK_402", "ERR_NGROK_403"))
            {
                Console.Out.WriteLine("Ignoring invalid wildcard domain.");
            }
            else
            {
                throw;
            }
        }
    }
}

Datatype Overrides

All datatype objects in the NgrokApi library property override Equal() and GetHashCode() so that the objects can be compared. Similarly, they override ToString() for more helpful pretty printing of ngrok domain objects.

Sync / Async Interfaces

All library interfaces are async. Another version of the library will follow up with separate side-by-side synchronous interfaces before reaching 1.0.0.

ngrok-api-dotnet's People

Contributors

bobzilladev avatar carlamko avatar inconshreveable avatar masonj5n avatar ngrok-bors-ng[bot] avatar nikolay-ngrok avatar russorat avatar wdawson avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar

ngrok-api-dotnet's Issues

Bug with the paging of Addresses and Domains

There seems to be an issue with the paging for the reserved addresses and domains. I seem to be getting the following NgrokException

ErrorCode: "ERR_NGROK_223"
Message: 'ra_4zAZAYTuXs2aLUC6FZV8H' is not a valid resource reference identifier.
StatusCode: 400

StackTrace:
at NgrokApi.ApiHttpClient.d__13.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\Logwood.NgrokApi\ApiHttpClient.cs:line 89
at NgrokApi.ApiHttpClient.d__101.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\Logwood.NgrokApi\ApiHttpClient.cs:line 52 at NgrokApi.ReservedAddrs.<ListPage>d__11.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\Logwood.NgrokApi\Services\ReservedAddrs.cs:line 107 at NgrokApi.ReservedAddrs.<>c__DisplayClass12_0.<<List>b__0>d.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\Logwood.NgrokApi\Services\ReservedAddrs.cs:line 145 at NgrokApi.Iterator1.d__3.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\Logwood.NgrokApi\Iterator.cs:line 34
at NgrokApi.Iterator`1.d__3.System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult(Int16 token)
at Logwood.Cache.Application.NgrokService.d__4.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\src\Application\Logwood.Cache.Application\NgrokService.cs:line 91
at Logwood.Cache.Application.NgrokService.d__4.MoveNext() in D:\Git Repositories\Current\Services\Cache Service\src\Application\Logwood.Cache.Application\NgrokService.cs:line 91

I managed to solve the issue for both addresses and domains by doing the following modification in 'ReservedAddrs' class and 'ReservedDomains' class. Was just something quick for testing.

Add the following parameters to the class.

` public string NextPageUri { get; set; }

    private bool HasNextPage = true;`

Then modify ListPage method like so.

` private async Task ListPage(Paging arg)
{
if (HasNextPage)
{
//Dictionary<string, string> query = null;
Paging body = null;
//query = new Dictionary<string, string>()
//{
// ["before_id"] = arg.BeforeId,
// ["limit"] = arg.Limit,
//};
var result = await apiClient.Do(
path: $"/reserved_domains",
method: new HttpMethod("get"),
body: body,
query: query
);

            if (!string.IsNullOrWhiteSpace(result.NextPageUri))
            {
                HasNextPage = true;

                var uriQuery = result.NextPageUri.Replace(result.Uri + "?", "");
                var uriQuerySplit = uriQuery.Split("&");

                foreach (var parameter in uriQuerySplit)
                {
                    var parameterSplit = parameter.Split("=");

                    query[parameterSplit[0]] = parameterSplit[1];
                }
            }
            else
                HasNextPage = false;

            return result;
        }

        return new ReservedDomainList() { ReservedDomains = new List<ReservedDomain>() };
    }`

Can I become a contributor?

I already made 4 pull requests. If I became a contributor, I could help keep this library up to date and keep it alive.

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.