Beispiel #1
0
        public void SendMailTest()
        {
            AccountController target = new AccountController();

            target.SendEmail("*****@*****.**","testc");
            Assert.IsTrue(true);
        }
        public void LoginTableTest()
        {
            //Arrange
            var tableGuid = Guid.NewGuid();
            var tableLogin = "******";
            var tablePassword = "******";
            var tableFirstHash = HashUtility.CreateFirstHash(tablePassword, tableLogin);
            var tableSecondHash = HashUtility.CreateSecondHashFromFirst(tableFirstHash);

            var viewProviderMock = new Mock<IViewProvider>();
            viewProviderMock.Setup(vp => vp.Get<TableView>()).Returns(new[] { new TableView() { Title = "title", Description = "description", Login = tableLogin, TableGuid = tableGuid, TableId = 0, SecondHash = tableSecondHash, UserId = tableGuid} }.AsQueryable());

            var unitOfWorkMock = new Mock<IUnitOfWork>();
            unitOfWorkMock.Setup(uow => uow.Add(It.IsAny<ActiveUser>())).Returns<ActiveUser>(au => au);

            var commandBusMock = new Mock<ICommandBus>();

            var accountController = new AccountController(unitOfWorkMock.Object, viewProviderMock.Object, commandBusMock.Object);

              var loginModel = new LoginModel() { Login = tableLogin, FirstHash = tableFirstHash };

            //Act
            var actionResult = accountController.LoginTable(loginModel);

            //Assert
            var okNegotiatedContentResult = actionResult as OkNegotiatedContentResult<Guid>;
            Assert.IsNotNull(okNegotiatedContentResult);
            Assert.IsTrue(okNegotiatedContentResult.Content != Guid.Empty);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string to = Request["To"].ToString();
            string body = Request["Body"].ToString();
            string from = Request["From"].ToString();

            var docStore = Application["DocumentStore"] as DocumentStore;
            var repository = new RavenDBRepository(docStore);
            var accountController = new AccountController();
            var users = accountController.GetActiveUsers(repository);

            var keywordProcessor = new KeywordProcessor(docStore);
            var message = keywordProcessor.SetActiveUsersForMatch(users)
                                            .MatchReplyToOriginalMessage(body, from);

            using (var session = docStore.OpenSession())
            {
                var step = session.Load<Step>(message.SubjectMatterId);
                step.Answer = message.UserAnswer;
                step.AnswerDate = DateTime.Now;
                string json = JsonConvert.SerializeObject(step);

                var workflowController = new WorkflowController();
                workflowController.ProcessStep(json, repository,
                                                   Application["Registry"] as RavenFilterRegistry<Step>,
                                                   message.UserId);
            }
        }
        public AccountRegisterTest()
        {
            _repository = Substitute.For<IUserRepository>();
            _validator = Substitute.For<IEmailValidator>();

            _controller=new AccountController(_repository, _validator);
        }
        public void DoesNotSendMessageIfUserIsNotConfirmedOrIfEmailDoesNotMatchUser(int userId, string submittedEmail, bool isConfirmed)
        {
            var webSecurity = Substitute.For<IWebSecurityService>();
            webSecurity.GetUserId("haacked").Returns(userId);
            webSecurity.IsConfirmed("haacked").Returns(isConfirmed);
            var messengerService = Substitute.For<IMessengerService>();
            var users = new TestDbSet<User> { new User { Id = 42, Name = "haacked", Email = "*****@*****.**" }, new User() };
            var tournamentContext = Substitute.For<ITournamentContext>();
            tournamentContext.Users.Returns(users);
            var accountController = new AccountController(webSecurity, messengerService, tournamentContext);
            var request = Substitute.For<HttpRequestBase>();
            request.Url.Returns(new Uri("http://localhost/"));
            var httpContext = Substitute.For<HttpContextBase>();
            httpContext.Request.Returns(request);
            accountController.ControllerContext = new ControllerContext(httpContext, new RouteData(), accountController);
            var forgotPasswordModel = new ForgotPasswordModel
            {
                UserName = "******",
                Email = submittedEmail
            };

            accountController.ForgotPassword(forgotPasswordModel);

            messengerService.DidNotReceive().Send(Args.String, Args.String, Args.String, Args.String, Args.Boolean);
        }
        public void Login_ValidCredentials_AuthenticateAndRedirect()
        {
            // arrange
            var model = new LoginViewModel { Password = "******", Email = "*****@*****.**", RememberMe = true };
            var returnUrl = "/home/index";
            bool calledValidateUser = false;
            bool calledSetCookie = false;
            using(ShimsContext.Create())
            {
                System.Web.Security.Fakes.ShimMembership.ValidateUserStringString = (usr, pwd) =>
                {
                    calledValidateUser = true;
                    return usr == "*****@*****.**" && pwd == "123";
                };

                System.Web.Security.Fakes.ShimFormsAuthentication.SetAuthCookieStringBoolean = (email, remeberMe) =>
                {
                    calledSetCookie = true;
                };

                // act
                AccountController controller = new AccountController();
                var redirectResult = controller.Login(model, returnUrl) as RedirectResult;

                // assert
                Assert.IsTrue(calledValidateUser, "Membership.ValidateUser not invoked");
                Assert.IsTrue(calledSetCookie, "FormsAuthentication.SetAuthCookie not invoked");
                Assert.AreEqual(returnUrl, redirectResult.Url);
            }
        }
        public void ManageTest()
        {
            var controller = new AccountController(_membershipServiceSub);
            var result = controller.Manage();

            Assert.IsNotNull(result);
        }
        public void account_controller_should_login_user()
        {
            var repository = Substitute.For<IRepository>();
            var usersView = Substitute.For<IUsersView>();
            var authentication = Substitute.For<IFormsAuthentication>();

            bool authenticated = false;
            authentication.WhenForAnyArgs(a => a.SetAuthentication(null, false)).Do(i => authenticated = true);

            var controller = new AccountController();
            controller.DataRepository = repository;
            controller.UsersByLogin = usersView;
            controller.FormsAuthentication = authentication;

            var dto = FakeUser.ArrangeUserDto();
            var user = User.CreateUser(dto.Login, dto.Password, new ConstantIdentityGenerator(){ Identity = dto.AggregateRootId});

            usersView.GetUserId(dto.Login).Returns(dto.AggregateRootId);
            repository.GetById<User>(dto.AggregateRootId).Returns(user);

            var result = controller.Login(dto);

            result.Should().BeOfType<RedirectResult>();
            authenticated.Should().BeTrue();
        }
        public void SendsResetMessageIfUserIsConfirmedAndEmailMatchesUserEmail()
        {
            var webSecurity = Substitute.For<IWebSecurityService>();
            webSecurity.GetUserId("haacked").Returns(42);
            webSecurity.IsConfirmed("haacked").Returns(true);
            var messengerService = Substitute.For<IMessengerService>();
            var users = new TestDbSet<User> { new User { Id = 42, Name = "haacked", Email = "*****@*****.**" }, new User() };
            var tournamentContext = Substitute.For<ITournamentContext>();
            tournamentContext.Users.Returns(users);
            var accountController = new AccountController(webSecurity, messengerService, tournamentContext);
            var request = Substitute.For<HttpRequestBase>();
            request.Url.Returns(new Uri("http://localhost/"));
            var httpContext = Substitute.For<HttpContextBase>();
            httpContext.Request.Returns(request);
            accountController.ControllerContext = new ControllerContext(httpContext, new RouteData(), accountController);
            var forgotPasswordModel = new ForgotPasswordModel
            {
                UserName = "******",
                Email = "*****@*****.**"
            };

            accountController.ForgotPassword(forgotPasswordModel);

            messengerService.Received().Send(Args.String, Args.String, Args.String, Args.String, Args.Boolean);
        }
        public void LoginWaiterTest()
        {
            //Arrange
            var waiterGuid = Guid.NewGuid();
            var waiterLogin = "******";
            var waiterPassword = "******";
            var waiterFirstHash = HashUtility.CreateFirstHash(waiterPassword, waiterLogin);
            var waiterSecondHash = HashUtility.CreateSecondHashFromFirst(waiterFirstHash);

            var viewProviderMock = new Mock<IViewProvider>();
            viewProviderMock.Setup(vp => vp.Get<WaiterView>()).Returns(new[] { new WaiterView() { FirstName = "firstName", LastName = "lastName", Login = waiterLogin, WaiterGuid = waiterGuid, WaiterId = 0, UserId = waiterGuid, SecondHash = waiterSecondHash } }.AsQueryable());

            var unitOfWorkMock = new Mock<IUnitOfWork>();
            unitOfWorkMock.Setup(uow => uow.Add(It.IsAny<ActiveUser>())).Returns<ActiveUser>(au => au);

            var commandBusMock = new Mock<ICommandBus>();

            var accountController = new AccountController(unitOfWorkMock.Object, viewProviderMock.Object, commandBusMock.Object);

              var loginModel = new LoginModel() { Login = waiterLogin, FirstHash = waiterFirstHash };

            //Act
            var actionResult = accountController.LoginWaiter(loginModel);

            //Assert
            var okNegotiatedContentResult = actionResult as OkNegotiatedContentResult<Guid>;
            Assert.IsNotNull(okNegotiatedContentResult);
            Assert.IsTrue(okNegotiatedContentResult.Content != Guid.Empty);
        }
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            var account = new AccountController();
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            if (UserManager.IsInRole(user.Id, RoleName))
            {
                UserManager.RemoveFromRole(user.Id, RoleName);
                var employee = context.Employees.Single(x => x.employeeFirstName == user.FirstName && x.employeeLastName ==user.LastName);
                var role = context.RolesForEmployees.Single(x => x.roleName == RoleName);
                var tmp = context.EmployeeRoles.Single(x => x.role == role && x.employee == employee);
                context.EmployeeRoles.Remove(tmp);
                context.SaveChanges();

                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;

            return View("ManageUserRoles");
        }
        public void x(Table table)
        {
            var form = table.CreateInstance<CreateAccountForm>();

            var controller = new AccountController(Database.Open());

            controller.Create(form);
        }
 public void LoginErrorTest()
 {
     AccountController target = new AccountController(); // TODO: Initialize to an appropriate value
     ActionResult expected = null; // TODO: Initialize to an appropriate value
     ActionResult actual;
     actual = target.LoginError();
     Assert.AreEqual(expected, actual);
       //  Assert.Inconclusive("Verify the correctness of this test method.");
 }
        public ActionResult AddRmvExstngTrtmnts(CreateEditTrtmntViewModel NewCreatedTreatment)
        {
            var account = new AccountController();
            var currentUser = account.UserManager.FindById(User.Identity.GetUserId());
            //perform db operation to add Treatment
            this._svcTrtmntRepository.AddRmvExstngTrtmnts(currentUser.CompanyID, NewCreatedTreatment);

            return RedirectToAction("Index");
        }
 public void PrivitiveParameterTest()
 {
     // arrange
     var controllerAction = new AccountController().Action(e => e.DeleteUser(1));
     // act
     var result = (ContentResult)controllerAction.GetActionResult();
     //assert
     Assert.AreEqual("Deleting User 1", result.Content);
 }
        public ActionResult CreateSvc(Service NewService)
        {
            var account = new AccountController();
            var currentUser = account.UserManager.FindById(User.Identity.GetUserId());

            //perform db operation to add svc
            this._svcTrtmntRepository.AddNewService(currentUser.CompanyID, NewService);

            return RedirectToAction("Index");
        }
        public void ShouldNotValidateModelWhenGetActionResult()
        {
            // arrange
            var invalidModel = new ChangePasswordModel {  };
            var controllerAction = new AccountController().Action(c => c.ChangePassword(invalidModel));
            var context = controllerAction.GetExecutionContext();

            // act
            controllerAction.GetActionResult(context);
            //assert
            context.ModelState.IsValid.Should().BeTrue();
        }
 public AccountControllerMock()
 {
     _request.Setup(r => r.Url).Returns(new Uri("http://www.strixit.com"));
     _httpContext.Setup(r => r.Request).Returns(_request.Object);
     var principal = new Mock<IPrincipal>();
     principal.Setup(p => p.Identity).Returns(_identity.Object);
     _httpContext.Setup(r => r.User).Returns(principal.Object);
     _controllerContext.Setup(c => c.HttpContext).Returns(_httpContext.Object);
     _controllerContext.Setup(c => c.IsChildAction).Returns(false);
     _controller = new AccountController(_authService.Object, _accountService.Object);
     _controller.ControllerContext = _controllerContext.Object;
 }
        public void account_controller_should_create_user()
        {
            CreateNewUserCommand receivedCommand = null;
            var controller = new AccountController();
            var handler = Substitute.For<ICommandHandler<CreateNewUserCommand>>();
            handler.WhenForAnyArgs(h => h.Execute(null)).Do(a => receivedCommand = a.Arg<CreateNewUserCommand>());
            controller.CreateNewUserHandler = handler;

            var dto = FakeUser.ArrangeUserDto();
            controller.Create(dto);

            receivedCommand.Should().NotBeNull();
        }
 public void ExpressionParameterTest()
 {
     // arrange
     var controllerAction = new AccountController()
         .Action(e => e.DeleteUser(0))
         .RequestData(new Dictionary<string, object>
         {
             {"userId", 1 }
         });
     // act
     var result = (ContentResult)controllerAction.GetActionResult();
     //assert
     Assert.AreEqual("Deleting User 1", result.Content);
 }
        public void Add_User_Success()
        {
            _membershipServiceSub
                .CreateUser(Arg.Any<MembershipUser>())
                .Returns(x => MembershipCreateStatus.Success);

            var viewModel = new MemberAddViewModel
            {
                Comment = "Test"
            };
            var controller = new AccountController(_membershipServiceSub);
            controller.Add(viewModel);

            Assert.IsTrue(controller.ModelState.IsValid);
        }
        public ActionResult CreateTreatment2(string SvcDetails)
        {
            var account = new AccountController();
            var currentUser = account.UserManager.FindById(User.Identity.GetUserId());

            CreateEditTrtmntViewModel objNewTrtmnt = new CreateEditTrtmntViewModel();

            //getting service Id and name - associated with treatment
            objNewTrtmnt.SvcID = Convert.ToInt64(SvcDetails.Split(new char[] { '~' })[0]);
            objNewTrtmnt.SvcName = SvcDetails.Split(new char[] { '~' })[1];

            objNewTrtmnt.NewTreatment = new Treatment();
            objNewTrtmnt.ExistingTreatments = (IList<BasicTreatmentViewModel>)this._svcTrtmntRepository.GetAllTreatments(currentUser.CompanyID, objNewTrtmnt.SvcID);

            return PartialView("_CreateTreatment2", objNewTrtmnt);
        }
        public void ShouldConfirmNewUserWithTokenAndNewPassword()
        {
            var model = new RegisterModelBuilder()
                .Build();

            var mock = GetEmailMock();
            string secureToken = null;

            mock.Setup(e => e.SendConfirmation(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<int>()))
                .Callback<string, string, string, int>((from, to, token, userId) =>
                {
                    secureToken = token;
                });
            string oldPassword = "";
            UsingSession(session =>
            {
                var controller = new AccountController(session) { EmailService = mock.Object };
                controller.Create(model);
                oldPassword = session.Query<User>().First(u => u.Username == model.Email).Password;
            });

            UsingSession(session =>
            {
                var user = session.Query<User>().First();
                var controller = new AccountController(session) { EmailService = mock.Object };
                var localPasswordModel = new LocalPasswordModelBuilder()
                    .WithSecurityToken(secureToken)
                    .WithUserId(user.Id)
                    .Build();
                var mockAccountService = new Mock<IAccountService>();
                mockAccountService.Setup(s => s.Login(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>())).Returns(true);
                controller.AccountService = mockAccountService.Object;
                var actionResult = (System.Web.Mvc.RedirectToRouteResult)(controller.RegisterConfirmation(localPasswordModel));
                Assert.AreEqual("Home", actionResult.RouteValues["controller"]);
                Assert.AreEqual("Index", actionResult.RouteValues["action"]);
            });

            UsingSession(session =>
            {
                Assert.IsTrue(session.Query<User>().First(u=>u.Username==model.Email).IsApproved);
                Assert.AreNotEqual(oldPassword,
                    session.Query<User>().First(u => u.Username == model.Email).Password);
            });
        }
 protected void btnUpdate_Click(object sender, EventArgs e)
 {
     AccountController oAccountController = new AccountController();
     Account oAccount = new Account();
     oAccount.Name = txtName.Text;
     oAccount.Surname = txtSurname.Text;
     oAccount.BirthDay = txtBirthDay.Text;
     oAccount.Phone = txtPhone.Text;
     oAccount.Email = txtEmail.Text;
     oAccount.Password = txtPassword.Text;
     oAccount.CityId = Convert.ToInt32(dllCity.SelectedValue.ToString());
     oAccount.Adress = txtAdress.Text;
     if (oAccount.ProfilImage != Session["imgAccount"].ToString())
     {
         oAccount.ProfilImage = Session["imgAccount"].ToString();
     }
     oAccountController.AccountUpdate(oAccount);
     Response.Redirect("~/Login.aspx");
 }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Account oAccount = new Account();
        oAccount.Email = TextBox1.Text;
        oAccount.Password = TextBox2.Text;

        AccountController oAccountController = new AccountController();
        oAccount = oAccountController.Login(oAccount);
        if (oAccount.Id > 0)
        {
            Session["Account"] = oAccount;
            Response.Redirect("User/Profil.aspx");

        }
        else
        {
            lblresult.Text = "Giris bilgileri hatalı";
        }
    }
        public void ModelStateTest(string newPassword, string confirmPassword, bool newPasswordValid, bool confirmPasswordValid)
        {
            // arrange
            // var model = new ChangePasswordModel { NewPassword = newPassword, ConfirmPassword = confirmPassword };
            var controllerAction = new AccountController()
                .Action("ChangePassword")
                .RequestData(new Dictionary<string, object>()
                {
                    {"newpassword", newPassword},
                    {"confirmPassword", confirmPassword}
                });

            // act
            var modelState = controllerAction.ValidateRequest();

            // assert
            Assert.AreEqual(newPasswordValid, modelState.IsValidField("model.NewPassword"));
            Assert.AreEqual(confirmPasswordValid, modelState.IsValidField("model.ConfirmPassword"));
        }
        public void should_succeed_if_registered()
        {


            AuthService auth = new AuthService();
            var acontroller = new AccountController(auth);
            acontroller.Request = new HttpRequestMessage();
            acontroller.Configuration = new HttpConfiguration();
            var p = new UserModel
           {
               Name = "*****@*****.**",
               Password = "******",
               ConfirmPassword = "******"

           };
            var res = acontroller.Register(p);


        }
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
            var account = new AccountController();
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (account.UserManager.IsInRole(user.Id, RoleName))
            {
                account.UserManager.RemoveFromRole(user.Id, RoleName);
                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;

            return View("ManageUserRoles");
        }
