public async Task <bool> SetCustomSettingAsync <TEntity>(string settingName, TEntity entity) where TEntity : class, new() { if (settingName == null) { throw new ArgumentNullException("settingName"); } if (entity == null) { throw new ArgumentNullException("entity"); } var address = baseAddress.WithResource(CustomResource); Dictionary <string, TEntity> setting = new Dictionary <string, TEntity> { { settingName, entity } }; string content = contentSerializer.Serialize(setting); IHttpRequest request = new HttpRequest(HttpMethod.Post, address.Build(), baseHeaders, content); IHttpResponse response = await httpFacade.RequestAsync(request); HttpUtils.ThrowOnBadStatus(response, contentSerializer); var success = new { success = false }; return(contentSerializer.Deserialize(response.Body, success).success); }
private static HttpContent SerializeValue(IRestClient client, IRequestParameter body, IContentSerializer serializer) { var s = serializer.Serialize(client, body.Value); var contentTypes = serializer.ContentTypes; return(new StringContent(s, Encoding.UTF8, contentTypes[0])); }
public async Task SaveItemAsync(string url, TItem item) { if (!Uri.IsWellFormedUriString(url, UriKind.Absolute)) { throw new ArgumentException(nameof(url)); } if (item == null) { throw new ArgumentNullException(nameof(item)); } var httpRequestMessage = item.Id == 0 ? new HttpRequestMessage(HttpMethod.Post, url) : new HttpRequestMessage(HttpMethod.Put, url); _contentSerializer.Serialize(httpRequestMessage, item); var response = await _httpService.SendAsync(httpRequestMessage); // while its possible that the server's implementation of validation // could return errors that escaped the client's implementation of validation, // we choose not to decode any error dictionary returned by the server. // We validate on the server to protect against clients that fail to // validate as this class does if (!response.IsSuccessStatusCode) { throw new FailedRequestException(response.StatusCode); } }
private async Task <IWorkflowBlueprint> GetWorkflowBlueprintAsync(WorkflowDefinition workflowDefinition) { var json = _serializer.Serialize(workflowDefinition); var deserializedWorkflowDefinition = _serializer.Deserialize <WorkflowDefinition>(json); return(await _materializer.CreateWorkflowBlueprintAsync(deserializedWorkflowDefinition)); }
private HttpRequestMessage CreateRequest(HttpMethod method, string uri, object body) { return(new HttpRequestMessage(method, uri) { Content = new StringContent(_contentSerializer.Serialize(body)) }); }
private async Task WriteContentAsync(CancellationToken cancellationToken) { var httpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext(); var response = httpContext.Response; var content = Content; if (content == null) { return; } if (content is string stringContent) { if (!string.IsNullOrWhiteSpace(stringContent)) { await response.WriteAsync(stringContent, cancellationToken); } return; } if (content is byte[] buffer) { await response.Body.WriteAsync(buffer, cancellationToken); return; } var json = _contentSerializer.Serialize(content); await response.WriteAsync(json, cancellationToken); }
private EventMessage CreateEventMessage(IntegrationEvent @event) { var msg = new EventMessage(); msg.EventTypeName = @event.GetType().Name; msg.Content = _serializer.Serialize(@event); return(msg); }
private string WriteWorkflowInfoAsync(ActivityExecutionContext context) { var model = new { WorkflowInstanceId = context.WorkflowInstance.Id, WorkflowStatus = context.WorkflowInstance.WorkflowStatus }; return(_contentSerializer.Serialize(model)); }
public async Task <HttpRequestMessage> BuildAsync <T>(HttpMethod method, string url, T item) where T : class { if (item == null) { throw new ArgumentNullException(nameof(item)); } var message = await BuildBaseRequest(method, url); _serializer.Serialize(message, item); return(message); }
private string CreateErrorResponse(int code, string message) { Error errorData = new Error { Code = code, Message = message }; var error = new { error = new List <Error> { errorData } }; return(serializer.Serialize(error)); }
public static ServiceBusMessage CreateMessage(IContentSerializer serializer, object message) { if (message is string s) { return(new ServiceBusMessage(s)); } var json = serializer.Serialize(message); var messageBytes = Encoding.UTF8.GetBytes(json); return(new ServiceBusMessage(messageBytes)); }
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 string Pack(CapMessage obj) { var content = new MessageContent { Id = obj.Id, Content = obj.Content, CallbackName = obj.CallbackName, Timestamp = obj.Timestamp }; return(_serializer.Serialize(content)); }
public async Task <ConfigResponse> SetConfigAsync(ConfigRequest config) { IHttpAddress address = baseAddress.WithResource("config"); string body = contentSerializer.Serialize(config); IHttpRequest request = new HttpRequest(HttpMethod.Get, address.Build(), baseHeaders, body); IHttpResponse response = await httpFacade.RequestAsync(request); HttpUtils.ThrowOnBadStatus(response, contentSerializer); return(contentSerializer.Deserialize <ConfigResponse>(response.Body)); }
internal static string AsSerializedString( this IDataContractTestEvent @event, IContentSerializer serializer) { var sb = new StringBuilder(); using (var w = XmlWriter.Create(sb)) { serializer.Serialize(w, @event); w.Flush(); } return(sb.ToString()); }
internal static object RoundTrip( this IDataContractTestEvent @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); } }
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; } }
public async Task <bool> RegisterAsync(Register register, bool login = false) { if (register == null) { throw new ArgumentNullException("register"); } var address = baseAddress.WithResource("register"); if (login) { address = address.WithParameter("login", true); } string content = contentSerializer.Serialize(register); IHttpRequest request = new HttpRequest(HttpMethod.Post, address.Build(), baseHeaders, content); IHttpResponse response = await httpFacade.RequestAsync(request); HttpUtils.ThrowOnBadStatus(response, contentSerializer); var success = new { success = false }; success = contentSerializer.Deserialize(response.Body, success); if (success.success && login) { Session session = await GetSessionAsync(); baseHeaders.AddOrUpdate(HttpHeaders.DreamFactorySessionTokenHeader, session.session_id); } return(success.success); }
protected override void OnSaving(ElsaContext dbContext, WorkflowDefinition entity) { var data = new { entity.Activities, entity.Connections, entity.Variables, entity.ContextOptions, entity.CustomAttributes }; var json = _contentSerializer.Serialize(data); dbContext.Entry(entity).Property("Data").CurrentValue = json; }
public static Message CreateMessage(IContentSerializer serializer, object message) { byte[] messageBytes; if (message is string s) { messageBytes = Encoding.UTF8.GetBytes(s); } else { var json = serializer.Serialize(message); messageBytes = Encoding.UTF8.GetBytes(json); } return(new Message(messageBytes)); }
public async Task <IActionResult> Handle(string workflowDefinitionId, VersionOptions versionOptions, CancellationToken cancellationToken) { var workflowDefinition = await _workflowDefinitionStore.FindByDefinitionIdAsync(workflowDefinitionId, versionOptions, cancellationToken); if (workflowDefinition == null) { return(NotFound()); } var json = _contentSerializer.Serialize(workflowDefinition); var bytes = Encoding.UTF8.GetBytes(json); var workflowName = workflowDefinition.Name is null or "" ? workflowDefinition.DefinitionId : workflowDefinition.Name.Trim(); var fileName = $"workflow-definition-{workflowName.Underscore().Dasherize().ToLowerInvariant()}.json"; return(File(bytes, "application/json", fileName)); }
public async Task <int> SendEmailAsync(EmailRequest emailRequest) { if (emailRequest == null) { throw new ArgumentNullException("emailRequest"); } string content = contentSerializer.Serialize(emailRequest); IHttpRequest request = new HttpRequest(HttpMethod.Post, baseAddress.Build(), baseHeaders, content); IHttpResponse response = await httpFacade.RequestAsync(request); HttpUtils.ThrowOnBadStatus(response, contentSerializer); var emailsSent = new { count = 0 }; return(contentSerializer.Deserialize(response.Body, emailsSent).count); }
protected override void OnSaving(ElsaContext dbContext, WorkflowInstance entity) { var data = new { entity.Output, entity.Variables, entity.ActivityData, entity.BlockingActivities, entity.ScheduledActivities, entity.Scopes, entity.Fault, entity.CurrentActivity }; var json = _contentSerializer.Serialize(data); dbContext.Entry(entity).Property("Data").CurrentValue = json; }
/// <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(); }
private async Task CreateOrUpdateTableAsync(HttpMethod httpMethod, TableSchema tableSchema) { if (tableSchema == null) { throw new ArgumentNullException("tableSchema"); } IHttpAddress address = baseAddress.WithResource("_schema"); var tableSchemas = new { table = new List <TableSchema> { tableSchema } }; string body = contentSerializer.Serialize(tableSchemas); IHttpRequest request = new HttpRequest(httpMethod, address.Build(), baseHeaders, body); IHttpResponse response = await httpFacade.RequestAsync(request); HttpUtils.ThrowOnBadStatus(response, contentSerializer); }
protected virtual string Serialize <T>(T obj, string callbackName = null) { string content; if (obj != null) { content = Helper.IsComplexType(obj.GetType()) ? _serializer.Serialize(obj) : obj.ToString(); } else { content = string.Empty; } var message = new CapMessageDto(content) { CallbackName = callbackName }; return(_msgPacker.Pack(message)); }
public async Task SendAsync(string messageId, string topicName, object bodyObj) { string body; if (bodyObj != null && Helper.IsComplexType(bodyObj.GetType())) { body = _contentSerializer.Serialize(bodyObj); } else { body = bodyObj?.ToString(); } _logger.LogDebug($"Callback message will publishing, name:{topicName},content:{body}"); var callbackMessage = new CapMessageDto { Id = messageId, Content = body }; var content = _messagePacker.Pack(callbackMessage); var publishedMessage = new CapPublishedMessage { Id = SnowflakeId.Default().NextId(), Name = topicName, Content = content, StatusName = StatusName.Scheduled }; using (var scope = _serviceProvider.CreateScope()) { var provider = scope.ServiceProvider; var callbackPublisher = provider.GetService <ICallbackPublisher>(); await callbackPublisher.PublishCallbackAsync(publishedMessage); } }
private async Task AddAttachmentsAsync(BodyBuilder bodyBuilder, CancellationToken cancellationToken) { var attachments = Attachments; if (attachments != null) { var index = 0; var attachmentObjects = InterpretAttachmentsModel(attachments); foreach (var attachmentObject in attachmentObjects) { switch (attachmentObject) { case Uri url: await AttachOnlineFileAsync(bodyBuilder, url, cancellationToken); break; case string path when path.Contains("://"): await AttachOnlineFileAsync(bodyBuilder, new Uri(path), cancellationToken); break; case string path: await AttachLocalFileAsync(bodyBuilder, path, cancellationToken); break; case byte[] bytes: { var fileName = $"Attachment-{++index}"; var contentType = "application/binary"; bodyBuilder.Attachments.Add(fileName, bytes, ContentType.Parse(contentType)); break; } case Stream stream: { var fileName = $"Attachment-{++index}"; var contentType = "application/binary"; await bodyBuilder.Attachments.AddAsync(fileName, stream, ContentType.Parse(contentType), cancellationToken); break; } case EmailAttachment emailAttachment: { var fileName = emailAttachment.FileName ?? $"Attachment-{++index}"; var contentType = emailAttachment.ContentType ?? "application/binary"; var parsedContentType = ContentType.Parse(contentType); if (emailAttachment.Content is byte[] bytes) { bodyBuilder.Attachments.Add(fileName, bytes, parsedContentType); } else if (emailAttachment.Content is Stream stream) { await bodyBuilder.Attachments.AddAsync(fileName, stream, parsedContentType, cancellationToken); } break; } default: { var json = _contentSerializer.Serialize(attachmentObject); var fileName = $"Attachment-{++index}"; var contentType = "application/json"; bodyBuilder.Attachments.Add(fileName, Encoding.UTF8.GetBytes(json), ContentType.Parse(contentType)); break; } } } } }
internal void SerializeContent(SerializationStream stream, IContentSerializer serializer, object objToSerialize) { stream.Context.SerializerSelector = ContentManager.Serializer.LowLevelSerializerSelector; serializer.Serialize(this, stream, objToSerialize); }
public string Pack(CapMessage obj) { return(_serializer.Serialize(obj)); }
/// <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(); }
/// <inheritdoc/> public async Task <TResult> PostAsync <TResult>(string url, object?body = null, CancellationToken cancellationToken = default) where TResult : class { if (string.IsNullOrWhiteSpace(url)) { throw new ArgumentException("Url should not be empty or null", nameof(url)); } var httpResponseMessage = await _httpClient.PostAsync(url, body == null?null : new ByteArrayContent(_contentSerializer.Serialize(body)), cancellationToken); return(await DeserializeResponseMessageAsync <TResult>(httpResponseMessage)); }
public object SerializeContent(SerializationStream stream, IContentSerializer serializer, object objToSerialize) { stream.Context.SerializerSelector = AssetManager.Serializer.LowLevelSerializerSelector; serializer.Serialize(this, stream, ref objToSerialize); return(objToSerialize); }