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); }
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 = "Животное добавлено"; } }
private void assertUserExists(AnimalRequest animalRequest) { if (null == userService.GetUser(animalRequest.UserId)) { throw new ArgumentException("User with given userId does not exist"); } }
/// <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); }
public virtual IHttpActionResult OneAnimal(int zooId, int animalId) { var request = new AnimalRequest(); request.belongsToZooId = zooId; var animal = animalQuery.ResolveOne(request, animalId); return(Ok(animal)); }
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)); }
public void GivenIHavePutARequestWithType(int animalType) { request = new AnimalRequest(); request.Type = (Animal.AnimalType)animalType; request.UserId = createdUser.ID; request.Name = "Garfield"; requestedAnimalType = animalType; }
public IActionResult CreateAnimal(AnimalRequest animal) { var res = _dbService.CreateAnimal(animal); if (res == null) { return(BadRequest()); } return(Created("", res)); }
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)); }
public IActionResult AddAnimal(AnimalRequest request) { try { _service.InsertAnimal(request); return(Ok()); } catch (SqlException) { return(NotFound()); } }
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)); }
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); } } }
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 = "Животное удалено"; } }
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)); }
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(); } }
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 = "Запрос выполнен успешно"; } }
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); }
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 })); }
public IActionResult enrollStudent(AnimalRequest animalRequest) { throw new System.NotImplementedException(); }
public IActionResult enrollAnimal(AnimalRequest request) { return(_serviceDb.enrollStudent(request)); }
public IActionResult AddAnimal([FromBody] AnimalRequest animal) { return(StatusCode(200, _service.InsertAnimal(animal))); }
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(); }