Пример #1
0
      public void Save(TadmapImage image)
      {
         bool isNew = false;

         TadmapDb db = new TadmapDb();
         UserImage dbImage = db.UserImages.SingleOrDefault(i => i.Id == image.Id);

         if (dbImage == null)
         {
            dbImage = new UserImage();

            // can't change date added, id or owner
            dbImage.DateAdded = DateTime.Now;
            dbImage.UserId = image.UserId;
            dbImage.Id = image.Id;

            isNew = true;
         }
         else
         {
            isNew = false;
         }

         dbImage.Title = image.Title;
         dbImage.Description = image.Description;
         dbImage.Key = image.Key;
         dbImage.OffensiveCount = image.IsOffensive ? (byte)1 : (byte)0;
         dbImage.Privacy = image.IsPublic ? (byte)1 : (byte)0;

         if (isNew)
            db.UserImages.InsertOnSubmit(dbImage);

         db.SubmitChanges();
      }
        private UserImage CreateImageModel(string fileName, byte[] content)
        {
            var image = new UserImage
            {
                Content = content,
                FileExtension = fileName.Split(new[] { '.' }).Last()
            };

            return image;
        }
 public System.Web.Mvc.FileResult GetUserImage(long userId)
 {
     UserImage image = new UserImage();
     string result = OBSDataSource.GetUserImage(userId, out image);
     if (string.IsNullOrEmpty(result) && image != null)
     {
         return new FileContentResult(image.FileContent, image.ContentType);
     }
     else
     {
         return new FilePathResult(Server.MapPath("/Images/patientFrame.png"),"image/png");
     }
 }
Пример #4
0
        public static List <string> LoadImage(UserImage obj)
        {
            var path      = String.Empty;
            var localPath = Path.Combine(DIRECTORY_ASSETS, DIRECTORY_MARKS);
            var files     = new List <string>();

            switch (obj.ImageType)
            {
            case UserImageEnum.Mark:
                if (String.IsNullOrEmpty(obj.OrganizationName))
                {
                    //get for all
                    localPath = Path.Combine(localPath, DIRECTORY_ALL);
                    path      = Path.Combine(HttpRuntime.AppDomainAppPath, localPath);
                }



                if (Directory.Exists(path))
                {
                    files = Directory.GetFiles(path).ToList();
                }

                var temp = new List <string>();

                foreach (var item in files)
                {
                    temp.Add(item.Remove(0, HttpRuntime.AppDomainAppPath.Length));
                }

                files = temp;

                break;

            case UserImageEnum.Logo:
                break;

            default:
                break;
            }

            return(files);
        }
Пример #5
0
        private async Task UserSaveImages(List <UserImageModel> userImages, int userId)
        {
            var    userImage = new UserImage();
            string fileName, filePath;

            if (userImages.Count > 0)
            {
                for (int i = 0; i < userImages.Count; i++)
                {
                    Byte[] bytes = Convert.FromBase64String(userImages[i].ImageBinaryData);
                    //IFormFile formFile = File.WriteAllBytes(path, bytes);
                    UploadedFile(bytes, null, out fileName, out filePath);
                    userImage.DocumentPath = filePath;
                    userImage.DocumentName = fileName;
                    userImage.UserId       = userId;
                    await _userImageRepository.AddAsync(userImage);
                }
            }
        }
Пример #6
0
        public async Task <Image> AddUserPhotoAsync(int authorId, IFormFile file)
        {
            var path =
                await _imageSaver.SaveAndReturnImagePath(file, "UserPhotos", authorId);

            var image = new Image
            {
                Path        = path,
                PublishDate = DateTime.Now
            };
            var userPhoto = new UserImage
            {
                UserId = authorId,
                Image  = image
            };
            await _repository.UserPhoto.Add(userPhoto);

            return(image);
        }
Пример #7
0
        public StudentInfoOutput AddPhoto([FromBody] StudentInfoInput input)
        {
            StudentInfoOutput output = new StudentInfoOutput();

            if (input == null)
            {
                Response.StatusCode = 400;
                output.Result       = "INPUT_IS_NULL";
            }
            else
            {
                Recognizer recognizer = _db.Recognizers.Where(e => e.Id.Equals(input.RecognizerId)).FirstOrDefault();
                if (recognizer == null)
                {
                    Response.StatusCode = 400;
                    output.Result       = "CREDENTIAL_ERROR";
                }
                else
                {
                    if (recognizer.Key.Equals(input.RecognizerKey))
                    {
                        UserImage userImage = new UserImage()
                        {
                            User      = _db._BCPUsers.Where(e => e.Id.Equals(input.StudentId)).FirstOrDefault(),
                            Url       = input.ImageUrl,
                            Status    = 1,
                            CreatedBy = recognizer.Id
                        };

                        _db.UserImages.Add(userImage);
                        _db.SaveChanges();
                        output.Result = "OK";
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        output.Result       = "CREDENTIAL_ERROR";
                    }
                }
            }

            return(output);
        }
Пример #8
0
        public async Task <JsonResult> UploadImage(HttpPostedFileBase file)
        {
            var userId = User.Identity.GetUserId();

            using (var db = new ZapContext())
            {
                if (file.ContentLength > 0)
                {
                    string       _FileName = Path.GetFileName(file.FileName);
                    MemoryStream ms        = new MemoryStream();

                    Image img = Image.FromStream(file.InputStream);

                    byte[] data;

                    int maxwidth = 720;

                    if (img.Width > maxwidth)
                    {
                        // rescale if too large for post
                        var    scale = Convert.ToDouble(maxwidth) / Convert.ToDouble(img.Width);
                        Bitmap thumb = ImageExtensions.ResizeImage(img, maxwidth, Convert.ToInt32(img.Height * scale));
                        data = thumb.ToByteArray(ImageFormat.Jpeg);
                    }
                    else
                    {
                        data = img.ToByteArray(ImageFormat.Jpeg);
                    }

                    UserImage i = new UserImage()
                    {
                        Image = data
                    };

                    db.Images.Add(i);
                    db.SaveChanges();
                    return(Json(new { result = "success", imgId = i.ImageId }));
                }

                return(Json(new { result = "failure" }));
            }
        }
Пример #9
0
        public ActionResult WriteReview(int mshipID)
        {
            Mentorship mentorship = ch.GetMentorship(mshipID);

            UserImage img = mentorship.MentorProfile.User.UserImage;
            Review    rev = mentorship.Review;

            WriteReviewViewModel model = new WriteReviewViewModel
            {
                MentorshipId  = mshipID,
                ImageFilename = img != null ? img.imagePath : "",
                MentorName    = mentorship.MentorProfile.User.fname + " " + mentorship.MentorProfile.User.lname,
                Email         = mentorship.MentorProfile.User.UserID,
                Subject       = mentorship.subject.name,
                Rating        = rev == null ? -1 : (int)rev.rating,
                Comment       = rev == null ? "" : rev.comments
            };

            return(View(model));
        }
        void ReleaseDesignerOutlets()
        {
            if (UserImage != null)
            {
                UserImage.Dispose();
                UserImage = null;
            }

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

            if (UserTitle != null)
            {
                UserTitle.Dispose();
                UserTitle = null;
            }
        }
Пример #11
0
        public ViewResult MiniProfile(int id)
        {
            var user = _userService.GetUser(id);

            if (user == null)
            {
                return(View("MiniUserNotFound"));
            }
            var       profile   = _profileService.GetProfile(user);
            UserImage userImage = null;

            if (profile.ImageID.HasValue)
            {
                userImage = _imageService.GetUserImage(profile.ImageID.Value);
            }
            var model = new DisplayProfile(user, profile, userImage);

            model.PostCount = _postService.GetPostCount(user);
            return(View(model));
        }