Beispiel #29
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            AccountController account = new AccountController();

            //Get Session
            var context = filterContext.HttpContext;
            var usernameFromSession = context.Session["username"];

            //Testen ob die Session erstellt wurde:
            if(usernameFromSession != null)
            {
                if (String.IsNullOrWhiteSpace(account.GetRole(usernameFromSession.ToString())))
                {
                    filterContext.Result = new RedirectResult("~/Home/Index");
                }
            }else
            {
                filterContext.Result = new RedirectResult("~/Home/Index");
            }
        }
        public void Login()
        {
            Mock<ISecurityAdapter> mockSecurityAdapter = new Mock<ISecurityAdapter>();
            mockSecurityAdapter.Setup(obj => obj.Initialize());

            string returnUrl = "/testreturnurl";

            AccountController controller = new AccountController(mockSecurityAdapter.Object);

            ActionResult result = controller.Login(returnUrl);

            Assert.IsTrue(result is ViewResult);

            ViewResult viewResult = result as ViewResult;

            Assert.IsTrue(viewResult.Model is AccountLoginModel);

            AccountLoginModel model = viewResult.Model as AccountLoginModel;

            Assert.IsTrue(model.ReturnUrl == returnUrl);
        }
        public void pagingall(List <PostSQL> acs)
        {
            string username = Request.Cookies["userLoginSystem"].Value;
            var    acc      = AccountController.GetByUsername(username);

            int           PageSize = 30;
            StringBuilder html     = new StringBuilder();

            html.Append("<tr>");
            html.Append("    <th class='image-column'>Ảnh</th>");
            html.Append("    <th class='name-column'>Tiêu đề</th>");
            html.Append("    <th class='sku-column'>Nổi bật</th>");
            html.Append("    <th class='stock-status-column'>Trạng thái</th>");
            html.Append("    <th class='category-column'>Danh mục</th>");
            html.Append("    <th class='date-column'>Ngày tạo</th>");
            html.Append("    <th class='action-column'></th>");
            html.Append("</tr>");

            if (acs.Count > 0)
            {
                int TotalItems = acs.Count;
                if (TotalItems % PageSize == 0)
                {
                    PageCount = TotalItems / PageSize;
                }
                else
                {
                    PageCount = TotalItems / PageSize + 1;
                }

                Int32 Page = GetIntFromQueryString("Page");

                if (Page == -1)
                {
                    Page = 1;
                }
                int FromRow = (Page - 1) * PageSize;
                int ToRow   = Page * PageSize - 1;
                if (ToRow >= TotalItems)
                {
                    ToRow = TotalItems - 1;
                }

                for (int i = FromRow; i < ToRow + 1; i++)
                {
                    var item = acs[i];
                    html.Append("<tr class='item-" + item.ID + "'>");

                    html.Append("<td>");
                    html.Append("   <a href=\"/xem-bai-viet?id=" + item.ID + "\"><img src=\"" + item.Image + "\"/></a>");
                    html.Append("   <a href=\"javascript:;\" onclick=\"copyPostInfo(" + item.ID + ")\" class=\"btn download-btn h45-btn\"><i class=\"fa fa-files-o\"></i> Copy</a>");
                    html.Append("</td>");

                    html.Append("   <td class=\"customer-name-link\"><a href=\"/xem-bai-viet?id=" + item.ID + "\">" + item.Title + "</a></td>");

                    if (item.Featured == 1)
                    {
                        html.Append("   <td>Có</td>");
                    }
                    else
                    {
                        html.Append("   <td>Không</td>");
                    }

                    if (item.Status == 1)
                    {
                        html.Append("   <td>Đang hiện</td>");
                    }
                    else
                    {
                        html.Append("   <td>Đang ẩn</td>");
                    }

                    html.Append("   <td>" + item.CategoryName + "</td>");
                    string date = string.Format("{0:dd/MM/yyyy}", item.CreatedDate);
                    html.Append("   <td>" + date + "</td>");

                    html.Append("   <td>");
                    html.Append("       <a href=\"javascript:;\" title=\"Download tất cả hình bài viết này\" class=\"btn primary-btn h45-btn\" onclick=\"getAllPostImage('" + item.ID + "');\"><i class=\"fa fa-file-image-o\" aria-hidden=\"true\"></i></a>");
                    html.Append("       <a href=\"javascript:;\" title=\"Xóa bài này\" class=\"btn primary-btn h45-btn\" onclick=\"deletePost('" + item.ID + "');\"><i class=\"fa fa-times\" aria-hidden=\"true\"></i></a>");
                    html.Append("  </td>");
                    html.Append("</tr>");
                }
            }
            else
            {
                html.Append("<tr><td colspan=\"11\">Không tìm thấy bài viết...</td></tr>");
            }

            ltrList.Text = html.ToString();
        }
 public void BeforeTests()
 {
     MockDb       = new Mock <IDatabase>();
     TokenBuilder = new Mock <ITokenBuilder>();
     controller   = new AccountController(MockDb.Object, TokenBuilder.Object);
 }
Beispiel #33
0
        public static string checkphone(string phonefullname)
        {
            RefundCust rf       = new RefundCust();
            int        AgentID  = 0;
            string     username = HttpContext.Current.Request.Cookies["userLoginSystem"].Value;

            if (!string.IsNullOrEmpty(username))
            {
                var a = AccountController.GetByUsername(username);
                if (a != null)
                {
                    AgentID = Convert.ToInt32(a.AgentID);
                }
            }
            var customer = CustomerController.GetByPhone(phonefullname);

            if (customer != null)
            {
                rf.CustName    = customer.CustomerName;
                rf.CustPhone   = customer.CustomerPhone;
                rf.CustZalo    = customer.Zalo;
                rf.CustFB      = customer.Facebook;
                rf.CustAddress = customer.CustomerAddress;


                int    custID    = customer.ID;
                double FeeRefund = 0;
                double NumOfDateToChangeProduct = 0;
                double NumOfProductCanChange    = 0;
                var    config = ConfigController.GetByTop1();
                if (config != null)
                {
                    FeeRefund = Convert.ToDouble(config.FeeChangeProduct);
                    NumOfDateToChangeProduct = Convert.ToDouble(config.NumOfDateToChangeProduct);
                    NumOfProductCanChange    = Convert.ToDouble(config.NumOfProductCanChange);
                }
                var d = DiscountCustomerController.getbyCustID(custID);
                if (d.Count > 0)
                {
                    FeeRefund = d[0].FeeRefund;
                    NumOfDateToChangeProduct = d[0].NumOfDateToChangeProduct;
                    NumOfProductCanChange    = d[0].NumOfProductCanChange;
                }

                DateTime toDate   = DateTime.Now.Date;
                var      fromDate = toDate.AddDays(-NumOfDateToChangeProduct);

                double totalProductRefund = 0;
                var    refundList         = RefundGoodController.GetByAgentIDCustomerIDFromDateToDate(AgentID, custID, fromDate, toDate.AddDays(1));
                if (refundList.Count > 0)
                {
                    foreach (var item in refundList)
                    {
                        var rfD = RefundGoodDetailController.GetByRefundGoodsID(item.ID);
                        if (rfD.Count > 0)
                        {
                            foreach (var fd in rfD)
                            {
                                totalProductRefund += Convert.ToDouble(fd.Quantity);
                            }
                        }
                    }
                }
                double leftCanchange = NumOfProductCanChange - totalProductRefund;
                if (leftCanchange > 0)
                {
                    rf.CustleftCanchange = leftCanchange.ToString();

                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    return(serializer.Serialize(rf));
                }
                else
                {
                    rf.CustleftCanchange = "full";
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    return(serializer.Serialize(rf));
                }
            }
            else
            {
                rf.CustleftCanchange = "nocustomer";
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                return(serializer.Serialize(rf));
            }
        }
 public void AddCheckingAccount()
 {
     AccountController.CreateAccountOf(AccountController.Kind.checking);
     DisableAllAccountBtn();
     ShowAccounts(ClientController.Client);
 }
