Beispiel #1
0
        public void Setup()
        {
            try
            {
                MockMessageBroker    broker           = new MockMessageBroker();
                MockExecutionTimer   timer            = new MockExecutionTimer();
                MockInspectorContext inspectorContext = new MockInspectorContext
                {
                    RuntimePolicyStrategy = () => RuntimePolicy.On,
                    MessageBroker         = broker,
                    TimerStrategy         = () => timer
                };

                JsonInspector inspector = new JsonInspector();
                inspector.Setup(inspectorContext);

                Assert.IsNotNull(JsonConvert.DefaultSettings);

                JsonSerializerSettings settings = JsonConvert.DefaultSettings();

                Assert.IsNotNull(settings.TraceWriter);
                Assert.IsInstanceOf <GlimpseTraceWriter>(settings.TraceWriter);
            }
            finally
            {
                JsonConvert.DefaultSettings = null;
            }
        }
        private void ConfigureWebApi(IAppBuilder app, IUnityContainer container)
        {
            var config = new HttpConfiguration()
            {
                DependencyResolver = new UnityDependencyResolver(container)
            };

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            config.EnableCors();
            JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
            {
                ContractResolver      = new CamelCasePropertyNamesContractResolver(),
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DateTimeZoneHandling  = DateTimeZoneHandling.Local
            };

            config.Formatters.JsonFormatter.SerializerSettings = JsonConvert.DefaultSettings();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));

            //doto
            //config.Services.Replace(typeof(IExceptionLogger), new GlobalExceptionLogger())
            //config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler())

            app.Map("/api", map =>
            {
                config.MapHttpAttributeRoutes();
                map.UseWebApi(config);
            });
        }
Beispiel #3
0
        protected virtual JsonSerializerSettings CreateSerializerSettings()
        {
            var settings = JsonConvert.DefaultSettings != null?JsonConvert.DefaultSettings() : new JsonSerializerSettings();

            AddOrReplaceConverters(settings.Converters);
            return(_settings = settings);
        }
Beispiel #4
0
        public void Initialize_DefaultSettings()
        {
            try
            {
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented
                };

                MockMessageBroker  broker = new MockMessageBroker();
                MockExecutionTimer timer  = new MockExecutionTimer();

                GlimpseJson.Initialize(() => RuntimePolicy.PersistResults, () => timer, broker);

                Assert.IsNotNull(JsonConvert.DefaultSettings);

                JsonSerializerSettings settings = JsonConvert.DefaultSettings();

                Assert.IsNotNull(settings.TraceWriter);
                Assert.IsInstanceOf <GlimpseTraceWriter>(settings.TraceWriter);

                Assert.AreEqual(Formatting.Indented, settings.Formatting);
            }
            finally
            {
                JsonConvert.DefaultSettings = null;
            }
        }
Beispiel #5
0
        /**
         * <summary>Initializes Cosmos network API</summary>
         * <param name="namespaceId">Bluzelle Database Namespace ID</param>
         * <param name="mnemonic">Mnemonic for account in BIP39</param>
         * <param name="address">Account address in Cosmos format. It'll be verified over given mnemonic</param>
         * <param name="chainId">Database chain ID. For Bluzelle network it equals to "bluzelle"</param>
         * <param name="endpoint">REST API endpoint including protocol and port</param>
         */
        public Cosmos(
            string namespaceId,
            string mnemonic,
            string address  = null,
            string chainId  = "bluzelle",
            string endpoint = "http://dev.testnet.public.bluzelle.com:1317")
        {
            _chainId        = chainId;
            NamespaceId     = namespaceId;
            _sessionPk      = MnemonicToPrivateKey(mnemonic);
            _sessionAddress = GetAddress(_sessionPk.PubKey);

            if (address != null && _sessionAddress != address)
            {
                throw new MnemonicInvalidException();
            }

            _restClient = new RestClient(endpoint);
            JsonConvert.DefaultSettings = () =>
                                          new JsonSerializerSettings
            {
                ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                },
                NullValueHandling = NullValueHandling.Ignore
            };

            _restClient.UseNewtonsoftJson(JsonConvert.DefaultSettings());

            _transactionQueue = new SerialQueue();

            UpdateAccount();
        }
        private dynamic ReadResource(
            IRequest request,
            HttpRequestMethod requestMethod,
            PermissionHandler <TRelation, TUser> permissionHandler)
        {
            var result = APIUtils.GetResource(dbContext, request);

            if (result == null)
            {
                return(new NotFoundResult());
            }

            var serializerSettings = JsonConvert.DefaultSettings();

            serializerSettings.ContractResolver = new APIJsonResolver <TRelation, TUser> {
                PermissionHandler = permissionHandler,
                ModelAction       = ModelAction.Read,
                RequestMethod     = requestMethod,
                IRequest          = request,
                DbContext         = dbContext,
                EngineService     = EngineService,
                IncludeBindNever  = true,
                IncludeKey        = true
            };

            EngineService.OnResourceRead(dbContext, request, result);

            Response.Headers.Add("Server", "NG-API");

            return(new OkObjectResult(JsonConvert.SerializeObject(result, serializerSettings)));
        }
