Ejemplo n.º 1
0
        public virtual ActionResult EditUserByUserName(string username)
        {
            username = string.IsNullOrEmpty(username) ? User.Identity.Name : username;
            var           userId       = _userService.GetAllUsers().FirstOrDefault(u => u.UserName == username)?.Id ?? 0;
            EditUserModel selectedUser = _userService.GetUserDataForEdit(userId);

            var model = new EditUserModel
            {
                BirthDay    = selectedUser.BirthDay,
                Description = selectedUser.Description,
                Email       = selectedUser.Email,
                FirstName   = selectedUser.FirstName,
                LastName    = selectedUser.LastName,
                Major       = selectedUser.Major,
                UserName    = selectedUser.UserName,
                Id          = selectedUser.Id,
                RoleId      = selectedUser.RoleId,
                IsBaned     = selectedUser.IsBaned
            };

            AvatarImage.BasePath = Url.Content("~/Content/avatars/");
            model.AvatarStatus   = (AvatarImage.Exist(selectedUser.UserName));

            ViewBag.Roles = new SelectList(_roleService.GetAllRoles(), "Id", "Description", model.RoleId);

            return(PartialView(MVC.Admin.User.Views._EditUser, model));
        }
Ejemplo n.º 2
0
        public virtual ActionResult EditUser(int userId)
        {
            EditUserModel selectedUser = _userService.GetUserDataForEdit(userId);

            var model = new EditUserModel
            {
                BirthDay    = selectedUser.BirthDay,
                Description = selectedUser.Description,
                Email       = selectedUser.Email,
                FirstName   = selectedUser.FirstName,
                LastName    = selectedUser.LastName,
                Major       = selectedUser.Major,
                UserName    = selectedUser.UserName,
                Id          = selectedUser.Id,
                RoleId      = selectedUser.RoleId,
                IsBaned     = selectedUser.IsBaned
            };

            AvatarImage.BasePath = Url.Content("~/Content/avatars/");
            model.AvatarStatus   = (AvatarImage.Exist(selectedUser.UserName));

            ViewBag.Roles = new SelectList(_roleService.GetAllRoles(), "Id", "Description", model.RoleId);

            return(PartialView(MVC.Admin.User.Views._EditUser, model));
        }
Ejemplo n.º 3
0
 public AvatarImageIdDTO CreateAvatarIdDTO(AvatarImage avatar)
 {
     return(new AvatarImageIdDTO()
     {
         Id = avatar.Id
     });
 }
Ejemplo n.º 4
0
    public void Init(PlayerProfile playerProfile, MicProfile micProfile)
    {
        lineDisplayer = GetComponentInChildren <LineDisplayer>();
        lineDisplayer.Init(6);

        sentenceDisplayer = GetComponentInChildren <SentenceDisplayer>();
        sentenceDisplayer.Init(12, micProfile);

        totalScoreDisplayer = GetComponentInChildren <TotalScoreDisplayer>();

        sentenceRatingDisplayer = GetComponentInChildren <SentenceRatingDisplayer>();

        beatGridDisplayer = GetComponentInChildren <BeatGridDisplayer>();

        currentBeatGridDisplayer = GetComponentInChildren <CurrentBeatGridDisplayer>();

        PlayerNameText playerNameText = GetComponentInChildren <PlayerNameText>();

        playerNameText.SetPlayerProfile(playerProfile);

        AvatarImage avatarImage = GetComponentInChildren <AvatarImage>();

        avatarImage.SetPlayerProfile(playerProfile);

        if (micProfile != null)
        {
            totalScoreDisplayer.SetColorOfMicProfile(micProfile);
            avatarImage.SetColorOfMicProfile(micProfile);
        }
    }
Ejemplo n.º 5
0
 public virtual ActionResult TopMenu()
 {
     AvatarImage.DefaultPath = Url.Content("~/Content/Admin/css/Images/profile_user.jpg");
     AvatarImage.BasePath    = Url.Content("~/Content/avatars/");
     ViewBag.AvatarPath      = AvatarImage.GetAvatarImage(User.Identity.Name);
     return(PartialView(MVC.Admin.Home.Views._TopMenu));
 }
