Show / Hide Table of Contents

Managed Service Code Samples

A Managed Service is a mechanism to 1) retrieve threat lists from the Google Safe Browsing API on a periodic schedule and manage a Threat Database for you automatically and 2) allow you to lookup a URL to determine whether it is safe or unsafe. It is, effectively, a complete implementation of the Google Safe Browsing Update API protocol.

A Managed Service is the easiest and quickest mechanism to get started using Safe Browsing.NET. However, it might not be applicable for all use cases. If you have a use case where you want to manage a Threat Database and lookup URLs from the same process, a Managed Service is for you.

If, however, you have a use case where you want to build a Threat Database that is shared by multiple different processes, regardless of whether those processes are local or remote, a Managed Service might not be the right solution for you.

A Managed Service is named so because it manages a Threat Database for you.

Tip

To follow along with these examples, please see the Gee.External.Browsing.Services namespace and in particular ManagedBrowsingServiceBuilder, ManagedBrowsingService, and UrlLookupResult in the Safe Browsing.NET API reference.

Example: Create a Managed Service With All Available Threat Lists

using Gee.External.Browsing.Cache;
using Gee.External.Browsing.Clients;
using Gee.External.Browsing.Databases;
using Gee.External.Browsing.Services;
using System.Threading.Tasks;

namespace Examples {
    /// <summary>
    ///     Main Program.
    /// </summary>
    public static class Program {
        /// <summary>
        ///     Execute Main Program.
        /// </summary>
        /// <param name="args">
        ///     A collection of arguments passed from the command line.
        /// </param>
        /// <returns>
        ///     A task representing the asynchronous operation
        /// </returns>
        public static async Task Main(string[] args) {
            // ...
            //
            // Create a managed service that uses an in-memory cache, a JSON database that is persisted to disk, and
            // an HTTP client to communicate with the Google Safe Browsing API.
            //
            // The managed service will automatically setup a database and manage it (i.e. it will automatically
            // synchronize it with the Google Safe Browsing API in accordance with the Google Safe Browsing Update API
            // protocol).
            var managedService = ManagedBrowsingService.Build()
                .UseMemoryCache()
                .UseJsonDatabase("/Google.json")
                .UseHttpClient("YOUR_GOOGLE_API_KEY")
                .Build();

            using (managedService) {
                try {
                    // ...
                    //
                    // Throws an exception if the operation fails.
                    const string testUrl = "https://testsafebrowsing.appspot.com/s/phishing.html";
                    var lookupTask = managedService.LookupAsync(testUrl);
                    var testUrlLookupResult = await lookupTask.ConfigureAwait(false);
                    if (testUrlLookupResult.IsDatabaseStale) {
                        // ...
                        //
                        // If the database is stale, you can either wait for a few minutes and try again or assume the
                        // URL is safe.
                        //
                        // Internally, if the database is stale, the service will block, up to a limit so your program
                        // doesn't freeze, until it is up-to-date before determining whether the URL is safe or unsafe.
                        // So this URL lookup result code should be rare.
                    }
                    else if (testUrlLookupResult.IsSafe) {
                        // ...
                        //
                        // Yay, the URL is safe!
                    }
                    else if (testUrlLookupResult.IsUnsafe) {
                        // ...
                        //
                        // If the URL is unsafe, retrieve the computed URL expression that indicated it is unsafe.
                        var unsafeUrlExpression = testUrlLookupResult.UnsafeUrlExpression;

                        // ...
                        //
                        // If the URL is unsafe, retrieve the collection of unsafe threat list descriptors the URL is
                        // associated with.
                        var unsafeThreatListDescriptors = testUrlLookupResult.UnsafeThreatListDescriptors;

                        // ...
                        //
                        // If the URL is unsafe, you can use the collection of unsafe threat list descriptors the URL
                        // is associated with to determine the target platforms and threat types. But you can also use
                        // the following convenient properties to retrieve them.
                        var targetPlatforms = testUrlLookupResult.TargetPlatforms;
                        var threatTypes = testUrlLookupResult.ThreatTypes;
                    }
                }
                catch (BrowsingCacheException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a caching error.
                }
                catch (BrowsingClientException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a communication error with the Google Safe Browsing
                    // API.
                }
                catch (BrowsingDatabaseException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a database error.
                }
            }
        }
    }
}

