Esempio n. 1
0
        public async Task <ActionResult <Establishment> > Post([FromBody] EstablishmentRequest body)
        {
            Establishment resultEstablishment;

            try {
                logger.LogInformation("Trying to verify if establishment with given Name exists");
                var establishment = await establishmentService.GetByName(body.Name.FirstCharToUpper());

                if (establishment != null)
                {
                    string errorMessage = responseMessages.NotAccepted.Replace("$", "estabelecimento");
                    logger.LogInformation("Error: " + errorMessage);
                    return(httpResponseHelper.ErrorResponse(errorMessage, 406));
                }

                logger.LogInformation("Inserting establishment into database");
                var newEstablishment = new Establishment()
                {
                    Name      = body.Name.FirstCharToUpper(),
                    Type      = body.Type.FirstCharToUpper(),
                    CreatedAt = DateTime.Now
                };

                resultEstablishment = await establishmentService.CreateItem(newEstablishment);
            } catch (Exception ex) {
                logger.LogInformation("Exception: " + ex.Message);
                throw ex;
            }

            logger.LogInformation("Action POST for /api/establishments returns 201");
            return(Created("", resultEstablishment));
        }
Esempio n. 2
0
        // edit establishment voor ingelogde merchant zijn company
        public async Task <(string, bool)> EditEstablishment(int establishmentId, EstablishmentRequest editEstablishmentRequest)
        {
            string message;
            bool   isSuccess = false;

            var editedEstablishmentJson = JsonConvert.SerializeObject(editEstablishmentRequest);

            var credentials = passwordVault.Retrieve("Stapp", "Token");

            credentials.RetrievePassword();
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", credentials.Password);

            try
            {
                var res = await client.PutAsync(new Uri($"{baseUrl}api/establishment/{establishmentId}"), new StringContent(editedEstablishmentJson, System.Text.Encoding.UTF8, "application/json"));

                if (res.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    message = JsonConvert.DeserializeObject <ErrorMessage>(await res.Content.ReadAsStringAsync()).Error;
                }
                else
                {
                    message   = JsonConvert.DeserializeObject <SuccesMessage>(await res.Content.ReadAsStringAsync()).Bericht;
                    isSuccess = true;
                }
            }
            catch
            {
                message = "Er is een onverwachte fout opgetreden tijdens het bewerken van de vestiging.";
            }

            return(message, isSuccess);
        }
Esempio n. 3
0
        public async void Put_SuccessStatus200_Test()
        {
            // 0: Remove all establishments from database
            await establishmentService.RemoveAll();

            // 1: POST Request body
            var postRequestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "alimentação"
            };

            // 2: Call POST Action passing body request with a new establishment
            var postQuery = await establishmentsController.Post(postRequestBody);

            var postResultValue = (Establishment)postQuery.Result.GetType().GetProperty("Value").GetValue(postQuery.Result);

            // 3: PUT Request body
            string id          = postResultValue.Id;
            var    requestBody = new EstablishmentRequest {
                Name = "Test 2",
                Type = "Alimentação"
            };

            var query = await establishmentsController.Put(id, requestBody);

            var statusCode = (int)query.Result.GetType().GetProperty("StatusCode").GetValue(query.Result);
            var result     = (Establishment)query.Result.GetType().GetProperty("Value").GetValue(query.Result);

            Assert.Equal(200, statusCode);
            Assert.Equal("Test 2", result.Name);
        }
