public ProfilePicture GetProfilePicture(User user)
 {
     try
     {
         ProfilePicture profilePicture = new ProfilePicture();
         _connection.SqlConnection.Open();
         SqlCommand sqlCommand = new SqlCommand("GetProfilePicture", _connection.SqlConnection);
         sqlCommand.CommandType = CommandType.StoredProcedure;
         sqlCommand.Parameters.AddWithValue("@UserId", user.Id);
         sqlCommand.ExecuteNonQuery();
         using (SqlDataReader reader = sqlCommand.ExecuteReader())
         {
             while (reader.Read())
             {
                 if (!reader.IsDBNull(0))
                 {
                     profilePicture.Image = (byte[])reader["Data"];
                 }
             }
         }
         _connection.SqlConnection.Close();
         return(profilePicture);
     }
     catch (Exception)
     {
         throw new Exception("Had trouble connecting with the server.");
     }
 }
Esempio n. 2
0
 public ActionResult UploadImage(string fname, HttpPostedFileBase img)
 {
     if (Request.HttpMethod == "POST")
     {
         Validation_Classes.Validation v1 = new Validation();
         if (img != null)
         {
             if (v1.IsImageFormat(fname))
             {
                 LeaveBusinessLayer lb = new LeaveBusinessLayer();
                 Employee           e1 = (LeaveApplication.Models.Employee)Session["Employee"];
                 e1.ImageBytes = lb.GetFileBytes(img);
                 ProfilePicture p1 = new ProfilePicture()
                 {
                     Image = e1.ImageBytes
                 };
                 p1.Update(int.Parse(Session["EmpId"].ToString()));
                 return(Content("Successfully Uploaded"));
             }
             else
             {
                 return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Invalid image format"));
             }
         }
     }
     return(View());
 }
Esempio n. 3
0
        public ProfilePicture getProfilePicture(int userId)
        {
            ProfilePicture  profilePicture   = null;
            string          connectionString = config.GetConnectionString("DefaultConnection");
            MySqlConnection conn             = new MySqlConnection(connectionString);
            MySqlCommand    mySqlCommand     = new MySqlCommand();

            try
            {
                conn.Open();
                mySqlCommand.Connection  = conn;
                mySqlCommand.CommandText = "get_profile_picture";
                mySqlCommand.CommandType = CommandType.StoredProcedure;
                mySqlCommand.Parameters.Add(new MySqlParameter("_user_id", userId));
                MySqlDataReader reader = mySqlCommand.ExecuteReader();
                while (reader.Read())
                {
                    profilePicture = getProfilePictureFromReader(reader);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return(profilePicture);
        }
Esempio n. 4
0
        public void DeletePicture(int id)
        {
            ProfilePicture picture = _db.ProfilePicture.Find(id);

            _db.ProfilePicture.Remove(picture);
            _db.SaveChanges();
        }
Esempio n. 5
0
        public string SetProfilePicture(ProfilePicture profilePicture)
        {
            Employee employee = _db.Employees.FirstOrDefault(c => c.Id == profilePicture.EntityId);

            if (employee == null)
            {
                throw new TranslatableException("EC9", profilePicture.EntityId.ToString());
            }

            string fileName = employee.Name + ".png";

            if (CloudStorageAccount.TryParse(_configuration[Constants.BlobStorageConnectionString], out CloudStorageAccount storageAccount))
            {
                CloudBlobClient    cloudBlobClient    = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_configuration[Constants.BlobStorageEmployeeProfilePictureContainer]);
                CloudBlockBlob     cloudBlockBlob     = cloudBlobContainer.GetBlockBlobReference(fileName);
                using (Stream profilePictureStream = profilePicture.File.OpenReadStream())
                {
                    cloudBlockBlob.UploadFromStreamAsync(profilePictureStream)
                    .GetAwaiter()
                    .GetResult();
                }
                employee.HasProfilePicture = true;

                return(fileName);
            }
            else
            {
                throw new TranslatableException("EC11");
            }
        }
        public async Task <UserDto> GetUser(string chatApiKey, string battleTag)
        {
            var user = await LoadFirst <ChatUser>(c => c.ApiKey == chatApiKey);

            var userClan = await LoadFirst <ClanMembership>(c => c.Id == battleTag);

            var userSettings = await LoadFirst <PersonalSetting>(c => c.Id == battleTag);

            if (user != null)
            {
                return(new UserDto(
                           user.Name,
                           user.BattleTag,
                           userClan?.ClanId,
                           userSettings?.ProfilePicture ?? ProfilePicture.Default(),
                           true));
            }
            user = new ChatUser(battleTag);
            return(new UserDto(
                       user.Name,
                       user.BattleTag,
                       userClan?.ClanId,
                       userSettings?.ProfilePicture ?? ProfilePicture.Default(),
                       false));
        }
        //Service To change Profile Picture.
        public async Task Upload(ProfilePicture input)
        {
            long size = 0;

            foreach (var file in input.F)
            {
                var filename = ContentDispositionHeaderValue
                               .Parse(file.ContentDisposition)
                               .FileName
                               .Trim('"');
                var c = "/images/" + filename;
                filename = _hostingEnv.WebRootPath + $@"\images\{filename}";
                size    += file.Length;

                /* var db = new ProfilePicture();
                 * db.ImagePath = c;
                 * db.ProfileId = (long)AbpSession.UserId;
                 */
                ProfileAttachment update = _profileAttachment.FirstOrDefault(cc => cc.ProfileId == input.ProfileId);
                update.ImagePath = c;
                update.ProfileId = 10008;
                using (var stream = new FileStream(filename, FileMode.Create))
                {
                    await file.CopyToAsync(stream);

                    await _profileAttachment.UpdateAsync(update);
                }
            }
        }
        public ProfilePicture RemoveFromPictureId(string pictureId)
        {
            ProfilePicture pfpLoaded = _profilePictures.Find(pfpQuery => pfpQuery.Id.Equals(pictureId)).FirstOrDefault();

            _profilePictures.DeleteOne(pfp => pfp.Id.Equals(pictureId));
            return(pfpLoaded);
        }
Esempio n. 9
0
        public async Task AddPictureAsync(string imagePath, string userId)
        {
            byte[] imageByteArray = null;
            using FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
            using BinaryReader reader   = new BinaryReader(fileStream);
            imageByteArray = new byte[reader.BaseStream.Length];
            for (int i = 0; i < reader.BaseStream.Length; i++)
            {
                imageByteArray[i] = reader.ReadByte();
            }

            var photo = new ProfilePicture()
            {
                Id         = Guid.NewGuid().ToString(),
                UploadDate = DateTime.UtcNow,
                Content    = imageByteArray,
                Size       = imageByteArray.Length,
                UserId     = userId,
            };

            if (this.repository.All().Any(x => x.UserId == userId))
            {
                this.repository.Delete(this.repository.All().First(x => x.UserId == userId));
            }

            await this.repository.AddAsync(photo);

            await this.repository.SaveChangesAsync();
        }
Esempio n. 10
0
        public async Task <bool> AddPictureAsync(IFormFile file, string userId)
        {
            using (var memoryStream = new MemoryStream())
            {
                await file.CopyToAsync(memoryStream);

                // Upload the file if less than 2 MB
                if (memoryStream.Length < 2097152)
                {
                    var photo = new ProfilePicture()
                    {
                        Id         = Guid.NewGuid().ToString(),
                        UploadDate = DateTime.UtcNow,
                        Content    = memoryStream.ToArray(),
                        Size       = memoryStream.Length,
                        UserId     = userId,
                    };

                    if (this.repository.All().Any(x => x.UserId == userId))
                    {
                        this.repository.Delete(this.repository.All().First(x => x.UserId == userId));
                    }

                    await this.repository.AddAsync(photo);

                    await this.repository.SaveChangesAsync();

                    return(true);
                }
            }

            return(false);
        }
        public ActionResult ProfilePage()
        {
            var userId = from a in db.UserInfos
                         where a.email == User.Identity.Name
                         select a.userId;
            int temporaryUserId = 0;

            foreach (var item in userId)
            {
                temporaryUserId = item;
            }
            List <ProfilePicture> images = GetImages();

            ProfilePicture imageFile = new ProfilePicture();

            foreach (var item in images)
            {
                if (item.userId == temporaryUserId)
                {
                    imageFile = item;
                }
            }
            ViewBag.Base64String = "data:image/png;base64," + Convert.ToBase64String(imageFile.profileImage, 0, imageFile.profileImage.Length);

            ViewData["userInfo"] = GetUserInfo();
            return(View());
        }
Esempio n. 12
0
        public void SetProfilePicture(ProfilePicture profilePicture)
        {
            // Feature disabled.

            //Client client = _db.Clients.FirstOrDefault(c => c.Id == profilePicture.EntityId);
            //if (client == null)
            //{
            //    throw new TranslatableException("EC9", profilePicture.EntityId.ToString());
            //}

            //string fileName = client.Name + ".png";
            //if (CloudStorageAccount.TryParse(_configuration[Constants.BlobStorageConnectionString], out CloudStorageAccount storageAccount))
            //{
            //    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            //    CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(_configuration[Constants.BlobStorageClientProfilePictureContainer]);
            //    CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
            //    using (Stream profilePictureStream = profilePicture.File.OpenReadStream())
            //    {
            //        cloudBlockBlob.UploadFromStreamAsync(profilePictureStream)
            //            .GetAwaiter()
            //            .GetResult();
            //    }
            //    client.HasProfilePicture = true;
            //}
            //else
            //{
            //    throw new TranslatableException("EC11");
            //}
        }
Esempio n. 13
0
        // POST: api/ProfilePicture
        public async Task <IHttpActionResult> Post(ProfilePicture profilePicture)
        {
            if (profilePicture.UserId != User.Identity.GetUserId())
            {
                return(StatusCode(HttpStatusCode.Forbidden));
            }
            var dataUri = new DataUri(profilePicture.Data);

            if (!dataUri.IsSupported)
            {
                return(BadRequest());
            }

            var objectName = String.Format("{0}.{1}", profilePicture.UserId, dataUri.Format);
            var finalUrl   = @"https://s3-ap-southeast-2.amazonaws.com/meet.u/ProfilePictures/" + objectName;
            var deferred   = Task
                             .Factory
                             .StartNew(
                () =>
                UploadToS3Async(profilePicture.UserId, dataUri, objectName)
                );
            await deferred
            .ContinueWith(
                d =>
                UpdateProfileTableAsync(profilePicture.UserId, finalUrl), TaskContinuationOptions.OnlyOnRanToCompletion
                );

            return(Ok(finalUrl));
        }
Esempio n. 14
0
        /// <summary>
        /// Asynchronously put a recognition item into queue
        /// </summary>
        public async Task Enqueue(IList <RecognitionItem> recognitionItems)
        {
            // Write work items
            foreach (var recognitionItem in recognitionItems)
            {
                // Gets recognized person
                var person = recognitionItem.Person;

                if (person != null)
                {
                    // add or update visit for person
                    _unit.VisitsRepository.AddOrUpdateVisit(person, recognitionItem.DateOfRecognition);
                    // Create a new profile picture
                    ProfilePicture newPicture = _unit.ProfilePicturesRepository.CreateProfilePicture
                                                    (person.PersonApiId, recognitionItem.ImageUrl, recognitionItem.Face, recognitionItem.Confidence);

                    person.Visits.Last().ProfilePictures.Add(newPicture);

                    // Update person's statistics
                    person.UpdateAge(recognitionItem.Face.FaceAttributes.Age);
                    person.UpdateGender(GenderValuesHelper.Parse(recognitionItem.Face.FaceAttributes.Gender));

                    _unit.PersonRepository.Update(person);

                    // Updates recognition item
                    recognitionItem.ProfilePictureId = newPicture.Id;
                }

                _unit.RecognitionItemsRepository.Insert(recognitionItem);
                await _unit.SaveAsync();
            }
        }
 public IActionResult Overview(User user)
 {
     if (HttpContext.Session.GetInt32("Id") == null)
     {
         return(RedirectToAction("Login", "Account"));
     }
     else
     {
         user.Id = (int)HttpContext.Session.GetInt32("Id");
         _userLogic.GetUserDetails(user);
         ProfilePicture   profilePicture   = _profilePictureLogic.GetProfilePicture(user);
         ProfileViewModel profileViewModel = new ProfileViewModel()
         {
             Id         = user.Id,
             Firstname  = user.Firstname,
             Middlename = user.Middlename,
             Lastname   = user.Lastname,
             Birthdate  = user.Birthdate,
             Country    = user.Country,
             City       = user.City,
             Biography  = user.Biography,
             Img        = profilePicture.Image,
         };
         profileViewModel.Posts = new List <Post>();
         profileViewModel.Posts.AddRange(_postLogic.GetPost(user));
         profileViewModel.Followers = new List <User>();
         profileViewModel.Followers.AddRange(_userLogic.GetFollowers(user));
         profileViewModel.Following = new List <User>();
         profileViewModel.Following.AddRange(_userLogic.GetFollowing(user));
         return(View(profileViewModel));
     }
 }
        public void EqualOperator_WithUnequalInput_ReturnsFalse()
        {
            ProfilePicture A = profilePictureFixture;
            ProfilePicture B = new ProfilePicture();

            Expect(() => A == B, Is.False);
        }
Esempio n. 17
0
        public ActionResult ProfilePicture(ProfilePicture pic, HttpPostedFileBase File)
        {
            ph.Add_Profile_Picture(pic, File, PhotoGrapherID);

            return(RedirectToAction("ProfilePicture", "PhotoGrapher"));
            //return View();
        }
        public void Equals_IsNotEqual_Fails()
        {
            ProfilePicture A = profilePictureFixture;
            ProfilePicture B = new ProfilePicture();

            Expect(A.Equals(B), Is.False);
        }
        public void EqualOperator_WithEqualInput_ReturnsTrue()
        {
            ProfilePicture A = profilePictureFixture;
            ProfilePicture B = profilePictureFixture;

            Expect(() => A == B, Is.True);
        }
        public void UnequalOperator_WithEqualInput_ReturnsFalse()
        {
            ProfilePicture A = new ProfilePicture();
            ProfilePicture B = new ProfilePicture();

            Expect(() => A != B, Is.False);
        }
        public void Equals_IsEqual_Passes()
        {
            ProfilePicture A = profilePictureFixture;
            ProfilePicture B = profilePictureFixture;

            Expect(A.Equals(B), Is.True);
        }
        public void EqualOperator_WithNullInput_ReturnsFalse()
        {
            ProfilePicture A = null;
            ProfilePicture B = new ProfilePicture();

            Expect(() => A == B, Is.False);
        }
        public void UnequalOperator_WithUnequalInput_ReturnsTrue()
        {
            ProfilePicture A = profilePictureFixture;
            ProfilePicture B = new ProfilePicture();

            Expect(() => A != B, Is.True);
        }
Esempio n. 24
0
        private async Task SaveProfilePicture(User user)
        {
            var folderPath = this._environment.WebRootPath + "/img/profiles/";

            Directory.CreateDirectory(folderPath);

            using (var stream = System.IO.File.OpenWrite(_environment.WebRootPath + $"/img/profiles/{user.Id}.jpg"))
            {
                await Input.ProfilePicture.CopyToAsync(stream);
            }


            var entity = new ProfilePicture
            {
                Name        = Input.ProfilePicture.FileName,
                ContentType = Input.ProfilePicture.ContentType,
                Size        = Input.ProfilePicture.Length,
                PathToFile  = $"/img/profiles/{user.Id}.jpg",
                UserId      = user.Id
            };

            await _picturesRepository.AddAsync(entity);

            await _picturesRepository.SaveChangesAsync();
        }
        //Event Save data filter
        private void TxtSaveOnClick(object sender, EventArgs e)
        {
            try
            {
                var dbDatabase        = new SqLiteDatabase();
                var newSettingsFilter = new DataTables.SearchFilterTB
                {
                    UserId         = UserDetails.User_id,
                    Gender         = Gender,
                    ProfilePicture = ProfilePicture,
                    Status         = Status
                };
                dbDatabase.InsertOrUpdate_SearchFilter(newSettingsFilter);
                dbDatabase.Dispose();

                // put the String to pass back into an Intent and close this activity
                var resultIntent = new Intent();
                resultIntent.PutExtra("gender", Gender.ToString());
                resultIntent.PutExtra("profilePicture", ProfilePicture.ToString());
                resultIntent.PutExtra("status", Status.ToString());
                SetResult(Result.Ok, resultIntent);
                Finish();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
        }
Esempio n. 26
0
        private void SaveImageNameToDb(ClaimsPrincipal user, string imagePath)
        {
            var userId = userManager.GetUserId(user);
            var currentProfilePicture = profilePicturesRepository.All().FirstOrDefault(x => x.UserId == userId);

            while (currentProfilePicture != null)
            {
                profilePicturesRepository.Delete(currentProfilePicture);
                profilePicturesRepository.SaveChangesAsync().GetAwaiter().GetResult();
                currentProfilePicture = profilePicturesRepository.All().FirstOrDefault(x => x.UserId == userId);
            }

            var newProfilePic = new ProfilePicture
            {
                FileName = imagePath,
                UserId   = userId,
            };

            profilePicturesRepository.AddAsync(newProfilePic).GetAwaiter().GetResult();

            var userProfilePicToChange = userManager.GetUserAsync(user).GetAwaiter().GetResult();

            profilePicturesRepository.SaveChangesAsync().GetAwaiter().GetResult();

            userProfilePicToChange.ProfilePictureId = newProfilePic.Id;

            userRepository.SaveChangesAsync().GetAwaiter().GetResult();
        }
Esempio n. 27
0
        private void UserDataDownloadWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var result         = e.Result as Object[];
                var profile        = (JObject)result[0];
                var totals         = (JObject)result[1];
                var isFemale       = (Char)result[2] == 'f';
                var profilePicture = result[3] as Image;

                if (profilePicture == null)
                {
                    ProfilePicture.BackgroundImage = isFemale
                        ? Resources.ProfileNoPicture_Female
                        : Resources.ProfileNoPicture_Male;
                }
                else
                {
                    ProfilePicture.BackgroundImage = profilePicture;
                }

                ProfilePicture.Invalidate();

                ProfileName.Text          = (String)profile["Name"] + " " + (String)profile["LastName"];
                ProfileLocation.Text      = ((String)profile["RegionCode"]).ToUpper();
                ProfileTotalDistance.Text = ((Int32)((Double)totals["TotalDistance"] / 1000)).ToString() + " KMS";

                MainWindow.Instance.HideLoadingPanel();
            }
            else
            {
                throw e.Error;
            }
        }
