Ejemplo n.º 1
0
        public void OneTimeSetup()
        {
            var contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    OverrideSpecifiedNames = false,
                    ProcessDictionaryKeys  = true,
                }
            };

            DefaultSettings = new JsonSerializerSettings
            {
                Formatting       = Formatting.None,
                ContractResolver = contractResolver,
                Converters       = new JsonConverterCollection(),
            };

            var optimizedConverters = new JsonConverterCollection();

            optimizedConverters.Add(DoubleArrayConverter.Create(6));
            OptimizedSettings = new JsonSerializerSettings
            {
                Formatting       = Formatting.None,
                ContractResolver = contractResolver,
                Converters       = optimizedConverters,
            };
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, params JsonConverter[] converters)
        {
            var jsonConverterCollection = new JsonConverterCollection();

            jsonConverterCollection.AddRange(converters);
            WriteTo(writer, jsonConverterCollection);
        }
Ejemplo n.º 3
0
        public RazorConfigurationSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.RegisterRazorConverters();
            Converters = converters.ToArray();
        }
Ejemplo n.º 4
0
        public ProjectSnapshotHandleSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.RegisterRazorConverters();
            Converters = converters.ToArray();
        }
        public void ProjectSnapshotHandleProxy_RoundTripsProperly()
        {
            // Arrange
            var tagHelpers = new[]
            {
                TagHelperDescriptorBuilder.Create("TestTagHelper", "TestAssembly").Build(),
                TagHelperDescriptorBuilder.Create("TestTagHelper2", "TestAssembly2").Build(),
            };
            var projectWorkspaceState = new ProjectWorkspaceState(tagHelpers);
            var expectedConfiguration = RazorConfiguration.Default;
            var expectedRootNamespace = "project";
            var handle = new ProjectSnapshotHandleProxy(new Uri("vsls://some/path/project.csproj"), RazorConfiguration.Default, expectedRootNamespace, projectWorkspaceState);
            var converterCollection = new JsonConverterCollection();

            converterCollection.RegisterRazorLiveShareConverters();
            var converters       = converterCollection.ToArray();
            var serializedHandle = JsonConvert.SerializeObject(handle, converters);

            // Act
            var deserializedHandle = JsonConvert.DeserializeObject <ProjectSnapshotHandleProxy>(serializedHandle, converters);

            // Assert
            Assert.Equal("vsls://some/path/project.csproj", deserializedHandle.FilePath.ToString());
            Assert.Equal(projectWorkspaceState, deserializedHandle.ProjectWorkspaceState);
            Assert.Equal(expectedConfiguration.ConfigurationName, deserializedHandle.Configuration.ConfigurationName);
            Assert.Equal(expectedConfiguration.Extensions.Count, deserializedHandle.Configuration.Extensions.Count);
            Assert.Equal(expectedConfiguration.LanguageVersion, deserializedHandle.Configuration.LanguageVersion);
            Assert.Equal(expectedRootNamespace, deserializedHandle.RootNamespace);
        }
        public RazorExtensionSerializationTest()
        {
            var converters = new JsonConverterCollection();

            converters.Add(RazorExtensionJsonConverter.Instance);
            Converters = converters.ToArray();
        }
Ejemplo n.º 7
0
        private static IEnumerable <JsonConverter> GetRazorConverters()
        {
            var collection = new JsonConverterCollection();

            collection.RegisterRazorConverters();
            return(collection);
        }
Ejemplo n.º 8
0
            public FastCompoundKey(Type type, JsonConverterCollection collection)
                : base(type.GetHashCode() * 17 + collection.GetHashCode())
            {
                Debug.Assert(collection.IsFrozen);

                this.Type       = type;
                this.Collection = collection;
            }
Ejemplo n.º 9
0
            public SlowCompoundKey(Type type, JsonConverterCollection collection)
                : base(type.GetHashCode() * 17 + collection.GetHashCode())
            {
                Debug.Assert(collection.IsFrozen);

                this.Type       = type;
                this.Collection = new WeakReference <JsonConverterCollection>(collection);
            }
