public void Authenticate()
        {
            var usersRepository = new UsersRepository(new MainUnitOfWork(ConfigurationManager.AppSettings["AzureConnectionString"]));

            var request = new AuthenticationRequest();
            var result = usersRepository.Authenticate(9822559890, "test123");
            Assert.IsNotNull(result);
        }
        public bool AuthenticateUser(string email, string password)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);

            LoggedUser = usersRepository.GetAll(filter: u => u.Email == email && u.Password == password).FirstOrDefault();
            return LoggedUser != null;
        }
 public Coach Get(int id)
 {
     TBL_COACH _coach = new CoachRepository().GetById(id);
     aspnet_Users user = new UsersRepository().GetAll().Where(u => u.UserId == _coach.UserID).SingleOrDefault();
     aspnet_Membership member = new MembershipRepository().GetAll().Where(m => m.UserId == _coach.UserID).SingleOrDefault();
     TBL_REGION _region = new RegionRepository().GetById(_coach.RegionID);
     Coach coach = new Coach();
     coach.UserName = user.UserName;
     coach.RegionName = _region.Name;
     coach.Email = member.Email;
     CoachMappings.ModelToViewModel(coach, _coach);
     return coach;
 }
        public ActionResult DeleteUser(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);
            UsersDeleteUserVM model = new UsersDeleteUserVM();

            User user = usersRepository.GetByID(id);

            model.ID = user.ID;
            model.FullName = user.ToString();

            return View(model);
        }
        public ActionResult Index()
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepo = new UsersRepository(context);
            HomeIndexVM model = new HomeIndexVM();
            TryUpdateModel(model);

            if (AuthenticationManager.LoggedUser != null)
            {
                model.ID = AuthenticationManager.LoggedUser.ID;
            }

            return View(model);
        }
        public void BuildParametersForInsertingTest()
        {
            List<DbParam> expectedParametersForInserting = new List<DbParam>
                       {
                           new DbParam { Name = "@Username", Value = _user.Username, Type = SqlDbType.NVarChar},
                           new DbParam { Name = "@Email", Value = _user.Email, Type = SqlDbType.NVarChar },
                           new DbParam { Name = "@PasswordHash", Value = _user.PasswordHash, Type = SqlDbType.NVarChar },
                           new DbParam { Name = "@Salt", Value = _user.Salt, Type = SqlDbType.NVarChar }
                       };

            UsersRepository usersRepository = new UsersRepository(_dbWrapper);
            List<DbParam> actualParametersForInserting = usersRepository.BuildParametersForInserting(_user).ToList();

            CollectionAssert.AreEqual(expectedParametersForInserting, actualParametersForInserting);
        }
        public void BuildParametersForUpdatingTest()
        {
            List<DbParam> expectedParametersForUpdating = new List<DbParam>
                       {
                           new DbParam { Name = "@Id", Value = _user.Key },
                           new DbParam { Name = "@Username", Value = _user.Username },
                           new DbParam { Name = "@Email", Value = _user.Email },
                           new DbParam { Name = "@PasswordHash", Value = _user.PasswordHash },
                           new DbParam { Name = "@Salt", Value = _user.Salt }
                       };

            UsersRepository usersRepository = new UsersRepository(_dbWrapper);
            List<DbParam> actualParametersForUpdating = usersRepository.BuildParametersForUpdating(_user).ToList();

            CollectionAssert.AreEqual(expectedParametersForUpdating, actualParametersForUpdating);
        }
        public ActionResult Create(int id = 0)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);

            List<User> usersSelectList;
            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            {
                usersSelectList =
                    usersRep.GetList()
                    .Where(user => ((RoleType)user.Roles & RoleType.OrdersApprover) == RoleType.OrdersApprover)
                    .ToList();
            }

            ViewBag.UsersSelectList = new SelectList(usersSelectList, "Id", "FullName");
            return View();
        }
        public ActionResult DeleteUser(UsersDeleteUserVM model)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);

            User user = usersRepository.GetAll(filter: u => u.ID == model.ID, includeProperties: "Roles").FirstOrDefault();
            if (user == null)
            {
                return HttpNotFound();
            }

            user.Roles = null;
            usersRepository.Delete(user);

            return RedirectToAction("Index", "Users");
        }
        public static void AuthenticateUser(string username, string password)
        {
            UsersRepository usersRepo = new UsersRepository();
            LoggedUser = usersRepo.GetAll().FirstOrDefault(u => u.Username == username && u.Password == password);

            if (LoggedUser != null)
            {
                HttpContext.Current.Session["LoggedUser"] = LoggedUser;

                HttpCookie rememberMeCookie = new HttpCookie("rememberMe");
                rememberMeCookie.Value = Guid.NewGuid().ToString();
                rememberMeCookie.Expires.AddDays(10);
                HttpContext.Current.Response.Cookies.Set(rememberMeCookie);

                //Task.Run(() => EmailService.SendEmail(LoggedUser));
                //Task.Run(() => EmailService.SendEmails());
            }
        }
        public void Test_Signup()
        {
            var usersRepository = new UsersRepository(new MainUnitOfWork(ConfigurationManager.AppSettings["AzureConnectionString"]));

            var user = new User()
            {
                MobileNumber = 8554983722,
                Password = "******",
                StreetAddress = "A-403 Leisure Apts, Bavdhan",
                Landmark = "Behind Maratha Mandir",
                City = "Pune",
                State = "MH",
                Pincode = 411021,
                EmailAddress = "*****@*****.**",
                FirstName = "chetan",
                LastName = "vihite",
                CreatedDate = DateTime.Now
            };

            usersRepository.Signup(user);
        }
        public ActionResult EditUser(int id)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);
            RolesRepository rolesRepository = new RolesRepository(context);
            UsersEditUserVM model = new UsersEditUserVM();

            if (id > 0)
            {
                User user = usersRepository.GetAll(filter: u => u.ID == id,
                    includeProperties: "Roles").FirstOrDefault();

                PopulateAssignedRoles(user, rolesRepository);

                model.ID = user.ID;
                model.PersonalNumber = user.PersonalNumber;
                model.Password = user.Password;
                model.FirstName = user.FirstName;
                model.Email = user.Email;
                model.Address = user.Address;
                model.LastName = user.LastName;
                model.Birthday = user.Birthday;
                model.DateIn = user.DateIn;
                if (user.DateOut != null)
                {
                    model.DateOut = user.DateOut.Value;
                }
            }
            else
            {
                model.Email = " ";

                User user = new User();
                user.Roles = new List<Role>();
                PopulateAssignedRoles(user, rolesRepository);
            }

            return View(model);
        }
        public void Delete(FranchiseeUser franchiseeUser)
        {
            FranchiseeUsersRepository userRepository;
            TBL_FRANCHISEE_USERS franchiseeUserToDelete = null;
            aspnet_Users user;
            ContactsRepository contactRepository;
            try
            {
                contactRepository = new ContactsRepository();
                contactRepository.DeleteContactsOfUser(franchiseeUser.FranchiseeID, new Guid(franchiseeUser.UserID));

                franchiseeUserToDelete = new FranchiseeUsersRepository().GetAll().Where(record => record.FranchiseeID == franchiseeUser.FranchiseeID && record.UserID == new Guid(franchiseeUser.UserID)).SingleOrDefault();
                userRepository = new FranchiseeUsersRepository();
                userRepository.Delete(franchiseeUserToDelete);

                user = new UsersRepository().GetAll().Where(u => u.UserId == new Guid(franchiseeUser.UserID)).SingleOrDefault();
                UserEntitiesFactory.DeleteUserWithRoles(user.UserName, SandlerRoles.FranchiseeUser.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public FranchiseeUser Get(int id, string userId)
        {
            TBL_FRANCHISEE_USERS _franchiseeUSer;
            aspnet_Users user;
            aspnet_Membership member;
            FranchiseeUser franchiseeUser = null;
            try
            {
                _franchiseeUSer = new FranchiseeUsersRepository().GetAll().Where(record => record.FranchiseeID == id && record.UserID == new Guid(userId)).SingleOrDefault();
                user = new UsersRepository().GetAll().Where(u => u.UserId == _franchiseeUSer.UserID).SingleOrDefault();
                member = new MembershipRepository().GetAll().Where(m => m.UserId == _franchiseeUSer.UserID).SingleOrDefault();

                franchiseeUser = new FranchiseeUser();
                franchiseeUser.UserName = user.UserName;
                franchiseeUser.Email = member.Email;
                FranchiseeUserMappings.ModelToViewModel(franchiseeUser, _franchiseeUSer);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return franchiseeUser;
        }
        public ContractorAppController(AccountantsRepository accountant,
            CarRepository car,
            ChequesRepository cheaque,
            CompaniesRepository companies,
            ContactsLoanRepository contactLoans,
            ExpensesRepository expenses,
            ExpensesTypes expensesTypes,

           FinancialcustodyRepository finacialCustody,
           InventoryprojectreleaseRepository inventoryprojectrelease,
           InventoryRepository inventory,
           InvoicesitemsRepository invoiceItem,
           InvoicesRepository invoice,
           LoansItemsRepository loanItems,
           LoansRepository loans,
           ProjectItemsRepository projectItems,
            UsersRepository userRepository
            )
        {
            _userRepository = userRepository;
            _accountant = accountant;
            _car = car;
            _cheaque = cheaque;
            _companies = companies;
            _contactLoans = contactLoans;
            _expenses = expenses;
            _expensesTypes = expensesTypes;

            _finacialCustody = finacialCustody;
            _inventoryprojectrelease = inventoryprojectrelease;
            _inventory = inventory;
            _invoiceItem = invoiceItem;
            _invoice = invoice;
            _loanItems = loanItems;
            _loans = loans;
            _projectItems = projectItems;
        }
        public ActionResult Create(ApprovalRouteModel model)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);

            Users_ApprovalRoutes newApprovalRoute = new Users_ApprovalRoutes();
            newApprovalRoute.Name = model.Name;

            using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId))
            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            {
                var usersIds = model.Steps.Select(x => x.UserId).Distinct();
                List<User> routeApprovers = usersRep.GetList().Where(x => usersIds.Contains(x.Id)).ToList();
                if(usersIds.Count() != routeApprovers.Count) return Error(Loc.Dic.error_invalid_form);

                foreach (var approver in routeApprovers)
                {
                    if (!Roles.HasRole(approver.Roles, RoleType.OrdersApprover))
                        return Error(Loc.Dic.error_invalid_form);
                }

                foreach (var step in model.Steps)
                {
                    newApprovalRoute.Users_ApprovalStep.Add(
                        new Users_ApprovalStep()
                        {
                            UserId = step.UserId,
                            StepNumber = step.StepNumber
                        }
                    );
                }

                if (!routesRep.Create(newApprovalRoute)) return Error(Loc.Dic.error_database_error);
            }

            return RedirectToAction("Index");
        }
 public void AuthenticateUser(string username, string password)
 {
     UsersRepository userRepo = new UsersRepository();
     LoggedUser = userRepo.GetAll(u => u.Username == username && u.Password == password).FirstOrDefault();
 }
