コード例 #1
0
        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;
            }
        }
コード例 #2
0
        /// <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));
        }
コード例 #3
0
        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;
            }
        }
コード例 #4
0
        public async Task <IActionResult> DeleteDesignVersion(string versionId)
        {
            Devon4NetLogger.Debug("Executing DeleteDesignVersion from controller SmaxHcm");
            await SmaxHcmHandler.DeleteDesignVersion(versionId);

            return(Ok());
        }
コード例 #5
0
        public async Task <IActionResult> UpdateComponent(UpdateComponentDto updateComponentDto)
        {
            Devon4NetLogger.Debug("Executing UpdateComponent from controller SmaxHcm");
            await SmaxHcmHandler.UpdateComponent(updateComponentDto);

            return(Ok());
        }
コード例 #6
0
        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);
            }
        }
コード例 #7
0
        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());
        }
コード例 #8
0
        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;
            }
        }
コード例 #9
0
        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;
            }
        }
コード例 #10
0
        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));
        }
コード例 #11
0
        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;
            }
        }
コード例 #12
0
        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;
            }
        }
コード例 #13
0
        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;
            }
        }
コード例 #14
0
        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;
                }
            }));
        }
コード例 #15
0
        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));
        }
コード例 #16
0
        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));
        }
コード例 #17
0
        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));
        }
コード例 #18
0
        /// <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));
        }
コード例 #19
0
        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));
        }
コード例 #20
0
 /// <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
     }));
 }
コード例 #21
0
        public async Task <IActionResult> GetDesignIcons()
        {
            Devon4NetLogger.Debug("Executing GetDesignIcons from controller SmaxHcm");
            var response = await SmaxHcmHandler.GetIcons();

            return(Ok(response));
        }
コード例 #22
0
        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)
            });
コード例 #23
0
        public async Task <IActionResult> DeleteDesignContainer(string containerId)
        {
            Devon4NetLogger.Debug("Executing DeleteDesignContainer from controller SmaxHcm");
            await SmaxHcmHandler.DeleteDesignContainer(containerId);

            return(Ok());
        }
コード例 #24
0
        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);
        }
コード例 #25
0
        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));
        }
コード例 #26
0
        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));
        }
コード例 #27
0
        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)));
        }
コード例 #28
0
 public async Task <IActionResult> DeleteTopicMessage(string topicName)
 {
     Devon4NetLogger.Debug("Executing DeleteTopicMessage from controller KafkaController");
     return(Ok(await KafkaHandler.DeleteTopic("Admin1", new List <string> {
         topicName
     })));
 }
コード例 #29
0
        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);
        }
コード例 #30
0
        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);
            }
        }