Example: Create a Managed Service With a Restricted Number of Threat Lists

using Gee.External.Browsing;
using Gee.External.Browsing.Cache;
using Gee.External.Browsing.Clients;
using Gee.External.Browsing.Databases;
using Gee.External.Browsing.Services;
using System.Threading.Tasks;

namespace Examples {
    /// <summary>
    ///     Main Program.
    /// </summary>
    public static class Program {
        /// <summary>
        ///     Execute Main Program.
        /// </summary>
        /// <param name="args">
        ///     A collection of arguments passed from the command line.
        /// </param>
        /// <returns>
        ///     A task representing the asynchronous operation
        /// </returns>
        public static async Task Main(string[] args) {
            // ...
            //
            // Create a managed service that uses an in-memory cache, a JSON database that is persisted to disk, and
            // an HTTP client to communicate with the Google Safe Browsing API.
            //
            // We're also restricting the managed service here to only retrieve threat list updates for URLs serving
            // malware on Linux and Windows. All other threat lists will be ignored.
            //
            // The managed service will automatically setup a threat database and manage it(i.e.it will automatically
            // synchronize it with the Google Safe Browsing API in accordance with the Google Safe Browsing Update API
            // protocol).
            var managedService = ManagedBrowsingService.Build()
                .UseMemoryCache()
                .UseJsonDatabase("/Google.json")
                .UseHttpClient("YOUR_GOOGLE_API_KEY")
                .RestrictUpdatesTo(ThreatType.Malware, PlatformType.Linux, ThreatEntryType.Url)
                .RestrictUpdatesTo(ThreatType.Malware, PlatformType.Windows, ThreatEntryType.Url)
                .Build();

            using (managedService) {
                try {
                    // ...
                    //
                    // Throws an exception if the operation fails.
                    const string testUrl = "https://testsafebrowsing.appspot.com/s/phishing.html";
                    var lookupTask = managedService.LookupAsync(testUrl);
                    var testUrlLookupResult = await lookupTask.ConfigureAwait(false);
                    if (testUrlLookupResult.IsDatabaseStale) {
                        // ...
                        //
                        // If the database is stale, you can either wait for a few minutes and try again or assume the
                        // URL is safe.
                        //
                        // Internally, if the database is stale, the service will block, up to a limit so your program
                        // doesn't freeze, until it is up-to-date before determining whether the URL is safe or unsafe.
                        // So this URL lookup result code should be rare.
                    }
                    else if (testUrlLookupResult.IsSafe) {
                        // ...
                        //
                        // Yay, the URL is safe!
                    }
                    else if (testUrlLookupResult.IsUnsafe) {
                        // ...
                        //
                        // If the URL is unsafe, retrieve the computed URL expression that indicated it is unsafe.
                        var unsafeUrlExpression = testUrlLookupResult.UnsafeUrlExpression;

                        // ...
                        //
                        // If the URL is unsafe, retrieve the collection of unsafe threat list descriptors the URL is
                        // associated with.
                        var unsafeThreatListDescriptors = testUrlLookupResult.UnsafeThreatListDescriptors;

                        // ...
                        //
                        // If the URL is unsafe, you can use the collection of unsafe threat list descriptors the URL
                        // is associated with to determine the target platforms and threat types. But you can also use
                        // the following convenient properties to retrieve them.
                        var targetPlatforms = testUrlLookupResult.TargetPlatforms;
                        var threatTypes = testUrlLookupResult.ThreatTypes;
                    }
                }
                catch (BrowsingCacheException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a caching error.
                }
                catch (BrowsingClientException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a communication error with the Google Safe Browsing
                    // API.
                }
                catch (BrowsingDatabaseException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a database error.
                }
            }
        }
    }
}