Ejemplo n.º 6
0
        public IActionResult Put([FromBody] AvatarImage avatar)
        {
            if (avatar == null || avatar.B64Data == null || avatar.B64Data.Length == 0)
            {
                return(BadRequest(_localizer[Strings.EmptyImageData].Value));
            }

            ImageEntry image = new ImageEntry {
                Id = avatar.Id, PersonId = avatar.PersonId
            };

            try
            {
                image.SetB64Data(avatar.B64Data);
                if (image.Data == null || image.Data.Length == 0)
                {
                    throw new Exception("Invalid B64Data");
                }
            }
            catch (Exception e)
            {
                // don't let b64 decoding failure result in Internal Server error
                Console.WriteLine(string.Format("PUT api/image: {0}: id {1}, personId {2}, b64Data {3}",
                                                e.Message, avatar.Id, avatar.PersonId, avatar.B64Data));
                return(BadRequest(_localizer[Strings.InvalidImageData].Value));
            }

            return(StoreAvatarImage(image));
        }
Ejemplo n.º 7
0
        void ReleaseDesignerOutlets()
        {
            if (AccountsTable != null)
            {
                AccountsTable.Dispose();
                AccountsTable = null;
            }

            if (AvatarImage != null)
            {
                AvatarImage.Dispose();
                AvatarImage = null;
            }

            if (FetchButton != null)
            {
                FetchButton.Dispose();
                FetchButton = null;
            }

            if (NameTextField != null)
            {
                NameTextField.Dispose();
                NameTextField = null;
            }

            if (LoadingIndicator != null)
            {
                LoadingIndicator.Dispose();
                LoadingIndicator = null;
            }
        }
Ejemplo n.º 8
0
 public void SelectedThisImage(AvatarImage toggle)
 {
     selectedImageID            = toggle.serverID;
     confirmButton.interactable = true;
     selectedDP = toggle.thisImage.sprite;
     Database.PutString(Database.Key.AVATAR_LINK, toggle.imageURL);
 }
Ejemplo n.º 9
0
        //USER MAPS

        public AvatarImageDTO CreateAvatarDTO(AvatarImage avatar)
        {
            return(new AvatarImageDTO()
            {
                Id = avatar.Id,
                AvatarImageBytes = avatar.AvatarImageBytes
            });
        }
Ejemplo n.º 10
0
 public virtual ActionResult RenderDashBoard()
 {
     // set avatar images for users
     AvatarImage.DefaultPath = Url.Content("~/Content/Images/user.gif");
     AvatarImage.BasePath    = Url.Content("~/Content/avatars/");
     ViewBag.AvatarPath      = AvatarImage.GetAvatarImage(User.Identity.Name);
     return(PartialView(MVC.Admin.Home.Views._DashBoard));
 }
Ejemplo n.º 11
0
        public virtual ActionResult DataTable(string term           = "", int page = 0, int count = 10,
                                              Order order           = Order.Descending, UserOrderBy orderBy = UserOrderBy.RegisterDate,
                                              UserSearchBy searchBy = UserSearchBy.UserName)
        {
            ViewBag.TERM     = term;
            ViewBag.PAGE     = page;
            ViewBag.COUNT    = count;
            ViewBag.ORDER    = order;
            ViewBag.ORDERBY  = orderBy;
            ViewBag.SEARCHBY = searchBy;


            IList <UserDataTableModel> selectedUsers = _userService.GetDataTable(term, page, count, order, orderBy,
                                                                                 searchBy);


            ViewBag.OrderByList = DropDownList.OrderList(order);
            ViewBag.CountList   = DropDownList.CountList(count);

            var selectListOrderBy = new List <SelectListItem>
            {
                new SelectListItem {
                    Value = "RegisterDate", Text = "تاریخ ثبت نام"
                },
                new SelectListItem {
                    Value = "UserName", Text = "نام کاربری"
                },
                new SelectListItem {
                    Value = "CommentCount", Text = "تعداد دیدگاه"
                },
                new SelectListItem {
                    Value = "PostCount", Text = "تعداد پست"
                },
                new SelectListItem {
                    Value = "IsBaned", Text = "وضعیت"
                },
                new SelectListItem {
                    Value = "LoginDate", Text = "تاریخ ورود"
                },
                new SelectListItem {
                    Value = "IP", Text = "IP"
                }
            };

            ViewBag.OrderByItems = new SelectList(selectListOrderBy, "Value", "Text", orderBy);

            ViewBag.TotalRecords = (string.IsNullOrEmpty(term)) ? _userService.Count : selectedUsers.Count;

            // set avatar images for users
            AvatarImage.DefaultPath = Url.Content("~/Content/Images/user.gif");
            AvatarImage.BasePath    = Url.Content("~/Content/avatars/");
            foreach (UserDataTableModel user in selectedUsers)
            {
                user.AvatarPath = AvatarImage.GetAvatarImage(user.UserName);
            }

            return(PartialView(MVC.Admin.User.Views._DataTable, selectedUsers));
        }
