예제 #1
0
        public ActionResult DeleteShelf(ShelvesViewModel model)
        {
            int id = model.DeleteShelfId;
            using (var db = new SDCContext())
            {
                //sanity check: this shelf exists.
                var shelf = db.Shelves.Find(id);
                if (shelf == null)
                    return RedirectToAction("Index");

                var userProfile = (UserProfile)this.Session["UserInfo"];

                if (shelf.CanBeEdited(userProfile))
                {
                    //we allow deletion

                    //delete all books in this shelf.
                    //todo: delete all other entities that are linked
                    var books = (from b in db.Books
                                 where b.Shelf.Id == shelf.Id
                                 select b).ToList();
                    db.Books.RemoveRange(books);
                    db.Shelves.Remove(shelf);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    //bad user, bad!
                    return RedirectToAction("Index");
                }
            }
        }
예제 #2
0
        public static void Activity_BookRemoved(SDCContext db, UserProfile profile, Book book, string shelfName)
        {
            string template = "<p>Removed <strong>%booktitle% </strong> from %shelfname% <span class='text-muted'>on %when%</span></p>";
            var content = template
                .Replace("%booktitle%", book.Title)
                .Replace("%shelfname%", shelfName)
                .Replace("%when%", DateTime.Now.ToString(G.DATE));

            Activity activity = new Activity()
            {
                Profile = profile,
                Content = content,
                Type = ActivityType.RemoveBook
            };

            db.Activities.Add(activity);
            db.SaveChanges();
        }
예제 #3
0
        public static void Activity_BookUpdated(SDCContext db, UserProfile profile, Book book, string bookurl, string shelfurl)
        {
            string template = "<p>Updated <a href = '%bookurl%'> <strong>%booktitle%</strong> </a> in <a href = '%shelfurl%'> <strong>%shelfname%</strong> </a> <span class='text-muted'>on %when%</span></p>";
            var content = template
                .Replace("%bookurl%", bookurl)
                .Replace("%booktitle%", book.Title)
                .Replace("%shelfurl%", shelfurl)
                .Replace("%shelfname%", book.Shelf.Name)
                .Replace("%when%", DateTime.Now.ToString(G.DATE));

            Activity activity = new Activity()
            {
                Profile = profile,
                Content = content,
                Type = ActivityType.UpdateBook
            };

            db.Activities.Add(activity);
            db.SaveChanges();
        }
예제 #4
0
        public static void Activity_BookUpdated(SDCContext db, UserProfile profile, Book book, string bookurl, string shelfurl)
        {
            string template = "<p>Updated <a href = '%bookurl%'> <strong>%booktitle%</strong> </a> in <a href = '%shelfurl%'> <strong>%shelfname%</strong> </a> <span class='text-muted'>on %when%</span></p>";
            var    content  = template
                              .Replace("%bookurl%", bookurl)
                              .Replace("%booktitle%", book.Title)
                              .Replace("%shelfurl%", shelfurl)
                              .Replace("%shelfname%", book.Shelf.Name)
                              .Replace("%when%", DateTime.Now.ToString(G.DATE));

            Activity activity = new Activity()
            {
                Profile = profile,
                Content = content,
                Type    = ActivityType.UpdateBook
            };

            db.Activities.Add(activity);
            db.SaveChanges();
        }
예제 #5
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider       = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (SDCContext db = new SDCContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile {
                            UserName = model.UserName
                        });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return(RedirectToLocal(returnUrl));
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl           = returnUrl;
            return(View(model));
        }
예제 #6
0
        public JsonResult AddBook(BookViewModel bookViewModel)
        {
            var profile = (UserProfile)Session["UserInfo"];
            if (!User.Identity.IsAuthenticated || profile == null)
            {
                //STUPID
                return Json(new { id = -1 });
            }

            int id = 0;

            using (var db = new SDCContext())
            {
                db.AttachProfile(profile);

                //verify that the shelf exists and it belongs to the logged in user
                var shelf = db.Shelves.Include(o => o.Owner).FirstOrDefault(s => s.Id == bookViewModel.ShelfId);
                if (shelf == null || shelf.Owner.UserId != profile.UserId)
                {
                    //STUPID
                    return Json(new { id = -1 });
                }

                Book book = AutoMapper.Mapper.Map<Book>(bookViewModel);
                book.Shelf = shelf;
                book.AddedDate = DateTime.Now;
                Book.MapComplexProperties(db, book, bookViewModel, profile);

                db.Books.Add(book);
                db.SaveChanges();
                id = book.Id;

                //activity
                SDC.Library.Helpers.ActivityHelper.Activity_BookAdded(
                    db, profile, book,
                    Url.Action("ViewBook", "Book", new { id = book.Id }),
                    Url.Action("Details", "Shelves", new { id = book.Shelf.Id }));
            }

            return Json(new { id = id });
        }
