public MessageTemplateDto UpdateMessageTemplate(MessageTemplateDto model) { try { var oldMessageTemplate = _context.messagetemplates.FirstOrDefault(x => x.Id == model.Id); var updatedMessageTemplate = Mapper.Map <messagetemplate>(model); updatedMessageTemplate.Modified = DateTime.Now; _context.Entry(oldMessageTemplate).CurrentValues.SetValues(updatedMessageTemplate); _context.SaveChanges(); return(model); } catch (DbEntityValidationException ex) { var errorMsg = EisHelper.ParseDbEntityValidationException(ex); _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace); throw ex; } catch (Exception ex) { _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace); throw ex; } }
/// <summary> /// 转换为消息模板实体 /// </summary> /// <param name="dto">消息模板数据传输对象</param> public static MessageTemplate ToEntity2(this MessageTemplateDto dto) { if (dto == null) { return(new MessageTemplate()); } return(new MessageTemplate(dto.Id.ToGuid()) { CategoryId = dto.CategoryId, Type = dto.Type, SendObject = dto.SendObject, Name = dto.Name, SourceId = dto.SourceId, Title = dto.Title, Content = dto.Content, IsEnabled = dto.IsEnabled, SortId = dto.SortId, CreationTime = dto.CreationTime, CreatorId = dto.CreatorId, LastModifierId = dto.LastModifierId, LastModificationTime = dto.LastModificationTime, IsDeleted = dto.IsDeleted, Version = dto.Version, }); }
public ActionResult Save(int id, MessageTemplateDto model) { // create view bag first for the vendors populateMessageTypesViewBag(); if (!ModelState.IsValid) { var errors = ModelState.Values.SelectMany(e => e.Errors.Select(x => x.ErrorMessage)); ModelState.AddModelError("", string.Join("<br/>", errors)); return(View(model)); } // save the message template model.UserName = User.Identity.Name; if (id == 0) { model = _messageTemplateService.CreateMessageTemplate(model); } else { model = _messageTemplateService.UpdateMessageTemplate(model); } TempData["Message"] = "Changes have been successfully saved!"; return(RedirectToAction("edit", new { id = model.Id })); }
/// <summary> /// 转换为消息模板实体 /// </summary> /// <param name="dto">消息模板数据传输对象</param> public static MessageTemplate ToEntity3(this MessageTemplateDto dto) { if (dto == null) { return(new MessageTemplate()); } return(MessageTemplateFactory.Create( templateId: dto.Id.ToGuid(), categoryId: dto.CategoryId, type: dto.Type, sendObject: dto.SendObject, name: dto.Name, sourceId: dto.SourceId, title: dto.Title, content: dto.Content, isEnabled: dto.IsEnabled, sortId: dto.SortId, creationTime: dto.CreationTime, creatorId: dto.CreatorId, lastModifierId: dto.LastModifierId, lastModificationTime: dto.LastModificationTime, isDeleted: dto.IsDeleted, version: dto.Version )); }
/// <summary> /// 转换为消息模板实体 /// </summary> /// <param name="dto">消息模板数据传输对象</param> public static MessageTemplate ToEntity(this MessageTemplateDto dto) { if (dto == null) { return(new MessageTemplate()); } return(dto.MapTo(new MessageTemplate(dto.Id.ToGuid()))); }
public MessageTemplate Create(MessageTemplateDto messageTemplateDto) { var messageTemplate = CheckAndPrepareMessageTemplateEntityForCreate(messageTemplateDto); Create(messageTemplate); Save(); return(_cache.GetOrAdd(messageTemplateDto.Type.ToString(), () => messageTemplate)); // TODO CK: test this ! }
private bool TryGetOne(MessageTemplateDto dto, out MessageTemplate entity) { Guard.IsNotNull(dto); return(TryGetOne(out entity, mt => mt.Type.Equals(dto.Type) && mt.Subject.Equals(dto.Subject) && mt.Body.Equals(dto.Body))); }
private MessageTemplate CheckAndPrepareMessageTemplateEntityForCreate(MessageTemplateDto messageTemplateDto) { if (TryGetOne(messageTemplateDto.Type, out var entity)) { throw new EntityAlreadyExistsException("Couldn't create a new message template, because a similar template already exists", entity); } var messageTemplate = _mapper.Map <MessageTemplate>(messageTemplateDto); return(messageTemplate); }
public bool TryGetOne(MessageTemplateDto dto, out MessageTemplate entity) { Guard.IsNotNull(dto); entity = FindAll() .Where(mt => mt.Type.Equals(dto.Type)) .Where(mt => mt.Subject.Equals(dto.Subject)) .Where(mt => mt.Body.Equals(dto.Body)) .FirstOrDefault(); return(entity.IsNotEmpty()); }
public MessageTemplate Update(MessageTemplateDto messageTemplateDto) { Guard.IsNotNull(messageTemplateDto); if (_mtRepo.TryGetOne(messageTemplateDto, out var entity)) { throw new EntityNotChangedException("Couldn't update the message template, because is hasn't changed"); } var messageType = messageTemplateDto.Type; entity = GetOne(messageType); entity.Subject = messageTemplateDto.Subject; entity.Body = messageTemplateDto.Body; return(_cache.Update(messageType.ToString(), () => _mtRepo.Update(entity))); }
public MessageTemplateDto CreateMessageTemplate(MessageTemplateDto model) { try { var result = Mapper.Map <messagetemplate>(model); result.Created = DateTime.Now; _context.messagetemplates.Add(result); _context.SaveChanges(); return(Mapper.Map <MessageTemplateDto>(result)); } catch (DbEntityValidationException ex) { var errorMsg = EisHelper.ParseDbEntityValidationException(ex); _logger.LogError(LogEntryType.VendorProductService, errorMsg, ex.StackTrace); throw ex; } catch (Exception ex) { _logger.LogError(LogEntryType.VendorProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace); throw ex; } }
public IActionResult CreateMessageTemplate([FromBody] MessageTemplateDto messageTemplateDto) { var tplEntity = _mtService.Create(messageTemplateDto); return(Created($"api/messageTemplates", tplEntity)); }
/// <summary> /// Edits a message template. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Host only. Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// Message template name /// </param> /// <param name='body'> /// Message template entity /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MessageTemplateDto> PutByIdAsync(this IMessageTemplates operations, string key, MessageTemplateDto body = default(MessageTemplateDto), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PutByIdWithHttpMessagesAsync(key, body, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Edits a message template. /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Host only. Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='key'> /// Message template name /// </param> /// <param name='body'> /// Message template entity /// </param> public static MessageTemplateDto PutById(this IMessageTemplates operations, string key, MessageTemplateDto body = default(MessageTemplateDto)) { return(operations.PutByIdAsync(key, body).GetAwaiter().GetResult()); }
/// <summary> /// Edits a message template. Host only. Requires authentication. /// </summary> /// <exception cref="UiPathEJC.Service.Rest.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">key: Id</param> /// <param name="messageTemplateDto">The entity to put</param> /// <returns>Task of ApiResponse (MessageTemplateDto)</returns> public async System.Threading.Tasks.Task <ApiResponse <MessageTemplateDto> > MessageTemplatesPutByIdAsyncWithHttpInfo(string id, MessageTemplateDto messageTemplateDto) { // verify the required parameter 'id' is set if (id == null) { throw new ApiException(400, "Missing required parameter 'id' when calling MessageTemplatesApi->MessageTemplatesPutById"); } // verify the required parameter 'messageTemplateDto' is set if (messageTemplateDto == null) { throw new ApiException(400, "Missing required parameter 'messageTemplateDto' when calling MessageTemplatesApi->MessageTemplatesPutById"); } var localVarPath = "/odata/MessageTemplates('{Id}')"; var localVarPathParams = new Dictionary <String, String>(); var localVarQueryParams = new List <KeyValuePair <String, String> >(); var localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary <String, String>(); var localVarFileParams = new Dictionary <String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) { localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); } if (id != null) { localVarPathParams.Add("Id", Configuration.ApiClient.ParameterToString(id)); // path parameter } if (messageTemplateDto != null && messageTemplateDto.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(messageTemplateDto); // http body (model) parameter } else { localVarPostBody = messageTemplateDto; // byte array } // authentication (Bearer) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Authorization"))) { localVarHeaderParams["Authorization"] = Configuration.GetApiKeyWithPrefix("Authorization"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int)localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("MessageTemplatesPutById", localVarResponse); if (exception != null) { throw exception; } } return(new ApiResponse <MessageTemplateDto>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (MessageTemplateDto)Configuration.ApiClient.Deserialize(localVarResponse, typeof(MessageTemplateDto)))); }
/// <summary> /// Edits a message template. Host only. Requires authentication. /// </summary> /// <exception cref="UiPathEJC.Service.Rest.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">key: Id</param> /// <param name="messageTemplateDto">The entity to put</param> /// <returns>Task of MessageTemplateDto</returns> public async System.Threading.Tasks.Task <MessageTemplateDto> MessageTemplatesPutByIdAsync(string id, MessageTemplateDto messageTemplateDto) { ApiResponse <MessageTemplateDto> localVarResponse = await MessageTemplatesPutByIdAsyncWithHttpInfo(id, messageTemplateDto); return(localVarResponse.Data); }
public async Task <MessageTemplate> CreateAsync(MessageTemplateDto messageTemplateDto) { var messageTemplate = CheckAndPrepareMessageTemplateEntityForCreate(messageTemplateDto); return(await _cache.GetOrAddAsync(messageTemplateDto.Type.ToString(), () => _mtRepo.CreateAsync(messageTemplate))); }
/// <summary> /// Edits a message template. /// </summary> /// <remarks> /// Host only. Requires authentication. /// </remarks> /// <param name='id'> /// key: Id /// </param> /// <param name='messageTemplateDto'> /// The entity to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <MessageTemplateDto> > PutByIdWithHttpMessagesAsync(string id, MessageTemplateDto messageTemplateDto, Dictionary <string, List <string> > customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (id == null) { throw new ValidationException(ValidationRules.CannotBeNull, "id"); } if (messageTemplateDto == null) { throw new ValidationException(ValidationRules.CannotBeNull, "messageTemplateDto"); } if (messageTemplateDto != null) { messageTemplateDto.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("id", id); tracingParameters.Add("messageTemplateDto", messageTemplateDto); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutById", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "odata/MessageTemplates('{Id}')").ToString(); _url = _url.Replace("{Id}", System.Uri.EscapeDataString(id)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (messageTemplateDto != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(messageTemplateDto, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 400) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <MessageTemplateDto>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <MessageTemplateDto>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public IActionResult UpdateMessageTemplate([FromBody] MessageTemplateDto messageTemplateDto) { var message = _mtService.Update(messageTemplateDto); return(Ok(message)); }
/// <summary> /// Edits a message template. /// </summary> /// <remarks> /// Host only. Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='messageTemplateDto'> /// The entity to put /// </param> public static MessageTemplateDto PutById(this IMessageTemplates operations, string id, MessageTemplateDto messageTemplateDto) { return(operations.PutByIdAsync(id, messageTemplateDto).GetAwaiter().GetResult()); }
/// <summary> /// Edits a message template. Host only. Requires authentication. /// </summary> /// <exception cref="UiPathEJC.Service.Rest.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">key: Id</param> /// <param name="messageTemplateDto">The entity to put</param> /// <returns>MessageTemplateDto</returns> public MessageTemplateDto MessageTemplatesPutById(string id, MessageTemplateDto messageTemplateDto) { ApiResponse <MessageTemplateDto> localVarResponse = MessageTemplatesPutByIdWithHttpInfo(id, messageTemplateDto); return(localVarResponse.Data); }
/// <summary> /// Edits a message template. /// </summary> /// <remarks> /// Host only. Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='id'> /// key: Id /// </param> /// <param name='messageTemplateDto'> /// The entity to put /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <MessageTemplateDto> PutByIdAsync(this IMessageTemplates operations, string id, MessageTemplateDto messageTemplateDto, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.PutByIdWithHttpMessagesAsync(id, messageTemplateDto, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
public MessageTemplate Create(MessageTemplateDto messageTemplateDto) { var messageTemplate = CheckAndPrepareMessageTemplateEntityForCreate(messageTemplateDto); return(_cache.GetOrAdd(messageTemplateDto.Type.ToString(), () => _mtRepo.Create(messageTemplate))); }