Esempio n. 4
0
        public async Task <ActionResult <Establishment> > Put(string id, [FromBody] EstablishmentRequest body)
        {
            // Validating id
            if (id == null || !Regex.IsMatch(id, "^[0-9a-fA-F]{24}$"))
            {
                string errorMessage = responseMessages.IncorretIdFormat;
                logger.LogInformation("Error: " + errorMessage);
                return(httpResponseHelper.ErrorResponse(errorMessage, 400));
            }

            Establishment updatedEstablishment;

            try
            {
                logger.LogInformation("Trying to get a establishemnt with given id");
                var actualEstablishment = await establishmentService.GetById(id);

                if (actualEstablishment == null)
                {
                    string errorMessage = responseMessages.NotFoundGivenId.Replace("$", "estabelecimento");
                    logger.LogInformation("Error: " + errorMessage);
                    return(httpResponseHelper.ErrorResponse(errorMessage, 404));
                }

                updatedEstablishment = new Establishment()
                {
                    Id        = id,
                    Name      = body.Name.FirstCharToUpper(),
                    Type      = body.Type.FirstCharToUpper(),
                    CreatedAt = actualEstablishment.CreatedAt,
                    UpdatedAt = DateTime.Now
                };

                logger.LogInformation("Trying to update establishment with id: " + id);
                var replaceResult = await establishmentService.UpdateById(id, updatedEstablishment);

                if (!replaceResult.IsAcknowledged)
                {
                    string errorMessage = responseMessages.CantUpdate;
                    logger.LogInformation("Error: " + errorMessage);
                    return(httpResponseHelper.ErrorResponse(errorMessage, 406));
                }

                //Send to RabbitMQ to event handler observer pattern
                Emitter.EstablishmentUpdated(updatedEstablishment, rabbitConnector.ConnectionString);
            }
            catch (Exception ex)
            {
                logger.LogInformation($"Message: {ex.Message}");
                logger.LogTrace($"Stack Trace: {ex.StackTrace}");
                throw;
            }

            logger.LogInformation("Action PUT for /api/establishments returns 200");
            return(Ok(updatedEstablishment));
        }
Esempio n. 5
0
 public AddEstablishmentPageViewModel(
     INavigationService navigationService,
     IApiService apiService,
     IFilesHelper filesHelper) : base(navigationService)
 {
     _navigationService = navigationService;
     _apiService        = apiService;
     _filesHelper       = filesHelper;
     Title         = "Add Establishment";
     Image         = App.Current.Resources["UrlNoImage"].ToString();
     IsEnabled     = true;
     IsRunning     = false;
     Establishment = new EstablishmentRequest();
 }
Esempio n. 6
0
        public async Task <IActionResult> PostEstablishment([FromBody] EstablishmentRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Bad request",
                    Result = ModelState
                }));
            }

            UserEntity userEntity = await _userHelper.GetUserAsync(request.UserId);

            if (userEntity == null)
            {
                return(BadRequest("User doesn't exists."));
            }

            EstablishmentEntity establishment = await _context.Establishments.FirstOrDefaultAsync(e => e.Name == request.Name);

            if (establishment != null)
            {
                return(BadRequest(new Response
                {
                    IsSuccess = false,
                    Message = "Establishment exist"
                }));
            }

            string picturePath = string.Empty;

            if (request.PictureEstablishmentArray != null && request.PictureEstablishmentArray.Length > 0)
            {
                picturePath = await _blobHelper.UploadBlobAsync(request.PictureEstablishmentArray, "establishments");
            }

            establishment = new EstablishmentEntity
            {
                Name = request.Name,
                LogoEstablishmentPath = picturePath,
                User = userEntity
            };

            _context.Establishments.Add(establishment);
            await _context.SaveChangesAsync();

            return(Ok(_converterHelper.ToEstablishmentResponse(establishment)));
        }
Esempio n. 7
0
        public async void Put_InvalidId400_Test(string id)
        {
            // 1: Request body
            var requestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "alimentação"
            };

            // 2: Call PUT Action passing body request with an updated establishment
            var query = await establishmentsController.Put(id, requestBody);

            var  result     = query.Result.GetType().GetProperty("Value").GetValue(query.Result);
            Type resultType = result.GetType();

            Assert.Equal(400, (int)resultType.GetProperty("StatusCode").GetValue(result));
            Assert.Equal(controllerMessages.IncorretIdFormat, (string)resultType.GetProperty("Message").GetValue(result));
        }
Esempio n. 8
0
        public async void Put_Returns404_IdNotFound_Test()
        {
            // 0: Remove all establishments from database
            await establishmentService.RemoveAll();

            // 1: Request body, given id is not found on database
            string id          = "5dcaad2526235a471cfcccad";
            var    requestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "Alimentação"
            };

            // 2: Call PUT Action passing body request with an updated establishment
            var query = await establishmentsController.Put(id, requestBody);

            var  result     = query.Result.GetType().GetProperty("Value").GetValue(query.Result);
            Type resultType = result.GetType();

            Assert.Equal(404, (int)resultType.GetProperty("StatusCode").GetValue(result));
            Assert.Equal(controllerMessages.NotFoundGivenId.Replace("$", "estabelecimento"), (string)resultType.GetProperty("Message").GetValue(result));
        }