Ejemplo n.º 10
0
        static MapReduceIndex()
        {
            MapReduceConverters = new JsonConverterCollection(Default.Converters)
            {
                new IgnoreFieldable()
            };

            MapReduceConverters.Freeze();
        }
Ejemplo n.º 11
0
        static MapReduceIndex()
        {
            MapReduceConverters = new JsonConverterCollection(Default.Converters)
            {
                new IgnoreFieldable()
            };

            MapReduceConverters.Freeze();
        }
        public RazorConfigurationSerializationTest()
        {
            var converters = new JsonConverterCollection
            {
                RazorExtensionJsonConverter.Instance,
                RazorConfigurationJsonConverter.Instance
            };

            Converters = converters.ToArray();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WriteStartArray();

            for (int i = 0; i < _values.Count; i++)
            {
                _values[i].WriteTo(writer, converters);
            }

            writer.WriteEndArray();
        }
Ejemplo n.º 14
0
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WriteStartObject();

            for (int i = 0; i < _properties.Count; i++)
            {
                _properties[i].WriteTo(writer, converters);
            }

            writer.WriteEndObject();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WriteStartConstructor(_name);

            foreach (JToken token in Children())
            {
                token.WriteTo(writer, converters);
            }

            writer.WriteEndConstructor();
        }
Ejemplo n.º 16
0
        public static JsonConverter GetMatchingConverter(JsonConverterCollection converters, Type type)
        {
            if (converters == null)
            {
                return(null);
            }

            if (!converters.IsFrozen)
            {
                int count = converters.Count;
                for (int i = 0; i < count; i++)
                {
                    var conv = converters[i];
                    if (conv.CanConvert(type))
                    {
                        return(conv);
                    }
                }

                return(null);
            }
            else
            {
                var key = new FastCompoundKey(type, converters);

                JsonConverter converter;

                // The locking will prevent the original thread to be able to continue until the one that got it releases it
                // With a lockless implementation we have found non-reproducible NullReferenceExceptions. The hypothesis is that task stealing
                // (lightweight threading) may be the culprit. I prefer to pay 10% in performance here than fail or mask the error with extra indirections.
                var cache = Cache;
                lock ( cache )
                {
                    if (!cache.TryGetValue(key, out converter))
                    {
                        int count = converters.Count;
                        for (int i = 0; i < count; i++)
                        {
                            var conv = converters[i];
                            if (conv.CanConvert(type))
                            {
                                converter = conv;
                                break;
                            }
                        }

                        var newKey = new SlowCompoundKey(type, converters);
                        cache[newKey] = converter;
                    }
                }

                return(converter);
            }
        }
Ejemplo n.º 17
0
        public static void RegisterRazorConverters(this JsonConverterCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            for (var i = 0; i < RazorConverters.Count; i++)
            {
                collection.Add(RazorConverters[i]);
            }
        }
Ejemplo n.º 18
0
        public static JsonConverterCollection DefaultConveter()
        {
            JsonConverterCollection converters = new JsonConverterCollection();
            IsoDateTimeConverter    item       = new IsoDateTimeConverter {
                DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
            };
            EntityConverter converter2 = new EntityConverter();

            converters.Add(item);
            converters.Add(converter2);
            return(converters);
        }
		public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
		{
			if (jsonWriter == null)
				throw new ArgumentNullException("jsonWriter");

			if (objectType != null)
				_rootContract = Serializer._contractResolver.ResolveContract(objectType);

            _internalConverters = Serializer.Converters;

			SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
		}