Beispiel #7
0
        public IHttpActionResult Index()
        {
            var jsonText = File.ReadAllText(ApplicationMetadataFile);
            var json     = JsonConvert.DeserializeObject(jsonText, JsonConvert.DefaultSettings());

            return(Json(json, JsonConvert.DefaultSettings()));
        }
Beispiel #8
0
        /// <summary>
        /// Initializes a new <see cref="SerializerSettingsFactory"/>.
        /// </summary>
        /// <remarks>
        /// <see cref="StringEnumConverter"/> and <see cref="KindAwareDateTimeConverter"/> are essentially added to <paramref name="globalConverters"/> by default.
        /// </remarks>
        /// <param name="globalConverters"><see cref="JsonConverter"/>s to add to the settings.</param>
        public SerializerSettingsFactory(params JsonConverter[] globalConverters)
        {
            var globalConvertersList = new List <JsonConverter>
            {
                new StringEnumConverter(),
                new KindAwareDateTimeConverter()
            };

            globalConvertersList.AddRange(globalConverters);

            JsonSerializerSettings serializerSettings = null;

            // TODO: Why does this throw a StackOverflowException when called from GetJsonSerializerSettings
            if (JsonConvert.DefaultSettings != null)
            {
                serializerSettings = JsonConvert.DefaultSettings();
            }

            if (serializerSettings == null)
            {
                serializerSettings = new JsonSerializerSettings();
            }

            serializerSettings.Converters = serializerSettings.Converters ?? new List <JsonConverter>();

            foreach (var converter in globalConvertersList)
            {
                if (!HasConverter(serializerSettings.Converters, converter.GetType()))
                {
                    serializerSettings.Converters.Add(converter);
                }
            }

            _JsonSerializerSettings = serializerSettings;
        }
        private static JsonSerializer GetJsonSerializer()
        {
            // ensure the serializer will not ignore null values
            JsonSerializerSettings settings = null;

            if (JsonConvert.DefaultSettings != null)
            {
                settings = JsonConvert.DefaultSettings();
            }
            else
            {
                settings = new JsonSerializerSettings();
            }
            settings.NullValueHandling      = NullValueHandling.Include;
            settings.ReferenceLoopHandling  = ReferenceLoopHandling.Ignore;
            settings.DateTimeZoneHandling   = DateTimeZoneHandling.Utc;
            settings.Formatting             = Formatting.None;
            settings.MissingMemberHandling  = MissingMemberHandling.Ignore;
            settings.ObjectCreationHandling = ObjectCreationHandling.Replace;

            // create our custom serializer
            var writer = JsonSerializer.Create(settings);

            return(writer);
        }
Beispiel #10
0
 public static IServiceCollection AddJsonTextProcessing(this IServiceCollection services)
 {
     services.TryAddSingleton <IEnumerable <ITextTransform> >(r => new ITextTransform[] { new CamelCase(), new SnakeCase(), new PascalCase() });
     services.TryAddSingleton <IConfigureOptions <MvcOptions>, ConfigureTextOptions>();
     services.TryAddSingleton(r => JsonConvert.DefaultSettings());
     services.TryAddEnumerable(ServiceDescriptor.Scoped <IMetaParameterProvider>(r => r.GetRequiredService <IOptionsSnapshot <JsonConversionOptions> >().Value));
     return(services);
 }