Beispiel #35
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string   username    = Request.Cookies["usernameLoginSystem"].Value;
            var      acc         = AccountController.GetByUsername(username);
            DateTime currentDate = DateTime.Now;
            int      cateID      = hdfParentID.Value.ToInt();

            if (cateID > 0)
            {
                int    CategoryID   = ddlCategory.Value.ToInt();
                var    category     = PostPublicCategoryController.GetByID(CategoryID);
                string CategorySlug = category.Slug;
                string Title        = txtTitle.Text.Trim();
                string Slugs        = Slug.ConvertToSlug(txtSlug.Text.Trim());
                string Link         = txtLink.Text.Trim();
                string Content      = pContent.Content.ToString();
                string Summary      = HttpUtility.HtmlDecode(pSummary.Content.ToString());
                string Action       = ddlAction.SelectedValue.ToString();
                string ActionValue  = "";
                if (Action == "view_more")
                {
                    ActionValue = Slugs;
                }
                else if (Action == "show_web")
                {
                    ActionValue = Link;
                }
                bool AtHome   = ddlAtHome.SelectedValue.ToBool();
                bool IsPolicy = false;

                var newPostPublic = new PostPublic()
                {
                    CategoryID   = CategoryID,
                    CategorySlug = CategorySlug,
                    Title        = Title,
                    Thumbnail    = "",
                    Summary      = Summary,
                    Content      = Content,
                    Action       = Action,
                    ActionValue  = ActionValue,
                    AtHome       = AtHome,
                    IsPolicy     = IsPolicy,
                    CreatedDate  = currentDate,
                    CreatedBy    = acc.Username,
                    ModifiedDate = currentDate,
                    ModifiedBy   = acc.Username
                };

                var post = PostPublicController.Insert(newPostPublic);

                if (post != null)
                {
                    // Thêm ảnh đại diện
                    string path  = "/uploads/images/posts/";
                    string Image = "";
                    if (PostPublicThumbnailImage.UploadedFiles.Count > 0)
                    {
                        foreach (UploadedFile f in PostPublicThumbnailImage.UploadedFiles)
                        {
                            var o = path + "post-app-" + post.ID.ToString() + "-" + Slug.ConvertToSlug(Path.GetFileName(f.FileName), isFile: true);
                            try
                            {
                                f.SaveAs(Server.MapPath(o));
                                Image = o;
                            }
                            catch { }
                        }
                    }
                    string updateImage = PostPublicController.UpdateImage(post.ID, Image);

                    // Thêm thư viện ảnh
                    string IMG = "";
                    if (ImageGallery.UploadedFiles.Count > 0)
                    {
                        foreach (UploadedFile f in ImageGallery.UploadedFiles)
                        {
                            var o = path + "post-app-" + post.ID.ToString() + "-" + Slug.ConvertToSlug(Path.GetFileName(f.FileName), isFile: true);
                            try
                            {
                                f.SaveAs(Server.MapPath(o));
                                IMG = o;
                                PostPublicImageController.Insert(post.ID, IMG, username, currentDate);
                            }
                            catch { }
                        }
                    }

                    // Copy bài viết vào hệ thống gốc
                    if (ddlCopyToSystem.SelectedValue == "True" && post.Action == "view_more")
                    {
                        var categorySystem = PostCategoryController.GetByName(category.Name);
                        var postSystem     = new tbl_Post()
                        {
                            Title        = post.Title,
                            Content      = post.Content,
                            Image        = Image,
                            Featured     = 1,
                            CategoryID   = categorySystem != null ? categorySystem.ID : 0,
                            Status       = 1,
                            CreatedBy    = post.CreatedBy,
                            CreatedDate  = post.CreatedDate,
                            ModifiedBy   = post.ModifiedBy,
                            ModifiedDate = post.ModifiedDate,
                            WebPublish   = true,
                            WebUpdate    = post.CreatedDate,
                            Slug         = post.ActionValue
                        };

                        PostController.Insert(postSystem);

                        // Copy image
                        if (postSystem != null)
                        {
                            var imagePostPublic = PostPublicImageController.GetByPostID(post.ID);
                            if (imagePostPublic.Count > 0)
                            {
                                foreach (var item in imagePostPublic)
                                {
                                    PostImageController.Insert(postSystem.ID, item.Image, postSystem.CreatedBy, DateTime.Now);
                                }
                            }
                        }
                    }


                    // Tạo phiên bản cho wordpress
                    if (!String.IsNullOrEmpty(hdfPostVariants.Value))
                    {
                        JavaScriptSerializer serializer = new JavaScriptSerializer();
                        var variants = serializer.Deserialize <List <PostClone> >(hdfPostVariants.Value);
                        if (variants != null)
                        {
                            foreach (var item in variants)
                            {
                                var newPostClone = new PostClone()
                                {
                                    PostPublicID = post.ID,
                                    Web          = item.Web,
                                    PostWebID    = 0,
                                    CategoryID   = post.CategoryID,
                                    CategoryName = category.Name,
                                    Title        = !String.IsNullOrEmpty(item.Title) ? item.Title : post.Title,
                                    Summary      = post.Summary,
                                    Content      = post.Content,
                                    Thumbnail    = Image,
                                    CreatedDate  = post.CreatedDate,
                                    CreatedBy    = acc.Username,
                                    ModifiedDate = post.ModifiedDate,
                                    ModifiedBy   = acc.Username
                                };

                                PostCloneController.Insert(newPostClone);
                            }
                        }
                    }

                    PJUtils.ShowMessageBoxSwAlertCallFunction("Tạo bài viết thành công", "s", true, "redirectTo(" + post.ID.ToString() + ")", Page);
                }
            }
        }
Beispiel #36
0
        public void LoadData()
        {
            string username = Request.Cookies["usernameLoginSystem"].Value;
            var    acc      = AccountController.GetByUsername(username);

            int id = Request.QueryString["id"].ToInt(0);

            if (id > 0)
            {
                var p = PostPublicController.GetByID(id);
                if (p == null)
                {
                    PJUtils.ShowMessageBoxSwAlertError("Không tìm thấy bài viết " + id, "e", true, "/danh-sach-bai-viet-app", Page);
                }
                else
                {
                    ltrThumbnail.Text = "<img src='" + p.Thumbnail + "'><a href='" + p.Thumbnail + "' download class='btn download-btn download-image h45-btn'><i class='fa fa-cloud-download'></i> Tải hình này</a>";
                    ltrSummary.Text   = p.Summary;
                    if (p.Action == "show_web")
                    {
                        ltrLink.Text = "<p><strong>Link:</strong> <a href='" + p.ActionValue + "' target='_blank'>" + p.ActionValue + "</a></p>";
                    }
                    else
                    {
                        ltrContent.Text = p.Content;
                    }
                    this.Title      = String.Format("{0} - Bài viết App", p.Title.ToTitleCase());
                    ltrEditTop.Text = "";
                    if (acc.RoleID == 0 || acc.Username == "nhom_zalo502")
                    {
                        ltrEditTop.Text += "<a href='/sua-bai-viet-app?id=" + p.ID + "' class='btn primary-btn fw-btn not-fullwidth'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Sửa</a>";
                        ltrEditTop.Text += "<a href='/tao-bai-viet-app' class='btn primary-btn fw-btn not-fullwidth print-invoice-merged'><i class='fa fa-file-text-o' aria-hidden='true'></i> Thêm</a>";
                        ltrEditTop.Text += "<a href='javascript:;' onclick='showPostSyncModal(" + p.ID + ");' class='btn primary-btn fw-btn not-fullwidth print-invoice-merged'><i class='fa fa-refresh' aria-hidden='true'></i> Đồng bộ</a>";
                    }
                    ltrEditBottom.Text = ltrEditTop.Text;
                    ltrTitle.Text      = p.Title;

                    // thư viện ảnh
                    var image = PostPublicImageController.GetByPostID(id);
                    if (image != null)
                    {
                        imageGallery.Text = "<ul class='image-gallery'>";
                        foreach (var img in image)
                        {
                            if (img.Image != p.Thumbnail)
                            {
                                imageGallery.Text += "<li><img src='" + img.Image + "' /><a href='" + img.Image + "' download class='btn download-btn download-image h45-btn'><i class='fa fa-cloud-download'></i> Tải hình này</a></li>";
                            }
                        }
                        imageGallery.Text += "</ul>";
                    }

                    string Action = "";
                    if (p.Action == "show_web")
                    {
                        Action = "Link ngoài";
                    }
                    else
                    {
                        Action = "Bài nội bộ";
                    }
                    string PostInfo = "<p><strong>Kiểu bài viết</strong>: " + Action + "</p>";
                    PostInfo        += "<p><strong>Ngày tạo</strong>: " + p.CreatedDate + "</p>";
                    PostInfo        += "<p><strong>Người viết</strong>: " + p.CreatedBy + "</p>";
                    PostInfo        += "<p><strong>Ngày cập nhật</strong>: " + p.ModifiedDate + "</p>";
                    PostInfo        += "<p><strong>Người cập nhật</strong>: " + p.ModifiedBy + "</p>";
                    ltrPostInfo.Text = PostInfo;
                }
            }
        }
Beispiel #37
0
        public void go(Client player, string type, int id)
        {
            AccountController account = player.getData("ACCOUNT");

            if (account == null)
            {
                return;
            }

            if (!AdminController.AdminRankCheck("goto", account))
            {
                return;
            }

            player.dimension = 0;
            if (type == "property")
            {
                PropertyController _PropertyController = EntityManager.GetProperty(id);
                if (_PropertyController == null)
                {
                    API.sendChatMessageToPlayer(player, "~r~ERROR: ~w~You specified an invalid ID.");
                }
                else
                {
                    player.position = _PropertyController.ExteriorMarker.position;
                }
            }
            else if (type == "job")
            {
                JobController job = EntityManager.GetJob(id);
                if (job == null)
                {
                    API.sendChatMessageToPlayer(player, "~r~ERROR: ~w~You specified an invalid ID.");
                }
                else
                {
                    player.position = new Vector3(job.JobData.PosX, job.JobData.PosY, job.JobData.PosZ);
                }
            }
            else
            {
                player.dimension = 0;
                if (id == 0)
                {
                    player.position  = SpawnManager.GetSpawnPosition();
                    player.dimension = SpawnManager.GetSpawnDimension();
                }
                else if (id == 1)
                {
                    API.setEntityPosition(player, new Vector3(-365.425, -131.809, 37.873));
                }
                else if (id == 2)
                {
                    API.setEntityPosition(player, new Vector3(-2023.661, -1038.038, 5.577));
                }
                else if (id == 3)
                {
                    API.setEntityPosition(player, new Vector3(3069.330, -4704.220, 15.043));
                }
                else if (id == 4)
                {
                    API.setEntityPosition(player, new Vector3(2052.000, 3237.000, 1456.973));
                }
                else if (id == 5)
                {
                    API.setEntityPosition(player, new Vector3(-129.964, 8130.873, 6705.307));
                }
                else if (id == 6)
                {
                    API.setEntityPosition(player, new Vector3(134.085, -637.859, 262.851));
                }
                else if (id == 7)
                {
                    API.setEntityPosition(player, new Vector3(150.126, -754.591, 262.865));
                }
                else if (id == 8)
                {
                    API.setEntityPosition(player, new Vector3(-75.015, -818.215, 326.176));
                }
                else if (id == 9)
                {
                    API.setEntityPosition(player, new Vector3(450.718, 5566.614, 806.183));
                }
                else if (id == 10)
                {
                    API.setEntityPosition(player, new Vector3(24.775, 7644.102, 19.055));
                }
                else if (id == 11)
                {
                    API.setEntityPosition(player, new Vector3(686.245, 577.950, 130.461));
                }
                else if (id == 12)
                {
                    API.setEntityPosition(player, new Vector3(205.316, 1167.378, 227.005));
                }
                else if (id == 13)
                {
                    API.setEntityPosition(player, new Vector3(-20.004, -10.889, 500.602));
                }
                else if (id == 14)
                {
                    API.setEntityPosition(player, new Vector3(-438.804, 1076.097, 352.411));
                }
                else if (id == 15)
                {
                    API.setEntityPosition(player, new Vector3(-2243.810, 264.048, 174.615));
                }
                else if (id == 16)
                {
                    API.setEntityPosition(player, new Vector3(-3426.683, 967.738, 8.347));
                }
                else if (id == 17)
                {
                    API.setEntityPosition(player, new Vector3(-275.522, 6635.835, 7.425));
                }
                else if (id == 18)
                {
                    API.setEntityPosition(player, new Vector3(-1006.402, 6272.383, 1.503));
                }
                else if (id == 19)
                {
                    API.setEntityPosition(player, new Vector3(-517.869, 4425.284, 89.795));
                }
                else if (id == 20)
                {
                    API.setEntityPosition(player, new Vector3(-1170.841, 4926.646, 224.295));
                }
                else if (id == 21)
                {
                    API.setEntityPosition(player, new Vector3(-324.300, -1968.545, 67.002));
                }
                else if (id == 22)
                {
                    API.setEntityPosition(player, new Vector3(-1868.971, 2095.674, 139.115));
                }
                else if (id == 23)
                {
                    API.setEntityPosition(player, new Vector3(2476.712, 3789.645, 41.226));
                }
                else if (id == 24)
                {
                    API.setEntityPosition(player, new Vector3(-2639.872, 1866.812, 160.135));
                }
                else if (id == 25)
                {
                    API.setEntityPosition(player, new Vector3(-595.342, 2086.008, 131.412));
                }
                else if (id == 26)
                {
                    API.setEntityPosition(player, new Vector3(2208.777, 5578.235, 53.735));
                }
                else if (id == 27)
                {
                    API.setEntityPosition(player, new Vector3(126.975, 3714.419, 46.827));
                }
                else if (id == 28)
                {
                    API.setEntityPosition(player, new Vector3(2395.096, 3049.616, 60.053));
                }
                else if (id == 29)
                {
                    API.setEntityPosition(player, new Vector3(2034.988, 2953.105, 74.602));
                }
                else if (id == 30)
                {
                    API.setEntityPosition(player, new Vector3(2062.123, 2942.055, 47.431));
                }
                else if (id == 31)
                {
                    API.setEntityPosition(player, new Vector3(2026.677, 1842.684, 133.313));
                }
                else if (id == 32)
                {
                    API.setEntityPosition(player, new Vector3(1051.209, 2280.452, 89.727));
                }
                else if (id == 33)
                {
                    API.setEntityPosition(player, new Vector3(736.153, 2583.143, 79.634));
                }
                else if (id == 34)
                {
                    API.setEntityPosition(player, new Vector3(2954.196, 2783.410, 41.004));
                }
                else if (id == 35)
                {
                    API.setEntityPosition(player, new Vector3(2732.931, 1577.540, 83.671));
                }
                else if (id == 36)
                {
                    API.setEntityPosition(player, new Vector3(486.417, -3339.692, 6.070));
                }
                else if (id == 37)
                {
                    API.setEntityPosition(player, new Vector3(899.678, -2882.191, 19.013));
                }
                else if (id == 38)
                {
                    API.setEntityPosition(player, new Vector3(-1850.127, -1231.751, 13.017));
                }
                else if (id == 39)
                {
                    API.setEntityPosition(player, new Vector3(-1475.234, 167.088, 55.841));
                }
                else if (id == 40)
                {
                    API.setEntityPosition(player, new Vector3(3059.620, 5564.246, 197.091));
                }
                else if (id == 41)
                {
                    API.setEntityPosition(player, new Vector3(2535.243, -383.799, 92.993));
                }
                else if (id == 42)
                {
                    API.setEntityPosition(player, new Vector3(971.245, -1620.993, 30.111));
                }
                else if (id == 43)
                {
                    API.setEntityPosition(player, new Vector3(293.089, 180.466, 104.301));
                }
                else if (id == 44)
                {
                    API.setEntityPosition(player, new Vector3(-1374.881, -1398.835, 6.141));
                }
                else if (id == 45)
                {
                    API.setEntityPosition(player, new Vector3(718.341, -1218.714, 26.014));
                }
                else if (id == 46)
                {
                    API.setEntityPosition(player, new Vector3(925.329, 46.152, 80.908));
                }
                else if (id == 47)
                {
                    API.setEntityPosition(player, new Vector3(-1696.866, 142.747, 64.372));
                }
                else if (id == 48)
                {
                    API.setEntityPosition(player, new Vector3(-543.932, -2225.543, 122.366));
                }
                else if (id == 49)
                {
                    API.setEntityPosition(player, new Vector3(1660.369, -12.013, 170.020));
                }
                else if (id == 50)
                {
                    API.setEntityPosition(player, new Vector3(2877.633, 5911.078, 369.624));
                }
                else if (id == 51)
                {
                    API.setEntityPosition(player, new Vector3(-889.655, -853.499, 20.566));
                }
                else if (id == 52)
                {
                    API.setEntityPosition(player, new Vector3(-695.025, 82.955, 55.855));
                }
                else if (id == 53)
                {
                    API.setEntityPosition(player, new Vector3(-1330.911, 340.871, 64.078));
                }
                else if (id == 54)
                {
                    API.setEntityPosition(player, new Vector3(711.362, 1198.134, 348.526));
                }
                else if (id == 55)
                {
                    API.setEntityPosition(player, new Vector3(-1336.715, 59.051, 55.246));
                }
                else if (id == 56)
                {
                    API.setEntityPosition(player, new Vector3(-31.010, 6316.830, 40.083));
                }
                else if (id == 57)
                {
                    API.setEntityPosition(player, new Vector3(-635.463, -242.402, 38.175));
                }
                else if (id == 58)
                {
                    API.setEntityPosition(player, new Vector3(-3022.222, 39.968, 13.611));
                }
                else if (id == 59)
                {
                    API.setEntityPosition(player, new Vector3(-1659993, -128.399, 59.954));
                }
                else if (id == 60)
                {
                    API.setEntityPosition(player, new Vector3(-549.467, 5308.221, 114.146));
                }
                else if (id == 61)
                {
                    API.setEntityPosition(player, new Vector3(1070.206, -711.958, 58.483));
                }
                else if (id == 62)
                {
                    API.setEntityPosition(player, new Vector3(1608.698, 6438.096, 37.637));
                }
                else if (id == 63)
                {
                    API.setEntityPosition(player, new Vector3(3430.155, 5174.196, 41.280));
                }
                else if (id == 64)
                {
                    API.setEntityPosition(player, new Vector3(3464.689, 5252.736, 20.29798));
                }
                else if (id == 65)
                {
                    API.setEntityPosition(player, new Vector3(1675.97961, 2585.18457, 45.92));                // Prison
                }
            }
        }
 public void LoadAccount(string id) => AccountController.SetAccount(id);