Esempio n. 28
0
        public async Task SetProfilePictureAsync(string userId, byte[] picture, string pictureExtension, string picturePath)
        {
            bool isInitialInstance = false;

            var pictureData = this.profilePicturesRepository.All().FirstOrDefault(u => u.UserId == userId);

            if (pictureData != null)
            {
                this.filesService.DeleteFile(picturePath, pictureData.Id, pictureData.Extension);
            }
            else
            {
                pictureData = new ProfilePicture
                {
                    UserId = userId,
                };

                isInitialInstance = true;
            }

            pictureData.Extension = pictureExtension;

            await this.filesService.SaveFileAsync(picture, picturePath, pictureData.Id, pictureExtension);

            if (isInitialInstance)
            {
                await this.profilePicturesRepository.AddAsync(pictureData);
            }

            await this.profilePicturesRepository.SaveChangesAsync();
        }
        private JsonResult saveProfilePicture(ProfilePicture profilePicture, string command)
        {
            Response response = new Response();
            ProfilePictureDataHandler profilePictureDataHandler = new ProfilePictureDataHandler(config);

            //main code
            return(Json(response));
        }
Esempio n. 30
0
        public async Task <bool> AddProfilePicture(AppUser user, ProfilePicture picture)
        {
            user.ProfilePicture = picture;

            await _dataContext.SaveChangesAsync();

            return(true);
        }