Пример #12
0
        public async Task <IActionResult> Upload(IFormFile file)
        {
            var uploads = _stegoModel.GetUploadsPath();

            if (file.Length > 0)
            {
                var userImage = new UserImage
                {
                    FileName    = file.FileName,
                    ContentType = file.ContentType,
                    Guid        = System.Guid.NewGuid().ToString()
                };
                using (var fileStream = new FileStream(Path.Combine(uploads, userImage.Guid), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
                HttpContext.Session.Set <UserImage>(nameof(UserImage), userImage);
            }
            return(Json("ok"));
        }
Пример #13
0
        public ActionResult UploadImage(HttpPostedFileBase file)
        {
            if (file != null)
            {
                string ContainerName = "userimages"; //hardcoded container name.
                file = file ?? Request.Files["file"];
                string fileName    = Path.GetFileName(file.FileName);
                Stream imageStream = file.InputStream;
                var    result      = utility.UploadBlob(fileName, ContainerName, imageStream);
                if (result != null)
                {
                    string loggedInUserId = User.Identity.GetUserId();

                    User user = this._service.Context.Users.Find(loggedInUserId);
                    if (user.UserImages.Count > 0)
                    {
                        string imageId = user.UserImages.ToList()[0].Id;

                        UserImage userImage        = this._service.DeleteImage(imageId);
                        string    BlobNameToDelete = userImage.ImageUrl.Split('/').Last();
                        utility.DeleteBlob(BlobNameToDelete, "userimages");
                    }

                    UserImage userimage = new UserImage();
                    userimage.Id       = Guid.NewGuid().ToString();
                    userimage.UserId   = loggedInUserId;
                    userimage.ImageUrl = result.Uri.ToString();
                    this._service.Context.UserImages.Add(userimage);
                    this._service.Context.SaveChanges();
                    return(RedirectToAction("Picture"));
                }
                else
                {
                    return(RedirectToAction("Picture"));
                }
            }
            else
            {
                return(RedirectToAction("Picture"));
            }
        }
        public async Task <int> AddImage(long contactId, UserImageCreateRequest request)
        {
            var userImage = new UserImage()
            {
                Caption    = request.Caption,
                DayCreated = DateTime.Now,
                IsDefault  = request.IsDefault,
                ContactID  = contactId,
            };

            if (request.ImageFile != null)
            {
                userImage.ImagePath = await this.SaveFile(request.ImageFile);

                userImage.FileSize = request.ImageFile.Length;
            }
            _context.UserImages.Add(userImage);
            await _context.SaveChangesAsync();

            return(userImage.ID);
        }
Пример #15
0
        public void SaveUserImage(int userID, string imagePath, bool isProfilePicture)
        {
            if (isProfilePicture)
            {
                var existingProfilePicture = _context.UserImages.Where(m => m.UserID == userID && m.IsActive == true && m.IsProfilePicture == true).FirstOrDefault();
                if (existingProfilePicture != null)
                {
                    existingProfilePicture.IsProfilePicture = false;
                    _context.SaveChanges();
                }
            }
            UserImage objentity = new UserImage();

            objentity.CreatedOn        = System.DateTime.Now;
            objentity.ImagePath        = imagePath;
            objentity.IsActive         = true;
            objentity.IsProfilePicture = isProfilePicture;
            objentity.UserID           = userID;
            _context.UserImages.Add(objentity);
            _context.SaveChanges();
        }
Пример #16
0
        public void ChangeStudentImage(User user, string path, string type)
        {
            UserImage img = context.UserImages.Where(u => u.fk_userId == user.ID).FirstOrDefault();

            if (img != null)    // edit
            {
                img.imagePath   = path;
                img.contentType = type;
            }
            else     // create new
            {
                img                         = new UserImage();
                img.fk_userId               = user.ID;
                img.imagePath               = path;
                img.contentType             = type;
                user.StudentProfile.imgPath = path;
                context.UserImages.Add(img);
            }

            context.SaveChanges();
        }
        public ActionResult UploadImage(IFormFile file)
        {
            string loggedInUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            int    imageCount     = (from r in _db.UserImages where r.ApplicationUserId == loggedInUserId select r).Count();

            if (imageCount >= 10)
            {
                return(RedirectToAction("Index"));
            }

            if (file != null)
            {
                using (var reader = new StreamReader(file.OpenReadStream()))
                {
                    var    fileContent = reader.BaseStream;
                    var    parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
                    string fileName = parsedContentDisposition.FileName;
                    var    result   = utility.UploadBlob(fileName, _config["BlobDetails:ContainerName"], fileContent);
                    if (result != null)
                    {
                        UserImage userimage = new UserImage();
                        userimage.Id = new Random().Next().ToString();
                        userimage.ApplicationUserId = loggedInUserId;
                        result.Wait();
                        userimage.ImageUrl = result.Result.Uri.ToString();
                        _db.UserImages.Add(userimage);
                        _db.SaveChanges();
                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        return(RedirectToAction("Index"));
                    }
                }
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
Пример #18
0
        public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                //string pic = Path.GetFileName(file.FileName);
                //string path = Path.Combine(Server.MapPath("~/images/profile"), pic);
                //// file is uploaded
                //file.SaveAs(path);

                // save the image path path to the database or you can send image
                // directly to database
                // in-case if you want to store byte[] ie. for DB
                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();

                    var userImage = new UserImage {
                        UserId = this.UserProfile.Id, Avatar = array
                    };
                    var existingImage = this.Data.UserImages.GetAll().
                                        FirstOrDefault(x => x.UserId == this.UserProfile.Id);
                    if (existingImage != null)
                    {
                        existingImage.Avatar = array;
                    }
                    else
                    {
                        this.Data.UserImages.Add(userImage);
                    }

                    this.Data.SaveChanges();
                }
            }

            this.TempData["Message"] = "Profile updated";

            // after successfully uploading redirect the user
            return(this.RedirectToAction("Index", new { username = this.UserProfile.UserName }));
        }
Пример #19
0
        public ViewResult ViewProfile(int id)
        {
            var user = _userService.GetUser(id);

            if (user == null)
            {
                return(this.NotFound("NotFound", null));
            }
            var       profile   = _profileService.GetProfile(user);
            UserImage userImage = null;

            if (profile.ImageID.HasValue)
            {
                userImage = _imageService.GetUserImage(profile.ImageID.Value);
            }
            var model = new DisplayProfile(user, profile, userImage);

            model.PostCount  = _postService.GetPostCount(user);
            model.Feed       = _feedService.GetFeed(user);
            model.UserAwards = _userAwardService.GetAwards(user);
            return(View(model));
        }
Пример #20
0
        protected bool SavetoFileServer(Profile value, UserImage user)
        {
            bool success = false;

            try
            {
                ImageFormat format    = ImageFormat.Png;
                String      imagename = value.UserID.ToString();
                string      imagepath = @"http://www.nestin.online/ImageServer/User/" + imagename + "." + format;
                using (FileStream stream = new FileStream(imagepath, FileMode.Create))
                {
                    stream.Write(user.Profile_image, 0, user.Profile_image.Length);
                    stream.Flush();
                }
                success = true;
            }

            catch (Exception ex)
            {
            }
            return(success);
        }
Пример #21
0
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            UserImage userImage = new UserImage();
            string    imageName = string.Empty;

            if (rbCats.IsChecked == true)
            {
                userImage.Category = "Cats";
            }
            else if (rbDogs.IsChecked == true)
            {
                userImage.Category = "Dogs";
            }
            else if (rbBirds.IsChecked == true)
            {
                userImage.Category = "Birds";
            }

            imageName = Guid.NewGuid().ToString() + ".jpg";

            string fullName = Environment.CurrentDirectory + @"\images\" + imageName;

            userImage.FileName = imageName;

            Uri         source   = new Uri(Environment.CurrentDirectory + @"\cropped.jpg");
            BitmapFrame image    = BitmapFrame.Create(source);
            String      filePath = fullName;

            var encoder = new PngBitmapEncoder();

            encoder.Frames.Add(image);
            using (FileStream stream = new FileStream(filePath, FileMode.Create))
                encoder.Save(stream);

            _context.UserImages.Add(userImage);
            _context.SaveChanges();
            Close();
        }