Example #18
0
 public static void EnsureUserIsNotRgistered(UsersRepository repository, string username)
 {
     if (repository.UserName_User.ContainsKey(username))
     {
         throw new ArgumentException($"A user with username {username} already exists.");
     }
 }
Example #19
0
 public CrarollaUow()
 {
     _crarollaContext = new CrarollaContext();
     UsersRepository = new UsersRepository(_crarollaContext);
 }
Example #20
0
        private static void Main(string[] args)
        {
            // Get Connection String from appsettings.json
            string dir     = Directory.GetCurrentDirectory();
            var    builder = new ConfigurationBuilder()
                             .SetBasePath(dir)
                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            IConfiguration Configuration = builder.Build();

            string connectionString = Configuration.GetConnectionString("PizzaLocationDB");


            var optionsBuilder = new DbContextOptionsBuilder <PizzaLocationDBContext>();

            optionsBuilder.UseSqlServer(connectionString);


            //  CREATING REPOSITORY OBJECTS  /    SERIALIZER OBJECTS FOR EACH CLASS
            //
            // Initialize Repo Objects to be used for reading/writing data to the DB
            //   based on the input from the user in the console
            var locationRepo       = new LocationRepository(new PizzaLocationDBContext(optionsBuilder.Options));
            var LocationSerializer = new XmlSerializer(typeof(List <Location>));

            var userRepo       = new UsersRepository(new PizzaLocationDBContext(optionsBuilder.Options));
            var UserSerializer = new XmlSerializer(typeof(List <Users>));

            var orderRepo       = new OrderRepository(new PizzaLocationDBContext(optionsBuilder.Options));
            var OrderSerializer = new XmlSerializer(typeof(List <AOrder>));



            //  ---------------------------BEGINNING OF CONSOLE APP FUNCTIONALITY----------------------------------------
            //  User can...
            //     I.) Select if they are a new or returning user
            //       I.2) If they are a new user they can enter their info to create a new user in DB tbl_Users
            //
            //     II.) If they are a returning user, or one who just entered their info they can...
            //       II.2) Make a new order, choosing from the available locations and order items
            //       II.3) Look up info regarding their order history, like...
            //            i) Look up all of the details of their account(orders, cost @ locations, overall cost etc...)
            //
            //     III.) Look up location specific info (number of orders per location, revenue for each location etc...)

            // Determine first and last Name via the Console
            bool   correctInput = false;
            bool   newOrNot = false;
            bool   serializeData = false;
            string newOrExisting, firstNameInput = "", lastNameInput = "", userFirstName = "", userLastName = "";


            Console.WriteLine("WELCOME TO THE PIZZA ORDERING APP.\n\n\nIf you are a new user enter new" +
                              "\n\nIf you are a returning user enter existing");
            newOrExisting = Console.ReadLine();


            while (correctInput == false)
            {
                if (newOrExisting.Contains("new"))
                {
                    Console.WriteLine("Thanks for starting an account with us!\n\nEnter you first name please:");
                    firstNameInput = Console.ReadLine();
                    Console.WriteLine("Enter your last name:");
                    lastNameInput = Console.ReadLine();
                    newOrNot      = true;
                    correctInput  = true;
                }
                else if (newOrExisting.Contains("existing"))
                {
                    Console.WriteLine("Welcome Back!\n\nEnter your first name please:");
                    userFirstName = Console.ReadLine();
                    Console.WriteLine("\nEnter your last name please:");
                    userLastName = Console.ReadLine();
                    newOrNot     = false;
                    correctInput = true;
                }
                else
                {
                    Console.WriteLine("Incorrect Value entered, please enter 'new' for a new user, or 'existing' for" +
                                      " an existing user.");
                    newOrExisting = Console.ReadLine();
                    newOrNot      = false;
                }
            }



            // Create an instance of the ANewUser Class, passing the correct variables whether the user was new or not
            if (newOrNot == true)
            {
                userRepo.AddUser(firstNameInput, lastNameInput);

                var locations = locationRepo.GetLocations();

                //DataSet dataSet = new DataSet("location");
                //Console.WriteLine("Chose a Location to order from (user the keyword in parentheses next to the location info:");
                //using (DataTableReader reader = dataSet.CreateDataReader())
                //{
                //    do
                //    {
                //        if (!reader.HasRows)
                //        {
                //            Console.WriteLine("No Locations available at this time");
                //        }
                //        else
                //        {
                //            foreach (int i in reader)
                //            {
                //                Console.WriteLine(reader.GetString(i))
                //            }

                //        }
                //        Console.WriteLine("========================");
                //    } while (reader.NextResult());

                //}
            }
        }
Example #21
0
 public DziennikRoleProvider()
 {
     roleRepo = new RolesRepository(new EFContext());
     userRepo = new UsersRepository(new EFContext());
 }
