Example #1
0
        public async Task <WorkoutHistoryOfmForGet> PostIncludingExerciseHistories(WorkoutHistoryOfmForPost ofmForPost, Guid ownerGuid)
        {
            var workoutHistory = Mapper.Map <WorkoutHistoryOfmForPost, WorkoutHistory>(ofmForPost);

            workoutHistory = await _workoutHistoryRepository.CreateIncludingExerciseHistories(workoutHistory, ownerGuid);

            var ofm = Mapper.Map <WorkoutHistory, WorkoutHistoryOfmForGet>(workoutHistory);

            return(ofm);
        }
        public async Task <RedirectToActionResult> CreateNewWorkoutHistory([FromForm] WorkoutHistoryOfmForPost workoutHistoryOfmForPost)
        {
            var postResult = await _workoutHistoryViewModelRepository.Create(workoutHistoryOfmForPost, includeExerciseHistories : true);

            if (postResult.HttpStatusCode == HttpStatusCode.Unauthorized ||
                postResult.HttpStatusCode == HttpStatusCode.Forbidden)
            {
                return(RedirectToAction("AccessDenied", "Authorization"));
            }

            //if ((int)postResult.HttpStatusCode != 201)
            //{
            //    // Todo: Do something when posting failed
            //}

            return(RedirectToAction("HistoryDetails", new { workoutHistoryId = postResult.ViewModel.Id }));
        }
