Beispiel #1
0
        public GumballMachineProxy(int numberOfBalls, string location)
        {
            var getResponse = _client.GetAsync($"https://localhost:5001/api/gumballmachine/{location}").Result;

            if (getResponse.IsSuccessStatusCode)
            {
                var getGumballMachineDto = JsonSerializer.Deserialize <GumballMachineDto>(getResponse.Content.ReadAsStringAsync().Result, new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });
                _remoteMachine = new GumballMachine(getGumballMachineDto.Inventory, getGumballMachineDto.Location);
                ((GumballMachine)_remoteMachine).CurrentState = Helper.StateFactory(getGumballMachineDto.CurrentState.Name, new GumballMachine(getGumballMachineDto.Inventory, getGumballMachineDto.Location));
            }
            else if (getResponse.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                var createGumballMachineDto = new CreateGumballMachineDto {
                    Location = location, Inventory = numberOfBalls
                };
                HttpContent content  = new StringContent(JsonSerializer.Serialize(createGumballMachineDto), Encoding.UTF8, "application/json");
                var         response = _client.PostAsync("https://localhost:5001/api/gumballmachine", content).Result;

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"An error has occurred. HTTP status code: {response.StatusCode}");
                }

                var gumballMachineDto = JsonSerializer.Deserialize <GumballMachineDto>(response.Content.ReadAsStringAsync().Result, new JsonSerializerOptions {
                    PropertyNameCaseInsensitive = true
                });
                _remoteMachine = new GumballMachine(gumballMachineDto.Inventory, gumballMachineDto.Location);
                ((GumballMachine)_remoteMachine).CurrentState = Helper.StateFactory(gumballMachineDto.CurrentState.Name, new GumballMachine(gumballMachineDto.Inventory, gumballMachineDto.Location));
            }
        }
        public IActionResult CreateGumballMachine([FromBody] CreateGumballMachineDto gumballMachine)
        {
            if (_machines.Any(m => m.Location.ToLower() == gumballMachine.Location.ToLower()))
            {
                return(Conflict());
            }

            var gm = new GumballMachine(gumballMachine.Inventory, gumballMachine.Location);

            _machines.Add(gm);
            var gumballMachineDto = new GumballMachineDto
            {
                Location     = gm.Location,
                Inventory    = gm.Count,
                CurrentState = new CurrentStateDto {
                    Name = gm.CurrentState.GetType().Name
                }
            };

            return(CreatedAtRoute("GetGumballMachine", new { location = gumballMachine.Location }, gumballMachineDto));
        }