Exemplo n.º 1
0
        private AnimalResponse SendRequest(AnimalRequest request)
        {
            string jsonRequest = JsonConvert.SerializeObject(request);

            byte[] msg = Encoding.UTF8.GetBytes(jsonRequest);
            // Отправляем данные через сокет
            sendSocket.Send(msg);
            // Получаем ответ от сервера
            int bytesRec = sendSocket.Receive(bytes);
            var json     = Encoding.UTF8.GetString(bytes, 0, bytesRec);
            var response = new AnimalResponse {
                IsSuccess = false
            };

            try
            {
                response = JsonConvert.DeserializeObject <AnimalResponse>(json);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message + "\nНе удалось десериализовать",
                                "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return(response);
        }
Exemplo n.º 2
0
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var request = new AnimalRequest
            {
                Animal = new Animal {
                    Title             = textBoxTitle.Text,
                    Latin_Title       = textBoxLatin_Title.Text,
                    Habitat           = textBoxHabitat.Text,
                    Protection_Status = comboBoxProtectionStatus.Text
                },

                Key  = textBoxTitle.Text,
                Type = AnimalRequestType.Add
            };
            var response = SendRequest(request);

            if (!response.IsSuccess)
            {
                labelResponseStatus.Text = response.ErrorMessage;
            }
            else
            {
                labelResponseStatus.Text = "Животное добавлено";
            }
        }
