Exemplo n.º 1
0
        public ViewResult EditAuthor(int id)
        {
            ViewBag.Title   = "Library :: Редакирование автора";
            ViewBag.Caption = "Редактирование автора";

            return(View("AuthorForm", aRepo.GetOne(id)));
        }
        public override bool ValidateUser(string userName, string password)
        {
            var query = _queryFactory.createFindValidatedUserByUsernameQuery(userName, "myApp");
            var user  = _repository.GetOne <User>(query);

            return(false);
        }
Exemplo n.º 3
0
        public ViewResult EditPublisher(int id)
        {
            ViewBag.Title   = "Library :: Редакирование издателя";
            ViewBag.Caption = "Редактирование издателя";

            return(View("PublisherForm", pRepo.GetOne(id)));
        }
Exemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="customerLedger"></param>
        public void Add(CustomerLedger customerLedger)
        {
            try
            {
                var identity = (LoginIdentity)Thread.CurrentPrincipal.Identity;
                if (string.IsNullOrEmpty(customerLedger.CompanyId))
                {
                    customerLedger.CompanyId = identity.CompanyId;
                }
                if (string.IsNullOrEmpty(customerLedger.BranchId))
                {
                    customerLedger.BranchId = identity.BranchId;
                }
                customerLedger.Id       = GenerateAutoId(customerLedger.CompanyId, customerLedger.BranchId, "CustomerLedger");
                customerLedger.Sequence = GetAutoSequence("CustomerLedger");
                Customer customer = _customerRepository.GetOne(x => x.Id == customerLedger.CustomerId);
                customerLedger.TrackingNo           = GenerateTrackingNo(customerLedger.CompanyId, customerLedger.BranchId, "CustomerLedger");
                customerLedger.MoneyReceiveNo       = GenerateMoneyReceiveNo(customerLedger.CompanyId, customerLedger.BranchId, "CustomerLedger");
                customerLedger.TransactionDate      = DateTime.Now;
                customerLedger.CustomerMobileNumber = customer.Phone1;

                customerLedger.Active = true;
                customerLedger.SynchronizationType = SynchronizationType.Server.ToString();
                customerLedger.AddedBy             = identity.Name;
                customerLedger.AddedDate           = DateTime.Now;
                customerLedger.AddedFromIp         = identity.IpAddress;
                _customerLedgerRepository.Add(customerLedger);
                _unitOfWork.SaveChanges();
                _rawSqlService.UpdateCustomerLedgerRunningBalance(customer.Id);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Exemplo n.º 5
0
        public ViewResult EditRole(int id)
        {
            ViewBag.Title   = "Library :: Редакирование роли";
            ViewBag.Caption = "Редактирование роли";

            return(View("RoleForm", rRepo.GetOne(id)));
        }
Exemplo n.º 6
0
        /// <summary>
        ///  获取单条符合条件的 user 数据
        /// </summary>
        /// <param name="exp">条件表达式</param>
        /// <returns></returns>
        public UserDto GetOne(Expression <Func <UserDto, bool> > exp)
        {
            var where = exp.Cast <UserDto, User, bool>();
            var entity = repository.GetOne(where);

            return(Mapper.Map <User, UserDto>(entity));
        }
Exemplo n.º 7
0
        public ViewResult EditRole(int id)
        {
            ViewBag.Title   = "MVC CRUD :: Редакирование роли";
            ViewBag.Caption = "Редактирование роли";
            ViewBag.NewRole = roleRepo.GetOne(id).RoleName;

            return(View("RoleForm"));
        }
Exemplo n.º 8
0
        public void Add(PromotionalDiscount promotionalDiscount)
        {
            var flag = false;

            try
            {
                _unitOfWork.BeginTransaction();
                flag = true;
                #region PromotionalDiscount
                var identity = (LoginIdentity)Thread.CurrentPrincipal.Identity;
                promotionalDiscount.Id                  = GetAutoNumber();
                promotionalDiscount.Sequence            = GetAutoSequence();
                promotionalDiscount.Active              = true;
                promotionalDiscount.SynchronizationType = SynchronizationType.Server.ToString();
                promotionalDiscount.AddedBy             = identity.Name;
                promotionalDiscount.AddedDate           = DateTime.Now;
                promotionalDiscount.AddedFromIp         = identity.IpAddress;
                #endregion

                #region PromotionalDiscount Detail
                var detailId = GetAutoIntNumber("PromotionalDiscountDetail");
                var sequence = GetAutoSequence("PromotionalDiscountDetail");
                if (promotionalDiscount.PromotionalDiscountDetails != null)
                {
                    foreach (var item in promotionalDiscount.PromotionalDiscountDetails)
                    {
                        var itemDb = _itemRepository.GetOne(item.ProductId);
                        item.Id       = detailId.ToString();
                        item.Sequence = sequence;
                        item.PromotionalDiscountId = promotionalDiscount.Id;
                        item.ProductCode           = itemDb?.Code;
                        item.Active      = true;
                        item.AddedBy     = identity.Name;
                        item.AddedDate   = DateTime.Now;
                        item.AddedFromIp = identity.IpAddress;
                        _promotionalDiscountDetailRepository.Add(item);
                        detailId++;
                        sequence++;
                    }
                }
                #endregion
                _promotionalDiscountRepository.Add(promotionalDiscount);
                _unitOfWork.SaveChanges();
                flag = false;
                _unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (flag)
                {
                    _unitOfWork.Rollback();
                }
            }
        }
Exemplo n.º 9
0
        public virtual void Delete(string id)
        {
            M model = _repo.GetOne(id);

            if (model != null)
            {
                _repo.Delete(model);
            }
        }
Exemplo n.º 10
0
        public ViewResult EditBook(int id)
        {
            ViewBag.Title      = "MVC CRUD :: Редакирование книги";
            ViewBag.Caption    = "Редактирование книги";
            ViewBag.Book       = bRepo.GetOne(id);
            ViewBag.Publishers = pRepo.GetAll();
            ViewBag.Authors    = aRepo.GetAll();

            return(View("BookForm"));
        }
Exemplo n.º 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public ProductMaster GetById(string id)
 {
     try
     {
         return(_productMasterRepository.GetOne(id));
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 12
0
        public JobApplication GetApplication(string companyName)
        {
            JobApplicationUser   user           = _userResolver.GetCurrentUser().Result;
            JobApplicationEntity jobApplication =
                _repository.GetOne(f => f.Owner.Equals(user) && f.CompanyName.Equals(companyName, StringComparison.Ordinal));

            if (jobApplication != null)
            {
                return(_mapper.Map <JobApplication>(jobApplication));
            }

            return(null);
        }
Exemplo n.º 13
0
        public IActionResult GetViagensPorMotorista([FromRoute] decimal id)
        {
            var motorista = _repositoryUser.GetOne(u => u.Id == id);

            if (motorista == null)
            {
                return(NotFound("Motorista não encontrado"));
            }

            var viagems = _repositoryViagem.GetAll(v => v.IdMotorista == id);

            return(Ok(viagems));
        }
Exemplo n.º 14
0
        public async Task <IActionResult> CriarRotaEmAndamento(int idViagem)
        {
            var viagem = _repositoryViagem.GetById(idViagem);

            if (viagem == null)
            {
                return(NotFound("Viagem não encontrada"));
            }

            if (viagem.Finalizacao != null)
            {
                return(BadRequest($"Viagem informada já finalizada"));
            }

            var rotaEmAndamento = await _repositoryRotaAtiva.GetOne(r => r.IdViagem == viagem.Id);

            if (rotaEmAndamento != null)
            {
                return(BadRequest($"Está viagem ja possui uma rota em andamento"));
            }

            if (viagem.IdMotorista != _idUser)
            {
                return(BadRequest("Motorista logado não condiz com a viagem selecionada"));
            }

            if (viagem.IdMotorista != _idUser)
            {
                return(BadRequest("Motorista logado não condiz com a viagem selecionada"));
            }

            var existRodaEmAndamento = _repositoryRotaAtiva.GetEntityByExpression(r => r.Viagem.IdMotorista == _idUser &&
                                                                                  r.Viagem.Finalizacao == null,
                                                                                  v => v.Viagem).Any();

            if (existRodaEmAndamento)
            {
                return(BadRequest("Motorista ja possui um rota em andamento"));
            }

            var rotaCriada = _repositoryRotaAtiva.Save(new RotaAtiva()
            {
                IdViagem = viagem.Id
            });

            viagem.DataInicio = DateTime.Now;
            _repositoryViagem.Update(viagem);

            return(Created(nameof(GetById), rotaCriada));
        }
Exemplo n.º 15
0
        public void OpenUoWConstructorTest()
        {
            var target = CreateUoW();

            Assert.IsNotNull(_repository.GetOne <Project>(t => t._id == _currentProject._id));
            Assert.IsNotNull(target);
        }
Exemplo n.º 16
0
        public decimal GetCustomerDiscountRate(string customerId)
        {
            decimal cstmrdsctrt = 0;
            var     customer    = _customerRepository.GetOne(customerId);

            if (customer != null)
            {
                var checkRate = customer.DiscountRate;
                if (checkRate > 0)
                {
                    cstmrdsctrt = checkRate;
                }
                else
                {
                    var cstmrctg = _customerCategoryRepository.GetOne(x => x.Id == customer.CustomerCategoryId);
                    if (cstmrctg != null)
                    {
                        checkRate = cstmrctg.DiscountRate;
                        if (checkRate > 0)
                        {
                            cstmrdsctrt = checkRate;
                        }
                    }
                }
            }
            return(cstmrdsctrt);
        }
Exemplo n.º 17
0
        //[Route("[area]/[controller]/[action]/{id:int}")]
        public IActionResult Edit(int id)
        {
            PizzaViewModel pizzaVM = new PizzaViewModel();

            Pizza pizza = repository.GetOne(id);

            pizzaVM.Title       = pizza.Title;
            pizzaVM.PizzaID     = pizza.PizzaID;
            pizzaVM.Description = pizza.Description;
            pizzaVM.PriceHT     = pizza.Price;
            pizzaVM.Image       = pizza.Image;

            return(View(pizzaVM));
        }
        protected virtual void DeleteOneFixture()
        {
            ClearRepository();
            using (IRepository <TestModel> repository = GetNewDbRepository())
            {
                repository.AddOne(new TestModel()
                {
                    TestId = 1, TestData = "data1"
                }).UpdateAll();
            }

            using (IRepository <TestModel> repository = GetNewDbRepository())
            {
                var one = new TestModel()
                {
                    TestId = 1
                };
                Assert.Throws <InvalidOperationException>(() => repository.DeleteOne(one));
                repository.DeleteOne(one, attache: true, autoupdate: true);
            }

            using (IRepository <TestModel> repository = GetNewDbRepository())
            {
                var one = repository.GetOne(entity => entity.TestId == 1);
                one.Should().Be.Null();
            }
            ClearRepository();
        }
        protected virtual void AddRangeFixture()
        {
            ClearRepository();
            using (IRepository <TestModel> repository = GetNewDbRepository())
            {
                var models = new List <TestModel> {
                    new TestModel()
                    {
                        TestId = 1, TestData = "data1"
                    },
                    new TestModel()
                    {
                        TestId = 2, TestData = "data1"
                    },
                    new TestModel()
                    {
                        TestId = 3, TestData = "data1"
                    }
                };

                repository.AddRange(models).UpdateAll();
            }

            using (IRepository <TestModel> repository = GetNewDbRepository())
            {
                var one = repository.GetOne(entity => entity.TestId == 1);
                one.Should().Not.Be.Null();
                one.TestId.Should().Equal(1);
            }

            ClearRepository();
        }
Exemplo n.º 20
0
 private List <BarcodeGeneratorViewModel> Barcode(string productId, int number, string companyId, string branchId)
 {
     try
     {
         List <BarcodeGeneratorViewModel> bracods = new List <BarcodeGeneratorViewModel>();
         var product = _productRepository.GetOne(productId);
         if (!string.IsNullOrEmpty(product?.Id))
         {
             var sizeName    = _sizeRepository.GetOne(product?.SizeId)?.Name;
             var companyName = _companyRepository.GetOne(companyId)?.Name;
             var branchName  = _branchRepository.GetOne(branchId)?.Name;
             for (int i = 1; i <= number; i++)
             {
                 if (columnNumber < 6)
                 {
                     columnNumber++;
                 }
                 else
                 {
                     rowNumber++;
                     columnNumber = 1;
                 }
                 bracods.Add(new BarcodeGeneratorViewModel {
                     RowNumber = rowNumber, ColumnNumber = columnNumber, ProductId = productId, ProductCode = product.Code, ProductName = product.Name, SizeName = sizeName, RetailPrice = product.RetailPrice, CompanyId = companyId, CompanyName = companyName, BranchId = branchId, BranchName = branchName
                 });
             }
         }
         return(bracods);
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemplo n.º 21
0
        public async Task <List <ViagemDtoSaida> > ListarViagensOferecidas()
        {
            var viagens = GetEntityByExpression(v => v.Finalizacao == null && v.Cancelada == null &&
                                                v.DataViagem > DateTime.Now && v.IdMotorista == _idUsuario, v => v.Motorista);

            var idsViagens         = viagens.Select(v => v.Id).ToList();
            var viagensDtoSaida    = _mapper.Map <List <ViagemDtoSaida> >(viagens);
            var viagensSolicitadas = _repositorySolicitacaoViagem.GetAll(vs => idsViagens.Contains(vs.IdViagem));


            var rotaAtiva = await _repositoryRotaAtiva.GetOne(r => r.Viagem.IdMotorista == _idUsuario && r.Viagem.Finalizacao == null);

            viagensDtoSaida.ForEach(viagem =>
            {
                viagem.MotoristaDaCorrida           = viagem.IdMotorista == _idUsuario;
                viagem.QuantidadeDeSolicitacaoAtiva = viagensSolicitadas.Where(v => v.IdViagem == viagem.Id && (v.Recusada == false || v.Recusada == null))
                                                      .Count();
            });

            if (rotaAtiva != null)
            {
                viagensDtoSaida.Where(v => rotaAtiva.IdViagem == v.Id).FirstOrDefault().EmAndamento = true;
            }

            return(viagensDtoSaida);
        }
        public async Task <IActionResult> RemoverSolicitacaoViagem([FromRoute] int idViagem)
        {
            var viagem = _repositoryViagem.GetById(idViagem);

            if (viagem == null)
            {
                return(BadRequest("Viagem não encontrada"));
            }

            if (viagem.Finalizacao != null)
            {
                return(BadRequest("Viagem ja finalizada"));
            }

            var solicitacao = await _repositorySolicitacaoViagem.GetOne(s => s.IdUsuario == _idUsuarioLogado && s.IdViagem == idViagem);

            if (solicitacao == null)
            {
                return(BadRequest("Solicitacao viagem não encontrada"));
            }

            _repositorySolicitacaoViagem.Remove(solicitacao);

            return(NoContent());
        }
        public Task Handle(UpdateIdeaCommentCommand message)
        {
            var existingComment = _repository.GetOne <IdeaComment>(message.Comment.Id);

            if (existingComment == null)
            {
                return(Task.CompletedTask);
            }

            existingComment.Content    = message.Comment.Content;
            existingComment.ModifiedOn = DateTime.UtcNow;

            var updatedComment = _repository.Update(existingComment);

            return(_bus.RaiseEvent(new IdeaCommentUpdatedEvent(_dataMapper.Map <IdeaCommentDto>(updatedComment))));
        }
Exemplo n.º 24
0
        public User ValidateLogin(string email, string password)
        {
            var repoUser = _userRepo.GetOne(email);

            if (repoUser == null || !repoUser.IsActive)
            {
                return(new User());
            }
            if (repoUser.Password == ComputeSha256Hash(password))
            {
                //authenticated
                repoUser.Password = "";
                try
                {
                    repoUser.Restaurant = _restaurantRepo.GetOne(repoUser.RestaurantId);
                }
                catch
                {
                    repoUser.Restaurant = null;
                }
                repoUser.Token = GenerateToken(repoUser);
                return(repoUser);
            }
            else
            {
                //not authenticated
                return(new User());
            }
        }
Exemplo n.º 25
0
        public async Task <IActionResult> DeleteEcoItem([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "ecoitem/delete")] HttpRequest req)
        {
            try
            {
                if (req.Body is null)
                {
                    throw new NullReferenceException();
                }
                else if (await IsTokenValid(req))
                {
                    int.TryParse(req.Query["id"], out int id);
                    using EcoItem item = await IEcoItemRepo.GetOne(id);

                    IEcoItemRepo.Remove(item);
                    await Context.SaveChangesAsync();

                    return(new OkObjectResult(new Response(true, "Item has been deleted.", null)));
                }
                else
                {
                    return(new UnauthorizedResult());
                }
            }
            catch (Exception)
            { throw new Exception("Oops! Something went wrong!"); }
        }
Exemplo n.º 26
0
        public override object Process(ServerParameters parameters, dynamic data)
        {
            var server = serversTable.GetOne(x => x.Endpoint == parameters.Endpoint);

            if (server != null)
            {
                // Update already existing server
                server.Info = data.ToObject <ServerInfo>();

                serversTable.Update(server);
            }
            else
            {
                // First time we met this endpoint, insert new server
                server = new Model.Server()
                {
                    Endpoint = parameters.Endpoint,
                    Info     = data.ToObject <ServerInfo>(),
                };

                serversTable.Insert(server);
            }

            return(new object());
        }
Exemplo n.º 27
0
        public virtual async Task <IActionResult> Delete(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var entity = await Repo.GetOne(id);

            if (entity == null)
            {
                return(NotFound());
            }

            return(View(entity));
        } // POST: ExampleAdmin/Delete/5
Exemplo n.º 28
0
        public Department GetByDepartmentName(string depName)
        {
            Department dep     = null;
            var        builder = Builders <Department> .Filter;
            var        filter  = builder.Eq("DepartmentName", depName);

            try
            {
                dep = repo.GetOne <Department>(filter);
            }
            catch (Exception ex)
            {
                DALUtils.ErrorRoutine(ex, "DepartmentDAO", "GetByDepartmentName");
            }

            return(dep);
        }
Exemplo n.º 29
0
        /*
         *  GetByProblemDescription()
         *  Uses the Repository and Gets the specific employee based on the "Description" of the Problem
         */
        public Problem GetByProblemDescription(string description)
        {
            Problem prob    = null;
            var     builder = Builders <Problem> .Filter;
            var     filter  = builder.Eq("Description", description);

            try
            {
                prob = repo.GetOne <Problem>(filter);
            }
            catch (Exception ex)
            {
                DALUtils.ErrorRoutine(ex, "ProblemDAO", "GetByProblemDescription");
            }

            return(prob);
        }
Exemplo n.º 30
0
        /*
         *  GetByLastname()
         *  Uses the Repository and Gets the specific employee based on the "Lastname" of the Employee
         */
        public Employee GetByLastname(string name)
        {
            Employee emp     = null;
            var      builder = Builders <Employee> .Filter;
            var      filter  = builder.Eq("Lastname", name);

            try
            {
                emp = repo.GetOne <Employee>(filter);
            }
            catch (Exception ex)
            {
                DALUtils.ErrorRoutine(ex, "EmployeeDAO", "GetByLastname");
            }

            return(emp);
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                return;
            }

            //TODO: temporary fix. IoC should resolve it automatically
            UserRepository = DependencyResolver.Current.GetService<IRepository<User, Guid>>();

            var viewResult = filterContext.Result as ViewResult;
            if (viewResult != null)
            {
                string currentUserEmail = filterContext.HttpContext.User.Identity.Name;
                User currentUser = UserRepository.GetOne(r => r.Email == currentUserEmail);
                if (currentUser != null)
                {
                    viewResult.ViewBag.Username = currentUser.Name;
                }
            }
        }
Exemplo n.º 32
0
 private static bool UserWithEmailExists(IRepository<User, Guid> userRepository, string userEmail)
 {
     return userRepository.GetOne(u => u.Email == userEmail) != null;
 }