Ejemplo n.º 1
0
        public async Task <IActionResult> PostImage(string id, IFormFile file)
        {
            var hasScope = User.HasRequiredScopes(WritePermission);

            if (!hasScope)
            {
                return(Unauthorized());
            }

            var owner = User.CheckClaimMatch(ObjectIdElement);

            if (owner != id)
            {
                return(Forbid());
            }

            if (file == null || file.Length == 0)
            {
                return(NoContent());
            }

            ProfileImage savedImage = null;

            using (var ms = new MemoryStream())
            {
                await file.CopyToAsync(ms);

                savedImage = await _profilesManager.UploadProfileImage(id, file.FileName, ms.ToArray());
            }
            return(Ok(savedImage));
        }
Ejemplo n.º 2
0
        public void Test_CreateUpdateDeleteProfileImageFile()
        {
            IUserBasic userBasic = Test_WorkmateMembershipProvider.CreateUser(this.DataStore, Workmate.Components.InstanceContainer.ApplicationSettings, this.Application, this.DummyDataManager);

            ProfileImageManager manager = new ProfileImageManager(this.DataStore);
            ProfileImage        record  = Test_ProfileImages.CreateProfileImage(this.DataStore, this.Application.ApplicationId, userBasic, this.Random);

            ProfileImage recordToCompare;

            for (int i = 0; i < this.DefaultUpdateTestIterations; i++)
            {
                PopulateWithRandomValues(record, this.DummyDataManager, this.Random);
                recordToCompare = record;

                manager.Update(record);
                record = manager.GetProfileImage(record.ImageId);

                string errors = string.Empty;
                // TODO (Roman): relax datetime comparisons
                Assert.IsTrue(DebugUtility.ArePropertyValuesEqual(record, recordToCompare, out errors), errors);
                Trace.WriteLine("Update test successfull.");
            }

            Delete(this.DataStore, record);
        }
Ejemplo n.º 3
0
        void ReleaseDesignerOutlets()
        {
            if (BigLabel != null)
            {
                BigLabel.Dispose();
                BigLabel = null;
            }

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

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

            if (SmallLabel != null)
            {
                SmallLabel.Dispose();
                SmallLabel = null;
            }
        }
        void ReleaseDesignerOutlets()
        {
            if (lblDuration != null)
            {
                lblDuration.Dispose();
                lblDuration = null;
            }

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

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

            if (SepratorView != null)
            {
                SepratorView.Dispose();
                SepratorView = null;
            }
        }
