Example #1
1
      public async Task<ActionResult> Index()
      {
         if (this.User.Identity.IsAuthenticated)
         {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

            var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

            IQueryable<Game> games = from membership in db.GameMemberships
                                     where membership.ApplicationUserID == appUser.Id
                                     join game in db.Games on membership.GameID equals game.ID
                                     select game;

            var adminRole = await db.Roles.FirstOrDefaultAsync(role => role.Name == "Admin");

            this.ViewBag.Games = await games.ToListAsync();

            this.ViewBag.Claims = await manager.GetClaimsAsync(appUser.Id);
            this.ViewBag.Roles = await manager.GetRolesAsync(appUser.Id);
         }

         return View();
      }
Example #2
0
      public async Task<ActionResult> Create([Bind(Include = "ID,Name,Visibility")] Game game)
      {
         if (ModelState.IsValid)
         {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

            var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

            db.Games.Add(game);

            await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
            await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

            var membership = new GameMembership()
            {
               Game = game,
               ApplicationUser = appUser,
               Roles = "Owner",
            };
            db.GameMemberships.Add(membership);
            await db.SaveChangesAsync();

            return RedirectToAction("Index");
         }

         return View(game);
      }
 public ActionResult Index()
 {
     if (User.Identity.IsAuthenticated)
     {
         var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
         ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
         if (UserManager.IsInRole(user.Id, "Admin"))
         {
             return RedirectToAction("Index", "Admins");
         }
         else if (UserManager.IsInRole(user.Id, "Profesor"))
         {
             return RedirectToAction("Index", "Profesors");
         }
         else if (UserManager.IsInRole(user.Id, "Referada"))
         {
             return RedirectToAction("Index", "Referadas");
         }
         else if (UserManager.IsInRole(user.Id, "Dekan"))
         {
             return RedirectToAction("Index", "Dekans");
         }
         else if (UserManager.IsInRole(user.Id, "Procelnik"))
         {
             return RedirectToAction("Index", "Procelniks");
         }
     }
     return View();
 }
        public async Task<JsonData> ChangePassword(ChangePasswordModel changePass)
        {
            try
            {
                var db = new DataContext();
                var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
                userMan.UserValidator = new UserValidator<MyUser>(userMan)
                {
                    AllowOnlyAlphanumericUserNames =
                        false
                };

                var user = await userMan.FindByIdAsync(User.Identity.GetUserId());
                if (user == null) throw new Exception("please check your old password");

                var newPassword = changePass.NewPassword;
                var result = await userMan.RemovePasswordAsync(user.Id);
                if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
                var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
                if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
                return DataHelpers.ReturnJsonData(null, true, "Password changed successful");
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        protected async override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var query = request.RequestUri.ParseQueryString();

            if (query.AllKeys.Any(x => x == "token"))
            {
                var jwt = ((JwtSecurityToken)new JwtSecurityTokenHandler().ReadToken(query.GetValues("token")[0]));

                var userId = jwt.Claims.FirstOrDefault(x => x.Type.Equals("nameid")).Value;

                if (userId != null)
                    using (var context = DatabaseContext.Create())
                    using (var userManager = new UserManager(new UserStore<User>(context)))
                    {
                        User currentUser = null;

                        if ((currentUser = await userManager.FindByIdAsync(userId)) != null)
                        {
                            var identity = await currentUser.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

                            var principal = new GenericPrincipal(identity, (await userManager.GetRolesAsync(currentUser.Id)).ToArray());

                            Thread.CurrentPrincipal = principal;
                            HttpContext.Current.User = principal;
                        }
                    }
            }

            return await base.SendAsync(request, cancellationToken);
        }
        public async Task<MyUser> GetUser(string userId)
        {
            var db = new DataContext();
            var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
            
            var currentUser = await userMan.FindByIdAsync(userId);

            return currentUser;
        }
        //
        // GET: /Users/
        public async Task<ActionResult> Index()
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(db);

            var userManager = new UserManager<ApplicationUser>(userStore);
            var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
            ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
            return View(user);
        }
        public ActionResult Profile()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(ApplicationDbContext.Create()));

            var currentUser = manager.FindByIdAsync(User.Identity.GetUserId<string>()).Result;

            ViewBag.HomeTown = currentUser.HomeTown;
            ViewBag.FirstName = currentUser.UserInfo.FirstName;

            return View();
        }