Пример #22
0
        private int SaveUserImage(HttpPostedFileBase img, string username)
        {
            string defaultUserImagePath = ConfigurationManager.AppSettings["DefaultUserImageDirectory"].ToString();
            string defaultUserImage     = ConfigurationManager.AppSettings["DefaultUserImage"].ToString();
            string userImageDirectory   = Server.MapPath(defaultUserImagePath);

            string destinationDir = Path.Combine(userImageDirectory, username);

            var image = new UserImage();

            if (img != null && img.ContentLength > 0)
            {
                string imagePath = SaveImage(img, destinationDir);

                image.Name = SaveImage(img, destinationDir);
                image.Path = defaultUserImagePath + "/" + username;
            }

            Context.UserImageRepo.Insert(image);
            Context.Save();

            return(image.Id);
        }
        private void UpdateImage(User user, UserImage oldUserImage)
        {
            if (user.UserImage != null)
            {
                var imageGuid = Guid.NewGuid();
                var imageName = $"{imageGuid}.Jpeg";

                user.UserImage.Path = Path.GetFileName(imageName);
                SaveImage(user.UserImage.Content, imageName);
                if (oldUserImage != null)
                {
                    oldUserImage.UpdateDate = DateTime.Now;
                    oldUserImage.Path       = imageName;
                }
            }
            else
            {
                if (oldUserImage != null)
                {
                    _context.UserImage.Remove(oldUserImage);
                }
            }
        }
Пример #24
0
        public ActionResult StoreImage(HttpPostedFileBase file)
        {
            if (Session["user_id"] != null)
            {
                if (file != null && file.ContentLength > 0 && file.ContentType.Contains("image") &&
                    Path.GetExtension(file.FileName).ToLower() != ".gif")
                {
                    using (var reader = new BinaryReader(file.InputStream))
                    {
                        var imageForUser = new UserImage()
                        {
                            UserId       = (int)Session["user_id"],
                            ImageContent = reader.ReadBytes(file.ContentLength),
                            ContentType  = file.ContentType
                        };

                        var newUserImage = _Context.UserImages.SingleOrDefault(ui => ui.UserId == imageForUser.UserId);
                        if (newUserImage == null)
                        {
                            _Context.UserImages.Add(imageForUser);
                            _Context.SaveChanges();
                        }
                        else
                        {
                            var existingUser = _Context.UserImages.SingleOrDefault(ui => ui.Id == newUserImage.Id);
                            existingUser.ImageContent = imageForUser.ImageContent;
                            existingUser.ContentType  = imageForUser.ContentType;
                            _Context.SaveChanges();
                        }

                        return(RedirectToAction("Index", "Users"));
                    }
                }
                return(Content("only .jpg, .jpeg, .png are allowed. <a href='/Users/UploadImage'> back to previous."));
            }
            return(RedirectToAction("LogInUser", "Users"));
        }
Пример #25
0
        public void AddUserProfile(string id, CustomRegisterModel model)
        {
            string path      = _fileService.UploadImage(model.ImageBase64);
            var    userImage = new UserImage
            {
                Id   = id,
                Path = path
            };

            _context.UserImages.Add(userImage);
            _context.SaveChanges();

            var userProfile = new UserProfile
            {
                Id          = id,
                FirstName   = model.FirstName,
                MiddleName  = model.MiddleName,
                LastName    = model.LastName,
                DateOfBirth = model.DateOfBirth
            };

            _context.UserProfiles.Add(userProfile);
            _context.SaveChanges();
        }
Пример #26
0
 public ActionResult CreateTeacherImages(UserImage objUserImage, IEnumerable <HttpPostedFileBase> image)
 {
     if (image != null)
     {
         if (!String.IsNullOrEmpty(objUserImage.VideoUrl))
         {
             if (objUserImage.VideoUrl.Contains("watch") && objUserImage.VideoUrl.Contains("youtube.com"))
             {
                 string querystring = objUserImage.VideoUrl.Split('=')[1];
                 objUserImage.VideoUrl = "https://www.youtube.com/embed/" + querystring;
             }
         }
         foreach (HttpPostedFileBase img in image)
         {
             string imageName = System.IO.Path.GetFileName(img.FileName);
             img.SaveAs(Server.MapPath("~/Images/" + Helper.UserId + "-" + imageName));
             objUserImage.ImageUrl  = "/Images/" + Helper.UserId + "-" + imageName;
             objUserImage.ImageName = imageName;
             DbHelper.InsertUserImages(objUserImage);
         }
         return(RedirectToAction("TeacherImages", new { classId = objUserImage.FKClassId }));
     }
     return(View(objUserImage));
 }
Пример #27
0
 /// <summary>
 /// Invoked when <see cref="ToDTO"/> operation is about to return.
 /// </summary>
 /// <param name="dto"><see cref="UserImageDTO"/> converted from <see cref="UserImage"/>.</param>
 static partial void OnDTO(this UserImage entity, UserImageDTO dto);
Пример #28
0
 /// <summary>Called when the given list item is activated by the user, either with the keyboard or mouse.</summary>
 void ActivateUserId(AttributeItem item)
 {
   // activating a photo ID will display it
   UserImage image = item.Attribute as UserImage;
   if(image != null) new PhotoIdForm(image).ShowDialog();
 }
Пример #29
0
 partial void DeleteUserImage(UserImage instance);
Пример #30
0
        public static string GetPreviewUrl(UserImage image)
        {
            ThreeSharpWrapper s3 = new ThreeSharpWrapper(S3Storage.AccessKey, S3Storage.SecretAccessKey);
            if (image.ImageSet == 0)
               return s3.GetUrl(S3Storage.BucketName, "LargeThumb_" + image.Key);

            return s3.GetUrl(S3Storage.BucketName, "Preview_" + image.Key);
        }
Пример #31
0
        public async Task <JsonDefaultResponse> Handle(CreateAccount request, CancellationToken cancellationToken)
        {
            try
            {
                var existentUser = await _context.User
                                   .Where(u => u.Username == request.Username)
                                   .SingleOrDefaultAsync();

                if (existentUser != null)
                {
                    return new JsonDefaultResponse
                           {
                               Success = false,
                               Message = "Já existe um usuário cadastrado com esse nome de usuário."
                           }
                }
                ;
            }
            catch
            {
                return(new JsonDefaultResponse
                {
                    Success = false,
                    Message = "Houve um problema ao consultar os usuários existentes."
                });
            }

            var user = new User
            {
                Username = request.Username,
                Password = _cryptoHelper.Encrypt(request.Password),
                Status   = Status.Active
            };

            var person = new Person
            {
                FirstName = request.FirstName,
                LastName  = request.LastName,
                Age       = request.Age,
                TaxNumber = request.TaxNumber,
                Gender    = request.Gender
            };

            var userHasPerson = new UserHasPerson
            {
                UserId   = user.Id,
                PersonId = person.Id
            };

            var contact = new Contact
            {
                PhoneNumber = request.PhoneNumber,
                Email       = request.PhoneNumber
            };

            var personHasContact = new PersonHasContact
            {
                PersonId  = person.Id,
                ContactId = contact.Id
            };

            var userImage = new UserImage
            {
                UserId = user.Id,
                Path   = request.ImagePath
            };

            try
            {
                _context.User.Add(user);
                _context.Person.Add(person);
                _context.UserHasPerson.Add(userHasPerson);
                _context.Contact.Add(contact);
                _context.PersonHasContact.Add(personHasContact);
                await _context.SaveChangesAsync(cancellationToken);
            }
            catch
            {
                return(new JsonDefaultResponse
                {
                    Success = false,
                    Message = "Houve um erro no servidor ao criar a sua conta"
                });
            }

            return(new JsonDefaultResponse
            {
                Success = true,
                Message = "Conta criada com sucesso."
            });
        }