Esempio n. 9
0
        public async void Post_SuccessStatus201_Test()
        {
            // 0: Remove all establishments from database
            await establishmentService.RemoveAll();

            // 1: Request body
            var requestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "alimentação"
            };

            // 2: Call POST Action passing body request with a new establishment
            var query = await establishmentsController.Post(requestBody);

            var resultStatusCode = query.Result.GetType().GetProperty("StatusCode").GetValue(query.Result);
            var resultValue      = (Establishment)query.Result.GetType().GetProperty("Value").GetValue(query.Result);

            Assert.Equal(201, (int)resultStatusCode);
            Assert.Equal("Test 1", resultValue.Name);
            Assert.Equal("Alimentação", resultValue.Type);
        }
Esempio n. 10
0
        public async void Post_ThrowsException_Test()
        {
            // 0: Remove all establishments from database
            await establishmentService.RemoveAll();

            // 1: Request body
            var requestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "Alimentação"
            };

            // 2: Mocking GetByName Method to throws
            var establishmentServiceMock = new Mock <EstablishmentService>(dbSettings);

            establishmentServiceMock.Setup(es => es.GetByName(It.IsAny <string>())).ThrowsAsync(new InvalidOperationException());

            var establishmentsControllerLocal = new EstablishmentsController(loggerWrapper, establishmentServiceMock.Object, controllerMessages);

            // 3: Call POST Action and Expects to throws
            await Assert.ThrowsAsync <InvalidOperationException>(async() => await establishmentsControllerLocal.Post(requestBody));
        }
Esempio n. 11
0
        public async void Delete_SuccessStatus200_Test()
        {
            // 1: POST Request body
            var postRequestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "alimentação"
            };

            // 2: Call POST Action passing body request with a new establishment
            var postQuery = await establishmentsController.Post(postRequestBody);

            var postResultValue = (Establishment)postQuery.Result.GetType().GetProperty("Value").GetValue(postQuery.Result);

            // 3: DELETE given Id param
            string id = postResultValue.Id;

            var query = await establishmentsController.Delete(id);

            var result = (ResponseDetails)query.Result.GetType().GetProperty("Value").GetValue(query.Result);

            Assert.Equal(200, result.StatusCode);
            Assert.Equal(controllerMessages.DeletedSuccess.Replace("$", "estabelecimento"), result.Message);
        }
Esempio n. 12
0
        public async void Put_Returns406_NotAcknowledged_Test()
        {
            // 0: Remove all establishments from database
            await establishmentService.RemoveAll();

            // 1: Request body
            string id          = "5dcaad2526235a471cfcccad";
            var    requestBody = new EstablishmentRequest {
                Name = "Test 1",
                Type = "Alimentação"
            };

            // 2: Mocking GetById Method to return fake data
            var fakeEstablishment = new Establishment {
                Id   = id,
                Name = requestBody.Name,
                Type = requestBody.Type
            };
            var establishmentServiceMock = new Mock <EstablishmentService>(dbSettings);

            establishmentServiceMock.Setup(es => es.GetById(It.IsAny <string>())).ReturnsAsync(fakeEstablishment);

            var replaceOneResultWrapper = new ReplaceOneResultWrapper();

            establishmentServiceMock.Setup(es => es.UpdateById(It.IsAny <string>(), It.IsAny <Establishment>())).ReturnsAsync(replaceOneResultWrapper);

            var establishmentsControllerLocal = new EstablishmentsController(loggerWrapper, establishmentServiceMock.Object, controllerMessages);

            var query = await establishmentsControllerLocal.Put(id, requestBody);

            var  result     = query.Result.GetType().GetProperty("Value").GetValue(query.Result);
            Type resultType = result.GetType();

            Assert.Equal(406, (int)resultType.GetProperty("StatusCode").GetValue(result));
            Assert.Equal(controllerMessages.CantUpdate, (string)resultType.GetProperty("Message").GetValue(result));
        }
Esempio n. 13
0
        public async Task <Response> GetEstablishmentLocationAsync(string urlBase, string servicePrefix, string controller, EstablishmentRequest model)
        {
            try
            {
                string        request = JsonConvert.SerializeObject(model);
                StringContent content = new StringContent(request, Encoding.UTF8, "application/json");
                HttpClient    client  = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                string url = $"{servicePrefix}{controller}";
                HttpResponseMessage response = await client.PostAsync(url, content);

                string answer = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = answer,
                    });
                }

                EstablishmentLocationResponse result = JsonConvert.DeserializeObject <EstablishmentLocationResponse>(answer);
                return(new Response
                {
                    IsSuccess = true,
                    Result = result,
                });
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message,
                });
            }
        }