public FriendsViewModel()
		{
			Title = "friends";

			ManageViewModel = new ManageViewModel();
			ManageViewModel.PropertyChanged += (sender, args) =>
			{
				SyncTitle(args);
			};
			ListViewModel = new ListViewModel();
		}
Exemple #2
0
        public async Task <ActionResult> ChangeUserData(ManageViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", new { Message = ManageMessageId.ValidationError }));
            }
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            user.UserData = model.UserData;
            var result = await UserManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                return(RedirectToAction("Index", new { Message = ManageMessageId.ChangeUserDataSuccess }));
            }
            return(RedirectToAction("Index", new { Message = ManageMessageId.Error }));
        }
        public async Task <ActionResult> Index()
        {
            var connect = GetConnection();
            var tables  = new List <TableViewModel>();

            tables.AddRange(await GetTables("TABLE", connect.AccountApiKey, connect.DatabaseApiKey));
            tables.AddRange(await GetTables("VIEW", connect.AccountApiKey, connect.DatabaseApiKey));

            var model = new ManageViewModel
            {
                AccountApiKey  = connect.AccountApiKey,
                DatabaseApiKey = connect.DatabaseApiKey,
                Tables         = tables
            };

            return(View(model));
        }
Exemple #4
0
        public async Task <IActionResult> Manage()
        {
            var account = await _userManager.GetUserAsync(User);

            var user = _pulseContext.User.Where(u => u.AccountId == account.Id).ToList()[0];

            ManageViewModel model = new ManageViewModel
            {
                Email       = account.Email,
                UserName    = account.UserName,
                Name        = user.Name,
                PhoneNumber = account.PhoneNumber,
                Location    = user.Location
            };

            return(View("Views/AccountManagement/Manage.cshtml", model));
        }
        public IActionResult DeleteFromManage(ManageViewModel viewModel)
        {
            if (viewModel.SelectedAccommodationToDelete != 0 && viewModel.SelectedActivityToDelete == 0 &&
                viewModel.SelectedDestinationToDelete == 0)
            {
                var accommodation = this.unitOfWork.Accommodations.Get()
                                    .FirstOrDefault(a => a.Id == viewModel.SelectedAccommodationToDelete);
                TempData["message"] = $"Deleted {accommodation.Name} from the accommodations";
                this.unitOfWork.Accommodations.Delete(accommodation);
                this.unitOfWork.Save();
                return(RedirectToAction("Home"));
            }

            if (viewModel.SelectedAccommodationToDelete == 0 && viewModel.SelectedActivityToDelete != 0 &&
                viewModel.SelectedDestinationToDelete == 0)
            {
                var activity = this.unitOfWork.Activities.Get()
                               .FirstOrDefault(a => a.Id == viewModel.SelectedActivityToDelete);
                TempData["message"] = $"Deleted {activity.Name} from the activities";
                this.unitOfWork.Activities.Delete(activity);
                this.unitOfWork.Save();
                return(RedirectToAction("Home"));
            }

            if (viewModel.SelectedAccommodationToDelete == 0 && viewModel.SelectedActivityToDelete == 0 &&
                viewModel.SelectedDestinationToDelete != 0)
            {
                var destination = this.unitOfWork.Destinations.Get()
                                  .FirstOrDefault(d => d.Id == viewModel.SelectedDestinationToDelete);
                TempData["message"] = $"Deleted {destination.Name} from the destinations";
                this.unitOfWork.Destinations.Delete(destination);
                this.unitOfWork.Save();
                return(RedirectToAction("Home"));
            }

            if (viewModel.SelectedAccommodationToDelete == 0 && viewModel.SelectedActivityToDelete == 0 &&
                viewModel.SelectedDestinationToDelete == 0)
            {
                TempData["message"] = "You need to select a destination, accommodation, or activity to delete";
                return(RedirectToAction("Manage"));
            }

            TempData["message"] = "You can only delete one destination, accommodation, or activity at a time.";

            return(RedirectToAction("Manage"));
        }
        public void CreateWithRecipient_CampignWithoutPhoneInDatabase_TrueResult()
        {
            ManageViewModel emptyCampaign = new ManageViewModel()
            {
                PhoneId = 1, Name = "test", Description = "Test"
            };
            List <RecipientViewModel> recepientsList = new List <RecipientViewModel>();

            mockUnitOfWork.Setup(u => u.CompanySubscribeWords.Insert(It.IsAny <CompanySubscribeWord>()));
            mockUnitOfWork.Setup(u => u.SubscribeWords.Get(It.IsAny <Expression <Func <SubscribeWord, bool> > >(), It.IsAny <Func <IQueryable <SubscribeWord>,
                                                                                                                                   IOrderedQueryable <SubscribeWord> > >(), It.IsAny <string>())).Returns(new List <SubscribeWord>()
            {
                new SubscribeWord()
                {
                    Id = 3, Word = "start"
                }
            });
            mockUnitOfWork.Setup(u => u.Phones.Get(It.IsAny <Expression <Func <Phone, bool> > >(), It.IsAny <Func <IQueryable <Phone>,
                                                                                                                   IOrderedQueryable <Phone> > >(), It.IsAny <string>())).Returns(new List <Phone>());
            mockUnitOfWork.Setup(u => u.Companies.Insert(It.IsAny <Company>()));
            mockUnitOfWork.Setup(u => u.Recipients.Insert(It.IsAny <Recipient>()));
            mockUnitOfWork.Setup(u => u.Phones.Insert(It.IsAny <Phone>()));
            mockMapper.Setup(m => m.Map <ManageViewModel, Company>(It.IsAny <ManageViewModel>()))
            .Returns(new Company()
            {
                PhoneId = 1, Name = "test", Message = "test", Description = "Test"
            });
            recepientsList.Add(new RecipientViewModel()
            {
                Phonenumber = "+380999999997",
                Birthdate   = DateTime.Now,
                Gender      = "Male",
                Name        = "Test",
                Surname     = "Test",
                Priority    = "Low"
            });
            mockMapper.Setup(m => m.Map <RecipientViewModel, Recipient>(It.IsAny <RecipientViewModel>()))
            .Returns(new Recipient()
            {
                PhoneId = 1, BirthDate = DateTime.Now, Name = "Test", Surname = "Test", Priority = "Low"
            });
            var result = manager.CreateWithRecipient(emptyCampaign, recepientsList);

            Assert.IsTrue(result);
        }
        private async Task <ManageViewModel> GetUserFunny(string nrid, string justification)
        {
            using (var client = new HttpClient())
            {
                var user = new ManageViewModel();

                try
                {
                    client.BaseAddress = new Uri("http://proxy/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var call = new BeContractCall
                    {
                        Id     = "GetFunnyContract",
                        ISName = $"Public Service/{nrid}",
                        Inputs = new Dictionary <string, dynamic>()
                        {
                            { "NRID", nrid },
                            { "Justification", justification }
                        }
                    };

                    var httpContent = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync("api/contract/call", httpContent);

                    if (response.IsSuccessStatusCode)
                    {
                        var resp = await response.Content.ReadAsAsync <Dictionary <int, BeContractReturn> >();

                        var outputs    = resp.Values.Select(ret => ret.Outputs).ToList();
                        var userValues = outputs.SelectMany(d => d)
                                         .ToDictionary(t => t.Key, t => t.Value);
                        user.ExtraInfo    = userValues["ExtraInfo"];
                        user.EmailAddress = userValues["Email"];
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                return(user);
            }
        }
        public IActionResult Delete(ManageViewModel vm)
        {
            bool   needsSave = false;
            string notifyMsg = string.Empty;

            if (vm.Destination.DestinationId > 0)
            {
                vm.Destination = data.Destinations.Get(vm.Destination.DestinationId);
                data.Destinations.Delete(vm.Destination);
                notifyMsg += $"{vm.Destination.Name}, ";
                needsSave  = true;

                if (vm.Accomodation.AccomodationId > 0)
                {
                    vm.Accomodation = data.Accomodations.Get(vm.Accomodation.AccomodationId);
                    data.Accomodations.Delete(vm.Accomodation);
                    notifyMsg += $"{vm.Accomodation.Name}, ";
                    needsSave  = true;
                }

                if (vm.Activity.ActivityId > 0)
                {
                    vm.Activity = data.Activities.Get(vm.Activity.ActivityId);
                    data.Activities.Delete(vm.Activity);
                    notifyMsg += $"{vm.Activity.Name}, ";
                    needsSave  = true;
                }

                if (needsSave)
                {
                    try
                    {
                        data.Save();
                        TempData["message"] = notifyMsg + "deleted";
                    }
                    catch
                    {
                        TempData["message"] = $"Unable to delete {vm.Destination.Name} because it is in a trip.";
                        LoadDropDownData(vm);
                        return(View("Index", vm));
                    }
                }
            }
            return(RedirectToAction("Confirm"));
        }
        public void CreateWithRecipient_CampignWithWrongRecipientMapping_FalseResult()
        {
            ManageViewModel emptyCampaign = new ManageViewModel()
            {
                PhoneId = 1, Name = "test", Description = "Test"
            };
            List <RecipientViewModel> recepientsList = new List <RecipientViewModel>();
            List <Phone> Phones = new List <Phone>();

            Phones.Add(
                new Phone()
            {
                Id          = 10,
                PhoneNumber = "+380999999999"
            });
            Phones.Add(
                new Phone()
            {
                Id          = 11,
                PhoneNumber = "+380999999998"
            });
            mockUnitOfWork.Setup(u => u.Phones.Get(It.IsAny <Expression <Func <Phone, bool> > >(), It.IsAny <Func <IQueryable <Phone>,
                                                                                                                   IOrderedQueryable <Phone> > >(), It.IsAny <string>())).Returns(new List <Phone>());
            mockUnitOfWork.Setup(u => u.Companies.Insert(It.IsAny <Company>()));
            mockUnitOfWork.Setup(u => u.Recipients.Insert(It.IsAny <Recipient>()));
            mockUnitOfWork.Setup(u => u.Phones.Insert(It.IsAny <Phone>()));
            mockMapper.Setup(m => m.Map <ManageViewModel, Company>(It.IsAny <ManageViewModel>()))
            .Returns(new Company()
            {
                PhoneId = 1, Name = "test", Message = "test", Description = "Test"
            });
            recepientsList.Add(new RecipientViewModel()
            {
                Phonenumber = "+380999999997",
                Birthdate   = DateTime.Now,
                Gender      = "Male",
                Name        = "Test",
                Surname     = "Test",
                Priority    = "Low"
            });

            var result = manager.CreateWithRecipient(emptyCampaign, recepientsList);

            Assert.IsFalse(result);
        }
        public void Insert_EmptyCampaign_FalseResult()
        {
            ManageViewModel           emptyCampaign  = new ManageViewModel();
            List <RecipientViewModel> recepientsList = new List <RecipientViewModel>();

            recepientsList.Add(new RecipientViewModel()
            {
                Phonenumber = "+380999999999",
                Birthdate   = DateTime.Now,
                Gender      = "Male",
                Name        = "Test",
                Surname     = "Test",
                Priority    = "Low"
            });
            var result = manager.CreateWithRecipient(emptyCampaign, recepientsList);

            Assert.IsFalse(result);
        }
Exemple #11
0
        public void DeleteFromManage_ContainsAcc_ContainsDest_ReturnsRedirectToAction()
        {
            var accessor   = TestHelperLibrary.SetUpHttpContextAccessor();
            var unitOfWork = TestHelperLibrary.SetupUnitOfWork();
            var tempData   = new TempDataDictionary(accessor.Object.HttpContext, Mock.Of <ITempDataProvider>());
            var controller = new VacationController(unitOfWork.Object, accessor.Object);

            controller.TempData = tempData;
            var viewmodel = new ManageViewModel {
                SelectedAccommodationToDelete = 1,
                SelectedActivityToDelete      = 0,
                SelectedDestinationToDelete   = 1
            };
            var result = controller.DeleteFromManage(viewmodel) as RedirectToActionResult;

            Assert.IsType <RedirectToActionResult>(result);
            Assert.Equal("Manage", result.ActionName);
        }
        /// <summary>
        ///     Setups the manage view model.
        /// </summary>
        /// <returns>ManageViewModel.</returns>
        private ManageViewModel setupManageViewModel()
        {
            var viewModel = new ManageViewModel {
                DestinationName               = (string)TempData["dest_name"] ?? "",
                AccommodationName             = (string)TempData["acc_name"] ?? "",
                AccommodationEmail            = (string)TempData["acc_email"] ?? "",
                AccommodationPhone            = (string)TempData["acc_phone"] ?? "",
                ActivityName                  = (string)TempData["act_name"] ?? "",
                Destinations                  = this.unitOfWork.Destinations.Get().ToList(),
                Accommodations                = this.unitOfWork.Accommodations.Get().ToList(),
                Activities                    = this.unitOfWork.Activities.Get().ToList(),
                SelectedAccommodationToDelete = 0,
                SelectedActivityToDelete      = 0,
                SelectedDestinationToDelete   = 0
            };

            return(viewModel);
        }
        public ActionResult Index(ManageMessageId?message)
        {
            string statusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
                : message == ManageMessageId.Error ? "An error has occurred."
                : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
                : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : string.Empty;

            var model = new ManageViewModel
            {
                StatusMessage = statusMessage
            };

            return(this.View(model));
        }
        // GET: Home
        public ActionResult Index()
        {
            ManageViewModel model = new ManageViewModel();

            model.Posts  = unitOfWork.PostRepository.GetPosts((Post p) => p.Published, null, 1, 3);
            model.Albums = unitOfWork.AlbumRepository.GetAlbums((Album a) => a.Published, null, false, 1, 4);

            foreach (var post in model.Posts)
            {
                var content = post.Description;
                int index   = content.IndexOf("<p>", content.IndexOf("<p>") + 1);
                if (index != -1)
                {
                    post.Description = content.Substring(0, index);
                }
            }

            return(View(model));
        }
        public ActionResult ManageProfile()
        {
            var userID = User.Identity.GetUserId();
            //ApplicationUser appUser = new ApplicationUser();
            //appUser = UserManager.FindByEmail(email);

            //UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
            //RoleManager<IdentityRole> RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
            //ApplicationUser appUser = new ApplicationUser();
            //appUser = UserManager.FindById(userID);

            var myrole = new Class1();
            //ViewBag.currentrole = myrole.a(userID);

            var currentrole = myrole.a(userID);
            //if (userID != null)
            //         {
            //             var rolesForUser = UserManager.FindById(userID).Roles;
            //             foreach (var item in rolesForUser)
            //             {
            //                 IdentityRole role = RoleManager.FindById(item.RoleId);
            //                 currentrole = role.Name;
            //             }
            //         }
            var user  = (from R in context.Users where R.Id == userID select R).FirstOrDefault();
            var model = new ManageViewModel
            {
                Id            = userID,
                usern         = user.usern.ToString(),
                Email         = user.Email.ToString(),
                UserName      = user.usern.ToString(),
                currrole      = currentrole.ToString(),
                Previoususern = user.usern.ToString(),
                PreviousEmail = user.Email.ToString(),
                oldusern      = user.usern.ToString()
            };

            //var user = UserManager.FindById(userID);
            //var name = user.usern.ToString();
            //var em = user.Email.ToString();
            //var p=Encoding.Unicode.GetString(decrypted);
            return(View(model));
        }
Exemple #16
0
        public async Task <IActionResult> Manage(ManageViewModel vm)
        {
            var user = await _userManager.FindByIdAsync(vm.UserId);

            if (user == null)
            {
                return(StatusCode(500, "No user with this id"));
            }
            else
            {
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, vm.Password);

                await _userManager.SetLockoutEnabledAsync(user, vm.Blocked);
            }

            return(Ok());
        }
        public ActionResult Manage(int?id)
        {
            if (id.HasValue && id.Value < 1)
            {
                return(this.HttpNotFound());
            }

            ManageViewModel model = new ManageViewModel();

            model.Category = id.HasValue && id > 0
                                                 ? this.categoryService.GetCategoryById(id.Value).MapTo <CategoryBinder>()
                                                 : CategoryBinder.EmptyInstance();

            model.Categories = id.HasValue
                                                   ? this.categoryService.GetCategories().Where(x => x.Id != id.Value)
                                                   : this.categoryService.GetCategories();

            return(this.View(model));
        }
Exemple #18
0
        public async Task <ActionResult> Index(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.ChangePasswordSuccess ? "Zmieniono hasło."
                : message == ManageMessageId.Error ? "Wystąpił błąd."
                : message == ManageMessageId.ChangeUserDataSuccess ? "Dane użytkownika zmieniono pomyślnie."
                : "";

            var userId = User.Identity.GetUserId();
            var user   = await UserManager.FindByIdAsync(userId);

            var model = new ManageViewModel
            {
                Message  = message,
                UserData = user.UserData
            };

            return(View(model));
        }
        public async Task<IActionResult> Manage(ManageViewModel model)
        {
            if (!ModelState.IsValid)
                return View();

            var user = await _userManager.GetUserAsync(HttpContext.User);

            string phoneToken = null;
            if (!string.IsNullOrWhiteSpace(user.PhoneNumber) && user.PhoneNumber != model.PhoneNumber)
            {
                user.PhoneNumberConfirmed = false;
                user.PhoneNumber = model.PhoneNumber;
                phoneToken = await _userManager.GenerateChangePhoneNumberTokenAsync(user, user.PhoneNumber);
                _smsService.SendSms($"Witaj, przesyłamy token do potwierdzenia numeru telefonu w aplikacji EventsReminder: {phoneToken}", user.PhoneNumber);
            }

            if (!string.IsNullOrEmpty(model.Password))
                user.PasswordHash = _userManager.PasswordHasher.HashPassword(user, model.Password);

            var result = await _userManager.UpdateAsync(user);

            if (result.Succeeded)
            {
                if (string.IsNullOrEmpty(phoneToken))
                {
                    return RedirectToAction(nameof(HomeController.Index), "Home");
                }
                else
                {
                    return RedirectToAction(nameof(this.ConfirmPhoneNumber), "Account");
                }
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }
            }
        
            return View(model);
        }
        public async Task <ActionResult> Index(string databaseApiKey = "")
        {
            var connect    = GetConnection(databaseApiKey);
            var tables     = new List <TableViewModel>();
            var procedures = new List <TableViewModel>();

            tables.AddRange(await GetTables("TABLE", connect.AccountApiKey, connect.DatabaseApiKey));
            tables.AddRange(await GetTables("VIEW", connect.AccountApiKey, connect.DatabaseApiKey));
            procedures.AddRange(await GetApiProcs(connect.AccountApiKey, connect.DatabaseApiKey));
            var model = new ManageViewModel
            {
                ApiUrl         = connect.ApiUrl,
                AccountApiKey  = connect.AccountApiKey,
                DatabaseApiKey = connect.DatabaseApiKey,
                Tables         = tables,
                Procedures     = procedures
            };

            return(View(model));
        }
Exemple #21
0
        public void AddFromManage_SuccessfulAddAccommodation_WithOnlyName_Returns_RedirectToActionResult()
        {
            var accessor   = TestHelperLibrary.SetUpHttpContextAccessor();
            var unitOfWork = TestHelperLibrary.SetupUnitOfWork();
            var tempData   = new TempDataDictionary(accessor.Object.HttpContext, Mock.Of <ITempDataProvider>());
            var controller = new VacationController(unitOfWork.Object, accessor.Object);

            controller.TempData = tempData;
            var viewmodel = new ManageViewModel {
                DestinationName    = "",
                AccommodationName  = "testacc",
                AccommodationEmail = "",
                AccommodationPhone = "",
                ActivityName       = ""
            };
            var result = controller.AddFromManage(viewmodel) as RedirectToActionResult;

            Assert.IsType <RedirectToActionResult>(result);
            Assert.Equal("Home", result.ActionName);
        }
        public async Task <IActionResult> Index()
        {
            try
            {
                var user = await _userManager.GetUserAsync(User);

                if (user == null)
                {
                    throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
                }

                var model = new ManageViewModel(user, StatusMessage);

                return(View(model));
            }
            catch
            {
                return(View("PageNotFound"));
            }
        }
        public ActionResult Index()
        {
            using (var dbContext = new MazzaDbContext())
            {
                var    userId         = User.Identity.GetUserId <int>();
                var    UserGA         = dbContext.GoogleAuths.FirstOrDefault(g => g.UserId == userId);
                string qrCodeImageUrl = string.Empty;
                string manualEntryKey = string.Empty;
                if (UserGA == null)
                {
                    var setupInfo = tfa.GenerateSetupCode(General.OMPTitle, dbContext.Users.FirstOrDefault(u => u.Id == userId).Email, "SuperSecretKeyGoesHere", 200, 200, true);

                    qrCodeImageUrl = setupInfo.QrCodeSetupImageUrl;
                    manualEntryKey = setupInfo.ManualEntryKey;
                    dbContext.GoogleAuths.Add(new GoogleAuthentication
                    {
                        UserId           = userId,
                        QrCodeUrl        = qrCodeImageUrl,
                        ManualEntryKey   = manualEntryKey,
                        AccountSecretKey = "SuperSecretKeyGoesHere",
                        IsActive         = false,
                        CreatedOn        = DateTime.UtcNow
                    });
                    dbContext.SaveChanges();
                }
                else
                {
                    qrCodeImageUrl = UserGA.QrCodeUrl;
                    manualEntryKey = UserGA.ManualEntryKey;
                }
                ManageViewModel model = new ManageViewModel
                {
                    Users          = dbContext.Users.ToList(),
                    QrCodeImageUrl = qrCodeImageUrl,
                    ManualEntryKey = manualEntryKey,
                    IsActive       = UserGA != null ? UserGA.IsActive : false
                };

                return(View(model));
            }
        }
Exemple #24
0
        public async Task <ActionResult> ChangePassword(ManageViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", new { Message = ManageMessageId.ValidationError }));
            }
            var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.ChangePasswordViewModel.OldPassword, model.ChangePasswordViewModel.NewPassword);

            if (result.Succeeded)
            {
                var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

                if (user != null)
                {
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);
                }
                return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }));
            }
            AddErrors(result);
            return(RedirectToAction("Index", new { Message = ManageMessageId.Error }));
        }
        public void GetDetails_ExistingId_ReturnManageViewModel()
        {
            ManageViewModel item = new ManageViewModel()
            {
                Id = 1, Name = "Test", Description = "Test", Type = CompanyType.Send, ApplicationGroupId = 2
            };

            mockUnitOfWork.Setup(u => u.Companies.GetById(1))
            .Returns(new Company()
            {
                Id = 1, Name = "Test", Description = "Test", Type = CompanyType.Send, ApplicationGroupId = 2, IsPaused = false
            });
            mockMapper.Setup(m => m.Map <ManageViewModel, Company>(item))
            .Returns(new Company()
            {
                Id = 1, Name = "Test", Description = "Test", Type = CompanyType.Send, ApplicationGroupId = 2, IsPaused = false
            });
            var result = manager.GetDetails(1);

            Assert.That(result, Is.EqualTo(result));
        }
