public void Equals_OnSameValues_ReturnsTrue(string category, string name, string version) { var identity1 = new ContentFormat(category, name, version, 1, "mime", string.Empty); var identity2 = new ContentFormat(category, name, version, 1, "mime", string.Empty); Assert.That(identity1.Equals(identity2), Is.True); }
public void ToString_VariousPatterns_ReturnsCorrectResult(string category, string name, string version, string expected) { var format = new ContentFormat(category, name, version, 1, "mime", string.Empty); string output = format.ToString(); Assert.That(output, Is.EqualTo(expected)); }
/// <inheritdoc /> public Response Put <TContent>( string resource, TContent content = default, ContentFormat contentFormat = ContentFormat.Json) where TContent : class { return(AsyncHelper.RunSync(() => PutAsync(resource, content, contentFormat))); }
/// <inheritdoc /> public Response <TResult> Post <TContent, TResult>( string resource = null, TContent content = default, ContentFormat contentFormat = ContentFormat.Json) where TContent : class { return(AsyncHelper.RunSync(() => PostAsync <TContent, TResult>(resource, content, contentFormat))); }
private async Task DownloadPipelineCacheAsync( AgentTaskPluginExecutionContext context, DedupManifestArtifactClient dedupManifestClient, DedupIdentifier manifestId, string targetDirectory, ContentFormat contentFormat, CancellationToken cancellationToken) { if (contentFormat == ContentFormat.SingleTar) { string manifestPath = Path.Combine(Path.GetTempPath(), $"{nameof(DedupManifestArtifactClient)}.{Path.GetRandomFileName()}.manifest"); await dedupManifestClient.DownloadFileToPathAsync(manifestId, manifestPath, proxyUri : null, cancellationToken : cancellationToken); Manifest manifest = JsonSerializer.Deserialize <Manifest>(File.ReadAllText(manifestPath)); await TarUtils.DownloadAndExtractTarAsync(context, manifest, dedupManifestClient, targetDirectory, cancellationToken); try { if (File.Exists(manifestPath)) { File.Delete(manifestPath); } } catch {} } else { DownloadDedupManifestArtifactOptions options = DownloadDedupManifestArtifactOptions.CreateWithManifestId( manifestId, targetDirectory, proxyUri: null, minimatchPatterns: null); await dedupManifestClient.DownloadAsync(options, cancellationToken); } }
private async Task DownloadPipelineCacheAsync( AgentTaskPluginExecutionContext context, DedupManifestArtifactClient dedupManifestClient, DedupIdentifier manifestId, string[] pathSegments, string workspaceRoot, ContentFormat contentFormat, CancellationToken cancellationToken) { if (contentFormat == ContentFormat.SingleTar) { string manifestPath = Path.Combine(Path.GetTempPath(), $"{nameof(DedupManifestArtifactClient)}.{Path.GetRandomFileName()}.manifest"); await AsyncHttpRetryHelper.InvokeVoidAsync( async() => { await dedupManifestClient.DownloadFileToPathAsync(manifestId, manifestPath, proxyUri: null, cancellationToken: cancellationToken); }, maxRetries : 3, tracer : tracer, canRetryDelegate : e => true, context : nameof(DownloadPipelineCacheAsync), cancellationToken : cancellationToken, continueOnCapturedContext : false); Manifest manifest = JsonSerializer.Deserialize <Manifest>(File.ReadAllText(manifestPath)); var(tarWorkingDirectory, _) = GetTarWorkingDirectory(pathSegments, workspaceRoot); await TarUtils.DownloadAndExtractTarAsync(context, manifest, dedupManifestClient, tarWorkingDirectory, cancellationToken); try { if (File.Exists(manifestPath)) { File.Delete(manifestPath); } } catch { } } else { DownloadDedupManifestArtifactOptions options = DownloadDedupManifestArtifactOptions.CreateWithManifestId( manifestId, pathSegments[0], proxyUri: null, minimatchPatterns: null); await AsyncHttpRetryHelper.InvokeVoidAsync( async() => { await dedupManifestClient.DownloadAsync(options, cancellationToken); }, maxRetries : 3, tracer : tracer, canRetryDelegate : e => true, context : nameof(DownloadPipelineCacheAsync), cancellationToken : cancellationToken, continueOnCapturedContext : false); } }
public GenericHandler(string contentType, RequestAttributes handlerAttributes, Feature format) { this.HandlerContentType = contentType; this.ContentTypeAttribute = ContentFormat.GetEndpointAttributes(contentType); this.HandlerAttributes = handlerAttributes; this.format = format; this.appHost = HostContext.AppHost; }
public Content(string name, ContentFormat format, Repository repository) { Id = Guid.NewGuid(); Name = name; Repository = repository; ContentFormat = format; Versions = new List <ContentVersion>(); }
public override object GetResponse(IRequest request, object requestDto) { var requestContentType = ContentFormat.GetEndpointAttributes(request.ResponseContentType); request.RequestAttributes |= HandlerAttributes | requestContentType; return(ExecuteService(requestDto, request)); }
public string SerializeToString(IRequest requestContext, object response) { var contentType = requestContext.ResponseContentType; StreamSerializerDelegate responseStreamWriter; if (this.ContentTypeSerializers.TryGetValue(contentType, out responseStreamWriter) || this.ContentTypeSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseStreamWriter)) { using (var ms = new MemoryStream()) { responseStreamWriter(requestContext, response, ms); ms.Position = 0; var result = new StreamReader(ms, UTF8EncodingWithoutBom).ReadToEnd(); return(result); } } ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseWriter)) { using (var ms = new MemoryStream()) { var httpRes = new HttpResponseStreamWrapper(ms) { KeepOpen = true, //Don't let view engines close the OutputStream }; responseWriter(requestContext, response, httpRes); var bytes = ms.ToArray(); var result = bytes.FromUtf8Bytes(); httpRes.ForceClose(); //Manually close the OutputStream return(result); } } var contentTypeAttr = ContentFormat.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case RequestAttributes.Xml: return(XmlSerializer.SerializeToString(response)); case RequestAttributes.Json: return(JsonDataContractSerializer.Instance.SerializeToString(response)); case RequestAttributes.Jsv: return(TypeSerializer.SerializeToString(response)); } throw new NotSupportedException("ContentType not supported: " + contentType); }
public IClientSettingsBuilder DefaultToFormat(ContentFormat format) { if (format == ContentFormat.Default) { throw new ArgumentException("Invalid default format"); } defaultFormat = format; return(this); }
private async Task <string> GetUploadPathAsync(ContentFormat contentFormat, AgentTaskPluginExecutionContext context, string path, CancellationToken cancellationToken) { string uploadPath = path; if (contentFormat == ContentFormat.SingleTar) { uploadPath = await TarUtils.ArchiveFilesToTarAsync(context, path, cancellationToken); } return(uploadPath); }
public byte[] SerializeToBytes(IRequest req, object response) { var contentType = req.ResponseContentType; StreamSerializerDelegate responseStreamWriter; if (this.ContentTypeSerializers.TryGetValue(contentType, out responseStreamWriter) || this.ContentTypeSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseStreamWriter)) { using (var ms = MemoryStreamFactory.GetStream()) { responseStreamWriter(req, response, ms); ms.Position = 0; return(ms.ToArray()); } } ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseWriter)) { using (var ms = MemoryStreamFactory.GetStream()) { var httpRes = new HttpResponseStreamWrapper(ms, req); responseWriter(req, response, httpRes); ms.Position = 0; return(ms.ToArray()); } } var contentTypeAttr = ContentFormat.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case RequestAttributes.Xml: return(XmlSerializer.SerializeToString(response).ToUtf8Bytes()); case RequestAttributes.Json: return(JsonDataContractSerializer.Instance.SerializeToString(response).ToUtf8Bytes()); case RequestAttributes.Jsv: return(TypeSerializer.SerializeToString(response).ToUtf8Bytes()); #if !NETSTANDARD1_6 case RequestAttributes.Soap11: return(SoapHandler.SerializeSoap11ToBytes(req, response)); case RequestAttributes.Soap12: return(SoapHandler.SerializeSoap12ToBytes(req, response)); #endif } throw new NotSupportedException("ContentType not supported: " + contentType); }
public string SerializeToString(IRequest req, object response) { var contentType = req.ResponseContentType; if (this.ContentTypeSerializers.TryGetValue(contentType, out var responseStreamWriter) || this.ContentTypeSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseStreamWriter)) { using (var ms = MemoryStreamFactory.GetStream()) { responseStreamWriter(req, response, ms); ms.Position = 0; var result = new StreamReader(ms, UTF8EncodingWithoutBom).ReadToEnd(); return(result); } } if (this.ContentTypeSerializersAsync.TryGetValue(contentType, out var responseWriter) || this.ContentTypeSerializersAsync.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseWriter)) { using (var ms = MemoryStreamFactory.GetStream()) { responseWriter(req, response, ms).Wait(); var bytes = ms.ToArray(); var result = bytes.FromUtf8Bytes(); return(result); } } var contentTypeAttr = ContentFormat.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case RequestAttributes.Xml: return(XmlSerializer.SerializeToString(response)); case RequestAttributes.Json: return(JsonDataContractSerializer.Instance.SerializeToString(response)); case RequestAttributes.Jsv: return(TypeSerializer.SerializeToString(response)); #if !NETSTANDARD1_6 case RequestAttributes.Soap11: return(SoapHandler.SerializeSoap11ToBytes(req, response).FromUtf8Bytes()); case RequestAttributes.Soap12: return(SoapHandler.SerializeSoap12ToBytes(req, response).FromUtf8Bytes()); #endif } throw new NotSupportedException("ContentType not supported: " + contentType); }
public static async Task <T> GetAsync <T>(string requestUri, List <KeyValuePair <string, string> > headers, ContentFormat responseContentFormat = ContentFormat.Type) { var builder = new HttpRequestBuilder() .AddMethod(HttpMethod.Get) .AddRequestUri(requestUri) .AddHeaders(headers); var response = await builder.SendAsync(); return(response.FormatContent <T>(responseContentFormat)); }
public async Task <Content> Handle(CreateContentCommand request, CancellationToken cancellationToken) { var content = new Content(request.File.Name, ContentFormat.From(request.File.Extension), request.Repository); var contentVersion = content.AddContentVersion(request.AuthorId, true); await _contentRepository.MergeContent(content); // Upload to blob storage --> See async solution for this in Seismic.Clean.Application.Contents.EventHandlers await _blobStorageService.UploadFile(request.File, contentVersion.BlobId); return(content); }
public void Render(HtmlTextWriter output) { var renderedTemplate = string.Format(HtmlTemplates.OperationControlTemplate, Title, HttpRequest.GetParentAbsolutePath().ToParentPath() + MetadataConfig.DefaultMetadataUri, ContentFormat.ToUpper(), OperationName, HttpRequestTemplate, ResponseTemplate, MetadataHtml); output.Write(renderedTemplate); }
/// <summary> /// Gửi Bản tin đăng bài cá nhân lên Server /// </summary> public async void SendContentPost() { // Kiểm tra xem có homepageInfo chưa? if (Services.Service.Instiance().NewsSiteVM.homePageInfo == null) { UserDialogs.Instance.Toast("Không xác định được trang cá nhân"); return; } var idhome = Services.Service.Instiance().NewsSiteVM.homePageInfo.homePageId; bool isPost = true; account = Helper.Instance().MyAccount; //thêm nội dung cho content var list = new List <string>(); // Lấy ảnh của bài đăng if (images.Count > 0) { isPost = await postMuiltiImage(); } QHVector Image_Id = new QHVector(); var imagesID = new List <long>(); if (!isPost) { for (int i = 0; i < images.Count; i++) { list.Add(images[i].UriImage); Image_Id.SetAt(i, new QHNumber(images[i].Image_Id)); imagesID.Add(images[i].Image_Id); } } QHMessage msg = new QHMessage((ushort)PingPongMsg.MSG_HOMEPAGE_ADD_CONTENT_REQ); json = new ContentFormat { Text = personalPost.content, Images_Id = list }; string output = JsonConvert.SerializeObject(json); //kiểm tra account if (Helper.Instance().CheckLogin()) { account = Helper.Instance().MyAccount; msg.SetAt((byte)MsgHomePageAddContentReq.SenderID, new QHNumber(account.Number_Id)); msg.SetAt((byte)MsgHomePageAddContentReq.HomePageID, new QHNumber(Services.Service.Instiance().NewsSiteVM.homePageInfo.homePageId)); msg.SetAt((byte)MsgHomePageAddContentReq.Content, new QHString(output)); msg.SetAt((byte)MsgHomePageAddContentReq.ImagesID, Image_Id); Services.Service.Instiance().SendMessage(msg); Debug.WriteLine("MSG_HOMEPAGE_ADD_CONTENT_REQ: " + msg.JSONString()); } }
//ToDo: Ne döndürecek Reponse da bir bilgi yok public ExecuteResult Report(Guid id, ReportType type, ReportFormat format, ContentFormat contentFormat = ContentFormat.Html) { return(_webRequest.CreateRequestWithQueryString(ApiResource.Scans.REPORT, new { Id = id, Type = type, Format = format, ContentFormat = contentFormat }) .ByteArrayResponseHandler() .Execute() .Get()); }
public virtual void Render(HtmlTextWriter output) { var baseUrl = HttpRequest.GetBaseUrl(); var renderedTemplate = HtmlTemplates.Format(HtmlTemplates.GetOperationControlTemplate(), Title, baseUrl.AppendPath(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, GetHttpRequestTemplate(), ResponseTemplate, MetadataHtml); output.Write(renderedTemplate); }
/// <summary> /// Get the latest crawl run results in desired format. /// </summary> /// <param name="extractorID">Unique identifier of your extractor.</param> /// <param name="format">Specifies returned format.</param> /// <returns></returns> public async Task <string> GetLatestRunResultAsync(string extractorID, ContentFormat format = ContentFormat.JSON) { if (string.IsNullOrEmpty(extractorID)) { throw new ArgumentException("Extractor ID cannot be empty"); } return(await _client.GetRawDataAsync(new[] { new Field("extractor"), new Field(extractorID), new Field(format.ToString().ToLower()), new Field("latest") })); }
public virtual void Render(HtmlTextWriter output) { string baseUrl = HttpRequest.ResolveAbsoluteUrl("~/"); var renderedTemplate = HtmlTemplates.Format(HtmlTemplates.GetOperationControlTemplate(), Title, baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, HttpRequestTemplate, ResponseTemplate, MetadataHtml); output.Write(renderedTemplate); }
public virtual Task RenderAsync(Stream output) { var baseUrl = HttpRequest.ResolveAbsoluteUrl("~/"); var renderedTemplate = Templates.HtmlTemplates.Format(Templates.HtmlTemplates.GetOperationControlTemplate(), Title, baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, GetHttpRequestTemplate(), ResponseTemplate, MetadataHtml); return(output.WriteAsync(renderedTemplate)); }
public override async Task ProcessRequestAsync(IRequest httpReq, IResponse httpRes, string operationName) { try { var restPath = httpReq.GetRoute(); if (restPath == null) throw new NotSupportedException("No RestPath found for: " + httpReq.Verb + " " + httpReq.PathInfo); httpReq.OperationName = operationName = restPath.RequestType.GetOperationName(); if (appHost.ApplyPreRequestFilters(httpReq, httpRes)) return; appHost.AssertContentType(httpReq.ResponseContentType); var request = httpReq.Dto = await CreateRequestAsync(httpReq, restPath); await appHost.ApplyRequestFiltersAsync(httpReq, httpRes, request); if (httpRes.IsClosed) return; var requestContentType = ContentFormat.GetEndpointAttributes(httpReq.ResponseContentType); httpReq.RequestAttributes |= HandlerAttributes | requestContentType; var rawResponse = await GetResponseAsync(httpReq, request); if (httpRes.IsClosed) return; await HandleResponse(httpReq, httpRes, rawResponse); } //sync with GenericHandler catch (TaskCanceledException) { httpRes.StatusCode = (int)HttpStatusCode.PartialContent; httpRes.EndRequest(); } catch (Exception ex) { if (!appHost.Config.WriteErrorsToResponse) { await appHost.ApplyResponseConvertersAsync(httpReq, ex); httpRes.EndRequest(); } else { await HandleException(httpReq, httpRes, operationName, await appHost.ApplyResponseConvertersAsync(httpReq, ex) as Exception ?? ex); } } }
public void RegisterAsync(string contentType, StreamSerializerDelegateAsync streamSerializer, StreamDeserializerDelegateAsync streamDeserializer) { if (contentType.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(contentType)); } var format = ContentFormat.GetContentFormat(contentType); var normalizedContentType = ContentFormat.NormalizeContentType(contentType); ContentTypeFormats[format] = normalizedContentType; ContentTypeSerializersAsync[normalizedContentType] = streamSerializer; ContentTypeDeserializersAsync[normalizedContentType] = streamDeserializer; }
public void Register(string contentType, StreamSerializerDelegate streamSerializer, StreamDeserializerDelegate streamDeserializer) { if (contentType.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(contentType)); } var format = contentType.LastRightPart('/'); var normalizedContentType = ContentFormat.NormalizeContentType(contentType); ContentTypeFormats[format] = normalizedContentType; SetContentTypeSerializer(normalizedContentType, streamSerializer); SetContentTypeDeserializer(normalizedContentType, streamDeserializer); }
private Task <string> GetUploadPathAsync(ContentFormat contentFormat, AgentTaskPluginExecutionContext context, Fingerprint pathFingerprint, string[] pathSegments, string workspaceRoot, CancellationToken cancellationToken) { if (contentFormat == ContentFormat.SingleTar) { var(tarWorkingDirectory, isWorkspaceContained) = GetTarWorkingDirectory(pathSegments, workspaceRoot); return(TarUtils.ArchiveFilesToTarAsync( context, pathFingerprint, tarWorkingDirectory, isWorkspaceContained, cancellationToken )); } return(Task.FromResult(pathFingerprint.Segments[0])); }
public StreamDeserializerDelegateAsync GetStreamDeserializerAsync(string contentType) { contentType = ContentFormat.NormalizeContentType(contentType); if (ContentTypeDeserializersAsync.TryGetValue(contentType, out var deserializerAsync)) { return(deserializerAsync); } var deserializer = GetStreamDeserializer(contentType); if (deserializer == null) { return(null); } return((type, stream) => Task.FromResult(deserializer(type, stream))); }
public object DeserializeFromString(string contentType, Type type, string request) { var contentTypeAttr = ContentFormat.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case RequestAttributes.Xml: return(XmlSerializer.DeserializeFromString(request, type)); case RequestAttributes.Json: return(JsonDataContractSerializer.Instance.DeserializeFromString(request, type)); case RequestAttributes.Jsv: return(TypeSerializer.DeserializeFromString(request, type)); default: throw new NotSupportedException("ContentType not supported: " + contentType); } }
public ResponseSerializerDelegate GetResponseSerializer(string contentType) { ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentFormat.GetRealContentType(contentType), out responseWriter)) { return(responseWriter); } var serializer = GetStreamSerializer(contentType); if (serializer == null) { return(null); } return((httpReq, dto, httpRes) => serializer(httpReq, dto, httpRes.OutputStream)); }
/// <summary>Initializes a new <see cref="ResponseBodyWriter"/> that can write the body of a response.</summary> /// <param name="encoding">Encoding, if available.</param> /// <param name="hasMoved">Whether <paramref name="queryResults"/> has already moved.</param> /// <param name="service">Service for the request being processed.</param> /// <param name="queryResults">Enumerator for results.</param> /// <param name="requestDescription">Description of request made to the system.</param> /// <param name="responseFormat">Content format for response.</param> internal ResponseBodyWriter( Encoding encoding, bool hasMoved, IDataService service, IEnumerator queryResults, RequestDescription requestDescription, ContentFormat responseFormat) { Debug.Assert(responseFormat != ContentFormat.Unknown, "responseFormat != ContentFormat.Unknown"); this.encoding = encoding; this.hasMoved = hasMoved; this.service = service; this.queryResults = queryResults; this.requestDescription = requestDescription; this.responseFormat = responseFormat; if (this.requestDescription.TargetKind == RequestTargetKind.MediaResource) { // Note that GetReadStream will set the ResponseETag before it returns this.mediaResourceStream = service.StreamProvider.GetReadStream(this.queryResults.Current, this.service.OperationContext); } }
/// <summary> /// Modify the value of the given resource to the given value /// </summary> /// <param name="description">description about the request</param> /// <param name="resourceToBeModified">resource that needs to be modified</param> /// <param name="requestValue">the new value for the target resource</param> /// <param name="contentFormat">specifies the content format of the payload</param> /// <param name="service">Service this request is against</param> internal static void ModifyResource(RequestDescription description, object resourceToBeModified, object requestValue, ContentFormat contentFormat, IDataService service) { if (description.TargetKind == RequestTargetKind.OpenProperty || description.TargetKind == RequestTargetKind.OpenPropertyValue) { Debug.Assert(!description.LastSegmentInfo.HasKeyValues, "CreateSegments must have caught the problem already."); SetOpenPropertyValue(resourceToBeModified, description.ContainerName, requestValue, service); } else if (description.TargetKind == RequestTargetKind.MediaResource) { SetStreamPropertyValue(resourceToBeModified, (Stream)requestValue, service, description); } else { Debug.Assert( description.TargetKind == RequestTargetKind.Primitive || description.TargetKind == RequestTargetKind.ComplexObject || description.TargetKind == RequestTargetKind.PrimitiveValue, "unexpected target kind encountered"); // update the primitive value ResourceProperty propertyToUpdate = description.LastSegmentInfo.ProjectedProperty; SetPropertyValue(propertyToUpdate, resourceToBeModified, requestValue, contentFormat, service); } }
private void writeContentType(String filePath, Alfresco.RepositoryWebService.Reference rwsRef, String property, String mimetype) { Alfresco.ContentWebService.Reference newContentNode = new Alfresco.ContentWebService.Reference(); newContentNode.path = rwsRef.path; newContentNode.uuid = rwsRef.uuid; Alfresco.ContentWebService.Store cwsStore = new Alfresco.ContentWebService.Store(); cwsStore.address = "SpacesStore"; spacesStore.scheme = Alfresco.RepositoryWebService.StoreEnum.workspace; newContentNode.store = cwsStore; // Open the file and convert to byte array FileStream inputStream = new FileStream(filePath, FileMode.Open); int bufferSize = (int)inputStream.Length; byte[] bytes = new byte[bufferSize]; inputStream.Read(bytes, 0, bufferSize); inputStream.Close(); ContentFormat contentFormat = new ContentFormat(); contentFormat.mimetype = mimetype; WebServiceFactory.getContentService().write(newContentNode, property, bytes, contentFormat); }
/// <summary> /// Converts the given value to the expected type as per the deserializer rules /// </summary> /// <param name="value">value to the converted</param> /// <param name="property">property information whose value is the first parameter</param> /// <param name="contentFormat">specifies the content format of the payload</param> /// <param name="provider">underlying data service provider.</param> /// <returns>object which is in [....] with the properties type</returns> internal static object ConvertValues(object value, ResourceProperty property, ContentFormat contentFormat, DataServiceProviderWrapper provider) { Debug.Assert(property.TypeKind == ResourceTypeKind.Primitive, "This method must be called for primitive types only"); if (contentFormat == ContentFormat.Json) { return JsonDeserializer.ConvertValues(value, property.Name, property.Type, provider); } else if (contentFormat == ContentFormat.Atom || contentFormat == ContentFormat.PlainXml) { return PlainXmlDeserializer.ConvertValuesForXml(value, property.Name, property.Type); } else { Debug.Assert( contentFormat == ContentFormat.Binary || contentFormat == ContentFormat.Text, "expecting binary or text"); // Do not do any coversions for them return value; } }
public CorpusDocument SetContent(string content, ContentFormat contentFormat) { Content = content; Format = contentFormat; return this; }
public static IOutput CreateOutput(ContentFormat format, ControllerContext context, object content, List<Type> knownTypes = null) { return new JsonOutput(context, content, knownTypes); }
/// <summary> /// Set the value of the given resource property to the new value /// </summary> /// <param name="resourceProperty">property whose value needs to be updated</param> /// <param name="declaringResource">instance of the declaring type of the property for which the property value needs to be updated</param> /// <param name="propertyValue">new value for the property</param> /// <param name="contentFormat">specifies the content format of the payload</param> /// <param name="service">Service this is request is against</param> protected static void SetPropertyValue(ResourceProperty resourceProperty, object declaringResource, object propertyValue, ContentFormat contentFormat, IDataService service) { Debug.Assert( resourceProperty.TypeKind == ResourceTypeKind.ComplexType || resourceProperty.TypeKind == ResourceTypeKind.Primitive, "Only primitive and complex type values must be set via this method"); // For open types, resource property can be null if (resourceProperty.TypeKind == ResourceTypeKind.Primitive) { // Only do the conversion if the provider explicitly asked us to do the configuration. if (service.Configuration.EnableTypeConversion) { // First convert the value of the property to the expected type, as specified in the resource property propertyValue = ConvertValues(propertyValue, resourceProperty, contentFormat, service.Provider); } } service.Updatable.SetValue(declaringResource, resourceProperty.Name, propertyValue); }