Example #9
0
        public static string Email(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
        {
            if (user.Identity.IsAuthenticated)
            {
                var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;

                return appUser.Email;
            }

            return string.Empty;
        }
Example #10
0
        public static string PhoneNumber(this ClaimsPrincipal user, UserManager<ApplicationUser> userManager)
        {
            if (user.Identity.IsAuthenticated)
            {
                var appUser = userManager.FindByIdAsync(user.Identity.GetUserId()).Result;

                return appUser.PhoneNumber;
            }

            return "";
        }
      public async Task<GameResult> Create([FromBody]GameResult result)
      {
         if (result == null)
         {
            throw new ArgumentNullException("game");
         }

         GameVisibility visibility;
         if (!Enum.TryParse(result.Visibility, out visibility))
         {
            throw new ArgumentException("game.Visibility is not valid");
         }

         var game = new Game()
         {
            Name = result.Name,
            Visibility = visibility,
         };

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         db.Games.Add(game);

         await manager.AddClaimAsync(appUser.Id, new Claim("GameMembership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameOwnership", game.ID.ToString()));
         await manager.AddClaimAsync(appUser.Id, new Claim("GameMaster", game.ID.ToString()));

         var membership = new GameMembership()
         {
            Game = game,
            ApplicationUser = appUser,
            Roles = "Owner",
         };
         db.GameMemberships.Add(membership);
         await db.SaveChangesAsync();


         result.GameId = game.ID;

         return result;
      }
        // GET: Profile
        public async Task<ActionResult> Index(ManageController.ManageMessageId? message)
        {
            ViewBag.StatusMessage =
                message == ManageController.ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
                : message == ManageController.ManageMessageId.SetPasswordSuccess ? "Your password has been set."
                : message == ManageController.ManageMessageId.SetTwoFactorSuccess ? "Your two factor provider has been set."
                : message == ManageController.ManageMessageId.Error ? "An error has occurred."
                : message == ManageController.ManageMessageId.AddPhoneSuccess ? "The phone number was added."
                : message == ManageController.ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
                : "";

            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());

            var model = new IndexViewModel
            {
                HasPassword = HasPassword(),
                PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()),
                TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()),
                Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()),
                BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()),


                FirstName = currentUser.UserProfile.FirstName,
                LastName = currentUser.UserProfile.LastName,
                Email = currentUser.UserProfile.Email,
                Address1 = currentUser.UserProfile.Address1,
                City = currentUser.UserProfile.City,
                ProvState = currentUser.UserProfile.ProvState,
                PostZipCode = currentUser.UserProfile.PostZipCode,
                Country = currentUser.UserProfile.Country,
                Telephone = currentUser.UserProfile.Telephone,
                AvatarImgUrl = currentUser.UserProfile.AvatarImgUrl,

            };

            ViewBag.UserId = User.Identity.GetUserId();

            return View(model);
        }
        public async Task<ActionResult> Me()
        {
            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var user = await userManager.FindByIdAsync(User.Identity.GetUserId());

                await ctx.Entry(user).Collection(u => u.Licenses).LoadAsync();

                var license = user.Licenses.FirstOrDefault(l => l.Season == 2014);
                return Json(new
                {
                    found = user != null,
                    lastName = user != null ? user.LastName : "",
                    firstName = user != null ? user.FirstName : "",
                    license = license!=null? license.Number : "",
                    userId = user!=null ? user.Id : ""
                },
                JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// Initializes the user.
        /// </summary>
        public void InitializeUser(SessionAuthUser authUser)
        {
            AuthUser = authUser;
              if ((AuthUser == null) || (AuthUser.SystemUserID == 0))
              {
            var store = new UserStore<ApplicationUser>(new AuthenticationDbContext());
            var userManager = new UserManager<ApplicationUser>(store);
            ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
            if (user == null)
              return;

            string nickname = user.UserName;
            if (nickname.Contains(" "))
              nickname = user.UserName.Substring(0, user.UserName.IndexOf(" "));

            if (nickname.Length > 30)
              nickname = nickname.Substring(0, 30);

            using (AuthManager authManager = PublicConfigurationSettings.GetAuthManager.Invoke())
            {
              authManager.RegisterUser(User.Identity.GetUserId(), nickname,
            user.UserName, user.PhoneNumber, user.Email);
              AuthUser = authManager.GetAuthUser(User.Identity.GetUserId());
            }
              }

              ViewBag.AuthUser = AuthUser;
              bool hasClient = PublicLogicManager.Client.CurrentUserHasClient();
              ViewBag.HasClient = hasClient;
              ViewBag.UserNickname = AuthUser.Nickname;
              if (hasClient)
              {
            ClientData client = PublicLogicManager.Client.LoadClientModel(false);
            ViewBag.ClientName = client.CompanyName;
            ViewBag.Client = client;

            ViewBag.Build = BuildNumber;
              }

              PerformClientLogic();
        }
Example #15
0
		public async Task EnsureDatabaseAsync()
		{
			await MigrateDatabaseAsync(ServiceProvider);
			_userManager = ServiceProvider.GetService<UserManager<ApplicationUser>>();
			var roleManager = ServiceProvider.GetService<RoleManager<IdentityRole>>();
			await EnsureUsersAsync(false);
			Context = ServiceProvider.GetRequiredService<ApplicationDbContext>();
			//var userStore = new UserStore<ApplicationUser>(context);
			////var roleManager = new RoleManager<IdentityRole>();
			//var userManager = new UserManager<ApplicationUser>(
			//	, );
			EnsureDatabaseExists();
			Context.Database.EnsureCreated();
			// Add Mvc.Client to the known applications.
			_productsCrud = new CrudBase<Product, int>(
				Context, Context.Products, p => p.ProductId);
			_ordersCrud = new CrudBase<Order, int>(
				Context, Context.Orders, p => p.Id);
			var customersCrud = new CrudBase<Customer, int>(
				Context, Context.Customers, p => p.CustomerId);

			//Action<string, double, int?, DateTime?, string> prod = (name, price, customerId, dateCreated, cratedByUserId) =>
			//{
			//	productId = Prod(productsCrud, productId, name, price, customerId, dateCreated, cratedByUserId);
			//};
			Action<string, string, string> cust = (guid, firstName, lastName) =>
			{
				customersCrud.EnsureEntity(
					guid, customer =>
					{
						customer.FirstName = firstName;
						customer.LastName = lastName;
					});
			};

			cust("6c13ec25-b9cf-4c99-87e7-13a45a034342", "Harry", "Whitburn");
			cust("0e941f32-8ae1-4eae-875a-f748bae3ce2a", "Nick", "Lawden");
			cust("134bd420-f64a-40db-bbe4-0b9a9ff3eb01", "Emil", "Roijer");
			Context.SaveChanges();
			Prod("00d5c0b0-738d-41ff-86d4-dca84da1d4d5", "Apple number1", 10, null, null);
			Prod("cd4c554d-3ca2-49aa-9286-08abacba3fa0", "Apple number1", 10, 1, null, "1");
			Prod("d100c753-3335-439c-88db-b8d9b6c09cc8", "Orange number1", 20, null, null);
			Prod("da93b8a4-4378-4ce0-918e-653f1bd4acaf", "Peanut butter number1", 25, 2, null);
			Prod("fe208521-4a77-4b09-94c2-2f08a4dd8872", "xApple number2", 10, 1, null);
			Prod("844fbc16-3d77-4421-9498-aa65300bc789", "xOrange number2", 20, 2, null);
			Prod("78509968-0073-4c57-8774-ec0d58ea7ff3", "xPeanut butter number2", 25, 2, null);
			Prod("18b8c4e7-48a2-40c7-bea8-1d1879bf852e", "xApple number2", 10, 1, null);
			Prod("e5ab744c-441c-447b-ae92-055b1bce5541", "xOrange number2", 20, 2, null);
			Prod("3a5476b1-7dd8-40b0-a6ce-b6bd3127da6f", "xPeanut butter number2", 25, 2, null);
			Prod("633a125c-1fe2-4f06-859d-a8d8fd52eb11", "xApple number2", 10, 1, null);
			Prod("27eea6ff-c4aa-44a0-84fe-32b0e13beec4", "xOrange number2", 20, 2, null);
			Prod("dcdc6836-3b44-41c5-8ade-792e39ce2112", "xPeanut butter number2", 25, 2, null);
			Prod("fdc3139d-8585-4b34-b815-13598bf55791", "xApple number2", 10, 1, null);
			Prod("46b058b2-dd55-4741-9ee0-99c63c4bd94a", "xOrange number2", 20, 2, null);
			Prod("11c0e3e5-c5d7-4ff5-ba6c-a54b77f91d1b", "xPeanut butter number2", 25, 2, null);
			Prod("796b6b1d-2d6d-413c-bcab-2659c0fdf02f", "Apple number3", 10, 1, null);
			Prod("5f928f2f-bc1b-4e73-a0d8-20c36f817342", "Orange number3", 20, 2, null);
			Prod("f4fa623d-f412-4b68-8a26-17cfa16cb0a0", "Peanut butter number3", 25, 2, null);
			Prod("8f81d6ab-4c8f-4800-aea0-3cb1ca116fc6", "Apple number4", 10, 1, null);
			Prod("f2b8032f-c8ac-406f-8038-939201771901", "Orange number4", 20, 2, null);
			Prod("dc872dbf-956c-43aa-aba4-e75395af7d83", "Peanut butter number4", 25, 2, null);
			Prod("4ca16ce0-1466-4ba6-a69b-5465ed0a4b1d", "Apple number5", 10, 1, null);
			Prod("66cc487b-2eb1-470b-98c8-03ee913d860e", "Orange number5", 20, 2, null);
			Prod("e77e6589-1dba-4c8b-97b1-1564056ddf10", "Peanut butter number5", 25, 2, null);
			Prod("183946f3-41a9-4140-a1cb-b328e3a778d1", "Apple number6", 10, 1, null);
			Prod("2995edec-ec1b-42ed-aa97-1e68a9ef765c", "Orange number6", 20, 2, null);
			Prod("a78204ae-169a-4d30-936b-034cda5abd0f", "Peanut butter number6", 25, 2, null);
			Context.SaveChanges();
			Order("31d57282-4824-4441-9bd0-49588b952728", "First order", 1);
			Order("fc41cc01-6dc3-4ca5-88a4-c4a463cd6316", "Second order", 1);
			Order("f1379562-c779-43bc-a507-71a8506ca8c9", "Third order", 1);
			Context.SaveChanges();
			await EnsureUsersAsync(true);
			await roleManager.CreateAsync(new IdentityRole("Admin"));
			await roleManager.CreateAsync(new IdentityRole("User"));
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "Admin");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("1"), "User");
			await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync("2"), "User");
		}