Ejemplo n.º 12
0
        private void SetupSubViews()
        {
            // Backpanel
            _backPanel = new UIView {
                BackgroundColor = iOS.Appearance.Colors.White
            };
            _topBorder = new UIView {
                BackgroundColor = iOS.Appearance.Colors.RulerColor
            };
            _bottomBorder = new UIView {
                BackgroundColor = iOS.Appearance.Colors.RulerColor
            };

            // Header
            var image = UIImage.FromBundle("Icons/default_avatar.jpg");

            _avatarImage = new AvatarImage(image);
            _displayName = new UILabel {
                Font = iOS.Appearance.Fonts.LatoBoldWithSize(14.5f), TextColor = iOS.Appearance.Colors.DefaultTextColor, Text = "Display Name"
            };
            _timeAgo = new UILabel {
                Font = iOS.Appearance.Fonts.LatoWithSize(11.86f), TextColor = iOS.Appearance.Colors.SubTextColor, Text = "30 minutes ago"
            };

            // Content
            _contentContainer = new UIView {
                BackgroundColor = UIColor.Clear,
            };

            // Footer
            _ruler = new UIView {
                BackgroundColor = iOS.Appearance.Colors.RulerColor
            };
            _commentButton = new FeedButton {
                ImageTopSpacing = 3
            };
            _likeButton = new FeedButton {
                ImageBottomSpacing = 3
            };

            // Add views
            ContentView.Add(_backPanel);
            ContentView.Add(_topBorder);
            ContentView.Add(_bottomBorder);
            ContentView.Add(_avatarImage);
            ContentView.Add(_displayName);
            ContentView.Add(_timeAgo);
            ContentView.Add(_contentContainer);
            ContentView.Add(_ruler);
            ContentView.Add(_commentButton);
            ContentView.Add(_likeButton);
            //_imageViewLoader = new MvxImageViewLoader(() => _avatarImage) { DefaultImagePath = "res:Icons/default_avatar.jpg" };

            foreach (var uiView in ControllsToAdd())
            {
                _contentContainer.Add(uiView);
            }
        }
Ejemplo n.º 13
0
 public virtual ActionResult RemoveAvatar()
 {
     AvatarImage.BasePath = Url.Content("~/Content/avatars/");
     AvatarImage.RemoveAvatarImage(User.Identity.Name);
     return(PartialView(MVC.Admin.Shared.Views._Alert,
                        new Alert {
         Message = "آواتار مورد نظر با موفقیت حذف شد", Mode = AlertMode.Success
     }));
 }
Ejemplo n.º 14
0
        public virtual ActionResult Detail(int userId)
        {
            UserDetailModel selectedUser = _userService.GetUserDetail(userId);


            AvatarImage.DefaultPath = Url.Content("~/Content/Images/user.gif");
            AvatarImage.BasePath    = Url.Content("~/Content/avatars/");
            selectedUser.AvatarPath = AvatarImage.GetAvatarImage(selectedUser.UserName);

            return(PartialView(MVC.Admin.User.Views._Detail, selectedUser));
        }
Ejemplo n.º 15
0
        public virtual ActionResult UpdateProfile()
        {
            EditProfileModel selectedUser = _userService.GetProfileData(User.Identity.Name);

            AvatarImage.DefaultPath = Url.Content("~/Content/Images/user.gif");
            AvatarImage.BasePath    = Url.Content("~/Content/avatars/");
            selectedUser.AvatarPath = AvatarImage.GetAvatarImage(User.Identity.Name);

            selectedUser.AvatarStatus = AvatarImage.Exist(User.Identity.Name);

            return(PartialView(MVC.User.Views._EditProfile, selectedUser));
        }
Ejemplo n.º 16
0
        public async Task <ActionResult> RegisterAsCandidate(RegisterCandidateViewModel model, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };

                if (upload != null && upload.ContentLength > 0)
                {
                    var avatar = new AvatarImage
                    {
                        FileName    = System.IO.Path.GetFileName(upload.FileName),
                        FileType    = FileType.Avatar,
                        ContentType = upload.ContentType
                    };
                    using (var reader = new System.IO.BinaryReader(upload.InputStream))
                    {
                        avatar.Content = reader.ReadBytes(upload.ContentLength);
                    }
                    user.AvatarImages = new List <AvatarImage> {
                        avatar
                    };
                }

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Comment the following line to prevent log in until the user is confirmed.
                    UserManager.AddToRole(user.Id, "Candidate");
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                    // Uncomment to debug locally
                    //TempData["ViewBagLink"] = callbackUrl;

                    ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                      + "before you can log in.";

                    //return View("Info");
                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Ejemplo n.º 17