Ejemplo n.º 20
0
        public static string ObjectToJson2(object value, bool clearLastZero)
        {
            //IL_0008: Unknown result type (might be due to invalid IL or missing references)
            //IL_000e: Expected O, but got Unknown
            //IL_0027: Unknown result type (might be due to invalid IL or missing references)
            //IL_0031: Expected O, but got Unknown
            //IL_0038: Unknown result type (might be due to invalid IL or missing references)
            //IL_003d: Unknown result type (might be due to invalid IL or missing references)
            //IL_004a: Expected O, but got Unknown
            //IL_0051: Unknown result type (might be due to invalid IL or missing references)
            //IL_005b: Expected O, but got Unknown
            //IL_005c: Unknown result type (might be due to invalid IL or missing references)
            //IL_0062: Expected O, but got Unknown
            //IL_00aa: Unknown result type (might be due to invalid IL or missing references)
            //IL_00b1: Expected O, but got Unknown
            Type           type = value.GetType();
            JsonSerializer val  = new JsonSerializer();

            val.ObjectCreationHandling = ObjectCreationHandling.Replace;
            val.MissingMemberHandling  = MissingMemberHandling.Ignore;
            val.ReferenceLoopHandling  = ReferenceLoopHandling.Ignore;
            val.ContractResolver       = new CamelCasePropertyNamesContractResolver();
            JsonConverterCollection converters = val.Converters;
            StringEnumConverter     val2       = new StringEnumConverter();

            val2.CamelCaseText = true;
            ((Collection <JsonConverter>)converters).Add(val2);
            ((Collection <JsonConverter>)val.Converters).Add(new StringEnumConverter());
            IsoDateTimeConverter val3 = new IsoDateTimeConverter();

            val3.DateTimeFormat = "yyyy-MM-dd";
            ((Collection <JsonConverter>)val.Converters).Add(val3);
            val.Formatting        = Formatting.None;
            val.NullValueHandling = NullValueHandling.Ignore;
            if (clearLastZero)
            {
                ((Collection <JsonConverter>)val.Converters).Add(new MinifiedNumArrayConverter());
            }
            StringWriter   stringWriter = new StringWriter();
            JsonTextWriter val4         = new JsonTextWriter((TextWriter)stringWriter);

            val4.Formatting = Formatting.None;
            val4.QuoteChar  = '"';
            val4.QuoteName  = false;
            val.Serialize(val4, value);
            string text = stringWriter.ToString();

            val4.Close();
            stringWriter.Close();
            return(text.Replace("coreCharts", "echarts", StringComparison.CurrentCultureIgnoreCase));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Writes this token to a <see cref="JsonWriter"/>.
        /// </summary>
        /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
        /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WriteStartArray();

            if (Items != null)
            {
                foreach (var token in Items)
                {
                    token.WriteTo(writer, converters);
                }
            }

            writer.WriteEndArray();
        }
        public static void RegisterRazorConverters(this JsonConverterCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            collection.Add(TagHelperDescriptorJsonConverter.Instance);
            collection.Add(RazorDiagnosticJsonConverter.Instance);
            collection.Add(RazorExtensionJsonConverter.Instance);
            collection.Add(RazorConfigurationJsonConverter.Instance);
            collection.Add(ProjectSnapshotJsonConverter.Instance);
            collection.Add(ProjectSnapshotHandleJsonConverter.Instance);
        }
Ejemplo n.º 23
0
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WritePropertyName(_name);

            JToken value = Value;

            if (value != null)
            {
                value.WriteTo(writer, converters);
            }
            else
            {
                writer.WriteNull();
            }
        }
Ejemplo n.º 24
0
        public static void RegisterRazorLiveShareConverters(this JsonConverterCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            if (collection.Contains(ProjectSnapshotHandleProxyJsonConverter.Instance))
            {
                // Already registered.
                return;
            }

            collection.Add(ProjectSnapshotHandleProxyJsonConverter.Instance);
            collection.RegisterRazorConverters();
        }
        public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
        {
            if (jsonWriter == null)
            {
                throw new ArgumentNullException("jsonWriter");
            }

            if (objectType != null)
            {
                _rootContract = Serializer._contractResolver.ResolveContract(objectType);
            }

            _internalConverters = Serializer.Converters;

            SerializeValue(jsonWriter, value, GetContractSafe(value), null, null, null);
        }
