public async Task <EquipoTransporte> RegisterEquipoTransporte(EquipoTransporte eq, Guid OrdenReciboId) { using (var transaction = _context.Database.BeginTransaction()) { var max = await _context.EquipoTransporte.MaxAsync(x => x.Codigo); if (max == null) { max = "EQ00000001"; } max = "EQ" + (Convert.ToInt64(max.Substring(2, 8)) + 1).ToString().PadLeft(8, '0'); eq.Codigo = max; eq.FechaRegistro = DateTime.Now; eq.PropietarioId = eq.PropietarioId; // var userDb = await _context.EquipoTransporte.SingleOrDefaultAsync(x=>x.Id == user.Id); await _context.AddAsync <EquipoTransporte>(eq); await _context.SaveChangesAsync(); // var ordenDb = await _context.OrdenesRecibo.SingleOrDefaultAsync(x=>x.Id == OrdenReciboId); // ordenDb.EquipoTransporteId = eq.Id; // await _context.SaveChangesAsync(); transaction.Commit(); // transaction.Dispose(); return(eq); } }
public async Task <IActionResult> PostValue([FromBody] Value entity) { await _context.AddAsync(entity); await _context.SaveChangesAsync(); return(Ok()); }
public async Task <UserAccessResponse> CreateAsync(UserAccess model) { var entity = _mapper.Map <Usuario>(model); await _context.AddAsync(entity); if (await _context.SaveChangesAsync() > 0) { var user = _mapper.Map <UserAccessResponse>(entity); return(user); } return(null); }
public async Task InserirHabilidadesFuncionarioAsync(Funcionario funcionario) { foreach (var habilidade in funcionario.Habilidades) { await dataContext.AddAsync(new FuncionarioHabilidades { FuncionarioId = funcionario.Id, HabilidadeId = habilidade.Id }); } await dataContext.SaveChangesAsync(); }
public async Task CreateUserAsync(UserDto model) { model.Password.CreatePasswordHash(out string hashedPassword); var theUser = new Users() { Email = model.Email, Name = model.Name, Surname = model.Surname, Password = hashedPassword }; await _dataContext.AddAsync(theUser); await _dataContext.SaveChangesAsync(); }
public async Task <Tuple <bool, string, Comment> > Add(AddCommentViewModel commentViewModel, int currentUser) { try { var comment = _mapper.Map <Comment>(commentViewModel); comment.Level = 1; await _context.AddAsync(comment); await _context.SaveChangesAsync(); await _context.AddAsync(new CommentDetail { CommentID = comment.ID, UserID = comment.UserID, Seen = true }); await _context.SaveChangesAsync(); var alert = await AlertComment(comment.TaskID, comment.UserID, commentViewModel.ClientRouter); var task = await _context.Tasks.FindAsync(comment.TaskID); if (!currentUser.Equals(task.CreatedBy)) { alert.Item1.Add(task.CreatedBy); var listUsers = alert.Item1.Where(x => x != currentUser).Distinct().ToList(); await _notificationService.Create(new CreateNotifyParams { AlertType = Data.Enum.AlertType.PostComment, Message = alert.Item2, Users = listUsers, TaskID = comment.TaskID, URL = alert.Item3, UserID = comment.UserID }); await _hubContext.Clients.All.SendAsync("ReceiveMessage", listUsers, "message"); //await _hubContext.Clients.All.SendAsync("ReceiveMessageForCurd", listUsers, "message"); return(Tuple.Create(true, string.Join(",", listUsers.ToArray()), comment)); } else { return(Tuple.Create(true, string.Empty, comment)); } } catch (Exception ex) { return(Tuple.Create(false, string.Empty, new Comment())); } }
public async Task <Income> Add(Income income, int userId) { try { if (income == null) { return(null); } var category = await GetIncomeCategory(income.Category.Id); if (category == null) { return(null); } income.UserId = userId; income.Category = category; await _context.AddAsync(income); await _context.SaveChangesAsync(); return(income); } catch (Exception) { return(null); } }
public async Task AddItem(SingleItemDto itemDto) { Item itemToSave = Mapper.Map <Item>(itemDto); await dataContext.AddAsync(itemToSave); await dataContext.SaveChangesAsync(); }
public async void AddCar(CarModels carToAdd) { if (carToAdd != null) { await _context.AddAsync(carToAdd); } }
public async Task UpdatePatientLocation(string patientId, int locationId, int accountId, int hospitalUnitId, int newHospitalUnitId, int encounterId) { var patientQueue = await _context.PatientQueue.Where(q => q.PatientId == patientId && q.EncounterId == encounterId && q.LocationId == locationId && q.AccountId == accountId && q.HospitalUnitId == hospitalUnitId && q.isCurrent == true).FirstOrDefaultAsync(); if (patientQueue != null) { patientQueue.isCurrent = false; patientQueue.ChangedLocationAt = DateTime.Now; _context.Update(patientQueue); await _context.SaveChangesAsync(); PatientQueue newQueue = new PatientQueue(); newQueue = patientQueue; newQueue.isCurrent = true; newQueue.DateAdded = DateTime.Now; newQueue.ChangedLocationAt = null; newQueue.HospitalUnitId = newHospitalUnitId; newQueue.PatientQueueId = 0; await _context.AddAsync(newQueue); await _context.SaveChangesAsync(); //_context.Update(patientQueue); //await _context.SaveChangesAsync(); } }
public static void MapWebService(this IEndpointRouteBuilder app) { app.MapGet($"{BASEURL}/{{id}}", async context => { long key = long.Parse(context.Request.RouteValues["id"] as string); DataContext data = context.RequestServices.GetService <DataContext>(); Product p = data.Products.Find(key); if (p == null) { context.Response.StatusCode = StatusCodes.Status404NotFound; } else { context.Response.ContentType = "application/json"; await context.Response .WriteAsync(JsonSerializer.Serialize <Product>(p)); } }); app.MapGet(BASEURL, async context => { DataContext data = context.RequestServices.GetService <DataContext>(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer .Serialize <IEnumerable <Product> >(data.Products)); }); app.MapPost(BASEURL, async context => { DataContext data = context.RequestServices.GetService <DataContext>(); Product p = await JsonSerializer.DeserializeAsync <Product>(context.Request.Body); await data.AddAsync(p); await data.SaveChangesAsync(); context.Response.StatusCode = StatusCodes.Status200OK; }); }
public async Task <IActionResult> Post(GroupOfIndicatorsModel groupOfIndicatorsModel) { groupOfIndicatorsModel.TypeOfForm = await _dataContext.TypeOfForm.FirstOrDefaultAsync(i => i.Id == groupOfIndicatorsModel.TypeOfForm.Id); var model = await _dataContext.GroupOfIndicators.FirstOrDefaultAsync(i => i.Name == groupOfIndicatorsModel.Name); if (model != null) { model.TypeOfForm = groupOfIndicatorsModel.TypeOfForm; _dataContext.GroupOfIndicators.Update(model); } else { await _dataContext.AddAsync(groupOfIndicatorsModel); } int?x = await _dataContext.SaveChangesAsync(); if (x.HasValue) { return(Ok(true)); } else { return(BadRequest("Произошла ошибка")); } }
public async Task CreateLocation(Location location) { location.Deleted = false; await _dataContext.AddAsync(location); await _dataContext.SaveChangesAsync(); }
public async Task <IActionResult> Search(string url, string searchedtext) { try { WebRequest request = HttpWebRequest.Create(url); WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string sourceText = reader.ReadToEnd(); int counter = 0; int location = sourceText.IndexOf(searchedtext); while (location != -1) { location = sourceText.IndexOf(searchedtext, location + 1); counter++; } var model = new UrlSearch(); model.UserId = (int)HttpContext.Session.GetInt32("userId"); model.SearchDate = DateTime.Now; model.SearchUrl = url.Trim().ToString(); model.SearchedTerm = searchedtext.ToString(); model.CountFoundTerm = (int)counter; HttpContext.Session.SetString("result", "The Url :" + url + "\nThe Searched Term :" + searchedtext + "\nCount :" + counter); await _context.AddAsync(model); await _context.SaveChangesAsync(); } catch { HttpContext.Session.SetString("result", "The Url is not valid"); } return(Redirect("/Home/SearchResult")); }
public async Task <BrandAccessResponse> CreateAsync(BrandAccess model) { var entity = _mapper.Map <Marca>(model); await _context.AddAsync(entity); return(await _context.SaveChangesAsync() > 0 ? _mapper.Map <BrandAccessResponse>(entity) : null); }
public async Task <Response> AddProject(ProjectRequest request) { try { ProjectEntity project = new() { Name = request.Name, Description = request.Description, StartDate = request.StartDate, EndDate = request.EndDate, State = State.Proceso }; await _context.AddAsync(project); await _context.SaveChangesAsync(); return(new Response { IsSuccess = true, Message = "Project created successfully", Result = project }); } catch (Exception ex) { return(new Response { IsSuccess = false, Message = ex.Message }); } }
public async static Task <int> UpdateWholeDatabase() { using (var context = new DataContext()) { var Base = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_"; var countries = DataParser.ParseRequest(RestClient.MakeRequest(Base + "confirmed_global.csv"), RestClient.MakeRequest(Base + "recovered_global.csv"), RestClient.MakeRequest(Base + "deaths_global.csv")); context.Countries.RemoveRange(context.Countries); context.Cases.RemoveRange(context.Cases); foreach (var country in countries) { await context.AddAsync(country); await context.AddRangeAsync(country.Confirmed); //await context.AddRangeAsync(country.Recovered); await context.AddRangeAsync(country.Deaths); } return(await context.SaveChangesAsync()); } }
public async Task AddClient(ClientInformation clientInformation) { var client = _mapper.Map <Client>(clientInformation); await _context.AddAsync(client); await _context.SaveChangesAsync(); }
public async Task <ServiceResponse <GetCharacterDto> > AddWeapon(AddWeaponDto newWeapon) { var response = new ServiceResponse <GetCharacterDto>(); var character = await _context.Characters .FirstOrDefaultAsync(c => c.Id == newWeapon.CharacterId && c.User.Id == GetSecurityUserId()); if (character == null) { response.Success = false; response.Message = "Cannot Add weapon."; return(response); } //create a new instace of weapon with mapper var weapon = _mapper.Map <Weapon>(newWeapon); weapon.Character = character; //TODO assign with automapper await _context.AddAsync(weapon); await _context.SaveChangesAsync(); response.Data = _mapper.Map <GetCharacterDto>(character); return(response); }
private async System.Threading.Tasks.Task CloneTask(List <Data.Models.Task> tasks, int projectId) { int parentID = 0; foreach (var item in tasks) { if (item.JobTypeID == (int)Data.Enum.JobType.Project) { if (item.Level == 1) { parentID = 0; } var itemAdd = new Data.Models.Task { JobName = item.JobName, JobTypeID = item.JobTypeID, periodType = item.periodType, OCID = item.OCID, CreatedBy = item.CreatedBy, FromWhoID = item.FromWhoID, Priority = item.Priority, Level = item.Level, ProjectID = projectId, ParentID = parentID }; itemAdd.CreatedDate = DateTime.Now.Date.AddDays(1); await _context.AddAsync(itemAdd); await _context.SaveChangesAsync(); parentID = itemAdd.ID; } } }
public async Task <ActionResult <List <Employee> > > CreateEmployees(EmployeeResource resource) { var newEmployee = _mapper.Map <EmployeeResource, Employee>(resource); newEmployee.Id = Guid.NewGuid(); newEmployee.FullName = newEmployee.Name + " " + newEmployee.Surname; newEmployee.CreationDate = DateTime.Now; newEmployee.UpdateDate = DateTime.Now; newEmployee.Age = DateTime.Today.Year - resource.DateOfBirth.Year; if (resource.Skills.Count > 0) { foreach (var skill in resource.Skills) { _context.EmployeeSkills.Add(new EmployeeSkill { EmployeeId = newEmployee.Id, SkillId = skill.Id }); } } await _context.AddAsync(newEmployee); await _context.SaveChangesAsync(); return(Ok(newEmployee)); }
public async Task <IActionResult> CreateOrder([FromBody] Order order) { if (ModelState.IsValid) { order.OrderId = 0; order.Shipped = false; order.Payment.Total = GetPrice(order.Products); ProcessPayment(order.Payment); if (order.Payment.AuthCode != null) { await _context.AddAsync(order); await _context.SaveChangesAsync(); return(Ok(new { orderId = order.OrderId, authCode = order.Payment.AuthCode, amount = order.Payment.Total })); } else { return(BadRequest("Payment rejected.")); } } return(BadRequest(ModelState)); }
public async Task <Result <GoodsReceivingOfReturnResponse> > Handle(CreateGoodsReceivingOfReturnCommand request, CancellationToken cancellationToken) { var check = await _context.MerchandiseReturnProposals .FirstOrDefaultAsync(x => x.Id == request.MerchandiseReturnProposalId && x.Status == MerchandiseReturnProposalStatus.Processing); if (check == null) { return(new Result <GoodsReceivingOfReturnResponse>( new NotFoundException() )); } var goodsReceivingOfReturn = _mapper.Map <GoodsReceivingOfReturn>(request); goodsReceivingOfReturn.Status = GoodsReceivingOfReturnStatus.New; await _context.AddAsync(goodsReceivingOfReturn); var created = await _context.SaveChangesAsync(); if (created > 0) { return(new Result <GoodsReceivingOfReturnResponse>( _mapper.Map <GoodsReceivingOfReturnResponse>(goodsReceivingOfReturn) )); } return(new Result <GoodsReceivingOfReturnResponse>( new BadRequestException(new ApiError("Tạo phiếu nhập kho trả hàng thất bại, vui lòng thử lại")) )); }
public async Task <Spending> Add(Spending spending, int userId) { try { if (spending == null) { return(null); } var category = await GetSpendingCategory(spending.Category.Id); if (category == null) { return(null); } spending.UserId = userId; spending.Category = category; await _context.AddAsync(spending); await _context.SaveChangesAsync(); return(spending); } catch (Exception) { return(null); } }
public async Task <AnualBalance> Add(AnualBalance anualBalance, int userId) { try { //Validates model. if (anualBalance == null) { return(null); } //Assign the validated user id to the Anual Balance anualBalance.UserId = userId; if (!await UniqueYear(userId, anualBalance.Year)) { return(null); } //Initialize the anual balance result. anualBalance.Result = 0; anualBalance.Positive = true; await _context.AddAsync(anualBalance); await _context.SaveChangesAsync(); return(anualBalance); } catch (Exception) { return(null); } }
public async Task CreateDepartment(string name, int MyId) { try { // save department var dept = new Department() { Name = name }; await _context.AddAsync <Department>(dept); await _context.SaveChangesAsync(); // save change entry for department creation var change = new Change() { Table = "Departments", ChangeType = "Create", EntryId = dept.Id, OnlineTimeStamp = DateTime.Now, OfflineTimeStamp = DateTime.Now, UserId = MyId }; await _context.Changes.AddAsync(change);; await _context.SaveChangesAsync(); } catch (Exception e) { throw e; } }
public async Task CreateTicket(Ticket ticket) { ticket.Deleted = false; await _dataContext.AddAsync(ticket); await _dataContext.SaveChangesAsync(); }
public async Task AddWorker(WorkerInformation workerInformation) { var worker = _mapper.Map <Worker>(workerInformation); await _context.AddAsync(worker); await _context.SaveChangesAsync(); }
public async Task <ColorAccessResponse> CreateAsync(ColorAccess request) { var entity = _mapper.Map <Color>(request); await _context.AddAsync(entity); return(await _context.SaveChangesAsync() > 0 ? _mapper.Map <ColorAccessResponse>(entity) : null); }
public async Task CreateTicketType(TicketType ticketType) { ticketType.Deleted = false; await _dataContext.AddAsync(ticketType); await _dataContext.SaveChangesAsync(); }