Пример #32
0
        //==================================================================================//
        //      Store Prospect Student information                                          //
        //                                                                                  //
        //      Register the prospective student information if it is                       //
        //      empty. Otherwise edit it.                                                   //
        //                                                                                  //
        //      Note: If the edit is true then the account is being edited.                 //
        //      Otherwise it is being registered.                                           //
        //==================================================================================//
        public static bool StoreProspectData(ProspectModel prospect, ref bool edit)
        {
            int UserId = WebSecurity.GetUserId(prospect.EmailAddress);

            ProspectiveStudent CurrentStudent;

            edit = false;

            try
            {
                using (ITintheDTestTableEntities context = new ITintheDTestTableEntities())
                {
                    // Put everything we find in the database in the var variable. All the
                    // information will be gotten using the User ID.

                    var ProspectData = from r in context.ProspectiveStudent
                                       where r.UserId == UserId
                                       select r;

                    // If the user has some information then edit it.
                    // Otherwise register the account.

                    if (ProspectData.Count() > 0 && UserId > 0)
                    {
                        edit = true;

                        CurrentStudent = ProspectData.FirstOrDefault();
                        CurrentStudent.Status = prospect.AccountStatus;
                        CurrentStudent.UserId = UserId;
                        CurrentStudent.Name = prospect.Name;
                        CurrentStudent.Telephone = prospect.Telephone;
                        CurrentStudent.EmailAddress = prospect.EmailAddress;
                        CurrentStudent.DesiredCareerPath = prospect.DesiredCareerPath;
                        CurrentStudent.Gender = prospect.Gender;
                        CurrentStudent.ProspectiveStudentTextField = prospect.ProspectiveStudentTextField;

                        // Store the avatar if it is supplied.

                        if (prospect.ImageFile != null)
                        {
                            UserImage image = new UserImage();

                            using (MemoryStream ms = new MemoryStream())
                            {
                                prospect.ImageFile.InputStream.CopyTo(ms);

                                image.FileContent = ms.ToArray();
                                image.FileName = Path.GetFileName(prospect.ImageFile.FileName);
                                image.ContentType = prospect.ImageFile.ContentType;
                                image.ContentLength = prospect.ImageFile.ContentLength;

                                DatabaseHelper.UploadImage(image, CurrentStudent.UserId);

                                CurrentStudent.ImageUploaded = "Yes";
                                prospect.ImageUploaded = "Yes";
                            }
                        }

                        // Store the new resume if it is supplied and not empty.

                        if (prospect.ResumeFile != null && prospect.ResumeFile.ContentLength > 0)
                        {
                            ProspectiveStudentResume Resume = new ProspectiveStudentResume();

                            using (MemoryStream ms = new MemoryStream())
                            {
                                prospect.ResumeFile.InputStream.CopyTo(ms);

                                Resume.FileContent = ms.ToArray();
                                Resume.FileName = Path.GetFileName(prospect.ResumeFile.FileName);
                                Resume.ContentType = prospect.ResumeFile.ContentType;
                                Resume.ContentLength = prospect.ResumeFile.ContentLength;

                                DatabaseHelper.UploadResume(Resume, prospect);

                                CurrentStudent.ResumeUploaded = "Yes";
                                prospect.ResumeUploaded = "Yes";
                            }
                        }

                        // Store the new transcript if it is supplied and not empty.

                        if (prospect.TranscriptFile != null && prospect.TranscriptFile.ContentLength > 0)
                        {
                            ProspectiveStudentTranscript Transcript = new ProspectiveStudentTranscript();

                            using (MemoryStream ts = new MemoryStream())
                            {
                                prospect.TranscriptFile.InputStream.CopyTo(ts);

                                Transcript.FileContent = ts.ToArray();
                                Transcript.FileName = Path.GetFileName(prospect.TranscriptFile.FileName);
                                Transcript.ContentType = prospect.TranscriptFile.ContentType;
                                Transcript.ContentLength = prospect.TranscriptFile.ContentLength;

                                DatabaseHelper.UploadTranscript(Transcript, prospect);

                                CurrentStudent.TranscriptUploaded = "Yes";
                                prospect.TranscriptUploaded = "Yes";
                            }
                        }
                    }

                    else
                    {
                        CurrentStudent = new ProspectiveStudent();

                        CurrentStudent.Status = prospect.AccountStatus;
                        CurrentStudent.Name = prospect.Name;
                        CurrentStudent.Telephone = prospect.Telephone;
                        CurrentStudent.EmailAddress = prospect.EmailAddress;
                        CurrentStudent.DesiredCareerPath = prospect.DesiredCareerPath;
                        CurrentStudent.Gender = prospect.Gender;
                        CurrentStudent.ProspectiveStudentTextField = prospect.ProspectiveStudentTextField;

                        context.AddToProspectiveStudent(CurrentStudent);
                    }

                    try
                    {
                        // If the account is edited then save changes. Otherwise register the account.

                        if (edit == false)
                        {
                            WebSecurity.CreateUserAndAccount(prospect.EmailAddress, prospect.Password);

                            // User is automatically logged in here.

                            WebSecurity.Login(prospect.EmailAddress, prospect.Password);

                            DatabaseHelper.AddUserToRole(prospect.EmailAddress, "Student");

                            CurrentStudent.UserId = WebSecurity.GetUserId(prospect.EmailAddress);

                            // Store the avatar if it is supplied.

                            if (prospect.ImageFile != null)
                            {
                                UserImage image = new UserImage();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    prospect.ImageFile.InputStream.CopyTo(ms);

                                    image.FileContent = ms.ToArray();
                                    image.FileName = Path.GetFileName(prospect.ImageFile.FileName);
                                    image.ContentType = prospect.ImageFile.ContentType;
                                    image.ContentLength = prospect.ImageFile.ContentLength;

                                    DatabaseHelper.UploadImage(image, CurrentStudent.UserId);

                                    CurrentStudent.ImageUploaded = "Yes";
                                    prospect.ImageUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentStudent.ImageUploaded = "No";
                                prospect.ImageUploaded = "No";
                            }

                            // Store the resume if it is supplied and not empty.

                            if (prospect.ResumeFile != null && prospect.ResumeFile.ContentLength > 0)
                            {
                                ProspectiveStudentResume Resume = new ProspectiveStudentResume();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    prospect.ResumeFile.InputStream.CopyTo(ms);

                                    Resume.FileContent = ms.ToArray();
                                    Resume.FileName = Path.GetFileName(prospect.ResumeFile.FileName);
                                    Resume.ContentType = prospect.ResumeFile.ContentType;
                                    Resume.ContentLength = prospect.ResumeFile.ContentLength;

                                    DatabaseHelper.UploadResume(Resume, prospect);

                                    CurrentStudent.ResumeUploaded = "Yes";
                                    prospect.ResumeUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentStudent.ResumeUploaded = "No";
                                prospect.ResumeUploaded = "No";
                            }

                            // Store the resume if it is supplied and not empty.

                            if (prospect.TranscriptFile != null && prospect.TranscriptFile.ContentLength > 0)
                            {
                                ProspectiveStudentTranscript Transcript = new ProspectiveStudentTranscript();

                                using (MemoryStream ts = new MemoryStream())
                                {
                                    prospect.TranscriptFile.InputStream.CopyTo(ts);

                                    Transcript.FileContent = ts.ToArray();
                                    Transcript.FileName = Path.GetFileName(prospect.TranscriptFile.FileName);
                                    Transcript.ContentType = prospect.TranscriptFile.ContentType;
                                    Transcript.ContentLength = prospect.TranscriptFile.ContentLength;

                                    DatabaseHelper.UploadTranscript(Transcript, prospect);

                                    CurrentStudent.TranscriptUploaded = "Yes";
                                    prospect.TranscriptUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentStudent.TranscriptUploaded = "No";
                                prospect.TranscriptUploaded = "No";
                            }
                        }

                        context.SaveChanges();
                        return true;
                    }

                    catch
                    {
                        return false;
                    }
                }
            }

            catch
            {
                return false;
            }
        }
Пример #33
0
 public void CreateUserImage(UserImage userImage)
 {
     context.UserImages.Add(userImage);
     SaveChange();
 }
Пример #34
0
        //==================================================================================//
        //      Upload Prospect Student Image.                                              //
        //                                                                                  //
        //      Uploads the prospective student image if it is not empty.                   //
        //==================================================================================//
        public static bool UploadImage(UserImage image, int UserId)
        {
            try
            {
                using (ITintheDTestTableEntities context = new ITintheDTestTableEntities())
                {
                    // Put everything we find in the database in the var variable. All the
                    // information will be gotten using the User ID.

                    var UserImage = from r in context.UserImage
                                     where r.UserID == UserId
                                     select r;

                    // If the user has an image then update it.
                    // Otherwise make a new row in the database.

                    if (UserImage.Count() > 0)
                    {
                        UserImage currentImage = UserImage.FirstOrDefault();

                        currentImage.UserID = UserId;
                        currentImage.FileContent = image.FileContent;
                        currentImage.FileName = image.FileName;
                        currentImage.ContentLength = image.ContentLength;
                        context.SaveChanges();
                        return true;
                    }

                    else
                    {
                        image.UserID = UserId;
                        context.AddToUserImage(image);
                        context.SaveChanges();
                        return true;
                    }
                }
            }

            catch (Exception)
            {
                return false;
            }
        }
Пример #35
0
 private UserImage GetDefaultImage()
 {
     var image = new UserImage();
     image.ImageData = ImageToByteArray(Properties.Resources.UserPlaceholder);
     image.ImageMimeType = new System.Drawing.ImageFormatConverter().ConvertToString(
         Properties.Resources.UserPlaceholder.RawFormat);
     return image;
 }
Пример #36
0
        //==================================================================================//
        //      Store Academic information                                                  //
        //                                                                                  //
        //      Register the academic information if it is empty. Otherwise edit it.        //
        //                                                                                  //
        //      Note: If the edit is true then the account is being edited.                 //
        //      Otherwise it is being registered.                                           //
        //==================================================================================//
        public static bool StoreAcademicData(AcademicModel academic, ref bool edit)
        {
            int UserId = WebSecurity.GetUserId(academic.PrimaryEmailAddress);

            edit = false;

            try
            {
                ProspectiveAcademic CurrentAcademic;

                using (ITintheDTestTableEntities context = new ITintheDTestTableEntities())
                {
                    // Put everything we find in the database in the var variable. All the
                    // information will be gotten using the User ID.

                    var AcademicData = from r in context.ProspectiveAcademic
                                       where r.AcademicId == UserId
                                       select r;

                    // If the user has some information then edit it.
                    // Otherwise register the account.

                    if (AcademicData.Count() > 0 && UserId > 0)
                    {
                        CurrentAcademic = AcademicData.FirstOrDefault();
                        CurrentAcademic.Status = academic.AccountStatus;
                        CurrentAcademic.AcademyAddress = academic.AcademyAddress;
                        CurrentAcademic.AcademyName = academic.AcademyName;
                        CurrentAcademic.PrimaryContactName = academic.PrimaryContactName;
                        CurrentAcademic.PrimaryEmailAddress = academic.PrimaryEmailAddress;
                        CurrentAcademic.PrimaryTitle = academic.PrimaryTitle;
                        CurrentAcademic.PrimaryTelephone = academic.PrimaryTelephone;

                        CurrentAcademic.SecondaryContactName = academic.SecondaryContactName;
                        CurrentAcademic.SecondaryEmailAddress = academic.SecondaryEmailAddress;
                        CurrentAcademic.SecondaryTitle = academic.SecondaryTitle;
                        CurrentAcademic.SecondaryTelephone = academic.SecondaryTelephone;

                        CurrentAcademic.AcademicInstitutionTextField = academic.AcademicInstitutionTextField;
                        CurrentAcademic.AcademicId = UserId;

                        // Store the avatar if it is supplied.

                        if (academic.ImageFile != null)
                        {
                            UserImage image = new UserImage();

                            using (MemoryStream ms = new MemoryStream())
                            {
                                academic.ImageFile.InputStream.CopyTo(ms);

                                image.FileContent = ms.ToArray();
                                image.FileName = Path.GetFileName(academic.ImageFile.FileName);
                                image.ContentType = academic.ImageFile.ContentType;
                                image.ContentLength = academic.ImageFile.ContentLength;

                                DatabaseHelper.UploadImage(image, CurrentAcademic.AcademicId);

                                CurrentAcademic.ImageUploaded = "Yes";
                                academic.ImageUploaded = "Yes";
                            }
                        }

                        edit = true;
                    }

                    else
                    {
                        CurrentAcademic = new ProspectiveAcademic();

                        CurrentAcademic.Status = academic.AccountStatus;
                        CurrentAcademic.AcademyAddress = academic.AcademyAddress;
                        CurrentAcademic.AcademyName = academic.AcademyName;
                        CurrentAcademic.PrimaryContactName = academic.PrimaryContactName;
                        CurrentAcademic.PrimaryEmailAddress = academic.PrimaryEmailAddress;
                        CurrentAcademic.PrimaryTitle = academic.PrimaryTitle;
                        CurrentAcademic.PrimaryTelephone = academic.PrimaryTelephone;

                        CurrentAcademic.SecondaryContactName = academic.SecondaryContactName;
                        CurrentAcademic.SecondaryEmailAddress = academic.SecondaryEmailAddress;
                        CurrentAcademic.SecondaryTitle = academic.SecondaryTitle;
                        CurrentAcademic.SecondaryTelephone = academic.SecondaryTelephone;
                        CurrentAcademic.AcademicInstitutionTextField = academic.AcademicInstitutionTextField;

                        context.AddToProspectiveAcademic(CurrentAcademic);
                    }

                    try
                    {
                        // If the account is edited then save changes. Otherwise register the account.

                        if (edit == false)
                        {
                            WebSecurity.CreateUserAndAccount(academic.PrimaryEmailAddress, academic.Password);
                            WebSecurity.Login(academic.PrimaryEmailAddress, academic.Password);

                            DatabaseHelper.AddUserToRole(academic.PrimaryEmailAddress, "Educator");

                            CurrentAcademic.AcademicId = WebSecurity.GetUserId(academic.PrimaryEmailAddress);

                            // Store the avatar if it is supplied.

                            if (academic.ImageFile != null)
                            {
                                UserImage image = new UserImage();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    academic.ImageFile.InputStream.CopyTo(ms);

                                    image.FileContent = ms.ToArray();
                                    image.FileName = Path.GetFileName(academic.ImageFile.FileName);
                                    image.ContentType = academic.ImageFile.ContentType;
                                    image.ContentLength = academic.ImageFile.ContentLength;

                                    DatabaseHelper.UploadImage(image, CurrentAcademic.AcademicId);

                                    CurrentAcademic.ImageUploaded = "Yes";
                                    academic.ImageUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentAcademic.ImageUploaded = "No";
                                academic.ImageUploaded = "No";
                            }
                        }

                        context.SaveChanges();
                        return true;
                    }

                    catch (Exception ex)
                    {
                        return false;
                    }
                }
            }

            catch
            {
                return false;
            }
        }
Пример #37
0
 public static string GetOriginalUrl(UserImage image)
 {
    ThreeSharpWrapper s3 = new ThreeSharpWrapper(S3Storage.AccessKey, S3Storage.SecretAccessKey);
    return s3.GetUrl(S3Storage.BucketName, image.Key);
 }
Пример #38
0
 /// <summary>
 /// Invoked when <see cref="ToEntity"/> operation is about to return.
 /// </summary>
 /// <param name="entity"><see cref="UserImage"/> converted from <see cref="UserImageDTO"/>.</param>
 static partial void OnEntity(this UserImageDTO dto, UserImage entity);
Пример #39
0
 public void UpdateUserImage(UserImage userImage)
 {
     throw new NotImplementedException();
 }
Пример #40
0
	private void attach_UserImages(UserImage entity)
	{
		this.SendPropertyChanging();
		entity.User = this;
	}
Пример #41
0
        //==================================================================================//
        //      Store Sponsor information                                                   //
        //                                                                                  //
        //      Register the sponsor information if it is empty. Otherwise edit it.         //
        //                                                                                  //
        //      Note: If the edit is true then the account is being edited.                 //
        //      Otherwise it is being registered.                                           //
        //==================================================================================//
        public static bool StoreSponsorData(SponsorModel sponsor, ref bool edit)
        {
            int UserId = WebSecurity.GetUserId(sponsor.EmailAddress);

            edit = false;

            try
            {
                ProspectiveCorporateSponsor CurrentSponsor;

                using (ITintheDTestTableEntities context = new ITintheDTestTableEntities())
                {
                    // Put everything we find in the database in the var variable. All the
                    // information will be gotten using the User ID.

                    var SponsorData = from r in context.ProspectiveCorporateSponsor
                                      where r.SponsorId == UserId
                                      select r;

                    // If the user has some information then edit it.
                    // Otherwise register the account.

                    if (SponsorData.Count() > 0 && UserId > 0)
                    {
                        CurrentSponsor = SponsorData.FirstOrDefault();
                        CurrentSponsor.Status = sponsor.AccountStatus;
                        CurrentSponsor.CompanyAddress = sponsor.CompanyAddress;
                        CurrentSponsor.CompanyName = sponsor.CompanyName;
                        CurrentSponsor.ContactName = sponsor.ContactName;
                        CurrentSponsor.EmailAddress = sponsor.EmailAddress;
                        CurrentSponsor.Title = sponsor.Title;
                        CurrentSponsor.Telephone = sponsor.Telephone;
                        CurrentSponsor.Reason = sponsor.Reason;
                        CurrentSponsor.SponsorPageTextField = sponsor.SponsorTextField;
                        CurrentSponsor.SponsorId = UserId;

                        // Store the avatar if it is supplied.

                        if (sponsor.ImageFile != null)
                        {
                            UserImage image = new UserImage();

                            using (MemoryStream ms = new MemoryStream())
                            {
                                sponsor.ImageFile.InputStream.CopyTo(ms);

                                image.FileContent = ms.ToArray();
                                image.FileName = Path.GetFileName(sponsor.ImageFile.FileName);
                                image.ContentType = sponsor.ImageFile.ContentType;
                                image.ContentLength = sponsor.ImageFile.ContentLength;

                                DatabaseHelper.UploadImage(image, CurrentSponsor.SponsorId);

                                CurrentSponsor.ImageUploaded = "Yes";
                                sponsor.ImageUploaded = "Yes";
                            }
                        }

                        edit = true;
                    }
                    else
                    {
                        CurrentSponsor = new ProspectiveCorporateSponsor();

                        CurrentSponsor.Status = sponsor.AccountStatus;
                        CurrentSponsor.CompanyAddress = sponsor.CompanyAddress;
                        CurrentSponsor.CompanyName = sponsor.CompanyName;
                        CurrentSponsor.ContactName = sponsor.ContactName;
                        CurrentSponsor.EmailAddress = sponsor.EmailAddress;
                        CurrentSponsor.Title = sponsor.Title;
                        CurrentSponsor.Telephone = sponsor.Telephone;
                        CurrentSponsor.Reason = sponsor.Reason;
                        CurrentSponsor.SponsorPageTextField = sponsor.SponsorTextField;

                        context.AddToProspectiveCorporateSponsor(CurrentSponsor);
                    }

                    try
                    {
                        // If the account is edited then save changes. Otherwise register the account.

                        if (edit == false)
                        {
                            WebSecurity.CreateUserAndAccount(sponsor.EmailAddress, sponsor.Password);

                            // User is automatically logged in here.

                            WebSecurity.Login(sponsor.EmailAddress, sponsor.Password);

                            DatabaseHelper.AddUserToRole(sponsor.EmailAddress, "Sponsor");

                            CurrentSponsor.SponsorId = WebSecurity.GetUserId(sponsor.EmailAddress);

                            // Store the avatar if it is supplied.

                            if (sponsor.ImageFile != null)
                            {
                                UserImage image = new UserImage();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    sponsor.ImageFile.InputStream.CopyTo(ms);

                                    image.FileContent = ms.ToArray();
                                    image.FileName = Path.GetFileName(sponsor.ImageFile.FileName);
                                    image.ContentType = sponsor.ImageFile.ContentType;
                                    image.ContentLength = sponsor.ImageFile.ContentLength;

                                    DatabaseHelper.UploadImage(image, CurrentSponsor.SponsorId);

                                    CurrentSponsor.ImageUploaded = "Yes";
                                    sponsor.ImageUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentSponsor.ImageUploaded = "No";
                                sponsor.ImageUploaded = "No";
                            }
                        }

                        context.SaveChanges();

                        return true;
                    }

                    catch (Exception e)
                    {
                        string errorMessage = e.Message;

                        return false;
                    }
                }
            }

            catch (Exception ex)
            {
                string exMessage = ex.Message;

                return false;
            }
        }
Пример #42
0
	private void detach_UserImages(UserImage entity)
	{
		this.SendPropertyChanging();
		entity.User = null;
	}
Пример #43
0
        public async Task <StudentInfoOutput> ProcessPhoto([FromBody] StudentInfoInput input)
        {
            StudentInfoOutput output  = new StudentInfoOutput();
            AspUserService    aspUser = new AspUserService(_db, this);
            bool failure = false;

            if (input == null)
            {
                Response.StatusCode = 400;
                output.Result       = "INPUT_IS_NULL";
            }
            else
            {
                string            personGroupId = _db.SiteConfigs.Where(e => e.Key.Equals("PERSONGROUP")).FirstOrDefault().Value;
                Uri               uri           = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/persongroups/" + personGroupId + "/training");
                HttpClientHandler handler       = new HttpClientHandler();
                StringContent     queryString   = null;
                HttpClient        client        = new HttpClient(handler);
                //string respond = null;
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                HttpResponseMessage response = await client.GetAsync(uri);

                string siteUrl = _db.SiteConfigs.Where(e => e.Key.Equals("SITEURL")).First().Value;
                string respond = await response.Content.ReadAsStringAsync();

                dynamic jsonObj        = JsonConvert.DeserializeObject(respond);
                string  trainingStatus = "NONE";
                if (jsonObj.status != null)
                {
                    trainingStatus = jsonObj.status;
                }
                else
                {
                    trainingStatus = "NONE";
                }

                if (trainingStatus.Equals("running"))
                {
                    Response.StatusCode = 400;
                    output.Result       = "TRAINING_IN_PROGRESS";
                }
                else
                {
                    if (aspUser.IsAdmin)
                    {
                        BCPUser user = _db._BCPUsers.Where(e => e.Id.Equals(input.StudentId)).FirstOrDefault();

                        if (user == null)
                        {
                            Response.StatusCode = 400;
                            output.Result       = "USER_NOT_FOUND";
                        }
                        else
                        {
                            List <UserImage> imageStore    = user.List_UserImage.Where(e => e.Status == 1).OrderBy(e => e.DateCreated).ToList();
                            List <string>    imageToBeUsed = new List <string>();
                            int    min             = int.Parse(_db.SiteConfigs.Where(e => e.Key.Equals("NUM_PHOTO_PER_STUDENT")).FirstOrDefault().Value);
                            string mainSiteUrl     = _db.SiteConfigs.Where(e => e.Key.Equals("SITEURL")).FirstOrDefault().Value;
                            int    imageCount      = imageStore.Count;
                            string faceIdToCompare = null;

                            if (imageCount >= min)
                            {
                                string faceListId = Guid.NewGuid().ToString().ToLower();
                                uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/facelists/" + faceListId);
                                handler     = new HttpClientHandler();
                                queryString = null;
                                client      = new HttpClient(handler);
                                //string respond = null;
                                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                PersonGroupInput pgInput = new PersonGroupInput()
                                {
                                    Name             = faceListId,
                                    RecognitionModel = "recognition_02"
                                };

                                queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                queryString.Headers.Remove("Content-Type");
                                queryString.Headers.Add("Content-Type", "application/json");
                                response = await client.PutAsync(uri, queryString);

                                //respond = await response.Content.ReadAsStringAsync();

                                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                {
                                    foreach (UserImage item in imageStore)
                                    {
                                        if (imageCount > 1)
                                        {
                                            uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/facelists/" + faceListId + "/persistedFaces");
                                            handler     = new HttpClientHandler();
                                            queryString = null;
                                            client      = new HttpClient(handler);
                                            //string respond = null;
                                            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                            pgInput = new PersonGroupInput()
                                            {
                                                Url = mainSiteUrl + "/" + item.Url
                                            };

                                            queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                            queryString.Headers.Remove("Content-Type");
                                            queryString.Headers.Add("Content-Type", "application/json");
                                            response = await client.PostAsync(uri, queryString);

                                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                            {
                                                respond = await response.Content.ReadAsStringAsync();

                                                jsonObj     = JsonConvert.DeserializeObject(respond);
                                                item.FaceId = jsonObj.persistedFaceId;
                                            }

                                            _db.SaveChanges();
                                            imageCount--;
                                        }
                                        else
                                        {
                                            uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/detect?recognitionModel=recognition_02");
                                            handler     = new HttpClientHandler();
                                            queryString = null;
                                            client      = new HttpClient(handler);
                                            //string respond = null;
                                            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                            pgInput = new PersonGroupInput()
                                            {
                                                Url = mainSiteUrl + "/" + item.Url
                                            };

                                            queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                            queryString.Headers.Remove("Content-Type");
                                            queryString.Headers.Add("Content-Type", "application/json");
                                            response = await client.PostAsync(uri, queryString);

                                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                            {
                                                respond = await response.Content.ReadAsStringAsync();

                                                try
                                                {
                                                    jsonObj         = JsonConvert.DeserializeObject(respond);
                                                    item.Status     = 0;
                                                    faceIdToCompare = jsonObj[0].faceId;
                                                } catch (ArgumentOutOfRangeException e)
                                                {
                                                    e.ToString();
                                                }
                                            }

                                            _db.SaveChanges();
                                        }
                                    }

                                    uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/findsimilars");
                                    handler     = new HttpClientHandler();
                                    queryString = null;
                                    client      = new HttpClient(handler);
                                    //string respond = null;
                                    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                    pgInput = new PersonGroupInput()
                                    {
                                        FaceId     = faceIdToCompare,
                                        FaceListId = faceListId,
                                        maxNumOfCandidatesReturned = 10
                                    };

                                    queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                    queryString.Headers.Remove("Content-Type");
                                    queryString.Headers.Add("Content-Type", "application/json");
                                    response = await client.PostAsync(uri, queryString);

                                    respond = await response.Content.ReadAsStringAsync();

                                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                    {
                                        respond = await response.Content.ReadAsStringAsync();

                                        jsonObj = JsonConvert.DeserializeObject(respond);
                                        foreach (var item in jsonObj)
                                        {
                                            string    id = item.persistedFaceId;
                                            UserImage ui = _db.UserImages.Where(e => e.FaceId.Equals(id)).FirstOrDefault();
                                            ui.Confidence = item.confidence;
                                            imageToBeUsed.Add(id);
                                            _db.SaveChanges();
                                        }
                                    }
                                    else
                                    {
                                        failure = true;
                                    }

                                    uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/facelists/" + faceListId);
                                    handler     = new HttpClientHandler();
                                    queryString = null;
                                    client      = new HttpClient(handler);
                                    //string respond = null;
                                    client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");

                                    queryString = new StringContent("", Encoding.UTF8, "application/json");
                                    queryString.Headers.Remove("Content-Type");
                                    queryString.Headers.Add("Content-Type", "application/json");
                                    response = await client.DeleteAsync(uri);

                                    if (imageToBeUsed.Count < min)
                                    {
                                        Response.StatusCode = 400;
                                        output.Result       = "IMAGE_USERSTORE_LESS_ACCURATE";
                                    }
                                    else
                                    {
                                        if (user.PersonId != null)
                                        {
                                            uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/persongroups/" + personGroupId + "/persons/" + user.PersonId);
                                            handler     = new HttpClientHandler();
                                            queryString = null;
                                            client      = new HttpClient(handler);
                                            //string respond = null;
                                            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");

                                            queryString = new StringContent("", Encoding.UTF8, "application/json");
                                            queryString.Headers.Remove("Content-Type");
                                            queryString.Headers.Add("Content-Type", "application/json");
                                            response = await client.DeleteAsync(uri);
                                        }

                                        if (response.StatusCode != System.Net.HttpStatusCode.OK)
                                        {
                                            failure = true;
                                        }

                                        uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/persongroups/" + personGroupId + "/persons");
                                        handler     = new HttpClientHandler();
                                        queryString = null;
                                        client      = new HttpClient(handler);
                                        //string respond = null;
                                        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                        pgInput = new PersonGroupInput()
                                        {
                                            Name = user.Id
                                        };
                                        queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                        queryString.Headers.Remove("Content-Type");
                                        queryString.Headers.Add("Content-Type", "application/json");
                                        response = await client.PostAsync(uri, queryString);

                                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                        {
                                            respond = await response.Content.ReadAsStringAsync();

                                            jsonObj       = JsonConvert.DeserializeObject(respond);
                                            user.PersonId = jsonObj.personId;
                                            _db.SaveChanges();
                                        }
                                        else
                                        {
                                            failure = true;
                                        }

                                        foreach (UserImage item in imageStore)
                                        {
                                            item.Status = 0;
                                            _db.SaveChanges();
                                        }

                                        foreach (string s in imageToBeUsed)
                                        {
                                            if (min > 0)
                                            {
                                                UserImage item = imageStore.Where(e => e.FaceId.Equals(s)).FirstOrDefault();
                                                uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/persongroups/" + personGroupId + "/persons/" + user.PersonId + "/persistedFaces");
                                                handler     = new HttpClientHandler();
                                                queryString = null;
                                                client      = new HttpClient(handler);
                                                //string respond = null;
                                                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                                pgInput = new PersonGroupInput()
                                                {
                                                    Url = mainSiteUrl + "/" + item.Url
                                                };
                                                queryString = new StringContent(JsonConvert.SerializeObject(pgInput), Encoding.UTF8, "application/json");
                                                queryString.Headers.Remove("Content-Type");
                                                queryString.Headers.Add("Content-Type", "application/json");
                                                response = await client.PostAsync(uri, queryString);

                                                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                                {
                                                    respond = await response.Content.ReadAsStringAsync();

                                                    jsonObj     = JsonConvert.DeserializeObject(respond);
                                                    item.FaceId = jsonObj.persistedFaceId;
                                                    item.Status = 2;
                                                    _db.SaveChanges();
                                                }
                                                else
                                                {
                                                    failure = true;
                                                }
                                            }
                                            min--;
                                        }

                                        uri         = new Uri("https://bcp-facial.cognitiveservices.azure.com/face/v1.0/persongroups/" + personGroupId + "/train");
                                        handler     = new HttpClientHandler();
                                        queryString = null;
                                        client      = new HttpClient(handler);
                                        //string respond = null;
                                        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8d4c42ecbb784d909275492115ea56f0");
                                        queryString = new StringContent("", Encoding.UTF8, "application/json");
                                        queryString.Headers.Remove("Content-Type");
                                        queryString.Headers.Add("Content-Type", "application/json");
                                        response = await client.PostAsync(uri, queryString);

                                        if (failure)
                                        {
                                            Response.StatusCode = 500;
                                            output.Result       = "INCOMPLETE_PROCESS";
                                        }
                                        else
                                        {
                                            output.Result = "OK";
                                        }
                                    }
                                }
                                else
                                {
                                    Response.StatusCode = 500;
                                    output.Result       = "INTERNAL_ERROR";
                                }
                            }
                            else
                            {
                                Response.StatusCode = 400;
                                output.Result       = "USER_IMAGESTORE_LESS_MIN";
                            }
                        }
                    }
                    else
                    {
                        Response.StatusCode = 400;
                        output.Result       = "NO_PRIVILEGE";
                    }
                }
            }

            return(output);
        }
Пример #44
0
 partial void InsertUserImage(UserImage instance);
Пример #45
0
 partial void UpdateUserImage(UserImage instance);
Пример #46
0
        //==================================================================================//
        //      Store Admin information                                                     //
        //                                                                                  //
        //      Register the admin information if it is empty. Otherwise edit it.           //
        //                                                                                  //
        //      Note: If the edit is true then the account is being edited.                 //
        //      Otherwise it is being registered.                                           //
        //==================================================================================//
        public static bool StoreAdminData(RegisterModel regAdmin, ref bool edit)
        {
            int UserId = WebSecurity.GetUserId(regAdmin.EmailAddress);

            edit = false;

            try
            {
                SiteAdmin CurrentAdmin;

                using (ITintheDTestTableEntities context = new ITintheDTestTableEntities())
                {
                    // Put everything we find in the database in the var variable. All the
                    // information will be gotten using the User ID.

                    var AdminData = from r in context.SiteAdmin
                                    where r.UserId == UserId
                                    select r;

                    // If the user has some information then edit it.
                    // Otherwise register the account.

                    if (AdminData.Count() > 0 && UserId > 0)
                    {
                        CurrentAdmin = AdminData.FirstOrDefault();
                        CurrentAdmin.Status = regAdmin.AccountStatus;
                        CurrentAdmin.Company = regAdmin.CompanyName;
                        CurrentAdmin.EmailAddress = regAdmin.EmailAddress;
                        CurrentAdmin.Name = regAdmin.Name;
                        CurrentAdmin.Telephone = regAdmin.Telephone;
                        CurrentAdmin.UserId = UserId;

                        // Store the avatar if it is supplied.

                        if (regAdmin.ImageFile != null)
                        {
                            UserImage image = new UserImage();

                            using (MemoryStream ms = new MemoryStream())
                            {
                                regAdmin.ImageFile.InputStream.CopyTo(ms);

                                image.FileContent = ms.ToArray();
                                image.FileName = Path.GetFileName(regAdmin.ImageFile.FileName);
                                image.ContentType = regAdmin.ImageFile.ContentType;
                                image.ContentLength = regAdmin.ImageFile.ContentLength;

                                DatabaseHelper.UploadImage(image, CurrentAdmin.UserId);

                                CurrentAdmin.ImageUploaded = "Yes";
                                regAdmin.ImageUploaded = "Yes";
                            }
                        }

                        edit = true;
                    }

                    else
                    {
                        CurrentAdmin = new SiteAdmin();

                        CurrentAdmin.Status = regAdmin.AccountStatus;
                        CurrentAdmin.Company = regAdmin.CompanyName;
                        CurrentAdmin.Name = regAdmin.Name;
                        CurrentAdmin.EmailAddress = regAdmin.EmailAddress;
                        CurrentAdmin.Telephone = regAdmin.Telephone;

                        context.AddToSiteAdmin(CurrentAdmin);
                    }

                    try
                    {
                        // If the account is edited then save changes. Otherwise register the account.

                        if (edit == false)
                        {
                            WebSecurity.CreateUserAndAccount(regAdmin.EmailAddress, regAdmin.Password);

                            DatabaseHelper.AddUserToRole(regAdmin.EmailAddress, "Admin");

                            CurrentAdmin.UserId = WebSecurity.GetUserId(regAdmin.EmailAddress);

                            // Store the avatar if it is supplied.

                            if (regAdmin.ImageFile != null)
                            {
                                UserImage image = new UserImage();

                                using (MemoryStream ms = new MemoryStream())
                                {
                                    regAdmin.ImageFile.InputStream.CopyTo(ms);

                                    image.FileContent = ms.ToArray();
                                    image.FileName = Path.GetFileName(regAdmin.ImageFile.FileName);
                                    image.ContentType = regAdmin.ImageFile.ContentType;
                                    image.ContentLength = regAdmin.ImageFile.ContentLength;

                                    DatabaseHelper.UploadImage(image, CurrentAdmin.UserId);

                                    CurrentAdmin.ImageUploaded = "Yes";
                                    regAdmin.ImageUploaded = "Yes";
                                }
                            }

                            else
                            {
                                CurrentAdmin.ImageUploaded = "No";
                                regAdmin.ImageUploaded = "No";
                            }
                        }

                        context.SaveChanges();

                        return true;
                    }

                    catch (Exception ex)
                    {
                        string errorMessage = ex.Message;

                        return false;
                    }
                }
            }

            catch (Exception ex)
            {
                string exMessage = ex.Message;

                return false;
            }
        }