public void CommitOperationThrowsExceptionWhenFindNewlyAddedKeyAfterLoadOperation()
        {
            var json              = @"{
  ""name"": ""test"",
  ""address"": {
    ""street"": ""Something street"",
    ""zipcode"": ""12345""
  }
}";
            var newJson           = @"{
  ""name"": ""test"",
  ""address"": {
    ""street"": ""Something street"",
    ""zipcode"": ""12345""
  },
  ""NewKey"": ""NewValue""
}";
            var jsonConfigSrc     = new JsonConfigurationSource(ArbitraryFilePath);
            var outputCacheStream = new MemoryStream();

            jsonConfigSrc.Load(StringToStream(json));

            var exception = Assert.Throws <InvalidOperationException>(
                () => jsonConfigSrc.Commit(StringToStream(newJson), outputCacheStream));

            Assert.Equal(Resources.FormatError_CommitWhenNewKeyFound("NewKey"), exception.Message);
        }
        public void CommitOperationThrowsExceptionWhenFindInvalidModificationAfterLoadOperation()
        {
            var json              = @"{
  ""name"": ""test"",
  ""address"": {
    ""street"": ""Something street"",
    ""zipcode"": ""12345""
  }
}";
            var modifiedJson      = @"
{
  ""name"": [""first"", ""last""],
  ""address"": {
    ""street"": ""Something street"",
    ""zipcode"": ""12345""
  }
}";
            var jsonConfigSrc     = new JsonConfigurationSource(ArbitraryFilePath);
            var outputCacheStream = new MemoryStream();

            jsonConfigSrc.Load(StringToStream(json));

            var exception = Assert.Throws <FormatException>(
                () => jsonConfigSrc.Commit(StringToStream(modifiedJson), outputCacheStream));

            Assert.Equal(Resources.FormatError_UnsupportedJSONToken("StartArray", "name", 3, 12), exception.Message);
        }
        public void NonObjectRootIsInvalid()
        {
            var json             = @"'test'";
            var jsonConfigSource = new JsonConfigurationSource(ArbitraryFilePath);
            var expectedMsg      = Resources.FormatError_RootMustBeAnObject(string.Empty, 1, 6);

            var exception = Assert.Throws <FormatException>(() => jsonConfigSource.Load(StringToStream(json)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void ArraysAreNotSupported()
        {
            var json             = @"{
                'name': 'test',
                'address': ['Something street', '12345']
            }";
            var jsonConfigSource = new JsonConfigurationSource(ArbitraryFilePath);
            var expectedMsg      = Resources.FormatError_UnsupportedJSONToken("StartArray", "address", 3, 29);

            var exception = Assert.Throws <FormatException>(() => jsonConfigSource.Load(StringToStream(json)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void ThrowExceptionWhenKeyIsDuplicated()
        {
            var json          = @"{
                'name': 'test',
                'address': {
                    'street': 'Something street',
                    'zipcode': '12345'
                },
                'name': 'new name'
            }";
            var jsonConfigSrc = new JsonConfigurationSource(ArbitraryFilePath);

            var exception = Assert.Throws <FormatException>(() => jsonConfigSrc.Load(StringToStream(json)));

            Assert.Equal(Resources.FormatError_KeyIsDuplicated("name"), exception.Message);
        }
        public void ThrowExceptionWhenUnexpectedEndFoundBeforeFinishParsing()
        {
            var json             = @"{
                'name': 'test',
                'address': {
                    'street': 'Something street',
                    'zipcode': '12345'
                }
            /* Missing a right brace here*/";
            var jsonConfigSource = new JsonConfigurationSource(ArbitraryFilePath);
            var expectedMsg      = Resources.FormatError_UnexpectedEnd("address", 7, 44);

            var exception = Assert.Throws <FormatException>(() => jsonConfigSource.Load(StringToStream(json)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void CommitOperationThrowsExceptionWhenKeysAreMissingInConfigFile()
        {
            var json              = @"{
  ""name"": ""test"",
  ""address"": {
    ""street"": ""Something street"",
    ""zipcode"": ""12345""
  }
}";
            var jsonConfigSrc     = new JsonConfigurationSource(ArbitraryFilePath);
            var outputCacheStream = new MemoryStream();

            jsonConfigSrc.Load(StringToStream(json));
            json = json.Replace(@"""name"": ""test"",", string.Empty);

            var exception = Assert.Throws <InvalidOperationException>(
                () => jsonConfigSrc.Commit(StringToStream(json), outputCacheStream));

            Assert.Equal(Resources.FormatError_CommitWhenKeyMissing("name"), exception.Message);
        }
Beispiel #8
0
        internal void Load(Stream stream)
        {
            var data = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            using (var reader = new JsonTextReader(new StreamReader(stream)))
            {
                var startObjectCount = 0;

                // Dates are parsed as strings
                reader.DateParseHandling = DateParseHandling.None;

                // Move to the first token
                reader.Read();

                SkipComments(reader);

                if (reader.TokenType != JsonToken.StartObject)
                {
                    throw new FormatException(Resources.FormatError_RootMustBeAnObject(reader.Path,
                                                                                       reader.LineNumber, reader.LinePosition));
                }

                do
                {
                    SkipComments(reader);

                    switch (reader.TokenType)
                    {
                    case JsonToken.StartObject:
                        startObjectCount++;
                        break;

                    case JsonToken.EndObject:
                        startObjectCount--;
                        break;

                    // Keys in key-value pairs
                    case JsonToken.PropertyName:
                        break;

                    // Values in key-value pairs
                    case JsonToken.Integer:
                    case JsonToken.Float:
                    case JsonToken.String:
                    case JsonToken.Boolean:
                    case JsonToken.Bytes:
                    case JsonToken.Raw:
                    case JsonToken.Null:
                        var key = GetKey(reader.Path);

                        if (data.ContainsKey(key))
                        {
                            throw new FormatException(Resources.FormatError_KeyIsDuplicated(key));
                        }
                        data[key] = reader.Value.ToString();
                        break;

                    // End of file
                    case JsonToken.None:
                    {
                        throw new FormatException(Resources.FormatError_UnexpectedEnd(reader.Path,
                                                                                      reader.LineNumber, reader.LinePosition));
                    }

                    default:
                    {
                        // Unsupported elements: Array, Constructor, Undefined
                        throw new FormatException(Resources.FormatError_UnsupportedJSONToken(
                                                      reader.TokenType, reader.Path, reader.LineNumber, reader.LinePosition));
                    }
                    }

                    reader.Read();
                } while (startObjectCount > 0);
            }

            ReplaceData(data);
        }
Beispiel #9
0
        // Use the original file as a template while generating new file contents
        // to make sure the format is consistent and comments are not lost
        internal void Commit(Stream inputStream, Stream outputStream)
        {
            var processedKeys = new HashSet <string>();
            var outputWriter  = new JsonTextWriter(new StreamWriter(outputStream));

            outputWriter.Formatting = Formatting.Indented;

            using (var inputReader = new JsonTextReader(new StreamReader(inputStream)))
            {
                var startObjectCount = 0;

                // Dates are parsed as strings
                inputReader.DateParseHandling = DateParseHandling.None;

                // Move to the first token
                inputReader.Read();

                CopyComments(inputReader, outputWriter);

                if (inputReader.TokenType != JsonToken.StartObject)
                {
                    throw new FormatException(Resources.FormatError_RootMustBeAnObject(inputReader.Path,
                                                                                       inputReader.LineNumber, inputReader.LinePosition));
                }

                do
                {
                    CopyComments(inputReader, outputWriter);

                    switch (inputReader.TokenType)
                    {
                    case JsonToken.StartObject:
                        outputWriter.WriteStartObject();
                        startObjectCount++;
                        break;

                    case JsonToken.EndObject:
                        outputWriter.WriteEndObject();
                        startObjectCount--;
                        break;

                    // Keys in key-value pairs
                    case JsonToken.PropertyName:
                        outputWriter.WritePropertyName(inputReader.Value.ToString());
                        break;

                    // Values in key-value pairs
                    case JsonToken.Integer:
                    case JsonToken.Float:
                    case JsonToken.String:
                    case JsonToken.Boolean:
                    case JsonToken.Bytes:
                    case JsonToken.Raw:
                    case JsonToken.Null:
                        var key = GetKey(inputReader.Path);

                        if (!Data.ContainsKey(key))
                        {
                            throw new InvalidOperationException(Resources.FormatError_CommitWhenNewKeyFound(key));
                        }
                        outputWriter.WriteValue(Data[key]);
                        processedKeys.Add(key);
                        break;

                    // End of file
                    case JsonToken.None:
                    {
                        throw new FormatException(Resources.FormatError_UnexpectedEnd(inputReader.Path,
                                                                                      inputReader.LineNumber, inputReader.LinePosition));
                    }

                    default:
                    {
                        // Unsupported elements: Array, Constructor, Undefined
                        throw new FormatException(Resources.FormatError_UnsupportedJSONToken(
                                                      inputReader.TokenType, inputReader.Path, inputReader.LineNumber,
                                                      inputReader.LinePosition));
                    }
                    }

                    inputReader.Read();
                } while (startObjectCount > 0);

                CopyComments(inputReader, outputWriter);
                outputWriter.Flush();
            }

            if (Data.Count() != processedKeys.Count())
            {
                var missingKeys = string.Join(", ", Data.Keys.Except(processedKeys));
                throw new InvalidOperationException(Resources.FormatError_CommitWhenKeyMissing(missingKeys));
            }
        }