Beispiel #39
0
 public LoginCommand(LoginDto loginDto, AccountController controller)
 {
     LoginDto   = loginDto;
     Controller = controller;
 }
    /// <summary>
    /// Sets up the game data
    /// </summary>
    /// <returns>void</returns>
    IEnumerator ISetupGameData()
    {
        Debug.Log("PreMenuSceneScript: Starting to load Gamedata");
        yield return(new WaitForSeconds(1));

        //Play the MainMenu Audio Music now
        glob_audiomanager.SendMessage("PlayMainMenuAudio");
        //Change the UI scenes to the loading
        ui_terms.SetActive(false);
        ui_loading.SetActive(true);
        //Begin loading of the game data
        bool          autoLogin  = false;
        RectTransform loadbar    = ui_loadingbar.GetComponent <RectTransform> ();
        string        remDetails = "";

        if (ui_loadingbar != null)
        {
            #region Loading Sequence 1
            //First pass we want to load the Gamemanager object and necceseties
            Instantiate(pref_gamemanager,
                        new Vector3(0, 0, 0), Quaternion.identity);
            glob_gamemanager = GameObject.FindGameObjectWithTag("GameManager");
            accountControl   = glob_gamemanager.GetComponent <AccountController> ();
            yield return(new WaitForSeconds(1));

            float x = 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 2
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 3
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 4
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 5
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 6
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 7
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 8
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 9
            yield return(new WaitForSeconds(0.5f));

            x += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
            #region Loading Sequence 10
            //Final sequence is to login to the game/check we can login
            //Checks and assigns the auto Login variable
            remDetails         = accountControl.loginToRemember;
            autoLogin          = (remDetails == null || remDetails == "") ? false : true;
            x                 += 0.1f;
            loadbar.localScale = new Vector3(x, 1.0f, 1.0f);
            #endregion
        }
        //Actually do the logging in or display of the login panel
        if (autoLogin)
        {
            //Send off request to our newly created gamemanager
            //Connects to PHP scripts in the 'cloud'
            //Returns the status of the login attempt
            Debug.Log("PreMenuSceneScript: Auto-login beginning");
            yield return(StartCoroutine(accountControl.ILogin(remDetails)));

            //Wait for login to complete
            Debug.Log("PreMenuSceneScript: Auto-login completed");
            if (accountControl.LoggedInAccount != null)
            {
                //We have successfully logged in
                Debug.Log("PreMenuSceneScript: Login was a success");
            }
        }
        else
        {
            //The Auto-Login functionality is not on so we need to show
            //a login panel box to allow user to type in user/pass combo
            Debug.Log("PreMenuSceneScript: Auto-login not on.. " +
                      "displaying menu");
            ui_loading.SetActive(false);
            ui_login.SetActive(true);
        }
        //Output to the console what is happening
        Debug.Log("PreMenuSceneScript: Finished loading Gamedata");
        switch_LoadedGamedata = true;         //We have completed the data load
    }
