static ManagedGameObjectIO() { var serializer_ = new SerializerBuilder(); var typeInspectorFactories_ = serializer_.GetType().GetField("typeInspectorFactories", BindingFlags.NonPublic | BindingFlags.Instance); var typeInspectorFactories = typeInspectorFactories_.GetValue(serializer_); var Add = typeInspectorFactories.GetType().GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); Add.Invoke(typeInspectorFactories, new object[] { typeof(YamlAttributesTypeInspector), new Func <ITypeInspector, ITypeInspector>((ITypeInspector inner) => new YamlAttributesTypeInspector(inner)) }); var Remove = typeInspectorFactories.GetType().GetMethod("Remove", BindingFlags.Public | BindingFlags.Instance); Remove.Invoke(typeInspectorFactories, new object[] { typeof(YamlDotNet.Serialization.YamlAttributesTypeInspector) }); #if DEBUG var _namingConvention = serializer_.GetType().GetField("namingConvention", BindingFlags.NonPublic | BindingFlags.Instance); var namingConvention = _namingConvention.GetValue(serializer_) as INamingConvention; var objectGraphTraversalStrategyFactory = (ObjectGraphTraversalStrategyFactory)((ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable <IYamlTypeConverter> typeConverters, int maximumRecursion) => new Debug_TraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention)); serializer_.WithObjectGraphTraversalStrategyFactory(objectGraphTraversalStrategyFactory); #endif m_Serializer = serializer_.Build(); var deserializer_ = new DeserializerBuilder(); var BuildTypeInspector = deserializer_.GetType().GetMethod("BuildTypeInspector", BindingFlags.NonPublic | BindingFlags.Instance); deserializer_.WithNodeDeserializer(new ManagedGameObject_Deserializer(BuildTypeInspector.Invoke(deserializer_, new object[] { }) as ITypeInspector)); m_Deserializer = deserializer_.Build(); }
/// <summary> /// Apply YAML Serializer /// </summary> /// <param name="swaggerDoc">SwaggerDocument</param> /// <param name="context">DocumentFilterContext</param> public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context) { try { var builder = new SerializerBuilder(); builder.WithNamingConvention(new CamelCaseNamingConvention()); builder.WithTypeInspector(innerInspector => new PropertiesIgnoreTypeInspector(innerInspector)); var serializer = builder.Build(); using (var writer = new StringWriter()) { serializer.Serialize(writer, swaggerDoc); var file = Path.Combine(hostingEnvironment.WebRootPath, "swagger.yaml"); using (var stream = new StreamWriter(file)) { var result = writer.ToString(); stream .WriteLine(result .Replace("2.0", "\"2.0\"", StringComparison.OrdinalIgnoreCase) .Replace("ref:", "$ref:", StringComparison.OrdinalIgnoreCase)); } } } catch (Exception e) { Console.WriteLine(e); } }
public static RenderedProjectionDefinition <TResult> TranslateGroup <TKey, TDocument, TResult>(Expression <Func <TDocument, TKey> > idProjector, Expression <Func <IGrouping <TKey, TDocument>, TResult> > groupProjector, IBsonSerializer <TDocument> parameterSerializer, IBsonSerializerRegistry serializerRegistry) { var keyBinder = new SerializationInfoBinder(serializerRegistry); var boundKeyExpression = BindSerializationInfo(keyBinder, idProjector, parameterSerializer); if (!(boundKeyExpression is ISerializationExpression)) { var keySerializer = SerializerBuilder.Build(boundKeyExpression, serializerRegistry); boundKeyExpression = new SerializationExpression( boundKeyExpression, new BsonSerializationInfo(null, keySerializer, typeof(TKey))); } var idExpression = new IdExpression(boundKeyExpression, ((ISerializationExpression)boundKeyExpression).SerializationInfo); var groupBinder = new GroupSerializationInfoBinder(BsonSerializer.SerializerRegistry); groupBinder.RegisterMemberReplacement(typeof(IGrouping <TKey, TDocument>).GetProperty("Key"), idExpression); var groupSerializer = new ArraySerializer <TDocument>(parameterSerializer); var boundGroupExpression = BindSerializationInfo(groupBinder, groupProjector, groupSerializer); var projectionSerializer = (IBsonSerializer <TResult>)SerializerBuilder.Build(boundGroupExpression, serializerRegistry); var projection = ProjectionBuilder.Build(boundGroupExpression).AsBsonDocument; // must have an "_id" in a group document if (!projection.Contains("_id")) { var idProjection = ProjectionBuilder.Build(boundKeyExpression); projection.InsertAt(0, new BsonElement("_id", idProjection)); } return(new RenderedProjectionDefinition <TResult>(projection, projectionSerializer)); }
public SerializationBenchmarks() { var builder = new SerializerBuilder(); builder.AddType <ClosedClass>(); _serializer = builder.Build(); _serializerOfT = _serializer.GetSerializerFor <ClosedClass>(); _openClass = new OpenClass { Boolean = true, Byte = 1, Sbyte = 2, Short = 3, Ushort = 4, Int = 5, Uint = 6, Long = 7, Ulong = 8, Float = 9, Double = 10, Decimal = 11, DateTime = DateTime.UtcNow, DateTimeOffset = DateTimeOffset.UtcNow, Guid = Guid.NewGuid(), String = "Test" }; _closedClass = new ClosedClass(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, Guid.NewGuid(), DateTime.UtcNow, DateTimeOffset.UtcNow, "Test", true); }
public static void Write(Config config, TextWriter writer) { var serializerBuilder = new SerializerBuilder().WithNamingConvention(new HyphenatedNamingConvention()); var serializer = serializerBuilder.Build(); serializer.Serialize(writer, config); }
public DeserializationBenchmarks() { var builder = new SerializerBuilder(); builder.AddType <ClosedClass>(); _serializer = builder.Build(); _serializerOfT = _serializer.GetSerializerFor <ClosedClass>(); _guid = Guid.NewGuid(); _dateTime = DateTime.UtcNow; _dateTimeOffset = DateTimeOffset.UtcNow; var openClass = new OpenClass { Boolean = true, Byte = 1, Sbyte = 2, Short = 3, Ushort = 4, Int = 5, Uint = 6, Long = 7, Ulong = 8, Float = 9, Double = 10, Decimal = 11, DateTime = _dateTime, DateTimeOffset = _dateTimeOffset, Guid = _guid, String = "Test" }; _bytes = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(openClass); }
private static void SaveConfig(string path, object obj, bool useFlowStyleList = false) { Directory.CreateDirectory(ConfigDir); //string jsonConfig = JsonConvert.SerializeObject(obj, Formatting.Indented); SerializerBuilder yamlBuilder; yamlBuilder = new SerializerBuilder().WithNamingConvention(PascalCaseNamingConvention.Instance); if (useFlowStyleList) { yamlBuilder.WithEventEmitter(next => new FlowStyleStringListEmitter(next)); } ISerializer yamlSerializer = yamlBuilder.Build(); string yamlConfig = yamlSerializer.Serialize(obj); for (int i = 0; i < 10; i++) { if (IsFileLocked(new FileInfo(path))) { Thread.Sleep(500); } else { using StreamWriter writer = new(File.Open(path, FileMode.Create, FileAccess.Write)); writer.WriteLine(yamlConfig); writer.Close(); return; } } throw new TimeoutException($"Saving to {path} failed after 10 retries"); }
private Expression BindSelector(ProjectionExpression projection, ProjectionBindingContext context, Expression id, Expression node) { var lambda = ExtensionExpressionVisitor.GetLambda(node); var binder = new AccumulatorBinder(context.GroupMap, context.SerializerRegistry); var serializer = SerializerBuilder.Build(projection.Projector, context.SerializerRegistry); var sequenceSerializer = (IBsonSerializer)Activator.CreateInstance( typeof(ArraySerializer <>).MakeGenericType(projection.Projector.Type), new object[] { serializer }); var sequenceInfo = new BsonSerializationInfo( null, sequenceSerializer, sequenceSerializer.ValueType); var sequenceExpression = new SerializationExpression( lambda.Parameters[1], sequenceInfo); binder.RegisterParameterReplacement(lambda.Parameters[0], id); binder.RegisterParameterReplacement(lambda.Parameters[1], sequenceExpression); var correlationId = Guid.NewGuid(); context.GroupMap.Add(sequenceExpression, correlationId); var bound = binder.Bind(lambda.Body); return(CorrelatedAccumulatorRemover.Remove(bound, correlationId)); }
public static SimulationConfiguration LoadConfigOrDefault() { if (File.Exists("Simulation.cfg")) { string sourceText = File.ReadAllText("Simulation.cfg"); Deserializer yamlDeserializer = new Deserializer(); SimulationConfiguration deserialized = yamlDeserializer.Deserialize <SimulationConfiguration>(sourceText); CheckLoadedConfig(deserialized); // Write config with updated values SerializerBuilder builder = new SerializerBuilder(); builder.EmitDefaults(); Serializer yamlSerializer = builder.Build(); string serialized = yamlSerializer.Serialize(deserialized); File.WriteAllText("Simulation.cfg", serialized); return(deserialized); } else { // Write out default config if there is no config for easier adjustment SerializerBuilder builder = new SerializerBuilder(); builder.EmitDefaults(); Serializer yamlSerializer = builder.Build(); string serialized = yamlSerializer.Serialize(DefaultConfig); File.WriteAllText("Simulation.cfg", serialized); return(DefaultConfig); } }
public static void ToYamlFile(IEnumerable <MirakurunChannel> list, string filePath) { if (list is null) { return; } if (File.Exists(filePath)) { if (MessageBox.Show($"Target file : \n{filePath}\n is already exists, do you want to overwrite it?", "Attention", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { try { File.SetAttributes(filePath, FileAttributes.Normal); File.Delete(filePath); } catch { MessageBox.Show($"Unable to overwrite target file : \n{filePath}", "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); return; } } else { return; } } var builder = new SerializerBuilder(); var serializer = builder.Build(); using (var writer = File.CreateText(filePath)) { serializer.Serialize(writer, list); } }
public static Serializer Create(SwaggerYamlOptions swaggerYamlOptions) { var builder = new SerializerBuilder(); switch (swaggerYamlOptions.NamingConvention) { case NamingConvention.CamelCase: builder.WithNamingConvention(new CamelCaseNamingConvention()); break; case NamingConvention.Hyphenated: builder.WithNamingConvention(new HyphenatedNamingConvention()); break; case NamingConvention.PascalCase: builder.WithNamingConvention(new PascalCaseNamingConvention()); break; case NamingConvention.Underscored: builder.WithNamingConvention(new UnderscoredNamingConvention()); break; } builder.WithTypeInspector(innerInspector => new PropertiesIgnoreTypeInspector(innerInspector, swaggerYamlOptions.IgnoredProperties)); builder.WithTypeInspector(innerInspector => new JsonPropertyNameApplyingTypeInspector(innerInspector)); builder.WithTypeInspector(innerInspector => new StringQuotingTypeInspector(innerInspector)); return(builder.Build()); }
public static void Serialize(Stream dest, object value) { var type = value.GetType(); SerializerBuilder.Build(Model, type); Model.Serialize(dest, value); }
public static string Serialize <T>(T obj, bool emitDefaults = false) where T : class { SerializerBuilder serializerBuilder = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance); ISerializer serializer = serializerBuilder.Build(); return(serializer.Serialize(obj)); }
public void Save <T>() { try { if (File.Exists(this.filePath)) { StreamWriter w = new StreamWriter(this.filePath, false, Encoding.UTF8); SerializerBuilder sb = new SerializerBuilder() .EmitDefaults() .WithTypeInspector(inner => new CommentTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new CommentObjectGraphVisitor(args.InnerVisitor)); Serializer s = (Serializer)sb.Build(); s.Serialize(w, this, typeof(T)); w.Close(); } else { FileStream file = File.Create(this.filePath); file.Close(); StreamWriter w = new StreamWriter(this.filePath, false, Encoding.UTF8); SerializerBuilder sb = new SerializerBuilder() .EmitDefaults() .WithTypeInspector(inner => new CommentTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new CommentObjectGraphVisitor(args.InnerVisitor)); Serializer s = (Serializer)sb.Build(); s.Serialize(w, this, typeof(T)); w.Close(); } } catch (Exception e) { throw e; } }
/// <summary> /// Adds and configures an YamlDotNet <see cref="ISerializer"/> and <see cref="IDeserializer"/> /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to configure</param> /// <param name="serializerConfiguration">The <see cref="Action{T}"/> used to configure the <see cref="ISerializer"/> to add</param> /// <param name="deserializerConfiguration">The <see cref="Action{T}"/> used to configure the <see cref="IDeserializer"/> to add</param> /// <returns>The configured <see cref="IServiceCollection"/></returns> public static IServiceCollection AddYamlDotNet(this IServiceCollection services, Action <SerializerBuilder> serializerConfiguration = null, Action <DeserializerBuilder> deserializerConfiguration = null) { services.TryAddSingleton(provider => { SerializerBuilder builder = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance); serializerConfiguration?.Invoke(builder); return(builder.Build()); }); services.TryAddSingleton(provider => { DeserializerBuilder builder = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .WithNodeDeserializer( inner => new JArrayDeserializer(inner), syntax => syntax.InsteadOf <ArrayNodeDeserializer>()) .WithNodeDeserializer( inner => new AbstractTypeDeserializer(inner), syntax => syntax.InsteadOf <ObjectNodeDeserializer>()) .WithNodeDeserializer( inner => new JTokenDeserializer(inner), syntax => syntax.InsteadOf <DictionaryNodeDeserializer>()) .WithObjectFactory(new NonPublicConstructorObjectFactory()) .IncludeNonPublicProperties(); deserializerConfiguration?.Invoke(builder); return(builder.Build()); }); return(services); }
public static ProjectionInfo <TResult> TranslateGroup <TKey, TDocument, TResult>(Expression <Func <TDocument, TKey> > idProjector, Expression <Func <IGrouping <TKey, TDocument>, TResult> > groupProjector, IBsonSerializer <TDocument> parameterSerializer, IBsonSerializerRegistry serializerRegistry) { if (groupProjector.Body.NodeType != ExpressionType.New) { throw new NotSupportedException("Must use an anonymous type for constructing $group pipeline operators."); } var keyBinder = new SerializationInfoBinder(serializerRegistry); var boundKeyExpression = BindSerializationInfo(keyBinder, idProjector, parameterSerializer); var groupBinder = new GroupSerializationInfoBinder(BsonSerializer.SerializerRegistry); groupBinder.RegisterMemberReplacement(typeof(IGrouping <TKey, TDocument>).GetProperty("Key"), boundKeyExpression); var groupSerializer = new ArraySerializer <TDocument>(parameterSerializer); var boundGroupExpression = BindSerializationInfo(groupBinder, groupProjector, groupSerializer); var projectionSerializer = (IBsonSerializer <TResult>)SerializerBuilder.Build(boundGroupExpression, serializerRegistry); var projection = ProjectionBuilder.Build(boundGroupExpression).AsBsonDocument; // must have an "_id" in a group document if (!projection.Contains("_id")) { var idProjection = ProjectionBuilder.Build(boundKeyExpression); projection.InsertAt(0, new BsonElement("_id", idProjection)); } return(new ProjectionInfo <TResult>(projection, projectionSerializer)); }
public static GameConfig LoadConfigOrDefault() { if (File.Exists("Config.cfg")) { string sourceText = File.ReadAllText("Config.cfg"); Deserializer yamlDeserializer = new Deserializer(); GameConfig deserialized = yamlDeserializer.Deserialize <GameConfig>(sourceText); CheckLoadedConfig(deserialized); SerializerBuilder builder = new SerializerBuilder(); builder.EmitDefaults(); Serializer yamlSerializer = builder.Build(); string serialized = yamlSerializer.Serialize(deserialized); File.WriteAllText("Config.cfg", serialized); return(deserialized); } else { // Write out default config if there is no config for easier adjustment SerializerBuilder builder = new SerializerBuilder(); builder.EmitDefaults(); Serializer yamlSerializer = builder.Build(); string serialized = yamlSerializer.Serialize(DefaultConfig); File.WriteAllText("Config.cfg", serialized); return(DefaultConfig); } }
public void Save() { if (File.Exists(this.FilePath)) { StreamWriter w = new StreamWriter(this.FilePath, false, Encoding.UTF8); SerializerBuilder sb = new SerializerBuilder() .EmitDefaults() .WithTypeInspector(inner => new CommentTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new CommentObjectGraphVisitor(args.InnerVisitor)); Serializer s = sb.Build(); s.Serialize(w, this.Root, typeof(Dictionary <string, object>)); w.Close(); } else { FileStream file = File.Create(this.FilePath); file.Close(); StreamWriter w = new StreamWriter(this.FilePath, false, Encoding.UTF8); SerializerBuilder sb = new SerializerBuilder() .EmitDefaults() .WithTypeInspector(inner => new CommentTypeInspector(inner)) .WithEmissionPhaseObjectGraphVisitor(args => new CommentObjectGraphVisitor(args.InnerVisitor)); Serializer s = sb.Build(); s.Serialize(w, this.Root, typeof(Dictionary <string, object>)); w.Close(); } }
private Expression BuildProjector(Expression selector, ProjectionBindingContext context) { var selectorNode = selector; if (!(selectorNode is ISerializationExpression)) { var serializer = SerializerBuilder.Build(selector, context.SerializerRegistry); BsonSerializationInfo info; switch (selector.NodeType) { case ExpressionType.MemberInit: case ExpressionType.New: info = new BsonSerializationInfo(null, serializer, serializer.ValueType); break; default: // this occurs when a computed field is used. This is a magic string // that shouldn't ever be reference anywhere else... info = new BsonSerializationInfo("__fld0", serializer, serializer.ValueType); break; } selectorNode = new SerializationExpression(selector, info); } return(selectorNode); }
public static string ToYaml <T>(this T obj) { SerializerBuilder sb = new SerializerBuilder() .EmitDefaults(); Serializer s = (Serializer)sb.Build(); return(s.Serialize(obj)); }
private void Save(TYamlSettings settingsYaml) { var serializer = SerializerBuilder.Build(); _ioLock.Wait(); this.WriteAllText(serializer.Serialize(settingsYaml)); _ioLock.Release(); }
public static byte[] Serialize(object obj, Type type) { SerializerBuilder.Build(Model, type); var ms = new MemoryStream(); Model.Serialize(ms, obj); return(ms.ToArray()); }
public static void SaveGameModeYaml(GameModeYaml gameModeYaml) { var serializer = SerializerBuilder.Build(); var gameModeFolder = new GameModesFolder().CreateFolder(gameModeYaml.Name, CreationCollisionOption.OpenIfExists); var gameModeFile = gameModeFolder.CreateFile(GameModeFilename, CreationCollisionOption.ReplaceExisting); gameModeFile.WriteAllText(serializer.Serialize(gameModeYaml)); }
public static Serializer CreateSerializer() { var builder = new SerializerBuilder(); builder.WithNamingConvention(namingConvention); return(builder.Build()); }
private static ISerializer InitializeSerializer() { var serializerBuilder = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitDefaults | DefaultValuesHandling.OmitEmptyCollections); return(serializerBuilder.Build()); }
private static ISerializer GetSerializer() { var serializerBuilder = new SerializerBuilder() .WithEmissionPhaseObjectGraphVisitor(args => new DefaultExclusiveObjectGraphVisitor(args.InnerVisitor)) .WithTypeConverter(new YamlStringEnumConverter()); var serializer = serializerBuilder.Build(); return(serializer); }
public static ISerializer CreateSerializer() { var builder = new SerializerBuilder(); builder.WithNamingConvention(namingConvention); builder.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitDefaults); return(builder.Build()); }
private async Task SaveAsync(TYamlSettings settingsYaml) { var serializer = SerializerBuilder.Build(); await _ioLock.WaitAsync(); await this.WriteAllTextAsync(serializer.Serialize(settingsYaml)); _ioLock.Release(); }
public static object Deserialize(Stream stream, Type type) { SerializerBuilder.Build(Model, type); if (stream.CanSeek) { stream.Position = 0; } return(Model.Deserialize(stream, null, type)); }
public static void Save() { var serializerBuilder = new SerializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()); var serializer = serializerBuilder.Build(); string body = serializer.Serialize(instance); Console.WriteLine(body); File.WriteAllText(@"eqemupatcher.yml", body); }