Esempio n. 1
0
 public void AddDefaultResponseFormat(string mediaType, IOutputFormatter outputFormatter = null)
 {
     AddDefaultResponseFormat(new ApiResponseFormat()
     {
         MediaType = mediaType, Formatter = outputFormatter
     });
 }
Esempio n. 2
0
        /// <summary>
        ///		Build an HTTP request message, selecting an appropriate content formatter to serialise its body content.
        /// </summary>
        /// <param name="request">
        ///		The <see cref="HttpRequest"/>.
        /// </param>
        /// <param name="httpMethod">
        ///		The HTTP request method.
        /// </param>
        /// <param name="bodyContent">
        ///		The request body content.
        /// </param>
        /// <param name="mediaType">
        ///		The request body media type to use.
        /// </param>
        /// <param name="encoding">
        ///		The request body encoding to use.
        /// </param>
        /// <param name="baseUri">
        ///		An optional base URI to use if the request does not already have an absolute request URI.
        /// </param>
        /// <returns>
        ///		The configured <see cref="HttpRequestMessage"/>.
        /// </returns>
        public static HttpRequestMessage BuildRequestMessage(this HttpRequest request, HttpMethod httpMethod, object bodyContent, string mediaType, Encoding encoding, Uri baseUri = null)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            HttpContent httpContent = bodyContent as HttpContent;

            if (httpContent == null && bodyContent != null)
            {
                IFormatterCollection formatters = request.CreateFormatterCollection();

                OutputFormatterContext writeContext   = new OutputFormatterContext(bodyContent, bodyContent.GetType(), mediaType, encoding);
                IOutputFormatter       writeFormatter = formatters.FindOutputFormatter(writeContext);
                if (writeFormatter == null)
                {
                    throw new HttpRequestException($"None of the supplied formatters can write data of type '{writeContext.DataType.FullName}' to media type '{writeContext.MediaType}'.");
                }

                httpContent = new FormattedObjectContent(writeFormatter, writeContext);
            }

            return(request.BuildRequestMessage(httpMethod, httpContent, baseUri));
        }
        public InvolvedTypeReportGenerator(
      InvolvedType[] involvedTypes,
      IIdentifierGenerator<Assembly> assemblyIdentifierGenerator,
      IIdentifierGenerator<Type> involvedTypeIdentifierGenerator,
      IIdentifierGenerator<MemberInfo> memberIdentifierGenerator,
      IIdentifierGenerator<Type> interfaceIdentifierGenerator,
      IIdentifierGenerator<Type> attributeIdentifierGenerator,
      IRemotionReflector remotionReflector,
      IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull ("involvedTypes", involvedTypes);
              ArgumentUtility.CheckNotNull ("assemblyIdentifierGenerator", assemblyIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("involvedTypeIdentifierGenerator", involvedTypeIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("memberIdentifierGenerator", memberIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("interfaceIdentifierGenerator", interfaceIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("attributeIdentifierGenerator", attributeIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("remotionReflector", remotionReflector);
              ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _involvedTypes = involvedTypes;
              _assemblyIdentifierGenerator = assemblyIdentifierGenerator;
              _involvedTypeIdentifierGenerator = involvedTypeIdentifierGenerator;
              _memberIdentifierGenerator = memberIdentifierGenerator;
              _interfaceIdentifierGenerator = interfaceIdentifierGenerator;
              _attributeIdentifierGenerator = attributeIdentifierGenerator;
              _remotionReflector = remotionReflector;
              _outputFormatter = outputFormatter;
        }
Esempio n. 4
0
        public void Send_NullList_ReturnsArgumentNullException(IOutputFormatter formatter)
        {
            IList <MetricsResult> results = null;

            formatter.Invoking(x => x.Format(results))
            .Should().Throw <ArgumentNullException>();
        }
 public TargetCallDependenciesReportGenerator(ReflectedObject mixinDefinition, IIdentifierGenerator<Assembly> assemblyIdentifierGenerator, IRemotionReflector remotionReflector, IOutputFormatter outputFormatter)
 {
     _mixinDefinition = mixinDefinition;
       _assemblyIdentifierGenerator = assemblyIdentifierGenerator;
       _remotionReflector = remotionReflector;
       _outputFormatter = outputFormatter;
 }
Esempio n. 6
0
        public void Send_NullObject_ReturnsArgumentNullException(IOutputFormatter formatter)
        {
            MetricsResult result = null;

            formatter.Invoking(x => x.Format(result))
            .Should().Throw <ArgumentNullException>();
        }
Esempio n. 7
0
        public async Task ObjectResult_Execute_NullContent_SetsStatusCode()
        {
            // Arrange
            var stream             = new MemoryStream();
            var expectedStatusCode = StatusCodes.Status201Created;
            var httpResponse       = new Mock <HttpResponse>();

            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var formatters = new IOutputFormatter[]
            {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };
            var actionContext = CreateMockActionContext(formatters,
                                                        httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);
            var result = new ObjectResult(null);

            result.StatusCode = expectedStatusCode;

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            httpResponse.VerifySet(r => r.StatusCode = expectedStatusCode);
            Assert.Equal(0, httpResponse.Object.Body.Length);
        }
Esempio n. 8
0
 public TargetCallDependenciesReportGenerator(ReflectedObject mixinDefinition, IIdentifierGenerator <Assembly> assemblyIdentifierGenerator, IRemotionReflector remotionReflector, IOutputFormatter outputFormatter)
 {
     _mixinDefinition             = mixinDefinition;
     _assemblyIdentifierGenerator = assemblyIdentifierGenerator;
     _remotionReflector           = remotionReflector;
     _outputFormatter             = outputFormatter;
 }
Esempio n. 9
0
        internal static IOutputFormatter SelectFormatterUsingSortedAcceptHeaders(this HttpRequest request, Type objectType, object @object, List <MediaTypeSegmentWithQuality> sortedAcceptHeaders)
        {
            var options = request.HttpContext.RequestServices.GetService <IOptions <MvcOptions> >()?.Value;

            if (options == null)
            {
                return(null);
            }

            Func <Stream, Encoding, TextWriter> writerFactory = (stream, encoding) => null;
            var formatterContext = new OutputFormatterWriteContext(
                request.HttpContext,
                writerFactory,
                objectType,
                @object);

            IOutputFormatter selectedFormatter = null;

            if (sortedAcceptHeaders.Count > 0)
            {
                selectedFormatter = request.SelectFormatterUsingSortedAcceptHeaders(formatterContext, options.OutputFormatters, sortedAcceptHeaders);
            }

            return(selectedFormatter);
        }
            public void ConvertType(IType type, IOutputFormatter formatter, CSharpFormattingOptions formattingPolicy)
            {
                TypeSystemAstBuilder astBuilder = CreateAstBuilder();
                AstType astType = astBuilder.ConvertType(type);

                astType.AcceptVisitor(new CSharpOutputVisitor(formatter, formattingPolicy));
            }
        public ReportMissingMiddleware(RequestDelegate next, IOptions <ReportOptions> options, IStringLocalizerFactory factory, IOutputFormatter formatter)
        {
            _next = next;
            var reportPath = options.Value.ReportPath;

            if (string.IsNullOrEmpty(reportPath))
            {
                return;
            }
            _templateMatcher = new TemplateMatcher(TemplateParser.Parse($"{reportPath}/{{filename?}}"), new RouteValueDictionary());

            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            _formatter = formatter;

            if (factory is ReportMissingStringLocalizerFactory rmslf)
            {
                _factory = rmslf;
            }
            else
            {
                throw new InvalidOperationException($"{ nameof(ReportMissingMiddleware) } cannot be used without { nameof(ReportMissingStringLocalizerFactory) }");
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Renders just the selection set completely.
        /// </summary>
        ///
        /// <param name="outputFormatter">
        /// The output formatter.
        /// </param>
        ///
        /// <returns>
        /// A string of HTML.
        /// </returns>

        public string RenderSelection(IOutputFormatter outputFormatter)
        {
            StringWriter writer = new StringWriter();
            RenderSelection(outputFormatter, writer);

            return writer.ToString();
        }
Esempio n. 13
0
        /// <summary>
        /// Creates a new <see cref="JsonResult"/> with the given <paramref name="value"/>.
        /// </summary>
        /// <param name="value">The value to format as JSON.</param>
        /// <param name="formatter">The formatter to use, or <c>null</c> to choose a formatter dynamically.</param>
        public JsonResult(object value, IOutputFormatter formatter)
        {
            Value = value;
            Formatter = formatter;

            ContentTypes = new List<MediaTypeHeaderValue>();
        }
Esempio n. 14
0
        private async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            HttpStatusCode   code = HttpStatusCode.InternalServerError;
            OperationOutcome outcome;

            if (exception is SparkException ex1)
            {
                code    = ex1.StatusCode;
                outcome = GetOperationOutcome(ex1);
            }
            else if (exception is HttpResponseException ex2)
            {
                code    = ex2.Response.StatusCode;
                outcome = GetOperationOutcome(ex2);
            }
            else
            {
                outcome = GetOperationOutcome(exception);
            }

            // Set HTTP status code
            context.Response.StatusCode = (int)code;
            OutputFormatterWriteContext writeContext = context.GetOutputFormatterWriteContext(outcome);
            IOutputFormatter            formatter    = context.SelectFormatter(writeContext);
            // Write the OperationOutcome to the Response using an OutputFormatter from the request pipeline
            await formatter.WriteAsync(writeContext);
        }
Esempio n. 15
0
        public async Task ObjectResult_WildcardAcceptMediaType_AndExplicitResponseContentType(
            string acceptHeader,
            string expectedResponseContentType,
            bool respectBrowserAcceptHeader)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person()
            {
                Name = "John"
            });

            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                outputFormatters,
                response.Object,
                acceptHeader,
                respectBrowserAcceptHeader: respectBrowserAcceptHeader);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
Esempio n. 16
0
        /// <summary>
        /// Render the entire document, parsed through a formatter passed using the parameter, to the
        /// specified writer.
        /// </summary>
        ///
        /// <param name="formatter">
        /// The formatter.
        /// </param>
        /// <param name="writer">
        /// The writer.
        /// </param>

        public void Render(IOutputFormatter formatter, TextWriter writer)
        {
            foreach (var element in Document.ChildNodes)
            {
                formatter.Render(element, writer);
            }
        }
Esempio n. 17
0
        public async Task ObjectResult_WithStringType_WritesTextPlain_Ignoring406Formatter()
        {
            // Arrange
            var expectedData     = "Hello World!";
            var objectResult     = new ObjectResult(expectedData);
            var outputFormatters = new IOutputFormatter[]
            {
                new HttpNotAcceptableOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };

            var response       = new Mock <HttpResponse>();
            var responseStream = new MemoryStream();

            response.SetupGet(r => r.Body).Returns(responseStream);

            var actionContext = CreateMockActionContext(
                outputFormatters,
                response.Object,
                requestAcceptHeader: "application/json");

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "text/plain; charset=utf-8");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();

            Assert.Equal(expectedData, actual);
        }
        private async Task WriteResponseBodyAsync(HttpResponse response, object content)
        {
            if (content is ExpandoObject expandoContent)
            {
                content = Utility.ToJson(expandoContent, Formatting.None);
            }

            var formatterContext = CreateFormatterContext(response, content);

            IOutputFormatter selectedFormatter = SelectedFormatter(formatterContext);

            if (selectedFormatter == null)
            {
                // We were unable to locate a formatter with the provided type, to maintain the original behavior
                // we'll convert the object to string and get a formatter
                content = content?.ToString() ?? string.Empty;

                formatterContext  = CreateFormatterContext(response, content);
                selectedFormatter = SelectedFormatter(formatterContext);
            }

            formatterContext.ContentType = response.ContentType;

            await selectedFormatter.WriteAsync(formatterContext);
        }
        public MixinReferenceReportGenerator(
            InvolvedType involvedType,
            IIdentifierGenerator <Assembly> assemblyIdentifierGenerator,
            IIdentifierGenerator <Type> involvedTypeIdentifierGenerator,
            IIdentifierGenerator <Type> interfaceIdentifierGenerator,
            IIdentifierGenerator <Type> attributeIdentifierGenerator,
            IRemotionReflector remotionReflector,
            IOutputFormatter outputFormatter
            )
        {
            ArgumentUtility.CheckNotNull("involvedType", involvedType);
            ArgumentUtility.CheckNotNull("assemblyIdentifierGenerator", assemblyIdentifierGenerator);
            ArgumentUtility.CheckNotNull("involvedTypeIdentifierGenerator", involvedTypeIdentifierGenerator);
            ArgumentUtility.CheckNotNull("interfaceIdentifierGenerator", interfaceIdentifierGenerator);
            ArgumentUtility.CheckNotNull("attributeIdentifierGenerator", attributeIdentifierGenerator);
            ArgumentUtility.CheckNotNull("remotionReflector", remotionReflector);
            ArgumentUtility.CheckNotNull("outputFormatter", outputFormatter);

            _involvedType = involvedType;
            _assemblyIdentifierGenerator     = assemblyIdentifierGenerator;
            _involvedTypeIdentifierGenerator = involvedTypeIdentifierGenerator;
            _interfaceIdentifierGenerator    = interfaceIdentifierGenerator;
            _attributeIdentifierGenerator    = attributeIdentifierGenerator;
            _remotionReflector = remotionReflector;
            _outputFormatter   = outputFormatter;
        }
Esempio n. 20
0
        public async Task ObjectResult_WithStream_DoesNotSetContentType_IfNotProvided()
        {
            // Arrange
            var objectResult     = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response       = new Mock <HttpResponse>();
            var responseStream = new MemoryStream();

            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                outputFormatters,
                response.Object,
                requestAcceptHeader: null,
                requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = It.IsAny <string>(), Times.Never());
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();

            Assert.Equal(expectedData, actual);
        }
 /// <summary>
 /// Tests whether action result contains the same output formatter as the provided one.
 /// </summary>
 /// <param name="outputFormatter">Expected instance of <see cref="IOutputFormatter"/>.</param>
 protected void ValidateContainingOfOutputFormatter(IOutputFormatter outputFormatter)
 {
     OutputFormatterValidator.ValidateContainingOfOutputFormatter(
         this.GetObjectResult(),
         outputFormatter,
         this.ThrowNewFailedValidationException);
 }
Esempio n. 22
0
        public virtual void Send(IList <ScanResult> results, IOutputFormatter formatter, ScanCommandOptions options)
        {
            string       path = Path.Combine(options.Path ?? string.Empty, $"freshli-scan-{DateTime.Now:yyyyMMddTHHmmss}.{options.Format}");
            StreamWriter file = File.CreateText(path);

            file.WriteLine(formatter.Format(results));
        }
Esempio n. 23
0
        private static string Serialize <T>(T value, IOutputFormatter formatter, MediaTypeHeaderValue contentType)
        {
            if (value == null)
            {
                return(string.Empty);
            }

            using (var stringWriter = new StringWriter())
            {
                var outputFormatterContext = GetOutputFormatterContext(
                    stringWriter,
                    value,
                    value.GetType(),
                    contentType);

                formatter.WriteAsync(outputFormatterContext).GetAwaiter().GetResult();
                stringWriter.FlushAsync().GetAwaiter().GetResult();
                var response = stringWriter.ToString();
                if (string.IsNullOrEmpty(response))
                {
                    // workaround for SystemTextJsonOutputFormatter
                    var ms = (MemoryStream)outputFormatterContext.HttpContext.Response.Body;
                    response = Encoding.ASCII.GetString(ms.ToArray());
                }

                return(response);
            }
        }
Esempio n. 24
0
        public InvolvedTypeReportGenerator(
            InvolvedType[] involvedTypes,
            IIdentifierGenerator <Assembly> assemblyIdentifierGenerator,
            IIdentifierGenerator <Type> involvedTypeIdentifierGenerator,
            IIdentifierGenerator <MemberInfo> memberIdentifierGenerator,
            IIdentifierGenerator <Type> interfaceIdentifierGenerator,
            IIdentifierGenerator <Type> attributeIdentifierGenerator,
            IRemotionReflector remotionReflector,
            IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull("involvedTypes", involvedTypes);
            ArgumentUtility.CheckNotNull("assemblyIdentifierGenerator", assemblyIdentifierGenerator);
            ArgumentUtility.CheckNotNull("involvedTypeIdentifierGenerator", involvedTypeIdentifierGenerator);
            ArgumentUtility.CheckNotNull("memberIdentifierGenerator", memberIdentifierGenerator);
            ArgumentUtility.CheckNotNull("interfaceIdentifierGenerator", interfaceIdentifierGenerator);
            ArgumentUtility.CheckNotNull("attributeIdentifierGenerator", attributeIdentifierGenerator);
            ArgumentUtility.CheckNotNull("remotionReflector", remotionReflector);
            ArgumentUtility.CheckNotNull("outputFormatter", outputFormatter);

            _involvedTypes = involvedTypes;
            _assemblyIdentifierGenerator     = assemblyIdentifierGenerator;
            _involvedTypeIdentifierGenerator = involvedTypeIdentifierGenerator;
            _memberIdentifierGenerator       = memberIdentifierGenerator;
            _interfaceIdentifierGenerator    = interfaceIdentifierGenerator;
            _attributeIdentifierGenerator    = attributeIdentifierGenerator;
            _remotionReflector = remotionReflector;
            _outputFormatter   = outputFormatter;
        }
Esempio n. 25
0
        /// <summary>
        /// Creates a new <see cref="JsonResult"/> with the given <paramref name="data"/>.
        /// </summary>
        /// <param name="value">The value to format as JSON.</param>
        /// <param name="formatter">The formatter to use, or <c>null</c> to choose a formatter dynamically.</param>
        public JsonResult(object value, IOutputFormatter formatter)
        {
            Value     = value;
            Formatter = formatter;

            ContentTypes = new List <MediaTypeHeaderValue>();
        }
Esempio n. 26
0
        public async Task ObjectResult_WithStream_SetsExplicitContentType()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));

            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response       = new Mock <HttpResponse>();
            var responseStream = new MemoryStream();

            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                outputFormatters,
                response.Object,
                requestAcceptHeader: "application/json",
                requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/foo");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();

            Assert.Equal(expectedData, actual);
        }
        public MixinReferenceReportGenerator(
        InvolvedType involvedType, 
        IIdentifierGenerator<Assembly> assemblyIdentifierGenerator, 
        IIdentifierGenerator<Type> involvedTypeIdentifierGenerator, 
        IIdentifierGenerator<Type> interfaceIdentifierGenerator, 
        IIdentifierGenerator<Type> attributeIdentifierGenerator, 
        IRemotionReflector remotionReflector, 
        IOutputFormatter outputFormatter
        )
        {
            ArgumentUtility.CheckNotNull ("involvedType", involvedType);
              ArgumentUtility.CheckNotNull ("assemblyIdentifierGenerator", assemblyIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("involvedTypeIdentifierGenerator", involvedTypeIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("interfaceIdentifierGenerator", interfaceIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("attributeIdentifierGenerator", attributeIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("remotionReflector", remotionReflector);
              ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _involvedType = involvedType;
              _assemblyIdentifierGenerator = assemblyIdentifierGenerator;
              _involvedTypeIdentifierGenerator = involvedTypeIdentifierGenerator;
              _interfaceIdentifierGenerator = interfaceIdentifierGenerator;
              _attributeIdentifierGenerator = attributeIdentifierGenerator;
              _remotionReflector = remotionReflector;
              _outputFormatter = outputFormatter;
        }
Esempio n. 28
0
        public async Task ObjectResult_PerformsContentNegotiation_OnAllMediaRangeAcceptHeaderMediaType(
            string acceptHeader,
            string expectedResponseContentType)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person()
            {
                Name = "John"
            });
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                outputFormatters,
                response.Object,
                requestAcceptHeader: acceptHeader,
                respectBrowserAcceptHeader: true);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
Esempio n. 29
0
 public ApiResponseFactory(
     IOutputFormatter outputFormatter,
     IModelMetadataProvider modelMetadataProvider)
 {
     _outputFormatter       = outputFormatter;
     _modelMetadataProvider = modelMetadataProvider;
 }
Esempio n. 30
0
        /// <summary>
        /// Renders just the selection set completely.
        /// </summary>
        ///
        /// <param name="outputFormatter">
        /// The output formatter.
        /// </param>
        /// <param name="writer">
        /// The writer.
        /// </param>
        ///
        /// <returns>
        /// A string of HTML.
        /// </returns>

        public void RenderSelection(IOutputFormatter outputFormatter, StringWriter writer)
        {
            foreach (IDomObject elm in this)
            {
                elm.Render(outputFormatter, writer);
            }
        }
Esempio n. 31
0
        /// <summary>
        /// Render the entire document, parsed through a formatter passed using the parameter.
        /// </summary>
        ///
        /// <remarks>
        /// CsQuery by default does not format the output at all, but rather returns exactly the same
        /// contents of each element from the source, including all extra whitespace. If you want to
        /// produce output that is formatted in a specific way, you can create an OutputFormatter for
        /// this purpose. The included <see cref="T:CsQuery.OutputFormatters.FormatPlainText"/> does some
        /// basic formatting by removing extra whitespace and adding newlines in a few useful places.
        /// (This formatter is pretty basic). A formatter to perform indenting to create human-readable
        /// output would be useful and will be included in some future release.
        /// </remarks>
        ///
        /// <param name="formatter">
        /// An object that parses a CQ object and returns a string of HTML.
        /// </param>
        ///
        /// <returns>
        /// A string of HTML.
        /// </returns>

        public string Render(IOutputFormatter formatter)
        {
            StringBuilder sb     = new StringBuilder();
            StringWriter  writer = new StringWriter(sb);

            Render(formatter, writer);
            return(sb.ToString());
        }
Esempio n. 32
0
 protected override IOutputFormatter SelectFormatter(
     OutputFormatterWriteContext formatterContext,
     MediaTypeCollection contentTypes,
     IList <IOutputFormatter> formatters)
 {
     SelectedOutputFormatter = base.SelectFormatter(formatterContext, contentTypes, formatters);
     return(SelectedOutputFormatter);
 }
Esempio n. 33
0
        /// <summary>
        /// Renders just the selection set completely.
        /// </summary>
        ///
        /// <param name="outputFormatter">
        /// The output formatter.
        /// </param>
        ///
        /// <returns>
        /// A string of HTML.
        /// </returns>

        public string RenderSelection(IOutputFormatter outputFormatter)
        {
            StringWriter writer = new StringWriter();

            RenderSelection(outputFormatter, writer);

            return(writer.ToString());
        }
 public static void FormatterSelected(
     this ILogger logger,
     IOutputFormatter outputFormatter,
     OutputFormatterWriteContext context)
 {
     var contentType = Convert.ToString(context.ContentType);
     _formatterSelected(logger, outputFormatter, contentType, null);
 }
Esempio n. 35
0
        /// <summary>
        /// Renders just the selection set completely.
        /// </summary>
        ///
        /// <param name="outputFormatter">
        /// The output formatter.
        /// </param>
        /// <param name="writer">
        /// The writer.
        /// </param>
        ///
        /// <returns>
        /// A string of HTML.
        /// </returns>

        public void RenderSelection(IOutputFormatter outputFormatter, StringWriter writer)
        {
            foreach (IDomObject elm in this)
            {
                elm.Render(outputFormatter, writer);
            }

        }
Esempio n. 36
0
 public static void Execute(ICaptureDevice device, IOutputFormatter output)
 {
     device.OnPacketArrival += Device_OnPacketArrival;
     device.Open();
     device.Filter = "port 53";
     device.Capture();
     device.Close();
 }
Esempio n. 37
0
    public void Send(IList <ScanResult> results, IOutputFormatter formatter, ScanCommandOptions options)
    {
        var path = Path.Combine(options.Path.FullName,
                                $"freshli-scan-{DateTime.Now:yyyyMMddTHHmmss}.{options.Format}");
        var file = File.CreateText(path);

        file.WriteLine(formatter.Format(results));
    }
 public DecoratedOutputFormatter(IOutputFormatter formatter, IAstVisitor visitor)
 {
     if (formatter == null)
         throw new ArgumentNullException(nameof(formatter));
     if (visitor == null)
         throw new ArgumentNullException(nameof(visitor));
     _formatter = formatter;
     _visitor = visitor;
 }
 /// <summary>
 /// Initializes a new instance of <see cref="CodeCommentDecorator"/> with the provided
 /// <paramref name="outputFormatter"/>.
 /// </summary>
 /// 
 /// <param name="outputFormatter">
 /// An <see cref="IOutputFormatter"/> implementation to which code documentation comments will be written.
 /// </param>
 public CodeCommentDecorator(IOutputFormatter outputFormatter)
 {
     if (outputFormatter == null)
     {
         Debug.Assert(false, "outputFormatter is null");
         throw new ArgumentNullException("outputFormatter");
     }
     _formatter = outputFormatter;
 }
Esempio n. 40
0
 public static InterfaceReportGenerator CreateInterfaceReportGenerator(IRemotionReflector remotionReflector, IOutputFormatter outputFormatter, params InvolvedType[] types)
 {
     return new InterfaceReportGenerator (types,
                                    new IdentifierGenerator<Assembly> (),
                                    new IdentifierGenerator<Type> (),
                                    new IdentifierGenerator<MemberInfo> (),
                                    new IdentifierGenerator<Type> (),
                                    remotionReflector,
                                    outputFormatter);
 }
Esempio n. 41
0
		public CSharpOutputVisitor (TextWriter textWriter, CSharpFormattingOptions formattingPolicy)
		{
			if (textWriter == null) {
				throw new ArgumentNullException ("textWriter");
			}
			if (formattingPolicy == null) {
				throw new ArgumentNullException ("formattingPolicy");
			}
			this.formatter = new TextWriterOutputFormatter (textWriter);
			this.policy = formattingPolicy;
		}
Esempio n. 42
0
		public CSharpOutputVisitor (IOutputFormatter formatter, CSharpFormattingOptions formattingPolicy)
		{
			if (formatter == null) {
				throw new ArgumentNullException ("formatter");
			}
			if (formattingPolicy == null) {
				throw new ArgumentNullException ("formattingPolicy");
			}
			this.formatter = formatter;
			this.policy = formattingPolicy;
		}
Esempio n. 43
0
 public Configuration(IEnumerable<IFieldHarvester> fieldHarvesters, 
   IEnumerable<IValueConverter> valueConverters, 
   string indentIncrement, 
   IOutputFormatter outputFormatter,
   CultureInfo culture)
 {
   this.valueConverters = valueConverters.ToList();
   this.fieldHarvesters = fieldHarvesters.ToList();
   IndentIncrement = indentIncrement;
   OutputFormatter = outputFormatter;
   Culture = culture;
 }
        public AdditionalDependencyReportGenerator(
        ReflectedObject explicitDependencies,
        IIdentifierGenerator<Type> involvedTypeIdentifierGenerator,
        IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull ("explicitDependencies", explicitDependencies);
              ArgumentUtility.CheckNotNull ("involvedTypeIdentifierGenerator", involvedTypeIdentifierGenerator);
              ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _explicitDependencies = explicitDependencies;
              _involvedTypeIdentifierGenerator = involvedTypeIdentifierGenerator;
              _outputFormatter = outputFormatter;
        }
Esempio n. 45
0
        public static InvolvedTypeReportGenerator CreateInvolvedTypeReportGenerator(IRemotionReflector remotionReflector, IOutputFormatter outputFormatter, params InvolvedType[] involvedTypes)
        {
            var assemblyIdentifierGenerator = StubFactory.CreateIdentifierGeneratorStub (new Assembly[0]);
              var involvedTypeIdentifierGenerator = StubFactory.CreateIdentifierGeneratorStub (involvedTypes.Select (t => t.Type));

              return new InvolvedTypeReportGenerator (involvedTypes,
                                              assemblyIdentifierGenerator,
                                              involvedTypeIdentifierGenerator,
                                              new IdentifierGenerator<MemberInfo> (),
                                              new IdentifierGenerator<Type> (),
                                              new IdentifierGenerator<Type> (),
                                              remotionReflector,
                                              outputFormatter);
        }
Esempio n. 46
0
        /// <summary>
        /// Instantiate using the <see cref="DefaultIndention"/> and the <see cref="CurlyBraceStyle"/>
        /// </summary>
        public Configuration(
            string indentIncrement = DefaultIndention,
            TestFrameworkAreEqualsMethod areEqualsMethod = null)
        {
            IndentIncrement = indentIncrement;
            OutputFormatter = new CurlyBraceStyle(this);
            NewLineDefinition = Environment.NewLine;
            LegacyBehaviour = new LegacyBehaviour();

            Test = new TestingBehaviour(this);
            Test.SetAutomaticTestRewrite(x => false);
            Test.SetAssertMessageCreator(new DefaultAssertMessage().Create);

            if(areEqualsMethod != null)
                Test.SetAreEqualsMethod(areEqualsMethod);
        }
Esempio n. 47
0
        public FullReportGenerator(
        InvolvedType[] involvedTypes,
        ErrorAggregator<Exception> configurationErrors,
        ErrorAggregator<Exception> validationErrors,
        IRemotionReflector remotionReflector,
        IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull ("_involvedTypes", involvedTypes);
              ArgumentUtility.CheckNotNull ("configurationErrors", configurationErrors);
              ArgumentUtility.CheckNotNull ("validationErrors", validationErrors);
              ArgumentUtility.CheckNotNull ("remotionReflector", remotionReflector);
              ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _involvedTypes = involvedTypes;
              _configurationErrors = configurationErrors;
              _validationErrors = validationErrors;
              _remotionReflector = remotionReflector;
              _outputFormatter = outputFormatter;
        }
        public MemberReportGenerator(
      Type type,
      InvolvedType involvedTypeOrNull,
      IIdentifierGenerator<Type> involvedTypeIdentifierGeneratorOrNull,
      IIdentifierGenerator<MemberInfo> memberIdentifierGeneratorOrNull,
      IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull ("type", type);
              // may be null
              // ArgumentUtility.CheckNotNull ("involvedTypeOrNull", involvedTypeOrNull);
              // ArgumentUtility.CheckNotNull ("involvedTypeIdentifierGeneratorOrNull", involvedTypeIdentifierGeneratorOrNull);
              // ArgumentUtility.CheckNotNull ("memberIdentifierGeneratorOrNull", memberIdentifierGeneratorOrNull);
              ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _type = type;
              _involvedType = involvedTypeOrNull;
              _involvedTypeIdentifierGenerator = involvedTypeIdentifierGeneratorOrNull;
              _memberIdentifierGenerator = memberIdentifierGeneratorOrNull;
              _outputFormatter = outputFormatter;
              _memberSignatureUtility = new MemberSignatureUtility (outputFormatter);
        }
Esempio n. 49
0
        private PlaceHolder(Match match)
        {
            rawText = match.Groups[0].Value;
            name = match.Groups["Name"].Value;
            prefix = match.Groups["Prefix"].Value;
            expression = match.Groups["Value"].Value;

            string formatName = match.Groups["Format"].Value;
            if (formatName.Length > 0)
                outputFormat = OutputFormatRegistry.Formats[formatName];
            string type = outputFormat == null ? "" : outputFormat.GetAttribute("OutputType");
            if (PageRequestHandler.Instance.OutputFormatters.ContainsKey(type))
                outputFormatter = PageRequestHandler.Instance.OutputFormatters[type];
            else
                outputFormatter = new MissingOutputFormatter();

            string lprefix = prefix.ToLower();
            if (PageRequestHandler.Instance.PlaceHolderRenderers.ContainsKey(lprefix))
                this.renderer = PageRequestHandler.Instance.PlaceHolderRenderers[lprefix];
            else
                this.renderer = new UnknownPlaceHolderRenderer();
        }
        private static ActionContext CreateMockActionContext(
                                                             HttpResponse response = null,
                                                             string requestAcceptHeader = "application/*",
                                                             string requestContentType = "application/json",
                                                             string requestAcceptCharsetHeader = "",
                                                             bool respectBrowserAcceptHeader = false)
        {
            var formatters = new IOutputFormatter[] { new StringOutputFormatter(), new JsonOutputFormatter() };
            var httpContext = new Mock<HttpContext>();
            if (response != null)
            {
                httpContext.Setup(o => o.Response).Returns(response);
            }

            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var request = new DefaultHttpContext().Request;
            request.Headers["Accept-Charset"] = requestAcceptCharsetHeader;
            request.Headers["Accept"] = requestAcceptHeader;
            request.ContentType = requestContentType;
            request.Body = new MemoryStream(contentBytes);

            httpContext.Setup(o => o.Request).Returns(request);
            httpContext.Setup(o => o.RequestServices).Returns(GetServiceProvider());
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOutputFormattersProvider)))
                       .Returns(new TestOutputFormatterProvider(formatters));

            var options = new Mock<IOptions<MvcOptions>>();
            options.SetupGet(o => o.Options)
                       .Returns(new MvcOptions()
                       {
                           RespectBrowserAcceptHeader = respectBrowserAcceptHeader
                       });
            httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>)))
                       .Returns(options.Object);

            return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor());
        }