Ejemplo n.º 5
0
        public async Task Create(CreateUserRequestModel model)
        {
            await new CreateUserValidator().ValidateRequestModelAndThrow(model);

            User user = new User(model.Name, model.Email, model.Password);

            await ThrowIfUserNameAlreadyExists(user.Name);
            await ThrowIfUserEmailAlreadyExists(user.Email);


            user.UpdateConfirmationCode(_randomCodeUtils.GenerateRandomCode());
            user.UpdatePassword(_hashUtils.GenerateHash(user.Password));

            Stream  userDefaultProfileImage = _fileUploadUtils.GetDefaultUserProfileImage();
            FileDTO uploadedProfileImage    = await _fileUploadUtils.UploadImage(userDefaultProfileImage);

            ProfileImage image = new ProfileImage(uploadedProfileImage.FileName, uploadedProfileImage.FilePath);

            user.AddProfileImage(image);
            await _userRepository.Create(user);

            await _userRepository.Save();

            await _emailUtils.SendEmail(user.Email, "Confirmation", $"Please confirm your account using this code {user.ConfirmationCode}");
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> OnPostUploadAsync()
        {
            var chatUser = await _userManager.GetUserAsync(User);

            if (ProfileImage.Length < 10485760L)              //10 MB
            {
                if (!ProfileImage.ValidateFileTypeAsImage())
                {
                    ModelState.AddModelError("File", "Invalid file type.");
                }
                else
                {
                    using Stream memoryStream = ProfileImage.OpenReadStream();
                    Image image = Image.FromStream(memoryStream).ResizeImageToFitSquare(512);

                    string output = _fileOperationProvider.SaveImageToFile(image, ProfileImage.Name);
                    _fileOperationProvider.DeleteFile(chatUser.ProfileImage);
                    chatUser.ProfileImage = output;
                    await _context.SaveChangesAsync();
                }
            }
            else
            {
                ModelState.AddModelError("File", "The file is too large.");
            }

            return(Page());
        }
Ejemplo n.º 7
0
        public async Task Command(ulong?id = null)
        {
            id ??= Context.User.Id;

            User user = await DatabaseQueries.GetOrCreateUserAsync(Context.User.Id);

            if (id != Context.User.Id && !user.IsBotOwner)
            {
                await SendBasicErrorEmbedAsync("Only bot owners can display other people's profiles. Please " +
                                               "use this command without a parameter.");

                return;
            }

            Server server = await DatabaseQueries.GetOrCreateServerAsync(Context.Guild.Id);

            if (id != Context.User.Id)
            {
                user = await DatabaseQueries.GetOrCreateUserAsync(id.Value);
            }

            using (Context.Channel.EnterTypingState())
            {
                var    p     = new ProfileImage();
                Stream image = await p.GenerateProfileImageStream(user, server, Context.Guild.GetUser(id.Value));

                await Context.Channel.SendFileAsync(image, "Kaguya_Profile_" +
                                                    $"{Context.User.Username}_{DateTime.Now.Month}_" +
                                                    $"{DateTime.Now.Day}_{DateTime.Now.Year}.png");
            }
        }
Ejemplo n.º 8
0
        //delete image
        public void Delete(int id)
        {
            ProfileImage image = _db.ProfileImages.Find(id);

            _db.ProfileImages.Remove(image);
            _db.SaveChanges();
        }
Ejemplo n.º 9
0
        // PUT api/<controller>/5
        public IHttpActionResult UpdateProfileImage(ProfileImage request)
        {
            UserResponse objResponse = new UserResponse();

            try
            {
                objResponse = objUserService.UpdateProfileImage(request);
                if (objResponse != null && objResponse.UserId > 0)
                {
                    return(Ok <APIResponse>(new APIResponse(true, objResponse, "Profile picture successfully.")));
                }
                else if (objResponse.UserId == 0)
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new APIResponse(false, objResponse, "Password  picture update failed."))));
                }
                else
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.ExpectationFailed, objResponse)));
                }
            }
            catch (Exception ex)
            {
                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new APIResponse(false, objResponse, "Unexpected error occured."))));
            }
        }
Ejemplo n.º 10
0
        void ReleaseDesignerOutlets()
        {
            if (ProfileImage != null)
            {
                ProfileImage.Dispose();
                ProfileImage = null;
            }

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

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

            if (Detail != null)
            {
                Detail.Dispose();
                Detail = null;
            }
        }
