Example #1
0
        protected JessModule(string basePath = "")
        {
            Routes = new List<JessicaRoute>();
            Before = new BeforeFilters();
            After = new AfterFilters();
            Response = new ResponseFactory(AppDomain.CurrentDomain.BaseDirectory);

            _viewFactory = new ViewFactory(Jess.ViewEngines, AppDomain.CurrentDomain.BaseDirectory);
            _basePath = basePath;
        }
Example #2
0
        public Client(IConnection connection)
        {
            Ensure.That(connection, "connection").IsNotNull();

            Connection = connection;
            EntityReflector = new EntityReflector();
            Serializer = new MyCouchSerializer(EntityReflector); //TODO: Either replace with Func<IEntityReflector> or pass IClient Latter is ugly...ugliest...
            ResponseFactory = new ResponseFactory(this);
            Databases = new Databases(this);
            Documents = new Documents(this);
            Entities = new Entities(this);
            Views = new Views(this);
        }
Example #3
0
        public static async Task <MapzenIsochroneResult> GetIsochroneAsync(Point geodeticPoint, string apiKey)
        {
            //  var url = $"matrix.mapzen.com/isochrone?json={{\"locations\":[{{\"lat\":{geodeticPoint.Y},\"lon\":{geodeticPoint.X}}}],\"costing\":\"bicycle\",\"contours\":[{{\"time\":15,\"color\":\"ff0000\"}}]}}&id=Walk_From_Office&api_key={apiKey}";

            var parameter = new MapzenRouteCostingModel()
            {
                locations = new Location[] { new Location()
                                             {
                                                 lon = geodeticPoint.X, lat = geodeticPoint.Y
                                             } },
                costing  = "auto",
                contours = new Contour[] { new Contour()
                                           {
                                               time = 4, color = "ff0000"
                                           } },
                polygons = true,
            };

            var url = $"http://matrix.mapzen.com/isochrone?id=Walk_From_Office&api_key={apiKey}";

            var result = await Helpers.NetHelper.HttpPostAsync <MapzenIsochroneResult>(new Helpers.HttpParameters()
            {
                Address = url, Data = parameter
            });

            if (result == null)
            {
                ResponseFactory.CreateError <string>("NULL VALUE");

                return(null);
            }
            else
            {
                return(ResponseFactory.Create(result?.Result)?.Result);
            }
        }
Example #4
0
        /// <summary>
        /// Generic send request
        /// </summary>
        /// <param name="request">Request to send</param>
        /// <returns>Response model</returns>
        public virtual WebServiceResponse SendRequest(WebServiceRequest request)
        {
            this.request = request;

            XmlDocument xmlRequest = RequestFactory.CreateRequest(request);

            this.xmlRequest = xmlRequest;

            XmlDocument xmlResponse = SendRequest(xmlRequest);

            this.xmlResponse = xmlResponse;

            WebServiceResponse response = ResponseFactory.CreateResponse(request.GetWebServiceResponseModel(), xmlResponse);

            if ((response is CompositeResponse) && (request is CompositeRequest))
            {
                CompositeResponse compositeResponse = (CompositeResponse)response;
                CompositeRequest  compositeRequest  = (CompositeRequest)request;

                if (compositeResponse.GetResponsesCount() > 0)
                {
                    List <WebServiceResponse> responses  = compositeResponse.GetResponses();
                    List <Operation>          operations = compositeRequest.GetOperations();

                    for (int i = 0; i < responses.Count; i++)
                    {
                        WebServiceResponse tempResponse = responses[i];
                        WebServiceRequest  temRequest   = operations[i].WebService;
                        tempResponse.WebServiceType = temRequest.WebServiceType;
                    }
                }
            }

            response.WebServiceType = request.WebServiceType;
            return(response);
        }
        public async Task <ActionResult> RegisterAdmin(RegisterViewModel registerModel, bool refreshFromDb = false)
        {
            var createUserResponse = CheckEmailCollision(registerModel.Email);

            if (!ResponseFactory.IsSuccessful(createUserResponse))
            {
                return(View("~/Views/Account/Login.cshtml"));
            }

            var passwordHash = HashPassword(registerModel.Password);

            registerModel.userType    = (int)UserType.ADMIN;
            registerModel.PhoneNumber = "0123456789";
            registerModel.Id          = Guid.NewGuid();

            var registerUserResponse = await AspNetUserCore.Register(registerModel, passwordHash).ConfigureAwait(false);

            if (!ResponseFactory.IsSuccessful(registerUserResponse))
            {
                return(View("~/Views/Account/Login.cshtml"));
            }

            return(View("~/Views/Account/Login.cshtml"));
        }
