private static MessagePackSerializerOptions CreateMessagePackSerializerOptions() { var formatters = new IMessagePackFormatter[] { FloatRangeFormatter.Instance, IPackageReferenceContextInfoFormatter.Instance, IProjectContextInfoFormatter.Instance, IProjectMetadataContextInfoFormatter.Instance, NuGetFrameworkFormatter.Instance, NuGetVersionFormatter.Instance, PackageDependencyFormatter.Instance, PackageDependencyInfoFormatter.Instance, PackageIdentityFormatter.Instance, PackageReferenceFormatter.Instance, PackageSourceFormatter.Instance, PackageSourceUpdateOptionsFormatter.Instance, ProjectActionFormatter.Instance, RemoteErrorFormatter.Instance, VersionRangeFormatter.Instance }; var resolvers = new IFormatterResolver[] { MessagePack.MessagePackSerializerOptions.Standard.Resolver }; return(MessagePack.MessagePackSerializerOptions.Standard .WithSecurity(MessagePackSecurity.UntrustedData) .WithResolver(CompositeResolver.Create(formatters, resolvers))); }
private void FavToggle_Toggled(object sender, ToggledArgs args) { _tableStore.GetIter(out TreeIter treeIter, new TreePath(args.Path)); string titleId = _tableStore.GetValue(treeIter, 2).ToString().Split("\n")[1].ToLower(); string metadataPath = System.IO.Path.Combine(new VirtualFileSystem().GetBasePath(), "games", titleId, "gui", "metadata.json"); IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase }); ApplicationMetadata appMetadata; using (Stream stream = File.OpenRead(metadataPath)) { appMetadata = JsonSerializer.Deserialize <ApplicationMetadata>(stream, resolver); } if ((bool)_tableStore.GetValue(treeIter, 0)) { _tableStore.SetValue(treeIter, 0, false); appMetadata.Favorite = false; } else { _tableStore.SetValue(treeIter, 0, true); appMetadata.Favorite = true; } byte[] saveData = JsonSerializer.Serialize(appMetadata, resolver); File.WriteAllText(metadataPath, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson()); }
public void SetUp() { random = new Random(); var resolver = CompositeResolver.Create(new IMessagePackFormatter[] { new UnsafeUnmanagedStructFormatter <Matrix4x4>(50), new UnsafeUnmanagedStructArrayFormatter <Matrix4x4>(51) }, new[] { StandardResolver.Instance }); options = MessagePackSerializerOptions.Standard.WithResolver(resolver); }
private void SetupResolver(MessagePackHubProtocolOptions options) { // if counts don't match then we know users customized resolvers so we set up the options // with the provided resolvers if (options.FormatterResolvers.Count != SignalRResolver.Resolvers.Count) { var resolver = CompositeResolver.Create(Array.Empty <IMessagePackFormatter>(), (IReadOnlyList <IFormatterResolver>)options.FormatterResolvers); _msgPackSerializerOptions = MessagePackSerializerOptions.Standard.WithResolver(resolver); return; } for (var i = 0; i < options.FormatterResolvers.Count; i++) { // check if the user customized the resolvers if (options.FormatterResolvers[i] != SignalRResolver.Resolvers[i]) { var resolver = CompositeResolver.Create(Array.Empty <IMessagePackFormatter>(), (IReadOnlyList <IFormatterResolver>)options.FormatterResolvers); _msgPackSerializerOptions = MessagePackSerializerOptions.Standard.WithResolver(resolver); return; } } // Use optimized cached resolver if the default is chosen _msgPackSerializerOptions = MessagePackSerializerOptions.Standard.WithResolver(SignalRResolver.Instance); }
static EventsSerializer() { Options ??= MessagePackSerializerOptions.Standard.WithResolver( CompositeResolver.Create( UnityWebBrowserResolver.Instance, StandardResolver.Instance)); }
public async Task PropertiesGetterOnlyMixed() { using var tempWorkarea = TemporaryProjectWorkarea.Create(); var contents = @" using System; using System.Collections.Generic; using MessagePack; namespace TempProject { [MessagePackObject(true)] public class MyMessagePackObject { public int A { get; } public string B { get; set; } } } "; tempWorkarea.AddFileToTargetProject("MyMessagePackObject.cs", contents); var compiler = new MessagePackCompiler.CodeGenerator(testOutputHelper.WriteLine, CancellationToken.None); await compiler.GenerateFileAsync( tempWorkarea.GetOutputCompilation().Compilation, tempWorkarea.OutputDirectory, "TempProjectResolver", "TempProject.Generated", false, string.Empty, Array.Empty <string>()); var compilation = tempWorkarea.GetOutputCompilation(); compilation.Compilation.GetDiagnostics().Should().NotContain(x => x.Severity == DiagnosticSeverity.Error); // Run tests with the generated resolver/formatter assembly. compilation.ExecuteWithGeneratedAssembly((ctx, assembly) => { var mpoType = assembly.GetType("TempProject.MyMessagePackObject"); var options = MessagePackSerializerOptions.Standard .WithResolver(CompositeResolver.Create( StandardResolver.Instance, TestUtilities.GetResolverInstance(assembly, "TempProject.Generated.Resolvers.TempProjectResolver"))); // Build `{ "A": -1, "B": "foobar" }`. var seq = new Sequence <byte>(); var writer = new MessagePackWriter(seq); writer.WriteMapHeader(2); writer.Write("A"); writer.Write(-1); writer.Write("B"); writer.Write("foobar"); writer.Flush(); // Verify deserialization dynamic result = MessagePackSerializer.Deserialize(mpoType, seq, options); ((int)result.A).Should().Be(0); // default ((string)result.B).Should().Be("foobar"); // from input }); }
private AboutWindow(Builder builder) : base(builder.GetObject("_aboutWin").Handle) { builder.Autoconnect(this); _aboutWin.Icon = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png"); _ryujinxLogo.Pixbuf = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.Icon.png", 100, 100); _patreonLogo.Pixbuf = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.PatreonLogo.png", 30, 30); _gitHubLogo.Pixbuf = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.GitHubLogo.png", 30, 30); _discordLogo.Pixbuf = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.DiscordLogo.png", 30, 30); _twitterLogo.Pixbuf = new Gdk.Pixbuf(Assembly.GetExecutingAssembly(), "Ryujinx.Ui.assets.TwitterLogo.png", 30, 30); try { IJsonFormatterResolver resolver = CompositeResolver.Create(new[] { StandardResolver.AllowPrivateSnakeCase }); using (Stream stream = File.OpenRead(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RyuFS", "Installer", "Config", "Config.json"))) { AboutInformation = JsonSerializer.Deserialize <AboutInfo>(stream, resolver); } _versionText.Text = $"Version {AboutInformation.InstallVersion} - {AboutInformation.InstallBranch} ({AboutInformation.InstallCommit})"; } catch { _versionText.Text = "Unknown Version"; } }
public ResultOfTTeMessagePackFormatterTests() { var resolver = CompositeResolver.Create(StandardResolver.Instance, CSharpFunctionalExtensionsFormatResolver.Instance); _options = MessagePackSerializerOptions.Standard .WithResolver(resolver); }
public void DataContractSerializerCompatibility() { var master = new Master { A = 1, InternalComplexProperty = new Detail { B1 = 2, B2 = 3, }, InternalComplexField = new Detail { B1 = 4, B2 = 5, }, }; var dcsValue = DataContractSerializerRoundTrip(master); var option = MessagePackSerializerOptions.Standard.WithResolver(CompositeResolver.Create( DynamicObjectResolverAllowPrivate.Instance, ContractlessStandardResolver.Instance)); var mpValue = MessagePackSerializer.Deserialize <Master>(MessagePackSerializer.Serialize(master, option), option); Assert.Equal(dcsValue, mpValue); }
public ProblemDetailsMessagePackFormatterTests() { var resolver = CompositeResolver.Create(StandardResolver.Instance, ProblemDetailsFormatResolver.Instance); _options = MessagePackSerializerOptions.Standard .WithResolver(resolver); }
private static MessagePackSerializerOptions CreateMessagePackSerializerOptions() { var formatters = new IMessagePackFormatter[] { AlternatePackageMetadataContextInfoFormatter.Instance, FloatRangeFormatter.Instance, IPackageReferenceContextInfoFormatter.Instance, IProjectContextInfoFormatter.Instance, IProjectMetadataContextInfoFormatter.Instance, NuGetFrameworkFormatter.Instance, NuGetVersionFormatter.Instance, PackageDependencyFormatter.Instance, PackageDependencyGroupFormatter.Instance, PackageDependencyInfoFormatter.Instance, PackageDeprecationMetadataContextInfoFormatter.Instance, PackageIdentityFormatter.Instance, PackageReferenceFormatter.Instance, PackageSearchMetadataContextInfoFormatter.Instance, PackageSourceFormatter.Instance, PackageSourceContextInfoFormatter.Instance, PackageSourceUpdateOptionsFormatter.Instance, PackageVulnerabilityMetadataContextInfoFormatter.Instance, ProjectActionFormatter.Instance, VersionRangeFormatter.Instance, SearchFilterFormatter.Instance, SearchResultContextInfoFormatter.Instance, VersionInfoContextInfoFormatter.Instance, }; var resolvers = new IFormatterResolver[] { MessagePack.MessagePackSerializerOptions.Standard.Resolver }; return(MessagePack.MessagePackSerializerOptions.Standard .WithSecurity(MessagePackSecurity.UntrustedData) .WithResolver(CompositeResolver.Create(formatters, resolvers))); }
/// <summary> /// Initializes a new instance of the <see cref="MessagePackHubProtocol"/> class. /// </summary> /// <param name="options">The options used to initialize the protocol.</param> public MessagePackHubProtocol(IOptions <MessagePackHubProtocolOptions> options) { var msgPackOptions = options.Value; var resolver = SignalRResolver.Instance; var hasCustomFormatterResolver = false; // if counts don't match then we know users customized resolvers so we set up the options with the provided resolvers if (msgPackOptions.FormatterResolvers.Count != SignalRResolver.Resolvers.Count) { hasCustomFormatterResolver = true; } else { // Compare each "reference" in the FormatterResolvers IList<> against the default "SignalRResolver.Resolvers" IList<> for (var i = 0; i < msgPackOptions.FormatterResolvers.Count; i++) { // check if the user customized the resolvers if (msgPackOptions.FormatterResolvers[i] != SignalRResolver.Resolvers[i]) { hasCustomFormatterResolver = true; break; } } } if (hasCustomFormatterResolver) { resolver = CompositeResolver.Create(Array.Empty <IMessagePackFormatter>(), (IReadOnlyList <IFormatterResolver>)msgPackOptions.FormatterResolvers); } _msgPackSerializerOptions = MessagePackSerializerOptions.Standard .WithResolver(resolver) .WithSecurity(MessagePackSecurity.UntrustedData); }
public void ActualOptions_IsOrDerivesFrom_SetMessagePackSerializerOptions() { var customFormatter = new CustomFormatter(); var options = (CustomOptions) new CustomOptions(MessagePackFormatter.DefaultUserDataSerializationOptions) { CustomProperty = 3 } .WithResolver(CompositeResolver.Create(customFormatter)); this.formatter.SetMessagePackSerializerOptions(options); var value = new JsonRpcRequest { RequestId = new RequestId(1), Method = "Eat", ArgumentsList = new object[] { new TypeRequiringCustomFormatter() }, }; var sequence = new Sequence <byte>(); this.formatter.Serialize(sequence, value); var observedOptions = Assert.IsType <CustomOptions>(customFormatter.LastObservedOptions); Assert.Equal(options.CustomProperty, observedOptions.CustomProperty); }
public override void InstallBindings() { var resolver = CompositeResolver.Create(GeneratedResolver.Instance, StandardResolver.Instance); var options = MessagePackSerializerOptions.Standard.WithResolver(resolver); MessagePackSerializer.DefaultOptions = options; }
private static (bool favorite, string timePlayed, string lastPlayed) GetMetadata(string titleId) { string metadataFolder = Path.Combine(new VirtualFileSystem().GetBasePath(), "games", titleId, "gui"); string metadataFile = Path.Combine(metadataFolder, "metadata.json"); IJsonFormatterResolver resolver = CompositeResolver.Create(StandardResolver.AllowPrivateSnakeCase); if (!File.Exists(metadataFile)) { Directory.CreateDirectory(metadataFolder); _appMetadata = new ApplicationMetadata { Favorite = false, TimePlayed = 0, LastPlayed = "Never" }; byte[] saveData = JsonSerializer.Serialize(_appMetadata, resolver); File.WriteAllText(metadataFile, Encoding.UTF8.GetString(saveData, 0, saveData.Length).PrettyPrintJson()); } using (Stream stream = File.OpenRead(metadataFile)) { _appMetadata = JsonSerializer.Deserialize <ApplicationMetadata>(stream, resolver); } return(_appMetadata.Favorite, ConvertSecondsToReadableString(_appMetadata.TimePlayed), _appMetadata.LastPlayed); }
public CacheFlowMessagePackSerializer(MessagePackSerializerOptions?options = null, params IFormatterResolver[]?resolvers) { resolvers ??= new IFormatterResolver[] { StandardResolver.Instance }; var resolver = CompositeResolver.Create(resolvers); options ??= MessagePackSerializerOptions.Standard; _options = options.WithResolver(resolver); }
public static IServiceCollection AddMessagePackSettings(this IServiceCollection services) => services.AddSingleton(MessagePackSerializerOptions.Standard .WithCompression(MessagePackCompression.Lz4BlockArray) .WithResolver(CompositeResolver.Create( NativeGuidResolver.Instance, NativeDateTimeResolver.Instance, StandardResolver.Instance )));
public void NormalizingIsoPeriodFormatter_RequiresNormalization() { // Can't use AssertConversions here, as it doesn't round-trip var period = Period.FromDays(2) + Period.FromHours(3) + Period.FromMinutes(90); var json = JsonSerializer.ToJsonString(period, CompositeResolver.Create(NodaFormatters.NormalizingIsoPeriodFormatter)); var expectedJson = "\"P2DT4H30M\""; Assert.Equal(expectedJson, json); }
internal static ApplicationMetadata LoadAndSaveMetaData(string titleId, Action <ApplicationMetadata> modifyFunction = null) { string metadataFolder = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "gui"); string metadataFile = Path.Combine(metadataFolder, "metadata.json"); IJsonFormatterResolver resolver = CompositeResolver.Create(StandardResolver.AllowPrivateSnakeCase); ApplicationMetadata appMetadata; if (!File.Exists(metadataFile)) { Directory.CreateDirectory(metadataFolder); appMetadata = new ApplicationMetadata { Favorite = false, TimePlayed = 0, LastPlayed = "Never" }; using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough)) { JsonSerializer.Serialize(stream, appMetadata, resolver); } } using (Stream stream = File.OpenRead(metadataFile)) { try { appMetadata = JsonSerializer.Deserialize <ApplicationMetadata>(stream, resolver); } catch (JsonParsingException) { Logger.PrintWarning(LogClass.Application, $"Failed to parse metadata json for {titleId}. Loading defaults."); appMetadata = new ApplicationMetadata { Favorite = false, TimePlayed = 0, LastPlayed = "Never" }; } } if (modifyFunction != null) { modifyFunction(appMetadata); using (FileStream stream = File.Create(metadataFile, 4096, FileOptions.WriteThrough)) { JsonSerializer.Serialize(stream, appMetadata, resolver); } } return(appMetadata); }
private static MessagePackSerializerOptions CreateMessagePackSerializerOptions() { IMessagePackFormatter[] formatters = CreateMessagePackFormatters(); var resolvers = new IFormatterResolver[] { MessagePack.MessagePackSerializerOptions.Standard.Resolver }; return(MessagePack.MessagePackSerializerOptions.Standard .WithSecurity(MessagePackSecurity.UntrustedData) .WithResolver(CompositeResolver.Create(formatters, resolvers))); }
public void InstantFormatter_EquivalentToIsoDateTimeFormatter() { var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, DateTimeKind.Utc); var instant = Instant.FromDateTimeUtc(dateTime); var jsonDateTime = JsonSerializer.ToJsonString(dateTime, CompositeResolver.Create(new ISO8601DateTimeFormatter())); var jsonInstant = JsonSerializer.ToJsonString(instant, CompositeResolver.Create(NodaFormatters.InstantFormatter)); Assert.Equal(jsonDateTime, jsonInstant); }
static int Main(string[] argv) { if (argv.Length == 0) { Console.WriteLine("Usage: Gherkin.CLI [--no-source] [--no-ast] [--no-pickles] feature-file.feature"); return(100); } List <string> args = new List <string> (argv); List <string> paths = new List <string> (); bool printSource = true; bool printAst = true; bool printPickles = true; foreach (string arg in args) { switch (arg) { case "--no-source": printSource = false; break; case "--no-ast": printAst = false; break; case "--no-pickles": printPickles = false; break; default: paths.Add(arg); break; } } var resolver = CompositeResolver.Create( new IJsonFormatter[] {}, new IJsonFormatterResolver[] { StandardResolver.ExcludeNullCamelCase } ); SourceEvents sourceEvents = new SourceEvents(paths); GherkinEvents gherkinEvents = new GherkinEvents(printSource, printAst, printPickles); foreach (var sourceEventEvent in sourceEvents) { foreach (IEvent evt in gherkinEvents.Iterable(sourceEventEvent)) { var jsonString = Utf8Json.JsonSerializer.ToJsonString((object)evt, StandardResolver.ExcludeNullCamelCase); // manual way of ignoring empty arrays... This is not that easy with Utf8Json... jsonString = Regex.Replace(jsonString, @",?""\w+"":\s*\[\]", ""); Console.WriteLine(jsonString); } } return(0); }
static SmartEnumNameConverterTests() { CompositeResolver.Create( new SmartEnumNameFormatter <TestEnumBoolean, bool>(), new SmartEnumNameFormatter <TestEnumInt16, short>(), new SmartEnumNameFormatter <TestEnumInt32, int>(), new SmartEnumNameFormatter <TestEnumDouble, double>() ); }
public static IUkiyoBuilder AddWebApi(this IUkiyoBuilder builder, Action <IMvcCoreBuilder> configureMvc, IJsonSerializer jsonSerializer = null, string sectionName = SectionName) { if (string.IsNullOrWhiteSpace(sectionName)) { sectionName = SectionName; } if (!builder.TryRegister(RegistryName)) { return(builder); } if (jsonSerializer is null) { var factory = new JsonSerializerFactory(StandardResolver.AllowPrivateCamelCase); JsonSerializer.SetDefaultResolver(new UkiyoFormatterResolver()); jsonSerializer = factory.GetSerializer(); } builder.Services.AddSingleton(jsonSerializer); builder.Services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); builder.Services.AddSingleton(new WebApiEndpointDefinitions()); var options = builder.GetOptions <WebApiOptions>(sectionName); builder.Services.AddSingleton(options); _bindRequestFromRoute = options.BindRequestFromRoute; var mvcCoreBuilder = builder.Services .AddLogging() .AddMvcCore(); mvcCoreBuilder.AddMvcOptions(o => { var resolver = CompositeResolver.Create(EnumResolver.Default, StandardResolver.AllowPrivateCamelCase); o.OutputFormatters.Clear(); o.OutputFormatters.Add(new JsonOutputFormatter(resolver)); o.InputFormatters.Clear(); o.InputFormatters.Add(new JsonInputFormatter(resolver)); }) .AddDataAnnotations() .AddApiExplorer() .AddAuthorization(); configureMvc?.Invoke(mvcCoreBuilder); builder.Services.Scan(s => s.FromAssemblies(AppDomain.CurrentDomain.GetAssemblies()) .AddClasses(c => c.AssignableTo(typeof(IRequestHandler <,>))) .AsImplementedInterfaces() .WithTransientLifetime()); builder.Services.AddTransient <IRequestDispatcher, RequestDispatcher>(); return(builder); }
/// <summary> /// Save a configuration file to disk /// </summary> /// <param name="path">The path to the JSON configuration file</param> public void SaveConfig(string path) { IJsonFormatterResolver resolver = CompositeResolver.Create( new[] { new ConfigurationEnumFormatter <Key>() }, new[] { StandardResolver.AllowPrivateSnakeCase } ); byte[] data = JsonSerializer.Serialize(this, resolver); File.WriteAllText(path, Encoding.UTF8.GetString(data, 0, data.Length).PrettyPrintJson()); }
public void Resolver_WithIsoIntervalFormatter() { var configuredResolver = CompositeResolver.Create(new NodaTimeResolver(DateTimeZoneProviders.Tzdb, isoIntervals: true), StandardResolver.Default); var explicitResolver = CompositeResolver.Create(new IJsonFormatter[] { NodaFormatters.IsoIntervalFormatter }, new[] { StandardResolver.Default }); var interval = new Interval(Instant.FromUnixTimeTicks(1000L), Instant.FromUnixTimeTicks(20000L)); Assert.Equal(Serialize(interval, explicitResolver), Serialize(interval, configuredResolver)); }
static SettingAppModel() { //ReactivePropertyをシリアライズ可能にするため、アプリケーション全体で固定のMessagePackResolverを設定 var resolver = CompositeResolver.Create( ReactivePropertyResolver.Instance, ContractlessStandardResolverAllowPrivate.Instance ); MessagePackSerializer.DefaultOptions = MessagePack.MessagePackSerializerOptions.Standard.WithResolver(resolver); }
public void LocalDateTimeFormatter_EquivalentToIsoDateTimeFormatter() { var dateTime = new DateTime(2012, 1, 2, 3, 4, 5, 6, DateTimeKind.Unspecified); var localDateTime = new LocalDateTime(2012, 1, 2, 3, 4, 5, 6, CalendarSystem.Iso); var jsonDateTime = JsonSerializer.ToJsonString(dateTime, CompositeResolver.Create(new ISO8601DateTimeFormatter())); var jsonLocalDateTime = JsonSerializer.ToJsonString(localDateTime, CompositeResolver.Create(NodaFormatters.LocalDateTimeFormatter)); Assert.Equal(jsonDateTime, jsonLocalDateTime); }
/// <summary> /// Initializes a new instance of the <see cref="MessagePackFormatter"/> class. /// </summary> /// <param name="compress">A value indicating whether to use LZ4 compression.</param> public MessagePackFormatter(bool compress) { var compositeResolver = CompositeResolver.Create( new IMessagePackFormatter[] { new RequestIdFormatter() }, new IFormatterResolver[] { TypelessContractlessStandardResolver.Instance }); this.options = TypelessContractlessStandardResolver.Options .WithResolver(compositeResolver) .WithLZ4Compression(useLZ4Compression: compress); }
private static byte[] CreateRawMessage <T>(uint code, T op, TypeMessage type) { var opt = MessagePackSerializerOptions.Standard.WithResolver(CompositeResolver.Create(new [] { new StatusCodeFormatter() }, new [] { StandardResolver.Instance })); var subOp = MessagePackSerializer.Serialize(op, opt); return(MessagePackSerializer.Serialize(new DefaultMessage() { OperationCode = code, OperationData = subOp, Type = type }, opt)); }