0
        public void PutImage_BadB64Data_BadRequest(string data)
        {
            AvatarImage avatar = new AvatarImage
            {
                Id       = "world.png",
                PersonId = "1",
                B64Data  = data
            };

            var result = _controller.Put(avatar);

            Assert.IsType <BadRequestObjectResult>(result);

            VerifyNoDbChanges();
        }
Ejemplo n.º 18
0
        public void PutImage_NoIdWithInvalidPersonId_BadRequest(string name, string personId)
        {
            byte[]      data   = GetEmbeddedImage(name);
            AvatarImage avatar = new AvatarImage
            {
                PersonId = personId,
                B64Data  = Convert.ToBase64String(data)
            };

            var result = _controller.Put(avatar);

            Assert.IsType <BadRequestObjectResult>(result);

            VerifyNoDbChanges();
        }
Ejemplo n.º 19
0
        public void PutImage_WithIdNoPersonId_Conflict(string name)
        {
            byte[]      data   = GetEmbeddedImage(name);
            AvatarImage avatar = new AvatarImage
            {
                Id      = name + ".png",
                B64Data = Convert.ToBase64String(data)
            };

            var result = _controller.Put(avatar);

            Assert.IsType <ConflictObjectResult>(result);

            VerifyNoDbChanges();
        }
Ejemplo n.º 20
0
        public void PutImage_WithIdNoPersonId_SuccessfulUpdate(string name)
        {
            byte[]      data   = GetEmbeddedImage(name);
            AvatarImage avatar = new AvatarImage
            {
                Id      = name + ".png",
                B64Data = Convert.ToBase64String(data)
            };

            var result = _controller.Put(avatar);

            Assert.IsType <OkResult>(result);

            VerifyUpdateImage();
            VerifySaveDbOnce();
        }
Ejemplo n.º 21
0
        public void PutImage_NoIdWithPersonId_SuccessfulAdd(string name, string personId)
        {
            byte[]      data   = GetEmbeddedImage(name);
            AvatarImage avatar = new AvatarImage
            {
                PersonId = personId,
                B64Data  = Convert.ToBase64String(data)
            };

            var result = _controller.Put(avatar);

            Assert.IsType <OkResult>(result);

            VerifyAddImage();
            VerifyUpdatePerson();
            VerifySaveDbOnce();
        }
Ejemplo n.º 22
0
        public ActionResult Login(FormCollection collection)
        {
            if (collection["UserIdenticator"] != null && collection["EncryptedPassword"] != null)
            {
                var userIdenticator = collection["UserIdenticator"];
                var password        = Cryptographing.Encrypt(collection["EncryptedPassword"]);

                User user = null;

                if (userIdenticator != null && userIdenticator.Contains("@"))
                {
                    user = db.Users.Where(x => x.Email == userIdenticator && x.EncryptedPassword == password).FirstOrDefault();
                }
                else
                {
                    user = db.Users.Where(x => x.Login == userIdenticator && x.EncryptedPassword == password).FirstOrDefault();
                }

                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(user.Login, (collection["rememberMeInput"] == "rememberMe"));

                    if (user.AvatarImage == null)
                    {
                        Debug.WriteLine("Brak zdjęcia dodam defaultowe");
                        AvatarImage avatarImage = new AvatarImage()
                        {
                            PathToFile = "../../App_Files/Images/UserAvatars/DefaultAvatar.jpg", User = user
                        };

                        user.AvatarImage = avatarImage;
                        db.SaveChanges();
                    }

                    ViewBag.UserAvatarURL = user.AvatarImage.PathToFile;
                    return(RedirectToAction("Index", "Home"));
                }
                ViewBag.ErrorMessage = "Nieprawidłowe dane logowania";
            }
            else
            {
                ViewBag.SomethingWentWrong = "Coś poszło nie tak.";
            }
            return(View());
        }
Ejemplo n.º 23
0
        public async Task <Guid> UploadImage(IFormFile file, Guid imageId, string fileName, Guid userId)
        {
            using (var transaction = _ctx.Database.BeginTransaction())
            {
                await _userService.UpdateAvatar(imageId, userId);

                var path = await _avatarImageStorageService.SaveImage(file, imageId, fileName);

                var avatarImage = new AvatarImage
                {
                    Id   = imageId,
                    Path = path
                };
                await _avatarImageService.AddAvatar(avatarImage);

                _ctx.Database.CommitTransaction();
                return(imageId);
            }
        }