Example #6
0
        public async Task <ResponseStatus> LeaveRoom(DbUserModel dbUserModel)
        {
            if (GameConfiguration.RoomStatus == RoomStatus.Open)
            {
                // Check if the player leaving was the host.
                if (GameConfiguration.Creator.Id == dbUserModel.UserModel.Id)
                {
                    // Delete the game
                    await MongoConnector.GetGameRoomCollection().DeleteOneAsync(it => it.Id == GameConfiguration.Id);

                    return(ResponseFactory.createResponse(ResponseType.SUCCESS));
                }

                // Otherwise, just remove the player from the player list.
                GameConfiguration.Players.Remove(dbUserModel.AsUser());
                await MongoConnector.GetGameRoomCollection().ReplaceOneAsync((it => it.Id == GameConfiguration.Id), new GameConfigurationMapper(GameConfiguration));

                return(ResponseFactory.createResponse(ResponseType.SUCCESS));
            }
            // TODO: Player left the game while ongoing.
            // Create a player leave game event and push to event list

            return(ResponseFactory.createResponse(ResponseType.INVALID_REQUEST));
        }
        public static Response <GoogleGeolocationResult> GetLocation(string key, List <Wifiaccesspoint> networks)
        {
            try
            {
                var parameter = new GoogleGeolocationParameters()
                {
                    wifiAccessPoints = networks.ToArray()
                };

                var url = $"https://www.googleapis.com/geolocation/v1/geolocate?key={key}";

                //return Helpers.NetHelper.HttpPost<GoogleGeolocationResult>(url, parameter, null, null);
                return(Helpers.NetHelper.HttpPost <GoogleGeolocationResult>(new Helpers.HttpParameters()
                {
                    Address = url, Data = parameter
                }));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);

                return(ResponseFactory.CreateError <GoogleGeolocationResult>(ex.GetMessagePlus()));
            }
        }