Exemple #26
0
        public ActionResult EditBook(ManageViewModel m)
        {
            var a = db.Пользователь_Книга.ToList().Find(o => o.Пользователь == User.Identity.Name && o.Код_книги == m.Код_книги);

            if (ModelState.IsValid)
            {
                if (m.ейтинг == "-")
                {
                    a.ейтинг = null;
                }
                else
                {
                    a.ейтинг = short.Parse(m.ейтинг);
                }

                a.Статус          = m.Статус;
                db.Entry(a).State = EntityState.Modified;
                db.SaveChanges();
            }
            return(RedirectToAction("Index"));
        }
        public ActionResult Index()
        {
            int userId = CurrentUser.UserId;
            var user   = repository.Set <Darbuotojas>().Find(userId);
            var model  = new ManageViewModel();

            if (user != null)
            {
                model = new ManageViewModel
                {
                    Email   = user.el_pastas,
                    Name    = user.vardas,
                    Surname = user.pavarde,
                };
            }
            else
            {
                throw new Exception("No user");
            }
            return(View(model));
        }
        public async Task <IActionResult> Index()
        {
            var user = await GetCurrentUserAsync();

            if (user == null)
            {
                _logger.LogError("Failed to get user to manage account.");

                return(View("Error"));
            }

            var userLogins = (await _userManager.GetLoginsAsync(user))
                             .OrderBy((p) => p.ProviderDisplayName)
                             .ThenBy((p) => p.LoginProvider)
                             .ToList();

            var otherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                              .Where((p) => userLogins.All((r) => p.Name != r.LoginProvider))
                              .OrderBy((p) => p.DisplayName)
                              .ThenBy((p) => p.Name)
                              .ToList();

            foreach (var login in userLogins)
            {
                if (string.IsNullOrWhiteSpace(login.ProviderDisplayName))
                {
                    login.ProviderDisplayName = login.LoginProvider;
                }
            }

            var model = new ManageViewModel()
            {
                CurrentLogins   = userLogins,
                ETag            = user.ETag,
                IsLinkedToAlexa = !string.IsNullOrWhiteSpace(user.AlexaToken),
                OtherLogins     = otherLogins,
            };

            return(View(model));
        }