Ejemplo n.º 26
0
        public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
        {
            if (jsonWriter == null)
            {
                throw new ArgumentNullException("jsonWriter");
            }

            _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
            _rootLevel    = _serializeStack.Count + 1;

            _internalConverters = Serializer.Converters;

            JsonContract contract = GetContractSafe(value);

            try
            {
                if (ShouldWriteReference(value, null, contract, null, null))
                {
                    WriteReference(jsonWriter, value);
                }
                else
                {
                    SerializeValue(jsonWriter, value, contract, null, null, null);
                }
            }
            catch (Exception ex)
            {
                if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
                {
                    HandleError(jsonWriter, 0);
                }
                else
                {
                    // clear context in case serializer is being used inside a converter
                    // if the converter wraps the error then not clearing the context will cause this error:
                    // "Current error context error is different to requested error."
                    ClearErrorContext();
                    throw;
                }
            }
            finally
            {
                // clear root contract to ensure that if level was > 1 then it won't
                // accidently be used for non root values
                _rootContract = null;
            }
        }
 public SerializationTest()
 {
     var languageVersion = RazorLanguageVersion.Experimental;
     var extensions = new RazorExtension[]
     {
         new SerializedRazorExtension("TestExtension"),
     };
     Configuration = RazorConfiguration.Create(languageVersion, "Custom", extensions);
     ProjectWorkspaceState = new ProjectWorkspaceState(new[]
     {
         TagHelperDescriptorBuilder.Create("Test", "TestAssembly").Build(),
     },
     LanguageVersion.LatestMajor);
     var converterCollection = new JsonConverterCollection();
     converterCollection.RegisterRazorConverters();
     Converters = converterCollection.ToArray();
 }
        public void Serialize(JsonWriter jsonWriter, object value, Type objectType)
        {
            if (jsonWriter == null)
                throw new ArgumentNullException("jsonWriter");

            _rootContract = (objectType != null) ? Serializer._contractResolver.ResolveContract(objectType) : null;
            _rootLevel = _serializeStack.Count + 1;

            _internalConverters = Serializer.Converters;

            JsonContract contract = GetContractSafe(value);

            try
            {
                if (ShouldWriteReference(value, null, contract, null, null))
                {
                    WriteReference(jsonWriter, value);
                }
                else
                {
                    SerializeValue(jsonWriter, value, contract, null, null, null);
                }
            }
            catch (Exception ex)
            {
                if (IsErrorHandled(null, contract, null, null, jsonWriter.Path, ex))
                {
                    HandleError(jsonWriter, 0);
                }
                else
                {
                    // clear context in case serializer is being used inside a converter
                    // if the converter wraps the error then not clearing the context will cause this error:
                    // "Current error context error is different to requested error."
                    ClearErrorContext();
                    throw;
                }
            }
            finally
            {
                // clear root contract to ensure that if level was > 1 then it won't
                // accidently be used for non root values
                _rootContract = null;
            }
        }
Ejemplo n.º 29
0
        public static JsonSerializerSettings GetDefaultSerializerSettings()
        {
            JsonSerializerSettings serializerSettings1 = new JsonSerializerSettings();

            serializerSettings1.Formatting = (Formatting)1;
            JsonSerializerSettings  serializerSettings2  = serializerSettings1;
            JsonConverterCollection converterCollection1 = new JsonConverterCollection();

            converterCollection1.Add(new StringEnumConverter());
            JsonConverterCollection converterCollection2 = converterCollection1;
            IsoDateTimeConverter    dateTimeConverter1   = new IsoDateTimeConverter();

            dateTimeConverter1.DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK";
            IsoDateTimeConverter dateTimeConverter2 = dateTimeConverter1;

            converterCollection2.Add(dateTimeConverter2);
            JsonConverterCollection converterCollection3 = converterCollection1;

            serializerSettings2.Converters = converterCollection3;
            return(serializerSettings1);
        }