Beispiel #41
0
        protected void btnOrder_Click(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            string   username    = Request.Cookies["userLoginSystem"].Value;
            var      acc         = AccountController.GetByUsername(username);

            if (acc != null)
            {
                if (acc.RoleID == 0 || acc.RoleID == 2)
                {
                    int    AgentID     = Convert.ToInt32(acc.AgentID);
                    int    OrderType   = hdfOrderType.Value.ToInt();
                    string AdditionFee = "0";
                    string DisCount    = "0";
                    int    CustomerID  = 0;

                    string CustomerPhone   = txtPhone.Text.Trim().Replace(" ", "");
                    string CustomerName    = txtFullname.Text.Trim();
                    string Nick            = txtNick.Text.Trim();
                    string CustomerAddress = txtAddress.Text.Trim();
                    string Zalo            = txtZalo.Text.Trim();
                    string Facebook        = txtFacebook.Text.Trim();
                    int    PaymentStatus   = hdfPaymentStatus.Value.ToInt(1);
                    int    ExcuteStatus    = hdfExcuteStatus.Value.ToInt(1);
                    int    PaymentType     = hdfPaymentType.Value.ToInt(1);
                    int    ShippingType    = hdfShippingType.Value.ToInt(1);

                    var checkCustomer = CustomerController.GetByPhone(CustomerPhone);

                    if (checkCustomer != null)
                    {
                        CustomerID = checkCustomer.ID;
                        string kq = CustomerController.Update(CustomerID, CustomerName, checkCustomer.CustomerPhone, CustomerAddress, "", Convert.ToInt32(checkCustomer.CustomerLevelID), Convert.ToInt32(checkCustomer.Status), checkCustomer.CreatedBy, currentDate, username, false, Zalo, Facebook, checkCustomer.Note, checkCustomer.ProvinceID.ToString(), Nick, checkCustomer.Avatar, Convert.ToInt32(checkCustomer.ShippingType), Convert.ToInt32(checkCustomer.PaymentType), Convert.ToInt32(checkCustomer.TransportCompanyID), Convert.ToInt32(checkCustomer.TransportCompanySubID), checkCustomer.CustomerPhone2);
                    }
                    else
                    {
                        string kq = CustomerController.Insert(CustomerName, CustomerPhone, CustomerAddress, "", 0, 0, currentDate, username, false, Zalo, Facebook, "", "", Nick, "", ShippingType, PaymentType);
                        if (kq.ToInt(0) > 0)
                        {
                            CustomerID = kq.ToInt();
                        }
                    }

                    var Customer = CustomerController.GetByID(CustomerID);

                    int TransportCompanyID    = 0;
                    int TransportCompanySubID = 0;
                    if (Customer.ShippingType == ShippingType)
                    {
                        TransportCompanyID    = Convert.ToInt32(Customer.TransportCompanyID);
                        TransportCompanySubID = Convert.ToInt32(Customer.TransportCompanySubID);
                    }

                    string totalPrice            = hdfTotalPrice.Value.ToString();
                    string totalPriceNotDiscount = hdfTotalPriceNotDiscount.Value;


                    double DiscountPerProduct = Convert.ToDouble(pDiscount.Value);

                    double TotalDiscount = Convert.ToDouble(pDiscount.Value) * Convert.ToDouble(hdfTotalQuantity.Value);
                    string FeeShipping   = pFeeShip.Value.ToString();

                    string OtherFeeName  = txtOtherFeeName.Text;
                    double OtherFeeValue = Convert.ToDouble(pOtherFee.Value);

                    bool IsHidden = false;
                    int  WayIn    = 1;

                    string datedone = "";

                    if (ExcuteStatus == 2)
                    {
                        datedone = DateTime.Now.ToString();
                    }

                    var ret = OrderController.Insert(AgentID, OrderType, AdditionFee, DisCount, CustomerID, CustomerName, CustomerPhone, CustomerAddress,
                                                     "", totalPrice, totalPriceNotDiscount, PaymentStatus, ExcuteStatus, IsHidden, WayIn, currentDate, username, Convert.ToDouble(pDiscount.Value),
                                                     TotalDiscount, FeeShipping, PaymentType, ShippingType, datedone, 0, 0, TransportCompanyID, TransportCompanySubID, OtherFeeName, OtherFeeValue, 1);

                    int OrderID = ret.ID;

                    double totalQuantity = 0;
                    if (OrderID > 0)
                    {
                        string   list  = hdfListProduct.Value;
                        string[] items = list.Split(';');
                        if (items.Length - 1 > 0)
                        {
                            for (int i = 0; i < items.Length - 1; i++)
                            {
                                var      item      = items[i];
                                string[] itemValue = item.Split(',');

                                int    ProductID         = itemValue[0].ToInt();
                                int    ProductVariableID = itemValue[11].ToInt();
                                string SKU         = itemValue[1].ToString();
                                int    ProductType = itemValue[2].ToInt();

                                // Tìm parentID
                                int parentID = ProductID;
                                var variable = ProductVariableController.GetByID(ProductVariableID);
                                if (variable != null)
                                {
                                    parentID = Convert.ToInt32(variable.ProductID);
                                }

                                string ProductVariableName  = itemValue[3];
                                string ProductVariableValue = itemValue[4];
                                double Quantity             = Convert.ToDouble(itemValue[5]);
                                string ProductName          = itemValue[6];
                                string ProductImageOrigin   = itemValue[7];
                                string ProductVariable      = itemValue[8];
                                double Price = Convert.ToDouble(itemValue[9]);
                                string ProductVariableSave = itemValue[10];

                                OrderDetailController.Insert(AgentID, OrderID, SKU, ProductID, ProductVariableID, ProductVariableSave, Quantity, Price, 1, 0,
                                                             ProductType, currentDate, username, true);

                                StockManagerController.Insert(
                                    new tbl_StockManager
                                {
                                    AgentID           = AgentID,
                                    ProductID         = ProductID,
                                    ProductVariableID = ProductVariableID,
                                    Quantity          = Quantity,
                                    QuantityCurrent   = 0,
                                    Type        = 2,
                                    NoteID      = "Xuất kho khi tạo đơn",
                                    OrderID     = OrderID,
                                    Status      = 3,
                                    SKU         = SKU,
                                    CreatedDate = currentDate,
                                    CreatedBy   = username,
                                    MoveProID   = 0,
                                    ParentID    = parentID,
                                });
                                totalQuantity += Quantity;
                            }
                        }

                        string refund = Request.Cookies["refundt"].Value;
                        if (refund != "1")
                        {
                            string[] RefundID = refund.Split('|');
                            var      update   = RefundGoodController.UpdateStatus(RefundID[0].ToInt(), username, 2, OrderID);
                            var      updateor = OrderController.UpdateRefund(OrderID, RefundID[0].ToInt(), username);
                        }

                        Response.Cookies["refundt"].Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(Response.Cookies["refundt"]);

                        PJUtils.ShowMessageBoxSwAlertCallFunction("Tạo đơn hàng thành công", "s", true, "redirectTo(" + OrderID + ")", Page);
                    }
                }
            }
        }
        public static void GenerateAdminMenu()
        {
            var generateMenu          = new GenerateMenu();
            var accountController     = new AccountController();
            var transactionController = new TransactionController();

            while (true)
            {
                try
                {
                    Console.Clear();
                    Console.WriteLine("—— Ngân hàng Spring Hero Bank ——");
                    Console.WriteLine(
                        $"Chào mừng Admin {AccountController.currentAccount.Fullname} quay trở lại. Vui lòng chọn thao tác:");
                    Console.WriteLine("1. Danh sách người dùng.");
                    Console.WriteLine("2. Danh sách lịch sử giao dịch.");
                    Console.WriteLine("3. Tìm kiếm người dùng theo tên.");
                    Console.WriteLine("4. Tìm kiếm người dùng theo số tài khoản.");
                    Console.WriteLine("5. Tìm kiếm người dùng theo số điện thoại.");
                    Console.WriteLine("6. Thêm người dùng mới.");
                    Console.WriteLine("7. Khoá và mở tài khoản người dùng.");
                    Console.WriteLine("8. Tìm kiếm lịch sử giao dịch theo số tài khoản.");
                    Console.WriteLine("9. Thay đổi thông tin tài khoản.");
                    Console.WriteLine("10. Thay đổi thông tin mật khẩu.");
                    Console.WriteLine("11. Đăng xuất.");
                    Console.WriteLine("12. Thoát.");
                    Console.WriteLine("--------------------------------");
                    Console.WriteLine("Nhập lựa chọn của bạn (1-12): ");
                    var choice = int.Parse(Console.ReadLine());
                    switch (choice)
                    {
                    case 1:
                        accountController.ListUser();
                        break;

                    case 2:
                        transactionController.PrintlistTransactionHistory();
                        break;

                    case 3:
                        accountController.FindUserByUsername();
                        break;

                    case 4:
                        accountController.FindUserByAccountNumber();
                        break;

                    case 5:
                        accountController.FindUserByPhone();
                        break;

                    case 6:
                        accountController.Register();
                        break;

                    case 7:
                        accountController.UpdateAccountStatus();
                        break;

                    case 8:
                        transactionController.PrintListTransaction();
                        break;

                    case 9:
                        accountController.UpdateAccountInfor();
                        break;

                    case 10:
                        accountController.UpdateAccountPassword();
                        break;

                    case 11:
                        Console.WriteLine("Đăng xuất");
                        break;

                    case 12:
                        Console.WriteLine("Tạm biệt và hẹn gặp lại!");
                        Environment.Exit(0);
                        break;

                    default:
                        Console.WriteLine("Hãy nhập từ 1 đến 12");
                        break;
                    }

                    if (choice == 11)
                    {
                        AccountController.currentAccount = null;
                        generateMenu.GetMenu(AccountController.currentAccount);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                Console.ReadLine();
            }
        }
Beispiel #43
0
        protected void btnImport_Click(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            string   username    = Request.Cookies["usernameLoginSystem"].Value;
            var      acc         = AccountController.GetByUsername(username);

            if (acc == null)
            {
                return;
            }

            var now = DateTime.Now;

            var checkWarehouse = new CheckWarehouse()
            {
                Name         = String.Format("{0} - {1:dd/MM/yyyy HH:mm}", hdfTestName.Value.Trim(), now),
                Stock        = hdfStock.Value.ToInt(),
                Active       = true,
                CreatedDate  = now,
                CreatedBy    = acc.Username,
                ModifiedDate = now,
                ModifiedBy   = acc.Username
            };

            _createCheckWarehouse(checkWarehouse);

            var data    = JsonConvert.DeserializeObject <List <ProductGetOut> >(hdfvalue.Value);
            var details = new List <CheckWarehouseDetail>();

            #region Xử lý với sản phẩm không có biến thể
            var products = data.Where(x => x.ProductStyle == 1).ToList();

            foreach (var item in products)
            {
                var temp = new CheckWarehouseDetail()
                {
                    CheckWarehouseID  = checkWarehouse.ID,
                    ProductID         = item.ID,
                    ProductVariableID = 0,
                    ProductSKU        = item.SKU,
                    QuantityOld       = Convert.ToInt32(item.WarehouseQuantity),
                    CreatedDate       = now,
                    CreatedBy         = acc.Username,
                    ModifiedDate      = now,
                    ModifiedBy        = acc.Username
                };
                details.Add(temp);
            }

            if (details.Count > 0)
            {
                _createCheckWarehouseDetail(details);
                details.Clear();
            }
            #endregion

            #region Xử lý với sản phẩm có biến thể
            IList <ProductVariation> variations;

            #region Lấy thông tin  stock
            using (var con = new inventorymanagementEntities())
            {
                var productIDs        = data.Except(products).Select(x => x.ID).Distinct().ToList();
                var productVariations = con.tbl_ProductVariable
                                        .Where(x => x.ProductID.HasValue)
                                        .Where(x => productIDs.Contains(x.ProductID.Value))
                                        .Select(x => new {
                    productID         = x.ProductID.Value,
                    productVariableID = x.ID,
                    sku = x.SKU
                })
                                        .OrderBy(o => o.productID)
                                        .ThenBy(o => o.productVariableID);

                // Lọc ra những dòng stock cần lấy
                var stockFilter = con.tbl_StockManager
                                  .Join(
                    productVariations,
                    s => s.SKU,
                    v => v.sku,
                    (s, v) => s
                    )
                                  .Select(x => new
                {
                    ParentID          = x.ParentID,
                    ProductVariableID = x.ProductVariableID,
                    SKU             = x.SKU,
                    CreatedDate     = x.CreatedDate,
                    Quantity        = x.Quantity,
                    QuantityCurrent = x.QuantityCurrent,
                    Type            = x.Type
                })
                                  .OrderBy(o => o.ParentID)
                                  .ThenBy(o => o.ProductVariableID)
                                  .ThenBy(o => o.CreatedDate);

                // Lấy dòng stock cuối cùng
                var stockLast = stockFilter
                                .Select(x => new
                {
                    parentID          = x.ParentID.Value,
                    productVariableID = x.ProductVariableID.Value,
                    createDate        = x.CreatedDate
                })
                                .GroupBy(x => new { x.parentID, x.productVariableID })
                                .Select(g => new
                {
                    parentID          = g.Key.parentID,
                    productVariableID = g.Key.productVariableID,
                    doneAt            = g.Max(x => x.createDate)
                });

                // Thông tin stock
                var stocks = stockFilter
                             .Join(
                    stockLast,
                    rec => new
                {
                    parentID          = rec.ParentID.Value,
                    productVariableID = rec.ProductVariableID.Value,
                    doneAt            = rec.CreatedDate
                },
                    last => new
                {
                    parentID          = last.parentID,
                    productVariableID = last.productVariableID,
                    doneAt            = last.doneAt
                },
                    (rec, last) => new
                {
                    parentID          = last.parentID,
                    productVariableID = last.productVariableID,
                    sku             = rec.SKU,
                    quantity        = rec.Quantity.HasValue ? rec.Quantity.Value : 0,
                    quantityCurrent = rec.QuantityCurrent.HasValue ? rec.QuantityCurrent.Value : 0,
                    type            = rec.Type.HasValue ? rec.Type.Value : 0
                }
                    )
                             .Select(x => new
                {
                    productID         = x.parentID,
                    productVariableID = x.productVariableID,
                    sku         = x.sku,
                    calQuantity = x.quantityCurrent + x.quantity * (x.type == 1 ? 1 : -1)
                })
                             .OrderBy(o => o.productID)
                             .ThenBy(o => o.productVariableID);

                variations = productVariations
                             .GroupJoin(
                    stocks,
                    v => v.sku,
                    s => s.sku,
                    (v, s) => new { variation = v, stock = s }
                    )
                             .SelectMany(
                    x => x.stock.DefaultIfEmpty(),
                    (parent, child) => new { variation = parent.variation, stock = child }
                    )
                             .Select(x => new ProductVariation()
                {
                    productID         = x.variation.productID,
                    productVariableID = x.variation.productVariableID,
                    sku         = x.variation.sku,
                    calQuantity = x.stock != null ? x.stock.calQuantity : 0D
                })
                             .ToList();
            }
            #endregion

            foreach (var item in variations)
            {
                var temp = new CheckWarehouseDetail()
                {
                    CheckWarehouseID  = checkWarehouse.ID,
                    ProductID         = item.productID,
                    ProductVariableID = item.productVariableID,
                    ProductSKU        = item.sku,
                    QuantityOld       = Convert.ToInt32(item.calQuantity),
                    CreatedDate       = now,
                    CreatedBy         = acc.Username,
                    ModifiedDate      = now,
                    ModifiedBy        = acc.Username
                };
                details.Add(temp);
            }

            if (details.Count > 0)
            {
                _createCheckWarehouseDetail(details);
                details.Clear();
            }
            #endregion

            PJUtils.ShowMessageBoxSwAlert("Tạo phiên kiểm kho thành công!", "s", true, Page);
        }
        public void LoadData()
        {
            string username = Request.Cookies["userLoginSystem"].Value;
            var    acc      = AccountController.GetByUsername(username);

            if (acc != null)
            {
                if (acc.RoleID == 0)
                {
                    ltrAddPost.Text = "<a href=\"/tao-bai-viet\" class=\"h45-btn btn primary-btn\">Thêm mới</a>";
                }
            }

            string TextSearch  = "";
            string CreatedDate = "";
            int    CategoryID  = 0;
            string Status      = "";

            if (Request.QueryString["textsearch"] != null)
            {
                TextSearch = Request.QueryString["textsearch"].Trim();
            }
            if (Request.QueryString["status"] != null)
            {
                Status = Request.QueryString["status"];
            }
            if (Request.QueryString["categoryid"] != null)
            {
                CategoryID = Request.QueryString["categoryid"].ToInt();
            }
            if (Request.QueryString["createddate"] != null)
            {
                CreatedDate = Request.QueryString["createddate"];
            }


            txtSearchPost.Text           = TextSearch;
            ddlCategory.SelectedValue    = CategoryID.ToString();
            ddlCreatedDate.SelectedValue = CreatedDate.ToString();
            ddlStatus.SelectedValue      = Status.ToString();

            List <PostSQL> a = new List <PostSQL>();

            a = PostController.GetAllSql(CategoryID, TextSearch);

            if (Status != "")
            {
                a = a.Where(p => p.Status == Status.ToInt()).ToList();
            }
            else
            {
                a = a.Where(p => p.Status == 1).ToList();
            }

            if (CreatedDate != "")
            {
                DateTime fromdate = DateTime.Today;
                DateTime todate   = DateTime.Now;
                switch (CreatedDate)
                {
                case "today":
                    fromdate = DateTime.Today;
                    todate   = DateTime.Now;
                    break;

                case "yesterday":
                    fromdate = fromdate.AddDays(-1);
                    todate   = DateTime.Today;
                    break;

                case "beforeyesterday":
                    fromdate = DateTime.Today.AddDays(-2);
                    todate   = DateTime.Today.AddDays(-1);
                    break;

                case "week":
                    int days = DateTime.Today.DayOfWeek == DayOfWeek.Sunday ? 7 : (int)DateTime.Today.DayOfWeek;
                    fromdate = fromdate.AddDays(-days + 1);
                    todate   = DateTime.Now;
                    break;

                case "month":
                    fromdate = new DateTime(fromdate.Year, fromdate.Month, 1);
                    todate   = DateTime.Now;
                    break;

                case "7days":
                    fromdate = DateTime.Today.AddDays(-6);
                    todate   = DateTime.Now;
                    break;

                case "30days":
                    fromdate = DateTime.Today.AddDays(-29);
                    todate   = DateTime.Now;
                    break;
                }

                a = a.Where(p => p.CreatedDate >= fromdate && p.CreatedDate <= todate).ToList();
            }

            pagingall(a);

            ltrNumberOfPost.Text = a.Count().ToString();
        }
Beispiel #45
0
        public void setproperty(Client player, int id, string msg)
        {
            AccountController account = player.getData("ACCOUNT");

            if (account == null)
            {
                return;
            }
            if (!AdminController.AdminRankCheck("setproperty", account))
            {
                return;
            }

            PropertyController PropertyController = EntityManager.GetProperty(id);

            if (PropertyController == null)
            {
                API.sendNotificationToPlayer(player, "You specified an invalid property.");
                return;
            }

            if (msg.ToLower() == "interior")
            {
                PropertyController.PropertyData.IntPosX = player.position.X;
                PropertyController.PropertyData.IntPosY = player.position.Y;
                PropertyController.PropertyData.IntPosZ = player.position.Z;

                PropertyController.InteriorMarker.position    = player.position - new Vector3(0.0f, 0.0f, 1.0f);
                PropertyController.InteriorTextLabel.position = player.position + new Vector3(0.0f, 0.0f, 0.5f);
                API.deleteColShape(PropertyController.InteteriorColShape);
                PropertyController.CreateColShape();
                ContextFactory.Instance.SaveChanges();
            }
            else if (msg.ToLower() == "exterior")
            {
                PropertyController.PropertyData.ExtPosX = player.position.X;
                PropertyController.PropertyData.ExtPosY = player.position.Y;
                PropertyController.PropertyData.ExtPosZ = player.position.Z;

                PropertyController.ExteriorMarker.position    = player.position - new Vector3(0.0f, 0.0f, 1.0f);
                PropertyController.ExteriorTextLabel.position = player.position + new Vector3(0.0f, 0.0f, 0.5f);
                API.deleteColShape(PropertyController.ExteriorColShape);
                PropertyController.CreateColShape();
                ContextFactory.Instance.SaveChanges();
            }
            else if (msg.ToLower() == "ipl")
            {
                PropertyController.PropertyData.IPL = msg;
                ContextFactory.Instance.SaveChanges();
            }
            else if (msg.ToLower() == "enterable")
            {
                bool IsEnterable = PropertyController.PropertyData.Enterable;
                PropertyController.PropertyData.Enterable = !IsEnterable;
                API.sendChatMessageToPlayer(player, "You set the property to: " + (IsEnterable ? "Enterable" : "Closed"));
                ContextFactory.Instance.SaveChanges();
            }
            else
            {
                API.sendChatMessageToPlayer(player, "~r~ERROR: ~w~You specified an invalid option.");
            }
        }
Beispiel #46
0
        public async Task Manage_Post_Success()
        {
            var returnUrl = "/";
            var context   = MakeContext();
            var user      = context.Users[1];

            context.LoggedInUser = user;

            var branch = context.Branches[0];
            var car    = context.Cars[0];
            var vm     = new ManageViewModel
            {
                UserId    = user.Id,
                UserName  = user.UserName + "1",
                Email     = user.Email + "1",
                FirstName = user.FirstName + "1",
                LastName  = user.LastName + "1",
                HasBranch = user.Role.HasBranch,
                BranchId  = branch.Id,
                HasCar    = user.Role.HasCar,
                CarId     = car.Id,
                Password  = user.PasswordHash,
                ReturnUrl = returnUrl
            };

            var controller = new AccountController(
                context.UsersDao,
                context.BranchesDao,
                context.CarsDao,
                context.CurrentUserService)
            {
                TempData = context.TempDataDictionary
            };

            var r = await controller.Manage(vm) as ViewResult;

            Assert.NotNull(r);
            Assert.Null(r.ViewName);

            var returnedVm = r.Model as ManageViewModel;

            Assert.NotNull(returnedVm);
            var expectedAllBranches = vm.HasBranch ? context.Branches : null;
            var expectedAllCars     = vm.HasCar ? context.Cars : null;

            Assert.Equal(expectedAllBranches, returnedVm.AllBranches);
            Assert.Equal(expectedAllCars, returnedVm.AllCars);
            Assert.Equal(vm.ReturnUrl, returnedVm.ReturnUrl);
            Assert.Equal(vm.UserName, context.LoggedInUser.UserName);
            Assert.Equal(vm.Email, context.LoggedInUser.Email);
            Assert.Equal(vm.FirstName, context.LoggedInUser.FirstName);
            Assert.Equal(vm.LastName, context.LoggedInUser.LastName);
            if (vm.HasBranch)
            {
                Assert.Same(branch, context.CurrentBranch);
            }
            else
            {
                context.CurrentUserServiceMock.Verify(
                    m => m.SetBranchAsync(It.IsAny <long>()),
                    Times.Never);
            }
            if (vm.HasCar)
            {
                Assert.Same(car, context.CurrentCar);
            }
            else
            {
                context.CurrentUserServiceMock.Verify(
                    m => m.SetCarAsync(It.IsAny <long>()),
                    Times.Never);
            }
        }
 public TestAccountController()
 {
     controller = new AccountController(acctrepo);
 }
Beispiel #48
0
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            string      V_AccountType = string.Empty;
            LVLoginUser user          = null;

            AccountController.ResultLogin loginUser = null;
            Task task;

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            //filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
            var form = await context.Request.ReadFormAsync();

            //sử dụng cho trường hợp login theo loại tài khoản nào
            if (form["V_AccountType"] != null)
            {
                V_AccountType = form["V_AccountType"].ToString();
            }
            task = Task.Factory.StartNew <LVLoginUser>(() =>
            {
                AccountController ac = new AccountController();
                loginUser            = ac.Login(context.UserName, context.Password);
                user = loginUser.loginUser;
                return(user);
            });

            await task;

            if (loginUser.loginUser == null)
            {
                context.SetError(loginUser.code);
                return;
            }
            IDictionary <string, string> data = new Dictionary <string, string>();

            if (loginUser.loginUser != null)
            {
                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                if (loginUser.loginUser.UserCode == null)
                {
                    loginUser.loginUser.UserCode = "";
                }
                if (loginUser.loginUser.Type == null)
                {
                    loginUser.loginUser.Type = loginUser.loginUser.Type;
                }
                if (loginUser.loginUser.ConfigByUser == null)
                {
                    loginUser.loginUser.ConfigByUser = "";
                }
                if (loginUser.loginUser.account.PrimaryRoleID == null)
                {
                    loginUser.loginUser.account.PrimaryRoleID = 0;
                }
                data.Add("error", loginUser.code);
                data.Add("ReturnCode", loginUser.code);
                data.Add("UserName", loginUser.loginUser.PersName);
                data.Add("Mail", loginUser.loginUser.Email);
                data.Add("PersonID", loginUser.loginUser.account.PersonID.ToString());
                data.Add("AccountID", loginUser.loginUser.account.AccountID.ToString());
                data.Add("ProfilePhoto", loginUser.loginUser.ProfilePhoto);
                data.Add("FirstName", loginUser.loginUser.FirstName);
                //data.Add("PtCode", loginUser.loginUser.UserCode);
                data.Add("Type", loginUser.loginUser.Type.ToString());
                data.Add("Role", loginUser.loginUser.account.PrimaryRoleID.ToString());
                data.Add("RoleName", loginUser.loginUser.account.RoleName);
                //data.Add("Config", loginUser.loginUser.ConfigByUser);
                AuthenticationProperties properties = new AuthenticationProperties(data);
                AuthenticationTicket     ticket     = new AuthenticationTicket(identity, properties);
                context.Validated(ticket);
            }
        }
 protected override void runImpl()
 {
     AccountController.CheckAuth(key, base.Client);
 }
Beispiel #50
0
        public async Task AccountController_newAccount_TryToOverwrite_ButItKeepsTheSamePassword()
        {
            // Arrange
            var userId = "*****@*****.**";
            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, userId)
            };

            _serviceProvider.GetRequiredService <IUserManager>();

            var httpContext = _serviceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;

            httpContext.User            = new ClaimsPrincipal(new ClaimsIdentity(claims));
            httpContext.RequestServices = _serviceProvider;

            // needed to have httpContext.User.Identity.IsAuthenticated
            _serviceProvider.GetRequiredService <IAuthenticationSchemeProvider>();

            var controller =
                new AccountController(_userManager, _appSettings, _antiForgery, _selectorStorage)
            {
                ControllerContext = { HttpContext = httpContext }
            };

            // Get context for url (netcore3)
            var routeData = new RouteData();

            routeData.Values.Add("key1", "value1");
            var actionDescriptor = new ActionDescriptor();
            var actionContext    = new ActionContext(httpContext, routeData, actionDescriptor);

            controller.Url = new UrlHelper(actionContext);
            // end url context

            var login = new LoginViewModel
            {
                Email    = userId,
                Password = "******"
            };

            // Make new account;
            var newAccount = new RegisterViewModel
            {
                Password        = "******",
                ConfirmPassword = "******",
                Email           = userId,
                Name            = userId
            };

            // Arrange > new account
            await controller.Register(newAccount);

            // login > it must be succesfull
            await controller.LoginPost(login);

            // Test login
            Assert.AreEqual(true, httpContext.User.Identity.IsAuthenticated);

            // The logout is mocked so this will not actual log it out;
            // controller.Logout() not crashing is good enough;
            controller.LogoutJson();


            var newAccountDuplicate = new RegisterViewModel
            {
                Password        = "******",          // DIFFERENT
                ConfirmPassword = "******",
                Email           = userId,
                Name            = "should not be updated"
            };

            // For security reasons there is no feedback when a account already exist
            await controller.Register(newAccountDuplicate);

            // Try login again > now it must be succesfull
            await controller.LoginPost(login);

            // Test login
            Assert.AreEqual(true, httpContext.User.Identity.IsAuthenticated);

            // The logout is mocked so this will not actual log it out;
            // controller.Logout() not crashing is good enough;
            controller.LogoutJson();

            // Clean afterwards
            var user = _dbContext.Users.FirstOrDefault(p => p.Name == userId);

            _dbContext.Users.Remove(user);
            await _dbContext.SaveChangesAsync();
        }
Beispiel #51
0
 public void SetupContext()
 {
     controller = new AccountController();
 }
Beispiel #52
0
        protected void btnOrder_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime currentDate = DateTime.Now;
                string   username    = Request.Cookies["usernameLoginSystem"].Value;
                var      acc         = AccountController.GetByUsername(username);
                if (acc != null)
                {
                    if (acc.RoleID == 0 || acc.RoleID == 2)
                    {
                        #region Lấy thông tin khởi tạo Order
                        // Change user
                        string UserHelp = "";
                        if (username != hdfUsernameCurrent.Value)
                        {
                            UserHelp = username;
                            username = hdfUsernameCurrent.Value;
                        }

                        int    AgentID     = Convert.ToInt32(acc.AgentID);
                        int    OrderType   = hdfOrderType.Value.ToInt();
                        string AdditionFee = "0";
                        string DisCount    = "0";
                        int    CustomerID  = 0;

                        string CustomerPhone   = Regex.Replace(txtPhone.Text.Trim(), @"[^\d]", "");
                        string CustomerName    = txtFullname.Text.Trim().ToLower().ToTitleCase();
                        string CustomerEmail   = "";
                        string CustomerAddress = txtAddress.Text.Trim().ToTitleCase();

                        int ProvinceID = hdfProvinceID.Value.ToInt(0);
                        int DistrictID = hdfDistrictID.Value.ToInt(0);
                        int WardID     = hdfWardID.Value.ToInt(0);

                        var checkCustomer = CustomerController.GetByPhone(CustomerPhone);

                        string kq = "";

                        #region Cập nhật thông tin khách hàng
                        if (checkCustomer != null)
                        {
                            CustomerID = checkCustomer.ID;
                            kq         = CustomerController.Update(CustomerID, CustomerName, checkCustomer.CustomerPhone, CustomerAddress, "", checkCustomer.CustomerLevelID.Value, checkCustomer.Status.Value, checkCustomer.CreatedBy, currentDate, username, false, checkCustomer.Zalo, checkCustomer.Facebook, checkCustomer.Note, checkCustomer.Nick, checkCustomer.Avatar, checkCustomer.ShippingType.Value, checkCustomer.PaymentType.Value, checkCustomer.TransportCompanyID.Value, checkCustomer.TransportCompanySubID.Value, checkCustomer.CustomerPhone2, ProvinceID, DistrictID, WardID);
                        }
                        else
                        {
                            kq = CustomerController.Insert(CustomerName, CustomerPhone, CustomerAddress, CustomerEmail, 0, 0, currentDate, username, false, "", "", "", "", "", 0, 0, 0, 0, "", ProvinceID, DistrictID, WardID);
                            if (kq.ToInt(0) > 0)
                            {
                                CustomerID = kq.ToInt(0);
                            }
                        }
                        #endregion

                        string totalPrice            = hdfTotalPrice.Value.ToString();
                        string totalPriceNotDiscount = hdfTotalPriceNotDiscount.Value;
                        int    PaymentStatus         = 3;
                        int    ExcuteStatus          = 2;
                        int    PaymentType           = 1;
                        int    ShippingType          = 1;

                        bool IsHidden = false;
                        int  WayIn    = 1;

                        double DiscountPerProduct = Convert.ToDouble(pDiscount.Value);

                        double TotalDiscount = Convert.ToDouble(pDiscount.Value) * Convert.ToDouble(hdfTotalQuantity.Value);
                        string FeeShipping   = pFeeShip.Value.ToString();
                        double GuestPaid     = Convert.ToDouble(pGuestPaid.Value);
                        double GuestChange   = Convert.ToDouble(totalPrice) - GuestPaid;
                        var    couponID      = hdfCouponID.Value.ToInt(0);
                        var    couponValue   = hdfCouponValue.Value.ToDecimal(0);

                        tbl_Order order = new tbl_Order()
                        {
                            AgentID               = AgentID,
                            OrderType             = OrderType,
                            AdditionFee           = AdditionFee,
                            DisCount              = DisCount,
                            CustomerID            = CustomerID,
                            CustomerName          = CustomerName,
                            CustomerPhone         = CustomerPhone,
                            CustomerAddress       = CustomerAddress,
                            CustomerEmail         = CustomerEmail,
                            TotalPrice            = totalPrice,
                            TotalPriceNotDiscount = totalPriceNotDiscount,
                            PaymentStatus         = PaymentStatus,
                            ExcuteStatus          = ExcuteStatus,
                            IsHidden              = IsHidden,
                            WayIn              = WayIn,
                            CreatedDate        = currentDate,
                            CreatedBy          = username,
                            DiscountPerProduct = DiscountPerProduct,
                            TotalDiscount      = TotalDiscount,
                            FeeShipping        = FeeShipping,
                            GuestPaid          = GuestPaid,
                            GuestChange        = GuestChange,
                            PaymentType        = PaymentType,
                            ShippingType       = ShippingType,
                            OrderNote          = String.Empty,
                            DateDone           = DateTime.Now,
                            OtherFeeName       = String.Empty,
                            OtherFeeValue      = 0,
                            PostalDeliveryType = 1,
                            UserHelp           = UserHelp,
                            CouponID           = couponID,
                            CouponValue        = couponValue
                        };

                        var ret = OrderController.InsertOnSystem(order);

                        int OrderID = ret.ID;
                        #endregion

                        #region Khởi tạo Other Fee
                        if (!String.IsNullOrEmpty(hdfOtherFees.Value))
                        {
                            JavaScriptSerializer serializer = new JavaScriptSerializer();
                            var fees = serializer.Deserialize <List <Fee> >(hdfOtherFees.Value);
                            if (fees != null)
                            {
                                foreach (var fee in fees)
                                {
                                    fee.OrderID      = ret.ID;
                                    fee.CreatedBy    = acc.ID;
                                    fee.CreatedDate  = DateTime.Now;
                                    fee.ModifiedBy   = acc.ID;
                                    fee.ModifiedDate = DateTime.Now;
                                }

                                FeeController.Update(ret.ID, fees);
                            }
                        }
                        #endregion

                        #region Cập nhật Coupon
                        if (order.CouponID.HasValue && order.CouponID.Value > 0)
                        {
                            CouponController.updateStatusCouponCustomer(CustomerID, order.CouponID.Value, false);
                        }
                        #endregion

                        if (OrderID > 0)
                        {
                            #region Khởi tạo chi tiết đơn hàng
                            ProductPOS              POS          = JsonConvert.DeserializeObject <ProductPOS>(hdfListProduct.Value);
                            List <tbl_OrderDetail>  orderDetails = new List <tbl_OrderDetail>();
                            List <tbl_StockManager> stockManager = new List <tbl_StockManager>();

                            // Reverser
                            POS.productPOS.Reverse();

                            foreach (ProductGetOut item in POS.productPOS)
                            {
                                orderDetails.Add(
                                    new tbl_OrderDetail()
                                {
                                    AgentID                   = AgentID,
                                    OrderID                   = OrderID,
                                    SKU                       = item.SKU,
                                    ProductID                 = item.ProductType == 1 ? item.ProductID : 0,
                                    ProductVariableID         = item.ProductType == 1 ? 0 : item.ProductVariableID,
                                    ProductVariableDescrition = item.ProductVariableSave,
                                    Quantity                  = item.QuantityInstock,
                                    Price                     = item.Giabanle,
                                    Status                    = 1,
                                    DiscountPrice             = 0,
                                    ProductType               = item.ProductType,
                                    CreatedDate               = currentDate,
                                    CreatedBy                 = username,
                                    IsCount                   = true
                                }
                                    );

                                int parentID = item.ProductID;
                                var variable = ProductVariableController.GetByID(item.ProductVariableID);
                                if (variable != null)
                                {
                                    parentID = Convert.ToInt32(variable.ProductID);
                                }

                                stockManager.Add(
                                    new tbl_StockManager()
                                {
                                    AgentID           = AgentID,
                                    ProductID         = item.ProductType == 1 ? item.ProductID : 0,
                                    ProductVariableID = item.ProductType == 1 ? 0 : item.ProductVariableID,
                                    Quantity          = item.QuantityInstock,
                                    QuantityCurrent   = 0,
                                    Type        = 2,
                                    NoteID      = "Xuất kho bán POS",
                                    OrderID     = OrderID,
                                    Status      = 3,
                                    SKU         = item.SKU,
                                    CreatedDate = currentDate,
                                    CreatedBy   = username,
                                    MoveProID   = 0,
                                    ParentID    = parentID
                                }
                                    );
                            }

                            OrderDetailController.Insert(orderDetails);
                            #endregion

                            // Cập nhật lại sô lượng và giá vố vào đơn hàng
                            OrderController.updateQuantityCOGS(OrderID);
                            // Cập nhật lại thông tin kho hàng
                            StockManagerController.Insert(stockManager);

                            #region Khởi tạo đơn hàng đổi trả
                            string refund = hdSession.Value;
                            if (refund != "1")
                            {
                                string[] RefundID = refund.Split('|');
                                var      update   = RefundGoodController.UpdateStatus(RefundID[0].ToInt(), username, 2, OrderID);
                                var      updateor = OrderController.UpdateRefund(OrderID, RefundID[0].ToInt(), username);
                            }
                            #endregion

                            // Hoàn thành khởi tạo đơn hàng nên gán lại giá trị trang lúc ban đầu
                            hdStatusPage.Value = "Create";
                            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { HoldOn.close(); printInvoice(" + OrderID + ") });", true);
                        }
                    }
                }
            }
            catch (Exception)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { handleErrorSubmit(); });", true);
            }
        }
        public void SetUp()
        {
            var activityLogMock = Substitute.For <IMembershipActivityLogger>();

            controller = new AccountController(activityLogMock, null);
        }