Example #22
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                ApplicationUser user   = null;
                IdentityResult  result = null;
                if (ModelState.IsValid)
                {
                    model.CPF = model.CPF.removerCaracteresEspeciais();
                    bool            cadastroSlave    = User.Identity.IsAuthenticated;
                    User            lUsuarioMaster   = null;
                    UsersRepository lUsersRepository = new UsersRepository();

                    if (cadastroSlave)
                    {
                        lUsuarioMaster = lUsersRepository.GetUserId(User.Identity.GetUserId());
                    }

                    using (TransactionScope _scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
                    {
                        User lUsuarioInativo = lUsersRepository.getMembershipEmail(model.Email);

                        if (lUsuarioInativo != null)
                        {
                            if (lUsuarioInativo.cpfDiferente(model.CPF))
                            {
                                AddError("Login já existente, porém CPF divergente");
                                return(View(model));
                            }

                            if (lUsersRepository.getCPF(model.CPF) != null)
                            {
                                AddError("CPF ativo já cadastrado.");
                                return(View(model));
                            }

                            lUsuarioInativo.ativo = 1;

                            if (cadastroSlave)
                            {
                                lUsuarioInativo.usermasterid = lUsuarioMaster.userid;
                            }

                            EditarUsers lEditarUsers = new EditarUsers();
                            if (!lEditarUsers.editar(lUsuarioInativo))
                            {
                                AddError("Não foi possível ativar o usuário");
                            }

                            var token = UserManager.GeneratePasswordResetToken(lUsuarioInativo.membershipid);
                            result = UserManager.ResetPassword(lUsuarioInativo.membershipid, token, model.Password);

                            if (!cadastroSlave)
                            {
                                user = UserManager.FindByEmail(model.Email);
                            }
                        }
                        else
                        {
                            try
                            {
                                try
                                {
                                    user = new ApplicationUser {
                                        UserName = model.Email, Email = model.Email
                                    };
                                }
                                catch (Exception e)
                                {
                                    ModelState.AddModelError("Erro", "Achei o erro => criando novo user (instancia)");
                                    return(View(model));
                                }

                                try
                                {
                                    result = UserManager.Create(user, model.Password);

                                    if (!result.Succeeded)
                                    {
                                        foreach (var item in result.Errors)
                                        {
                                            ModelState.AddModelError("erro $item", item);
                                        }
                                        return(View(model));
                                    }
                                }
                                catch (Exception e)
                                {
                                    ModelState.AddModelError("Erro", "Achei o erro => incluindo novo user");
                                    return(View(model));
                                }

                                try
                                {
                                    result = UserManager.AddToRole(user.Id, "default".ToUpper());

                                    if (!result.Succeeded)
                                    {
                                        foreach (var item in result.Errors)
                                        {
                                            ModelState.AddModelError("erro $item", item);
                                        }
                                        return(View(model));
                                    }
                                }
                                catch (Exception e)
                                {
                                    ModelState.AddModelError("Erro", "Achei o erro => adicionando a role");
                                    return(View(model));
                                }
                            }
                            catch (Exception e)
                            {
                                ModelState.AddModelError("Erro", "Achei o erro => inclusao no identity");
                                return(View(model));
                            }


                            if (result.Succeeded)
                            {
                                User lUser = new User()
                                {
                                    membershipid   = user.Id,
                                    cpf            = model.CPF,
                                    email          = model.Email,
                                    datanascimento = model.DataNascimento,
                                    nome           = model.Nome,
                                    telefone       = model.Telefone,
                                    ativo          = 1,
                                    usermasterid   = cadastroSlave ? (int?)lUsuarioMaster.userid : null
                                };

                                IncluirUsers lIncluirUsers = new IncluirUsers();
                                if (!lIncluirUsers.incluir(lUser))
                                {
                                    foreach (var item in lIncluirUsers.Messages)
                                    {
                                        AddError(item.ToString());
                                    }
                                    _scope.Dispose();
                                    return(View(model));
                                }
                            }
                        }
                        if (ModelState.IsValid)
                        {
                            if (cadastroSlave)
                            {
                                _scope.Complete(); return(RedirectToAction("Index", "Manage"));
                            }
                            else
                            {
                                SignInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
                                _scope.Complete();
                                return(RedirectToAction("Index", "Home"));
                            }
                        }
                        else
                        {
                            _scope.Dispose();
                            return(View(model));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Exception occurred", e.Message);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public int GetPagesCount(Expression<Func<User, bool>> filter = null)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);

            int pagesCount = 0;
            int pageSize = ApplicationConfiguration.ItemsPerPage;
            int usersCount = 0;
            usersCount = usersRepository.Count(filter);
            pagesCount = usersCount / pageSize;
            if ((usersCount % pageSize) > 0)
            {
                pagesCount++;
            }

            return pagesCount;
        }
Example #24
0
        public ActionResult MyTests(int?userId)
        {
            var userRepo = new UsersRepository();

            DataAccessLayer.Models.UserModel user = null;

            if (!userId.HasValue)
            {
                if (User.IsInRole("Admin"))
                {
                    return(HttpNotFound());
                }
                else
                {
                    user = userRepo.GetUserInfo(User.Identity.Name);
                }
            }
            else
            {
                user = userRepo
                       .GetAllUsers()
                       .Where(x => x.UserID == userId)
                       .FirstOrDefault();
                var checkingUser = userRepo.GetUserInfo(User.Identity.Name);

                if (!User.IsInRole("Admin") && user.UserID != checkingUser.UserID)
                {
                    return(HttpNotFound());
                }
            }

            if (user == null)
            {
                return(HttpNotFound());
            }

            var testRepo  = new TestRepository();
            var tests     = testRepo.GetAllTests();
            var viewTests = new List <UserTestViewModel>();

            foreach (var test in tests)
            {
                var questionsCount = testRepo.GetTestQuestions(test.TestID).Count;

                var sessions = testRepo.GetUserTestSessions(new DataAccessLayer.Models.UserTestModel
                {
                    TestID = test.TestID,
                    UserID = user.UserID
                });

                var lastSession = sessions.LastOrDefault(x => x.Time != null);

                var testView = new UserTestViewModel
                {
                    UserID            = user.UserID,
                    TestID            = test.TestID,
                    TestName          = test.TestName,
                    RemainingAttempts = test.AttemptsCount - sessions.Count,
                    LastScore         = lastSession == null ? 0 : lastSession.RightAnswers,
                    QuestionsCount    = questionsCount
                };

                viewTests.Add(testView);
            }

            var userResults = new UserResultsViewModel
            {
                UserName = string.Format("{0} {1} ({2})", user.LastName, user.FirstName, user.Login),
                Tests    = viewTests
            };

            return(View(userResults));
        }
Example #25
0
        public ActionResult WorkDoneExportToExcel(
            int?toDoListFK, int?legalEntityFK, int?workTypeFK, int?workSubtypeFK, int?serviceTypeFK, int?userFK, string dateFrom, string dateTo, int?timeSpentFrom, int?timeSpentTo, int?numberOfAttachmentsFrom, int?numberOfAttachmentsTo, string description,
            bool ShowBasicInfo, bool ShowOrdinal, bool ShowID, bool ShowToDoList, bool ShowLegalEntity, bool ShowWorkType, bool ShowWorkSubtype, bool ShowServiceType, bool ShowDate, bool ShowUsername, bool ShowDescription, bool ShowTimeSpent, bool ShowComment, bool ShowAttachments)
        {
            IWorkDonesRepository           workDonesRepository           = new WorkDonesRepository(db);
            IWorkDoneAttachmentsRepository workDoneAttachmentsRepository = new WorkDoneAttachmentsRepository(db);
            WorkDoneView                   workDoneView                  = new WorkDoneView();
            IContractsRepository           contractsRepository           = new ContractsRepository(db);
            ILegalEntityBranchesRepository legalEntityBranchesRepository = new LegalEntityBranchesRepository(db);
            IToDoListsRepository           toDoListsRepository           = new ToDoListsRepository(db);
            ILegalEntitiesRepository       legalEntitiesRepository       = new LegalEntitiesRepository(db);
            IWorkTypesRepository           workTypesRepository           = new WorkTypesRepository(db);
            IWorkSubtypesRepository        workSubtypesRepository        = new WorkSubtypesRepository(db);
            IServiceTypesRepository        serviceTypesRepository        = new ServiceTypesRepository(db);
            IUsersRepository               usersRepository               = new UsersRepository(db);

            string sortOrder  = !string.IsNullOrWhiteSpace(Request.QueryString["sortOrder"]) ? Request.QueryString["sortOrder"] : "DESC";
            string sortColumn = !string.IsNullOrWhiteSpace(Request.QueryString["sortColumn"]) ? Request.QueryString["sortColumn"] : "WorkDonePK";
            string ordering   = sortColumn + " " + sortOrder;

            ordering = ordering.Trim();

            if (legalEntityFK != null)
            {
                ViewBag.LegalEntity = legalEntitiesRepository.GetLegalEntityByPK((int)legalEntityFK).Name;
            }
            if (toDoListFK != null)
            {
                ViewBag.ToDoList = toDoListsRepository.GetToDoListByPK((int)toDoListFK).Name;
            }
            if (workTypeFK != null)
            {
                ViewBag.WorkType = workTypesRepository.GetWorkTypeByPK((int)workTypeFK).Name;
            }
            if (workSubtypeFK != null)
            {
                ViewBag.WorkSubtype = workSubtypesRepository.GetWorkSubtypeByPK((int)workSubtypeFK).Name;
            }
            if (userFK != null)
            {
                ViewBag.User = usersRepository.GetUserByUserID((int)userFK).Username;
            }

            DateTime?dateFromTime = null;
            DateTime?dateToTime   = null;

            if (dateFrom != null && dateFrom != "")
            {
                dateFromTime = DateTime.ParseExact(dateFrom, "dd.MM.yyyy.", null);
            }
            if (dateTo != null && dateTo != "")
            {
                dateToTime = DateTime.ParseExact(dateTo, "dd.MM.yyyy.", null);
            }

            // Applying filters
            IQueryable <WorkDone> workDonesFiltered = WorkDoneView.GetWorkDonesReport(db, toDoListFK, legalEntityFK, workTypeFK, workSubtypeFK, serviceTypeFK, userFK, dateFromTime, dateToTime, timeSpentFrom, timeSpentTo, numberOfAttachmentsFrom, numberOfAttachmentsTo, description);

            IQueryable <WorkDoneView> workDones = WorkDoneView.GetWorkDoneView(workDonesFiltered,
                                                                               toDoListsRepository.GetValid(),
                                                                               workDoneAttachmentsRepository.GetValid(),
                                                                               legalEntitiesRepository.GetValidLegalEntities(),
                                                                               workTypesRepository.GetValid(),
                                                                               workSubtypesRepository.GetValid(),
                                                                               serviceTypesRepository.GetValid(),
                                                                               usersRepository.GetValid())
                                                  .OrderBy(ordering);

            var workDonesList = workDones.ToList();

            var columns = new Dictionary <string, int>();

            var ms = new MemoryStream();

            using (var package = new ExcelPackage(ms))
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Izvršeni posao");

                var columnPosition = 1;

                Action <bool, string> setColumnHeader = (columnVisible, columnName) =>
                {
                    if (columnVisible)
                    {
                        worksheet.Cells[1, columnPosition].Value           = columnName;
                        worksheet.Cells[1, columnPosition].Style.Font.Bold = true;
                        columns.Add(columnName, columnPosition++);
                    }
                };

                setColumnHeader(ShowOrdinal, "#");
                setColumnHeader(ShowID, "ID");
                setColumnHeader(ShowToDoList, "Obaveza");
                setColumnHeader(ShowLegalEntity, "Tvrtka");
                setColumnHeader(ShowWorkType, "Vrsta rada");
                setColumnHeader(ShowWorkSubtype, "Vrsta posla");
                setColumnHeader(ShowServiceType, "Vrsta usluge");
                setColumnHeader(ShowDate, "Datum izvršenja");
                setColumnHeader(ShowUsername, "Korisnik");
                setColumnHeader(ShowDescription, "Opis");
                setColumnHeader(ShowTimeSpent, "Utrošeno vrijeme");
                setColumnHeader(ShowComment, "Važna napomena");
                setColumnHeader(ShowAttachments, "Prilozi");

                Action <int, bool, string, object> setRowValue = (ri, columnVisible, columnName, value) =>
                {
                    if (columnVisible)
                    {
                        worksheet.Cells[ri, columns[columnName]].Value = value;
                    }
                };

                var rowIndex = 2;
                foreach (var item in workDonesList)
                {
                    setRowValue(rowIndex, ShowOrdinal, "#", rowIndex - 1);
                    setRowValue(rowIndex, ShowID, "ID", item.WorkDonePK);
                    setRowValue(rowIndex, ShowToDoList, "Obaveza", item.ToDoListName);
                    setRowValue(rowIndex, ShowLegalEntity, "Tvrtka", item.LegalEntityName);
                    setRowValue(rowIndex, ShowWorkType, "Vrsta rada", item.WorkTypeName);
                    setRowValue(rowIndex, ShowWorkSubtype, "Vrsta posla", item.WorkSubtypeName);
                    setRowValue(rowIndex, ShowServiceType, "Vrsta usluge", item.ServiceTypeName);
                    setRowValue(rowIndex, ShowDate, "Datum izvršenja", item.Date?.ToString("dd.MM.yyyy."));
                    setRowValue(rowIndex, ShowUsername, "Korisnik", item.UserUsername);
                    setRowValue(rowIndex, ShowDescription, "Opis", item.Description);
                    setRowValue(rowIndex, ShowTimeSpent, "Utrošeno vrijeme", LinkHelper.calculateTimeSpent(item.TimeSpent));
                    setRowValue(rowIndex, ShowComment, "Važna napomena", item.Comment);
                    setRowValue(rowIndex, ShowAttachments, "Prilozi", item.WorkDoneAttachmentsCount);

                    rowIndex++;
                }

                worksheet.Calculate();
                worksheet.Cells.AutoFitColumns(0);

                package.Save();
            }

            ms.Seek(0, SeekOrigin.Begin);

            return(new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = $"Izvršeni posao {DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss")}.xlsx"
            });
        }