Example #8
0
        public static async Task <Response <Order> > Finalize(Order order)
        {
            if (!SalesValidator.ValidateOrder(order, false))
            {
                return(ResponseFactory <Order> .CreateResponse(false, ResponseCode.ErrorInvalidInput));
            }

            order.Status = OrderStatus.Finalized.ToInt();

            using (var unitOfWork = new DataLayerUnitOfWork())
            {
                var orderRepository = unitOfWork.TrackingRepository <OrderRepository>();

                var dbModel      = order.CopyTo <DataLayer.Order>();
                var updatedOrder = await orderRepository.UpdateAsync(dbModel, true).ConfigureAwait(false);

                if (updatedOrder == null)
                {
                    return(ResponseFactory <Order> .CreateResponse(false, ResponseCode.Error));
                }

                return(await CreatePayroll(order, unitOfWork, orderRepository));
            }
        }
        public override async Task <AuthorizationResponse> Login(AuthorizationRequest request, ServerCallContext context)
        {
            // Try to get a user
            RedisUserModel user = await RedisUserModel.GetUserFromUsername(request.Username);

            if (user == null || !JwtManager.VerifyPasswordHash(request.Password, user.UserModel.PasswordHash))
            {
                return new AuthorizationResponse()
                       {
                           Status = ResponseFactory.createResponse(ResponseType.INVALID_CREDENTIALS)
                       }
            }
            ;

            string token = JwtManager.GenerateToken(user.UserModel.Id);

            context.ResponseTrailers.Add("Authorization", token);
            return(new AuthorizationResponse
            {
                Token = token,
                User = user.asUser(),
                Status = ResponseFactory.createResponse(ResponseType.SUCCESS),
            });
        }
        public override async Task <GetMessageGroupsResponse> GetMessageGroups(GetMessageGroupsRequest request, ServerCallContext context)
        {
            RedisUserModel user = context.UserState["user"] as RedisUserModel;

            if (user == null)
            {
                return new GetMessageGroupsResponse()
                       {
                           Status = ResponseFactory.createResponse(ResponseType.UNAUTHORIZED)
                       }
            }
            ;

            RedisRoomModel room = await RedisRoomModel.GetRoomFromGuid(request.RoomId);

            if (room == null)
            {
                return new GetMessageGroupsResponse()
                       {
                           Status = ResponseFactory.createResponse(ResponseType.ROOM_DOES_NOT_EXIST)
                       }
            }
            ;

            List <GroupChatModel> groupChats = await room.GetPlayerGroupChats(user);

            GetMessageGroupsResponse response = new GetMessageGroupsResponse();

            foreach (var groupModel in groupChats)
            {
                response.MessageGroups.Add(await groupModel.asMessageGroup());
            }

            response.Status = ResponseFactory.createResponse(ResponseType.SUCCESS);
            return(response);
        }
        public override async Task <StartGameEarlyResponse> StartGameEarly(StartGameEarlyRequest request, ServerCallContext context)
        {
            RedisUserModel user = context.UserState["user"] as RedisUserModel;

            if (user == null)
            {
                return new StartGameEarlyResponse()
                       {
                           Status = ResponseFactory.createResponse(ResponseType.UNAUTHORIZED)
                       }
            }
            ;

            RedisRoomModel room = await RedisRoomModel.GetRoomFromGuid(request.RoomId);

            if (room == null)
            {
                return new StartGameEarlyResponse()
                       {
                           Status = ResponseFactory.createResponse(ResponseType.ROOM_DOES_NOT_EXIST)
                       }
            }
            ;

            if (room.RoomModel.CreatorId == user.UserModel.Id)
            {
                return(new StartGameEarlyResponse()
                {
                    Status = await room.StartGame(),
                });
            }
            return(new StartGameEarlyResponse()
            {
                Status = ResponseFactory.createResponse(ResponseType.PERMISSION_DENIED),
            });
        }
Example #12
0
        public static Response <byte[]> HttpPostDownloadData(string address, object data, Encoding encoding, string contentType = contentTypeJson, WebProxy proxy = null, string bearer = null)
        {
            try
            {
                //WebClient client = new WebClient();

                //client.Headers.Add(HttpRequestHeader.ContentType, contentType);
                //client.Headers.Add(HttpRequestHeader.UserAgent, "application!");

                //if (!string.IsNullOrWhiteSpace(bearer))
                //{
                //    client.Headers.Add(HttpRequestHeader.Authorization, $"Bearer {bearer}");
                //}

                //client.Encoding = encoding;

                //if (proxy?.Address != null)
                //{
                //    client.Proxy = proxy;
                //}
                var client = CreateWebClient(contentType, encoding, proxy, bearer);

                var stringData = Newtonsoft.Json.JsonConvert.SerializeObject(data, new Newtonsoft.Json.JsonSerializerSettings()
                {
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                });

                var result = client.UploadData(address, Encoding.UTF8.GetBytes(stringData));

                return(ResponseFactory.Create(result));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <byte[]>(ex.Message));
            }
        }
