public IEnumerable<dynamic> Index( int? UserId, int? PictureId)
        {
            PhotoNetwork.Entities.User CurrentUser = GetCurrentUser();

            if (UserId == null)
            {
                UserId = (int?)CurrentUser.Id;
            }
            if (PictureId == null)
            {
                using (IDAL dal = new SqlDAL())
                {
                    PictureId = (int?)dal.PhotoRepository.ReadAll().Max(photo => photo.Id);
                }
            }
            int PicturesOnQuery = 9;
                using (IDAL dal = new SqlDAL())
                {
                    var tempQueue = dal.PhotoRepository.ReadAll().OrderByDescending(photo => photo.Id).Where(photo => (photo.UserID == UserId)&& (photo.Id <= PictureId)).Take(PicturesOnQuery);
                    if (UserId != CurrentUser.Id)
                    {
                        tempQueue.Where(photo => photo.IsPrivate == false);
                    }
                    return tempQueue.ToList();
                }
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            // накидываем всякие там claims на токен так, чтобы они в зашифрованом виде хранились у пользователя
            
            using (IDAL dal = new SqlDAL())
            {
                var user = dal.UserRepository.ReadAll().Where(ent => ((ent.Email == context.UserName) && (ent.Password == context.Password))).FirstOrDefault();
                if (user.Id == 0)
                {
                    context.SetError("Indavid password or username", "");
                }
                else
                {
                    var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                    identity.AddClaim(new Claim("sub", context.UserName));
                    identity.AddClaim(new Claim("role", user.RoleID.ToString()));

                    context.Validated(identity);
                }
            }

            


        }
        public string GetImage(int ImageId, int Size)
        {
            String filePath;
            PhotoNetwork.Entities.User CurrentUser = GetCurrentUser();
            PhotoNetwork.Entities.Photo tempPhoto;
            PhotoNetwork.Entities.User PhotoOwner;
            using (IDAL dal = new SqlDAL())
            {
                //TODO: или избавиться от address в модели, или вынести в отдельный метод подгрузку картинки (из внешнего источника или файловой системы)
                try
                {
                    tempPhoto = dal.PhotoRepository.Read(ImageId);
                    PhotoOwner = dal.UserRepository.ReadAll().Where(user => user.Id == tempPhoto.UserID).First();
                }
                catch
                {
                    return "";
                }
            }
            if ((PhotoOwner.Id != CurrentUser.Id) && (tempPhoto.IsPrivate))
            {
                return "";
            }
            filePath = File.Exists(SettingsProvider.FileRepositoryPath + ImageId + "-" + Size + ".jpg") ? (SettingsProvider.FileRepositoryPath + ImageId + "-" + Size + ".jpg") : (SettingsProvider.FileRepositoryPath + SettingsProvider.DefaultPhotoName + ".jpg");
            FileStream fileStream = new FileStream(filePath,FileMode.Open, FileAccess.Read);
            byte[] resultArray = new byte[fileStream.Length];
            fileStream.Read(resultArray, 0, (int)fileStream.Length);
            fileStream.Close();
            string resultString = System.Convert.ToBase64String(resultArray);

            return resultString;
        }
 public IHttpActionResult UserInfo(PhotoNetwork.Entities.User user)
 {
     using (IDAL dal = new SqlDAL())
     {
         dal.UserRepository.Update(user);
     }
     return Ok();
 }
 public IHttpActionResult RegisterNewUser(PhotoNetwork.Entities.User user)
 {
     user.RoleID = 1;
     using (IDAL dal = new SqlDAL())
     {
         dal.UserRepository.Create(user);
     }
     return Ok();
 }
        public void TestMethod1()
        {
            IQueryable<string> result;
            using (IDAL dal = new SqlDAL())
            {
                result = dal.UserRepository.ReadAll().Where(user => user.RoleID == 2)
                    .Select(user => user.Id).Join(dal.CommentRepository.ReadAll(), user => user, comment => comment.UserID, (user, comment) => comment.Text);
            }

            Assert.AreEqual( 341, result.ToList().Count());
        }
 public void TestMethod2()
 {
     IQueryable<PhotoNetwork.Entities.Photo> result;
     using (IDAL dal = new SqlDAL())
     {
         result = dal.PhotoRepository.ReadAll()
             .Join(dal.CommentRepository.ReadAll(), photo => photo.Id, comment => comment.PhotoID, (photo, comment) => photo)
             .Join(dal.LikeRepository.ReadAll(), photo => photo.Id, like => like.PhotoID, (photo, like) => photo)
             .Distinct();
     }
     Assert.AreEqual(96, result.Count());
 }
        public PhotoNetwork.Entities.User UserInfo()
        {
            var s = (ClaimsPrincipal)HttpContext.Current.User;
            var res = s.Claims.First(x => x.Type == "sub");
            PhotoNetwork.Entities.User user;
            using (IDAL dal = new SqlDAL())
            {
                user = dal.UserRepository.ReadAll().First(x => x.Email == res.Value);
            }

            return user;
        }
 public void TestMethod3()
 {
     try
     {
          using (IDAL dal =  new SqlDAL())
          {
             dal.UserRepository.Create(new PhotoNetwork.Entities.User() { Id = 1001 });
          }
     }
     catch (DbEntityValidationException e)
     {
         foreach (var eve in e.EntityValidationErrors)
         {
             Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                 eve.Entry.Entity.GetType().Name, eve.Entry.State);
             foreach (var ve in eve.ValidationErrors)
             {
                 Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                     ve.PropertyName, ve.ErrorMessage);
             }
         }
         throw;
     }
 }
        public string UploadImage()
        {
            var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
                var photo = new PhotoNetwork.Entities.Photo() { CreateDate = DateTime.Now };
                photo.UserID = GetCurrentUser().Id;
                photo.Description = HttpContext.Current.Request.Form.Get("Description");
                photo.IsPrivate = Convert.ToBoolean(HttpContext.Current.Request.Form.Get("IsPrivate"));
                if (httpPostedFile != null)
                {
                    using (IDAL dal = new SqlDAL())
                    {
                        photo.Address = "dfg";
                        photo = dal.PhotoRepository.Create(photo);
                        photo.Address = photo.Id.ToString();
                        dal.PhotoRepository.Update(photo);
                    }
                    httpPostedFile.SaveAs(SettingsProvider.FileRepositoryPath + photo.Address + "-3" + ".jpg");
                    httpPostedFile.SaveAs(SettingsProvider.FileRepositoryPath + photo.Address + "-2" + ".jpg");
                    httpPostedFile.SaveAs(SettingsProvider.FileRepositoryPath + photo.Address + "-1" + ".jpg");

                }
                else
                {
                    return "Bad input fild name";
                }
                return "Created";
        }
        private PhotoNetwork.Entities.User GetCurrentUser()
        {
            PhotoNetwork.Entities.User CurrentUser;
            using (IDAL dal = new SqlDAL())
            {

                var s = (ClaimsPrincipal)HttpContext.Current.User;
                var res = s.Claims.First(x => x.Type == "sub");
                CurrentUser = dal.UserRepository.ReadAll().First(user => user.Email == res.Value);
            }
            return CurrentUser;
        }