Esempio n. 51
0
        public async Task ObjectResult_WithStringType_WritesTextPlain_Ignoring406Formatter()
        {
            // Arrange
            var expectedData = "Hello World!";
            var objectResult = new ObjectResult(expectedData);
            var outputFormatters = new IOutputFormatter[] 
            {
                new HttpNotAcceptableOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };

            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/json");

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "text/plain; charset=utf-8");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Esempio n. 52
0
        public async Task ObjectResult_Execute_NullContent_SetsStatusCode()
        {
            // Arrange
            var stream = new MemoryStream();
            var expectedStatusCode = StatusCodes.Status201Created;
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.SetupGet(r => r.Body).Returns(stream);

            var formatters = new IOutputFormatter[]
            {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter()
            };
            var actionContext = CreateMockActionContext(formatters,
                                                        httpResponse.Object,
                                                        requestAcceptHeader: null,
                                                        requestContentType: null);
            var result = new ObjectResult(null);
            result.StatusCode = expectedStatusCode;

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            httpResponse.VerifySet(r => r.StatusCode = expectedStatusCode);
            Assert.Equal(0, httpResponse.Object.Body.Length);
        }
        public MemberSignatureUtility(IOutputFormatter outputFormatter)
        {
            ArgumentUtility.CheckNotNull ("outputFormatter", outputFormatter);

              _outputFormatter = outputFormatter;
        }
Esempio n. 54
0
        public async Task ObjectResult_WildcardAcceptMediaType_AndExplicitResponseContentType(
            string acceptHeader,
            string expectedResponseContentType,
            bool respectBrowserAcceptHeader)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/xml"));
            objectResult.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    acceptHeader,
                                    respectBrowserAcceptHeader: respectBrowserAcceptHeader);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
Esempio n. 55
0
        public async Task ObjectResult_PerformsContentNegotiation_OnAllMediaRangeAcceptHeaderMediaType(
            string acceptHeader,
            string expectedResponseContentType)
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            var outputFormatters = new IOutputFormatter[] {
                new HttpNoContentOutputFormatter(),
                new StringOutputFormatter(),
                new JsonOutputFormatter(),
                new XmlDataContractSerializerOutputFormatter()
            };
            var response = GetMockHttpResponse();

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: acceptHeader,
                                    respectBrowserAcceptHeader: true);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(resp => resp.ContentType = expectedResponseContentType);
        }
 public void SetUp()
 {
     _remotionReflector = Helpers.RemotionReflectorFactory.GetRemotionReflection ();
       _outputFormatter = new OutputFormatter ();
 }
Esempio n. 57
0
        private static ActionContext CreateMockActionContext(
            HttpResponse response = null,
            string requestAcceptHeader = "application/*",
            string requestContentType = "application/json",
            string requestAcceptCharsetHeader = "",
            bool respectBrowserAcceptHeader = false)
        {
            var formatters = new IOutputFormatter[] { new StringOutputFormatter(), new JsonOutputFormatter() };

            return CreateMockActionContext(
                                            formatters,
                                            response: response,
                                            requestAcceptHeader: requestAcceptHeader,
                                            requestContentType: requestContentType,
                                            requestAcceptCharsetHeader: requestAcceptCharsetHeader,
                                            respectBrowserAcceptHeader: respectBrowserAcceptHeader);
        }
Esempio n. 58
0
        public async Task ObjectResult_WithStream_SetsExplicitContentType()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/json",
                                    requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/foo");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Esempio n. 59
0
        public async Task ObjectResult_WithStream_DoesNotSetContentType_IfNotProvided()
        {
            // Arrange
            var objectResult = new ObjectResult(new MemoryStream(Encoding.UTF8.GetBytes("Name=James")));
            var outputFormatters = new IOutputFormatter[]
            {
                new StreamOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "Name=James";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: null,
                                    requestContentType: null);

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = It.IsAny<string>(), Times.Never());
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }
Esempio n. 60
-1
        public async Task ObjectResult_WithMultipleContentTypes_Ignores406Formatter()
        {
            // Arrange
            var objectResult = new ObjectResult(new Person() { Name = "John" });
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/foo"));
            objectResult.ContentTypes.Add(new MediaTypeHeaderValue("application/json"));
            var outputFormatters = new IOutputFormatter[] 
            {
                new HttpNotAcceptableOutputFormatter(),
                new JsonOutputFormatter()
            };
            var response = new Mock<HttpResponse>();
            var responseStream = new MemoryStream();
            response.SetupGet(r => r.Body).Returns(responseStream);
            var expectedData = "{\"Name\":\"John\"}";

            var actionContext = CreateMockActionContext(
                                    outputFormatters,
                                    response.Object,
                                    requestAcceptHeader: "application/non-existing",
                                    requestContentType: "application/non-existing");

            // Act
            await objectResult.ExecuteResultAsync(actionContext);

            // Assert
            response.VerifySet(r => r.ContentType = "application/json; charset=utf-8");
            responseStream.Position = 0;
            var actual = new StreamReader(responseStream).ReadToEnd();
            Assert.Equal(expectedData, actual);
        }