Example #26
0
        public ActionResult WorkDone(int?toDoListFK, int?legalEntityFK, int?workTypeFK, int?workSubtypeFK, int?serviceTypeFK, int?userFK, string dateFrom, string dateTo, int?timeSpentFrom, int?timeSpentTo, int?numberOfAttachmentsFrom, int?numberOfAttachmentsTo, string description)
        {
            IWorkDonesRepository           workDonesRepository           = new WorkDonesRepository(db);
            IWorkDoneAttachmentsRepository workDoneAttachmentsRepository = new WorkDoneAttachmentsRepository(db);
            WorkDoneView                   workDoneView                  = new WorkDoneView();
            IContractsRepository           contractsRepository           = new ContractsRepository(db);
            ILegalEntityBranchesRepository legalEntityBranchesRepository = new LegalEntityBranchesRepository(db);
            IToDoListsRepository           toDoListsRepository           = new ToDoListsRepository(db);
            ILegalEntitiesRepository       legalEntitiesRepository       = new LegalEntitiesRepository(db);
            IWorkTypesRepository           workTypesRepository           = new WorkTypesRepository(db);
            IWorkSubtypesRepository        workSubtypesRepository        = new WorkSubtypesRepository(db);
            IServiceTypesRepository        serviceTypesRepository        = new ServiceTypesRepository(db);
            IUsersRepository               usersRepository               = new UsersRepository(db);

            string sortOrder  = !string.IsNullOrWhiteSpace(Request.QueryString["sortOrder"]) ? Request.QueryString["sortOrder"] : "DESC";
            string sortColumn = !string.IsNullOrWhiteSpace(Request.QueryString["sortColumn"]) ? Request.QueryString["sortColumn"] : "WorkDonePK";
            string ordering   = sortColumn + " " + sortOrder;

            ordering = ordering.Trim();

            //grid filters ddl
            ViewBag.ToDoLists     = new SelectList(toDoListsRepository.GetValid().OrderBy("Name ASC").ToList(), "ToDoListPK", "Name", toDoListFK);
            ViewBag.LegalEntities = new SelectList(legalEntitiesRepository.GetValidLegalEntities().OrderBy("Name ASC").ToList(), "LegalEntityPK", "Name", legalEntityFK);
            ViewBag.WorkTypes     = new SelectList(workTypesRepository.GetValid().OrderBy("Name ASC").ToList(), "WorkTypePK", "Name", workTypeFK);
            ViewBag.WorkSubtypes  = new SelectList(workSubtypesRepository.GetValid().OrderBy("Name ASC").ToList(), "WorkSubtypePK", "Name", workSubtypeFK);
            ViewBag.ServiceTypes  = new SelectList(serviceTypesRepository.GetValid().OrderBy("Name ASC").ToList(), "ServiceTypePK", "Name", serviceTypeFK);
            ViewBag.Users         = new SelectList(usersRepository.GetValid().OrderBy("Username ASC").ToList(), "UserPK", "Username", userFK);

            if (legalEntityFK != null)
            {
                ViewBag.LegalEntity = legalEntitiesRepository.GetLegalEntityByPK((int)legalEntityFK).Name;
            }
            if (toDoListFK != null)
            {
                ViewBag.ToDoList = toDoListsRepository.GetToDoListByPK((int)toDoListFK).Name;
            }
            if (workTypeFK != null)
            {
                ViewBag.WorkType = workTypesRepository.GetWorkTypeByPK((int)workTypeFK).Name;
            }
            if (workSubtypeFK != null)
            {
                ViewBag.WorkSubtype = workSubtypesRepository.GetWorkSubtypeByPK((int)workSubtypeFK).Name;
            }
            if (userFK != null)
            {
                ViewBag.User = usersRepository.GetUserByUserID((int)userFK).Username;
            }

            DateTime?dateFromTime = null;
            DateTime?dateToTime   = null;

            if (dateFrom != null && dateFrom != "")
            {
                dateFromTime = DateTime.ParseExact(dateFrom, "dd.MM.yyyy.", null);
            }
            if (dateTo != null && dateTo != "")
            {
                dateToTime = DateTime.ParseExact(dateTo, "dd.MM.yyyy.", null);
            }

            // Applying filters
            IQueryable <WorkDone> workDonesFiltered = WorkDoneView.GetWorkDonesReport(db, toDoListFK, legalEntityFK, workTypeFK, workSubtypeFK, serviceTypeFK, userFK, dateFromTime, dateToTime, timeSpentFrom, timeSpentTo, numberOfAttachmentsFrom, numberOfAttachmentsTo, description);

            IQueryable <WorkDoneView> workDones = WorkDoneView.GetWorkDoneView(workDonesFiltered,
                                                                               toDoListsRepository.GetValid(),
                                                                               workDoneAttachmentsRepository.GetValid(),
                                                                               legalEntitiesRepository.GetValidLegalEntities(),
                                                                               workTypesRepository.GetValid(),
                                                                               workSubtypesRepository.GetValid(),
                                                                               serviceTypesRepository.GetValid(),
                                                                               usersRepository.GetValid())
                                                  .OrderBy(ordering);

            // Excluding temporary deleted items from view
            workDonesPKPKsToExclude = new List <int>();

            // Empty session on first request
            if (Request.QueryString.Count == 0)
            {
                Session["workDonesPKPKsToExclude"] = null;
            }

            if (Session["workDonesPKPKsToExclude"] != null)
            {
                workDonesPKPKsToExclude = (List <int>)Session["workDonesPKPKsToExclude"];
                workDones = workDones.Where(c => !workDonesPKPKsToExclude.Contains(c.WorkDonePK));
            }

            return(View("WorkDone", workDones.ToList()));
        }
