예제 #1
0
        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);
            }
        }
예제 #2
0
        public async Task <IActionResult> PostValue([FromBody] Value entity)
        {
            await _context.AddAsync(entity);

            await _context.SaveChangesAsync();

            return(Ok());
        }
예제 #3
0
        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);
        }
예제 #4
0
 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();
        }
예제 #6
0
        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()));
            }
        }
예제 #7
0
        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);
            }
        }
예제 #8
0
        public async Task AddItem(SingleItemDto itemDto)
        {
            Item itemToSave = Mapper.Map <Item>(itemDto);
            await dataContext.AddAsync(itemToSave);

            await dataContext.SaveChangesAsync();
        }
예제 #9
0
 public async void AddCar(CarModels carToAdd)
 {
     if (carToAdd != null)
     {
         await _context.AddAsync(carToAdd);
     }
 }
예제 #10
0
        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;
            });
        }
예제 #12
0
        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("Произошла ошибка"));
            }
        }
예제 #13
0
        public async Task CreateLocation(Location location)
        {
            location.Deleted = false;
            await _dataContext.AddAsync(location);

            await _dataContext.SaveChangesAsync();
        }
예제 #14
0
        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"));
        }
예제 #15
0
        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);
        }
예제 #16
0
        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
                });
            }
        }
예제 #17
0
        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());
            }
        }
예제 #18
0
        public async Task AddClient(ClientInformation clientInformation)
        {
            var client = _mapper.Map <Client>(clientInformation);
            await _context.AddAsync(client);

            await _context.SaveChangesAsync();
        }
예제 #19
0
        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);
        }
예제 #20
0
        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));
        }
예제 #22
0
        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"))
                       ));
        }
예제 #24
0
        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);
            }
        }
예제 #25
0
        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);
            }
        }
예제 #26
0
        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;
            }
        }
예제 #27
0
        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();
        }
예제 #29
0
        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);
        }
예제 #30
0
        public async Task CreateTicketType(TicketType ticketType)
        {
            ticketType.Deleted = false;
            await _dataContext.AddAsync(ticketType);

            await _dataContext.SaveChangesAsync();
        }