Example #16
0
        public async Task<ActionResult> DeleteConfirmed(string id) {

            var roleStore = new RoleStore<IdentityRole>(db);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            var userStore = new UserStore<ApplicationUser>(db);
            var userManager = new UserManager<ApplicationUser>(userStore);

            if (ModelState.IsValid) {
                if (id == null) {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }

                var user = await userManager.FindByIdAsync(id);
                
                // ev. 3parts inloggningar
                var logins = user.Logins;
                foreach (var login in logins.ToList()) {
                    await userManager.RemoveLoginAsync(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                }

                var rolesForUser = await userManager.GetRolesAsync(id);

                if (rolesForUser.Count() > 0) {
                    foreach (var item in rolesForUser.ToList()) {
                        // item should be the name of the role
                        var result = await userManager.RemoveFromRoleAsync(user.Id, item);
                    }
                }

                if (user.Documents.Count() > 0) {
                    foreach (var doc in user.Documents.ToList()) {
                        db.Documents.Remove(doc);
                    }
                }

                await userManager.DeleteAsync(user);

                return RedirectToAction("Index");
            }
            else {
                return View();
            }
        }
        //
        // GET: /Users/Details/5
        public async Task<ActionResult> Details(string id)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(db);
            var roleStore = new RoleStore<ApplicationRole>(db);

            var userManager = new UserManager<ApplicationUser>(userStore);
            var roleManager = new RoleManager<ApplicationRole>(roleStore);
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = await userManager.FindByIdAsync(id);

            ViewBag.RoleNames = await userManager.GetRolesAsync(user.Id);

            return View(user);
        }
 private ApplicationUser currentUser()
 {
     var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;
     return user;
 }
        public async Task<ActionResult> RegisterFinish(OrderViewModel modelObj, string slug)
        {
            if (modelObj == null) modelObj = new OrderViewModel();

            TryUpdateModel(modelObj);

            using (var ctx = new SportDataContext())
            {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                var team = SearchService.FindTeam(modelObj.Entrant, ctx);
                if (team == null)                
                    team = modelObj.CreateTeam();

                var driver1 = await SearchService.FindUser(modelObj.Driver1License, ctx) ?? await SearchService.FindUserById(modelObj.Driver1Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver1FirstName, modelObj.Driver1LastName, ctx);
                var driver2 = await SearchService.FindUser(modelObj.Driver2License, ctx) ?? await SearchService.FindUserById(modelObj.Driver2Id, ctx) ?? await SearchService.FindUserName(modelObj.Driver2FirstName, modelObj.Driver2LastName, ctx);

                //Защита от
                if (driver1==null || string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + "")) {
                    driver1 = modelObj.CreateDriver1();
                    var existingUser = await userManager.FindByNameAsync(driver1.UserName);
                    if (existingUser != null)
                        driver1.UserName = Guid.NewGuid().ToString();
                }
                if (driver2 == null || string.IsNullOrWhiteSpace(driver2.LastName + driver2.FirstName + ""))
                {
                    driver2 = modelObj.CreateDriver2();
                    var existingUser = await userManager.FindByNameAsync(driver2.UserName);
                    if (existingUser != null)
                        driver2.UserName = Guid.NewGuid().ToString();
                }

                var car = modelObj.CreateCar();

                var ev = await EventService.GetEvent(slug, ctx);

                Dictionary<SubEvent, Order> orders = new Dictionary<SubEvent,Order>();
                ViewBag.Error = null;
                if (driver1.Id == driver2.Id)
                {
                    ViewBag.Error = "В вашей заявке совпадают первый и второй водитель. Пожалуйста, проверьте правильность заполнения заявки. Если у вас в настоящее время нет полной информации о составе экипажа - оставьте недостающие поля пустыми.";                    
                }
                if (string.IsNullOrWhiteSpace(driver1.LastName + driver1.FirstName + driver2.LastName + driver2.FirstName))
                {
                    ViewBag.Error = "Укажите пожалуйста в заявке не менее 1 водителя.";                    
                }
                if (modelObj.Groups == null || modelObj.Groups.Count() == 0)
                {
                    ViewBag.Error = "В вашей заявке на " + ev.Title + " не указано ни одной зачетной группы. Пожалуйста, укажите минимум 1 зачет из списка.";                    
                }
                if(!string.IsNullOrWhiteSpace(ViewBag.Error))
                    return View("RegistrationError", ev);

                foreach (var group in modelObj.Groups)
                {
                    var tokens = group.Split('_');
                    var subEv = ev.SubEvents.First(e=>e.Id == int.Parse(tokens[0]));

                    if(!orders.ContainsKey(subEv)) {
                        orders.Add(subEv, new Order() {
                            Driver = driver1,
                            CoDriver = driver2,
                            Team = team,
                            Car = car,
                            Redimmed = false,
                            Confirmed = false,
                            CreatedAt= DateTime.Now,
                            StartNumber="",
                            Group = new List<Group>(),
                            CreatedBy = currentUser
                        });
                    }

                    orders[subEv].Group.Add(subEv.Groups.First(g => g.Id == int.Parse(tokens[1])));
                }

                foreach (var item in orders.Keys)
                {

                    item.Tag.Orders = item.Tag.Orders ?? new List<Order>();
                    item.Tag.Orders.Add(orders[item]);
                }
                try
                {
                    await ctx.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw;
                }

                return View("RegistrationComplete", ev);
            }
        }
        public async Task<ActionResult> AccreditationFinish(Accreditation model, string slug)
        {
            using(var ctx = new SportDataContext()) {
                var userManager = new UserManager<User>(new UserStore<User>(ctx));
                var currentUser = await userManager.FindByIdAsync(User.Identity.GetUserId());

                model.User = currentUser;
                var ev = await EventService.GetEvent(slug, ctx); 

                var tag = ev.SubEvents.Select(s => s.Tag).First();                
                model.Tag = tag;

                tag.Accreditations.Add(model);
                await ctx.SaveChangesAsync();

                ViewBag.Slug = slug;
                ViewBag.EventName = ev.Title;

                EmailService.SendAdministrativeMail("Поступила заявка на аккредитацию на " + ev.Title,
                    @"Поступила заявка на аккредитацию на " + ev.Title + " от " + model.User.LastName + " " + model.User.FirstName + ". Пожалуйста перейдите по ссылке http://www.afspb.org.ru/controlpanel/accreditations/validate/" + model.Id + " для обработки заявки."); 

                return View();
            }
        }
        //Receive Ajax call
        //public ActionResult GetMerchantDetails(string id)
        //{
        //    //Get current user
        //    //var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

        //    var profileId = UserManager.FindById(id).UserProfile.Id;

        //    //var currentUser = UserManager.FindById(User.Identity.GetUserId());

        //    var merchant = _merchantServie.FindSupplierBy(profileId);
            

        //    return PartialView("_MerchantDetails", merchant);
        //}


        //public ActionResult GetMerchantEdit(string id)
        //{
        //    var profileId = UserManager.FindById(id).UserProfile.Id;

        //    //var currentUser = UserManager.FindById(User.Identity.GetUserId());

        //    var merchant = _merchantServie.FindSupplierBy(profileId);


        //    return PartialView("_MerchantEdit", merchant);
        //}


        //Ajax call to get full name
        public async Task<ActionResult> GetFullName()
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

            var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());

            var model = new IndexViewModel
            {
                //HasPassword = HasPassword(),
                //PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId()),
                //TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId()),
                //Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()),
                //BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(User.Identity.GetUserId()),


                FirstName = currentUser.UserProfile.FirstName,
                LastName = currentUser.UserProfile.LastName,
                //Email = currentUser.UserProfile.Email,
                //Address1 = currentUser.UserProfile.Address1,
                //City = currentUser.UserProfile.City,
                //ProvState = currentUser.UserProfile.ProvState,
                //PostZipCode = currentUser.UserProfile.PostZipCode,
                //Country = currentUser.UserProfile.Country,
                //Telephone = currentUser.UserProfile.Telephone,
                //AvatarImgUrl = currentUser.UserProfile.AvatarImgUrl,

            };


            return PartialView("_Name", model);

        }
      public async Task Update(GameResult result)
      {
         if (result == null)
         {
            throw new ArgumentNullException("game");
         }

         GameVisibility visibility;
         if (!Enum.TryParse(result.Visibility, out visibility))
         {
            throw new ArgumentException("game.Visibility is not valid");
         }

         var game = await db.Games.FindAsync(result.GameId);

         if (game == null)
         {
            throw new ArgumentException("Could not find game with id " + result.GameId);
         }

         var userID = this.User.Identity.GetUserId();

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         var gameId = game.ID.ToString();

         var ownership = appUser.Claims.FirstOrDefault(c => c.ClaimType == "GameOwnership" && c.ClaimValue == gameId);

         if (ownership == null)
         {
            throw new ArgumentException("Could not update game");
         }

         game.Name = result.Name;
         game.Visibility = visibility;

         await db.SaveChangesAsync();
      }
 public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
 {
     if (!ModelState.IsValid)
     {
         return View(model);
     }
     ApplicationDbContext db = new ApplicationDbContext();
     var userStore = new UserStore<ApplicationUser>(db);
     var userManager = new UserManager<ApplicationUser>(userStore);
     var user = await userManager.FindByIdAsync(User.Identity.GetUserId());
     if (user != null)
     {
         user.PhoneNumber = model.Number;
     }
     var result = await userManager.UpdateAsync(user);
     var ctx = userStore.Context;
     var result1 = await ctx.SaveChangesAsync();
     // However, it always succeeds inspite of not updating the database
     if (!result.Succeeded)
     {
         AddErrors(result);
     }
     return RedirectToAction("Index", "Manage");
 }
      public async Task Delete(int? gameID)
      {
         if (gameID == null)
         {
            throw new ArgumentNullException("gameID");
         }

         var id = gameID.Value;

         var game = await db.Games.FindAsync(id);

         if (game == null)
         {
            throw new ArgumentException("Could not find game with id " + id);
         }
         var userID = this.User.Identity.GetUserId();

         var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));

         var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());

         if (!DoesUserOwnGame(appUser, id))
         {
            throw new ArgumentException("Could not delete game");
         }

         var memberships = await db.GameMemberships.Where(m => m.GameID == id).Include(m => m.ApplicationUser).ToListAsync();

         var claims = await Task.WhenAll(memberships.Select(m => m.ApplicationUser).Select(user =>
            manager.GetClaimsAsync(user.Id).ContinueWith(t => new { Claims = t.Result, User = user })));

         var strId = id.ToString();
         var removeTasks = from tuple in claims
                           from claim in tuple.Claims
                           where (claim.Type == "GameOwnership" || claim.Type == "GameOwnership" || claim.Type == "GameMaster") && claim.Value == strId
                           select manager.RemoveClaimAsync(tuple.User.Id, claim);
         await Task.WhenAll(removeTasks);


         db.GameMemberships.RemoveRange(memberships);
         db.Games.Remove(game);

         await db.SaveChangesAsync();
      }