public async Task <string> CreateSqsQueue(SqsQueueOptions sqsQueueOptions) { var queueAttrs = new Dictionary <string, string>(); try { queueAttrs.Add(QueueAttributeName.FifoQueue, sqsQueueOptions.UseFifo.ToString().ToLowerInvariant()); queueAttrs.Add(QueueAttributeName.DelaySeconds, sqsQueueOptions.DelaySeconds.ToString().ToLowerInvariant()); queueAttrs.Add(QueueAttributeName.MaximumMessageSize, sqsQueueOptions.MaximumMessageSize.ToString().ToLowerInvariant()); queueAttrs.Add(QueueAttributeName.ReceiveMessageWaitTimeSeconds, sqsQueueOptions.ReceiveMessageWaitTimeSeconds.ToString().ToLowerInvariant()); if (sqsQueueOptions.RedrivePolicy != null && !string.IsNullOrEmpty(sqsQueueOptions.RedrivePolicy.DeadLetterQueueUrl) && sqsQueueOptions.RedrivePolicy.MaxReceiveCount > 0) { queueAttrs.Add(QueueAttributeName.RedrivePolicy, await GetRedrivePolicy(sqsQueueOptions.RedrivePolicy).ConfigureAwait(false)); } var responseCreate = await AmazonSQSClient.CreateQueueAsync(new CreateQueueRequest { QueueName = sqsQueueOptions.QueueName, Attributes = queueAttrs }).ConfigureAwait(false); return(responseCreate.QueueUrl); } catch (QueueNameExistsException ex) { Devon4NetLogger.Error($"Error creating the queue: {sqsQueueOptions.QueueName}. The queue name already exists"); Devon4NetLogger.Error(ex); throw; } catch (QueueDeletedRecentlyException ex) { Devon4NetLogger.Error($"Error creating the queue: {sqsQueueOptions.QueueName}. The queue has been deleted recently"); Devon4NetLogger.Error(ex); throw; } }
/// <summary> /// Gets the object /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task <IEnumerable <TodoDto> > GetTodo(Expression <Func <Todos, bool> > predicate = null) { Devon4NetLogger.Debug("GetTodo method from service TodoService"); var result = await _todoRepository.GetTodo(predicate).ConfigureAwait(false); return(result.Select(TodoConverter.ModelToDto)); }
public BsonValue CreateMessageBackup(Command command, QueueActions action = QueueActions.Sent, bool increaseRetryCounter = false, string additionalData = null, string errorData = null) { try { if (command?.InternalMessageIdentifier == null || command.InternalMessageIdentifier.IsNullOrEmptyGuid()) { throw new ArgumentException($"The provided command and the command identifier cannot be null "); } var backUp = new RabbitBackup { Id = Guid.NewGuid(), InternalMessageIdentifier = command.InternalMessageIdentifier, Retries = increaseRetryCounter ? 1 : 0, AdditionalData = string.IsNullOrEmpty(additionalData) ? string.Empty : additionalData, IsError = false, MessageContent = GetSerializedContent(command), MessageType = command.MessageType, TimeStampUTC = command.Timestamp.ToUniversalTime(), Action = action.ToString(), Error = string.IsNullOrEmpty(errorData) ? string.Empty : errorData }; var result = RabbitMqBackupLiteDbRepository.Create(backUp); return(result); } catch (Exception ex) { Devon4NetLogger.Error($"Error storing data with LiteDb: {ex.Message} {ex.InnerException}"); Devon4NetLogger.Error(ex); throw; } }
public async Task <IActionResult> DeleteDesignVersion(string versionId) { Devon4NetLogger.Debug("Executing DeleteDesignVersion from controller SmaxHcm"); await SmaxHcmHandler.DeleteDesignVersion(versionId); return(Ok()); }
public async Task <IActionResult> UpdateComponent(UpdateComponentDto updateComponentDto) { Devon4NetLogger.Debug("Executing UpdateComponent from controller SmaxHcm"); await SmaxHcmHandler.UpdateComponent(updateComponentDto); return(Ok()); }
private static async Task Migrate <T>(IServiceCollection services) where T : DbContext { try { using var sp = services.BuildServiceProvider(); if (sp == null) { Devon4NetLogger.Error($"Unable to build the service provider, the migration {typeof(T).FullName} will not be launched"); } else { var context = sp.GetService(typeof(T)); if (context == null) { Devon4NetLogger.Error($"Unable to resolve {typeof(T).FullName} and the migration will not be launched"); } ((T)context)?.Database.Migrate(); await sp.DisposeAsync().ConfigureAwait(false); } } catch (Exception ex) { Devon4NetLogger.Fatal(ex); } }
public async Task <BookResponseDto> PublishBook(Guid authorId, PublishBookRequestDto request) { Devon4NetLogger.Debug("Entering Publish book on AuhtorService"); var author = await _authorRepository.GetFirstOrDefault(aut => aut.Id == authorId).ConfigureAwait(false); if (author == null) { throw new AuthorNotFoundException(); } Book book; // using (var transaction = await UoW.BeginTransaction().ConfigureAwait(false)) // { book = await _bookRepository.Create(request.ToBook()).ConfigureAwait(false); var authorBook = new AuthorBook { Author = author.Id, Book = book.Id, PublishDate = DateTime.Now, ValidityDate = DateTime.Now.AddYears(1) }; await _authorBookRepository.Create(authorBook).ConfigureAwait(false); // await transaction.CommitAsync().ConfigureAwait(false); // } return(book.ToBookResponse()); }
public BsonValue CreateMessageBackup <T>(ActionBase <T> command, MediatrActions action = MediatrActions.Sent, bool increaseRetryCounter = false, string additionalData = null, string errorData = null) where T : class { try { if (command?.InternalMessageIdentifier == null || command.InternalMessageIdentifier.IsNullOrEmptyGuid()) { throw new ArgumentException($"The provided command and the command identifier cannot be null "); } var backUp = new MediatRBackup { Id = Guid.NewGuid(), InternalMessageIdentifier = command.InternalMessageIdentifier, Retries = increaseRetryCounter ? 1 : 0, AdditionalData = string.IsNullOrEmpty(additionalData) ? string.Empty : additionalData, IsError = false, MessageContent = GetSerializedContent(command), //System.Text.Json.JsonSerializer.Serialize(command), MessageType = command.MessageType, TimeStampUTC = command.Timestamp.ToUniversalTime(), Action = action.ToString(), Error = string.IsNullOrEmpty(errorData) ? string.Empty : errorData }; return(MediatRBackupLiteDbRepository.Create(backUp)); } catch (Exception ex) { Devon4NetLogger.Error(ex); throw; } }
public BsonValue CreateResponseMessageBackup(object command, MediatrActions action = MediatrActions.Sent, bool increaseRetryCounter = false, string additionalData = null, string errorData = null) { try { var backUp = new MediatRBackup { Id = Guid.NewGuid(), Retries = increaseRetryCounter ? 1 : 0, AdditionalData = string.IsNullOrEmpty(additionalData) ? string.Empty : additionalData, IsError = false, MessageContent = GetSerializedContent(command), //System.Text.Json.JsonSerializer.Serialize(command), TimeStampUTC = DateTime.UtcNow.ToUniversalTime(), Action = action.ToString(), Error = string.IsNullOrEmpty(errorData) ? string.Empty : errorData }; return(MediatRBackupLiteDbRepository.Create(backUp)); } catch (Exception ex) { Devon4NetLogger.Error(ex); throw; } }
protected override Task <bool> ProcessMessage(Message message) { var theMessage = JsonSerializer.Deserialize <SqSMessage>(message.Body); Devon4NetLogger.Debug($"Received message {message.MessageId} with Id : {theMessage.Id}"); return(Task.FromResult(true)); }
public bool ValidateToken(string jwtToken, out ClaimsPrincipal claimsPrincipal, out SecurityToken securityToken) { var handler = new JwtSecurityTokenHandler(); try { claimsPrincipal = handler.ValidateToken(jwtToken, new TokenValidationParameters { ValidateIssuer = JwtOptions.ValidateIssuer, ValidateAudience = JwtOptions.RequireAudience, ValidateIssuerSigningKey = JwtOptions.ValidateIssuerSigningKey, ValidateLifetime = JwtOptions.ValidateLifetime, RequireSignedTokens = JwtOptions.RequireSignedTokens, RequireExpirationTime = JwtOptions.RequireExpirationTime, RequireAudience = JwtOptions.RequireAudience, TokenDecryptionKey = SecurityKey, IssuerSigningKey = SecurityKey, ValidAudience = JwtOptions.Audience, ValidIssuer = JwtOptions.Issuer }, out securityToken); return(true); } catch (Exception ex) { Devon4NetLogger.Error(ex); throw; } }
public async Task <MediatRBackup> CreateResponseMessageBackup(object command, MediatRActionsEnum action = MediatRActionsEnum.Sent, bool increaseRetryCounter = false, string additionalData = null, string errorData = null) { try { var ctx = CreateContext(); var backUp = new MediatRBackup { Id = Guid.NewGuid(), Retries = increaseRetryCounter ? 1 : 0, AdditionalData = string.IsNullOrEmpty(additionalData) ? string.Empty : additionalData, IsError = false, MessageContent = GetSerializedContent(command), //System.Text.Json.JsonSerializer.Serialize(command), TimeStampUTC = DateTime.UtcNow.ToUniversalTime(), Action = action.ToString(), Error = string.IsNullOrEmpty(errorData) ? string.Empty : errorData }; var result = await ctx.MediatRBackup.AddAsync(backUp).ConfigureAwait(false); await ctx.SaveChangesAsync(); await ctx.DisposeAsync(); return(result.Entity); } catch (Exception ex) { Devon4NetLogger.Error(ex); throw; } }
private async Task <bool> SaveChanges() { try { await Context.SaveChangesAsync().ConfigureAwait(false); return(true); } catch (OperationCanceledException ex) { Devon4NetLogger.Error(ex); throw; } catch (DbUpdateConcurrencyException ex) { foreach (var entry in ex.Entries) { var databaseValues = entry.GetDatabaseValues(); // Refresh original values to bypass next concurrency check entry.OriginalValues.SetValues(databaseValues); } Devon4NetLogger.Error(ex); throw; } catch (DbUpdateException ex) { Devon4NetLogger.Error(ex); throw; } }
public Task Commit(IDbContextTransaction transaction) { if (transaction == null) { throw new TransactionNullException("Transaction cannot be null to perform transaction operations."); } var transactionSavePointName = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture); return(Task.Run(async() => { try { transaction.CreateSavepoint(transactionSavePointName); _ = await SaveChanges().ConfigureAwait(false); await transaction.CommitAsync().ConfigureAwait(false); } catch (DbUpdateConcurrencyException ex) { Devon4NetLogger.Error(ex); RollbackTransaction(transaction, transactionSavePointName); throw; } catch (Exception ex) { Devon4NetLogger.Error(ex); RollbackTransaction(transaction, transactionSavePointName); throw; } })); }
public async Task <ActionResult> CreateBookAndGetModel(BookDto newBook) { Devon4NetLogger.Debug("Executing GetTodo from controller TodoController"); var result = await _bookService.CreateBookAndGetModel(newBook).ConfigureAwait(false); return(StatusCode(StatusCodes.Status201Created, result)); }
public async Task <ActionResult> Create(string todoDescription) { Devon4NetLogger.Debug("Executing GetTodo from controller TodoController"); var result = await _todoService.CreateTodo(todoDescription).ConfigureAwait(false); return(StatusCode(StatusCodes.Status201Created, result)); }
public async Task <ActionResult> Create(EmployeeDto employeeDto) { Devon4NetLogger.Debug("Executing GetEmployee from controller EmployeeController"); var result = await _employeeService.CreateEmployee(employeeDto.Name, employeeDto.Surname, employeeDto.Mail).ConfigureAwait(false); return(StatusCode(StatusCodes.Status201Created, result)); }
/// <summary> /// Gets the Employee /// </summary> /// <param name="predicate"></param> /// <returns></returns> public async Task <IEnumerable <EmployeeDto> > GetEmployee(Expression <Func <Employee, bool> > predicate = null) { Devon4NetLogger.Debug("GetEmployee method from service Employeeervice"); var result = await _employeeRepository.GetEmployee(predicate).ConfigureAwait(false); return(result.Select(EmployeeConverter.ModelToDto)); }
public IActionResult CurrentUser() { Devon4NetLogger.Debug("Executing CurrentUser from controller AuthController"); //Get claims var token = Request.Headers["Authorization"].ToString().Replace($"{AuthConst.AuthenticationScheme} ", string.Empty); if (string.IsNullOrEmpty(token)) { return(Unauthorized()); } var userClaims = JwtHandler.GetUserClaims(token).ToList(); // Return result with claims values var result = new CurrentUserResponse { Id = JwtHandler.GetClaimValue(userClaims, ClaimTypes.NameIdentifier), UserName = JwtHandler.GetClaimValue(userClaims, ClaimTypes.Name), CorporateInfo = new List <CorporateBasicInfo> { new CorporateBasicInfo { Id = ClaimTypes.Role, Value = JwtHandler.GetClaimValue(userClaims, ClaimTypes.Role), } } }; return(Ok(result)); }
/// <summary> /// Creates the Employee /// </summary> /// <param name="name"></param> /// <param name="surName"></param> /// <param name="mail"></param> /// <returns></returns> public Task <Employee> Create(string name, string surName, string mail) { Devon4NetLogger.Debug($"SetEmployee method from repository Employeeervice with value : {name}"); return(Create(new Employee { Name = name, Surname = surName, Mail = mail })); }
public async Task <IActionResult> GetDesignIcons() { Devon4NetLogger.Debug("Executing GetDesignIcons from controller SmaxHcm"); var response = await SmaxHcmHandler.GetIcons(); return(Ok(response)); }
private Task HandleException(ref HttpContext context, ref System.Exception exception) { Devon4NetLogger.Error(exception); var exceptionTypeValue = exception.GetType(); var exceptionInterfaces = exceptionTypeValue.GetInterfaces().Select(i => i.Name).ToList(); exceptionInterfaces.Add(exceptionTypeValue.Name); return(exceptionInterfaces switch { { } exceptionType when exceptionType.Contains("InvalidDataException") => HandleContext(ref context, StatusCodes.Status422UnprocessableEntity), { } exceptionType when exceptionType.Contains("ArgumentException") || exceptionType.Contains("ArgumentNullException") || exceptionType.Contains("NotFoundException") || exceptionType.Contains("FileNotFoundException") => HandleContext(ref context, StatusCodes.Status400BadRequest), { } exceptionType when exceptionType.Contains("IWebApiException") => HandleContext(ref context, ((IWebApiException)exception).StatusCode, exception.Message, ((IWebApiException)exception).ShowMessage), _ => HandleContext(ref context, StatusCodes.Status500InternalServerError, exception.Message) });
public async Task <IActionResult> DeleteDesignContainer(string containerId) { Devon4NetLogger.Debug("Executing DeleteDesignContainer from controller SmaxHcm"); await SmaxHcmHandler.DeleteDesignContainer(containerId); return(Ok()); }
public async Task <DeliveryResult <T, TV> > DeliverMessage <T, TV>(T key, TV value, string producerId) where T : class where TV : class { DeliveryResult <T, TV> result; var producerOptions = GetProducerOptions(producerId); using var producer = GetProducerBuilder <T, TV>(producerId); try { result = await producer.ProduceAsync(producerOptions.Topic, new Message <T, TV> { Key = key, Value = value }).ConfigureAwait(false); } catch (ProduceException <string, string> e) { Devon4NetLogger.Error(e); throw; } finally { producer?.Flush(); producer?.Dispose(); } return(result); }
public Task <Author> Create(AuthorDto newAuthor) { MethodBase m = MethodBase.GetCurrentMethod(); Devon4NetLogger.Debug($"{m.ReflectedType.Name} method from repository " + $"BookService with value : {newAuthor}"); var author = new Author { Name = newAuthor._name, Surname = newAuthor._surname, Email = newAuthor._email, Phone = newAuthor._phone }; #if ENABLE // TODO: Add it correctly var result = AuthorValidator.Validate(newAuthor); if (!result.IsValid) { throw new ArgumentException($"The 'Description' field can not be null.{result.Errors}"); } #endif return(Create(author)); }
public async Task <IActionResult> DeliverMessage(string key, string value) { Devon4NetLogger.Debug("Executing DeliverMessage from controller KafkaController"); var result = await MessageProducer.SendMessage(key, value); return(Ok(result)); }
public async Task <IActionResult> GetTodoById(long todoId) { Devon4NetLogger.Debug("Executing GetTodoById from controller MediatRController"); var query = new GetTodoQuery(todoId); return(Ok(await MediatRHandler.QueryAsync(query).ConfigureAwait(false))); }
public async Task <IActionResult> DeleteTopicMessage(string topicName) { Devon4NetLogger.Debug("Executing DeleteTopicMessage from controller KafkaController"); return(Ok(await KafkaHandler.DeleteTopic("Admin1", new List <string> { topicName }))); }
public async Task <bool> UploadObject(Stream streamFile, string keyName, string bucketName, string contentType, bool autoCloseStream = false, List <Tag> tagList = null) { try { CheckUploadObjectParams(streamFile, keyName, bucketName); using var s3Client = GetS3Client(AwsRegion, AwsSecretAccessKeyId, AwsSecretAccessKey); using var fileTransferUtility = new TransferUtility(s3Client); var transferUtilityUploadRequest = new TransferUtilityUploadRequest { InputStream = streamFile, Key = keyName, BucketName = bucketName, CannedACL = S3CannedACL.BucketOwnerFullControl, ContentType = contentType, AutoCloseStream = autoCloseStream, TagSet = tagList ?? new List <Tag>() }; await fileTransferUtility.UploadAsync(transferUtilityUploadRequest).ConfigureAwait(false); if (!autoCloseStream) { streamFile.Position = 0; } } catch (Exception ex) { Devon4NetLogger.Fatal(ex); throw; } return(true); }
public async Task DeleteSqsQueue(string queueUrl, bool waitForDeletion = false) { try { await AmazonSQSClient.DeleteQueueAsync(queueUrl).ConfigureAwait(false); if (!waitForDeletion) { return; } var queueExists = true; do { var queues = await GetSqsQueues().ConfigureAwait(false); queueExists = queues.Any(q => q == queueUrl); await Task.Delay(1000); } while (queueExists); } catch (Exception ex) { Devon4NetLogger.Error($"Error deleting the queue: {queueUrl}"); Devon4NetLogger.Error(ex); } }