Example #13
0
        public static Response <byte[]> HttpGetDownloadData(string address, string contentType, WebProxy proxy = null)
        {
            try
            {
                //WebClient client = new WebClient();

                //client.Headers.Add(HttpRequestHeader.ContentType, contentType);
                //client.Headers.Add(HttpRequestHeader.UserAgent, "application!");

                //if (proxy?.Address != null)
                //{
                //    client.Proxy = proxy;
                //}
                var client = CreateWebClient(contentType, null, proxy, bearer: null);

                var resultByteArray = client.DownloadData(address);

                return(ResponseFactory.Create(resultByteArray));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <byte[]>(ex.Message));
            }
        }
Example #14
0
        public async Task Read200WithComments()
        {
            var sut = ResponseFactory.FromFiddlerLikeResponseFile(FilesFolder + @"happy/200_WithComments.txt");

            sut.StatusCode.Should().Be(HttpStatusCode.OK);

            var body = await sut.GetResponseString();

            body.Should().Be(@"{""Content"":""testing comments""}");

            sut.Content.Headers.ShouldContainHeader("Content-Type", "application/json; charset=utf-8");
            sut.Content.Headers.ShouldContainHeader("Expires", "Mon, 04 Mar 2019 07:17:49 GMT");
            sut.Content.Headers.ShouldContainHeader("Last-Modified", "Sun, 03 Mar 2019 07:17:48 GMT");

            sut.Headers.ShouldContainHeader("Date", "Sun, 03 Mar 2019 07:17:49 GMT");
            sut.Headers.ShouldContainHeader("Cache-Control", "public, max-age=86400");
            sut.Headers.ShouldContainHeader("Vary", "*");
            sut.Headers.ShouldContainHeader("X-AspNet-Version", "4.0.30319");
            sut.Headers.ShouldContainHeader("X-Powered-By", "ASP.NET");
            sut.Headers.ShouldContainHeader("Access-Control-Allow-Origin", "*");
            sut.Headers.ShouldContainHeader("CF-Cache-Status", "MISS");
            sut.Headers.ShouldContainHeader("CF-RAY", "4b19d532ce5419aa-SYD");
            sut.Headers.ShouldContainHeader("Server", "cloudflare");
        }
        private async Task HandleFilePostRequestAsync(HttpListenerContext context, FileSection section, string filePath)
        {
            if (File.Exists(filePath))
            {
                LogDebug($"File {filePath} already exists");
                ResponseFactory.BuildResponse(context, HttpStatusCode.Conflict, null);
                return;
            }
            var fileContent   = context.Request.InputStream;
            var contentLength = context.Request.ContentLength64;

            if (section.MaxFileSize > 0 && contentLength > section.MaxFileSize)
            {
                LogDebug($"Trying to create file of size {contentLength} in section {section.Name} with max size of {section.MaxFileSize}");
                ResponseFactory.BuildResponse(context, HttpStatusCode.RequestEntityTooLarge, null);
                return;
            }
            using (var file = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                await fileContent.CopyToAsync(file).ConfigureAwait(false);

                await file.FlushAsync();
            }
            GC.Collect(1);
            LogTrace($"Total memory: {GC.GetTotalMemory(true)}");
            LogDebug($"File {filePath} created");
            if (FilesPreprocessingEnabled)
            {
                var code = FilePreprocessController.EnqueueFile(filePath) ? HttpStatusCode.Accepted : HttpStatusCode.Created;
                ResponseFactory.BuildResponse(context, code, null);
            }
            else
            {
                ResponseFactory.BuildResponse(context, HttpStatusCode.Created, null);
            }
        }
Example #16
0
        public async Task HandleRequestAsync(HttpListenerContext context)
        {
            var response = context.Response;

            if (_statisticsAuthorizer != null)
            {
                if (await _statisticsAuthorizer.Invoke(context.Request))
                {
                    var responseBody = Statistics?.Serialize();
                    ResponseFactory.BuildResponse(context, HttpStatusCode.OK, responseBody, null, true);
                    response.ContentType = "text/plain";
                }
                else
                {
                    ResponseFactory.BuildResponse(context, HttpStatusCode.Forbidden, null);
                }
            }
            else
            {
                var responseBody = Statistics?.Serialize();
                ResponseFactory.BuildResponse(context, HttpStatusCode.OK, responseBody, null, true);
                response.ContentType = "text/plain";
            }
        }
