public void GetTypeMapping_IfJsonTypeNameAttributeIsAbsent_UsesGetTypeTypeName() { // Act IDictionary <string, Type> typeMapping = PolymorphicJsonConverter.GetTypeMapping <TypeWithoutCustomName>(); // Assert Assert.NotNull(typeMapping); Assert.Equal(1, typeMapping.Count); Assert.True(typeMapping.ContainsKey("TypeWithoutCustomName")); Assert.Equal(typeof(TypeWithoutCustomName), typeMapping["TypeWithoutCustomName"]); }
public void TypePropertyName_ReturnsSpecifiedInstance() { // Arrange string expectedTypePropertyName = "IgnoreProperty"; IDictionary <string, Type> typeMapping = new Dictionary <string, Type>(); PolymorphicJsonConverter product = CreateProductUnderTest(expectedTypePropertyName, typeMapping); // Act string typePropertyName = product.TypePropertyName; // Assert Assert.Same(expectedTypePropertyName, typePropertyName); }
public void GetTypeMapping_IncludesDerivedTypes() { // Act IDictionary <string, Type> typeMapping = PolymorphicJsonConverter.GetTypeMapping <TypeWithTwoDerivedTypes>(); // Assert Assert.NotNull(typeMapping); Assert.Equal(3, typeMapping.Count); Assert.True(typeMapping.ContainsKey("TypeWithTwoDerivedTypes")); Assert.Equal(typeof(TypeWithTwoDerivedTypes), typeMapping["TypeWithTwoDerivedTypes"]); Assert.True(typeMapping.ContainsKey("ChildTypeWithoutCustomName")); Assert.Equal(typeof(ChildTypeWithoutCustomName), typeMapping["ChildTypeWithoutCustomName"]); Assert.True(typeMapping.ContainsKey("CustomTypeName")); Assert.Equal(typeof(GrandchildTypeWithCustomName), typeMapping["CustomTypeName"]); }
public ParameterDescriptorConverter() : base("Type", PolymorphicJsonConverter.GetTypeMapping <ParameterDescriptor>()) { }
public ParameterSnapshotConverter() : base("Type", PolymorphicJsonConverter.GetTypeMapping <ParameterSnapshot>()) { }
public ParameterLogConverter() : base("Type", PolymorphicJsonConverter.GetTypeMapping <ParameterLog>()) { }
public PersistentQueueMessageConverter() : base("Type", PolymorphicJsonConverter.GetTypeMapping <PersistentQueueMessage>()) { }
public HostMessageConverter() : base("Type", PolymorphicJsonConverter.GetTypeMapping <HostMessage>()) { }
/// <summary> /// Deserializes an object from a JSON string and flattens out Properties. /// </summary> /// <param name="reader">The JSON reader.</param> /// <param name="objectType">The type of the object.</param> /// <param name="existingValue">The existing value.</param> /// <param name="serializer">The JSON serializer.</param> /// <returns></returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader == null) { throw new ArgumentNullException("reader"); } if (objectType == null) { throw new ArgumentNullException("objectType"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } try { JObject resourceJObject = JObject.Load(reader); // Flatten resource JObject propertiesJObject = resourceJObject[PropertiesNode] as JObject; // Update type if there is a polymorphism var polymorphicDeserializer = serializer.Converters .FirstOrDefault(c => c.GetType().GetTypeInfo().IsGenericType&& c.GetType().GetGenericTypeDefinition() == typeof(PolymorphicDeserializeJsonConverter <>) && c.CanConvert(objectType)) as PolymorphicJsonConverter; if (polymorphicDeserializer != null) { objectType = PolymorphicJsonConverter.GetDerivedType(objectType, (string)resourceJObject[polymorphicDeserializer.Discriminator]) ?? objectType; } // Initialize appropriate type instance var resource = Activator.CreateInstance(objectType); // For each property in resource - populate property var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType); foreach (JsonProperty property in contract.Properties) { JToken propertyValueToken = resourceJObject[property.PropertyName]; if (propertyValueToken == null && propertiesJObject != null && property.PropertyName.StartsWith("properties.", StringComparison.OrdinalIgnoreCase)) { propertyValueToken = propertiesJObject[property.PropertyName.Substring("properties.".Length)]; } if (propertyValueToken != null && property.Writable) { var propertyValue = propertyValueToken.ToObject(property.PropertyType, serializer); property.ValueProvider.SetValue(resource, propertyValue); } } return(resource); } catch (JsonException) { return(null); } }
public override async Task <int> ExecuteAsync(CommandContext context, Settings settings) { var webHost = default(IWebHost); using var cancellationTokenSource = new CancellationTokenSource(); Logger.LogInformation( "Generating self-signed certificate for HTTPS" ); using var cert = CertificateManager.Create(); await Console.Status() .Spinner(Spinner.Known.Earth) .StartAsync( "Starting AirDrop services...", async _ => { webHost = WebHost.CreateDefaultBuilder() .ConfigureLogging( (hostContext, builder) => { builder.ClearProviders(); builder.AddConfiguration(hostContext.Configuration.GetSection("Logging")); builder.AddProvider(new SpectreInlineLoggerProvider(Console)); } ) .ConfigureKestrel( options => options.ConfigureAirDropDefaults(cert) ) .ConfigureServices( (hostContext, services) => { var uploadPath = Path.Join( hostContext.HostingEnvironment.ContentRootPath, "uploads" ); Directory.CreateDirectory(uploadPath); services.Configure <StaticFileOptions>(options => { options.FileProvider = new CompositeFileProvider( new IFileProvider[] { // provides access to the files embedded in the assembly new ManifestEmbeddedFileProvider( typeof(ServerCommand).Assembly, "wwwroot" ), // provides access to uploaded files new PhysicalFileProvider(uploadPath) } ); // we don't know what files could be uploaded using AirDrop // so enable everything by default options.ServeUnknownFileTypes = true; } ); services.AddAirDrop( options => { options.ListenPort = settings.Port; options.UploadPath = uploadPath; } ); services.AddRouting(); services .AddSignalR( options => { options.EnableDetailedErrors = true; } ) .AddJsonProtocol( options => { options.PayloadSerializerOptions = new JsonSerializerOptions { Converters = { PolymorphicJsonConverter.Create(typeof(AirDropHubMessage)) } }; } ); } ) .Configure( app => { app .UseRouting() .UseStaticFiles() .UseEndpoints( endpoints => { endpoints.MapAirDrop(); endpoints.MapHub <AirDropHub>("/airdrop"); endpoints.MapFallbackToFile("index.html"); } ); } ) .SuppressStatusMessages(true) .Build(); await webHost.StartAsync(cancellationTokenSource.Token); } ); var feature = webHost !.ServerFeatures.Get <IServerAddressesFeature>(); if (feature != null) { foreach (var address in feature.Addresses) { Logger.LogInformation("Listening on {Url}", address); } } Logger.LogInformation("Waiting for AirDrop clients..."); // ReSharper disable AccessToDisposedClosure void Shutdown() { if (!cancellationTokenSource.IsCancellationRequested) { Logger.LogInformation("Shutting down AirDrop services..."); cancellationTokenSource.Cancel(); } } AppDomain.CurrentDomain.ProcessExit += (_, _) => Shutdown(); System.Console.CancelKeyPress += (_, _) => Shutdown(); await webHost.WaitForShutdownAsync(cancellationTokenSource.Token); return(0); }