예제 #7
0
        public ActionResult UploadBookPicture(BookImageUploadViewModel model)
        {
            try
            {
                if (model.ImageUpload != null &&
                    model.ImageUpload.ContentLength > 0 &&
                    model.ImageUpload.ContentLength < 1024 * 1024 &&
                    model.UploadForBookId != 0)
                {
                    S3File f = S3.UploadBookImage(
                        model.UploadForBookId.ToString(),
                        model.ImageUpload.FileName,
                        model.ImageUpload.InputStream);

                    using (var db = new SDCContext())
                    {
                        var book = db.Books.Include(b => b.Pictures).First(b => b.Id == model.UploadForBookId);
                        book.Pictures.Add(new BookPicture()
                        {
                            Url    = f.Url,
                            Key    = f.Key,
                            Title  = "",
                            IsMain = false
                        });

                        db.SaveChanges();
                        return(new HttpStatusCodeResult(HttpStatusCode.OK));
                    }
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #8
0
        public ActionResult AuthorScrapeWiki()
        {
            string baseUrl = "https://en.wikipedia.org/wiki/List_of_authors_by_name:_";
            int updated = 0;

            //65..90
            using (var db = new SDCContext())
            {
                //load all authors
                db.Set<Author>().Load();

                for (int i = 65; i <= 90; i++)
                {
                    var url = baseUrl + (char)i;
                    Scrape(db, url, ref updated);
                }

                db.SaveChanges();
            }

            throw new NotImplementedException();
        }
예제 #9
0
        public ActionResult ApproveAuthor(int id)
        {
            try
            {
                var profile = (UserProfile)Session["UserInfo"];
                if (profile == null || profile.Role == RolesCustom.USER)
                    return RedirectToAction("Index", "Home");

                using (var db = new SDCContext())
                {
                    var author = db.Authors.Find(id);
                    author.IsVerified = true;
                    author.LastModifiedBy = db.AttachProfile(profile);
                    db.SaveChanges();
                }

                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
예제 #10
0
        public ActionResult ChangeAvatar(int avatarId)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(Redirect("/"));
            }

            var profile = db.UserProfiles.First(p => p.UserName == User.Identity.Name);
            var avatar  = db.Avatars.Find(avatarId);

            profile.Avatar = avatar;
            db.SaveChanges();


            ((UserProfile)Session["UserInfo"]).Avatar = avatar;

            return(RedirectToAction("Index"));
        }
예제 #11
0
        public ActionResult DeleteShelf(ShelvesViewModel model)
        {
            int id = model.DeleteShelfId;

            using (var db = new SDCContext())
            {
                //sanity check: this shelf exists.
                var shelf = db.Shelves.Find(id);
                if (shelf == null)
                {
                    return(RedirectToAction("Index"));
                }

                var userProfile = (UserProfile)this.Session["UserInfo"];

                if (shelf.CanBeEdited(userProfile))
                {
                    //we allow deletion

                    //delete all books in this shelf.
                    //todo: delete all other entities that are linked
                    var books = (from b in db.Books
                                 where b.Shelf.Id == shelf.Id
                                 select b).ToList();
                    db.Books.RemoveRange(books);
                    db.Shelves.Remove(shelf);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                else
                {
                    //bad user, bad!
                    return(RedirectToAction("Index"));
                }
            }
        }
예제 #12
0
        public ActionResult EditShelf(ShelvesViewModel model)
        {
            if (String.IsNullOrEmpty(model.Name))
                return RedirectToAction("Index");

            int id = model.EditShelfId;
            using(var db = new SDCContext())
            {
                var shelf = db.Shelves.Find(id);
                if (shelf == null)
                    return RedirectToAction("Index");

                var userProfile = (UserProfile)this.Session["UserInfo"];
                if (shelf.CanBeEdited(userProfile))
                {
                    shelf.Name = model.Name;
                    shelf.IsVisible = model.IsVisible;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    return RedirectToAction("Index");
                }
            }
        }
예제 #13
0
        public Task<int> Import(int max = 0)
        {
            if (!_csvDataLoaded)
                throw new Exception("CSV data not loaded.");

            if (max == 0)
                _max = TotalBookCount;
            else
                _max = max;

            Task<int> importTask = new Task<int>(() =>
            {
                try {
                    Progress = 0;
                    Running = true;
                    Cancel = false;
                    ImportStart = DateTime.Now;
                    TargetCount = _max;
                    using (var db = new SDCContext())
                    {
                        db.Configuration.AutoDetectChangesEnabled = false;

                        _allGenres = db.Genres.ToArray();
                        _lang = db.Languages.Find("FR");
                        _country = db.Countries.Find("CA");
                        _city = db.Cities.Find(4);

                        var authors = db.Authors.ToList();
                        authors.ForEach(a =>
                        {
                            if (!_authorsSet.ContainsKey(a.Name))
                                _authorsSet.Add(a.Name, a);
                        });
                        var publishers = db.Publishers.ToList();
                        publishers.ForEach(p =>
                        {
                            if (!_publishersSet.ContainsKey(p.Name))
                                _publishersSet.Add(p.Name, p);
                        });

                        do
                        {
                            string firstName = _firstNames[_rnd.Next(0, _firstNames.Length - 1)];
                            string lastName = _lastNames[_rnd.Next(0, _lastNames.Length - 1)];

                            Shelf shelf;
                            var profile = CreateUser(db, firstName, lastName, out shelf);
                            LoadBooks(db, profile, shelf);

                            db.ChangeTracker.DetectChanges();
                            db.SaveChanges();

                            var localBooks = db.Books.Local.ToArray();
                            foreach(var le in localBooks)
                            {
                                db.Entry(le).State = System.Data.Entity.EntityState.Detached;
                            }
                            var localPictures = db.BookPictures.Local.ToArray();
                            foreach(var le in localPictures)
                            {
                                db.Entry(le).State = System.Data.Entity.EntityState.Detached;
                            }

                        } while (Progress < _max && !Cancel);
                    }

                    return Progress;
                }
                finally
                {
                    Running = false;
                }
            });

            importTask.Start();
            return importTask;
        }
예제 #14
0
파일: SDCService.cs 프로젝트: teo-mateo/sdc
        public SearchResultDTO Search(string term, int? userId = null)
        {
            try
            {
                term = term.Trim();
                if (String.IsNullOrWhiteSpace(term) || term.Length < 3)
                {
                    return SearchResultDTO.Empty();
                }

                using (var db = new SDCContext())
                {

                    UserProfile profile = null;
                    if (userId != null)
                        profile = db.UserProfiles.FirstOrDefault(p => p.UserId == (int)userId);

                    var booksResult = db.Books
                        .Where(b => b.Shelf.IsVisible && b.Title.Contains(term))
                        .Select(b => new SearchResultBookDTO()
                         {
                             Id = b.Id,
                             OwnerId = b.Shelf.Owner.UserId,
                             OwnerUserName = b.Shelf.Owner.UserName,
                             OwnerRating = 3.5f,
                             OwnerAvatarUrl = b.Shelf.Owner.Avatar.Url,
                             Title = b.Title,
                             Authors = b.Authors.Select(a => new AuthorDTO()
                             {
                                 Id = a.Id,
                                 Name = a.Name
                             }).ToList(),
                             BookPictures = b.Pictures.Select(p => new BookPictureDTO()
                             {
                                 Url = p.Url
                             }).ToList()
                         }).ToArray();

                    for(int i = 0; i < booksResult.Length; i++)
                    {
                        booksResult[i].Rank = i + 1;
                    }

                    BookSearch search = new BookSearch()
                    {
                        Date = DateTime.Now,
                        Term = term,
                        User = profile
                    };

                    db.BookSearches.Add(search);
                    db.SaveChanges();

                    var result = new SearchResultDTO(search.Id, booksResult, search.Term);

                    _cache.Add(result.Id, result);
                    return result.Subset(0, 10);
                }
            }
            catch (Exception ex)
            {
                //return empty result
                return SearchResultDTO.Empty();
            }
        }
예제 #15
0
        public ActionResult DeleteAccount(UserProfileViewModel model)
        {
            try
            {
                if (Membership.ValidateUser(User.Identity.Name, model.Password))
                {
                    //delete profile and log out.
                    using (var db = new SDCContext())
                    using (var t = db.Database.BeginTransaction())
                    {
                        var profile = db.UserProfiles.First(p => p.UserName == User.Identity.Name);

                        //delete login traces for this account
                        var login_traces = db.LogInTraces.Where(p => p.User.UserId == profile.UserId).ToList();
                        db.LogInTraces.RemoveRange(login_traces);
                        //delete custom avatar
                        var custom_avatar = db.Avatars.FirstOrDefault(p => p.CustomForUserId == profile.UserId);
                        if (custom_avatar != null)
                        {
                            var relative_avatar_path = VirtualPathUtility.ToAppRelative(custom_avatar.Url);
                            var path = Server.MapPath(relative_avatar_path);
                            System.IO.File.Delete(path);
                            db.Avatars.Remove(custom_avatar);
                        }

                        db.SaveChanges();
                        t.Commit();

                    }

                    //delete user profile
                    // I wonder if the transaction has anything to do with it...
                    Membership.DeleteUser(User.Identity.Name, true);
                    WebSecurity.Logout();
                }
                else
                {
                    model.Message = "Enter your password to delete your account.";
                    //redirect to /profile/index#privacy
                    return Redirect(Url.RouteUrl(new
                    {
                        controller = "Profile",
                        action = "Index"
                    }) + "#DeleteProfile");
                }
            }
            catch (Exception ex)
            {
                //todo: log this shit.
            }

            return Redirect("/");
        }
예제 #16
0
        public ActionResult NewShelf(ShelvesViewModel model)
        {
            if (String.IsNullOrEmpty(model.Name))
            {
                return RedirectToAction("Index");
            }

            UserProfile profile = null;

            //save
            using (var db = new SDCContext())
            {
                profile = db.UserProfiles.Find(((UserProfile)Session["UserInfo"]).UserId);

                Shelf newShelf = new Shelf()
                {
                    CreationDate = DateTime.Now,
                    Name = model.Name,
                    IsVisible = model.IsVisible,
                    Owner = profile
                };

                db.Shelves.Add(newShelf);
                db.SaveChanges();
                Session["UserInfoEx"] = profile.GetExtendedInfo(db);
            }

            return RedirectToAction("Index");
        }
예제 #17
0
        public ActionResult DeleteBook(int deleteBookId)
        {
            using (var db = new SDCContext())
            {
                var book = db.Books
                    .Include(b=>b.Pictures)
                    .Include(b=>b.Shelf)
                    .Include(b=>b.Shelf.Owner)
                    .FirstOrDefault(b=>b.Id == deleteBookId);
                if(book != null)
                {
                    var shelfId = book.Shelf.Id;

                    // only admin, curator or shelf owner can delete it.
                    var profile = (UserProfile)Session["UserInfo"];
                    if( profile.Role == RolesCustom.ADMIN ||
                        profile.Role == RolesCustom.CURATOR ||
                        book.Shelf.Owner.UserId == profile.UserId)
                    {
                        //f**k this.
                        profile = db.UserProfiles.Find(profile.UserId);

                        //remove book images
                        foreach(var pic in book.Pictures)
                        {
                            db.BookPictures.Remove(pic);
                            S3.DeleteFile(pic.Key);
                        }

                        string shelfName = book.Shelf.Name;

                        db.Books.Remove(book);
                        db.SaveChanges();

                        //activity
                        SDC.Library.Helpers.ActivityHelper.Activity_BookRemoved(db, profile, book, shelfName);

                        return RedirectToAction("Details", "Shelves", new { id = shelfId });
                    }
                }
            }
            //any other case
            return RedirectToAction("Index", "Home");
        }
예제 #18
0
        public ActionResult UpdateBook(BookViewModel bookViewModel)
        {
            var profile = ((UserProfile)Session["UserInfo"]);
            if (!User.Identity.IsAuthenticated || profile == null)
                return RedirectToAction("Index", "Home");

            try
            {
                using (var db = new SDCContext())
                {
                    db.AttachProfile(profile);

                    var book = db.Books
                        .Include(b=>b.Authors)
                        .Include(b=>b.Genres)
                        .Include(b=>b.Publisher)
                        .Include(b=>b.Language)
                        .Include(b=>b.Shelf)
                        .First(b => b.Id == bookViewModel.Id);

                    AutoMapper.Mapper.Map<BookViewModel, Book>(bookViewModel, book);

                    Book.MapComplexProperties(db, book, bookViewModel, profile);

                    db.SaveChanges();

                    //activity
                    SDC.Library.Helpers.ActivityHelper.Activity_BookUpdated(
                        db, profile, book,
                        Url.Action("ViewBook", "Book", new { id = book.Id }),
                        Url.Action("Details", "Shelves", new { id = book.Shelf.Id }));

                    return new HttpStatusCodeResult(HttpStatusCode.OK);
                }
            }
            catch(Exception ex)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
        }
예제 #19
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    using (var db = new SDCContext())
                    {
                        var avatar = db.Avatars.Where(a => a.CustomForUserId == 0).OrderBy(a=>a.Id).First();

                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                            new {
                                Email = model.Email,
                                Avatar_Id = avatar.Id, // by default, use the first avatar that is available.
                                LastSeen = DateTime.Now,
                                IsLocked = false,
                                ShowEmail = false,
                                City_Id = 1
                        });

                        Roles.AddUsersToRole(new string[] { model.UserName }, RolesCustom.USER);

                        if (WebSecurity.Login(model.UserName, model.Password))
                        {
                            var profile = db.UserProfiles
                                .Include(p => p.Avatar)
                                .Include(p => p.Country.Language)
                                .First(p => p.UserName == model.UserName);

                            //default page size:10
                            profile.PageSize = 10;
                            profile.Created = DateTime.Now;
                            profile.City = db.Cities.Include(c=>c.Country).First();
                            profile.Country = profile.City.Country;

                            //create default shelf
                            Shelf defaultShelf = new Shelf()
                            {
                                CreationDate = DateTime.Now,
                                Name = String.Format("{0}'s shelf", model.UserName),
                                IsVisible = true,
                                Owner = profile
                            };
                            db.Shelves.Add(defaultShelf);
                            db.SaveChanges();

                            SaveLoginTrace(model.UserName, db);

                            profile.Role = Roles.GetRolesForUser(model.UserName)[0];
                            profile.Shelves = db.Shelves.Where(p => p.Owner.UserId == profile.UserId).ToList();

                            Session["UserInfo"] = profile;
                            Session["UserInfoEx"] = profile.GetExtendedInfo(db);
                        }

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

                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
예제 #20
0
        public ActionResult DeleteAuthor(int id)
        {
            try
            {
                var profile = (UserProfile)Session["UserInfo"];
                if (profile == null || profile.Role == RolesCustom.USER)
                    return RedirectToAction("Index", "Home");

                using (var db = new SDCContext())
                using(var trans = db.Database.BeginTransaction())
                {
                    //delete books
                    //delete book images
                    //delete author

                    var books = db.Books
                        .Include(b => b.Pictures)
                        .Where(b => b.Authors.Any(a => a.Id == id)).ToArray();

                    foreach (var book in books)
                    {
                        //delete book images
                        foreach (var pic in book.Pictures.ToArray())
                        {
                            //delete from s3
                            if (!String.IsNullOrEmpty(pic.Key))
                            {
                                S3.DeleteFile(pic.Key);
                            }
                            //delete from db
                            db.BookPictures.Remove(pic);
                        }

                        //delete book
                        db.Books.Remove(book);
                    }

                    var author = db.Authors
                        .Include(a => a.Books)
                        .Include(a => a.Books.Select(b => b.Pictures))
                        .First(a => a.Id == id);

                    db.Authors.Remove(author);
                    db.SaveChanges();
                    trans.Commit();
                }

                return new HttpStatusCodeResult(HttpStatusCode.OK);

            }
            catch (Exception)
            {

                throw;
            }
        }
예제 #21
0
        public ActionResult DeleteBookPicture(int id)
        {
            try
            {
                var profile = (UserProfile)this.Session["UserInfo"];

                using (var db = new SDCContext())
                using (var trans = db.Database.BeginTransaction())
                {
                    var picture = db.BookPictures
                        .Include(p => p.Book)
                        .Include(p => p.Book.Pictures)
                        .Include(p => p.Book.Shelf)
                        .Include(p => p.Book.Shelf.Owner)
                        .FirstOrDefault(p => p.Id == id);

                    if (picture != null)
                    {
                        if (picture.Book.Shelf.Owner.UserId == profile.UserId ||
                            profile.IsAdmin || profile.IsCurator)
                        {
                            picture.Book.Pictures.Remove(picture);
                            db.SaveChanges();

                            try
                            {
                                S3.DeleteFile(picture.Key);
                            }
                            catch (Exception ex)
                            {
                                //todo: log
                                trans.Rollback();
                                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
                            }
                            trans.Commit();
                        }
                        else
                        {
                            throw new Exception("Unauthorized");
                        }
                    }
                }

                return new HttpStatusCodeResult(HttpStatusCode.OK);
            }
            catch(Exception ex)
            {
                //todo: log.
                throw ex;
            }
        }
예제 #22
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    using (var db = new SDCContext())
                    {
                        var avatar = db.Avatars.Where(a => a.CustomForUserId == 0).OrderBy(a => a.Id).First();

                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password,
                                                         new {
                            Email     = model.Email,
                            Avatar_Id = avatar.Id,     // by default, use the first avatar that is available.
                            LastSeen  = DateTime.Now,
                            IsLocked  = false,
                            ShowEmail = false,
                            City_Id   = 1
                        });

                        Roles.AddUsersToRole(new string[] { model.UserName }, RolesCustom.USER);

                        if (WebSecurity.Login(model.UserName, model.Password))
                        {
                            var profile = db.UserProfiles
                                          .Include(p => p.Avatar)
                                          .Include(p => p.Country.Language)
                                          .First(p => p.UserName == model.UserName);

                            //default page size:10
                            profile.PageSize = 10;
                            profile.Created  = DateTime.Now;
                            profile.City     = db.Cities.Include(c => c.Country).First();
                            profile.Country  = profile.City.Country;

                            //create default shelf
                            Shelf defaultShelf = new Shelf()
                            {
                                CreationDate = DateTime.Now,
                                Name         = String.Format("{0}'s shelf", model.UserName),
                                IsVisible    = true,
                                Owner        = profile
                            };
                            db.Shelves.Add(defaultShelf);
                            db.SaveChanges();

                            SaveLoginTrace(model.UserName, db);


                            profile.Role    = Roles.GetRolesForUser(model.UserName)[0];
                            profile.Shelves = db.Shelves.Where(p => p.Owner.UserId == profile.UserId).ToList();

                            Session["UserInfo"]   = profile;
                            Session["UserInfoEx"] = profile.GetExtendedInfo(db);
                        }

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #23
0
 public void UpdatePageSize(SDCContext db, int pagesize)
 {
     //update profile page size
     if (pagesize != this.PageSize)
     {
         var profile = db.UserProfiles
             .Include(p => p.Country)
             .FirstOrDefault(p => p.UserId == this.UserId);
         profile.PageSize = pagesize;
         db.SaveChanges();
     }
 }
예제 #24
0
        private void SaveLoginTrace(string userName, SDCContext db)
        {
            DateTime now = DateTime.Now;

            var profile = db.UserProfiles.First(p => p.UserName == userName);
            profile.LastSeen = now;

            string ip = this.Request.ServerVariables["REMOTE_ADDR"];
            var trace = new LogInTrace()
            {
                User = profile,
                Timestamp = now,
                IPAddress = ip
            };

            db.LogInTraces.Add(trace);
            db.SaveChanges();
        }
예제 #25
0
        public SearchResultDTO Search(string term, int?userId = null)
        {
            try
            {
                term = term.Trim();
                if (String.IsNullOrWhiteSpace(term) || term.Length < 3)
                {
                    return(SearchResultDTO.Empty());
                }

                using (var db = new SDCContext())
                {
                    UserProfile profile = null;
                    if (userId != null)
                    {
                        profile = db.UserProfiles.FirstOrDefault(p => p.UserId == (int)userId);
                    }

                    var booksResult = db.Books
                                      .Where(b => b.Shelf.IsVisible && b.Title.Contains(term))
                                      .Select(b => new SearchResultBookDTO()
                    {
                        Id             = b.Id,
                        OwnerId        = b.Shelf.Owner.UserId,
                        OwnerUserName  = b.Shelf.Owner.UserName,
                        OwnerRating    = 3.5f,
                        OwnerAvatarUrl = b.Shelf.Owner.Avatar.Url,
                        Title          = b.Title,
                        Authors        = b.Authors.Select(a => new AuthorDTO()
                        {
                            Id   = a.Id,
                            Name = a.Name
                        }).ToList(),
                        BookPictures = b.Pictures.Select(p => new BookPictureDTO()
                        {
                            Url = p.Url
                        }).ToList()
                    }).ToArray();

                    for (int i = 0; i < booksResult.Length; i++)
                    {
                        booksResult[i].Rank = i + 1;
                    }

                    BookSearch search = new BookSearch()
                    {
                        Date = DateTime.Now,
                        Term = term,
                        User = profile
                    };

                    db.BookSearches.Add(search);
                    db.SaveChanges();

                    var result = new SearchResultDTO(search.Id, booksResult, search.Term);

                    _cache.Add(result.Id, result);
                    return(result.Subset(0, 10));
                }
            }
            catch (Exception ex)
            {
                //return empty result
                return(SearchResultDTO.Empty());
            }
        }
예제 #26
0
        public ActionResult UploadBookPicture(BookImageUploadViewModel model)
        {
            try
            {
                if (model.ImageUpload != null &&
                    model.ImageUpload.ContentLength > 0 &&
                    model.ImageUpload.ContentLength < 1024 * 1024 &&
                    model.UploadForBookId != 0)
                {
                    S3File f = S3.UploadBookImage(
                        model.UploadForBookId.ToString(),
                        model.ImageUpload.FileName,
                        model.ImageUpload.InputStream);

                    using(var db = new SDCContext())
                    {
                        var book = db.Books.Include(b => b.Pictures).First(b => b.Id == model.UploadForBookId);
                        book.Pictures.Add(new BookPicture()
                        {
                            Url = f.Url,
                            Key = f.Key,
                            Title = "",
                            IsMain = false
                        });

                        db.SaveChanges();
                        return new HttpStatusCodeResult(HttpStatusCode.OK);
                    }
                }
                else
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #27
0
        public Task <int> Import(int max = 0)
        {
            if (!_csvDataLoaded)
            {
                throw new Exception("CSV data not loaded.");
            }

            if (max == 0)
            {
                _max = TotalBookCount;
            }
            else
            {
                _max = max;
            }

            Task <int> importTask = new Task <int>(() =>
            {
                try {
                    Progress    = 0;
                    Running     = true;
                    Cancel      = false;
                    ImportStart = DateTime.Now;
                    TargetCount = _max;
                    using (var db = new SDCContext())
                    {
                        db.Configuration.AutoDetectChangesEnabled = false;

                        _allGenres = db.Genres.ToArray();
                        _lang      = db.Languages.Find("FR");
                        _country   = db.Countries.Find("CA");
                        _city      = db.Cities.Find(4);

                        var authors = db.Authors.ToList();
                        authors.ForEach(a =>
                        {
                            if (!_authorsSet.ContainsKey(a.Name))
                            {
                                _authorsSet.Add(a.Name, a);
                            }
                        });
                        var publishers = db.Publishers.ToList();
                        publishers.ForEach(p =>
                        {
                            if (!_publishersSet.ContainsKey(p.Name))
                            {
                                _publishersSet.Add(p.Name, p);
                            }
                        });

                        do
                        {
                            string firstName = _firstNames[_rnd.Next(0, _firstNames.Length - 1)];
                            string lastName  = _lastNames[_rnd.Next(0, _lastNames.Length - 1)];

                            Shelf shelf;
                            var profile = CreateUser(db, firstName, lastName, out shelf);
                            LoadBooks(db, profile, shelf);

                            db.ChangeTracker.DetectChanges();
                            db.SaveChanges();

                            var localBooks = db.Books.Local.ToArray();
                            foreach (var le in localBooks)
                            {
                                db.Entry(le).State = System.Data.Entity.EntityState.Detached;
                            }
                            var localPictures = db.BookPictures.Local.ToArray();
                            foreach (var le in localPictures)
                            {
                                db.Entry(le).State = System.Data.Entity.EntityState.Detached;
                            }
                        } while (Progress < _max && !Cancel);
                    }

                    return(Progress);
                }
                finally
                {
                    Running = false;
                }
            });


            importTask.Start();
            return(importTask);
        }
예제 #28
0
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;

            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (SDCContext db = new SDCContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
                        db.SaveChanges();

                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }