예제 #1
0
 public void AddDefaultResponseFormat(string mediaType, IOutputFormatter outputFormatter = null)
 {
     AddDefaultResponseFormat(new ApiResponseFormat()
     {
         MediaType = mediaType, Formatter = outputFormatter
     });
 }
예제 #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;
        }
예제 #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;
 }
예제 #6
0
        public void Send_NullObject_ReturnsArgumentNullException(IOutputFormatter formatter)
        {
            MetricsResult result = null;

            formatter.Invoking(x => x.Format(result))
            .Should().Throw <ArgumentNullException>();
        }
예제 #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);
        }
예제 #8
0
 public TargetCallDependenciesReportGenerator(ReflectedObject mixinDefinition, IIdentifierGenerator <Assembly> assemblyIdentifierGenerator, IRemotionReflector remotionReflector, IOutputFormatter outputFormatter)
 {
     _mixinDefinition             = mixinDefinition;
     _assemblyIdentifierGenerator = assemblyIdentifierGenerator;
     _remotionReflector           = remotionReflector;
     _outputFormatter             = outputFormatter;
 }
예제 #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) }");
            }
        }
예제 #12
0
파일: Render.cs 프로젝트: emrahoner/CsQuery
        /// <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();
        }
예제 #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>();
        }
예제 #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);
        }
예제 #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);
        }
예제 #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);
            }
        }
예제 #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);
        }
예제 #18
0
        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;
        }
예제 #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);
 }
예제 #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));
        }
예제 #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);
            }
        }
예제 #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;
        }
예제 #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>();
        }
예제 #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;
        }
예제 #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);
        }
예제 #29
0
 public ApiResponseFactory(
     IOutputFormatter outputFormatter,
     IModelMetadataProvider modelMetadataProvider)
 {
     _outputFormatter       = outputFormatter;
     _modelMetadataProvider = modelMetadataProvider;
 }
예제 #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);
            }
        }
예제 #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());
        }
예제 #32
0
 protected override IOutputFormatter SelectFormatter(
     OutputFormatterWriteContext formatterContext,
     MediaTypeCollection contentTypes,
     IList <IOutputFormatter> formatters)
 {
     SelectedOutputFormatter = base.SelectFormatter(formatterContext, contentTypes, formatters);
     return(SelectedOutputFormatter);
 }
예제 #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);
 }
예제 #35
0
파일: Render.cs 프로젝트: emrahoner/CsQuery
        /// <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);
            }

        }
예제 #36
0
 public static void Execute(ICaptureDevice device, IOutputFormatter output)
 {
     device.OnPacketArrival += Device_OnPacketArrival;
     device.Open();
     device.Filter = "port 53";
     device.Capture();
     device.Close();
 }
예제 #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;
 }
예제 #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);
 }
예제 #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;
		}
예제 #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;
		}
예제 #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;
        }
예제 #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);
        }
예제 #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);
        }
예제 #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;
        }
예제 #48
0
        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);
        }
예제 #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());
        }
예제 #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);
        }
예제 #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;
        }
예제 #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);
        }
예제 #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 ();
 }
예제 #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);
        }
예제 #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);
        }
예제 #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);
        }
예제 #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);
        }