Beispiel #11
0
        protected override async Task <IActionResult> ProcessWellFormedRequestAsync(GetManagementGroupsRatesRequest request, CancellationToken cancellationToken)
        {
            var managementGroupYearPointers = new ManagementGroupYearPointer[request.Identifiers.Length];

            for (var i = 0; i < managementGroupYearPointers.Length; i++)
            {
                var idParts = request.Identifiers[i].Split(
                    new char[] { '-' },
                    StringSplitOptions.RemoveEmptyEntries);

                if (idParts.Length != 2)
                {
                    return(this.httpErrorBodyResultProvider.GetHttpErrorBodyResult(
                               HttpStatusCode.BadRequest,
                               1));
                }

                if (!int.TryParse(idParts[0], out var year))
                {
                    return(this.httpErrorBodyResultProvider.GetHttpErrorBodyResult(
                               HttpStatusCode.BadRequest,
                               2,
                               idParts[0]));
                }

                if (!short.TryParse(idParts[1], out var laNumber))
                {
                    return(this.httpErrorBodyResultProvider.GetHttpErrorBodyResult(
                               HttpStatusCode.BadRequest,
                               4,
                               idParts[1]));
                }

                managementGroupYearPointers[i] = new ManagementGroupYearPointer
                {
                    Year     = year,
                    LaNumber = laNumber,
                };
            }

            var learningProviderRates = await this.managementGroupRatesManager.GetManagementGroupsRatesAsync(
                managementGroupYearPointers, request.Fields, cancellationToken);


            JsonSerializerSettings jsonSerializerSettings =
                JsonConvert.DefaultSettings();

            if (jsonSerializerSettings == null)
            {
                return(new JsonResult(learningProviderRates));
            }
            else
            {
                return(new JsonResult(
                           learningProviderRates,
                           jsonSerializerSettings));
            }
        }
Beispiel #12
0
        private static void InitializeJsonSerializer()
        {
            //_serializer = new JsonSerializer();
            var settings = JsonConvert.DefaultSettings();

            settings.Converters.Add(new TileJsonConverter());
            settings.Converters.Add(new GameAssetJSONDataConverter());
            settings.TypeNameHandling = TypeNameHandling.Auto;
        }
        private static JsonSerializerSettings GetSerializerSettings(bool withType)
        {
            var serializerSettings = JsonConvert.DefaultSettings();

            serializerSettings.TypeNameHandling = withType ?
                                                  TypeNameHandling.Auto :
                                                  TypeNameHandling.None;

            return(serializerSettings);
        }
Beispiel #14
0
        private async Task ProcessWafActionRequestAsync(HttpContext context)
        {
            Assure.ArgumentNotNull(context, nameof(context));

            var logger = context.RequestServices.GetRequiredService <ILogger <WafActionWebProcessor> >();

            var response = await ProcessAndExecuteWafActionRequestAsync(context, logger);

            // make sure the response is well-formed
            if (response == null)
            {
                response = GetErrorResponse(logger, WafActionResponseCodeEnum.InternalServerError, "Empty response.");
            }
            else if (response.Meta == null)
            {
                response.Meta = new WafActionResponseMeta(WafActionResponseCodeEnum.InternalServerError, "Empty response meta.");
            }

            // response serialization
            string responseBody = null;

            if (response.Meta.Code == WafActionResponseCodeEnum.Ok)
            {
                try
                {
                    var serializerSettings = JsonConvert.DefaultSettings();
                    // try to serialize response with data
                    if (context.Request.Headers.Keys.Contains("X-Api-Request"))
                    {
                        serializerSettings.TypeNameHandling = TypeNameHandling.Arrays;
                    }

                    responseBody = JsonConvert.SerializeObject(response, serializerSettings);
                }
                catch (Exception ex)
                {
                    response.Meta.Code         = WafActionResponseCodeEnum.InternalServerError;
                    response.Meta.ErrorMessage = $"Response data serialization error: '{ex.Message}'.";
                }
            }

            // serialize error response
            if (responseBody == null)
            {
                responseBody = JsonConvert.SerializeObject(response);
            }

            // send response
            var httpResponse = context.Response;

            httpResponse.StatusCode  = (int)response.Meta.Code;
            httpResponse.ContentType = "application/json";
            await httpResponse.WriteAsync(responseBody);
        }
