public IActionResult EmployeeAdd(XMLEmployee employee) { if (!ModelState.IsValid) { BadRequest(ModelState); } var lempxml = new List <XMLEmployee>(); lempxml.Add(employee); var lemp = XMLActions.ToEmployee(lempxml); var emp = lemp.First(); //Check if we have already the same object with criteria Matching Name var emps = _repo.GetAll().Where(x => x.Name.Replace(" ", "").Replace(",", "").Replace(".", "").Contains(emp.Name.Replace(" ", "").Replace(",", "").Replace(".", ""))); if (emps.Count() > 0) { ModelState.AddModelError("Error", "Person with the same name exists. You may want to use Update functionality to update this person"); return(BadRequest(ModelState)); } _repo.Create(emp); return(Ok(emp)); }
public async Task TestThatPostAddNotValidIdNegative() { //send request to the server to /Add XMLEmployee xemmpl = new XMLEmployee("-1", "AQA", "Strong", "John Doe", "2500", "3"); HttpContent content = new StringContent(JsonConvert.SerializeObject(xemmpl)); content.Headers.ContentType.MediaType = MediaTypeNames.Application.Json; HttpResponseMessage response = await _client.PostAsync(urladd, content); //Verify that the we have NotOK status code Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest, "Sorry, the response status is not BadRequest"); }
public async Task TestThatPostAddValidWithValidJson() { //send request to the server to /Add XMLEmployee xempl = new XMLEmployee("10", "AQA", "Strong", "John Doe", "2500", "3"); //xempl.Name = ""; HttpContent content = new StringContent(JsonConvert.SerializeObject(xempl)); content.Headers.ContentType.MediaType = MediaTypeNames.Application.Json; HttpResponseMessage response = await _client.PostAsync(urladd, content); //debug var message = await response.Content.ReadAsStringAsync(); //Verify that the we have NotOK status code Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Sorry, the response status is not OK"); }
public async Task TestThatPostAddValidJsonButExistingData() { //send request to the server to /Add XMLEmployee xempl = new XMLEmployee("10", "SDET", "Senior", "John Doe Jr", "2500", "3"); //xempl.Name = ""; HttpContent content = new StringContent(JsonConvert.SerializeObject(xempl)); content.Headers.ContentType.MediaType = MediaTypeNames.Application.Json; HttpResponseMessage response = await _client.PostAsync(urladd, content); //Verify that the we have NotOK status code Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "Sorry, the response status is not OK"); //Try to add the same object response = await _client.PostAsync(urladd, content); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode, "Sorry, the response status is not BadRequest"); }
public async Task <IActionResult> AddFile(IFormFileCollection filestruct) { switch (type) { case "employees": foreach (var file in filestruct) { using (var fileStream = file.OpenReadStream()) { try { _logger.LogInformation("Начали парсинг"); XmlDocument doc = new XmlDocument(); doc.Load(fileStream); var deptsBase = _context.Departments.ToList(); XmlNode deptNodes = doc.DocumentElement.SelectSingleNode("/Данные/Подразделения"); foreach (XmlNode nodeDept in deptNodes.ChildNodes) { var dNew = new XMLDepartment() { Name = nodeDept.Attributes["Наименование"].Value.Trim(), GUID = nodeDept.Attributes["GUID"].Value.Trim().ToUpper(), Parent = nodeDept.Attributes["Родитель"].Value.Trim().ToUpper(), }; var dOld = deptsBase.FirstOrDefault(d => d.Idguid1C.ToString().ToUpper() == dNew.GUID.ToUpper()); var dParentNew = deptsBase.FirstOrDefault(d => d.Idguid1C.ToString().ToUpper() == dNew.Parent.ToUpper()); if (dParentNew == null && !string.IsNullOrEmpty(dNew.Parent)) { dParentNew = new Department() { Name = "Подразделение отсутствует в списке", Idguid1C = new Guid(dNew.Parent), }; _context.Departments.Add(dParentNew); deptsBase.Add(dParentNew); } if (dOld == null) { dOld = new Department(); _context.Departments.Add(dOld); deptsBase.Add(dOld); } dOld.Name = dNew.Name; dOld.Idguid1C = new Guid(dNew.GUID); if (dParentNew != null) { dOld.Parent = dParentNew; } } await _context.SaveChangesAsync(); deptsBase = await _context.Departments.ToListAsync(); var empBase = await _context.Employees.ToListAsync(); XmlNode recruits = doc.DocumentElement.SelectSingleNode("/Данные/Сотрудники"); foreach (XmlNode nodeRecruit in recruits.ChildNodes) { var eNew = new XMLEmployee() { Email = nodeRecruit.Attributes["Email"].Value, GazPhone = CutPhone(nodeRecruit.Attributes["ГазовыйТелефон"].Value), InnerPhone = nodeRecruit.Attributes["ВнутреннийТелефон"] != null?CutPhone(nodeRecruit.Attributes["ВнутреннийТелефон"].Value) : "", WorkPhone = CutPhone(nodeRecruit.Attributes["СлужебныйТелефон"].Value), MobilePhone = CutPhone(nodeRecruit.Attributes["МобильныйТелефон"].Value), Birthsday = nodeRecruit.Attributes["ДатаРождения"].Value, Department = nodeRecruit.Attributes["Подразделение"].Value.ToUpper(), Role = nodeRecruit.Attributes["Должность"].Value, Name = nodeRecruit.Attributes["Наименование"].Value, City = nodeRecruit.Attributes["Город"].Value, GUID = nodeRecruit.Attributes["GUID"].Value.ToUpper(), Status = nodeRecruit.Attributes["Состояние"].Value, StatusTill = nodeRecruit.Attributes["СостояниеДействуетДо"].Value, }; var eOld = empBase.FirstOrDefault(d => d.Idguid1C.ToString().ToUpper() == eNew.GUID.ToUpper()); // Если не нашли по ID, возможно есть по ФИО или email, тогда надо обновить Guid у старого на новый if (eOld == null) { eOld = empBase.FirstOrDefault(d => d.Name.ToUpper() == eNew.Name.ToUpper() && d.City == eNew.City && d.Position == eNew.Role); eOld.Idguid1C = new Guid(eNew.GUID); } var eDeptNew = deptsBase.FirstOrDefault(d => d.Idguid1C.ToString().ToUpper() == eNew.Department.ToUpper()); if (eOld == null) { eOld = new Employee(); await _context.Employees.AddAsync(eOld); empBase.Add(eOld); } else { // Пропускаем всех, кто уже был в базе continue; } eOld.Name = eNew.Name; eOld.Idguid1C = new Guid(eNew.GUID); eOld.Address = eNew.Address; eOld.City = eNew.City; eOld.Email = eNew.Email; eOld.GazPhone = eNew.GazPhone; eOld.InnerPhone = eNew.InnerPhone; eOld.MobilePhone = eNew.MobilePhone; eOld.WorkPhone = eNew.WorkPhone; eOld.Position = eNew.Role; if (string.IsNullOrWhiteSpace(eNew.Status)) { eOld.Status = (short)EEmployeeStatus.Working; eOld.StatusTill = null; } // TODO: переделать на атрибуты else if (eNew.Status.Contains("отпуск")) { eOld.Status = (short)EEmployeeStatus.Vacation; } else if (eNew.Status.Contains("больнич")) { eOld.Status = (short)EEmployeeStatus.Sickness; } else if (eNew.Status.Contains("удал")) { eOld.Status = (short)EEmployeeStatus.Remote; } else { eOld.Status = (short)EEmployeeStatus.Other; } DateTime dt; if (DateTime.TryParse(eNew.Birthsday, out dt)) { eOld.Birthsday = dt; } if (DateTime.TryParse(eNew.StatusTill, out dt)) { eOld.StatusTill = dt; } if (eDeptNew == null && !string.IsNullOrEmpty(eNew.Department)) { eDeptNew = new Department() { Name = "Подразделение отсутствует в списке", Idguid1C = new Guid(eNew.Department), }; _context.Departments.Add(eDeptNew); deptsBase.Add(eDeptNew); } if (eDeptNew != null) { eOld.Department = eDeptNew; } } await _context.SaveChangesAsync(); } catch (Exception ex) { throw ex; } } } break; default: throw new Exception("Неизвестный тип импорта"); } return(Ok(new { success = "true" })); }