Ejemplo n.º 30
0
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            writer.WriteStartObject();

            if (Properties != null)
            {
                foreach (var property in Properties)
                {
                    writer.WritePropertyName(property.Key);
                    if (property.Value == null)
                    {
                        writer.WriteNull();
                    }
                    else
                    {
                        property.Value.WriteTo(writer, converters);
                    }
                }
            }

            writer.WriteEndObject();
        }
Ejemplo n.º 31
0
 /// <summary>
 ///     Writes this token to a <see cref="JsonWriter" />.
 /// </summary>
 /// <param name="writer">A <see cref="JsonWriter" /> into which this method will write.</param>
 /// <param name="converters">A collection of <see cref="JsonConverter" /> which will be used when writing the token.</param>
 public abstract void WriteTo(JsonWriter writer, JsonConverterCollection converters);
Ejemplo n.º 32
0
 public static void RegisterOmniSharpRazorConverters(this JsonConverterCollection collection)
 {
     collection.RegisterRazorConverters();
     collection.Add(OmniSharpProjectSnapshotHandleJsonConverter.Instance);
 }
Ejemplo n.º 33
0
        public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
        {
            switch (_valueType)
            {
            case JTokenType.Comment:
                writer.WriteComment(_value.ToString());
                return;

            case JTokenType.Raw:
                writer.WriteRawValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Null:
                writer.WriteNull();
                return;

            case JTokenType.Undefined:
                writer.WriteUndefined();
                return;
            }

            if (_value != null)
            {
                Type typeToFind = _value.GetType();

                // If we are using the default converters we will try to avoid repeatedly check the same types as
                // GetMatchingConverter is a costly call with a very low probability to hit (less than 1% in real scenarios).
                JsonConverter matchingConverter = JsonConverterCache.GetMatchingConverter(converters, typeToFind);
                if (matchingConverter != null)
                {
                    matchingConverter.WriteJson(writer, _value, JsonExtensions.CreateDefaultJsonSerializer());
                    return;
                }
            }

            switch (_valueType)
            {
            case JTokenType.Integer:
                writer.WriteValue(Convert.ToInt64(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Float:
                if (_value is decimal)
                {
                    writer.WriteValue((decimal)_value);
                    return;
                }
                if (_value is float)
                {
                    writer.WriteValue((float)_value);
                    return;
                }
                writer.WriteValue(Convert.ToDouble(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.String:
                writer.WriteValue((_value != null) ? _value.ToString() : null);
                return;

            case JTokenType.Boolean:
                writer.WriteValue(Convert.ToBoolean(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Date:
#if !PocketPC && !NET20
                if (_value is DateTimeOffset)
                {
                    writer.WriteValue((DateTimeOffset)_value);
                }
                else
#endif
                writer.WriteValue(Convert.ToDateTime(_value, CultureInfo.InvariantCulture));
                return;

            case JTokenType.Bytes:
                writer.WriteValue((byte[])_value);
                return;

            case JTokenType.Guid:
            case JTokenType.Uri:
            case JTokenType.TimeSpan:
                writer.WriteValue((_value != null) ? _value.ToString() : null);
                return;
            }

            throw MiscellaneousUtils.CreateArgumentOutOfRangeException("TokenType", _valueType, "Unexpected token type.");
        }
Ejemplo n.º 34
0
	    /// <summary>
	    /// Writes this token to a <see cref="JsonWriter"/>.
	    /// </summary>
	    /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param>
	    /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param>
		public override void WriteTo(JsonWriter writer, JsonConverterCollection converters)
	    {
		    writer.WriteStartConstructor(_name);

            foreach (JToken token in Children())
            {
                token.WriteTo(writer, converters);
            }

            writer.WriteEndConstructor();
        }