Example #17
0
        public void Test_StateService_ResponseGeneration()
        {
            const string TestResponseString = "2900005404ae7306d073d512006c00004c4946585632000098ccad3a23613d1403000000017cdd0000";

            byte[] testMessage = GetResponseBufferFromHexString(TestResponseString);

            Response response = ResponseFactory.ConstructResponseFromBuffer(testMessage);

            Assert.IsNotNull(response, "ResponseFactory unexpectedly failed to deserialize the StateService message!");

            StateServiceResponse stateServiceResponse = response as StateServiceResponse;

            Assert.IsNotNull(response, "ResponseFactory did not produce a StateServiceResponse object!");

            // Check the internals of the response
            //
            MacAddress expectedMacAddress = new MacAddress(new byte[] { 0xd0, 0x73, 0xd5, 0x12, 0x00, 0x6c });

            Assert.AreEqual <MacAddress>(expectedMacAddress, stateServiceResponse.Target);
            Assert.AreEqual <UInt32>(108244484, stateServiceResponse.Source);
            Assert.AreEqual <byte>(0, stateServiceResponse.SequenceNumber);
            Assert.AreEqual <byte>(1, stateServiceResponse.Service);
            Assert.AreEqual <UInt32>(56700, stateServiceResponse.PortNumber);
        }
Example #18
0
        private static async Task <Response <Order> > CreatePayroll(Order order, DataLayerUnitOfWork unitOfWork, OrderRepository orderRepository)
        {
            var orderWithItems = await orderRepository.GetAsync(order.Id, new[]
            {
                nameof(Order.OrderItems)
            }).ConfigureAwait(false);

            var payroll = new Payroll
            {
                ClientId = order.ClientId,
                Date     = DateTime.Now,
                OrderId  = order.Id,
                Value    = orderWithItems.OrderItems.Sum(orderItem => orderItem.Price * orderItem.Quantity)
            };

            payroll = await unitOfWork.TrackingRepository <PayrollRepository>().CreateAsync(payroll).ConfigureAwait(false);

            if (payroll == null)
            {
                return(ResponseFactory <Order> .CreateResponse(false, ResponseCode.Error));
            }

            return(ResponseFactory <Order> .CreateResponse(true, ResponseCode.Success, order));
        }