Beispiel #54
0
        public async Task AccountController_NoLogin_Login_And_newAccount_Test()
        {
            // Arrange
            var userId = "TestUserA";
            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, userId)
            };

            var httpContext = _serviceProvider.GetRequiredService <IHttpContextAccessor>().HttpContext;

            httpContext.User            = new ClaimsPrincipal(new ClaimsIdentity(claims));
            httpContext.RequestServices = _serviceProvider;

            AccountController controller = new AccountController(_userManager, _appSettings, _antiForgery, _selectorStorage);

            controller.ControllerContext.HttpContext = httpContext;

            // Get context for url (netcore3)
            var routeData = new RouteData();

            routeData.Values.Add("key1", "value1");
            var actionDescriptor = new ActionDescriptor();

            var actionContext = new ActionContext(httpContext, routeData, actionDescriptor);

            controller.Url = new UrlHelper(actionContext);
            // end url context

            var login = new LoginViewModel
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            // Try login > result login false
            await controller.LoginPost(login);

            // Test login
            Assert.AreEqual(false, httpContext.User.Identity.IsAuthenticated);

            // Reset the model state,
            // to avoid errors on RegisterViewModel
            // in a normal session the State is cleared after 1 request
            controller.ModelState.Clear();


            // Make new account;
            var newAccount = new RegisterViewModel
            {
                Password        = "******",
                ConfirmPassword = "******",
                Email           = "*****@*****.**",
                Name            = "*****@*****.**",
            };

            // Arange > new account
            await controller.Register(newAccount);

            // Try login again > now it must be succesfull
            await controller.LoginPost(login);

            // Test login
            Assert.AreEqual(true, httpContext.User.Identity.IsAuthenticated);

            // The logout is mocked so this will not actual log it out;
            // controller.Logout() not crashing is good enough;
            controller.Logout();

            // And clean afterwards
            var itemWithId = _dbContext.Users.FirstOrDefault(p => p.Name == newAccount.Name);

            _dbContext.Users.Remove(itemWithId);
            await _dbContext.SaveChangesAsync();
        }