Example #27
0
        public void Send(bool disableFilter)
        {
            var appId       = ConfigurationManager.AppSettings["MicrosoftAppId"];
            var appPassword = ConfigurationManager.AppSettings["MicrosoftAppPassword"];

            var nowUtc = DateTime.Now.ToUniversalTime();

            Log($"UTC現在時刻- {nowUtc}");

            var usersRepo = new UsersRepository();
            var users     = usersRepo.GetAllUsers().RunAsSync();

            var conversationStateRepo = new ConversationStateRepository();

            Log($"処理ユーザー数: {users.Count()}");
            foreach (var user in users)
            {
                try
                {
                    Log($"ユーザー: {user.NickName}({user.UserId}) ---");

                    var startHhmm = Hhmm.Parse(user.AskEndOfWorkStartTime);
                    var endHhmm   = Hhmm.Parse(user.AskEndOfWorkEndTime);

                    // 24時超過分をオフセットして比較する
                    // 19:00~26:00 の設定だった時に、翌日の深夜1時(25時)も送信対象となるように。
                    var offsetHour = endHhmm.Hour - 23;
                    if (offsetHour < 0)
                    {
                        offsetHour = 0;
                    }
                    Log($"オフセット時間: {offsetHour}h");

                    var tzUser    = TimeZoneInfo.FindSystemTimeZoneById(user.TimeZoneId);
                    var nowUserTz = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tzUser); // ユーザーのタイムゾーンでの現在時刻
                    Log($"ユーザータイムゾーンの現在時刻(オフセット前): {nowUserTz}");
                    nowUserTz = nowUserTz.AddHours(-offsetHour);
                    var nowHour         = nowUserTz.Hour + offsetHour;
                    var nowStepedMinute = nowUserTz.Minute / 30 * 30;
                    Log($"ユーザータイムゾーンの現在時刻(オフセット前、丸め後): {nowHour}時{nowStepedMinute:00}分");

                    var startTotalMinute = (startHhmm.Hour - offsetHour) * 60 + startHhmm.Minute;
                    var endTotalMinute   = (endHhmm.Hour - offsetHour) * 60 + endHhmm.Minute;
                    var nowTotalMinute   = (nowHour - offsetHour) * 60 + nowStepedMinute;
                    Log($"ユーザータイムゾーンの現在時刻(オフセット後、丸め後): {(nowHour - offsetHour)}時{nowStepedMinute:00}分");
                    Log($"判定時刻範囲(オフセット前): {startHhmm.Hour}時{startHhmm.Minute:00}分~{endHhmm.Hour}時{endHhmm.Minute:00}分");
                    Log($"判定時刻範囲(オフセット後): {(startHhmm.Hour - offsetHour)}時{startHhmm.Minute:00}分~{(endHhmm.Hour - offsetHour)}時{endHhmm.Minute:00}分");

                    if (startTotalMinute >= endTotalMinute)
                    {
                        Log($"{user.UserId} は、開始時刻({user.AskEndOfWorkStartTime})と終了時刻({user.AskEndOfWorkEndTime})が逆転しているので何もしない。");
                        continue;
                    }

                    var nowUserTzDateText = $"{nowUserTz.Year:0000}/{nowUserTz.Month:00}/{nowUserTz.Day:00}";  // ユーザーTZ現在時刻を文字列化

                    var stateEntity = conversationStateRepo.GetStatusByUserId(user.UserId).RunAsSync();

                    var currentTargetDate = stateEntity?.TargetDate ?? "2000/01/01";

                    // ターゲット日付と現在時刻が同じで、
                    // 打刻済/今日はもう聞かないで/休日だったら何もしない
                    var currentState = stateEntity?.State ?? AskingState.None;
                    if (!disableFilter)
                    {
                        if (string.Equals(nowUserTzDateText, currentTargetDate) &&
                            (currentState == AskingState.DoNotAskToday || currentState == AskingState.Punched || currentState == AskingState.TodayIsOff))
                        {
                            Log($"ターゲット日付({currentTargetDate})とユーザーTZ現在日付({nowUserTzDateText})が同じで、State が {currentState} なので何もしない");
                            continue;
                        }

                        // 今日の曜日はユーザー設定で有効か?
                        var enableDayOfWeek = (user.DayOfWeekEnables?.Length ?? 0) - 1 > (int)nowUserTz.DayOfWeek ?
                                              (user.DayOfWeekEnables[(int)nowUserTz.DayOfWeek] == '1') : true;
                        if (!enableDayOfWeek)
                        {
                            Log($"ユーザーTZ現在日付({nowUserTzDateText})の曜日は仕事が休みなので何もしない");
                            continue;
                        }

                        // FIXME 毎年ある祝日か、単発の休日かの管理が面倒なので、とりまオミットしておく
                        //// 祝日か?(面倒だからJson文字列のまま検索しちゃう)
                        //var isHoliday = user.HolidaysJson?.Contains($"\"{nowUserTz:M/d}\"") ?? false; // "6/1" みたいにダブルコートして検索すればいいっしょ
                        //if (isHoliday)
                        //{
                        //    Log($"ユーザーTZ現在日付({nowUserTzText})の休日に設定されている何もしない");
                        //    continue;
                        //}

                        var containsTimeRange = startTotalMinute <= nowTotalMinute && nowTotalMinute <= endTotalMinute;

                        // 聞き取り終了時刻を過ぎていたらStateをNoneにする
                        // AskingEoW のまま y を打たれると打刻できてしまうので。
                        if (startTotalMinute > endTotalMinute)
                        {
                            conversationStateRepo.UpsertState(
                                user.PartitionKey, user.UserId, AskingState.None, $"{endHhmm.Hour:00}{endHhmm.Minute:00}",
                                nowUserTzDateText).RunAsSync();
                        }

                        if (!containsTimeRange)
                        {
                            Log($"現在時刻({nowUserTz}) が {user.AskEndOfWorkStartTime} から {user.AskEndOfWorkEndTime} の範囲外なので何もしない");
                            continue;
                        }
                    }

                    var conversationRef = JsonConvert.DeserializeObject <ConversationReference>(user.ConversationRef);

                    MicrosoftAppCredentials.TrustServiceUrl(conversationRef.ServiceUrl);
                    var connector = new ConnectorClient(new Uri(conversationRef.ServiceUrl), appId, appPassword);

                    var userAccount = new ChannelAccount(id: user.UserId);
                    var res         = connector.Conversations.CreateDirectConversation(conversationRef.Bot, userAccount);

                    // conversationRef.GetPostToUserMessage() では Slack にポストできなかったので、
                    // 普通に CreateMessageActivity した。
                    var message = Activity.CreateMessageActivity();
                    message.From         = conversationRef.Bot;
                    message.Recipient    = userAccount;
                    message.Conversation = new ConversationAccount(id: res.Id);

                    message.Text = $"{user.NickName} さん、お疲れさまです。{nowHour}時{nowStepedMinute:00}分 です、今日のお仕事は終わりましたか?\n\n" +
                                   $"--\n\ny:終わった\n\nn:終わってない\n\nd:今日は徹夜";
                    message.Locale = "ja-Jp";

                    //message.Attachments.Add(new Attachment()
                    //{
                    //    ContentType = AdaptiveCard.ContentType,
                    //    Content = MakeAdaptiveCard()
                    //});

                    connector.Conversations.SendToConversation((Activity)message);

                    conversationStateRepo.UpsertState(
                        user.PartitionKey, conversationRef.User.Id, AskingState.AskingEoW, $"{nowHour:00}{nowStepedMinute:00}",
                        nowUserTzDateText).RunAsSync();

                    Log($"メッセージを送信しました。 ({message.Text})");
                }
                catch (Exception ex)
                {
                    Log($"メッセージ送信に失敗しました。 ({ex.Message} - {ex.StackTrace})");
                }
            }
        }
 public ResourceOwnerValidator(UsersRepository repository)
 {
     _repository = repository;
 }
