public bool UploadPhoto(UserInfo user, string file, bool isPrivate = true, bool isAvatar = false)
        {
            file = file.Substring(23);

            _blobHandler = new BlobHandler(user.BlobContainerName);
            var photoKey = Guid.NewGuid().ToString();
            var photo = new UserPhoto
            {
                Author = user,
                BlobStorageLink = photoKey,
                IsPrivate = isPrivate,
                IsUserAvatar = isAvatar
            };
            try
            {
                _blobHandler.Upload(photoKey, file);

                _objectFactory._context.Entry<UserInfo>(photo.Author).State = System.Data.Entity.EntityState.Modified;
                _objectFactory.GetRepositoryInstance<Guid, UserPhoto>().Add(photo);
                _objectFactory.Commit();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
Example #2
0
        public void SetUserPhoto(int tenant, Guid id, byte[] photo)
        {
            using var tr = UserDbContext.Database.BeginTransaction();

            var userPhoto = UserDbContext.Photos.FirstOrDefault(r => r.UserId == id && r.Tenant == tenant);

            if (photo != null && photo.Length != 0)
            {
                if (userPhoto == null)
                {
                    userPhoto = new UserPhoto
                    {
                        Tenant = tenant,
                        UserId = id,
                        Photo  = photo
                    };
                }
                else
                {
                    userPhoto.Photo = photo;
                }

                UserDbContext.AddOrUpdate(r => r.Photos, userPhoto);
            }
            else if (userPhoto != null)
            {
                UserDbContext.Photos.Remove(userPhoto);
            }

            UserDbContext.SaveChanges();
            tr.Commit();
        }
Example #3
0
        public void Create_Should_Return_Failure_Result_When_Path_Is_Empity(int order, string path)
        {
            var userPhoto = UserPhoto.Create(order, path);

            userPhoto.IsSuccessed.Should().BeFalse();
            userPhoto.GetErrorString().Should().Be(UserPhoto.Path_Should_Not_Be_Empty);
        }
Example #4
0
        public void Create_Should_Return_Failure_Result_When_Order_Is_Invalid(int order, string path)
        {
            var userPhoto = UserPhoto.Create(order, path);

            userPhoto.IsSuccessed.Should().BeFalse();
            userPhoto.GetErrorString().Should().Be(UserPhoto.Order_Should_Be_Greater_Than_Zero);
        }
Example #5
0
        public ActionResult Create(UserAccountPhoto UserAccountPhoto)
        {
            try
            {
                Usuario                 Usuario       = new Usuario();
                UserAccount             UserAccount   = new UserAccount();
                UserPhoto               UserPhoto     = new UserPhoto();
                List <UserPhoto>        UserPhotoList = new List <UserPhoto>();
                List <UserAccountPhoto> dataList      = new List <UserAccountPhoto>();

                for (int x = 0; x < UserAccountPhoto.PhotoList.Count; x++)
                {
                    UserPhoto       = new UserPhoto();
                    UserPhoto.Photo = UserAccountPhoto.PhotoList[x];
                    for (int i = 0; i < UserAccountPhoto.UserNameList.Count; i++)
                    {
                        Usuario.ID           = UserAccountPhoto.ID;
                        Usuario.Name         = UserAccountPhoto.Name;
                        Usuario.LastName     = UserAccountPhoto.LastName;
                        UserAccount.UserName = UserAccountPhoto.UserNameList[i];
                        UserAccount.Password = UserAccountPhoto.Password;
                    }
                    UserPhotoList.Add(UserPhoto);
                }
                _usuarioBusiness.InsertUsuario(Usuario);
                _useraccountBusiness.InsertUserAccount(UserAccount);
                _userphotoBusiness.InsertUserPhoto(UserPhoto);
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        public async Task <IActionResult> AddPhoto([FromForm] CloudinaryPhoto cloudinaryPhoto)
        {
            var userId       = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var file         = cloudinaryPhoto.File;
            var uploadResult = new ImageUploadResult();

            if (file.Length > 0)
            {
                using (var stream = file.OpenReadStream())
                {
                    var uploadParams = new ImageUploadParams()
                    {
                        File           = new FileDescription(file.Name, stream),
                        Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
                    };

                    uploadResult = _cloudinary.Upload(uploadParams);
                }
            }

            cloudinaryPhoto.Url      = uploadResult.Uri.ToString();
            cloudinaryPhoto.PublicID = uploadResult.PublicId;
            UserPhoto userPhoto = new UserPhoto();

            userPhoto.ImgUrl    = cloudinaryPhoto.Url;
            userPhoto.PublicID  = cloudinaryPhoto.PublicID;
            userPhoto.UserID    = userId;
            userPhoto.IsDefault = true;
            await _context.UserPhotos.AddAsync(userPhoto);

            await _context.SaveChangesAsync();

            return(CreatedAtRoute("GetPhoto", new { id = userPhoto.UserPhotoID }, userPhoto));
        }
        /// <summary>
        /// Add a photo for the user
        /// Documentation https://developers.google.com/directory/directory_v1/reference/photos/update
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated directory service.</param>
        /// <param name="userKey">Email or immutable Id of the user</param>
        /// <param name="body">A valid directory directory_v1 body.</param>
        /// <returns>UserPhotoResponse</returns>
        public static UserPhoto Update(directoryService service, string userKey, UserPhoto body)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (body == null)
                {
                    throw new ArgumentNullException("body");
                }
                if (userKey == null)
                {
                    throw new ArgumentNullException(userKey);
                }

                // Make the request.
                return(service.Photos.Update(body, userKey).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Photos.Update failed.", ex);
            }
        }
Example #8
0
        public async Task <IActionResult> Register(UserForRegister userDto)
        {
            //IS NOT NECESSRYYYYYY por que herada de apicontroller
            //if(!ModelState.IsValid)
            //{
            //    return BadRequest(new Error(HttpStatusCode.BadRequest.ToString(), "Los datos ingresados tienen un formato incorrecto"));

            //}
            if (await _authRepository.UserExists(userDto.UserName))
            {
                return(BadRequest(new Error(HttpStatusCode.BadRequest.ToString(), "User " + userDto.UserName + "already exists")));
            }

            var userToCreate = _mapper.Map <UserApplication>(userDto);

            var registerdUser = await this._authRepository.RegisterUser(userToCreate, userDto.Password);

            UserPhoto photo = new UserPhoto
            {
                IsMain            = true,
                UserApplicationId = registerdUser.Id,
                PublicId          = "i0qwn3iomugvu4ps04p8",
                DateAdded         = DateTime.Now,
                user = registerdUser,
                Url  = "http://res.cloudinary.com/dapyqzhn4/image/upload/v1591522415/i0qwn3iomugvu4ps04p8.png"
            };

            registerdUser.Photos = new List <UserPhoto>();
            registerdUser.Photos.Add(photo);
            await _authRepository.SaveAll();

            var userToReturn = _mapper.Map <UserDetailsDTO>(userToCreate);

            return(CreatedAtRoute("GetUser", new { controller = "users", id = userToCreate.Id }, userToReturn));
        }
Example #9
0
        // Create documents with class - instances.
        public async Task CreateDocuments()
        {
            Console.Clear();
            Console.WriteLine("Add Email");
            string email = Console.ReadLine();

            Console.WriteLine("Add a photo url");
            string photoUrl = Console.ReadLine();

            if (email.Trim().Length > 0 && photoUrl.Trim().Length > 0)
            {
                if (DataContext.IsValid(email))
                {
                    emailDoc = new UserEmail(email);
                    photoDoc = new UserPhoto(photoUrl, email);
                    InsertUserIfNotExists();
                }
                else
                {
                    Console.WriteLine("That Email is not valid. Try Again!");
                    Thread.Sleep(2000);
                }
            }
            else
            {
                Console.WriteLine("Enter both email & photo url to add user!");
                Thread.Sleep(2000);
            }
            Console.Clear();
        }
Example #10
0
        public UserPhoto GetUserProfilePhoto(int userID)
        {
            UserPhoto  result = null;
            SqlCommand comm   = new SqlCommand()
            {
                CommandText =
                    "SELECT id, photo FROM dbo.UserProfiles prof " +
                    "LEFT JOIN dbo.Photos phot ON prof.photoGuid = phot.guid WHERE userID = @userID\n",
                CommandType    = System.Data.CommandType.Text,
                CommandTimeout = 2000,
                Connection     = this.conn
            };

            comm.Parameters.AddWithNullableValue("userID", userID);
            SqlDataReader reader = comm.ExecuteReader();

            if (reader.Read())
            {
                result = new UserPhoto()
                {
                    UserID    = userID,
                    ProfileID = reader.GetConverted <int>("id"),
                };
                if (reader.GetConverted <byte[]>("photo") != null)
                {
                    result.PhotoBase64 = Convert.ToBase64String(reader.GetConverted <byte[]>("photo"));
                }
            }
            reader.Close();
            return(result);
        }
Example #11
0
        public async Task <ActionResult <UserPhotoDto> > AddPhoto(IFormFile file)
        {
            var user = await _userRepository.GetByNameAsync(User.GetUsername());

            var result = await _photoService.AddPhotoAsync(file);

            if (result.Error != null)
            {
                return(BadRequest(result.Error.Message));
            }

            var photo = new UserPhoto()
            {
                Url      = result.SecureUrl.AbsoluteUri,
                PublicId = result.PublicId
            };

            if (user.Photos.Count == 0)
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            if (await _userRepository.SaveAllAsync())
            {
                return(CreatedAtRoute("GetUser", new { username = user.UserName }, _mapper.Map <UserPhotoDto>(photo)));
            }

            return(BadRequest("Ocurrió un problema al agregar la foto"));
        }
Example #12
0
        public static void Create(UserPhotoDTO userPhotoDTO)
        {
            UserPhoto userPhoto = MapperTransform <UserPhoto, UserPhotoDTO> .ToEntity(userPhotoDTO);

            Database.UserPhotos.Create(userPhoto);
            Database.Save();
        }
Example #13
0
        public void SetPhoto_Should_Be_Add_Photo_To_User()
        {
            var photo = UserPhoto.Create(1, "test");

            _user.SetPhoto(photo.Value);
            _user.Photos[0].Should().BeEquivalentTo(photo.Value);
        }
Example #14
0
        public async Task <ActionResult <UserPhotoDto> > AddPhoto(IFormFile file)
        {
            // we eagerly load our photos here too
            var user = await _userRepository.GetUserByUsernameAsync(User.GetUsername());

            var result = await _photoService.AddPhotoAsync(file);

            if (result.Error != null)
            {
                return(BadRequest(result.Error.Message));
            }

            var photo = new UserPhoto
            {
                Url      = result.SecureUrl.AbsoluteUri,
                PublicId = result.PublicId
            };

            if (user.Photos.Count == 0)
            {
                photo.IsMain = true;
            }

            user.Photos.Add(photo);

            if (await _userRepository.SaveAllAsync())
            {
                //CreatedAtRoute returns a 201 and adds a location to the headers returned
                return(CreatedAtRoute("GetEmployee", new { username = user.UserName }, _mapper.Map <UserPhotoDto>(photo)));
            }


            return(BadRequest("Problem adding photo"));
        }
Example #15
0
        /// <summary>
        /// Add Photos to User
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="path"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        public async Task <Result> SetUserPhotoAsync(int userId, string path, int order)
        {
            var result = UserPhoto.Create(order, path);

            if (!result.IsSuccessed)
            {
                return(Result.Fail(result.GetErrorString()));
            }

            var userResult = await _userRepository.GetUserByIdAsync(userId);

            if (!userResult.IsSuccessed)
            {
                return(Result.Fail(userResult.GetErrorString()));
            }

            var user      = userResult.Value;
            var userPhoto = result.Value;

            user.SetPhoto(userPhoto);
            _userRepository.Update(user);

            var saveResult = await _userRepository.SaveChangesAsync(Failed_To_Update_Photos);

            if (!saveResult.IsSuccessed)
            {
                return(Result.Fail(saveResult.GetErrorString()));
            }

            _mediator.Publish(new UserModified(user));
            return(Result.Ok());
        }
        public async Task <UserPhoto> AddPhoto(IFormFile file)
        {
            if (file.Length > 0)
            {
                var uploadsFolderPath = Path.Combine(host.ContentRootPath, "wwwroot/uploads");
                if (!Directory.Exists(uploadsFolderPath))
                {
                    Directory.CreateDirectory(uploadsFolderPath);
                }

                var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                var filePath = Path.Combine(uploadsFolderPath, fileName);

                using (var stream = file.OpenReadStream())
                {
                    var uploadedImage = Image.FromStream(stream);
                    var imageWidth    = uploadedImage.Width < 800?uploadedImage.Width:800;

                    var img = ImageResize.ScaleByWidth(uploadedImage, imageWidth);
                    img.SaveAs(filePath);

                    await stream.DisposeAsync();
                }

                var UserPhoto = new UserPhoto
                {
                    ImageFullPath = filePath,
                    ImageUrl      = fileName
                };

                return(UserPhoto);
            }

            throw new RestException(HttpStatusCode.BadRequest, new { UserPhoto = "Please select an image file" });
        }
        public ActionResult ChangePicture(UserPhoto userPhoto)
        {
            inject();

            string fileUrl = "https://res.cloudinary.com/votel/image/upload/v1550180723/1.jpg";

            if (userPhoto.ImageData != null)
            {
                //try upload
                //var imageData = userDto.PictureUrl.Split(',')[1];
                var imageData = userPhoto.ImageData;

                //Remove this part "data:image/jpeg;base64,"
                // Base64String = Base64String.Split(',')[1];
                fileUrl = App.Services.FileUpload.uploadToNet(imageData);
                if (fileUrl == null)
                {
                    fileUrl = "https://res.cloudinary.com/votel/image/upload/v1550180723/1.jpg";
                }
            }
            var user = _context.AspNetUsers.Where(a => a.Id == userPhoto.Id).SingleOrDefault();

            user.ImageUrl = fileUrl;
            _context.Entry(user).State = EntityState.Modified;
            _context.SaveChanges();
            return(RedirectToAction("User1", new { userid = userPhoto.Id }));
        }
        public HttpResponseMessage UserProfile([FromBody] UserPhoto user)
        {
            string message = "";

            if (ModelState.IsValid)
            {
                using (MyDbEntities db = new MyDbEntities())
                {
                    UserViewModel model = new UserViewModel();

                    var userProfile = db.UserDataExtended2.Where(a => a.UserId == user.UploaderID).FirstOrDefault();
                    //var userProfile = db.UserPhotos.Where(c => c.UploaderID == user.UserId).FirstOrDefault();

                    //model.Link = ProfilePic.Link;

                    // map user detail with profile 4to
                    return(Request.CreateResponse(HttpStatusCode.OK, userProfile));
                    // create the user profile and load it in the home page of mobile app
                }
            }
            else
            {
                message = "Connection Error! Try Again";
                return(Request.CreateResponse(HttpStatusCode.BadRequest, message));
            }
        }
Example #19
0
        public async Task <ActionResult <PhotoDto> > AddUserPhoto(IFormFile file)
        {
            var user = await _userRepository.GetUserByUsernameAsync(User.GetUsername());

            var result = await _photoService.AddPhotoAsync(file);

            if (result.Error != null)
            {
                return(BadRequest(result.Error.Message));
            }

            var photo = new UserPhoto
            {
                Url      = result.SecureUrl.AbsoluteUri,
                publicId = result.PublicId
            };

            user.Photo = photo;

            if (await _userRepository.SaveAllAsync())
            {
                return(CreatedAtRoute("GetUser", new { username = user.UserName }, _mapper.Map <UserPhoto, PhotoDto>(photo)));
            }

            return(BadRequest("Unable to upload photo"));
        }
Example #20
0
        protected void save_Click(object sender, EventArgs e)
        {
            if (!filPhoto.HasFile)
            {
                this.PageEngine.ShowMessageBox("请选择头像文件");
                return;
            }

            List <string> ext = new List <string>()
            {
                ".JPG", ".PNG", ".GIF"
            };
            string filExt = System.IO.Path.GetExtension(filPhoto.FileName).ToUpper();

            if (ext.IndexOf(filExt) == -1)
            {
                this.PageEngine.ShowMessageBox("文件格式不合法");
                return;
            }

            var userPhoto = UserPhoto.GetUserPhotoByAccount(Args["Account"]);

            if (userPhoto == null)
            {
                userPhoto         = UserPhoto.Create();
                userPhoto.Account = Args["Account"];
            }

            userPhoto.PhotoBinary = filPhoto.FileBytes;
            userPhoto.PhotoExt    = filExt;
            userPhoto.Save();

            this.PageEngine.ShowMessageBox("上传成功");
            this.PageEngine.CloseWindow();
        }
Example #21
0
        public ActionResult DeleteConfirmed(int id)
        {
            UserPhoto userPhoto = db.UserPhoto.Find(id);

            db.UserPhoto.Remove(userPhoto);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #22
0
        public async Task <UserPhoto> RegisterPhoto(UserPhoto userPhoto)
        {
            await _context.UserPhoto.AddAsync(userPhoto);

            await _context.SaveChangesAsync();

            return(userPhoto);
        }
Example #23
0
        public static void Update(UserPhotoDTO userPhotoDTO)
        {
            UserPhoto userPhoto = Database.UserPhotos.Get(userPhotoDTO.Id);

            userPhoto.MainPhoto = userPhotoDTO.MainPhoto;
            userPhoto.SRC       = userPhotoDTO.SRC;
            userPhoto.UserId    = userPhotoDTO.UserId;
            Database.UserPhotos.Update(userPhoto);
            Database.Save();
        }
Example #24
0
        private dynamic GetProfilePhoto(dynamic arg)
        {
            UserPhoto photo = dao.GetUserProfilePhoto(arg.id);

            if (photo == null)
            {
                return(HttpStatusCode.BadRequest);
            }
            return(photo);
        }
 public void UploadPhoto(HttpPostedFileBase photoFile, UserPhoto userPhoto)
 {
     if (photoFile != null)
     {
         string pic  = System.IO.Path.GetFileName(photoFile.FileName);
         string path = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/UserPicture"), pic);
         photoFile.SaveAs(path);
         userPhoto.UserPhotoImage = photoFile.FileName;
     }
 }
Example #26
0
        public int InsertImageOfUser(UserPhoto userPhoto)
        {
            using (var dataContext = new DataContext(_connectionString))
            {
                dataContext.GetTable <UserPhoto>().InsertOnSubmit(userPhoto);
                dataContext.SubmitChanges();
            }

            return(userPhoto.Id);
        }
Example #27
0
        public static UserPhotoInfo GetUserPhotoByAccount(string account)
        {
            var userPhoto = UserPhoto.GetUserPhotoByAccount(account);

            if (userPhoto == null)
            {
                return(null);
            }
            return(userPhoto.MappingTo <UserPhotoInfo>());
        }
        public IActionResult Add([FromForm(Name = ("ImagePath"))] IFormFile file, [FromForm] UserPhoto photo)
        {
            var result = _userPhotoService.Add(file, photo);

            if (result.Success)
            {
                return(Ok(result));
            }
            return(BadRequest(result));
        }
Example #29
0
 private void InitUserImge()
 {
     if (parkBoxOptions.UserImg != null)
     {
         UserPhoto.SetImage(parkBoxOptions.UserImg);
     }
     else
     {
         UserPhoto.SetImage(parkBoxOptions.DefultUserImg);
     }
 }
Example #30
0
        public IActionResult DeleteUserPhoto(long id)
        {
            UserPhoto a = Photo_repo.Find(id);

            if (a == null)
            {
                return(NotFound());
            }
            Photo_repo.Delete(a);
            return(Ok());
        }
Example #31
0
        public async Task <IActionResult> UpdatePhoto([FromBody] UserPhoto userPhoto)
        {
            var user = await context.People.FindAsync(userPhoto.UserId);

            user.Photo = userPhoto.Photo;
            context.Update(user);

            var result = await context.SaveChangesAsync();

            return(Ok(result));
        }
Example #32
0
        public ActionResult EditPhoto(HttpPostedFileBase file)
        {
            mu = Membership.GetUser();
            UserPhoto up1 = null;
            int swapID = 0;

            var acl = CannedAcl.PublicRead;

            S3Service s3 = new S3Service();

            s3.AccessKeyID = AmazonCloudConfigs.AmazonAccessKey;
            s3.SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey;

            if (Request.Form["new_default"] != null &&
                int.TryParse(Request.Form["new_default"], out swapID))
            {
                // swap the default with the new default
                uad = new UserAccountDetail();
                uad.GetUserAccountDeailForUser(Convert.ToInt32(mu.ProviderUserKey));

                string currentDefaultMain = uad.ProfilePicURL;
                string currentDefaultMainThumb = uad.ProfileThumbPicURL;

                up1 = new UserPhoto(swapID);

                uad.ProfilePicURL = up1.PicURL;
                uad.ProfileThumbPicURL = up1.ThumbPicURL;
                uad.LastPhotoUpdate = DateTime.UtcNow;
                uad.Update();

                up1.PicURL = currentDefaultMain;
                up1.ThumbPicURL = currentDefaultMainThumb;
                up1.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                up1.Update();

                LoadCurrentImagesViewBag(Convert.ToInt32(mu.ProviderUserKey));

                return View(uad);
            }

            string photoOne = "photo_edit_1";
            string photoTwo = "photo_edit_2";
            string photoThree = "photo_edit_3";

            LoadCurrentImagesViewBag(Convert.ToInt32(mu.ProviderUserKey));

            uad = new UserAccountDetail();
            uad.GetUserAccountDeailForUser(Convert.ToInt32(mu.ProviderUserKey));

            if (file == null)
            {
                ViewBag.IsValid = false;
                ModelState.AddModelError(string.Empty, BootBaronLib.Resources.Messages.NoFile);
                return View(uad);
            }

            string photoEdited = Request.Form["photo_edit"];
            string mainPhotoToDelete = string.Empty;
            string thumbPhotoToDelete = string.Empty;

            ups = new UserPhotos();
            ups.GetUserPhotos(uad.UserAccountID);

            if (string.IsNullOrEmpty(uad.ProfilePicURL) ||
                ups.Count == 2 && photoEdited == photoOne)
            {
                mainPhotoToDelete = uad.ProfilePicURL;
                thumbPhotoToDelete = uad.ProfileThumbPicURL;
            }
            else
            {
                if (ups.Count > 1 && photoEdited == photoTwo)
                {
                    up1 = new UserPhoto(ups[0].UserPhotoID);
                    up1.RankOrder = 1;
                    mainPhotoToDelete = up1.PicURL;
                    thumbPhotoToDelete = up1.ThumbPicURL;
                }
                else if (ups.Count > 1 && photoEdited == photoThree)
                {
                    up1 = new UserPhoto(ups[1].UserPhotoID);
                    up1.RankOrder = 2;
                    mainPhotoToDelete = ups[1].FullProfilePicURL;
                    thumbPhotoToDelete = up1.ThumbPicURL;
                }

            }

            if (!string.IsNullOrEmpty(mainPhotoToDelete))
            {
                // delete the existing photos
                try
                {

                    if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, mainPhotoToDelete))
                    {
                        s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, mainPhotoToDelete);
                    }

                    if (s3.ObjectExists(AmazonCloudConfigs.AmazonBucketName, thumbPhotoToDelete))
                    {
                        s3.DeleteObject(AmazonCloudConfigs.AmazonBucketName, thumbPhotoToDelete);
                    }
                }
                catch
                {
                    // whatever
                }
            }

            Bitmap b = new Bitmap(file.InputStream);

            // full
            System.Drawing.Image fullPhoto = (System.Drawing.Image)b;

            fullPhoto = ImageResize.FixedSize(fullPhoto, 300, 300, System.Drawing.Color.Black);

            string fileNameFull = Utilities.CreateUniqueContentFilename(file);

            Stream maker = fullPhoto.ToAStream(ImageFormat.Jpeg);

            s3.AddObject(
                maker,
                maker.Length,
                AmazonCloudConfigs.AmazonBucketName,
                fileNameFull,
                file.ContentType,
                acl);

            if (string.IsNullOrEmpty(uad.ProfileThumbPicURL) ||
                ups.Count == 2 && photoEdited == photoOne)
            {
                uad.ProfilePicURL = fileNameFull;
            }
            else
            {
                if (up1 == null)
                {
                    up1 = new UserPhoto();
                }

                up1.UserAccountID = Convert.ToInt32(mu.ProviderUserKey);
                up1.PicURL = fileNameFull;

                if ((ups.Count > 0 && photoEdited == photoTwo) || (ups.Count == 0))
                {
                    up1.RankOrder = 1;
                }
                else if ((ups.Count > 1 && photoEdited == photoThree) || ups.Count == 1)
                {
                    up1.RankOrder = 2;
                }

                if (ups.Count == 1 && ups[0].RankOrder == 2)
                {
                    ups[0].RankOrder = 1;
                    ups[0].Update();
                }
            }

            fullPhoto = (System.Drawing.Image)b;

            fullPhoto = ImageResize.FixedSize(fullPhoto, 75, 75, System.Drawing.Color.Black);

            fileNameFull = Utilities.CreateUniqueContentFilename(file);

            maker = fullPhoto.ToAStream(ImageFormat.Jpeg);

            s3.AddObject(
                maker,
                maker.Length,
                AmazonCloudConfigs.AmazonBucketName,
                fileNameFull,
                file.ContentType,
                acl);

            //// thumb

            if (string.IsNullOrEmpty(uad.ProfileThumbPicURL) ||
                ups.Count == 2 && photoEdited == photoOne)
            {
                uad.ProfileThumbPicURL = fileNameFull;
                uad.LastPhotoUpdate = DateTime.UtcNow;
                uad.Set();
            }
            else
            {
                up1.UserAccountID = Convert.ToInt32(mu.ProviderUserKey);
                up1.ThumbPicURL = fileNameFull;

                if (
                    (ups.Count == 0 && photoEdited == photoTwo) ||
                    (ups.Count > 0 && photoEdited == photoTwo)
                    )
                {
                    up1.RankOrder = 1;
                }
                else if
                    (
                    (ups.Count == 0 && photoEdited == photoThree) ||
                    (ups.Count > 1 && photoEdited == photoThree)
                    )
                {
                    up1.RankOrder = 2;
                }
            }

            b.Dispose();

            if (up1 != null && up1.UserPhotoID == 0)
            {
                up1.CreatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                up1.Create();
            }
            else if (up1 != null && up1.UserPhotoID > 0)
            {
                up1.UpdatedByUserID = Convert.ToInt32(mu.ProviderUserKey);
                up1.Update();
            }

            LoadCurrentImagesViewBag(Convert.ToInt32(mu.ProviderUserKey));

            return View(uad);
        }
Example #33
0
        private void LoadCurrentImagesViewBag(int userAccountID)
        {
            UserPhotos ups = new UserPhotos();
            ups.GetUserPhotos(userAccountID);

            if (ups.Count == 0)
            {
                UserPhoto up = new UserPhoto();
                ups.Add(up);
                up = new UserPhoto();
                ups.Add(up);
            }
            else if (ups.Count == 1)
            {
                UserPhoto up = new UserPhoto();
                up.RankOrder = 2;
                ups.Add(up);
            }

            ViewBag.SecondUserPhotoFull = ups[0].FullProfilePicURL;
            ViewBag.SecondUserPhotoThumb = ups[0].FullProfilePicThumbURL;
            ViewBag.SecondUserPhotoID = ups[0].UserPhotoID;

            ViewBag.ThirdUserPhotoFull = ups[1].FullProfilePicURL;
            ViewBag.ThirdUserPhotoThumb = ups[1].FullProfilePicThumbURL;
            ViewBag.ThirdUserPhotoID = ups[1].UserPhotoID;
        }
Example #34
0
        private void LoadCurrentImagesViewBag(int userAccountID)
        {
            UserPhotos ups = new UserPhotos();
            ups.GetUserPhotos(userAccountID);

            if (ups.Count == 0)
            {
                UserPhoto up = new UserPhoto();
                ups.Add(up);
                up = new UserPhoto();
                ups.Add(up);
            }
            else if (ups.Count == 1)
            {
                UserPhoto up = new UserPhoto();
                up.RankOrder = 2;
                ups.Add(up);
            }

            if (!string.IsNullOrWhiteSpace(ups[0].PicURL))
            {
                ViewBag.SecondUserPhotoFull = ups[0].FullProfilePicURL;
                ViewBag.SecondUserPhotoThumb = ups[0].FullProfilePicThumbURL;
            }

            if (!string.IsNullOrWhiteSpace(ups[1].PicURL))
            {
                ViewBag.ThirdUserPhotoFull = ups[1].FullProfilePicURL;
                ViewBag.ThirdUserPhotoThumb = ups[1].FullProfilePicThumbURL;
            }
        }
Example #35
0
        public void CreateUserPhoto()
        {
            var path = @"E:\Projects\SilverlightProject_2.0\Framework\Net\ZxdFramework.WebUI\Styles\lighttheme\Images\user.png";

            var f = new FileInfo(path);

            var photo = new UserPhoto
                            {
                                Owner = ServiceFactory.AuthorityService.AccountRepository.GetUser("Guest"),
                                Type = f.FullName.Substring(f.FullName.LastIndexOf(".")+1).ToLower(),
                                Data = (new System.IO.BinaryReader(f.Open(FileMode.Open))).ReadBytes((int)f.Length)
                            };

            ServiceFactory.AuthorityService.AccountRepository.UpdateOrSavePhoto(photo);

            path = @"E:\Projects\SilverlightProject_2.0\Framework\Net\ZxdFramework.WebUI\Styles\lighttheme\Images\admin.png";

            f = new FileInfo(path);

            photo = new UserPhoto
            {
                Owner = ServiceFactory.AuthorityService.AccountRepository.GetUser("Administrator"),
                Type = f.FullName.Substring(f.FullName.LastIndexOf(".")+1).ToLower(),
                Data = (new System.IO.BinaryReader(f.Open(FileMode.Open))).ReadBytes((int)f.Length)
            };

            ServiceFactory.AuthorityService.AccountRepository.UpdateOrSavePhoto(photo);
        }
Example #36
0
        private void LoadCurrentImagesViewBag(int userAccountID)
        {
            var ups = new UserPhotos();
            ups.GetUserPhotos(userAccountID);

            switch (ups.Count)
            {
                case 0:
                {
                    var up = new UserPhoto();
                    ups.Add(up);
                    up = new UserPhoto();
                    ups.Add(up);
                }
                    break;
                case 1:
                {
                    var up = new UserPhoto {RankOrder = 2};
                    ups.Add(up);
                }
                    break;
            }

            if (!string.IsNullOrWhiteSpace(ups[0].PicURL))
            {
                ViewBag.SecondUserPhotoFull = ups[0].FullProfilePicURL;
                ViewBag.SecondUserPhotoThumb = ups[0].FullProfilePicThumbURL;
            }

            if (string.IsNullOrWhiteSpace(ups[1].PicURL)) return;
            ViewBag.ThirdUserPhotoFull = ups[1].FullProfilePicURL;
            ViewBag.ThirdUserPhotoThumb = ups[1].FullProfilePicThumbURL;
        }
Example #37
0
        private void LoadCurrentImagesViewBag(int userAccountID)
        {
            var ups = new UserPhotos();
            ups.GetUserPhotos(userAccountID);

            switch (ups.Count)
            {
                case 0:
                {
                    var up = new UserPhoto();
                    ups.Add(up);
                    up = new UserPhoto();
                    ups.Add(up);
                }
                    break;
                case 1:
                {
                    var up = new UserPhoto {RankOrder = 2};
                    ups.Add(up);
                }
                    break;
            }

            ViewBag.SecondUserPhotoFull = ups[0].FullProfilePicURL;
            ViewBag.SecondUserPhotoThumb = ups[0].FullProfilePicThumbURL;
            ViewBag.SecondUserPhotoID = ups[0].UserPhotoID;

            ViewBag.ThirdUserPhotoFull = ups[1].FullProfilePicURL;
            ViewBag.ThirdUserPhotoThumb = ups[1].FullProfilePicThumbURL;
            ViewBag.ThirdUserPhotoID = ups[1].UserPhotoID;
        }
Example #38
0
        public ActionResult EditPhoto(HttpPostedFileBase file)
        {
            UserPhoto up1 = null;
            var currentUserId = Convert.ToInt32(_mu.ProviderUserKey);
            int swapID;
            const CannedAcl acl = CannedAcl.PublicRead;

            var s3 = new S3Service
            {
                AccessKeyID = AmazonCloudConfigs.AmazonAccessKey,
                SecretAccessKey = AmazonCloudConfigs.AmazonSecretKey
            };

            if (Request.Form["new_default"] != null &&
                int.TryParse(Request.Form["new_default"], out swapID))
            {
                // swap the default with the new default
                up1 = SwapOutDefaultPhoto(currentUserId, swapID);

                return View(_uad);
            }

            const string photoOne = "photo_edit_1";
            const string photoTwo = "photo_edit_2";
            const string photoThree = "photo_edit_3";

            if (_mu != null) LoadCurrentImagesViewBag(currentUserId);

            _uad = new UserAccountDetail();

            if (_mu != null) _uad.GetUserAccountDeailForUser(currentUserId);

            if (file == null)
            {
                ViewBag.IsValid = false;
                ModelState.AddModelError(string.Empty, Messages.NoFile);
                return View(_uad);
            }

            string photoEdited = Request.Form["photo_edit"];
            string rawPhotoToDelete = string.Empty;
            string mainPhotoToDelete = string.Empty;
            string thumbPhotoToDelete = string.Empty;

            _ups = new UserPhotos();
            _ups.GetUserPhotos(_uad.UserAccountID);

            if (string.IsNullOrEmpty(_uad.ProfilePicURL) ||
                _ups.Count == 2 && photoEdited == photoOne)
            {
                rawPhotoToDelete = _uad.RawProfilePicUrl;
                mainPhotoToDelete = _uad.ProfilePicURL;
                thumbPhotoToDelete = _uad.ProfileThumbPicURL;
            }
            else
            {
                if (_ups.Count > 1 && photoEdited == photoTwo)
                {
                    up1 = new UserPhoto(_ups[0].UserPhotoID) { RankOrder = 1 };

                    rawPhotoToDelete = up1.RawPicUrl;
                    mainPhotoToDelete = up1.PicURL;
                    thumbPhotoToDelete = up1.ThumbPicURL;
                }
                else if (_ups.Count > 1 && photoEdited == photoThree)
                {
                    up1 = new UserPhoto(_ups[1].UserPhotoID) { RankOrder = 2 };

                    rawPhotoToDelete = up1.RawPicUrl;
                    mainPhotoToDelete = up1.FullProfilePicURL;
                    thumbPhotoToDelete = up1.ThumbPicURL;
                }
            }

            if (!string.IsNullOrEmpty(mainPhotoToDelete))
            {
                DeletePhotos(s3, rawPhotoToDelete, mainPhotoToDelete, thumbPhotoToDelete);
            }

            var photoBitmap = new Bitmap(file.InputStream);

            // 300x 300 and raw
            up1 = ProcessMainPhotoItem(file, up1, currentUserId, acl, s3, photoOne, photoTwo, photoThree, photoEdited, photoBitmap);

            // 75 x 75 (thumbnail)
            var thumbFileName = AddPhotoToBucket(file, acl, s3, photoBitmap, true, 75, 75);

            if (string.IsNullOrEmpty(_uad.ProfileThumbPicURL) ||
                _ups.Count == 2 && photoEdited == photoOne)
            {
                _uad.ProfileThumbPicURL = thumbFileName;
                _uad.LastPhotoUpdate = DateTime.UtcNow;
                _uad.Set();
            }
            else
            {
                if (up1 != null)
                {
                    if (_mu != null) up1.UserAccountID = currentUserId;
                    up1.ThumbPicURL = thumbFileName;

                    if (
                        (_ups.Count == 0 && photoEdited == photoTwo) ||
                        (_ups.Count > 0 && photoEdited == photoTwo)
                        )
                    {
                        up1.RankOrder = 1;
                    }
                    else if
                        (
                        (_ups.Count == 0 && photoEdited == photoThree) ||
                        (_ups.Count > 1 && photoEdited == photoThree)
                        )
                    {
                        up1.RankOrder = 2;
                    }
                }
            }

            photoBitmap.Dispose();

            if (up1 != null && up1.UserPhotoID == 0)
            {
                if (_mu != null) up1.CreatedByUserID = currentUserId;
                up1.Create();
            }
            else if (up1 != null && up1.UserPhotoID > 0)
            {
                up1.UpdatedByUserID = currentUserId;
                up1.Update();
            }

            LoadCurrentImagesViewBag(currentUserId);

            return View(_uad);
        }
Example #39
0
        private UserPhoto SwapOutDefaultPhoto(int currentUserId, int swapID)
        {
            UserPhoto up1;
            _uad = new UserAccountDetail();
            if (_mu != null) _uad.GetUserAccountDeailForUser(currentUserId);

            string currentDefaultRaw = _uad.RawProfilePicUrl;
            string currentDefaultMain = _uad.ProfilePicURL;
            string currentDefaultMainThumb = _uad.ProfileThumbPicURL;

            up1 = new UserPhoto(swapID);

            _uad.RawProfilePicUrl = up1.RawPicUrl;
            _uad.ProfilePicURL = up1.PicURL;
            _uad.ProfileThumbPicURL = up1.ThumbPicURL;
            _uad.LastPhotoUpdate = DateTime.UtcNow;
            _uad.Update();

            up1.RawPicUrl = currentDefaultRaw;
            up1.PicURL = currentDefaultMain;
            up1.ThumbPicURL = currentDefaultMainThumb;

            if (_mu != null) up1.UpdatedByUserID = currentUserId;

            up1.Update();

            if (_mu != null) LoadCurrentImagesViewBag(currentUserId);
            return up1;
        }
Example #40
0
        private UserPhoto ProcessMainPhotoItem(
            HttpPostedFileBase file, 
            UserPhoto up1, 
            int currentUserId, 
            CannedAcl acl, 
            S3Service s3, 
            string photoOne, 
            string photoTwo, 
            string photoThree, 
            string photoEdited,
            Bitmap photoBitmap)
        {
            string rawPhotoFileName = AddPhotoToBucket(file, acl, s3, photoBitmap, false);
            string profilePhotoFileName = AddPhotoToBucket(file, acl, s3, photoBitmap, true, 300,  300);

            if (string.IsNullOrEmpty(_uad.ProfileThumbPicURL) ||
                _ups.Count == 2 && photoEdited == photoOne)
            {
                _uad.ProfilePicURL = profilePhotoFileName;
                _uad.RawProfilePicUrl = rawPhotoFileName;
            }
            else
            {
                if (up1 == null)
                {
                    up1 = new UserPhoto();
                }

                if (_mu != null) up1.UserAccountID = currentUserId;

                up1.RawPicUrl = rawPhotoFileName;
                up1.PicURL = profilePhotoFileName;

                if ((_ups.Count > 0 && photoEdited == photoTwo) || (_ups.Count == 0))
                {
                    up1.RankOrder = 1;
                }
                else if ((_ups.Count > 1 && photoEdited == photoThree) || _ups.Count == 1)
                {
                    up1.RankOrder = 2;
                }

                if (_ups.Count == 1 && _ups[0].RankOrder == 2)
                {
                    _ups[0].RankOrder = 1;
                    _ups[0].Update();
                }
            }

            return up1;
        }