public FilesApi(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, IHttpHeaders baseHeaders, string serviceName) { this.baseAddress = baseAddress.WithResource(serviceName); this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
/// <summary> /// Initializes a new instance of the <see cref="MockDynamicTypeBuilder"/> class. /// </summary> /// <param name="httpClientFactory"><see cref="IHttpClientFactory"/> that will be used for <see cref="HttpClient"/> building.</param> /// <param name="contentSerializer"><see cref="IContentSerializer"/> that will be used for http content serialization.</param> /// <param name="httpClient">Http client.</param> public MockDynamicTypeBuilder( IHttpClientFactory httpClientFactory, IContentSerializer contentSerializer, IHttpClient?httpClient = null) { _methodReplacer = new MethodReplacer(httpClientFactory, contentSerializer, httpClient); }
private void SerializeToResponseBody(HttpContext context, IContentSerializer serializer, object values, bool canCompress) { Stream responseStream = context.Response.Body; if (canCompress) { if (context.Request.Headers.TryGetValue("Accept-Encoding", out var encoding)) { var encoder = _contentEncodingProvider.GetContentEncoder(encoding.ToString()); if (encoder != null) { context.Response.Headers["Content-Encoding"] = encoder.ContentEncoding; responseStream = encoder.EncodeStream(responseStream); } } } SerializeToStream(context, serializer, values, responseStream); if (responseStream != context.Response.Body) { responseStream.Dispose(); } }
/// <summary> /// Initializes a new instance of the <see cref="RestContext"/> class. /// </summary> /// <param name="baseAddress">Base address (URL).</param> /// <param name="applicationName">Application name.</param> /// <param name="applicationApiKey">Application API key.</param> /// <param name="sessionId">SessionId to be added to base headers.</param> /// <param name="httpFacade">User defined instance of <see cref="IHttpFacade"/>.</param> /// <param name="serializer">User defined instance of <see cref="IContentSerializer"/>.</param> /// <param name="apiVersion">REST API version to use.</param> public RestContext(string baseAddress, string applicationName, string applicationApiKey, string sessionId, IHttpFacade httpFacade, IContentSerializer serializer, RestApiVersion apiVersion = RestApiVersion.V2) { HttpUtils.CheckUrlString(baseAddress); if (applicationName == null) { throw new ArgumentNullException("applicationName"); } if (applicationApiKey == null) { throw new ArgumentNullException("applicationApiKey"); } if (httpFacade == null) { throw new ArgumentNullException("httpFacade"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } address = new HttpAddress(baseAddress, apiVersion); HttpFacade = httpFacade; ContentSerializer = serializer; SetBaseHeaders(applicationName, applicationApiKey, sessionId); Factory = new ServiceFactory(address, HttpFacade, ContentSerializer, httpHeaders); }
public FilesApi(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, IHttpHeaders baseHeaders, string serviceName) { this.baseAddress = baseAddress.WithResource(serviceName); this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
public SystemApi(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, IHttpHeaders baseHeaders) { this.baseAddress = baseAddress.WithResource("system"); this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
public SendEmail(ISmtpService smtpService, IOptions <SmtpOptions> options, IHttpClientFactory httpClientFactory, IContentSerializer contentSerializer) { _smtpService = smtpService; _httpClientFactory = httpClientFactory; _contentSerializer = contentSerializer; _options = options.Value; }
/// <summary> /// Initializes a new instance of the <see cref="FluentClient"/> class. /// </summary> /// <param name="serializer">The serializer to convert to and from HttpContent.</param> /// <param name="httpHandler">The HTTP handler stack to use for sending requests.</param> /// <param name="disposeHandler"> /// <c>true</c> if the inner handler should be disposed of by the Dispose method, /// <c>false</c> if you intend to reuse the inner handler. /// </param> /// <param name="interceptors">The list of <see cref="IFluentClientInterceptor"/> for this client..</param> /// <exception cref="System.ArgumentNullException"> /// </exception> public FluentClient(IContentSerializer serializer, HttpMessageHandler httpHandler, bool disposeHandler, IEnumerable <IFluentClientInterceptor> interceptors) { if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } if (httpHandler == null) { throw new ArgumentNullException(nameof(httpHandler)); } if (interceptors == null) { throw new ArgumentNullException(nameof(interceptors)); } Serializer = serializer; HttpHandler = httpHandler; DisposeHandler = disposeHandler; Interceptors = new List <IFluentClientInterceptor>(interceptors); MaxRetry = 1; _defaultRequest = new FluentRequest(); }
public UserApi(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) { this.baseAddress = baseAddress.WithResource("user"); this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
/// <summary> /// Initializes a new instance of the <see cref="RestContext"/> class. /// </summary> /// <param name="baseAddress">Base address (URL).</param> /// <param name="applicationName">Application name.</param> /// <param name="applicationApiKey">Application API key.</param> /// <param name="sessionId">SessionId to be added to base headers.</param> /// <param name="httpFacade">User defined instance of <see cref="IHttpFacade"/>.</param> /// <param name="serializer">User defined instance of <see cref="IContentSerializer"/>.</param> /// <param name="apiVersion">REST API version to use.</param> public RestContext(string baseAddress, string applicationName, string applicationApiKey, string sessionId, IHttpFacade httpFacade, IContentSerializer serializer, RestApiVersion apiVersion = RestApiVersion.V2) { HttpUtils.CheckUrlString(baseAddress); if (applicationName == null) { throw new ArgumentNullException("applicationName"); } if (applicationApiKey == null) { throw new ArgumentNullException("applicationApiKey"); } if (httpFacade == null) { throw new ArgumentNullException("httpFacade"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } address = new HttpAddress(baseAddress, apiVersion); HttpFacade = httpFacade; ContentSerializer = serializer; SetBaseHeaders(applicationName, applicationApiKey, sessionId); Factory = new ServiceFactory(address, HttpFacade, ContentSerializer, httpHeaders); }
public ServiceFactory(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) { this.baseAddress = baseAddress; this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
public BlobStorageWorkflowProvider(IOptions <BlobStorageWorkflowProviderOptions> options, IWorkflowBlueprintMaterializer workflowBlueprintMaterializer, IContentSerializer contentSerializer, ILogger <BlobStorageWorkflowProvider> logger) { _storage = options.Value.BlobStorageFactory(); _workflowBlueprintMaterializer = workflowBlueprintMaterializer; _contentSerializer = contentSerializer; _logger = logger; }
public BlobStorageWorkflowProvider(IBlobStorage storage, IWorkflowBlueprintMaterializer workflowBlueprintMaterializer, IContentSerializer contentSerializer, ILogger <BlobStorageWorkflowProvider> logger) { _storage = storage; _workflowBlueprintMaterializer = workflowBlueprintMaterializer; _contentSerializer = contentSerializer; _logger = logger; }
public ServiceFactory(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) { this.baseAddress = baseAddress; this.httpFacade = httpFacade; this.contentSerializer = contentSerializer; this.baseHeaders = baseHeaders; }
/// <summary> /// Initializes a new instance of the <see cref="Poster"/> class. /// </summary> /// <param name="httpClientFactory">Http client factory.</param> /// <param name="contentSerializer">Content serializer.</param> /// <param name="httpClient">Http client.</param> internal Poster( IHttpClientFactory httpClientFactory, IContentSerializer contentSerializer, IHttpClient?httpClient = null) { _typeBuilder = new MockDynamicTypeBuilder(httpClientFactory, contentSerializer, httpClient); }
public void ToXmlStringWithSettingsReturnsCorrectResult( TestXmlWritable writable, IContentSerializer dummySerializer) { var settings = new XmlWriterSettings { OmitXmlDeclaration = true }; var actual = writable.ToXmlString(dummySerializer, settings); var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb, settings)) { writable.WriteTo(w); w.Flush(); } var expected = XDocument.Parse(sb.ToString()); Assert.Equal( expected, XDocument.Parse(actual), new XNodeEqualityComparer()); Assert.False( actual.StartsWith("<?"), "XML declaration not expected due to XmlWriterSettings"); }
public RequestBuilderImplementation(RefitSettings refitSettings = null) { Type targetInterface = typeof(TApi); settings = refitSettings ?? new RefitSettings(); serializer = settings.ContentSerializer; interfaceGenericHttpMethods = new ConcurrentDictionary <CloseGenericMethodKey, RestMethodInfo>(); if (targetInterface == null || !targetInterface.GetTypeInfo().IsInterface) { throw new ArgumentException("targetInterface must be an Interface"); } TargetType = targetInterface; var dict = new Dictionary <string, List <RestMethodInfo> >(); foreach (var methodInfo in targetInterface.GetMethods()) { var attrs = methodInfo.GetCustomAttributes(true); var hasHttpMethod = attrs.OfType <HttpMethodAttribute>().Any(); if (hasHttpMethod) { if (!dict.ContainsKey(methodInfo.Name)) { dict.Add(methodInfo.Name, new List <RestMethodInfo>()); } var restinfo = new RestMethodInfo(targetInterface, methodInfo, settings); dict[methodInfo.Name].Add(restinfo); } } interfaceHttpMethods = dict; }
public void ReadNonPersistedFeedReturnsCorrectFeed( AtomEventsInMemory sut, UuidIri id, IContentSerializer dummySerializer) { var expectedSelfLink = AtomLink.CreateSelfLink( new Uri( ((Guid)id).ToString(), UriKind.Relative)); var before = DateTimeOffset.Now; using (var r = sut.CreateFeedReaderFor(expectedSelfLink.Href)) { var actual = AtomFeed.ReadFrom(r, dummySerializer); Assert.Equal(id, actual.Id); Assert.Equal("Index of event stream " + (Guid)id, actual.Title); Assert.True(before <= actual.Updated, "Updated should be very recent."); Assert.True(actual.Updated <= DateTimeOffset.Now, "Updated should not be in the future."); Assert.Empty(actual.Entries); Assert.Contains( expectedSelfLink, actual.Links); } }
public CybtansContentSerializer(Encoding encoding, IContentSerializer defaultSerializer) { _encoding = encoding; _mediaType = $"{BinarySerializer.MEDIA_TYPE}; charset={_encoding.WebName}"; _defaultSerializer = defaultSerializer; _arrayPool = ArrayPool <byte> .Shared; }
public RequestBuilderImplementation(RefitSettings refitSettings = null) { Type targetInterface = typeof(TApi); Type[] targetInterfaceInheritedInterfaces = targetInterface.GetInterfaces(); settings = refitSettings ?? new RefitSettings(); serializer = settings.ContentSerializer; interfaceGenericHttpMethods = new ConcurrentDictionary <CloseGenericMethodKey, RestMethodInfo>(); if (targetInterface == null || !targetInterface.GetTypeInfo().IsInterface) { throw new ArgumentException("targetInterface must be an Interface"); } TargetType = targetInterface; var dict = new Dictionary <string, List <RestMethodInfo> >(); AddInterfaceHttpMethods(targetInterface, dict); foreach (var inheritedInterface in targetInterfaceInheritedInterfaces) { AddInterfaceHttpMethods(inheritedInterface, dict); } interfaceHttpMethods = dict; }
public NozomiClient(HttpClient client, string baseAddress, IContentSerializer requestSerializer, IContentSerializer responseSerializer) { this.client = client ?? throw new ArgumentNullException(nameof(client)); this.baseAddress = baseAddress ?? throw new ArgumentNullException(nameof(baseAddress)); this.requestSerializer = requestSerializer ?? throw new ArgumentNullException(nameof(requestSerializer)); this.responseSerializer = responseSerializer ?? throw new ArgumentNullException(nameof(responseSerializer)); }
public List(IWorkflowDefinitionStore workflowDefinitionStore, IContentSerializer serializer, IMapper mapper, ITenantAccessor tenantAccessor) { _workflowDefinitionStore = workflowDefinitionStore; _serializer = serializer; _mapper = mapper; _tenantAccessor = tenantAccessor; }
protected CapPublisherBase(IServiceProvider service) { ServiceProvider = service; _transaction = service.GetRequiredService <CapTransactionBase>(); _msgPacker = service.GetRequiredService <IMessagePacker>(); _serializer = service.GetRequiredService <IContentSerializer>(); }
private void WriteEntriesTo(XmlWriter xmlWriter, IContentSerializer serializer) { foreach (var e in this.entries) { e.WriteTo(xmlWriter, serializer); } }
/// <summary> /// Parses the supplied XML into an instance of /// <see cref="AtomFeed" />. /// </summary> /// <param name="xml"> /// A string of characters containing the XML representation of an Atom Feed. /// </param> /// <param name="serializer"> /// An <see cref="IContentSerializer" /> used to deserialize custom /// content to objects. /// </param> /// <returns> /// A new instance of <see cref="AtomFeed" /> containing the data from /// the supplied <paramref name="xml" />. /// </returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="serializer" /> is <see langword="null" />. /// </exception> public static AtomFeed Parse(string xml, IContentSerializer serializer) { if (serializer == null) { throw new ArgumentNullException("serializer"); } var sr = new StringReader(xml); try { using (var r = XmlReader.Create(sr)) { sr = null; return(AtomFeed.ReadFrom(r, serializer)); } } finally { if (sr != null) { sr.Dispose(); } } }
public void WithSerializerContent_GivenRuleBuilderAndContentSerializationProvider_SetsContentContainerAsSerializedContentContainer() { // Assert ContentContainer <ContentType> contentContainer = null; ContentType contentType = ContentType.Type1; string content = "TEST"; IRuleBuilder <ContentType, ConditionType> ruleBuilder = Mock.Of <IRuleBuilder <ContentType, ConditionType> >(); Mock.Get(ruleBuilder) .Setup(x => x.WithContentContainer(It.IsAny <ContentContainer <ContentType> >())) .Callback <ContentContainer <ContentType> >((x) => contentContainer = x) .Returns(ruleBuilder); IContentSerializer contentSerializer = Mock.Of <IContentSerializer>(); Mock.Get(contentSerializer) .Setup(x => x.Deserialize(It.IsAny <object>(), It.IsAny <Type>())) .Returns(content); IContentSerializationProvider <ContentType> contentSerializationProvider = Mock.Of <IContentSerializationProvider <ContentType> >(); Mock.Get(contentSerializationProvider) .Setup(x => x.GetContentSerializer(contentType)) .Returns(contentSerializer); // Act IRuleBuilder <ContentType, ConditionType> returnRuleBuilder = ruleBuilder.WithSerializedContent(contentType, content, contentSerializationProvider); // Assert returnRuleBuilder.Should().BeSameAs(ruleBuilder); contentContainer.Should().NotBeNull() .And.BeOfType <SerializedContentContainer <ContentType> >(); }
/// <summary> /// Writes the object to XML using the supplied /// <see cref="XmlWriter" /> and <see cref="IContentSerializer" />. /// </summary> /// <param name="xmlWriter"> /// The <see cref="XmlWriter" /> with which the object should be /// written. /// </param> /// <param name="serializer"> /// The <see cref="IContentSerializer" /> to use to serialize any /// custom content. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="xmlWriter" /> is <see langword="null" />. /// </exception> public void WriteTo(XmlWriter xmlWriter, IContentSerializer serializer) { if (xmlWriter == null) { throw new ArgumentNullException("xmlWriter"); } xmlWriter.WriteStartElement("feed", "http://www.w3.org/2005/Atom"); xmlWriter.WriteElementString("id", this.id.ToString()); xmlWriter.WriteStartElement("title"); xmlWriter.WriteAttributeString("type", "text"); xmlWriter.WriteString(this.title); xmlWriter.WriteEndElement(); xmlWriter.WriteElementString( "updated", this.updated.ToString( "o", CultureInfo.InvariantCulture)); this.author.WriteTo(xmlWriter); this.WriteLinksTo(xmlWriter); this.WriteEntriesTo(xmlWriter, serializer); xmlWriter.WriteEndElement(); }
protected BaseApi(IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders, string apiName) { this.BaseAddress = baseAddress.WithResource(apiName); this.HttpFacade = httpFacade; this.ContentSerializer = contentSerializer; this.BaseHeaders = baseHeaders; }
public ContainerSpecificContentCreator(IDocumentCreator documentCreator, IIdGenerator idGenerator, IContentTypeProvider contentTypeRepository, IContentSerializer contentSerializer) { DocumentCreator = documentCreator; IdGenerator = idGenerator; ContentTypeRepository = contentTypeRepository; ContentSerializer = contentSerializer; }
public ContentSerializerFactory() { Serializers = new Dictionary <string, IContentSerializer>(); DefaultSerializer = new JsonNetSerializer(); RegisterContentSerializer(DefaultSerializer); RegisterContentSerializer(new JavaBinSerializer()); }
public ContentUpdater(IDocumentUpdater documentUpdater, IContentTypeProvider contentTypeRepository, ISaveListenerProvider saveListenerProvider, IContentSerializer contentSerializer) { DocumentUpdater = documentUpdater; ContentTypeRepository = contentTypeRepository; SaveListenerProvider = saveListenerProvider; ContentSerializer = contentSerializer; }
public void ToXmlStringWithSettingsReturnsCorrectResult( TestXmlWritable writable, IContentSerializer dummySerializer) { var settings = new XmlWriterSettings { OmitXmlDeclaration = true }; var actual = writable.ToXmlString(dummySerializer, settings); var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb, settings)) { writable.WriteTo(w); w.Flush(); } var expected = XDocument.Parse(sb.ToString()); Assert.Equal( expected, XDocument.Parse(actual), new XNodeEqualityComparer()); Assert.False( actual.StartsWith("<?"), "XML declaration not expected due to XmlWriterSettings"); }
public UserApi( IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) : base(baseAddress, httpFacade, contentSerializer, baseHeaders, "user") { }
public void SutCanRoundTripToString( AtomAuthor expected, IContentSerializer dummySerializer) { var xml = expected.ToXmlString(dummySerializer); AtomAuthor actual = AtomAuthor.Parse(xml); Assert.Equal(expected, actual); }
public SystemApi( IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) : base(baseAddress, httpFacade, contentSerializer, baseHeaders, "system") { }
/// <summary> /// Initializes a new instance of the <see cref="MethodReplacer"/> class. /// </summary> /// <param name="httpClientFactory">Http client factory that will use for <see cref="HttpClient"/> building.</param> /// <param name="contentSerializer"><see cref="IContentSerializer"/> that will be used for http content serialization.</param> /// <param name="httpClient">Http client.</param> public MethodReplacer( IHttpClientFactory httpClientFactory, IContentSerializer contentSerializer, IHttpClient?httpClient = null) { _mockExpressionBuilder = new MockExpressionBuilder(); _httpClientExpressionBuilder = new HttpClientExpressionBuilder(httpClientFactory, contentSerializer, httpClient); }
public SystemApi( IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) : base(baseAddress, httpFacade, contentSerializer, baseHeaders, "system") { }
public UserApi( IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders) : base(baseAddress, httpFacade, contentSerializer, baseHeaders, "user") { }
public EmailApi( IHttpAddress baseAddress, IHttpFacade httpFacade, IContentSerializer contentSerializer, HttpHeaders baseHeaders, string serviceName) : base(baseAddress, httpFacade, contentSerializer, baseHeaders, serviceName) { }
/// <summary> /// Registers a serializer with this AssetSerializer. /// </summary> /// <param name="serializer">The serializer.</param> public void RegisterSerializer(IContentSerializer serializer) { lock (contentSerializers) { var serializers1 = GetSerializers(serializer.SerializationType); var serializers2 = GetSerializers(serializer.ActualType); serializers1.Insert(0, serializer); serializers2.Insert(0, serializer); } }
public WebApiClientSettings(string serviceUrl, ClientOptions options = ClientOptions.Default, IContentSerializer serializer = null, IClientErrorHandler errorHandler = null, Type badRequestContentType = null, Type serverErrorContentType = null) { Util.Check(!string.IsNullOrWhiteSpace(serviceUrl), "ServiceUrl may not be empty."); if (serviceUrl.EndsWith("/")) serviceUrl = serviceUrl.Substring(0, serviceUrl.Length - 1); ServiceUrl = serviceUrl; Options = options; Serializer = serializer ?? new JsonContentSerializer(options); ErrorHandler = errorHandler ?? new DefaultClientErrorHandler(Serializer, badRequestContentType, serverErrorContentType); }
public void ReadFromReturnsCorrectResult( AtomAuthor expected, IContentSerializer dummySerializer) { using (var sr = new StringReader(expected.ToXmlString(dummySerializer))) using (var r = XmlReader.Create(sr)) { AtomAuthor actual = AtomAuthor.ReadFrom(r); Assert.Equal(expected, actual); } }
/// <summary> /// Throws DreamFactoryException on bad HTTP status code. /// </summary> /// <param name="response"><see cref="IHttpResponse"/> instance.</param> /// <param name="serializer">Serializer instance.</param> public static void ThrowOnBadStatus(IHttpResponse response, IContentSerializer serializer) { if (response == null) { throw new ArgumentNullException("response"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } if (response.Code >= 200 && response.Code < 300) { return; } string message; switch (response.Code) { case 400: message = "400: Bad Request - Request does not have a valid format, all required parameters, etc."; break; case 401: message = "401 - The login information did not match any records on the backend."; break; case 403: message = "403 - CORS has not been enabled and you’re trying to use the API cross-domain."; break; case 404: message = "404 - The requested DSP is not found."; break; case 500: message = "500 - Internal server error"; break; default: message = string.Format("Got HTTP error: {0}", response.Code); break; } message = TryGetErrorMessage(response, serializer, message); DreamFactoryException exception = new DreamFactoryException(message); exception.Data.Add("Method", response.Request.Method); exception.Data.Add("URL", response.Request.Url); throw exception; }
internal static string AsSerializedString( this IXmlAttributedTestEvent @event, IContentSerializer serializer) { var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb)) { serializer.Serialize(w, @event); w.Flush(); } return sb.ToString(); }
public TestDataHttpFacade(string suffix = null) { this.suffix = suffix; serializer = new JsonContentSerializer(); Uri location = new Uri(Assembly.GetExecutingAssembly().CodeBase); testDataPath = Path.GetDirectoryName(location.AbsolutePath) ?? Environment.CurrentDirectory; testDataPath = Path.Combine(testDataPath, "TestData"); if (!Directory.Exists(testDataPath)) { Assert.Fail("TestData directory does not exist, please check the solution"); } }
internal static object RoundTrip( this IXmlAttributedTestEvent @event, IContentSerializer serializer) { using (var ms = new MemoryStream()) using (var w = XmlWriter.Create(ms)) { serializer.Serialize(w, @event); w.Flush(); ms.Position = 0; using (var r = XmlReader.Create(ms)) return serializer.Deserialize(r).Item; } }
/// <summary> /// Converts an <see cref="IXmlWritable" /> to an XML string. /// </summary> /// <param name="xmlWritable"> /// The object that can be converted to XML. /// </param> /// <param name="serializer"> /// A serializer that can serialize custom content, in case the object /// contains custom content. /// </param> /// <param name="settings"> /// Settings that control how the XML is formatted. /// </param> /// <returns> /// A string of characters containing XML corresponding to the data in /// the object. /// </returns> public static string ToXmlString( this IXmlWritable xmlWritable, IContentSerializer serializer, XmlWriterSettings settings) { if (xmlWritable == null) throw new ArgumentNullException("xmlWritable"); var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb, settings)) { xmlWritable.WriteTo(w, serializer); w.Flush(); return sb.ToString(); } }
public void CreateNewFeedReturnsCorrectResult( Guid id, IContentSerializer dummySerializer) { var href = new Uri(id.ToString(), UriKind.Relative); var before = DateTimeOffset.Now; XmlReader actual = AtomEventStorage.CreateNewFeed(href); var actualFeed = AtomFeed.ReadFrom(actual, dummySerializer); Assert.Equal<Guid>(id, actualFeed.Id); Assert.True(before <= actualFeed.Updated); Assert.True(actualFeed.Updated <= DateTimeOffset.Now); Assert.Empty(actualFeed.Entries); Assert.Contains(AtomLink.CreateSelfLink(href), actualFeed.Links); }
public void RegisterContentSerializer(IContentSerializer serializer) { if (serializer == null) throw new ArgumentNullException("serializer"); if (Serializers.ContainsKey(serializer.ContentType)) throw new MizoreSerializationException("Serializer for Content-Type " + serializer.ContentType + " is already registered", serializer); Serializers[serializer.ContentType] = serializer; if (!serializer.Aliases.IsNullOrEmpty()) { foreach (var alias in serializer.Aliases) { if (Serializers.ContainsKey(alias)) throw new MizoreSerializationException("Serializer for alias Content-Type " + serializer.ContentType + " is already registered", serializer); Serializers[alias] = serializer; } } }
public void ParseThrowsOnWrongContainingElement( string startElement, string endElement, IContentSerializer dummySerializer) { var xml = startElement + " <test-event-x xmlns=\"urn:grean:atom-event-store:unit-tests\">" + " <number>42</number>" + " <text>Foo</text>" + " </test-event-x>" + endElement; Assert.Throws<ArgumentException>( () => XmlAtomContent.Parse( xml, dummySerializer)); }
public void ToXmlStringReturnsCorrectResult( TestXmlWritable writable, IContentSerializer dummySerializer) { var actual = writable.ToXmlString(dummySerializer); var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb)) { writable.WriteTo(w); w.Flush(); } var expected = XDocument.Parse(sb.ToString()); Assert.Equal( expected, XDocument.Parse(actual), new XNodeEqualityComparer()); }
/// <summary> /// Creates an <see cref="XmlAtomContent" /> instance from XML. /// </summary> /// <param name="xmlReader"> /// The <see cref="XmlReader" /> containing the XML representation of /// the Atom Content element. /// </param> /// <param name="serializer"> /// The <see cref="IContentSerializer" /> used to deserialize the XML /// into an instance of the correct object type. /// </param> /// <returns> /// A new instance <see cref="XmlAtomContent" /> containing the data /// from the XML representation of the Atom Content element contained /// in <paramref name="xmlReader" />. /// </returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="xmlReader" /> /// or /// <paramref name="serializer" /> is <see langword="null" />. /// </exception> public static XmlAtomContent ReadFrom( XmlReader xmlReader, IContentSerializer serializer) { if (xmlReader == null) throw new ArgumentNullException("xmlReader"); if (serializer == null) throw new ArgumentNullException("serializer"); GuardContentElement(xmlReader); xmlReader.Read(); return serializer.Deserialize(xmlReader); }
public TestSettings OverrideContentSerializer(IContentSerializer serializer) { _contentSerializer = serializer; return this; }
public DefaultClientErrorHandler(IContentSerializer serializer, Type badRequestContentType = null, Type serverErrorContentType = null) { Serializer = serializer; BadRequestContentType = badRequestContentType ?? typeof(List<ClientFault>); ServerErrorContentType = serverErrorContentType ?? typeof(string); }
/// <summary> /// Writes an <see cref="AtomLink"/>the object to XML using the /// supplied <see cref="XmlWriter" /> and /// <see cref="IContentSerializer" />. /// </summary> /// <param name="xmlWriter"> /// The <see cref="XmlWriter" /> with which the object should be /// written. /// </param> /// <param name="serializer"> /// The <see cref="IContentSerializer" /> to use to serialize any /// custom content. Ignore in this implementation. /// </param> /// <remarks> /// <para> /// <paramref name="serializer" /> is ignore in this implementation, /// because <see cref="AtomLink" /> has no custom content. /// </para> /// </remarks> public void WriteTo(XmlWriter xmlWriter, IContentSerializer serializer) { this.WriteTo(xmlWriter); }
/// <summary> /// Converts an <see cref="IXmlWritable" /> to an XML string. /// </summary> /// <param name="xmlWritable"> /// The object that can be converted to XML. /// </param> /// <param name="serializer"> /// A serializer that can serialize custom content, in case the object /// contains custom content. /// </param> /// <returns> /// A string of characters containing XML corresponding to the data in /// the object. /// </returns> /// <seealso cref="ToXmlString(IXmlWritable, IContentSerializer, XmlWriterSettings)" /> public static string ToXmlString( this IXmlWritable xmlWritable, IContentSerializer serializer) { return xmlWritable.ToXmlString(serializer, new XmlWriterSettings()); }
public void ReadNonPersistedFeedReturnsCorrectFeed( AtomEventsInMemory sut, UuidIri id, IContentSerializer dummySerializer) { var expectedSelfLink = AtomLink.CreateSelfLink( new Uri( ((Guid)id).ToString(), UriKind.Relative)); var before = DateTimeOffset.Now; using (var r = sut.CreateFeedReaderFor(expectedSelfLink.Href)) { var actual = AtomFeed.ReadFrom(r, dummySerializer); Assert.Equal(id, actual.Id); Assert.Equal("Index of event stream " + (Guid)id, actual.Title); Assert.True(before <= actual.Updated, "Updated should be very recent."); Assert.True(actual.Updated <= DateTimeOffset.Now, "Updated should not be in the future."); Assert.Empty(actual.Entries); Assert.Contains( expectedSelfLink, actual.Links); } }
/// <summary> /// Writes the object to XML using the supplied /// <see cref="XmlWriter" /> and <see cref="IContentSerializer" />. /// </summary> /// <param name="xmlWriter"> /// The <see cref="XmlWriter" /> with which the object should be /// written. /// </param> /// <param name="serializer"> /// The <see cref="IContentSerializer" /> to use to serialize any /// custom content. /// </param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="xmlWriter" /> /// or /// <paramref name="serializer" /> is <see langword="null" />. /// </exception> public void WriteTo(XmlWriter xmlWriter, IContentSerializer serializer) { if (xmlWriter == null) throw new ArgumentNullException("xmlWriter"); if (serializer == null) throw new ArgumentNullException("serializer"); xmlWriter.WriteStartElement("content", "http://www.w3.org/2005/Atom"); xmlWriter.WriteAttributeString("type", "application/xml"); serializer.Serialize(xmlWriter, this.item); xmlWriter.WriteEndElement(); }
/// <summary> /// Parses the supplied XML into an instance of /// <see cref="XmlAtomContent" />. /// </summary> /// <param name="xml"> /// A string of characters containing the XML representation of an Atom /// Content element. /// </param> /// <param name="serializer"> /// The <see cref="IContentSerializer" /> used to deserialize the XML /// into an instance of the correct object type. /// </param> /// <returns> /// A new instance of <see cref="XmlAtomContent" /> containing the data /// from the supplied <paramref name="xml" />. /// </returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="serializer" /> is <see langword="null" />. /// </exception> public static XmlAtomContent Parse( string xml, IContentSerializer serializer) { if (serializer == null) throw new ArgumentNullException("serializer"); var sr = new StringReader(xml); try { using (var r = XmlReader.Create(sr)) { sr = null; return XmlAtomContent.ReadFrom(r, serializer); } } finally { if (sr != null) sr.Dispose(); } }
public MizoreSerializationException(string message, IContentSerializer serializer, Exception innerException = null) : base(message, innerException) { Serializer = serializer; }