Beispiel #15
0
 public GraphUserConverter()
 {
     // Get the settings if needed
     if (appId == null)
     {
         var settings     = JsonConvert.DefaultSettings();
         var jsonContract = settings.ContractResolver.ResolveContract(typeof(IOptionsMonitor <AzureADOptions>));
         var aadOptions   = (IOptionsMonitor <AzureADOptions>)jsonContract.DefaultCreator();
         appId = aadOptions.Get(AzureADDefaults.AuthenticationScheme).ClientId.Replace("-", "");
     }
 }
Beispiel #16
0
 public GraphUserConverter()
 {
     // Get the settings if needed
     if (appId == null)
     {
         var settings     = JsonConvert.DefaultSettings();
         var jsonContract = settings.ContractResolver.ResolveContract(typeof(IOptions <AzureAdOptions>));
         var aadOptions   = (IOptions <AzureAdOptions>)jsonContract.DefaultCreator();
         appId = aadOptions.Value.ClientId.Replace("-", "");
     }
 }
 static LocalDataManager()
 {
     keyArray    = Encoding.UTF8.GetBytes("fucknflsfucknflsfucknflsfucknfls");
     rij         = new RijndaelManaged();
     rij.Key     = keyArray;
     rij.Mode    = CipherMode.ECB;
     rij.Padding = PaddingMode.PKCS7;
     encryptor   = rij.CreateEncryptor();
     decryptor   = rij.CreateDecryptor();
     JsonConvert.DefaultSettings().Converters.Add(new Newtonsoft.Json.Converters.ColorConverter());
 }
        private static IContractResolver GetDefaultContractResolver()
        {
            // Would be nice to use null propagation here (requires C# 6)
            if (JsonConvert.DefaultSettings != null &&
                JsonConvert.DefaultSettings() != null &&
                JsonConvert.DefaultSettings().ContractResolver != null)
            {
                return(JsonConvert.DefaultSettings().ContractResolver);
            }

            return(new DefaultContractResolver());
        }
Beispiel #19
0
        private static JsonSerializerSettings CreateSerializerSettings(ClientVersion version)
        {
            var settings = JsonConvert.DefaultSettings != null?JsonConvert.DefaultSettings() : new JsonSerializerSettings();

            settings.ContractResolver = new ContractResolver(
                DefaultCompletionItemKinds,
                DefaultSymbolKinds,
                DefaultSymbolKinds
                );
            AddOrReplaceConverters(settings.Converters, version);

            return(settings);
        }
Beispiel #20
0
        public static IServiceCollection AddPublicApi(this IServiceCollection services, IConfiguration config)
        {
            services.Configure <PublicApiOptions>(config);

            services.AddCors();
            services.AddHttpCaching();
            services.AddGzipCompression();

            services.AddSingleton <IEnumerable <ITextTransform> >(r => new ITextTransform[] { new CamelCase(), new SnakeCase(), new PascalCase() });
            services.AddSingleton <IConfigureOptions <MvcOptions>, PublicApiMvcConfiguration>();
            services.AddSingleton(r => JsonConvert.DefaultSettings());

            return(services);
        }
Beispiel #21
0
        private void RunAPICommand(HttpListenerContext context)
        {
            try
            {
                // get type of message
                string typeName = "caveCache.API." + context.Request.RawUrl.Substring(5);
                Type   mt       = Type.GetType(typeName, false, true);
                // get the command info
                object request = null;
                using (var reader = new StreamReader(context.Request.InputStream))
                {
                    string json = reader.ReadToEnd();
                    request = JsonConvert.DeserializeObject(json, mt, JsonConvert.DefaultSettings());
                }

                if (request != null)
                {
                    object response = null;
                    lock (_cmd)
                        response = _cmd.GenericInvokeCommand(request);

                    if (response != null)
                    {
                        string json   = JsonConvert.SerializeObject(response);
                        byte[] buffer = Encoding.UTF8.GetBytes(json);
                        context.Response.StatusCode        = (int)HttpStatusCode.OK;
                        context.Response.StatusDescription = "OK";
                        context.Response.ContentType       = "application/json";
                        context.Response.ContentLength64   = buffer.Length;
                        context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        context.Response.StatusCode        = (int)HttpStatusCode.NotFound;
                        context.Response.StatusDescription = "Not found";
                    }
                }
                else
                {
                    context.Response.StatusCode        = (int)HttpStatusCode.NotFound;
                    context.Response.StatusDescription = "Not found";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.GetType().Name} {ex.Message}\r\n{ex.StackTrace}");
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                //context.Response.StatusDescription = $"Internal Error: {ex.Message} {ex.StackTrace}";
            }
        }
