public bool Register(string fname, string lname, string email, string password)
        {
            using (var work = new UnitOfWork())
            {
                if (work.Users.GetAll().FirstOrDefault(x => x.Email == email) != null)
                {
                    Logger.Error(string.Format(Resources.LogRegisterExistingEmail, email));
                    return(false);
                }

                var hash = new Md5CryptoService();

                ProfilePhoto photo = (new UsersPhotoService()).GetRandomPhoto();
                var          user  = new User(fname, lname, email, password, photo)
                {
                    HashPassword = hash.CalculateMd5Hash(password),
                    LocationId   = work.Locations.GetAll().First().Id,
                    UserName     = email,
                    Birthdate    = DateTime.Now
                };

                work.Users.Create(user);
                work.Save();
                List <User> users = work.Users.GetAll().ToList();
                Logger.Info(string.Format(Resources.RegistrationFinished, email));

                return(true);
            }
        }
        public static async Task <IdentityResult> Registration(SocialNetwork.Domain.DataTransferObjects.RegistrationDTO model)
        {
            using (var work = new UnitOfWork())
            {
                List <Role> roles = new List <Role>();
                roles.Add(work.Roles.FindByNameAsync("User").Result);

                ProfilePhoto photo = (new UsersPhotoService()).GetRandomPhoto();
                var          user  = new User(model.FirstName, model.LastName, model.Email, photo)
                {
                    LocationId = work.Locations.GetAll().First().Id,
                    UserName   = model.UserName,
                    Birthdate  = DateTime.Now,
                    Roles      = roles
                };

                try
                {
                    IdentityUserManager userManager = new IdentityUserManager(work.Users);
                    var res = await userManager.CreateAsync(user, model.Password);

                    work.Save();
                    return(res);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
Exemplo n.º 3
0
        private void UpdateObjectFromFields()
        {
            SelectedItem.UserName = Username.Text;

            var password          = Password.Text.Trim();
            var encryptedPassword = StringHelper.Encrypt(password);

            if (password != "")
            {
                SelectedItem.Password = encryptedPassword;
            }

            SelectedItem.EmailAddress        = EmailAddress.Text;
            SelectedItem.IsActive            = IsActive.Checked;
            SelectedItem.ProfilePhoto        = ProfilePhoto.GetValue().ToString();
            SelectedItem.FirstName           = FirstName.Text;
            SelectedItem.LastName            = LastName.Text;
            SelectedItem.AfterLoginStartPage = AfterLoginStartPage.Text;

            SelectedItem.Roles.Clear();

            foreach (ListItem item in RolesList.Items)
            {
                if (item.Selected)
                {
                    SelectedItem.Roles.Add(BaseMapper.GetObjectFromContext <Role>(RolesMapper.GetByID(long.Parse(item.Value))));
                }
            }
        }
Exemplo n.º 4
0
 public void ConvertByteArrayToBase64()
 {
     if (ProfilePhoto != null && ProfilePhoto.Count() > 0)
     {
         ProfilePhotoBase64 = Encoding.ASCII.GetString(ProfilePhoto);
     }
 }
Exemplo n.º 5
0
        public async Task <CommandResult> SaveImage(IFormFile image)
        {
            var savingResult = await _imageSaver.SaveImage(image);

            if (!savingResult.IsSuccessful)
            {
                return(new CommandResult(savingResult.Error));
            }

            var currentUser = _userCredentialsGetter.GetCuurentUser();

            var photo = new ProfilePhoto
            {
                AddedAtUtc            = DateTime.UtcNow,
                UserId                = currentUser.UserId,
                FilePath              = savingResult.Result.Path,
                AdditionalInformation = QueryString.Create(new Dictionary <string, string>
                {
                    { "Name", savingResult.Result.Name.ToString() },
                    { "Version", "1" }
                }).ToUriComponent(),
            };

            _profileRepo.Add(photo);
            await _profileRepo.SaveChangesAsync();

            return(new CommandResult());
        }
Exemplo n.º 6
0
        public async Task <ProfilePhoto> Update(ProfilePhoto profilePhoto)
        {
            var result = dataContext.ProfilePhotos.Update(profilePhoto);
            await dataContext.SaveChangesAsync();

            return(result.Entity);
        }
Exemplo n.º 7
0
        public async Task UpdateUserPhoto(User user, IFormFile file)
        {
            var profilePhoto = await profilePhotoRepository.GetForUser(user.Id);

            byte[] array;
            using (var stream = new MemoryStream())
            {
                await file.CopyToAsync(stream);

                array = stream.ToArray();
            }

            if (profilePhoto == null)
            {
                profilePhoto = new ProfilePhoto
                {
                    UserId = user.Id,
                    Image  = array
                };

                await profilePhotoRepository.Create(profilePhoto);
            }
            else
            {
                profilePhoto.Image = array;

                await profilePhotoRepository.Update(profilePhoto);
            }
        }
Exemplo n.º 8
0
        public async Task <PhotoDetail> GetPhotoAsync(string userId)
        {
            PhotoDetail detail;

            var graphClient = AuthenticationHelper.Instance.GetAuthenticatedClient();

            try
            {
                ProfilePhoto photo = await graphClient.Users[userId].Photo.Request().GetAsync();

                Stream photoStream = await graphClient.Users[userId].Photo.Content.Request().GetAsync();

                using (MemoryStream ms = new MemoryStream())
                {
                    photoStream.CopyTo(ms);
                    detail.Photo = ms.ToArray();
                }

                detail.Width  = photo.Width;
                detail.Height = photo.Height;
            }
            catch (Exception)
            {
                detail.Width  = 0;
                detail.Height = 0;
                detail.Photo  = null;
            }

            return(detail);
        }
Exemplo n.º 9
0
        public FileContentResult GetProfilePhoto(string Id)
        {
            ApplicationDbContext ctx = new ApplicationDbContext();

            try
            {
                byte[] p = ctx.profilePhotos.FirstOrDefault(ph => ph.Id == Id).Photo;
                return(new FileContentResult(p, "image/jpeg"));
            }
            catch
            {
                var          user = ctx.Users.Single(u => u.Id == Id);
                ProfilePhoto p;
                if (user.Gender == Gender.Female)
                {
                    p = new ProfilePhoto()
                    {
                        Photo = imageToByteArray(System.Drawing.Image.FromFile(Server.MapPath("~/img/woman.png"))), Id = user.Id
                    };
                    ctx.profilePhotos.Add(p);
                }
                else
                {
                    p = new ProfilePhoto()
                    {
                        Photo = imageToByteArray(System.Drawing.Image.FromFile(Server.MapPath("~/img/man.png"))), Id = user.Id
                    };
                    ctx.profilePhotos.Add(p);
                }
                ctx.SaveChanges();
                return(new FileContentResult(p.Photo, "image/jpeg"));
            }
        }
Exemplo n.º 10
0
        public TaskPageViewModel(NavigationService navigation)
        {
            this.navigation = navigation;

            if (CurrentTask.Instance.Task.Image == null)
            {
                TaskImgPath = new BitmapImage(new Uri(Path.Combine(Environment.CurrentDirectory + "\\empty_task_img.png")));
            }
            else
            {
                TaskImgPath = ProfilePhoto.ByteArrayToImage(CurrentTask.Instance.Task.Image);
            }

            ColumnTitle        = CurrentColumn.Instance.Column.Title;
            TaskTitle          = CurrentTask.Instance.Task.Title;
            Deadline           = CurrentTask.Instance.Task.Deadline;
            AssignedTo         = CurrentTask.Instance.Task.AssignedTo;
            Description        = CurrentTask.Instance.Task.Description;
            CreatedAt          = "Created at: " + CurrentTask.Instance.Task.CreatedAt.Humanize();
            CurrentKanbanState = CurrentProject.Instance.KanbanStates.FirstOrDefault(x => x.Name.Equals(CurrentTask.Instance.Task.CurrentKanbanState)).Name;


            timer = new System.Timers.Timer(1000);
            timer.Start();
            timer.Elapsed += Timer_Elapsed;
        }
Exemplo n.º 11
0
        private void GenerateBot(SocialNetworkContext db)
        {
            Location l = db.Locations.FirstOrDefaultAsync().Result;

            ProfilePhoto botPhoto = new ProfilePhoto
            {
                Url = @"..\Resources\Images\ProfilePhotos\bot.png"
            };

            db.ProfilePhotos.Add(botPhoto);

            User bot =
                new User
            {
                Email          = "*****@*****.**",
                FirstName      = "Botty",
                LastName       = "Bot",
                UserName       = "******",
                HashPassword   = "******",
                Birthdate      = DateTime.Now,
                ProfilePhotoId = botPhoto.Id,
                LocationId     = l.Id
            };

            db.Users.Add(bot);

            db.SaveChanges();
        }
Exemplo n.º 12
0
        public ActionResult DeleteConfirmed(int id)
        {
            ProfilePhoto profilephoto = db.ProfilePhotoes.Find(id);

            db.ProfilePhotoes.Remove(profilephoto);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public string ConstructOrDefault(ProfilePhoto profilePhoto)
 {
     if (profilePhoto == null)
     {
         return($"{_domainName}/favicon.ico");
     }
     return($"{_domainName}/Resources/Photo/Profile/{HttpUtility.ParseQueryString(profilePhoto.AdditionalInformation)["Name"]}");
 }
        public IActionResult Add([FromForm(Name = ("Image"))] IFormFile file, [FromForm] ProfilePhoto profilephoto)
        {
            var result = _profilePhotoService.Update(file, profilephoto);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Exemplo n.º 15
0
        public override string ToString()
        {
            string str = string.Format("{{public key={0}, nickname={1}, status={2}, photo={3}}}",
                                       PublicKey == null? "" : Convert.ToBase64String(PublicKey),
                                       NickName,
                                       Status,
                                       ProfilePhoto == null ? "null" : ProfilePhoto.ToString());

            return(str);
        }
Exemplo n.º 16
0
        public IActionResult ShowProfilePhoto(int id)
        {
            ProfilePhoto image = _contactRepository.GetProfilePhoto(id);

            if (image == null)
            {
                byte[] imageContent = System.IO.File.ReadAllBytes("wwwroot\\images\\profile-icon.png");
                return(File(imageContent, "image/jpg"));
            }
            return(File(image.Content, "image/jpg"));
        }
Exemplo n.º 17
0
        public ActionResult Create([Bind(Include = "ProfilePhotoId,UserId,ProfileImage")] ProfilePhoto profilephoto)
        {
            if (ModelState.IsValid)
            {
                db.ProfilePhotoes.Add(profilephoto);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(profilephoto));
        }
Exemplo n.º 18
0
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Returns HashCode</returns>
 public override int GetHashCode()
 {
     return(String.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|",
                          PasswordProfile.GetHashCode(),
                          AccountEnabled.GetHashCode(),
                          DisplayName?.GetHashCode() ?? 0,
                          MailNickname?.GetHashCode() ?? 0,
                          PasswordPolicies?.GetHashCode() ?? 0,
                          UserPrincipalName?.GetHashCode() ?? 0,
                          ProfilePhoto?.GetHashCode() ?? 0,
                          Licenses.Aggregate(0, (acc, next) => acc += (next != null ? next.GetHashCode() : 0))
                          ).GetHashCode());
 }
Exemplo n.º 19
0
        public IResult Delete(ProfilePhoto profilePhoto)
        {
            var imagePath = _profilePhotoDal.Get(p => p.Id == profilePhoto.Id).ImagePath;
            var fullPath  = @"C:\Users\Erhan\Desktop\C#\CarProject\WebAPI\wwwroot\" + imagePath;

            PPHelper.Delete(fullPath);
            //if (result != null)
            //{
            //    return result;
            //}
            _profilePhotoDal.Delete(profilePhoto);
            return(new SuccessResult(Messages.PPDelete));
        }
Exemplo n.º 20
0
 public SignUpViewModel(NavigationService navigation)
 {
     this.navigation  = navigation;
     this.userService = new UserService();
     if (CurrentUser.Instance.User.Image == null)
     {
         ProfileImgPath = new BitmapImage(new Uri(Path.Combine(Environment.CurrentDirectory + "\\user.png")));
     }
     else
     {
         ProfileImgPath = ProfilePhoto.ByteArrayToImage(CurrentUser.Instance.User.Image);
     }
 }
Exemplo n.º 21
0
        public async Task <ActionResult> UploadPhoto(HttpPostedFileBase upload)
        {
            var id = User.Identity.GetUserId();

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            User _user = db.Users.Find(id);

            if (_user == null)
            {
                return(HttpNotFound());
            }
            try
            {
                if (ModelState.IsValid)
                {
                    if (upload != null && upload.ContentLength > 0)
                    {
                        if (_user.Photos.Any(f => f.FileType == FileType.Photo))
                        {
                            db.Photos.Remove(_user.Photos.First(f => f.FileType == FileType.Photo));
                        }
                        var newPhoto = new ProfilePhoto
                        {
                            FileId      = Guid.NewGuid(),
                            FileName    = System.IO.Path.GetFileName(upload.FileName),
                            FileType    = FileType.Photo,
                            ContentType = upload.ContentType,
                            UserId      = _user.Id
                        };
                        using (var reader = new System.IO.BinaryReader(upload.InputStream))
                        {
                            newPhoto.Content = reader.ReadBytes(upload.ContentLength);
                        }
                        _user.Photos = new List <ProfilePhoto> {
                            newPhoto
                        };
                        db.Photos.Add(newPhoto);
                        await db.SaveChangesAsync();
                    }
                }

                return(RedirectToAction("UserProfile", new { Message = ManageMessageId.UploadPhotoSuccess }));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 22
0
        // GET: /ProfilePhoto/Delete/5
        public ActionResult Delete(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProfilePhoto profilephoto = db.ProfilePhotoes.Find(id);

            if (profilephoto == null)
            {
                return(HttpNotFound());
            }
            return(View(profilephoto));
        }
Exemplo n.º 23
0
        public async Task <Response> SaveImage(ProfilePhoto imageDetail)
        {
            var detail = JsonConvert.SerializeObject(imageDetail);
            var result = await CallPostFunction(detail, SaveImageAction);

            if (result == null)
            {
                return(null);
            }
            else
            {
                return(result);
            }
        }
Exemplo n.º 24
0
        private void UpdateFieldsFromObject()
        {
            Username.Text = SelectedItem.UserName;
            //Password.Text = SelectedItem.Password;
            EmailAddress.Text = SelectedItem.EmailAddress;
            IsActive.Checked  = SelectedItem.IsActive;
            ProfilePhoto.SetValue(SelectedItem.ProfilePhoto);
            FirstName.Text           = SelectedItem.FirstName;
            LastName.Text            = SelectedItem.LastName;
            AfterLoginStartPage.Text = SelectedItem.AfterLoginStartPage;

            foreach (Role userRole in SelectedItem.Roles)
            {
                RolesList.Items.FindByValue(userRole.ID.ToString()).Selected = true;
            }
        }
        //// private readonly IPathProvider pathProvider;

        //// public ImageService(IPathProvider pathProvider)
        //// {
        ////    this.pathProvider = pathProvider;
        //// }

        public ProfilePhoto Create(Guid photoId, Guid userId)
        {
            using (UnitOfWork work = new UnitOfWork())
            {
                ProfilePhoto image = work.ProfilePhotos.Get(photoId);
                var          user  = work.Users.Get(userId);
                if (user.ProfilePhotoId != null && work.ProfilePhotos.Get(user.ProfilePhotoId) != null)
                {
                    DeletePhoto(user.ProfilePhotoId);
                }

                user.ProfilePhotoId = image.Id;
                work.Save();

                return(image);
            }
        }
Exemplo n.º 26
0
        private string ProcessUploadFile()
        {
            if (ProfilePhoto == null)
            {
                return(string.Empty);
            }

            var uploadFolder = Path.Combine(HostEnvironment.WebRootPath, "Images");
            var fileName     = $"{Guid.NewGuid()}_{ProfilePhoto.FileName}";
            var filePath     = Path.Combine(uploadFolder, fileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                ProfilePhoto.CopyTo(stream);
            }
            return(fileName);
        }
        public ActionResult Create([Bind(Include = "EmpProfileID,PhotoName,PhotoContent")] ProfilePhoto profilePhoto, HttpPostedFileBase upload)
        {
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {
                    profilePhoto.PhotoName = System.IO.Path.GetFileName(upload.FileName);
                    byte[] data = new byte[upload.ContentLength];
                    upload.InputStream.Read(data, 0, upload.ContentLength);

                    profilePhoto.PhotoContent = data;
                }
                db.ProfilePhotos.Add(profilePhoto);
                db.SaveChanges();
                return(RedirectToAction("Index", "Dashboard"));
            }
            return(PartialView(profilePhoto));
        }
        public ActionResult Edit()
        {
            string abc = User.Identity.GetUserId();
            int?   id  = db.EmpProfiles.Where(r => r.UserID == abc).First().EmpProfileID;

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProfilePhoto profilePhoto = db.ProfilePhotos.Find(id);

            if (profilePhoto == null)
            {
                return(HttpNotFound());
            }
            ViewBag.EmpProfileID = new SelectList(db.EmpProfiles, "EmpProfileID", "UserID", profilePhoto.EmpProfileID);
            return(View(profilePhoto));
        }
Exemplo n.º 29
0
        public IResult Update(IFormFile formFile, ProfilePhoto profilePhoto)
        {
            var oldImage = _profilePhotoDal.Get(p => p.UserId == profilePhoto.UserId);

            if (oldImage != null)
            {
                _profilePhotoDal.Delete(oldImage);
            }
            profilePhoto.ImagePath = PPHelper.Add(formFile);

            var data = profilePhoto.ImagePath.Split('\\').LastOrDefault();

            profilePhoto.ImagePath = "/Images/ProfilePhotos/" + data;

            profilePhoto.Date = DateTime.Now;
            _profilePhotoDal.Add(profilePhoto);

            return(new SuccessResult(Messages.PPSuccesfullUpdate));
        }
        /// <summary>
        /// Update the navigation property photo in users
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePatchRequestInformation(ProfilePhoto body, Action <PhotoRequestBuilderPatchRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.PATCH,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new PhotoRequestBuilderPatchRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }