private String FormatColumnName() { var formatters = FormatterCollection.GetFormattersFor(this.TableName); string newColumnName = this.Name; foreach (var formatter in formatters) { if (formatter.IsApplicable(this, newColumnName)) { newColumnName = formatter.Apply(this, newColumnName); if (formatter.SkipOtherFormatters(this, newColumnName)) { break; } } } //ensure name is not the same as enclosingType if (this.Table.CLRTypeName == newColumnName) { newColumnName = newColumnName + "_" + newColumnName; } //if te name is a foreign key ref, add suffix _Key if (this.IsForeignKey) { newColumnName = newColumnName + "_Key"; } return(newColumnName); }
/// <summary> /// Initializes a new instance of the <see cref="HttpBasedAzureFunction"/> class. /// </summary> /// <param name="httpCorrelation">The correlation service to provide information of related requests.</param> /// <param name="logger">The logger instance to write diagnostic messages throughout the execution of the HTTP trigger.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="httpCorrelation"/> is <c>null</c></exception> protected HttpBasedAzureFunction(HttpCorrelation httpCorrelation, ILogger logger) { Guard.NotNull(httpCorrelation, nameof(httpCorrelation), "Requires an HTTP correlation instance"); _httpCorrelation = httpCorrelation; Logger = logger ?? NullLogger.Instance; var jsonSettings = new JsonSerializerSettings { MaxDepth = 10, NullValueHandling = NullValueHandling.Ignore, TypeNameHandling = TypeNameHandling.None }; jsonSettings.Converters.Add(new StringEnumConverter()); JsonSerializer = JsonSerializer.Create(jsonSettings); var jsonOptions = new JsonSerializerOptions { MaxDepth = 10, IgnoreNullValues = true }; jsonOptions.Converters.Add(new JsonStringEnumConverter()); OutputFormatters = new FormatterCollection <IOutputFormatter> { new SystemTextJsonOutputFormatter(jsonOptions) }; }
/// <summary> /// Creates a new instance of <see cref="MvcOptions"/>. /// </summary> public MvcOptions() { CacheProfiles = new Dictionary <string, CacheProfile>(StringComparer.OrdinalIgnoreCase); Conventions = new List <IApplicationModelConvention>(); Filters = new FilterCollection(); FormatterMappings = new FormatterMappings(); InputFormatters = new FormatterCollection <IInputFormatter>(); OutputFormatters = new FormatterCollection <IOutputFormatter>(); ModelBinderProviders = new List <IModelBinderProvider>(); ModelBindingMessageProvider = new DefaultModelBindingMessageProvider(); ModelMetadataDetailsProviders = new List <IMetadataDetailsProvider>(); ModelValidatorProviders = new List <IModelValidatorProvider>(); ValueProviderFactories = new List <IValueProviderFactory>(); _allowCombiningAuthorizeFilters = new CompatibilitySwitch <bool>(nameof(AllowCombiningAuthorizeFilters)); _allowBindingHeaderValuesToNonStringModelTypes = new CompatibilitySwitch <bool>(nameof(AllowBindingHeaderValuesToNonStringModelTypes)); _allowValidatingTopLevelNodes = new CompatibilitySwitch <bool>(nameof(AllowValidatingTopLevelNodes)); _inputFormatterExceptionPolicy = new CompatibilitySwitch <InputFormatterExceptionPolicy>(nameof(InputFormatterExceptionPolicy), InputFormatterExceptionPolicy.AllExceptions); _suppressBindingUndefinedValueToEnumType = new CompatibilitySwitch <bool>(nameof(SuppressBindingUndefinedValueToEnumType)); _enableEndpointRouting = new CompatibilitySwitch <bool>(nameof(EnableEndpointRouting)); _switches = new ICompatibilitySwitch[] { _allowCombiningAuthorizeFilters, _allowBindingHeaderValuesToNonStringModelTypes, _allowValidatingTopLevelNodes, _inputFormatterExceptionPolicy, _suppressBindingUndefinedValueToEnumType, _enableEndpointRouting, }; }
/// <summary> /// Creates a new instance of <see cref="MvcOptions"/>. /// </summary> public MvcOptions() { CacheProfiles = new Dictionary <string, CacheProfile>(StringComparer.OrdinalIgnoreCase); Conventions = new List <IApplicationModelConvention>(); Filters = new FilterCollection(); FormatterMappings = new FormatterMappings(); InputFormatters = new FormatterCollection <IInputFormatter>(); OutputFormatters = new FormatterCollection <IOutputFormatter>(); ModelBinderProviders = new List <IModelBinderProvider>(); ModelBindingMessageProvider = new DefaultModelBindingMessageProvider(); ModelMetadataDetailsProviders = new List <IMetadataDetailsProvider>(); ModelValidatorProviders = new List <IModelValidatorProvider>(); ValueProviderFactories = new List <IValueProviderFactory>(); _inputFormatterExceptionPolicy = new CompatibilitySwitch <InputFormatterExceptionPolicy>(nameof(InputFormatterExceptionPolicy), InputFormatterExceptionPolicy.AllExceptions); _suppressBindingUndefinedValueToEnumType = new CompatibilitySwitch <bool>(nameof(SuppressBindingUndefinedValueToEnumType)); _allowShortCircuitingValidationWhenNoValidatorsArePresent = new CompatibilitySwitch <bool>(nameof(AllowShortCircuitingValidationWhenNoValidatorsArePresent)); _switches = new ICompatibilitySwitch[] { _inputFormatterExceptionPolicy, _suppressBindingUndefinedValueToEnumType, _allowShortCircuitingValidationWhenNoValidatorsArePresent, }; }
private static void RestoreDefaultJsonOutputFormatter(FormatterCollection <IOutputFormatter> formatters, SystemTextJsonOutputFormatter jsonOutputFormatter) { if (jsonOutputFormatter != null) { formatters.Add(jsonOutputFormatter); } }
static void RemoveJsonFormatter <T>(FormatterCollection <T> formatters) { for (int i = formatters.Count - 1; i >= 0; --i) { if (formatters[i]?.GetType().FullName.IndexOf("Json", StringComparison.CurrentCultureIgnoreCase) + 1 != 0) { formatters.RemoveAt(i); } } }
public ServiceResultDatransject(bool succeeded, object?content, JsonErrors?errors, Type declaredType, FormatterCollection <IOutputFormatter>?formatters, MediaTypeCollection?contentTypes, int?statusCode) { Succeeded = succeeded; Content = content; Errors = errors; DeclaredType = declaredType; Formatters = formatters; ContentTypes = contentTypes; StatusCode = statusCode; }
public DomainExceptionFilter( ILoggerFactory loggerFactory, IOptions <DomainOptions> domainOptions, IOptions <MvcOptions> mvcOptions, IHttpResponseStreamWriterFactory writerFactory) { this.logger = loggerFactory.CreateLogger <DomainExceptionFilter>(); this.options = domainOptions; this.optionsFormatters = mvcOptions.Value.OutputFormatters; this.writerFactory = writerFactory.CreateWriter; }
private static void RegisterOutputFormatters(FormatterCollection <IOutputFormatter> formatters) { var jsonOutputFormatter = RemoveDefaultJsonOutputFormatter(formatters); RegisterArticleOutputFormatters(formatters); RegisterContentOutputFormatters(formatters); RegisterAuxOutputFormatters(formatters); RestoreDefaultJsonOutputFormatter(formatters, jsonOutputFormatter); }
private static void RegisterInputFormatters(FormatterCollection <IInputFormatter> formatters) { formatters.Insert(0, new ModelMediaTypeInputFormatter <Article, JsonProductFormatter>(WebApiConstants.JsonMediaType)); formatters.Insert(0, new ModelMediaTypeInputFormatter <Article, XmlProductFormatter>(WebApiConstants.XmlMediaType)); formatters.Insert(0, new ModelMediaTypeInputFormatter <Article, XamlProductFormatter>(WebApiConstants.XamlMediaType)); formatters.Add(new BinaryInputFormatter(WebApiConstants.BinaryMediaType)); }
private static void RegisterArticleOutputFormatters(FormatterCollection <IOutputFormatter> formatters) { formatters.Add( new ModelMediaTypeOutputFormatter <Article, XmlProductFormatter>(WebApiConstants.XmlMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Article, XamlProductFormatter>(WebApiConstants.XamlMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Article, JsonProductFormatter>(WebApiConstants.JsonMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Article, PdfProductFormatter>(WebApiConstants.PdfMediaType)); }
public async Task SelectsFormatterBasedOnObjectResultTest() { var inner = InnerExecutor; inner.Setup(i => i.ExecuteAsync(It.IsAny <ActionContext>(), It.IsAny <ObjectResult>())) .Returns(Task.CompletedTask); var formatters = new FormatterCollection <IOutputFormatter>(); var mediaTypes = new MediaTypeCollection(); var result = ObjectResult; result.ContentTypes = mediaTypes; result.Formatters = formatters; var httpContext = HttpContext; httpContext.Features.Set <HalFeature>(new HalFeature()); var formatterSelector = FormatterSelector; formatterSelector.Setup(f => f.SelectFormatter( It.IsAny <OutputFormatterCanWriteContext>(), It.IsAny <IList <IOutputFormatter> >(), It.IsAny <MediaTypeCollection>())) .Callback < OutputFormatterCanWriteContext, IList <IOutputFormatter>, MediaTypeCollection>((c, f, m) => { Assert.AreSame(formatters, f); Assert.AreSame(m, mediaTypes); }) .Returns(default(IOutputFormatter)) .Verifiable(); var executor = new HalObjectResultExecutor( inner.Object, WriterFactory.Object, formatterSelector.Object, Logger); var actionContext = new ActionContext { HttpContext = httpContext }; await executor.ExecuteAsync(actionContext, result); formatterSelector.Verify(); }
public MvcOptions() { CacheProfiles = new Dictionary<string, CacheProfile>(StringComparer.OrdinalIgnoreCase); Conventions = new List<IApplicationModelConvention>(); Filters = new FilterCollection(); FormatterMappings = new FormatterMappings(); InputFormatters = new FormatterCollection<IInputFormatter>(); OutputFormatters = new FormatterCollection<IOutputFormatter>(); ModelBinderProviders = new List<IModelBinderProvider>(); ModelBindingMessageProvider = new ModelBindingMessageProvider(); ModelMetadataDetailsProviders = new List<IMetadataDetailsProvider>(); ModelValidatorProviders = new List<IModelValidatorProvider>(); ValueProviderFactories = new List<IValueProviderFactory>(); }
/// <summary> /// Creates a new instance of <see cref="MvcOptions"/>. /// </summary> public MvcOptions() { CacheProfiles = new Dictionary <string, CacheProfile>(StringComparer.OrdinalIgnoreCase); Conventions = new List <IApplicationModelConvention>(); Filters = new FilterCollection(); FormatterMappings = new FormatterMappings(); InputFormatters = new FormatterCollection <IInputFormatter>(); OutputFormatters = new FormatterCollection <IOutputFormatter>(); ModelBinderProviders = new List <IModelBinderProvider>(); ModelBindingMessageProvider = new DefaultModelBindingMessageProvider(); ModelMetadataDetailsProviders = new List <IMetadataDetailsProvider>(); ModelValidatorProviders = new List <IModelValidatorProvider>(); ValueProviderFactories = new List <IValueProviderFactory>(); }
/// <summary> /// Adds custom configured <see cref="JsonOutputFormatter"/>. /// </summary> /// <param name="outputFormatters"></param> public static void AddDefaultJsonOutputFormatter( this FormatterCollection <IOutputFormatter> outputFormatters) { IOutputFormatter outputFormatter = outputFormatters .FirstOrDefault(c => c is JsonOutputFormatter); if (outputFormatter != null) { outputFormatters.Remove(outputFormatter); } outputFormatters.Add(new JsonOutputFormatter( new JsonSerializerSettings().SetupDefaults(), ArrayPool <Char> .Shared)); }
public void RemoveType_RemovesAllOfType() { // Arrange var collection = new FormatterCollection<IOutputFormatter> { new TestOutputFormatter(), new AnotherTestOutputFormatter(), new TestOutputFormatter() }; // Act collection.RemoveType<TestOutputFormatter>(); // Assert var formatter = Assert.Single(collection); Assert.IsType(typeof(AnotherTestOutputFormatter), formatter); }
/// <summary> /// Initializes a new instance of the <see cref="HttpBasedAzureFunction"/> class. /// </summary> /// <param name="httpCorrelation">The correlation service to provide information of related requests.</param> /// <param name="logger">The logger instance to write diagnostic messages throughout the execution of the HTTP trigger.</param> /// <exception cref="ArgumentNullException">Thrown when the <paramref name="httpCorrelation"/> is <c>null</c></exception> protected HttpBasedAzureFunction(HttpCorrelation httpCorrelation, ILogger logger) { Guard.NotNull(httpCorrelation, nameof(httpCorrelation), "Requires an HTTP correlation instance"); _httpCorrelation = httpCorrelation; Logger = logger ?? NullLogger.Instance; var options = new JsonSerializerOptions(); options.IgnoreNullValues = true; options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.Converters.Add(new JsonStringEnumConverter()); JsonOptions = options; OutputFormatters = new FormatterCollection <IOutputFormatter> { new SystemTextJsonOutputFormatter(JsonOptions) }; }
private static void RegisterContentOutputFormatters(FormatterCollection <IOutputFormatter> formatters) { formatters.Add( new ModelMediaTypeOutputFormatter <Content, XamlSchemaFormatter>(WebApiConstants.XamlMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Content, XmlSchemaFormatter>(WebApiConstants.XmlMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Content, JsonSchemaFormatter>(WebApiConstants.JsonMediaType)); formatters.Add( new ModelMediaTypeOutputFormatter <Content, JsonDefinitionSchemaFormatter>( WebApiConstants.JsonDefinitionMediaType) ); formatters.Add( new ModelMediaTypeOutputFormatter <Content, JsonDefinitionSchemaClassifiersAsBackwardsFormatter>( WebApiConstants.JsonDefinition2MediaType) ); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAdB2C")); // services.AddSingleton<ILinkMangler, GuidMangler>(); services.AddSingleton <ILinkMangler, NoMangler>(); services.AddMvc(options => { options.OutputFormatters.Insert(0, new HtmlOutputFormatter()); options.RespectBrowserAcceptHeader = true; // false by default Outputs = options.OutputFormatters; }).AddJsonOptions(opts => { opts.JsonSerializerOptions.IgnoreNullValues = true; // opts.JsonSerializerOptions.Converters.Add(new JsonLinkConverter()); // opts.JsonSerializerOptions.Converters.Add(new JsonLinksConverter()); }); services.AddHttpContextAccessor(); services.AddSingleton <IDbInspector>(new DbInspector(new DbConnectionProvider(Configuration, null))); // services.AddSingleton<IDbInspector, DbInspector>(); services.AddScoped <IDbConnectionProvider, DbConnectionProvider>(); services.AddScoped <FormCreator>(); services.AddScoped <DbMutator>(); services.AddScoped <ILinkManager, LinkManager>(); // services.AddScoped<IDbConnectionProvider>( x => // { // var config = x.GetRequiredService<IConfiguration>(); // var p = new DbConnectionProvider(config); // p. // return p; // }); services.AddControllers(); services.AddTransient <ProblemDetailsFactory, CustomProblemDetailsFactory>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "HttpServer", Version = "v1" }); }); services.AddHostedService <DbInspectorLoader>(); }
public void RemoveType_RemovesAllOfType() { // Arrange var collection = new FormatterCollection <IOutputFormatter> { new TestOutputFormatter(), new AnotherTestOutputFormatter(), new TestOutputFormatter() }; // Act collection.RemoveType <TestOutputFormatter>(); // Assert var formatter = Assert.Single(collection); Assert.IsType <AnotherTestOutputFormatter>(formatter); }
public static BeetleObjectResult HandleResponse(ProcessResult processResult, HttpResponse response) { var result = processResult.Result; var actionContext = processResult.ActionContext; var service = actionContext.Service; var config = actionContext.Config ?? service?.Config ?? BeetleConfig.Instance; var formatter = new BeetleMediaTypeFormatter(config); var formatters = new List <IOutputFormatter> { formatter }; var formatterCollection = new FormatterCollection <IOutputFormatter>(formatters); return(new BeetleObjectResult(result) { Formatters = formatterCollection, ContentTypes = new MediaTypeCollection { config.Serializer.ContentType } }); }
public string FormatTableName() { var formatters = FormatterCollection.GetFormattersFor(this.Name); string newTableName = this.Name; foreach (var formatter in formatters) { if (formatter.IsApplicable(this, newTableName)) { newTableName = formatter.Apply(this, newTableName); if (formatter.SkipOtherFormatters(this, newTableName)) { break; } } } //Todo change the Info thing with sthg else. basically it is used to check duplicates return(newTableName + Info); }
private static void RegisterAuxOutputFormatters(FormatterCollection <IOutputFormatter> formatters) { formatters.Add( new ModelMediaTypeOutputFormatter < Dictionary <string, object>[], XmlDataContractFormatter <Dictionary <string, object>[]> >(WebApiConstants.XmlMediaType) ); formatters.Add( new ModelMediaTypeOutputFormatter < IEnumerable <Article>, JsonProductArrayFormatter >(WebApiConstants.JsonMediaType) ); formatters.Add( new ModelMediaTypeOutputFormatter < IEnumerable <Article>, XmlDataContractFormatter <IEnumerable <Article> > >(WebApiConstants.XmlMediaType) ); formatters.Add(new BinaryOutputFormatter(WebApiConstants.BinaryMediaType)); }
internal void Init() { //Create formatters classes for columns FormatterCollection <Column> columnFormatters = new FormatterCollection <Column>(); if (GeneratorOptions.ColumnNameFormatters != null) { foreach (var constructorDescription in GeneratorOptions.ColumnNameFormatters) { var formatterType = Type.GetType(constructorDescription.Name); if (formatterType == null) { throw new Exception($"Could not load type {constructorDescription.Name}"); } INameFormatter <Column> instance; if (constructorDescription.ParamsForConstructor != null) { instance = (INameFormatter <Column>)Activator.CreateInstance(formatterType, constructorDescription.ParamsForConstructor); } else { instance = (INameFormatter <Column>)Activator.CreateInstance(formatterType); } columnFormatters.AddFormatter(instance); } } FormatterCollection <Table> tableFormatters = new FormatterCollection <Table>(); if (GeneratorOptions.TableNameFormatters != null) { foreach (var formatterName in GeneratorOptions.TableNameFormatters) { var formatterType = Type.GetType(formatterName); if (formatterType == null) { throw new Exception($"Could not load type {formatterName}"); } var instance = (INameFormatter <Table>)Activator.CreateInstance(formatterType); tableFormatters.AddFormatter(instance); } } FormatterCollection <Table> DbSetFormatters = new FormatterCollection <Table>(); if (GeneratorOptions.DbSetNameFormatters != null) { foreach (var formatterName in GeneratorOptions.DbSetNameFormatters) { var formatterType = Type.GetType(formatterName); if (formatterType == null) { throw new Exception($"Could not load type {formatterName}"); } var instance = (INameFormatter <Table>)Activator.CreateInstance(formatterType); DbSetFormatters.AddFormatter(instance); } } foreach (var table in Tables) { //create the reverse link to table table.FormatterCollection = tableFormatters; table.DbSetFormatters = DbSetFormatters; } foreach (var col in AllColumns) { //create the reverse link to table Table table = FindTable(col.TableName); col.Table = table; col.FormatterCollection = columnFormatters; } //init foreignTables foreach (var col in AllColumns.Where(c => c.IsForeignKey)) { var referencedTable = (from t in Tables where t.Name == col.ReferencedTableName select t).FirstOrDefault(); col.ForeignTable = referencedTable; } }
/// <summary> /// Creates a new <see cref="ObjectResult"/> instance with the provided <paramref name="value"/>. /// </summary> /// <param name="value"></param> public ObjectResult(object?value) { Value = value; Formatters = new FormatterCollection <IOutputFormatter>(); _contentTypes = new MediaTypeCollection(); }
public ObjectResult(object value) { Value = value; Formatters = new FormatterCollection <IOutputFormatter>(); ContentTypes = new List <MediaTypeHeaderValue>(); }
private static void AddConfiguredFormatters(FormatterCollection <IOutputFormatter> outputFormatters) { outputFormatters.Insert(0, new OpenSearchDescriptionFormatter()); }
public ObjectResult(object value) { Value = value; Formatters = new FormatterCollection<IOutputFormatter>(); ContentTypes = new List<MediaTypeHeaderValue>(); }
private static SystemTextJsonOutputFormatter RemoveDefaultJsonOutputFormatter(FormatterCollection <IOutputFormatter> formatters) { var jsonOutputFormatter = formatters.OfType <SystemTextJsonOutputFormatter>().FirstOrDefault(); if (jsonOutputFormatter != null) { formatters.Remove(jsonOutputFormatter); } return(jsonOutputFormatter); }