Ejemplo n.º 11
0
        public bool CheckUploadedImage()
        {
            string srcValue = ProfileImage.GetAttribute("src");

            //I use StartWith because when student choose its photo, he can choose defined area in photo
            return(srcValue.StartsWith("data"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// starts the animation if the mouse hovers over the profile picture and the <see cref="HamburgerMenu"/> is not already opened or is not animating
        /// </summary>
        /// <param name="sender">sender of the event</param>
        /// <param name="e">mouse information</param>
        private void ProfileIconContainer_MouseEnter(object sender, MouseEventArgs e)
        {
            if (!isOpen && animFinished)
            {
                isOpen       = true;
                animFinished = false;

                GridLengthAnimation gridAnim = new GridLengthAnimation
                {
                    From     = new GridLength(PictureSizeSmall, GridUnitType.Pixel),
                    To       = new GridLength(PictureSizeBig, GridUnitType.Pixel),
                    Duration = AnimationDuration
                };

                DoubleAnimation doubleAnim = new DoubleAnimation
                {
                    From     = PictureSizeSmall,
                    To       = PictureSizeBig,
                    Duration = AnimationDuration
                };

                gridAnim.Completed += animationCompleted;
                MainGrid.ColumnDefinitions[0].BeginAnimation(ColumnDefinition.WidthProperty, gridAnim);
                ProfileImage.BeginAnimation(Ellipse.HeightProperty, doubleAnim);
                ProfileImage.BeginAnimation(Ellipse.WidthProperty, doubleAnim);

                ProfileName.Visibility = Visibility.Visible;
            }
        }
Ejemplo n.º 13
0
        public async Task <IHttpActionResult> PutProfileImage(string id, ProfileImage profileImage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != profileImage.UserId)
            {
                return(BadRequest());
            }

            db.Entry(profileImage).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProfileImageExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 14
0
        public ActionResult DragUpload(IEnumerable <HttpPostedFileBase> pictureFiles)
        {
            //TODO
            string pathToSave = null;

            foreach (var pictureFile in pictureFiles)
            {
                if (null == pictureFile || pictureFile.ContentLength == 0)
                {
                    continue;
                }
                pathToSave = Path.Combine(
                    AppDomain.CurrentDomain.BaseDirectory,
                    Path.GetFileName(pictureFile.FileName));
                //pictureFile.SaveAs(pathToSave);

                //for now just do 1...
                break;
            }
            var img = new ProfileImage()
            {
                //as test, ignore path &hard-code this
                ImageData = System.IO.File.ReadAllBytes("~/images/darth.png")
            };

            return(View("DragUpload", img));
        }
Ejemplo n.º 15
0
        public ActionResult cropped_img(ProfileImage profileImage)
        {
            string user_id = profileImage.user_id;
            string base64  = profileImage.img_data;

            byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);

            string file_name = "profileimg.png";
            string savedurl  = "/images/uploads/" + user_id;

            bool exists = Directory.Exists(Server.MapPath(savedurl));

            if (!exists)
            {
                Directory.CreateDirectory(Server.MapPath(savedurl));
                Directory.GetAccessControl(Server.MapPath(savedurl));
            }
            try
            {
                using (FileStream stream = new FileStream(Server.MapPath(savedurl + "/" + file_name), FileMode.Create))
                {
                    stream.Write(bytes, 0, bytes.Length);
                    stream.Flush();
                }
                db.Database.ExecuteSqlCommand("update AspNetUsers set image='" + savedurl + "/" + file_name + "' where Id='" + user_id + "'");
                return(Json(new { message = "Image successfully uploaded.", SavedUrl = savedurl + "/" + file_name }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exc)
            {
                return(Json(new { message = exc.GetBaseException().ToString() }, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 16
0
 public async Task<Guid> SetProfileImage(User user, IFormFile formFile)
 {
     var images = (await this.databaseContext.Users.Include(x => x.Icons)
         .FirstOrDefaultAsync(x => x.Id == user.Id)).Icons;
     ProfileImage profileImage;
     await using (MemoryStream ms = new MemoryStream())
     {
         await formFile.CopyToAsync(ms);
         profileImage = new ProfileImage()
         {
             IsActive = true,
             BLOB = new BLOB()
             {
                 Data = ms.ToArray()
             },
             ContentType = formFile.ContentType,
             FileName = formFile.FileName,
             FileSize = formFile.Length,
             User = user
         };
     }
     images.ForEach(x => x.IsActive = false);
     images.Add(profileImage);
     //await this.databaseContext.ProfileImages.AddAsync(profileImage);
     await this.databaseContext.SaveChangesAsync();
     return profileImage.Id;
 }
Ejemplo n.º 17
0
        public async Task <IHttpActionResult> PostProfileImage(ProfileImage profileImage)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.ProfileImages.Add(profileImage);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (ProfileImageExists(profileImage.UserId))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = profileImage.UserId }, profileImage));
        }
        public ReplaceOneResult AddImage(string galleryId, ProfileImage image)
        {
            var gallery = collection.Find(g => g.Id == galleryId).FirstOrDefault();

            gallery.Images.Add(image);
            return(collection.ReplaceOne(g => g.Id == galleryId, gallery));
        }
        public void UpdateCell(NotificationTableItemModel data)
        {
            if (data.Image == null && data.MesaageCount == null)
            {
                ProfileImage.RemoveFromSuperview(); //remove cotroll with space
                btnCount.Hidden     = true;         //hides the controll but keeps the space
                lblName.Text        = data.Name;
                lblDescription.Text = data.Description;
                lblDuration.Text    = data.Duration;
                //lblName.LeadingAnchor.ConstraintEqualTo(ProfileImage.LeadingAnchor,10f).Active=true;
            }
            else
            {
                ProfileImage.Image  = UIImage.FromFile(data.Image);
                lblName.Text        = data.Name;
                lblDescription.Text = data.Description;
                lblDuration.Text    = data.Duration;
                btnCount.SetTitle(data.MesaageCount, UIControlState.Normal);

                CALayer profileImageCircle = ProfileImage.Layer;
                profileImageCircle.CornerRadius = 34;
                //profileImageCircle.BorderColor = UIColor.FromRGB(98, 107, 186).CGColor;
                //profileImageCircle.BorderWidth = 3;
                profileImageCircle.MasksToBounds = true;
            }
        }
Ejemplo n.º 20
0
        public ActionResult DeleteLogo()
        {
            var image = new ProfileImage();

            Session["ImageSrc"] = null;
            return(PartialView("_UploadLogo", image));
        }
Ejemplo n.º 21
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName       = model.Email,
                    Email          = model.Email,
                    DriversLicense = model.DriversLicense,
                    PhoneNumber    = model.PhoneNumber,
                    FirstName      = model.FirstName,
                    LastName       = model.LastName,
                    OrganizationId = model.OrganizationId
                };

                var userProfImage = _context.ProfileImages.SingleOrDefault(pi => pi.User.Email == model.Email);



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



                if (result.Succeeded)
                {
                    //To set everyone as Normal Users
                    var roleStore   = new RoleStore <IdentityRole>(new ApplicationDbContext());
                    var roleManager = new RoleManager <IdentityRole>(roleStore);
                    await roleManager.CreateAsync(new IdentityRole(RoleName.NormalUsers));

                    await UserManager.AddToRoleAsync(user.Id, RoleName.NormalUsers);


                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    if (userProfImage == null)
                    {
                        var profileImage = new ProfileImage
                        {
                            UserId = _context.Users.Single(u => u.Email == model.Email).Id,
                            Path   = "~/Image/Avatar.jpg",
                        };
                        _context.ProfileImages.Add(profileImage);
                        _context.SaveChanges();
                    }

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

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public void UpdateCell(Contact contact, int position)
        {
            switch (position)
            {
            case 0:
                lblContactPersonName.Text = "New Group";
                ProfileImage.Image        = new UIImage("addGroup.png");
                break;

            default:
                if (contact != null)
                {
                    CommonHelper.SetCircularImage(ProfileImage);
                    lblContactPersonName.Text = contact.name;
                    if (!string.IsNullOrEmpty(contact.contactPicUrl))
                    {
                        ProfileImage.SetImage(new NSUrl(contact.contactPicUrl), UIImage.FromBundle("default_profile.png"));
                    }
                    else
                    {
                        ProfileImage.Image = new UIImage("default_profile.png");
                    }
                }
                break;
            }
        }
Ejemplo n.º 23
0
        public void TestPersonsImages()
        {
            // Get config
            _config.Client.GetConfig();

            // Get images
            ProfileImages images = _config.Client.GetPersonImages(BruceWillis);

            Assert.IsNotNull(images);
            Assert.IsNotNull(images.Profiles);
            Assert.AreEqual(BruceWillis, images.Id);

            // Test image url generator
            TestImagesHelpers.TestImages(_config, images);

            ProfileImage image = images.Profiles.SingleOrDefault(s => s.FilePath == "/kI1OluWhLJk3pnR19VjOfABpnTY.jpg");

            Assert.IsNotNull(image);
            Assert.IsTrue(Math.Abs(0.666666666666667 - image.AspectRatio) < double.Epsilon);
            Assert.AreEqual("/kI1OluWhLJk3pnR19VjOfABpnTY.jpg", image.FilePath);
            Assert.AreEqual(1500, image.Height);
            Assert.IsNull(image.Iso_639_1);
            Assert.AreEqual(1000, image.Width);
            Assert.IsTrue(image.VoteAverage > 0);
            Assert.IsTrue(image.VoteCount > 0);
        }
Ejemplo n.º 24
0
        public void GetAndSet_ShouldBePublic()
        {
            var profileImage = new ProfileImage();

            profileImage.UserId = 1;

            Assert.True(profileImage.UserId == 1);
        }
Ejemplo n.º 25
0
 public HomeViewModel(IEnumerable <Inspection> inspection, ApplicationUser user, IEnumerable <SafetyNews> safetyNews, ILookup <int, Like> like, ProfileImage profileImage)
 {
     Inspection       = inspection;
     User             = user;
     ListOfSafetyNews = safetyNews;
     Like             = like;
     ProfileImage     = profileImage;
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Updates the specified profile image.
 /// </summary>
 /// <param name="profileImage">The profile image.</param>
 /// <returns></returns>
 public BusinessObjectActionReport <DataRepositoryActionStatus> Update(ProfileImage profileImage)
 {
     if (profileImage.IsSystemProfileImage)
     {
         throw new ArgumentException("It is not allowed to update a  profile image via the ProfileImageManager.Update method. Use SystemProfileManager.Update instead.");
     }
     return(_CMSFileManager.Update(profileImage.CMSFile));
 }
Ejemplo n.º 27
0
        public void GetAndSeT_ShouldBePublic()
        {
            var profileImage = new ProfileImage();
            var user         = new User();

            profileImage.User = user;

            Assert.True(profileImage.User == user);
        }
Ejemplo n.º 28
0
 public XTUProfile()
 {
     Name         = "NEW_PROFILE";
     MinimumWatt  = 7.00;
     MaximumWatt  = 15.00;
     CPUUndervolt = 0;
     GPUUndervolt = 0;
     ProfileImage = ProfileImage.Gaming;
 }
Ejemplo n.º 29
0
        public void GetAndSeT_ShouldBePublic()
        {
            var user         = new User();
            var profileImage = new ProfileImage();

            user.ProfileImage = profileImage;

            Assert.True(user.ProfileImage == profileImage);
        }
Ejemplo n.º 30
0
 public XTUProfile(string name, double minimumWatt, double maximumWatt, int cpuUndervolt, int gpuUndervolt, ProfileImage profileImage)
 {
     Name         = name;
     MinimumWatt  = minimumWatt;
     MaximumWatt  = maximumWatt;
     CPUUndervolt = cpuUndervolt;
     GPUUndervolt = gpuUndervolt;
     ProfileImage = profileImage;
 }
        public void GetTwitterNewsAPI11(string url)
        {
            TwitterStatuses.Clear();
            if (string.IsNullOrEmpty(url)) {
                TwitterStatuses.Add(new TwitterItemViewModel(LanguageManager) {
                    Title = LanguageManager.Model.NewsTwitterError + ": [ERRCODE 4 - No URL specified]",
                    Date = DateTime.Now
                });
                return;
            }
            Uri link = new Uri(url);
            string response;
            using (WebClient wc = new WebClientEx()) {
                try {
                    response = wc.DownloadString(link);
                } catch (Exception e) {
                    TwitterStatuses.Add(new TwitterItemViewModel(LanguageManager) {
                        Title = LanguageManager.Model.NewsTwitterError + ": " + e.Message + " [ERRCODE 3 - Remote Error]",
                        Date = DateTime.Now
                    });
                    return;
                }
            }

            JArray tList;
            try {
                tList = JArray.Parse(System.Web.HttpUtility.HtmlDecode(response));
            } catch {
                TwitterStatuses.Add(new TwitterItemViewModel(LanguageManager) {
                    Title = LanguageManager.Model.NewsTwitterError + " [ERRCODE 1 - Parse Error]",
                    Date = DateTime.Now
                });
                return;
            }

            List<UserStatus> statuses = new List<UserStatus>();
            List<ProfileImage> profileImages = new List<ProfileImage>();
            List<ProfileImage> currentImage;
            ProfileImage profileImage;
            for (int i = 0; i < tList.Count(); i++) {
                JObject tweet = JObject.Parse(tList[i].ToString());
                UserStatus status = new UserStatus();

                status.UserName = tweet["user"]["name"].ToString();
                status.UserScreenName = tweet["user"]["screen_name"].ToString();
                status.ProfileImageUrl = tweet["user"]["profile_image_url"].ToString();
                var retweet = tweet["retweeted_status"];
                if (retweet != null) {
                    status.UserScreenName = retweet["user"]["name"].ToString();
                    status.UserName = retweet["user"]["screen_name"].ToString();
                    status.RetweetImageUrl = retweet["user"]["profile_image_url"].ToString();
                }

                status.Status = tweet["text"].ToString();
                status.StatusId = tweet["id"].ToString();
                status.StatusDate = ParseDateTime(tweet["created_at"].ToString());

                string profile_image;
                if (status.RetweetImageUrl != null) {
                    profile_image = status.RetweetImageUrl;
                } else {
                    profile_image = status.ProfileImageUrl;
                }

                currentImage = profileImages.FindAll(im => (im.url == profile_image));
                if (currentImage.Count == 0) {
                    profileImage = new ProfileImage();
                    profileImage.url = profile_image;
                    profileImage.bitmap = GetImage(profile_image);
                    if (profileImage.bitmap != null) {
                        profileImages.Add(profileImage);
                    }
                } else {
                    profileImage = currentImage[0];
                }
                status.ProfileImageBitmap = profileImage.bitmap;
                statuses.Add(status);
            }
            foreach (UserStatus status in statuses) {
                TwitterStatuses.Add(new TwitterItemViewModel(LanguageManager) {
                    Title = status.Status,
                    Date = status.StatusDate,
                    Image = status.ProfileImageBitmap,
                    StatusLink = "https://twitter.com/statuses/" + status.StatusId,
                    UserLink = "https://twitter.com/" + status.UserScreenName,
                    UserName = status.UserName
                });
            }
        }