Example: Create a Managed Service With Threat List Update Constraints

using Gee.External.Browsing;
using Gee.External.Browsing.Cache;
using Gee.External.Browsing.Clients;
using Gee.External.Browsing.Databases;
using Gee.External.Browsing.Services;
using System.Threading.Tasks;

namespace Examples {
    /// <summary>
    ///     Main Program.
    /// </summary>
    public static class Program {
        /// <summary>
        ///     Execute Main Program.
        /// </summary>
        /// <param name="args">
        ///     A collection of arguments passed from the command line.
        /// </param>
        /// <returns>
        ///     A task representing the asynchronous operation
        /// </returns>
        public static async Task Main(string[] args) {
            // ...
            //
            // Create a managed service that uses an in-memory cache, an in-memory database, and an HTTP client to
            // communicate with the Google Safe Browsing API.
            //
            // We're also restricting the managed service here to only retrieve 4096 threats for social engineering
            // URLs on any platform. All other threat lists will be ignored.
            //
            // The managed service will automatically setup a threat database and manage it (i.e. it will automatically
            // synchronize it with the Google Safe Browsing API in accordance with the Google Safe Browsing Update API
            // protocol).
            var managedService = ManagedBrowsingService.Build()
                .UseMemoryCache()
                .UseMemoryDatabase()
                .UseHttpClient("YOUR_GOOGLE_API_KEY")
                .RestrictUpdatesTo(ThreatType.SocialEngineering, PlatformType.Any, ThreatEntryType.Url, b => {
                    b.SetMaximumDatabaseEntries(4096);
                    return b.Build();
                })
                .Build();

            using (managedService) {
                try {
                    // ...
                    //
                    // Throws an exception if the operation fails.
                    const string testUrl = "https://testsafebrowsing.appspot.com/s/phishing.html";
                    var lookupTask = managedService.LookupAsync(testUrl);
                    var testUrlLookupResult = await lookupTask.ConfigureAwait(false);
                    if (testUrlLookupResult.IsDatabaseStale) {
                        // ...
                        //
                        // If the database is stale, you can either wait for a few minutes and try again or assume the
                        // URL is safe.
                        //
                        // Internally, if the database is stale, the service will block, up to a limit so your program
                        // doesn't freeze, until it is up-to-date before determining whether the URL is safe or unsafe.
                        // So this URL lookup result code should be rare.
                    }
                    else if (testUrlLookupResult.IsSafe) {
                        // ...
                        //
                        // Yay, the URL is safe!
                    }
                    else if (testUrlLookupResult.IsUnsafe) {
                        // ...
                        //
                        // If the URL is unsafe, retrieve the computed URL expression that indicated it is unsafe.
                        var unsafeUrlExpression = testUrlLookupResult.UnsafeUrlExpression;

                        // ...
                        //
                        // If the URL is unsafe, retrieve the collection of unsafe threat list descriptors the URL is
                        // associated with.
                        var unsafeThreatListDescriptors = testUrlLookupResult.UnsafeThreatListDescriptors;

                        // ...
                        //
                        // If the URL is unsafe, you can use the collection of unsafe threat list descriptors the URL
                        // is associated with to determine the target platforms and threat types. But you can also use
                        // the following convenient properties to retrieve them.
                        var targetPlatforms = testUrlLookupResult.TargetPlatforms;
                        var threatTypes = testUrlLookupResult.ThreatTypes;
                    }
                }
                catch (BrowsingCacheException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a caching error.
                }
                catch (BrowsingClientException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a communication error with the Google Safe Browsing
                    // API.
                }
                catch (BrowsingDatabaseException) {
                    // ...
                    //
                    // Catch this exception if you want to handle a database error.
                }
            }
        }
    }
}
Back to top Generated by DocFX