Example #29
0
 public ForgotPasswordHandler(string connectionString) : base(connectionString)
 {
     _usersRepository = new UsersRepository(connectionString);
 }
        public ActionResult Edit(int id = 0)
        {
            if (!Authorized(RoleType.SystemManager)) return Error(Loc.Dic.error_no_permission);

            ApprovalRouteModel model = new ApprovalRouteModel();
            List<User> usersSelectList;
            using (ApprovalRoutesRepository routesRep = new ApprovalRoutesRepository(CurrentUser.CompanyId))
            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            {
                model.ApprovalRoute = routesRep.GetEntity(id, "Users_ApprovalStep.User");
                if (model.ApprovalRoute == null) return Error(Loc.Dic.error_database_error);

                usersSelectList =
                    usersRep.GetList()
                    .Where(user => ((RoleType)user.Roles & RoleType.OrdersApprover) == RoleType.OrdersApprover)
                    .ToList();
            }

            ViewBag.UsersSelectList = new SelectList(usersSelectList, "Id", "FullName");
            return View(model);
        }
Example #31
0
        public ActionResult TestSessionResult(int testSessionId, int userId)
        {
            var testRepo = new TestRepository();
            var userRepo = new UsersRepository();
            var user     = userRepo.GetUserInfo(User.Identity.Name);

            if (!User.IsInRole("Admin"))
            {
                var userSessions = testRepo
                                   .GetAllTests()
                                   .SelectMany(x => testRepo.GetUserTestSessions(new DataAccessLayer.Models.UserTestModel
                {
                    UserID = user.UserID,
                    TestID = x.TestID
                }));

                if (!userSessions.Select(x => x.TestSessionID).Contains(testSessionId))
                {
                    return(HttpNotFound());
                }
            }

            var testSession = testRepo.GetTestSessionInfo(testSessionId);

            if (testSession == null)
            {
                return(RedirectToAction("MyTests", new { userId = userId }));
            }

            var test          = testRepo.GetTestInfo(testSession.TestID);
            var questions     = testRepo.GetTestQuestions(testSession.TestID);
            var userAnswers   = testRepo.GetUserAnswers(testSessionId);
            var viewQuestions = new List <QuestonWithResultViewModel>();

            foreach (var question in questions)
            {
                var questionAnswers = testRepo
                                      .GetQuestionAnswers(question.QuestionID)
                                      .Select(x => new UserAnswerViewModel
                {
                    AnswerID   = x.AnswerID,
                    AnswerText = x.AnswerText,
                    IsChecked  = userAnswers.Contains(x.AnswerID)
                })
                                      .ToList();

                var points = testRepo.GetQuestionPoints(new DataAccessLayer.Models.QuestionSessionModel
                {
                    QuestionID    = question.QuestionID,
                    TestSessionID = testSession.TestSessionID
                });

                viewQuestions.Add(new QuestonWithResultViewModel
                {
                    QuestionText = question.QuestionText,
                    Answers      = questionAnswers,
                    Points       = points
                });
            }

            var viewTest = new UserTestSessionResultViewModel
            {
                UserID    = userId,
                TestID    = test.TestID,
                TestName  = test.TestName,
                Questions = viewQuestions,
                Score     = string.Format("{0}/{1}", viewQuestions.Sum(x => x.Points), viewQuestions.Count),
            };

            return(View(viewTest));
        }
        public ActionResult Achievements()
        {
            var achievementList = UsersRepository.GetUserAchievements(UserContextHelper.GetUserContextModel().ID);

            return(View("Achievements", achievementList));
        }
 public OrdersController()
 {
     _orderRepo = new OrderRepository();
     _userRepo  = new UsersRepository();
 }
        public JsonResult GetNotifications()
        {
            var notifications = UsersRepository.GetNotificationsForUser(UserContextHelper.GetUserContextModel().ID);

            return(Json(notifications));
        }
Example #35
0
 public SessionsController(SessionsRepository sRepo, UsersRepository uRepo)
 {
     this.sessionRepository = sRepo;
     this.userRepository    = uRepo;
 }
Example #36
0
 public VoteController(RestaurantRepository restaurantRepository, VoteRepository voteRepository, UsersRepository usersRepository, Services services)
 {
     this.restaurantRepository = restaurantRepository;
     this.voteRepository       = voteRepository;
     this.usersRepository      = usersRepository;
     this.services             = services;
 }
 public CustomersController(CustomersRepository repo, UsersRepository usersRepo, GeoDivisionsRepository geoDivisonsRepo)
 {
     _repo            = repo;
     _usersRepo       = usersRepo;
     _geoDivisonsRepo = geoDivisonsRepo;
 }
Example #38
0
 public AuthService(IPasswordHasher <User> passwordHasher, UsersRepository usersRepository, IJwtHandler jwtHandler)
 {
     _jwtHandler      = jwtHandler;
     _passwordHasher  = passwordHasher;
     _usersRepository = usersRepository;
 }
Example #39
0
 public AccountController()
 {
     db = new OefenfirmaContext();
     usersRepository = new UsersRepository(db);
 }
Example #40
0
        public ActionResult Search(OrdersSearchValuesModel model)
        {
            if (!Authorized(RoleType.OrdersWriter) && !Authorized(RoleType.OrdersViewer)) return Error(Loc.Dic.error_no_permission);

            List<Order> matchingOrders;
            List<Order> TextMatchOrders = new List<Order>();

            ViewBag.UserId = model.UserId;
            ViewBag.StatusId = model.StatusId;
            ViewBag.SupplierId = model.SupplierId;
            ViewBag.HideUserField = model.HideUserField;
            ViewBag.HideStatusField = model.HideStatusField;
            ViewBag.HideSupplierField = model.HideSupplierField;

            using (OrdersRepository ordersRep = new OrdersRepository(CurrentUser.CompanyId))
            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            using (SuppliersRepository suppliersRep = new SuppliersRepository(CurrentUser.CompanyId))
            {
                IQueryable<Order> ordersQuery;

                ordersQuery = ordersRep.GetList("Company", "Orders_Statuses", "Supplier", "User").Where(x => x.CompanyId == CurrentUser.CompanyId);

                if (Authorized(RoleType.OrdersViewer))
                {
                    if (model.UserId.HasValue && model.UserId.Value != -1)
                        ordersQuery = ordersQuery.Where(x => x.UserId == model.UserId.Value);
                }
                else
                {
                    ordersQuery = ordersQuery.Where(x => x.UserId == CurrentUser.UserId);
                    ViewBag.UserId = CurrentUser.UserId;
                }

                if (model.BudgetId.HasValue && model.BudgetId.Value != -1)
                    ordersQuery = ordersQuery.Where(x => x.BudgetId == model.BudgetId.Value);

                if (model.OrderNumber.HasValue && model.OrderNumber.Value != -1)
                    ordersQuery = ordersQuery.Where(x => x.OrderNumber == model.OrderNumber.Value);

                if (model.SupplierId.HasValue && model.SupplierId.Value != -1)
                    ordersQuery = ordersQuery.Where(x => x.SupplierId == model.SupplierId.Value);

                if (model.StatusId.HasValue && model.StatusId.Value != -1)
                    ordersQuery = ordersQuery.Where(x => x.StatusId == model.StatusId.Value);

                if (model.AllocationId != null && model.AllocationId != "-1")
                    ordersQuery = ordersQuery.Where(x => x.Orders_OrderToAllocation.Any(oa => oa.Budgets_Allocations.ExternalId == model.AllocationId));

                if (model.PriceMin.HasValue && model.PriceMax.HasValue && model.PriceMax.Value < model.PriceMin.Value)
                    model.PriceMax = null;

                if (model.PriceMin.HasValue)
                    ordersQuery = ordersQuery.Where(x => x.Price >= model.PriceMin.Value);

                if (model.PriceMax.HasValue)
                    ordersQuery = ordersQuery.Where(x => x.Price <= model.PriceMax.Value);

                if (model.CreationMin.HasValue && model.CreationMax.HasValue && model.CreationMax.Value < model.CreationMin.Value)
                    model.CreationMax = null;

                if (model.CreationMin.HasValue)
                    ordersQuery = ordersQuery.Where(x => x.CreationDate >= model.CreationMin.Value);

                if (model.CreationMax.HasValue)
                    ordersQuery = ordersQuery.Where(x => x.CreationDate <= model.CreationMax.Value);

                matchingOrders = ordersQuery.ToList();
            }

            if (!String.IsNullOrEmpty(model.NoteText))
            {
                List<string> searchWords = model.NoteText.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(str => str.Trim()).ToList();
                foreach (var order in matchingOrders)
                {
                    foreach (var word in searchWords)
                    {
                        if (!String.IsNullOrEmpty(order.NotesForSupplier) && order.NotesForSupplier.Contains(word))
                        {
                            TextMatchOrders.Add(order);
                            break;
                        }
                    }
                }

                model.Matches = TextMatchOrders;
            }
            else
            {
                model.Matches = matchingOrders;
            }

            return View(model);
        }
 public UsersController()
 {
     _repository = new UsersRepository(User);
 }