Ejemplo n.º 24
0
        public async Task <ActionResult> EditAvatar()
        {
            User editUser           = db.Users.Where(i => i.Login == HttpContext.User.Identity.Name).First();
            HttpPostedFileBase file = null;

            if (Request.Files.Count > 0)
            {
                file = Request.Files[0];
            }
            else
            {
                return(Json("There is no image to set as avatar!"));
            }


            var imageUrl = await FileManager.UploadAvatar(file, editUser.UserID);

            if (imageUrl != null)
            {
                if (editUser.AvatarImage == null)
                {
                    AvatarImage newAvatar = new AvatarImage()
                    {
                        PathToFile = imageUrl, User = editUser
                    };
                    db.Entry(newAvatar).State = System.Data.Entity.EntityState.Added;
                }
                else
                {
                    editUser.AvatarImage.PathToFile = imageUrl;
                    db.Entry(editUser).State        = System.Data.Entity.EntityState.Modified;
                }
                db.SaveChanges();
                return(Json("Pomyślnie zmieniono avatar! \nZmiany mogą być widocznę dopiero po chwili."));
            }

            return(Json("FileManager.UploadAvatar return null"));
        }
Ejemplo n.º 25
0
        public async Task <IActionResult> AvatarUpload(Guid Id, List <IFormFile> files)
        {
            long size = files.Sum(f => f.Length);

            // full path to file in temp location
            var filePath = Path.GetTempFileName();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);

                        var imageUrl = await _fileUploader.UploadImage(formFile, ".jpg");

                        var imageAvatar = new AvatarImage()
                        {
                            Id              = Guid.NewGuid(),
                            UserId          = Id,
                            Url             = imageUrl,
                            UploadDate      = DateTime.Now,
                            IsCurrentAvatar = true
                        };

                        _context.AvatarImage.Add(imageAvatar);
                        _context.SaveChanges();
                    }
                }
            }


            // process uploaded files
            // Don't rely on or trust the FileName property without validation.

            return(RedirectToAction("Details", "UserInformation", new { id = Id }));
        }
Ejemplo n.º 26
0
        public async Task <IActionResult> EditProfile(string userName)
        {
            // Находим пользователя по имени
            User user = await _websiteDB.Users.FirstOrDefaultAsync(u => u.Name == userName);

            // Находим его аватар
            AvatarImage avatarImage = await _websiteDB.AvatarImages.FirstOrDefaultAsync(a => a.UserId == user.Id);

            // Проверяем, чтобы пользователь не был NUll и чтобы имя залогиненного пользователя совпадало с полученным в методе
            if (User.Identity.Name == userName && user != null)
            {
                ViewBag.Title = $"Редактирование профиля {user.Name}";

                // Создаем модель для передачи в представление
                EditProfileViewModel model = new EditProfileViewModel()
                {
                    UserId           = user.Id,
                    Name             = user.Name,
                    Email            = user.Email,
                    CharacterClassId = user.CharacterClassId
                };

                // Аватар
                if (avatarImage != null)
                {
                    model.AvatarImage = avatarImage.ImagePath;
                }

                SelectList ingameClasses = new SelectList(_websiteDB.CharacterClasses, "Id", "ClassName", user.CharacterClassId);
                ViewBag.Classes = ingameClasses;

                return(View(model));
            }

            // Возврат ошибки 404, если пользователь не найден или пытается редактировать не свой профиль
            return(Redirect("/Main/PageNotFound"));
        }
Ejemplo n.º 27
0
    public void Init(PlayerProfile playerProfile, MicProfile micProfile)
    {
        lineDisplayer = GetComponentInChildren <LineDisplayer>();
        lineDisplayer.Init(6);

        sentenceDisplayer = GetComponentInChildren <SentenceDisplayer>();
        sentenceDisplayer.Init(12, micProfile);

        totalScoreDisplayer = GetComponentInChildren <TotalScoreDisplayer>();

        sentenceRatingDisplayer = GetComponentInChildren <SentenceRatingDisplayer>();

        beatGridDisplayer = GetComponentInChildren <BeatGridDisplayer>();

        currentBeatGridDisplayer = GetComponentInChildren <CurrentBeatGridDisplayer>();

        PlayerNameText playerNameText = GetComponentInChildren <PlayerNameText>();

        playerNameText.SetPlayerProfile(playerProfile);

        AvatarImage avatarImage = GetComponentInChildren <AvatarImage>();

        avatarImage.SetPlayerProfile(playerProfile);

        if (micProfile != null)
        {
            totalScoreDisplayer.SetColorOfMicProfile(micProfile);
            avatarImage.SetColorOfMicProfile(micProfile);
        }

        // Inject all children
        foreach (INeedInjection childThatNeedsInjection in GetComponentsInChildren <INeedInjection>())
        {
            injector.Inject(childThatNeedsInjection);
        }
    }
Ejemplo n.º 28
0
 public async Task <int> AddAvatar(AvatarImage avatarImage)
 {
     return(await _avatarImageRepo.AddNew(avatarImage));
 }
Ejemplo n.º 29
0
        public async Task <ActionResult> Register(FormCollection collection)
        {
            if (collection != null)
            {
                if (collection["Email"] != null && collection["Login"] != null && collection["BirthDate"] != null && collection["Password"] != null)
                {
                    string email        = collection["Email"].Trim();
                    string login        = collection["Login"].Trim();
                    User   tmpEmailUser = db.Users.Where(u => u.Email == email).FirstOrDefault();
                    User   tmpLoginUser = db.Users.Where(u => u.Login == login).FirstOrDefault();

                    bool properDate       = DateTime.TryParse(collection["BirthDate"], out DateTime dataUrodzenia);
                    bool properAge        = Utilities.CheckRegistrationAge(dataUrodzenia);
                    bool uniqueEmail      = tmpEmailUser is null;                // If user with given EMAIL doesn't exist returns true that allows to register, works like "tmpEmailUser is null ? true : null"
                    bool uniqueLogin      = tmpLoginUser is null;                // If user with given LOGIN doesn't exist returns true that allows to register, works like "tmpLoginUser is null ? true : null"
                    bool minimalPswLength = collection["Password"].Length >= 8;

                    if (!properDate)
                    {
                        ViewBag.DateMessage = "Nieprawidłowa data.";
                    }
                    if (!properAge)
                    {
                        ViewBag.AgeMessage = "Musisz mieć ukończone przynajmniej 13 lat.";
                    }
                    if (!uniqueEmail)
                    {
                        ViewBag.EmailMessage = "Konto z podanym emailem już istnieje!";
                    }
                    if (!uniqueLogin)
                    {
                        ViewBag.LoginMessage = "Konto z podanym loginem już istnieje!";
                    }
                    if (!minimalPswLength)
                    {
                        ViewBag.minimalPswLength = "Hasło musi być dłuższe niż 8 znaków!";
                    }

                    if (ModelState.IsValid && properDate && properAge && uniqueEmail && uniqueLogin && minimalPswLength)
                    {
                        try
                        {
                            User user = new User()
                            {
                                FirstName         = collection["FirstName"].Trim(),
                                LastName          = collection["LastName"].Trim(),
                                Login             = login,
                                EncryptedPassword = Cryptographing.Encrypt(collection["Password"]),
                                Email             = email,
                                BirthDate         = dataUrodzenia,
                                CreationDate      = DateTime.Now,
                                IsActivated       = false
                            };
                            AvatarImage avatarImage = new AvatarImage()
                            {
                                PathToFile = "../../App_Files/Images/UserAvatars/DefaultAvatar.jpg", User = user
                            };

                            db.Users.Add(user);
                            db.SaveChanges();

                            user.AvatarImage = avatarImage;
                            db.SaveChanges();

                            var bucket = new Bucket
                            {
                                User = db.Users.Where(i => i.Login == user.Login).First()
                            };
                            db.Buckets.Add(bucket);
                            db.SaveChanges();

                            Order UniqueOrderForThatUser = new Order
                            {
                                User = db.Users.Where(i => i.Login == user.Login).First()
                            };

                            db.Orders.Add(UniqueOrderForThatUser);
                            db.SaveChanges();

                            Task.Run(() => EmailManager.SendEmailAsync(EmailManager.EmailType.Registration, user.FirstName, user.LastName, user.Email));
                            return(RedirectToAction("Login"));
                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.StackTrace);
                            ViewBag.SomethingWentWrong = "Coś poszło nie tak";
                        }
                    }
                }
            }
            return(View());
        }
Ejemplo n.º 30
0
 public AvatarImage AddAvatar(AvatarImage avatar)
 {
     context.Avatars.Add(avatar);
     context.SaveChanges();
     return(avatar);
 }