Beispiel #22
0
 public JsonContentSerializer(JsonSerializerSettings jsonSerializerSettings)
 {
     this.jsonSerializerSettings = new Lazy <JsonSerializerSettings>(() =>
     {
         if (jsonSerializerSettings == null)
         {
             if (JsonConvert.DefaultSettings == null)
             {
                 return(new JsonSerializerSettings());
             }
             return(JsonConvert.DefaultSettings());
         }
         return(jsonSerializerSettings);
     });
 }
Beispiel #23
0
        private static string Serialize(object obj)
        {
            if (JsonConvert.DefaultSettings == null)
            {
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings();
            }
            var settings = JsonConvert.DefaultSettings();

            settings.DefaultValueHandling = DefaultValueHandling.Ignore;
            var          serializer = JsonSerializer.Create(settings);
            StringWriter sw         = new StringWriter();

            serializer.Serialize(sw, obj);
            return(sw.ToString());
        }
        private async Task <IActionResult> ExecuteValidatedRequestAsync(
            int year,
            long urn,
            string fields,
            CancellationToken cancellationToken)
        {
            IActionResult toReturn = null;

            try
            {
                LearningProviderRates learningProviderRates =
                    await this.learningProviderRatesManager.GetLearningProviderRatesAsync(
                        year,
                        urn,
                        fields,
                        cancellationToken)
                    .ConfigureAwait(false);

                learningProviderRates.Name =
                    $"Learning Provider Rates for year {year} " +
                    $"({nameof(urn)}: {urn})";

                JsonSerializerSettings jsonSerializerSettings =
                    JsonConvert.DefaultSettings();

                if (jsonSerializerSettings == null)
                {
                    toReturn = new JsonResult(learningProviderRates);
                }
                else
                {
                    toReturn = new JsonResult(
                        learningProviderRates,
                        jsonSerializerSettings);
                }
            }
            catch (RatesNotFoundException)
            {
                toReturn =
                    this.httpErrorBodyResultProvider.GetHttpErrorBodyResult(
                        HttpStatusCode.NotFound,
                        3,
                        year.ToString(CultureInfo.InvariantCulture),
                        urn.ToString(CultureInfo.InvariantCulture));
            }

            return(toReturn);
        }
        private async Task <IActionResult> ExecuteValidatedRequestAsync(
            int year,
            short laNumber,
            string fields,
            CancellationToken cancellationToken)
        {
            IActionResult toReturn = null;

            try
            {
                ManagementGroupRates managementGroupRates =
                    await this.managementGroupRatesManager.GetManagementGroupRatesAsync(
                        year,
                        laNumber,
                        fields,
                        cancellationToken)
                    .ConfigureAwait(false);

                managementGroupRates.Name =
                    $"Management Group Rates for year {year} " +
                    $"({nameof(laNumber)}: {laNumber})";

                JsonSerializerSettings jsonSerializerSettings =
                    JsonConvert.DefaultSettings();

                if (jsonSerializerSettings == null)
                {
                    toReturn = new JsonResult(managementGroupRates);
                }
                else
                {
                    toReturn = new JsonResult(
                        managementGroupRates,
                        jsonSerializerSettings);
                }
            }
            catch (RatesNotFoundException)
            {
                toReturn =
                    this.httpErrorBodyResultProvider.GetHttpErrorBodyResult(
                        HttpStatusCode.NotFound,
                        6,
                        year.ToString(CultureInfo.InvariantCulture),
                        laNumber.ToString(CultureInfo.InvariantCulture));
            }

            return(toReturn);
        }
        public RegistryAuthService(ILogger <RegistryAuthService> logger)
        {
            var homeDirectory = Environment.OSVersion.Platform == PlatformID.Unix ?
                                Environment.GetEnvironmentVariable("HOME") ?? string.Empty :
                                Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");

            _config     = Path.Combine(homeDirectory, ".docker/config.json");
            _serializer = JsonSerializer.Create(JsonConvert.DefaultSettings());
            _logger     = logger;

            // Make sure the file exists on disk
            if (!File.Exists(_config))
            {
                File.Create(_config).Close();
            }
        }