Example #42
0
 public UserController(UsersRepository userRepository)
 {
     this.userRepository = userRepository;
 }
Example #43
0
        public static User EnsureUserIsRegistered(UsersRepository repository, string username)
        {
            if (!repository.UserName_User.ContainsKey(username))
            {
                throw new ArgumentException($"A user with username {username} does not exist.");
            }

            return repository.UserName_User[username];
        }
Example #44
0
 public NoteController(ApplicationDbContext context)
 {
     _noteRepository     = new NoteRepository(context);
     _usersRepository    = new UsersRepository(context);
     _categoryRepository = new CategoryRepository(context);
 }
 public DziennikMembershipProvider()
 {
     repository = new UsersRepository(new EFContext());
 }
Example #46
0
        private void setUserRegSeenTrue(int userid)
        {
            UsersRepository ur = new UsersRepository();

            ur.setRegSeenToTrue(userid);
        }
Example #47
0
 public UnitOfWork(AppDbContext context)
 {
     _context        = context;
     UsersRepository = new UsersRepository(_context);
 }
Example #48
0
 public ReposTests(string connString)
 {
     repo = new UsersRepository(connString);
 }
        public ActionResult EditUser(UsersEditUserVM model, string[] assignedRoles)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();

            ModelState.Remove("DateOut");

            UsersRepository usersRepositoryContext = new UsersRepository(context);
            if (model.Email != null && usersRepositoryContext.GetAll().Any(u => u.Email == model.Email) &&
                model.ID != usersRepositoryContext.GetAll(filter: u => u.Email == model.Email).FirstOrDefault().ID)
            {
                ModelState.AddModelError("Email", "* email already exists");
            }
            if (model.ID <= 0 && string.IsNullOrEmpty(model.Password))
            {
                this.ModelState.AddModelError("Password", "* password required");
            }
            if (!this.ModelState.IsValid)
            {
                RolesRepository rolesRepository = new RolesRepository(context);
                var allRoles = rolesRepository.GetAll();

                List<AssignedRolesVM> assignedRolesViewModel = new List<AssignedRolesVM>();
                foreach (var role in allRoles)
                {
                    assignedRolesViewModel.Add(new AssignedRolesVM
                        {
                            ID = role.ID,
                            Name = role.Name,
                            IsAssigned = false
                        });
                }

                ViewBag.Roles = assignedRolesViewModel;
                return View(model);
            }

            TryUpdateModel(model);

            User user = null;
            using (UnitOfWork unitOfWork = new UnitOfWork(context))
            {
                try
                {
                    UsersRepository usersRepositoryUnitOfWork = new UsersRepository(unitOfWork);
                    RolesRepository rolesRepository = new RolesRepository(unitOfWork);

                    if (model.ID > 0)
                    {
                        user = usersRepositoryUnitOfWork.GetAll(filter: u => u.ID == model.ID, includeProperties: "Roles").FirstOrDefault();
                        user.PersonalNumber = model.PersonalNumber;
                    }
                    else
                    {
                        user = new User();
                        user.Roles = new List<Role>();
                        user.PersonalNumber = usersRepositoryUnitOfWork.GetAll().LastOrDefault().PersonalNumber + 1;
                    }

                    user.Password =
                        (model.Password != null) && (model.Password.Trim() != String.Empty) ? model.Password.Trim() : user.Password;
                    user.FirstName = model.FirstName;
                    user.Email = model.Email;
                    user.Address = model.Address;
                    user.LastName = model.LastName;
                    user.Birthday = model.Birthday;
                    user.DateIn = model.DateIn;
                    user.DateOut = model.DateOut != null ? model.DateOut : null;

                    UpdateUserRoles(assignedRoles, user, rolesRepository);
                    usersRepositoryUnitOfWork.Save(user);

                    PopulateAssignedRoles(user, rolesRepository);
                    unitOfWork.Commit();
                }
                catch (Exception ex)
                {
                    unitOfWork.RollBack();
                    throw ex;
                }
            }

            return RedirectToAction("Index", "Users");
        }
        public ActionResult FileUpload(FileUpload sf, HttpPostedFileBase file)
        {
            try
            {
                if (file != null)
                {
                    var    storage = StorageClient.Create();
                    string link    = "";
                    using (var f = file.InputStream)
                    {
                        var filename      = Guid.NewGuid() + System.IO.Path.GetExtension(file.FileName);
                        var storageObject = storage.UploadObject("justinportellipfc", filename, null, f);

                        link = "https://storage.cloud.google.com/justinportellipfc/" + filename;


                        if (null == storageObject.Acl)
                        {
                            storageObject.Acl = new List <ObjectAccessControl>();
                        }


                        storageObject.Acl.Add(new ObjectAccessControl()
                        {
                            Bucket = "justinportellipfc",
                            Entity = $"user-" + User.Identity.Name, //whereas [email protected] has to be replaced by a gmail email address who you want to have access granted
                            Role   = "OWNER",                       //READER
                        });

                        storageObject.Acl.Add(new ObjectAccessControl()
                        {
                            Bucket = "justinportellinpfc",
                            Entity = $"user-" + sf.receiverEmail, //whereas [email protected] has to be replaced by a gmail email address who you want to have access granted
                            Role   = "READER",                    //READER
                        });

                        var updatedObject = storage.UpdateObject(storageObject, new UpdateObjectOptions()
                        {
                            // Avoid race conditions.
                            IfMetagenerationMatch = storageObject.Metageneration,
                        });
                        FileRepository  fr = new FileRepository();
                        UsersRepository ur = new UsersRepository();
                        CacheRepository cr = new CacheRepository();
                        fr.AddFile(filename.ToString(), link, sf.receiverEmail, ur.GetUserID(User.Identity.Name));
                        cr.UpdateCache(GetFiles(ur.GetUserID(User.Identity.Name)), ur.GetUserID(User.Identity.Name));

                        PubSubRepository psr = new PubSubRepository();
                        psr.AddToEmailQueue(sf);
                    }


                    ViewBag.Message = "File uploaded";
                    LogsRepository logr = new LogsRepository();
                    logr.WriteLogEntry("File was Uploaded");
                }
            }
            catch (Exception ex)
            {
                LogsRepository logr = new LogsRepository();
                logr.LogError(ex);
                ViewBag.Message = "File was not uploaded";
            }
            return(View());
        }
        public ActionResult Index(string sortOrder)
        {
            LibraryManagementSystemContext context = new LibraryManagementSystemContext();
            UsersRepository usersRepository = new UsersRepository(context);
            UsersIndexVM model = new UsersIndexVM();
            this.TryUpdateModel(model);

            model.UsersPager = model.UsersPager ?? new GenericPagerVM();
            model.UsersPager.CurrentPage = model.UsersPager.CurrentPage == 0 ? 1 : model.UsersPager.CurrentPage;
            model.UsersPager.Action = "Index";
            model.UsersPager.Controller = "Users";
            model.UsersPager.Prefix = "UsersPager";
            model.UsersPager.CurrentParameters = new Dictionary<string, object>()
            {
                { "PersonaNumber", model.PersonalNumber },
                { "CustomerName", model.UserName },
                { "Email", model.Email },
                { "Address", model.Address },
                { "RoleName", model.RoleName },
                { "BirthdayStartDate", model.BirthdayStartDate },
                { "BirthdayEndDate", model.BirthdayEndDate },
                { "DateInStartDate", model.DateInStartDate },
                { "DateInEndDate", model.DateInEndDate },
                { "DateOutStartDate", model.DateOutStartDate },
                { "DateOutEndDate", model.DateOutEndDate },
                { "UsersPager.CurrentPage", model.UsersPager.CurrentPage }
            };

            #region Soring and Filtering
            Expression<Func<User, bool>> filter = u =>
                   (model.PersonalNumber == default(int) || u.PersonalNumber == model.PersonalNumber) &&
                   (string.IsNullOrEmpty(model.UserName) || (u.FirstName.Contains(model.UserName) || u.LastName.Contains(model.UserName))) &&
                   (string.IsNullOrEmpty(model.Email) || u.Email.Contains(model.Email)) &&
                   (string.IsNullOrEmpty(model.Address) || u.Address.Contains(model.Address)) &&
                   (string.IsNullOrEmpty(model.RoleName) || u.Roles.Any(r => r.Name.Contains(model.RoleName))) &&
                   (model.BirthdayStartDate == default(DateTime) || (u.Birthday == model.BirthdayStartDate || (u.Birthday >= model.BirthdayStartDate && u.Birthday <= model.BirthdayEndDate))) &&
                   (model.DateInStartDate == default(DateTime) || (u.DateIn == model.DateInStartDate || (u.DateIn >= model.DateInStartDate && u.Birthday <= model.DateInEndDate))) &&
                   (model.DateOutStartDate == default(DateTime) || (u.DateOut == model.DateOutStartDate || (u.DateOut >= model.DateOutStartDate && u.Birthday <= model.DateOutEndDate)));
            model.UsersPager.PagesCount = GetPagesCount(filter);

            ViewBag.NameSortParam = string.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.RolesSortParam = sortOrder == "Roles" ? "roles_desc" : "Roles";
            ViewBag.PersonalNumberSortParam = sortOrder == "PersonalNumber" ? "personalNumber_desc" : "PersonalNumber";
            ViewBag.EmailSortParam = sortOrder == "Email" ? "email_desc" : "Email";
            ViewBag.AddressSortParam = sortOrder == "Address" ? "address_desc" : "Address";
            ViewBag.BirthdaySortParam = sortOrder == "Birthday" ? "birthday_desc" : "Birthday";
            ViewBag.DateInSortParam = sortOrder == "DateIn" ? "dateIn_desc" : "DateIn";
            ViewBag.DateOutSortParam = sortOrder == "DateOut" ? "dateOut_desc" : "DateOut";
            switch (sortOrder)
            {
                case "name_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.FirstName));
                    break;
                case "Roles":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Roles.FirstOrDefault().Name));
                    break;
                case "roles_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Roles.FirstOrDefault().Name));
                    break;
                case "PersonalNumber":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.PersonalNumber));
                    break;
                case "personalNumber_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.PersonalNumber));
                    break;
                case "Email":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Email));
                    break;
                case "email_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Email));
                    break;
                case "Address":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Address));
                    break;
                case "address_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Address));
                    break;
                case "Birthday":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.Birthday));
                    break;
                case "birthday_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.Birthday));
                    break;
                case "DateIn":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.DateIn));
                    break;
                case "dateIn_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.DateIn));
                    break;
                case "DateOut":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.DateOut));
                    break;
                case "dateOut_desc":
                    model.UsersList = usersRepository
                        .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderByDescending(c => c.DateOut));
                    break;
                default:
                    model.UsersList = usersRepository
                       .GetAll(model.UsersPager.CurrentPage, ApplicationConfiguration.ItemsPerPage, filter, order: x => x.OrderBy(c => c.FirstName));
                    break;
            }
            #endregion

            return View(model);
        }
 public AccountService(IConfiguration configuration, UsersRepository usersRepository)
 {
     _configuration   = configuration;
     _usersRepository = usersRepository;
 }
 public UsersService(UsersRepository usersRepository, ILogger <UsersService> logger, PublishingRouter publishingRouter)
 {
     this.usersRepository  = usersRepository;
     this.logger           = logger;
     this.publishingRouter = publishingRouter;
 }