Exemple #29
0
        public async Task <IActionResult> ChangePassword(ManageViewModel input)
        {
            var account = await _userManager.GetUserAsync(User);

            var user = _pulseContext.User.Where(u => u.AccountId == account.Id).ToList()[0];

            ManageViewModel model = new ManageViewModel
            {
                Email       = account.Email,
                UserName    = account.UserName,
                Name        = user.Name,
                PhoneNumber = account.PhoneNumber,
                Location    = user.Location
            };

            if (ModelState.IsValid)
            {
                var passwordResult = await _userManager.ChangePasswordAsync(account, input.Password, input.NewPassword);

                if (!passwordResult.Succeeded)
                {
                    foreach (var error in passwordResult.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                    return(View());
                }

                var result = await _userManager.UpdateAsync(account);

                if (result.Succeeded)
                {
                    await _pulseContext.SaveChangesAsync();

                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(View("Views/AccountManagement/Manage.cshtml", model));
        }
Exemple #30
0
        //
        // Manage
        public ActionResult Manage(string currentFilter, string searchString, int?page, bool?oldInventoryIsShown)
        {
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            var inventory = _bookService.GetBooksIncludingDisabled();

            oldInventoryIsShown = oldInventoryIsShown ?? false;
            if (oldInventoryIsShown == false)
            {
                inventory = inventory.Where(b => !b.IsArchived);
            }

            if (!String.IsNullOrEmpty(searchString))
            {
                inventory = inventory.Where(book => book.Author.ToLower().Contains(searchString.ToLower()) ||
                                            book.Title.ToLower().Contains(searchString.ToLower()));
            }

            int pageSize   = 3;
            int pageNumber = page ?? 1;

            var model = new ManageViewModel
            {
                Inventory           = inventory.OrderBy(book => book.Author).ToPagedList(pageNumber, pageSize),
                SearchString        = searchString,
                OldInventoryIsShown = (bool)oldInventoryIsShown
            };

            return(View(model));
        }
        /// <summary>
        /// GET: Admin/Manage
        /// Index for Edit onTrax
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Index()
        {
            // We will pass through an instance of ManageViewModel

            var model = new ManageViewModel();

            // Create an instance of the Data utility
            var Data = new Data();


            // Fill ManageViewModel using the appropriate Data utiltiy

            model.Employees = Data.GetActiveEmployees();
            model.Products  = Data.GetActiveProducts();
            model.Processes = Data.GetActiveProcesses();
            model.Issues    = Data.GetActiveIssues();
            model.Batches   = Data.GetActiveBatches();


            // Return model to view
            return(View(model));
        }
        public async Task<ActionResult> Index(ManageViewModel model, HttpPostedFileBase upload)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
            if (user != null)
            {
                user.UserName = model.UserName;
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.TrainerName = model.TrainerName;
                user.Email = model.Email;
                user.Sex = model.Sex;
                user.BirthDate = model.BirthDate;

                if (upload != null && upload.ContentLength > 0)
                {
                    user.ImageMimeType = upload.ContentType;
                    user.ImageData = new byte[upload.ContentLength];
                    upload.InputStream.Read(user.ImageData, 0, upload.ContentLength);
                    //using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    //{
                    //    model.ImageData = reader.ReadBytes(upload.ContentLength);
                    //}
                    //context.SaveChanges();
                }

                var result = await UserManager.UpdateAsync(user);
                if (!result.Succeeded)
                {
                    AddErrors(result);
                }
            }
            return View(model);
        }
        // GET: /Manage/Index
        public ActionResult Index()
        {
            ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
            if (user != null)
            {
                var model = new ManageViewModel
                {
                    UserName = user.UserName,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    TrainerName = user.TrainerName,
                    Email = user.Email,
                    Sex = user.Sex,
                    BirthDate = user.BirthDate,

                    HasPassword = HasPassword(),
                };
                return View(model);
            }
            else
            {
                return View();
            }
        }
 public ResourceResult Post(EditUrl url, ManageViewModel input)
 {
     var gig = gigStorer.Save(input.AsGig());
     input.Id = gig.Id;
     return OK(input).AsHtml();
 }
 public ResourceResult Post(AddUrl url, ManageViewModel input)
 {
     gigStorer.Save(input.AsGig());
     return SeeOther(new ListUrl()).AsHtml();
 }