Example #19
0
        public Respuesta AgregarVehiculo(DataVehiculo data)
        {
            log.Info("Agregar Vehiculo : " + data);

            try
            {
                SqlConnection conn = dataSource.getConnection();
                SqlCommand    cmd  = dataSource.getCommand(storeProcedureName, conn);

                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@Patente", SqlDbType.VarChar).Value         = data.Patente;
                cmd.Parameters.Add("@Marca", SqlDbType.NVarChar).Value          = data.Marca;
                cmd.Parameters.Add("@Modelo", SqlDbType.NVarChar).Value         = data.Modelo;
                cmd.Parameters.Add("@Anio", SqlDbType.VarChar).Value            = data.Anio;
                cmd.Parameters.Add("@TipoVehiculo", SqlDbType.NVarChar).Value   = data.Tipo_Vehiculo;
                cmd.Parameters.Add("@Contrato", SqlDbType.NVarChar).Value       = data.Contrato;
                cmd.Parameters.Add("@RazonSocial", SqlDbType.NVarChar).Value    = data.Razon_Social;
                cmd.Parameters.Add("@FechaExpiracion", SqlDbType.VarChar).Value = data.Fecha_Expiracion;
                cmd.Parameters.Add("@MotivoRechazo", SqlDbType.NVarChar).Value  = data.Motivo_Rechazo;

                AgregarParametrosSalida(cmd);

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
            catch (System.Exception ex)
            {
                log.Error("No es posible agregar vehículo", ex);
                throw new BusinessException("No es posible agregar vehículo", Errors.AGREGAR_VEHICULO_DAO, ex);
            }

            ValidarResultado(Errors.AGREGAR_VEHICULO_DAO);

            return(ResponseFactory.CreateSuccessResponse("Se agregó el vehículo correctamente"));
        }
Example #20
0
        public JsonResult GetMeals()
        {
            var meals = MealCore.GetAll();

            if (meals == null)
            {
                return(Json(ResponseFactory.ErrorReponse, JsonRequestBehavior.AllowGet));
            }

            var returnedModel = new List <MealViewModel>();

            foreach (var item in meals)
            {
                returnedModel.Add(new MealViewModel
                {
                    Id         = item.Id,
                    Calories   = item.Calories.Value.ToString("0.00"),
                    Name       = item.Name,
                    PictureUrl = item.PictureUrl
                });
            }

            return(Json(ResponseFactory.Success((int)ResponseCode.Success, returnedModel), JsonRequestBehavior.AllowGet));
        }
        public async Task <IActionResult> GetAllCustomersAsync(
            [FromQuery] PagingOptions pagingOptions,
            [FromQuery] SortOptions sortOptions,
            [FromQuery] SearchOptions searchOptions,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            pagingOptions.PageNumber = pagingOptions.PageNumber ?? ApiSettings.DefaultPageNumber;
            pagingOptions.PageSize   = pagingOptions.PageSize ?? ApiSettings.DefaultPageSize;

            var query = new GetCustomersPreviewQuery
            {
                PageNumber = pagingOptions.PageNumber.Value,
                PageSize   = pagingOptions.PageSize.Value,
                OrderBy    = sortOptions.OrderBy,
                Query      = searchOptions.Query
            };

            var result = await Mediator.Send(query, cancellationToken).ConfigureAwait(false);

            var customers = Mapper.Map <List <Customer> >(result);
            var response  = ResponseFactory.CreatePagedReponse(customers, typeof(CustomersController), query, ResponseStatus.Success, "1.0.0");

            return(Ok(response));
        }
Example #22
0
 public TrackDao(MagmaDawDbContext magmaDbContext)
 {
     this.magmaDbContext = magmaDbContext;
     responseFactory     = new ResponseFactory();
     response            = new Response();
 }
Example #23
0
 public PingController(ResponseFactory responseFactory)
 {
     this._responseFactory = responseFactory;
 }
 public HomeService(MagmaDawDbContext magmaDbContext)
 {
     responseFactory = new ResponseFactory();
     userDao         = new UserDao(magmaDbContext);
 }
        public async Task <IActionResult> AddDestinationAsync(
            [FromBody] CreateDestination command,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var result = await Mediator.Send(command, cancellationToken).ConfigureAwait(false);

            var desination = Mapper.Map <Destination>(result);

            return(Created(Url.Link(nameof(GetDestinationByIdAsync), new { result.Id }), ResponseFactory.CreateReponse(desination, typeof(CustomersController), ResponseStatus.Success, "1.0.0")));
        }
 public AudioEffectController(MagmaDawDbContext magmaDbContext)
 {
     audioEffectService = new AudioEffectService(magmaDbContext);
     responseFactory    = new ResponseFactory();
 }
Example #27
0
 public AudioEffectDao(MagmaDawDbContext magmaDbContext)
 {
     this.magmaDbContext = magmaDbContext;
     responseFactory     = new ResponseFactory();
     response            = new Response();
 }
Example #28
0
 public SlackController(DatabaseContext context, ResponseFactory responseFactory)
 {
     _context = context;
     this._responseFactory = responseFactory;
 }
Example #29
0
        public async Task <SingleResponse <Diet> > GenerateDiet(int id, DateTime date)
        {
            SingleResponse <User> user = await userService.GetById(id);

            try
            {
                double breakfastCalories      = user.Data.Daily_Calories * 0.3;
                double breakfastCarbohydrates = user.Data.Daily_Carbohydrates * 0.3;
                double breakfastProteins      = user.Data.Daily_Protein * 0.3;
                double breakfastLipids        = user.Data.Daily_Fats * 0.3;

                double lunchCalories      = user.Data.Daily_Calories * 0.4;
                double lunchCarbohydrates = user.Data.Daily_Carbohydrates * 0.4;
                double lunchProteins      = user.Data.Daily_Protein * 0.4;
                double lunchLipids        = user.Data.Daily_Fats * 0.4;

                double dinnerCalories      = user.Data.Daily_Calories * 0.3;
                double dinnerCarbohydrates = user.Data.Daily_Carbohydrates * 0.3;
                double dinnerProteins      = user.Data.Daily_Protein * 0.3;
                double dinnerLipids        = user.Data.Daily_Fats * 0.3;

                QueryResponse <Meal> breakfastMeals = await mealService.GetByCategory(Meal_Category.Café_da_manhã);

                QueryResponse <Meal> lunchMeals = await mealService.GetByCategory(Meal_Category.Almoço);

                QueryResponse <Meal> dinnerMeals = await mealService.GetByCategory(Meal_Category.Jantar);

                QueryResponse <Food> restrictionFoods = await userService.GetFoodsFromRestrictionByUserID(user.Data.ID);


                Diet        diet  = new Diet();
                List <Meal> meals = new List <Meal>();


                if (restrictionFoods.Data != null)
                {
                    List <Meal> restrictedMeals = new List <Meal>();

                    foreach (Meal meal in breakfastMeals.Data)
                    {
                        QueryResponse <FoodAmountPerMeal> foods = await mealService.GetMealFoodsById(meal.ID);

                        foreach (Food food in restrictionFoods.Data)
                        {
                            foreach (FoodAmountPerMeal foodAmount in foods.Data)
                            {
                                if (food.ID == foodAmount.FoodID)
                                {
                                    restrictedMeals.Add(meal);
                                }
                            }
                        }
                    }

                    foreach (Meal meal in lunchMeals.Data)
                    {
                        QueryResponse <FoodAmountPerMeal> foods = await mealService.GetMealFoodsById(meal.ID);

                        foreach (Food food in restrictionFoods.Data)
                        {
                            foreach (FoodAmountPerMeal foodAmount in foods.Data)
                            {
                                if (food.ID == foodAmount.FoodID)
                                {
                                    restrictedMeals.Add(meal);
                                }
                            }
                        }
                    }

                    foreach (Meal meal in dinnerMeals.Data)
                    {
                        QueryResponse <FoodAmountPerMeal> foods = await mealService.GetMealFoodsById(meal.ID);

                        foreach (Food food in restrictionFoods.Data)
                        {
                            foreach (FoodAmountPerMeal foodAmount in foods.Data)
                            {
                                if (food.ID == foodAmount.FoodID)
                                {
                                    restrictedMeals.Add(meal);
                                }
                            }
                        }
                    }

                    if (restrictedMeals.Count != 0)
                    {
                        foreach (Meal meal in restrictedMeals)
                        {
                            breakfastMeals.Data.Remove(meal);
                            lunchMeals.Data.Remove(meal);
                            dinnerMeals.Data.Remove(meal);
                        }
                    }
                }

                foreach (Meal item in breakfastMeals.Data)
                {
                    if (item.Total_Calories <= (breakfastCalories + breakfastCalories * 0.30) && item.Total_Calories >= (breakfastCalories - breakfastCalories * 0.30))
                    {
                        if (item.Total_Carbohydrates <= (breakfastCarbohydrates + breakfastCarbohydrates * 0.70) && item.Total_Carbohydrates >= (breakfastCarbohydrates - breakfastCarbohydrates * 0.70))
                        {
                            if (item.Total_Proteins <= (breakfastProteins + breakfastProteins * 0.95) && item.Total_Proteins >= (breakfastProteins - breakfastProteins * 0.95))
                            {
                                if (item.Total_Lipids <= (breakfastLipids + breakfastLipids * 0.95) && item.Total_Lipids >= (breakfastLipids - breakfastLipids * 0.95))
                                {
                                    meals.Add(item);
                                }
                            }
                        }
                    }
                }

                foreach (Meal item in lunchMeals.Data)
                {
                    if (item.Total_Calories <= (lunchCalories + lunchCalories * 0.30) && item.Total_Calories >= lunchCalories - lunchCalories * 0.30)
                    {
                        if (item.Total_Carbohydrates <= (lunchCarbohydrates + lunchCarbohydrates * 0.70) && item.Total_Carbohydrates >= (lunchCarbohydrates - lunchCarbohydrates * 0.70))
                        {
                            if (item.Total_Proteins <= (lunchProteins + lunchProteins * 0.95) && item.Total_Proteins >= (lunchProteins - lunchProteins * 0.95))
                            {
                                if (item.Total_Lipids <= (lunchLipids + lunchLipids * 0.95) && item.Total_Lipids >= (lunchLipids - lunchLipids * 0.95))
                                {
                                    meals.Add(item);
                                }
                            }
                        }
                    }
                }

                foreach (Meal item in dinnerMeals.Data)
                {
                    if (item.Total_Calories == (dinnerCalories + dinnerCalories * 0.30) && item.Total_Calories == (dinnerCalories - dinnerCalories * 0.30))
                    {
                        if (item.Total_Carbohydrates <= (dinnerCarbohydrates + dinnerCarbohydrates * 0.70) && item.Total_Carbohydrates >= (dinnerCarbohydrates - dinnerCarbohydrates * 0.70))
                        {
                            if (item.Total_Proteins <= (dinnerProteins + dinnerProteins * 0.95) && item.Total_Proteins >= (dinnerProteins - dinnerProteins * 0.95))
                            {
                                if (item.Total_Lipids <= (dinnerLipids + dinnerLipids * 0.95) && item.Total_Lipids >= (dinnerLipids - dinnerLipids * 0.95))
                                {
                                    meals.Add(item);
                                }
                            }
                        }
                    }
                }

                if (meals.Count != 3)
                {
                    Random rand = new Random();
                    meals.Add(breakfastMeals.Data.ElementAt(rand.Next(breakfastMeals.Data.Count())));
                    meals.Add(lunchMeals.Data.ElementAt(rand.Next(lunchMeals.Data.Count())));
                    meals.Add(dinnerMeals.Data.ElementAt(rand.Next(dinnerMeals.Data.Count())));
                }

                SingleResponse <Diet> dietResponse = new SingleResponse <Diet>();
                diet.Date   = date;
                diet.Meals  = meals;
                diet.UserID = id;
                return(ResponseFactory.SingleResponseSuccessModel <Diet>(diet));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.SingleResponseExceptionModel <Diet>(ex));
            }
        }
Example #30
0
 public void TestInitialize()
 {
     _mockApiCaller   = new MockApiCaller();
     _httpClient      = new HttpClient();
     _responseFactory = new ResponseFactory();
 }
Example #31
0
        /// <summary>
        /// Creates an <see cref="HttpResponseMessage"/> with <see cref="HttpStatusCode.InternalServerError"/>
        /// and the message <see cref="DefaultErrorMessage"/>
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        protected virtual void CreateErrorResponse(HttpActionExecutedContext actionExecutedContext)
        {
            var exceptionResponse = ResponseFactory.Exception(DefaultErrorMessage);

            actionExecutedContext.Response = ResponseGenerator.CreateResponse(actionExecutedContext.Request, exceptionResponse);
        }
Example #32
0
 public static IResponse Update(Customer customer)
 {
     return(ResponseFactory.NotImplemented("This feature will be available at the end of 2018."));
 }
 public void SetUp()
 {
     _factory = new ResponseFactory(AppDomain.CurrentDomain.BaseDirectory);
 }