Beispiel #27
0
        /// <inheritdoc/>
        public async Task <IDatabase> OpenAsync(string databaseId)
        {
            if (string.IsNullOrEmpty(databaseId))
            {
                databaseId = "default";
            }
            var cs       = ConnectionString.Parse(_config.DbConnectionString);
            var settings = _jsonConfig?.Serializer ?? JsonConvert.DefaultSettings();
            var client   = new DocumentClient(new Uri(cs.Endpoint),
                                              cs.SharedAccessKey, settings);
            await client.CreateDatabaseIfNotExistsAsync(new Database {
                Id = databaseId
            });

            return(new DocumentDatabase(client, databaseId, settings, _logger));
        }
Beispiel #28
0
        private dynamic CreateResource(
            IRequest request,
            HttpRequestMethod requestMethod,
            PermissionHandler <TRelation, TUser> permissionHandler,
            string jsonData)
        {
            var jsonResolver = new APIJsonResolver <TRelation, TUser> {
                DbContext         = dbContext,
                PermissionHandler = permissionHandler,
                ModelAction       = ModelAction.Create,
                RequestMethod     = requestMethod,
                IRequest          = request,
                IncludeKey        = false,
                IncludeBindNever  = false,
                EngineService     = EngineService
            };

            var serializerSettings = JsonConvert.DefaultSettings();

            serializerSettings.ContractResolver = jsonResolver;

            var model =
                JsonConvert.DeserializeObject(
                    value: jsonData,
                    type: request.Temp_ResourceType,
                    settings: serializerSettings);

            dbContext.Add(model);
            dbContext.SaveChanges();

            var intraction = new ModelInteraction <TRelation> {
                CreatorId      = permissionHandler.getRequesterID(),
                FirstModelId   = permissionHandler.getRequesterID(),
                SecondModelId  = model.GetKeyPropertyValue(),
                IntractionType = (TRelation)Enum.Parse(typeof(TRelation), "Global"),
                ModelAction    = ModelAction.Create
            };

            dbContext.MagicAddIntraction(intraction, EngineService.MapRelationToType("Global"));
            dbContext.SaveChangesAsync();

            EngineService.OnResourceCreated(dbContext, request, model, intraction);

            return(new OkObjectResult(new {
                GeneratedID = model.GetKeyPropertyValue()
            }));
        }
Beispiel #29
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var jsonSettings = JsonConvert.DefaultSettings();

            config.Formatters.JsonFormatter.SerializerSettings = jsonSettings;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
Beispiel #30
0
        static ConsoleMain()
        {
            // Set Console to UTF-8
            Console.OutputEncoding = Encoding.UTF8;
            errorMessagesReported  = new HashSet <string>();

            // Invoked from command line
            if (JsonConvert.DefaultSettings == null)
            {
                JsonConvert.DefaultSettings = () => new JsonSerializerSettings
                {
                    DefaultValueHandling = DefaultValueHandling.Ignore,
                    Error = (sender, args) =>
                    {
                        string m = args.ErrorContext.Error.Message;
                        if (!errorMessagesReported.Contains(m))
                        {
                            Console.Error.WriteLine(m);
                            errorMessagesReported.Add(m);
                        }
                        args.ErrorContext.Handled = true;
                    }
                };
            }
            serializer = JsonSerializer.Create(JsonConvert.DefaultSettings());

            if (Environment.GetCommandLineArgs().Length > 0)
            {
                // Check for a rebuild argument
                string[] args = Environment.GetCommandLineArgs();
                if (!args.Contains("--rebuild"))
                {
                    (splatTagController, importer) = SplatTagControllerFactory.CreateController();
                }
                else
                {
                    (splatTagController, importer) = SplatTagControllerFactory.CreateController(suppressLoad: true);
                }
            }
            else
            {
                (splatTagController, importer) = SplatTagControllerFactory.CreateController();
            }
        }