Exemplo n.º 3
0
 private void assertUserExists(AnimalRequest animalRequest)
 {
     if (null == userService.GetUser(animalRequest.UserId))
     {
         throw new ArgumentException("User with given userId does not exist");
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a new animal for a user based on the <c>AnimalRequest</c>.
        /// The enum value given there for the type of animal determines what kind of animal class is created
        /// </summary>
        /// <param name="animalRequest">the request that contains which type of animal and for which user.</param>
        /// <returns>the new <c>Animal</c> entity</returns>
        public Animal AddAnimal(AnimalRequest animalRequest)
        {
            assertUserExists(animalRequest);

            //TODO: better with string instead of enum numbers?
            Animal.AnimalType animalType = animalRequest.Type; //(Animal.AnimalType)Enum.ToObject(typeof(Animal.AnimalType), type);

            Animal newPet;

            switch (animalType)
            {
            case Animal.AnimalType.Cat:
                newPet = new Cat();
                break;

            case Animal.AnimalType.Dog:
                newPet = new Dog();
                break;

            case Animal.AnimalType.Parrot:
                newPet = new Parrot();
                break;

            default:
                throw new ArgumentException("Could not create specific animal type. Enum value is not handled.");
            }
            logger.LogInformation("Creating a new animal of type {0} for user {1}", new object[] { animalType.ToString(), animalRequest.UserId.ToString() });

            newPet.Name   = animalRequest.Name;
            newPet.UserId = animalRequest.UserId;

            databaseService.AddAnimal(newPet);
            return(newPet);
        }
Exemplo n.º 5
0
        public virtual IHttpActionResult OneAnimal(int zooId, int animalId)
        {
            var request = new AnimalRequest();

            request.belongsToZooId = zooId;
            var animal = animalQuery.ResolveOne(request, animalId);

            return(Ok(animal));
        }
Exemplo n.º 6
0
        public void TestAddAnimalWithInvalidUser()
        {
            AnimalRequest request = new AnimalRequest();

            request.UserId = 1234;
            userServiceMock.Setup(us => us.GetUser(1234)).Returns <User>(null);

            Assert.Throws <ArgumentException>(() => underTest.AddAnimal(request));
        }
Exemplo n.º 7
0
        public void GivenIHavePutARequestWithType(int animalType)
        {
            request        = new AnimalRequest();
            request.Type   = (Animal.AnimalType)animalType;
            request.UserId = createdUser.ID;
            request.Name   = "Garfield";

            requestedAnimalType = animalType;
        }
Exemplo n.º 8
0
        public IActionResult CreateAnimal(AnimalRequest animal)
        {
            var res = _dbService.CreateAnimal(animal);

            if (res == null)
            {
                return(BadRequest());
            }
            return(Created("", res));
        }
Exemplo n.º 9
0
        public virtual IHttpActionResult AllAnimals(int zooId, [FromUri] GridRequest request)
        {
            var proper = new AnimalRequest(request);

            proper.belongsToZooId = zooId;

            var animals = animalQuery.Resolve(proper);

            return(Ok(animals));
        }
Exemplo n.º 10
0
 public IActionResult AddAnimal(AnimalRequest request)
 {
     try
     {
         _service.InsertAnimal(request);
         return(Ok());
     }
     catch (SqlException)
     {
         return(NotFound());
     }
 }
Exemplo n.º 11
0
        public async Task <IActionResult> Create([FromBody] AnimalRequest animalRequest)
        {
            Animal animal = new Animal
            {
                Name   = animalRequest.Name,
                Age    = animalRequest.Age,
                Color  = animalRequest.Color,
                Weight = animalRequest.Weight
            };

            await _context.Animals.AddAsync(animal);

            await _context.SaveChangesAsync();

            return(CreatedAtAction("Create", new { id = animal.Id }, animal));
        }
Exemplo n.º 12
0
        public Animal InsertAnimal(AnimalRequest animal)
        {
            using (SqlConnection connection = new SqlConnection(ConnectionString))
                using (SqlCommand command = new SqlCommand())
                {
                    {
                        connection.Open();
                        SqlTransaction transcation = connection.BeginTransaction();
                        command.Transaction = transcation;
                        command.Connection  = connection;
                        command.Parameters.AddWithValue("name", animal.Name);
                        command.Parameters.AddWithValue("type", animal.AnimalType);
                        command.Parameters.AddWithValue("admissionDate", animal.AdmissionDate);
                        command.Parameters.AddWithValue("idOwner", animal.IdOwner);
                        command.CommandText = "INSERT INTO Animal VALUES (@name, @type, @admissionDate, @idOwner)";
                        command.ExecuteScalar();

                        command.CommandText = "SELECT IdAnimal FROM Animal WHERE name = @name AND idOwner = @idOwner";
                        SqlDataReader dr = command.ExecuteReader();
                        dr.Read();
                        int id = dr.GetInt32(0);
                        dr.Close();

                        foreach (Procedure p in animal.UnderwentProcedure)
                        {
                            command.Parameters.AddWithValue("id", id);
                            command.Parameters.AddWithValue("idProcedure", p.IdProcedure);
                            command.Parameters.AddWithValue("procedureDate", p.ProcedureDate);
                            command.CommandText = "INSERT INTO Procedure_Animal VALUES (@idProcedure, @id, @procedureDate)";
                            command.ExecuteScalar();
                            command.Parameters.Clear();
                        }

                        transcation.Commit();

                        Animal inserted = new Animal
                        {
                            Name          = animal.Name,
                            IdAnimal      = animal.IdAnimal,
                            IdOwner       = animal.IdOwner,
                            Type          = animal.AnimalType,
                            AdmissionDate = animal.AdmissionDate
                        };
                        return(inserted);
                    }
                }
        }
Exemplo n.º 13
0
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var request = new AnimalRequest
            {
                Key  = textBoxTitle.Text,
                Type = AnimalRequestType.Get
            };
            var response = SendRequest(request);

            if (!response.IsSuccess)
            {
                labelResponseStatus.Text = response.ErrorMessage;
            }
            else
            {
                labelResponseStatus.Text = "Животное удалено";
            }
        }
Exemplo n.º 14
0
        protected IOrderedQueryable <Animal> ProcessRequest(AnimalRequest request)
        {
            IQueryable <Animal> animals;

            if (request.belongsToZooId.HasValue)
            {
                animals = from zoo in this.context.Set <Entity.Model.Zoo>()
                          from a in zoo.Animals
                          where zoo.Id == request.belongsToZooId.Value
                          select a;
            }
            else
            {
                animals = from a in this.context.Set <Animal>()
                          select a;
            }

            return(animals.OrderBy(a => a.Id));
        }
Exemplo n.º 15
0
        public AnimalRequest CreateAnimal(AnimalRequest request)
        {
            using (SqlConnection con = new SqlConnection(connection))
                using (SqlCommand com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();
                    SqlTransaction transaction = con.BeginTransaction();
                    com.Transaction = transaction;

                    com.CommandText = "Insert Into Animal (Name, Type, AdmissionDate, IdOwner) Values (@Name, @Type, @AdmissionDate, @IdOwner)";
                    com.Parameters.AddWithValue("Name", request.name);
                    com.Parameters.AddWithValue("Type", request.type);
                    com.Parameters.AddWithValue("AdmissionDate", request.admissionDate);
                    com.Parameters.AddWithValue("IdOwner", request.idOwner);

                    com.ExecuteNonQuery();
                    transaction.Commit();
                }
            return(request);
        }
        public void InsertAnimal(AnimalRequest request)
        {
            using (var con =
                       new SqlConnection(@"Data Source=DESKTOP-5G2FL6J\SQLEXPRESS;Initial Catalog=APBD_4;Integrated Security=True"))
                using (var com = new SqlCommand())

                {
                    com.Connection = con;
                    var tran = con.BeginTransaction();

                    try
                    {
                        com.CommandText =
                            "insert into Animal (IdAnimal,Name,Type,AdmissionDate,IdOwner)" +
                            " values(@IdAnimal,@Name,@Type,@AdmissionDate,@IdOwner)";
                        com.Parameters.AddWithValue("IdAnimal", request.IdAnimal);
                        com.Parameters.AddWithValue("Name", request.Name);
                        com.Parameters.AddWithValue("Type", request.AnimalType);
                        com.Parameters.AddWithValue("AdmissionDate", request.DateOfAdmision);
                        com.Parameters.AddWithValue("IdOwner", request.IdOwner);

                        foreach (Procedure procedure in request.Procedures)
                        {
                            com.CommandText =
                                "insert into Procedure_Animal (IdProcedure,IdAnimal,Date)" +
                                " values(@IdProcedure,@IdAnimal,@Date)";
                            com.Parameters.AddWithValue("IdProcedure", procedure.IdProcedure);
                            com.Parameters.AddWithValue("IdAnimal", request.IdAnimal);
                            com.Parameters.AddWithValue("Date", procedure.Date);
                        }
                    }
                    catch
                    {
                        tran.Rollback();
                        throw new Exception();
                    }
                    tran.Commit();
                    com.ExecuteNonQuery();
                }
        }
Exemplo n.º 17
0
        private void buttonGet_Click(object sender, EventArgs e)
        {
            var request = new AnimalRequest
            {
                Key  = textBoxTitle.Text,
                Type = AnimalRequestType.Get
            };
            var response = SendRequest(request);

            if (!response.IsSuccess)
            {
                labelResponseStatus.Text = response.ErrorMessage;
            }
            else
            {
                textBoxTitle.Text             = response.Animal.Title;
                textBoxLatin_Title.Text       = response.Animal.Latin_Title;
                textBoxHabitat.Text           = response.Animal.Habitat;
                comboBoxProtectionStatus.Text = response.Animal.Protection_Status;
                labelResponseStatus.Text      = "Запрос выполнен успешно";
            }
        }
Exemplo n.º 18
0
        public void TestAddAnimal()
        {
            User testUser = new User();

            testUser.AccountName = "Andy";
            testUser.ID          = 1234;

            AnimalRequest request = new AnimalRequest();

            request.Name   = "Bello";
            request.Type   = Animal.AnimalType.Dog;
            request.UserId = testUser.ID;

            userServiceMock.Setup(us => us.GetUser(1234)).Returns(testUser);

            Animal newAnimal = underTest.AddAnimal(request);

            Assert.NotNull(newAnimal);
            Assert.Equal(Animal.AnimalType.Dog.ToString(), newAnimal.AnimalTypus);
            Assert.Equal("Bello", newAnimal.Name);
            Assert.Equal(testUser.ID, newAnimal.UserId);
        }
Exemplo n.º 19
0
 public JsonResult <Estado> Post(AnimalRequest animal_)
 {
     if (animal_ == null)
     {
         return(Json(new Estado {
             detalle = "Faltan parámetros", estado = false
         }));
     }
     using (SqlConnection conexion = new SqlConnection(ConfigurationManager.ConnectionStrings["cadenaConexion"].ConnectionString))
     {
         conexion.Open();
         using (SqlCommand cmd = new SqlCommand("INSERT INTO animales VALUES(@id,@nombre,@peso,@altura,@habitat,@nombreCientifico,@vertebrado,@oviparo,@tipoAlimentacion)", conexion))
         {
             try
             {
                 cmd.Parameters.AddWithValue("@id", animal_.id);
                 cmd.Parameters.AddWithValue("@nombre", animal_.nombre);
                 cmd.Parameters.AddWithValue("@peso", animal_.peso);
                 cmd.Parameters.AddWithValue("@altura", animal_.altura);
                 cmd.Parameters.AddWithValue("@habitat", animal_.habitat);
                 cmd.Parameters.AddWithValue("@nombreCientifico", animal_.nombreCientifico);
                 cmd.Parameters.AddWithValue("@vertebrado", animal_.vertebrado);
                 cmd.Parameters.AddWithValue("@oviparo", animal_.oviparo);
                 cmd.Parameters.AddWithValue("@tipoAlimentacion", animal_.tipoAlimentacionValor);
                 cmd.ExecuteNonQuery();
             }
             catch (Exception ex)
             {
                 return(Json(new Estado {
                     detalle = ex.Message, estado = false
                 }));
             }
         }
     }
     return(Json(new Estado {
         detalle = "", estado = true
     }));
 }
Exemplo n.º 20
0
 public IActionResult enrollStudent(AnimalRequest animalRequest)
 {
     throw new System.NotImplementedException();
 }
 public IActionResult enrollAnimal(AnimalRequest request)
 {
     return(_serviceDb.enrollStudent(request));
 }
Exemplo n.º 22
0
 public IActionResult AddAnimal([FromBody] AnimalRequest animal)
 {
     return(StatusCode(200, _service.InsertAnimal(animal)));
 }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            // Буфер для входящих данных
            byte[] bytes = new byte[10240];

            // Соединяемся с удаленным устройством

            // Устанавливаем удаленную точку для сокета
            IPHostEntry ipHost     = Dns.GetHostEntry("localhost");
            IPAddress   ipAddr     = ipHost.AddressList[0];
            IPEndPoint  ipEndPoint = new IPEndPoint(ipAddr, 11000);

            Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // Соединяем сокет с удаленной точкой
            sender.Connect(ipEndPoint);
            while (true)
            {
                try
                {
                    AnimalRequest request = null;
                    Console.Write("Действие (add, get): ");
                    string action = Console.ReadLine();
                    if (action == "add")
                    {
                        string title = Console.ReadLine();
                        request = new AnimalRequest
                        {
                            Animal = new Animal {
                                Title = title
                            },
                            Key  = title,
                            Type = AnimalRequestType.Add
                        };
                    }
                    else if (action == "get")
                    {
                        string key = Console.ReadLine();
                        request = new AnimalRequest
                        {
                            Key  = key,
                            Type = AnimalRequestType.Get
                        };
                    }
                    else
                    {
                        continue;
                    }
                    string jsonRequest = JsonConvert.SerializeObject(request);
                    byte[] msg         = Encoding.UTF8.GetBytes(jsonRequest);
                    // Отправляем данные через сокет
                    sender.Send(msg);
                    // Получаем ответ от сервера
                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Запрос к серверу: {0}\n\n", jsonRequest);
                    Console.WriteLine("Ответ от сервера: {0}\n\n", Encoding.UTF8.GetString(bytes, 0, bytesRec));
                }
                catch (Exception)
                {
                    break;
                }
            }
            // Освобождаем сокет
            sender.Shutdown(SocketShutdown.Both);
            sender.Close();
        }