Example #3
0
        public async Task <IActionResult> Post([FromBody] WorkoutHistoryOfmForPost ofmForPost, [FromQuery] string includeExerciseHistories)
        {
            var stringOwnerGuid = User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value;

            if (String.IsNullOrWhiteSpace(stringOwnerGuid))
            {
                return(Unauthorized());
            }
            var ownerGuid = new Guid(stringOwnerGuid);

            if (ofmForPost == null)
            {
                ModelState.AddModelError(_shortCamelCasedControllerName, "The supplied body for the " + _shortCamelCasedControllerName + " is null.");
                return(new BadRequestObjectResult(ModelState));
            }

            if (!int.TryParse(includeExerciseHistories, out int parsedResult))
            {
                ModelState.AddModelError(_shortCamelCasedControllerName, "The query parameter 'includeExerciseHistories' can only take a value of 0 (=false) or 1 (=true).");
                return(new BadRequestObjectResult(ModelState));
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            WorkoutHistoryOfmForGet ofmForGet;

            if (parsedResult == 1)
            {
                ofmForGet = await _asyncOfmRepository.PostIncludingExerciseHistories(ofmForPost, ownerGuid);
            }
            else
            {
                ofmForGet = await _asyncOfmRepository.Post(ofmForPost, ownerGuid);
            }

            var result = CreatedAtRoute(routeName: "GetWorkoutHistoryById", routeValues: new { id = ofmForGet.Id }, value: ofmForGet);

            return(result);
        }
        public async Task CorrectlyCreateNewOfm()
        {
            // Arrange
            var asyncDataCrudMock = new Mock <IWorkoutHistoryRepository>();

            asyncDataCrudMock
            .Setup(s => s.CreateIncludingExerciseHistories(It.IsAny <WorkoutHistory>(), It.IsAny <Guid>())).Returns(Task.FromResult(new WorkoutHistory()   //// Todo: Posting should include non-null workoutHistory.WorkoutId !!
            {
                Id      = 1,
                Workout = new Workout()
                {
                    Id   = 1,
                    Name = "MockWorkout"
                },
                ExerciseHistories = new List <ExerciseHistory>()
                {
                    new ExerciseHistory()
                    {
                        Id = 1
                    },
                    new ExerciseHistory()
                    {
                        Id = 2
                    },
                    new ExerciseHistory()
                    {
                        Id = 3
                    },
                    new ExerciseHistory()
                    {
                        Id = 4
                    },
                    new ExerciseHistory()
                    {
                        Id = 5
                    }
                }
            }));

            var workoutHistoryOfmRepository = new WorkoutHistoryOfmRepository(asyncDataCrudMock.Object, new PropertyMappingService(), new TypeHelperService());
            var workoutHistoryOfmForPost    = new WorkoutHistoryOfmForPost()
            {
                //WorkoutId = 1
            };

            // Act
            var workoutHistoryOfmForGet = await workoutHistoryOfmRepository.PostIncludingExerciseHistories(workoutHistoryOfmForPost, _ownerGuid);

            // Assert
            var actualOfmResult = JsonConvert.SerializeObject(workoutHistoryOfmForGet,
                                                              new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented
            }).MinifyJson().PrettifyJson();

            var expectedOfmResult =
                @"
                    {
                        ""Id"": 1,
                        ""Workout"": {
                            ""Id"": 1,
                            ""Name"": ""MockWorkout""
                        },
                        ""RangeOfExerciseHistoryIds"": ""1-5"",
                        ""ExerciseHistories"": [
                        {
                            ""Id"": 1,
                            ""PreviousExerciseHistory"": null,
                            ""Exercise"": null,
                            ""RangeOfWeightLiftingSetIds"": null,
                            ""WeightLiftingSets"": [],
                            ""RangeOfCardioSetIds"": null,
                            ""CardioSets"": [],
                            ""WorkoutHistoryId"": 0,
                            ""ExecutedOnDateTime"": ""0001-01-01T00:00:00"",
                            ""PreviousExerciseHistoryId"": null
                        },
                        {
                            ""Id"": 2,
                            ""PreviousExerciseHistory"": null,
                            ""Exercise"": null,
                            ""RangeOfWeightLiftingSetIds"": null,
                            ""WeightLiftingSets"": [],
                            ""RangeOfCardioSetIds"": null,
                            ""CardioSets"": [],
                            ""WorkoutHistoryId"": 0,
                            ""ExecutedOnDateTime"": ""0001-01-01T00:00:00"",
                            ""PreviousExerciseHistoryId"": null
                        },
                        {
                            ""Id"": 3,
                            ""PreviousExerciseHistory"": null,
                            ""Exercise"": null,
                            ""RangeOfWeightLiftingSetIds"": null,
                            ""WeightLiftingSets"": [],
                            ""RangeOfCardioSetIds"": null,
                            ""CardioSets"": [],
                            ""WorkoutHistoryId"": 0,
                            ""ExecutedOnDateTime"": ""0001-01-01T00:00:00"",
                            ""PreviousExerciseHistoryId"": null
                        },
                        {
                            ""Id"": 4,
                            ""PreviousExerciseHistory"": null,
                            ""Exercise"": null,
                            ""RangeOfWeightLiftingSetIds"": null,
                            ""WeightLiftingSets"": [],
                            ""RangeOfCardioSetIds"": null,
                            ""CardioSets"": [],
                            ""WorkoutHistoryId"": 0,
                            ""ExecutedOnDateTime"": ""0001-01-01T00:00:00"",
                            ""PreviousExerciseHistoryId"": null
                        },
                        {
                            ""Id"": 5,
                            ""PreviousExerciseHistory"": null,
                            ""Exercise"": null,
                            ""RangeOfWeightLiftingSetIds"": null,
                            ""WeightLiftingSets"": [],
                            ""RangeOfCardioSetIds"": null,
                            ""CardioSets"": [],
                            ""WorkoutHistoryId"": 0,
                            ""ExecutedOnDateTime"": ""0001-01-01T00:00:00"",
                            ""PreviousExerciseHistoryId"": null
                        }
                        ],
                        ""DateTimeStart"": null,
                        ""DateTimeEnd"": null
                    }
                ".MinifyJson().PrettifyJson();

            Assert.AreEqual(expectedOfmResult, actualOfmResult);
        }
        public async Task ReturnSuccessfulOfmQueryResult_UsingPost()
        {
            await Task.Run(async() =>
            {
                // Arrange
                using (var testAppConfiguration = new AppConfigurationMock(File.ReadAllText(Path.GetDirectoryName(typeof(Startup).GetTypeInfo().Assembly.Location) + "\\appsettings.json")))
                {
                    // ARRANGE
                    var httpContextAccessorMock     = new Mock <IHttpContextAccessor>();
                    var httpRequestExecuter         = new Mock <IHttpRequestExecuter>();
                    var workoutHistoryOfmRepository = new WorkoutHistoryApiModelRepository(
                        testAppConfiguration.Instance, httpContextAccessorMock.Object, httpRequestExecuter.Object);

                    var workoutHistoryOfmForPost = new WorkoutHistoryOfmForPost()
                    {
                        WorkoutId = 4
                    };

                    var returnedWorkoutHistoryOfmForGet = new WorkoutHistoryOfmForGet()
                    {
                        Id      = 1,
                        Workout = new WorkoutHistoryOfmForGet.WorkoutOfm()
                        {
                            Id   = 4,
                            Name = "MockWorkout"
                        }
                    };

                    var uri                 = new Uri(testAppConfiguration.Instance.GetValue <string>("FittifyApiBaseUrl") + "api/workouthistories");
                    var httpResponse        = new HttpResponseMessage();
                    httpResponse.Content    = new StringContent(JsonConvert.SerializeObject(returnedWorkoutHistoryOfmForGet));
                    httpResponse.StatusCode = HttpStatusCode.OK;
                    httpRequestExecuter
                    .Setup(s => s.Post(uri, workoutHistoryOfmForPost, testAppConfiguration.Instance, httpContextAccessorMock.Object))
                    .ReturnsAsync(httpResponse);

                    // ACT
                    var ofmQueryResult = await workoutHistoryOfmRepository.Post(workoutHistoryOfmForPost);

                    // Assert
                    var actualOfmQueryResult = JsonConvert.SerializeObject(ofmQueryResult, new JsonSerializerSettings()
                    {
                        Formatting = Newtonsoft.Json.Formatting.Indented
                    }).MinifyJson().PrettifyJson();
                    var expectedOfmQueryResult =
                        @"
                            {
                              ""OfmForGet"": {
                                ""Id"": 1,
                                ""Workout"": {
                                  ""Id"": 4,
                                  ""Name"": ""MockWorkout""
                                },
                                ""RangeOfExerciseHistoryIds"": null,
                                ""ExerciseHistories"": null,
                                ""DateTimeStart"": null,
                                ""DateTimeEnd"": null
                              },
                              ""HttpStatusCode"": 200,
                              ""HttpResponseHeaders"": [],
                              ""ErrorMessagesPresented"": null
                            }
                        ".MinifyJson().PrettifyJson();

                    Assert.AreEqual(actualOfmQueryResult, expectedOfmQueryResult);
                }
            });
        }
        public async Task ReturnOfmQueryResultWithErrorMessages_UsingPostWithIncludeExerciseHistoresOverload()
        {
            await Task.Run(async() =>
            {
                // Arrange
                using (var testAppConfiguration = new AppConfigurationMock(File.ReadAllText(Path.GetDirectoryName(typeof(Startup).GetTypeInfo().Assembly.Location) + "\\appsettings.json")))
                {
                    // ARRANGE
                    var httpContextAccessorMock     = new Mock <IHttpContextAccessor>();
                    var httpRequestExecuter         = new Mock <IHttpRequestExecuter>();
                    var workoutHistoryOfmRepository = new WorkoutHistoryApiModelRepository(
                        testAppConfiguration.Instance, httpContextAccessorMock.Object, httpRequestExecuter.Object);

                    var workoutHistoryOfmForPost = new WorkoutHistoryOfmForPost()
                    {
                        WorkoutId = 4
                    };

                    var queryResult = new Dictionary <string, object>()
                    {
                        {
                            "workouthistory",
                            new List <string>()
                            {
                                "Some error message",
                                "Some other error message"
                            }
                        }
                    };

                    var uri                 = new Uri(testAppConfiguration.Instance.GetValue <string>("FittifyApiBaseUrl") + "api/workouthistories?includeExerciseHistories=1");
                    var httpResponse        = new HttpResponseMessage();
                    httpResponse.Content    = new StringContent(JsonConvert.SerializeObject(queryResult));
                    httpResponse.StatusCode = HttpStatusCode.BadRequest;
                    httpRequestExecuter.Setup(s => s.Post(uri, workoutHistoryOfmForPost, testAppConfiguration.Instance, httpContextAccessorMock.Object)).ReturnsAsync(httpResponse);

                    // ACT
                    var ofmQueryResult = await workoutHistoryOfmRepository.Post(workoutHistoryOfmForPost, includeExerciseHistories: true);

                    // Assert
                    var actualOfmQueryResult = JsonConvert.SerializeObject(ofmQueryResult, new JsonSerializerSettings()
                    {
                        Formatting = Newtonsoft.Json.Formatting.Indented
                    }).MinifyJson().PrettifyJson();
                    var expectedOfmQueryResult =
                        @"
                            {
                              ""OfmForGet"": null,
                              ""HttpStatusCode"": 400,
                              ""HttpResponseHeaders"": [],
                              ""ErrorMessagesPresented"": {
                                ""workouthistory"": [
                                  ""Some error message"",
                                  ""Some other error message""
                                ]
                              }
                            }
                        ".MinifyJson().PrettifyJson();

                    Assert.AreEqual(actualOfmQueryResult, expectedOfmQueryResult);
                }
            });
        }