public async Task ExecuteAsync(DiagnosticTest test)
        {
            _logger.LogInformation($"Starting {nameof(PagingDiagnostic)}");

            if (string.IsNullOrWhiteSpace(test.Table))
            {
                throw new ConfigurationException($"{nameof(test.Table)} must be set.");
            }

            try
            {
                using (var client = new ServiceNowClient(
                           _configuration.Credentials.ServiceNowAccount,
                           _configuration.Credentials.ServiceNowUsername,
                           _configuration.Credentials.ServiceNowPassword,
                           new Options {
                    ValidateCountItemsReturned = true, ValidateCountItemsReturnedTolerance = 0, PageSize = test.PageSize.Value, Logger = _logger
                }))
                {
                    var results = await client.GetAllByQueryAsync(test.Table, test.Query, fieldList : test.Fields).ConfigureAwait(false);

                    _logger.LogInformation($"Got {results.Count} results");

                    // Check for dupes
                    var dupes  = results.GroupBy(ci => ci["sys_id"]).Where(g => g.Count() > 1).Select(g => new { Id = g.First()["sys_id"], Count = g.Count() }).ToList();
                    var unique = results.GroupBy(ci => ci["sys_id"]).Select(ci => ci.First()).ToList();

                    _logger.LogInformation($"Found {dupes.Count} dupes - total retrieved = {results.Count} - unique = {unique.Count}");
                }
            }
            catch (System.Exception e)
            {
                _logger.LogError(e, e.Message);
            }
        }
        /// <summary>
        ///   Constructs a ServiceNowClient
        /// </summary>
        /// <param name="iTestOutputHelper"></param>
        /// <param name="appsettingsFilename"></param>
        /// <param name="options"></param>
        protected ServiceNowTest(
            ITestOutputHelper iTestOutputHelper,
            string appsettingsFilename = "appsettings.json",
            Options?options            = null)
        {
            options ??= new();
            Logger         = iTestOutputHelper.BuildLogger();
            options.Logger = Logger;

            // Locate the configuration file path at the root of the test project, relative from where these assemblies were deployed
            var configurationJsonFilePath = Path.Combine(Path.GetDirectoryName(typeof(ServiceNowTest).GetTypeInfo().Assembly.Location) ?? string.Empty, "../../..");
            var configurationRoot         = new ConfigurationBuilder()
                                            .SetBasePath(configurationJsonFilePath)
                                            .AddJsonFile(appsettingsFilename, optional: false, reloadOnChange: false)
                                            .Build();

            var config = new TestConfiguration
            {
                ServiceNowAccount     = configurationRoot["ServiceNowAccount"],
                ServiceNowUsername    = configurationRoot["ServiceNowUsername"],
                ServiceNowPassword    = configurationRoot["ServiceNowPassword"],
                ServiceNowEnvironment = configurationRoot["ServiceNowEnvironment"]
            };

            if (string.IsNullOrWhiteSpace(config.ServiceNowAccount))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowAccount)} must be set.");
            }

            if (string.IsNullOrWhiteSpace(config.ServiceNowUsername))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowUsername)} must be set.");
            }

            if (string.IsNullOrWhiteSpace(config.ServiceNowPassword))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowPassword)} must be set.");
            }

            var environment = ServiceNowEnvironment.Community;

            Enum.TryParse(config.ServiceNowEnvironment, true, out environment);

            options.Environment = environment;

            Client = new ServiceNowClient(
                config.ServiceNowAccount,
                config.ServiceNowUsername,
                config.ServiceNowPassword,
                options
                );
        }
示例#3
0
 public ServiceNowConnectedSystemManager(
     ConnectedSystem connectedSystem,
     State state,
     TimeSpan maxFileAge,
     ILoggerFactory loggerFactory)
     : base(connectedSystem, state, maxFileAge, loggerFactory.CreateLogger <ServiceNowConnectedSystemManager>())
 {
     _serviceNowClient = new ServiceNowClient(
         connectedSystem.Credentials.Account,
         connectedSystem.Credentials.PublicText,
         connectedSystem.Credentials.PrivateText,
         loggerFactory.CreateLogger <ServiceNowClient>());
     _cache = new QueryCache <JObject>(TimeSpan.FromMinutes(1));
 }
示例#4
0
        public async static Task Main(string[] args)
        {
            var account  = args[0];
            var username = args[1];
            var password = args[2];

            Console.WriteLine("Lists Windows Servers");

            using var serviceNowClient = new ServiceNowClient(account, username, password, new Options());

            // MANDATORY: The table name can be obtained from this list:
            // https://docs.servicenow.com/bundle/london-platform-administration/page/administer/reference-pages/reference/r_TablesAndClasses.html
            const string tableName = "cmdb_ci_win_server";

            // OPTIONAL: The main sysparm_query goes here.  See documention here:
            // https://docs.servicenow.com/bundle/geneva-servicenow-platform/page/integrate/inbound_rest/reference/r_TableAPI-GET.html
            // If you omit this, an unfiltered result will be returned
            const string query = "name";

            // OPTIONAL: The fields to bring back.
            // This should be set to constrain the response to ONLY the fields that you are going to process.
            // Doing so will hugely speed up your query.
            var fields = new List <string> {
                "sys_id", "name"
            };

            var jObjectResults = await serviceNowClient.GetAllByQueryAsync(
                tableName,
                query,
                fields
                ).ConfigureAwait(false);

            var modelResults = jObjectResults.ConvertAll(o => o.ToObject <WinServerModel>());

            Console.WriteLine("Windows Servers:");
            foreach (var modelResult in modelResults)
            {
                Console.WriteLine($"  - {modelResult.Id}: {modelResult.Name}");
            }
        }
示例#5
0
        /// <summary>
        ///   Constructs a ServiceNowClient
        /// </summary>
        /// <param name="iTestOutputHelper"></param>
        /// <param name="appsettingsFilename"></param>
        /// <param name="options"></param>
        protected ServiceNowTest(ITestOutputHelper iTestOutputHelper, string appsettingsFilename = "appsettings.json", Options options = null)
        {
            options = options ?? new Options();
            Logger  = new LoggerFactory()
                      .AddDebug(LogLevel.Trace)
                      .AddXunit(iTestOutputHelper, LogLevel.Trace)
                      .CreateLogger <ServiceNowClient>();
            options.Logger = Logger;

            // Locate the configuration file path at the root of the test project, relative from where these assemblies were deployed
            var configurationJsonFilePath = Path.Combine(Path.GetDirectoryName(typeof(ServiceNowTest).GetTypeInfo().Assembly.Location), "../../..");
            var configurationRoot         = new ConfigurationBuilder()
                                            .SetBasePath(configurationJsonFilePath)
                                            .AddJsonFile(appsettingsFilename, optional: false, reloadOnChange: false)
                                            .Build();
            var config = configurationRoot.Get <TestConfiguration>();

            if (string.IsNullOrWhiteSpace(config.ServiceNowAccount))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowAccount)} must be set.");
            }

            if (string.IsNullOrWhiteSpace(config.ServiceNowUsername))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowUsername)} must be set.");
            }

            if (string.IsNullOrWhiteSpace(config.ServiceNowPassword))
            {
                throw new Exception($"{nameof(TestConfiguration)}.{nameof(TestConfiguration.ServiceNowPassword)} must be set.");
            }

            Client = new ServiceNowClient(
                config.ServiceNowAccount,
                config.ServiceNowUsername,
                config.ServiceNowPassword,
                options
                );
        }