Beispiel #55
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            int      AgentID     = 0;
            string   username    = Request.Cookies["userLoginSystem"].Value;

            if (!string.IsNullOrEmpty(username))
            {
                var a = AccountController.GetByUsername(username);
                if (a != null)
                {
                    AgentID = Convert.ToInt32(a.AgentID);
                    string phone = hdfPhone.Value;
                    if (!string.IsNullOrEmpty(phone))
                    {
                        var cust = CustomerController.GetByPhone(phone);
                        if (cust != null)
                        {
                            int    custID        = cust.ID;
                            string totalprice    = hdfTotalPrice.Value;
                            string totalquantity = hdfTotalQuantity.Value;
                            string totalrefund   = hdfTotalRefund.Value;
                            var    agent         = AgentController.GetByID(AgentID);
                            string agentName     = "";
                            if (agent != null)
                            {
                                agentName = agent.AgentName;
                            }
                            //insert ddlstatus, refundnote
                            int    status      = ddlRefundStatus.SelectedValue.ToInt();
                            string RefundsNote = txtRefundsNote.Text;
                            int    rID         = RefundGoodController.Insert(AgentID, totalprice, status, custID, Convert.ToDouble(totalquantity),
                                                                             totalrefund, agentName, cust.CustomerName, cust.CustomerPhone, currentDate, username, RefundsNote);
                            if (rID > 0)
                            {
                                string   listString = hdfListProduct.Value;
                                string[] items      = listString.Split('|');
                                if (items.Length - 1 > 0)
                                {
                                    for (int i = 0; i < items.Length - 1; i++)
                                    {
                                        string[] element                 = items[i].Split(';');
                                        var      sku                     = element[0];
                                        var      orderID                 = element[1].ToInt(0);
                                        var      orderDetailID           = element[2];
                                        var      ProductName             = element[3];
                                        var      GiavonPerProduct        = Convert.ToDouble(element[5]);
                                        var      SoldPricePerProduct     = Convert.ToDouble(element[6]);
                                        var      DiscountPricePerProduct = Convert.ToDouble(element[7]);
                                        var      quantity                = Convert.ToDouble(element[10]);
                                        var      quantityMax             = Convert.ToDouble(element[8]);
                                        var      ProductType             = element[4].ToInt(1);
                                        var      RefundType              = element[9].ToInt(1);
                                        var      RefundFeePerProduct     = Convert.ToDouble(element[11]);
                                        var      TotalPriceRow           = element[12];
                                        var      PriceNotFeeRefund       = SoldPricePerProduct * quantity;
                                        var      rdTotalRefundFee        = RefundFeePerProduct * quantity;

                                        int rdID = RefundGoodDetailController.Insert(rID, AgentID, orderID, ProductName, custID, sku, quantity,
                                                                                     quantityMax, PriceNotFeeRefund.ToString(), ProductType, true, RefundType, RefundFeePerProduct.ToString(),
                                                                                     rdTotalRefundFee.ToString(), GiavonPerProduct.ToString(), DiscountPricePerProduct.ToString(), SoldPricePerProduct.ToString(),
                                                                                     TotalPriceRow, currentDate, username);
                                        if (rdID > 0)
                                        {
                                            if (RefundType < 3)
                                            {
                                                int    typeRe = 0;
                                                string note   = "";
                                                if (RefundType == 1)
                                                {
                                                    note   = "Đổi size";
                                                    typeRe = 8;
                                                }
                                                else if (RefundType == 2)
                                                {
                                                    note   = "Đổi sản phẩm";
                                                    typeRe = 9;
                                                }
                                                if (ProductType == 1)
                                                {
                                                    var product = ProductController.GetBySKU(sku);
                                                    if (product != null)
                                                    {
                                                        int    productID          = product.ID;
                                                        string ProductImageOrigin = "";
                                                        var    ProductImage       = ProductImageController.GetFirstByProductID(product.ID);
                                                        if (ProductImage != null)
                                                        {
                                                            ProductImageOrigin = ProductImage.ProductImage;
                                                        }
                                                        StockManagerController.Insert(
                                                            new tbl_StockManager {
                                                            AgentID           = AgentID,
                                                            ProductID         = productID,
                                                            ProductVariableID = 0,
                                                            Quantity          = quantity,
                                                            QuantityCurrent   = 0,
                                                            Type        = 1,
                                                            NoteID      = note,
                                                            OrderID     = orderID,
                                                            Status      = typeRe,
                                                            SKU         = sku,
                                                            CreatedDate = currentDate,
                                                            CreatedBy   = username,
                                                            MoveProID   = 0,
                                                            ParentID    = productID,
                                                        });
                                                    }
                                                }
                                                else
                                                {
                                                    string ProductVariableName  = "";
                                                    string ProductVariableValue = "";
                                                    string ProductVariable      = "";
                                                    int    parentID             = 0;
                                                    string parentSKU            = "";
                                                    string ProductImageOrigin   = "";
                                                    int    ID = 0;

                                                    var productvariable = ProductVariableController.GetBySKU(sku);
                                                    if (productvariable != null)
                                                    {
                                                        ID = productvariable.ID;
                                                        ProductImageOrigin = productvariable.Image;
                                                        parentSKU          = productvariable.ParentSKU;
                                                        var variables = ProductVariableValueController.GetByProductVariableID(productvariable.ID);
                                                        if (variables.Count > 0)
                                                        {
                                                            foreach (var v in variables)
                                                            {
                                                                ProductVariable      += v.VariableName.Trim() + ":" + v.VariableValue.Trim() + "|";
                                                                ProductVariableName  += v.VariableName + "|";
                                                                ProductVariableValue += v.VariableValue + "|";
                                                            }
                                                        }
                                                    }
                                                    if (!string.IsNullOrEmpty(parentSKU))
                                                    {
                                                        var product = ProductController.GetBySKU(parentSKU);
                                                        if (product != null)
                                                        {
                                                            parentID = product.ID;
                                                        }
                                                    }


                                                    StockManagerController.Insert(
                                                        new tbl_StockManager {
                                                        AgentID           = AgentID,
                                                        ProductID         = 0,
                                                        ProductVariableID = ID,
                                                        Quantity          = quantity,
                                                        QuantityCurrent   = 0,
                                                        Type        = 1,
                                                        NoteID      = note,
                                                        OrderID     = orderID,
                                                        Status      = typeRe,
                                                        SKU         = sku,
                                                        CreatedDate = currentDate,
                                                        CreatedBy   = username,
                                                        MoveProID   = 0,
                                                        ParentID    = parentID,
                                                    });
                                                }
                                            }
                                        }
                                        PJUtils.ShowMessageBoxSwAlertCallFunction("Tạo đơn hàng đổi trả thành công", "s", true, "redirectTo(" + rID + ")", Page);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
 public AccountControllerTest()
 {
     fakeUserService = new FakeUserService();
     controller      = new AccountController(fakeUserService);
 }
Beispiel #57
0
        public void LoadData()
        {
            string username = HttpContext.Current.Request.Cookies["usernameLoginSystem"].Value;
            var    acc      = AccountController.GetByUsername(username);

            int    id  = Request.QueryString["id"].ToInt(0);
            string sku = Request.QueryString["sku"];

            var p = new tbl_Product();

            if (id > 0)
            {
                p = ProductController.GetByID(id);
            }
            else if (id == 0)
            {
                int variableid = Request.QueryString["variableid"].ToInt(0);
                if (variableid != 0)
                {
                    p = ProductController.GetByVariableID(variableid);
                }
                else
                {
                    if (sku != "")
                    {
                        p = ProductController.GetBySKU(sku);
                        if (p == null)
                        {
                            p = ProductController.GetByVariableSKU(sku);
                        }
                    }
                }
            }

            if (p == null)
            {
                PJUtils.ShowMessageBoxSwAlertError("Không tìm thấy sản phẩm " + id, "e", true, "/tat-ca-san-pham", Page);
            }
            else
            {
                this.Title = String.Format("{0} - Sản phẩm", p.ProductSKU.ToTitleCase());

                ViewState["ID"]     = id;
                ViewState["cateID"] = p.CategoryID;
                ViewState["SKU"]    = p.ProductSKU;

                ltrEdit1.Text = "";
                if (acc.RoleID == 0 || acc.RoleID == 1 || acc.Username == "nhom_zalo502")
                {
                    ltrEdit1.Text += "<a href='/thong-tin-san-pham?id=" + p.ID + "' class='btn primary-btn fw-btn not-fullwidth'><i class='fa fa-pencil-square-o' aria-hidden='true'></i> Chỉnh sửa</a>";
                    ltrEdit1.Text += "<a href='/tao-san-pham' class='btn primary-btn fw-btn not-fullwidth print-invoice-merged'><i class='fa fa-file-text-o' aria-hidden='true'></i> Thêm mới</a>";
                    if (p.ShowHomePage == 1)
                    {
                        ltrEdit1.Text += "<a href='javascript:;' onclick='showProductSyncModal(`" + p.ProductSKU + "`, " + p.ID + ", " + p.CategoryID + ");' class='btn primary-btn not-fullwidth print-invoice-merged'><i class='fa fa-upload' aria-hidden='true'></i> Đồng bộ</a>";
                    }
                }
                ltrEdit1.Text += "<a href='javascript:;' onclick='copyProductInfo(" + p.ID + ")' class='btn primary-btn not-fullwidth print-invoice-merged'><i class='fa fa-files-o'></i> Copy thông tin</a>";
                ltrEdit1.Text += "<a href='javascript:;' onclick='getAllProductImage(`" + p.ProductSKU + "`);' class='btn primary-btn not-fullwidth print-invoice-merged'><i class='fa fa-cloud-download'></i> Tải tất cả hình ảnh</a>";

                if (acc.RoleID == 0 || acc.Username == "nhom_zalo502")
                {
                    ltrEdit1.Text += "<a href='javascript:;' onclick='deleteProduct(" + p.ID + ");' class='btn primary-btn not-fullwidth print-invoice-merged btn-red'><i class='fa fa-times'></i> Xóa sản phẩm</a>";
                    ltrEdit1.Text += "<a href='javascript:;' data-toggle='modal' data-target='#modalUpdateProductSKU' data-backdrop='static' data-keyboard='false' class='btn primary-btn not-fullwidth print-invoice-merged btn-blue'><i class='fa fa-times'></i> Sửa mã sản phẩm</a>";
                }

                ltrEdit2.Text = ltrEdit1.Text;

                lbProductTitle.Text = p.ProductTitle;
                pContent.Text       = p.ProductContent;
                lblSKU.Text         = p.ProductSKU;
                txtOldSKU.Text      = p.ProductSKU;

                // Create order fileter
                var filter = new ProductFilterModel()
                {
                    search = p.ProductSKU
                };
                // Create pagination
                var page = new PaginationMetadataModel();
                var a    = ProductController.GetAllSql(filter, ref page);
                if (page.totalCount > 0)
                {
                    foreach (var item in a)
                    {
                        lbProductStock.Text          = item.TotalProductInstockQuantityLeft.ToString();
                        ddlStockStatus.SelectedValue = item.StockStatus.ToString();
                    }
                }
                else
                {
                    lbProductStock.Text = "0";
                }

                lbOldPrice.Text     = string.Format("{0:N0}", p.Old_Price);
                lbRegularPrice.Text = string.Format("{0:N0}", p.Regular_Price);

                ltrCostOfGood.Text = "";
                if (acc.RoleID == 0)
                {
                    ltrCostOfGood.Text += "<div class='form-row'>";
                    ltrCostOfGood.Text += "    <div class='row-left'>";
                    ltrCostOfGood.Text += "        Giá vốn";
                    ltrCostOfGood.Text += "    </div>";
                    ltrCostOfGood.Text += "    <div class='row-right'>";
                    ltrCostOfGood.Text += "        <span class='form-control'>" + string.Format("{0:N0}", p.CostOfGood) + "</span>";
                    ltrCostOfGood.Text += "    </div>";
                    ltrCostOfGood.Text += "</div>";
                }

                lbRetailPrice.Text        = string.Format("{0:N0}", p.Retail_Price);
                ddlSupplier.SelectedValue = p.SupplierID.ToString();
                ddlCategory.SelectedValue = p.CategoryID.ToString();
                lbMaterials.Text          = p.Materials;
                lbColor.Text = p.Color;

                // Hàng order
                ddlPreOrder.SelectedValue = p.PreOrder ? "1" : "0";

                // thư viện ảnh
                var image = ProductImageController.GetByProductID(id);
                imageGallery.Text  = "<ul class='image-gallery'>";
                imageGallery.Text += "<li><img src='" + Thumbnail.getURL(p.ProductImage, Thumbnail.Size.Normal) + "'><a href='" + Thumbnail.getURL(p.ProductImage, Thumbnail.Size.Source) + "' download class='btn download-btn download-image h45-btn'><i class='fa fa-cloud-download'></i> Tải hình này</a></li>";
                if (image != null)
                {
                    foreach (var img in image)
                    {
                        if (img.ProductImage != p.ProductImage)
                        {
                            imageGallery.Text += "<li><img src='" + Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Normal) + "'><a href='" + Thumbnail.getURL(img.ProductImage, Thumbnail.Size.Source) + "' download class='btn download-btn download-image h45-btn'><i class='fa fa-cloud-download'></i> Tải hình này</a></li>";
                        }
                    }
                }
                imageGallery.Text += "</ul>";


                hdfTable.Value = p.ProductStyle.ToString();

                // Init Tag
                var tagIDList = ProductTagController.get(p.ID, 0)
                                .Select(x => x.name)
                                .ToList();
                hdfTags.Value = String.Join(",", tagIDList);

                List <tbl_ProductVariable> b = new List <tbl_ProductVariable>();

                b = ProductVariableController.SearchProductID(p.ID, "");
                if (b != null)
                {
                    pagingall(b, Convert.ToInt32(acc.RoleID));
                }
            }
        }
 public void Setup()
 {
     databaseController = Substitute.For <IDatabaseController>();
     _options           = Substitute.For <IOptions <AppSettings> >();
     _uut = new AccountController(databaseController, _options);
 }
Beispiel #59
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.GetCurrent(this).AsyncPostBackTimeout = 600;

            if (!IsPostBack)
            {
                if (Request.Cookies["usernameLoginSystem"] != null)
                {
                    hdStatusPage.Value = "Create";
                    string username = Request.Cookies["usernameLoginSystem"].Value;
                    var    acc      = AccountController.GetByUsername(username);
                    if (acc != null)
                    {
                        hdfUsernameCurrent.Value = acc.Username;

                        if (acc.RoleID == 0)
                        {
                            hdfRoleID.Value = acc.RoleID.ToString();
                        }
                        else if (acc.RoleID == 2)
                        {
                            hdfRoleID.Value   = acc.RoleID.ToString();
                            hdfUsername.Value = acc.Username;
                        }
                        else
                        {
                            Response.Redirect("/trang-chu");
                        }

                        hdSession.Value = "1";

                        var dc = DiscountController.GetAll();
                        if (dc != null)
                        {
                            string list = "";
                            foreach (var item in dc)
                            {
                                list += item.Quantity + "-" + item.DiscountPerProduct + "|";
                            }
                            hdfChietKhau.Value = list;
                        }

                        // get user list (only role 2) to change user when create order
                        var CreateBy = AccountController.GetAllByRoleID(2);
                        if (CreateBy != null)
                        {
                            string listUser = "";
                            foreach (var item in CreateBy)
                            {
                                if (item.Username != acc.Username)
                                {
                                    listUser += item.Username + "|";
                                }
                            }
                            hdfListUser.Value = listUser;
                        }
                    }
                }
                else
                {
                    Response.Redirect("/dang-nhap");
                }
                LoadPage();
            }
        }
Beispiel #60
0
        protected void btnOrder_Click(object sender, EventArgs e)
        {
            DateTime currentDate = DateTime.Now;
            string   username    = Request.Cookies["userLoginSystem"].Value;
            var      acc         = AccountController.GetByUsername(username);

            if (acc != null)
            {
                if (acc.RoleID == 0 || acc.RoleID == 2)
                {
                    // Change user
                    string OrderNote = "";
                    if (username != hdfUsernameCurrent.Value)
                    {
                        OrderNote = "Được tính tiền giúp bởi " + username;
                        username  = hdfUsernameCurrent.Value;
                    }

                    int    AgentID     = Convert.ToInt32(acc.AgentID);
                    int    OrderType   = hdfOrderType.Value.ToInt();
                    string AdditionFee = "0";
                    string DisCount    = "0";
                    int    CustomerID  = 0;

                    string CustomerPhone   = txtPhone.Text.Trim().Replace(" ", "");
                    string CustomerName    = txtFullname.Text.Trim();
                    string Nick            = txtNick.Text.Trim();
                    string CustomerEmail   = "";
                    string CustomerAddress = txtAddress.Text.Trim();

                    var checkCustomer = CustomerController.GetByPhone(CustomerPhone);

                    if (checkCustomer != null)
                    {
                        CustomerID = checkCustomer.ID;
                        string kq = CustomerController.Update(CustomerID, CustomerName, checkCustomer.CustomerPhone, CustomerAddress, "", Convert.ToInt32(checkCustomer.CustomerLevelID), Convert.ToInt32(checkCustomer.Status), checkCustomer.CreatedBy, currentDate, username, false, checkCustomer.Zalo, checkCustomer.Facebook, checkCustomer.Note, checkCustomer.ProvinceID.ToString(), Nick, checkCustomer.Avatar, Convert.ToInt32(checkCustomer.ShippingType), Convert.ToInt32(checkCustomer.PaymentType), Convert.ToInt32(checkCustomer.TransportCompanyID), Convert.ToInt32(checkCustomer.TransportCompanySubID), checkCustomer.CustomerPhone2);
                    }
                    else
                    {
                        string kq = CustomerController.Insert(CustomerName, CustomerPhone, CustomerAddress, CustomerEmail, 0, 0, currentDate, username, false, "", "", "", "", Nick);
                        if (kq.ToInt(0) > 0)
                        {
                            CustomerID = kq.ToInt(0);
                        }
                    }

                    string totalPrice            = hdfTotalPrice.Value.ToString();
                    string totalPriceNotDiscount = hdfTotalPriceNotDiscount.Value;
                    int    PaymentStatus         = 3;
                    int    ExcuteStatus          = 2;
                    int    PaymentType           = 1;
                    int    ShippingType          = 1;
                    bool   IsHidden = false;
                    int    WayIn    = 1;

                    double DiscountPerProduct = Convert.ToDouble(pDiscount.Value);

                    double TotalDiscount = Convert.ToDouble(pDiscount.Value) * Convert.ToDouble(hdfTotalQuantity.Value);
                    string FeeShipping   = pFeeShip.Value.ToString();
                    double GuestPaid     = Convert.ToDouble(pGuestPaid.Value);
                    double GuestChange   = Convert.ToDouble(totalPrice) - GuestPaid;
                    string OtherFeeName  = txtOtherFeeName.Text;
                    double OtherFeeValue = Convert.ToDouble(pOtherFee.Value);

                    var ret = OrderController.InsertOnSystem(AgentID, OrderType, AdditionFee, DisCount, CustomerID, CustomerName, CustomerPhone, CustomerAddress,
                                                             CustomerEmail, totalPrice, totalPriceNotDiscount, PaymentStatus, ExcuteStatus, IsHidden, WayIn, currentDate, username, DiscountPerProduct,
                                                             TotalDiscount, FeeShipping, GuestPaid, GuestChange, PaymentType, ShippingType, OrderNote, DateTime.Now, OtherFeeName, OtherFeeValue, 1);
                    int OrderID = ret.ID;

                    if (OrderID > 0)
                    {
                        ProductPOS              POS          = JsonConvert.DeserializeObject <ProductPOS>(hdfListProduct.Value);
                        List <tbl_OrderDetail>  orderDetails = new List <tbl_OrderDetail>();
                        List <tbl_StockManager> stockManager = new List <tbl_StockManager>();

                        foreach (ProductGetOut item in POS.productPOS)
                        {
                            orderDetails.Add(
                                new tbl_OrderDetail()
                            {
                                AgentID                   = AgentID,
                                OrderID                   = OrderID,
                                SKU                       = item.SKU,
                                ProductID                 = item.ProductType == 1 ? item.ProductID : 0,
                                ProductVariableID         = item.ProductType == 1 ? 0 : item.ProductVariableID,
                                ProductVariableDescrition = item.ProductVariableSave,
                                Quantity                  = item.QuantityInstock,
                                Price                     = item.Giabanle,
                                Status                    = 1,
                                DiscountPrice             = 0,
                                ProductType               = item.ProductType,
                                CreatedDate               = currentDate,
                                CreatedBy                 = username,
                                IsCount                   = true
                            }
                                );

                            int parentID = item.ProductID;
                            var variable = ProductVariableController.GetByID(item.ProductVariableID);
                            if (variable != null)
                            {
                                parentID = Convert.ToInt32(variable.ProductID);
                            }

                            stockManager.Add(
                                new tbl_StockManager()
                            {
                                AgentID           = AgentID,
                                ProductID         = item.ProductType == 1 ? item.ProductID : 0,
                                ProductVariableID = item.ProductType == 1 ? 0 : item.ProductVariableID,
                                Quantity          = item.QuantityInstock,
                                QuantityCurrent   = 0,
                                Type        = 2,
                                NoteID      = "Xuất kho bán POS",
                                OrderID     = OrderID,
                                Status      = 3,
                                SKU         = item.SKU,
                                CreatedDate = currentDate,
                                CreatedBy   = username,
                                MoveProID   = 0,
                                ParentID    = parentID
                            }
                                );
                        }

                        OrderDetailController.Insert(orderDetails);
                        StockManagerController.Insert(stockManager);

                        string refund = Request.Cookies["refund"].Value;
                        if (refund != "1")
                        {
                            string[] RefundID = refund.Split('|');
                            var      update   = RefundGoodController.UpdateStatus(RefundID[0].ToInt(), username, 2, OrderID);
                            var      updateor = OrderController.UpdateRefund(OrderID, RefundID[0].ToInt(), username);
                        }

                        Response.Cookies["refund"].Expires = DateTime.Now.AddDays(-1d);
                        Response.Cookies.Add(Response.Cookies["refund"]);

                        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", "$(function () { printInvoice(" + OrderID + ") });", true);
                    }
                }
            }
        }