Example #54
0
 public UserService()
 {
     usersRepositoryG = new GenericRepository <Users>();
     usersRepository  = new UsersRepository();
 }
 public HomeController(UsersRepository usersRepository, PersistentRepository persistentRepository)
 {
     UsersRepository = usersRepository;
     PersistentRepository = persistentRepository;
 }
Example #56
0
 public AuthController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, UsersRepository userRepo)
 {
     UserManager   = userManager;
     SignInManager = signInManager;
     UserRepo      = userRepo;
 }
Example #57
0
        public ActionResult SearchForm(OrdersSearchValuesModel model, bool isExpanding, bool isCollapsed, int? userId = null, int? statusId = null, int? supplierId = null, bool hideUserField = false, bool hideStatusField = false, bool hideSupplierField = false)
        {
            if (model == null) model = new OrdersSearchValuesModel();

            using (UsersRepository usersRep = new UsersRepository(CurrentUser.CompanyId))
            using (BudgetsRepository budgetsRep = new BudgetsRepository(CurrentUser.CompanyId))
            using (SuppliersRepository suppliersRep = new SuppliersRepository(CurrentUser.CompanyId))
            using (OrderStatusesRepository statusesRep = new OrderStatusesRepository())
            using (AllocationRepository allocationsRep = new AllocationRepository(CurrentUser.CompanyId))
            {
                List<SelectListItemDB> usersAsSelectItems = new List<SelectListItemDB>() { new SelectListItemDB() { Id = -1, Name = Loc.Dic.AllUsersOption } };
                usersAsSelectItems.AddRange(usersRep.GetList().Select(x => new SelectListItemDB() { Id = x.Id, Name = x.FirstName + " " + x.LastName }));
                model.UsersList = new SelectList(usersAsSelectItems, "Id", "Name");

                List<SelectListItemDB> budgetsAsSelectItems = new List<SelectListItemDB>() { new SelectListItemDB() { Id = -1, Name = Loc.Dic.AllBudgetsOption } };
                budgetsAsSelectItems.AddRange(budgetsRep.GetList().AsEnumerable().Select(x => new SelectListItemDB() { Id = x.Id, Name = "(" + x.Year + ") " + x.Name }));
                model.BudgetsList = new SelectList(budgetsAsSelectItems, "Id", "Name");

                List<Supplier> suppliersSelectList = new List<Supplier>() { new Supplier() { Id = -1, Name = Loc.Dic.AllSuppliersOption } };
                suppliersSelectList.AddRange(suppliersRep.GetList().OrderByDescending(x => x.Name).ToList());
                model.SuppliersList = new SelectList(suppliersSelectList, "Id", "Name");

                List<Orders_Statuses> statusesSelectList = new List<Orders_Statuses>() { new Orders_Statuses() { Id = -1, Name = Loc.Dic.AllStatusesOption } };
                statusesSelectList.AddRange(statusesRep.GetList().ToList());
                model.StatusesList = new SelectList(statusesSelectList, "Id", "Name");

                List<SelectListStringItem> allocationsSelectList = new List<SelectListStringItem>() { new SelectListStringItem() { Id = "-1", Name = Loc.Dic.AllAllocationsOption } };
                allocationsSelectList.AddRange(allocationsRep.GetList().GroupBy(x => x.ExternalId).AsEnumerable().Select(x => new SelectListStringItem() { Id = x.First().ExternalId, Name = x.First().DisplayName }).ToList());
                model.AllocationsList = new SelectList(allocationsSelectList, "Id", "Name");
            }

            ViewBag.IsExpanding = isExpanding;
            ViewBag.IsCollapsed = isCollapsed;
            ViewBag.UserId = userId;
            ViewBag.StatusId = statusId;
            ViewBag.SupplierId = supplierId;
            ViewBag.HideUserField = hideUserField;
            ViewBag.HideStatusField = hideStatusField;
            ViewBag.HideSupplierField = hideSupplierField;
            return PartialView(model);
        }
Example #58
0
 public AppService(UsersRepository usersRepo, BugsRepository bugsRepo)
 {
     this.usersRepo = usersRepo;
     this.bugsRepo  = bugsRepo;
     loggedUsers    = new Dictionary <string, User>();
 }
Example #59
0
 protected override void DisposeCore()
 {
     lock (_lockObject)
     {
         _connectionDbRepository = null;
         _projectsRepository = null;
         _projectsShareRepository = null;
         _queriesRepository = null;
         _usersRepository = null;
     }
     QueryBuilderContext.Dispose();
 }
Example #60
0
 public JwtTokenProvider(UsersRepository usersRepository)
 {
     this.usersRepository = usersRepository;
 }