Exemple #1
0
        private async void Task5_Delete_Employee_OkResult()
        {
            //Arrange
            _context    = new SDCContext(dbContextOptions);
            _controller = new EmployeesController(_context);
            var employee = new Employee()
            {
                UserName  = "******",
                FirstName = "Kevin",
                LastName  = "Durant",
                Password  = "******",
                JobId     = 3
            };

            //Act
            var resultCreate = await _controller.PostEmployee(employee);

            var okResult  = resultCreate.Should().BeOfType <CreatedAtActionResult>().Subject;
            var resClient = okResult.Value.Should().BeAssignableTo <Employee>().Subject;
            int delId     = resClient.UserId;
            var result    = await _controller.DeleteEmployee(delId);

            //Assert
            Assert.IsType <OkObjectResult>(result);
        }
Exemple #2
0
        public async void Task3_Post_NewEmployee_FindName()
        {
            //Arrange
            _context    = new SDCContext(dbContextOptions);
            _controller = new EmployeesController(_context);
            var employee = new Employee()
            {
                UserName  = "******",
                FirstName = "Pascal",
                LastName  = "Siakam",
                Password  = "******",
                JobId     = 3
            };

            //Act
            var result = await _controller.PostEmployee(employee);

            //Assert
            var okResult  = result.Should().BeOfType <CreatedAtActionResult>().Subject;
            var resClient = okResult.Value.Should().BeAssignableTo <Employee>().Subject;

            resClient.FirstName.Should().Be("Pascal");

            //delete JayNew
            int newId        = _context.Employee.FirstOrDefault(p => p.FirstName == "Pascal").UserId;
            var resultDelete = await _controller.DeleteEmployee(newId);
        }
Exemple #3
0
        public async void Task3_Post_New_Product_FindName()
        {
            //Arrange
            _context    = new SDCContext(dbContextOptions);
            _controller = new ProductsController(_context);
            var product = new Product()
            {
                SupplierId = 1,
                ProductId  = "NewPKItem"
            };

            //Act
            var result = await _controller.PostProduct(product);

            //Assert
            var okResult   = result.Should().BeOfType <CreatedAtActionResult>().Subject;
            var resProduct = okResult.Value.Should().BeAssignableTo <Product>().Subject;

            resProduct.ProductId.Should().Be("NewPKItem");

            //delete JayNew
            int    SupplierId   = _context.Product.FirstOrDefault(p => p.ProductId == "NewPKItem").SupplierId;
            string ProductId    = _context.Product.FirstOrDefault(p => p.ProductId == "NewPKItem").ProductId;
            var    resultDelete = await _controller.DeleteProduct(ProductId, SupplierId);
        }
Exemple #4
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"));
        }
Exemple #5
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;
            }
        }
        /// <summary>
        /// on every's request OnAuthorization: 
        /// get the current user's profile
        /// if not set already, set it as session data.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                Library.Redis.ActivityTracker.TrackActive(filterContext.RequestContext.HttpContext.User.Identity.Name);

                if(filterContext.RequestContext.HttpContext.Session["UserInfo"] == null)
                {
                    using (var db = new SDCContext())
                    {
                        var profile = db.UserProfiles
                            .Include(p=>p.Avatar)
                            .Include(p=>p.Country.Language)
                            .FirstOrDefault(p => p.UserName == filterContext.RequestContext.HttpContext.User.Identity.Name);

                        if(profile != null)
                        {
                            profile.Role = Roles.GetRolesForUser(profile.UserName)[0];
                            profile.Shelves = db.Shelves.Where(p => p.Owner.UserId == profile.UserId).ToList();
                            filterContext.RequestContext.HttpContext.Session["UserInfo"] = profile;
                            filterContext.RequestContext.HttpContext.Session["UserInfoEx"] = profile.GetExtendedInfo(db);
                        }
                        else
                        {
                            filterContext.RequestContext.HttpContext.Session["UserInfo"] = null;
                            filterContext.RequestContext.HttpContext.Session["UserInfoEx"] = null;
                        }
                    }
                }
            }
        }
Exemple #7
0
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
            {
                using (var db = new SDCContext())
                {
                    var profile = db.UserProfiles
                                  .Include(p => p.Avatar)
                                  .Include(p => p.Country.Language)
                                  .First(p => p.UserName == model.UserName);
                    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);
                }

                SaveLoginTrace(model.UserName);
                return(RedirectToAction("Index", "Home"));
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return(View(model));
        }
Exemple #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();
        }
Exemple #9
0
 private void SaveLoginTrace(string userName)
 {
     using (var db = new SDCContext())
     {
         SaveLoginTrace(userName, db);
     }
 }
Exemple #10
0
        /// <summary>
        /// on every's request OnAuthorization:
        /// get the current user's profile
        /// if not set already, set it as session data.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
            {
                Library.Redis.ActivityTracker.TrackActive(filterContext.RequestContext.HttpContext.User.Identity.Name);

                if (filterContext.RequestContext.HttpContext.Session["UserInfo"] == null)
                {
                    using (var db = new SDCContext())
                    {
                        var profile = db.UserProfiles
                                      .Include(p => p.Avatar)
                                      .Include(p => p.Country.Language)
                                      .FirstOrDefault(p => p.UserName == filterContext.RequestContext.HttpContext.User.Identity.Name);

                        if (profile != null)
                        {
                            profile.Role    = Roles.GetRolesForUser(profile.UserName)[0];
                            profile.Shelves = db.Shelves.Where(p => p.Owner.UserId == profile.UserId).ToList();
                            filterContext.RequestContext.HttpContext.Session["UserInfo"]   = profile;
                            filterContext.RequestContext.HttpContext.Session["UserInfoEx"] = profile.GetExtendedInfo(db);
                        }
                        else
                        {
                            filterContext.RequestContext.HttpContext.Session["UserInfo"]   = null;
                            filterContext.RequestContext.HttpContext.Session["UserInfoEx"] = null;
                        }
                    }
                }
            }
        }
Exemple #11
0
        public dynamic GetExtendedInfo(SDCContext db)
        {
            var shelves = (from s in db.Shelves
                           join b in db.Books on s.Id equals b.Shelf.Id into sb
                           where s.Owner.UserId == UserId
                           select new
            {
                Id = s.Id,
                Name = s.Name,
                Books = sb.Count()
            }).ToArray();

            dynamic info = new ExpandoObject();

            info.Shelves = shelves.Select(s =>
            {
                dynamic shelf = new ExpandoObject();
                shelf.Id      = s.Id;
                shelf.Name    = s.Name;
                shelf.Books   = s.Books;
                return(shelf);
            });
            return(info);

            //dynamic o = new ExpandoObject();
            //o.Prop = "a property";
        }
        private async void Task5_Delete_Code_OkResult()
        {
            //Arrange
            _context    = new SDCContext(dbContextOptions);
            _controller = new CodeListsController(_context);
            var code = new CodeList()
            {
                CategoryId = 1,
                CodeId     = 10,
                CodeName   = "New and Del Pickle",
            };

            //Act
            var resultCreate = await _controller.PostCodeList(code);

            var okResult      = resultCreate.Should().BeOfType <CreatedAtActionResult>().Subject;
            var resClient     = okResult.Value.Should().BeAssignableTo <CodeList>().Subject;
            int delcategoryId = resClient.CategoryId;
            int delcodeId     = resClient.CodeId;

            var result = await _controller.DeleteCodeList(delcategoryId, delcodeId);

            //Assert
            Assert.IsType <OkObjectResult>(result);
        }
Exemple #13
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");
                }
            }
        }
        public async void Task3_Post_NewCode_FindName()
        {
            //Arrange
            _context    = new SDCContext(dbContextOptions);
            _controller = new CodeListsController(_context);
            var category = new CodeList()
            {
                CategoryId = 1,
                CodeId     = 6,
                CodeName   = "NewPickle"
            };

            //Act
            var result = await _controller.PostCodeList(category);

            //Assert
            var okResult  = result.Should().BeOfType <CreatedAtActionResult>().Subject;
            var resClient = okResult.Value.Should().BeAssignableTo <CodeList>().Subject;

            resClient.CodeName.Should().Be("NewPickle");

            //delete JayNew
            int categoryId   = _context.CodeList.FirstOrDefault(p => p.CodeName == "NewPickle").CategoryId;
            int codeId       = _context.CodeList.FirstOrDefault(p => p.CodeName == "NewPickle").CodeId;
            var resultDelete = await _controller.DeleteCodeList(categoryId, codeId);
        }
Exemple #15
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"));
                }
            }
        }
Exemple #16
0
        public SearchResultDTO Search(string term, int?userId)
        {
            term = term.Trim();
            if (String.IsNullOrWhiteSpace(term) || term.Length < 3)
            {
                //return empty result
                return(new SearchResultDTO()
                {
                    Id = -1,
                    Results = new SearchResultEntryDTO[0],
                    SearchTerm = null
                });
            }

            using (var db = new SDCContext())
            {
                //simple stuff:
                //return books that contain the term in their title.

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



                var booksResult = (from b in db.Books
                                   where b.Shelf.IsVisible && b.Title.Contains(term)
                                   select new SearchResultBookDTO()
                {
                    Id = b.Id,
                    OwnerId = b.Shelf.Owner.UserId,
                    OwnerUserName = b.Shelf.Owner.UserName,
                    Title = b.Title,
                    Authors = b.Authors.Select(a => new AuthorDTO()
                    {
                        Id = a.Id,
                        Name = a.Name
                    }).ToList()
                }).ToArray();

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

                db.BookSearches.Add(search);

                return(new SearchResultDTO()
                {
                    Id = search.Id,
                    Results = booksResult,
                    SearchTerm = term
                });
            }
        }
Exemple #17
0
        public static void MapComplexProperties(SDCContext db, Book book, BookViewModel bookViewModel, UserProfile profile)
        {
            #region Authors entities
            var auth_to_remove = book.Authors.Where(a => !bookViewModel.Authors.Any(a2 => a2.Id == a.Id)).ToList();
            var auth_to_add    = bookViewModel.Authors.Where(a => !book.Authors.Any(a2 => a2.Id == a.Id)).ToList();
            auth_to_remove.ForEach(a => book.Authors.Remove(a));
            auth_to_add.ForEach(a => book.Authors.Add(a));

            foreach (Author a in book.Authors)
            {
                if (a.Id == 0)
                {
                    a.AddedDate = DateTime.Now;
                    a.AddedBy   = profile;
                    db.Entry <Author>(a).State = EntityState.Added;
                }
                else
                {
                    db.Attach(a);
                }
            }
            #endregion

            #region Genres entities
            var genres_to_remove = book.Genres.Where(g => !bookViewModel.Genres.Any(g2 => g2.Id == g.Id)).ToList();
            var genres_to_add    = bookViewModel.Genres.Where(g => !book.Genres.Any(g2 => g2.Id == g.Id)).ToList();
            genres_to_remove.ForEach(g => book.Genres.Remove(g));
            genres_to_add.ForEach(g => book.Genres.Add(g));

            foreach (var g in book.Genres)
            {
                db.Attach(g);
            }
            #endregion

            #region Publisher entity

            if (bookViewModel.Publisher != null)
            {
                db.Attach(bookViewModel.Publisher);
                book.Publisher = bookViewModel.Publisher;
            }
            else
            {
                book.Publisher = null;
            }



            #endregion

            #region Language
            var lang = bookViewModel.Language;
            db.AttachCodeEntity(ref lang);
            book.Language = lang;

            #endregion
        }
Exemple #18
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;
            }
        }
Exemple #19
0
        private void Scrape(SDCContext db, string url, ref int updated)
        {
            string token = "<ul>\n<li>";

            WebRequest req = WebRequest.Create(url);

            using (WebResponse response = req.GetResponse())
                using (var stream = response.GetResponseStream())
                    using (var sr = new StreamReader(stream))
                    {
                        var html = sr.ReadToEnd();

                        int idx = html.IndexOf(token);
                        while (idx > 0)
                        {
                            if (html.Length < idx + 1)
                            {
                                break;
                            }

                            html = html.Substring(idx + 1);
                            int idx_end = html.IndexOf("</ul>");

                            if (idx_end < 0)
                            {
                                break;
                            }

                            string   list_html = html.Substring(0, idx_end);
                            string[] lines     = list_html.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); // assuming \r\n. good enough for now.
                            lines = lines.Where(p => p.StartsWith("<li><a")).ToArray();

                            string title_attr = "title=\"";

                            foreach (var l in lines)
                            {
                                string line       = l;
                                int    auth_start = line.IndexOf(title_attr) + title_attr.Length;
                                line = line.Substring(auth_start);

                                string auth = line.Substring(0, line.IndexOf("\""));

                                //if none of the authors that were loaded into the local set has the same name as the one found,
                                //then add it.
                                if (!db.Authors.Local.Any(p => p.Name.ToLower().Equals(auth.ToLower())))
                                {
                                    db.Authors.Local.Add(new Author()
                                    {
                                        Name       = auth,
                                        IsVerified = true
                                    });
                                }
                            }
                        }
                    }
        }
Exemple #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;
            }
        }
Exemple #21
0
        public JsonResult GetAllAuthorsJson()
        {
            using (var db = new SDCContext())
            {
                bool filterOnlyWithBooks = false;
                bool.TryParse(this.Request.QueryString["onlyWithBooks"], out filterOnlyWithBooks);

                int skip = Int32.Parse(this.Request.QueryString["start"]);
                int take = Int32.Parse(this.Request.QueryString["length"]);
                int draw = Int32.Parse(this.Request.QueryString["draw"]);

                string nameFilter = Request.QueryString["search[value]"];

                var allAuthorsQuery = db.Authors
                                      .Where(p => (!filterOnlyWithBooks || p.Books.Count > 0) && (String.IsNullOrEmpty(nameFilter) || p.Name.Contains(nameFilter)))
                                      .AsQueryable();

                string orderByField   = TranslateColumnOrderBy(Request.QueryString["order[0][column]"]);
                string orderDirection = TranslateColumnOrderDirection(Request.QueryString["order[0][dir]"]);


                var orderedQuery = allAuthorsQuery.OrderByAnyDirection(orderByField, orderDirection);

                int filteredCount = orderedQuery.Count();

                var allAuthors = orderedQuery
                                 .Skip(skip).Take(take)
                                 .Select(a => new
                {
                    id         = a.Id.ToString(),
                    name       = a.Name,
                    isverified = a.IsVerified.ToString(),
                    bookcount  = a.Books.Count.ToString(),
                    addedby    = (a.AddedBy != null) ? a.AddedBy.UserName : "******",
                    addeddate  = a.AddedDate.Value
                }).ToArray();

                var o = new
                {
                    draw            = draw,
                    recordsTotal    = filteredCount,
                    recordsFiltered = filteredCount,
                    data            = allAuthors.Select(a => new string[] {
                        a.id,
                        a.name,
                        a.isverified,
                        a.bookcount,
                        a.addedby,
                        a.addeddate.ToString(Library.G.DATE)
                    }).ToArray()
                };

                return(Json(o, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #22
0
        public SearchResultDTO Search(string term, int? userId)
        {
            term = term.Trim();
            if(String.IsNullOrWhiteSpace(term) || term.Length < 3)
            {
                //return empty result
                return new SearchResultDTO()
                {
                    Id = -1,
                    Results = new SearchResultEntryDTO[0],
                    SearchTerm = null
                };
            }

            using (var db = new SDCContext())
            {
                //simple stuff:
                //return books that contain the term in their title.

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

                var booksResult = (from b in db.Books
                                   where b.Shelf.IsVisible && b.Title.Contains(term)
                                   select new SearchResultBookDTO()
                                   {
                                       Id = b.Id,
                                       OwnerId = b.Shelf.Owner.UserId,
                                       OwnerUserName = b.Shelf.Owner.UserName,
                                       Title = b.Title,
                                       Authors = b.Authors.Select(a => new AuthorDTO()
                                       {
                                           Id = a.Id,
                                           Name = a.Name
                                       }).ToList()
                                   }).ToArray();

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

                db.BookSearches.Add(search);

                return new SearchResultDTO()
                {
                    Id = search.Id,
                    Results = booksResult,
                    SearchTerm = term
                };
            }
        }
Exemple #23
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("/"));
        }
Exemple #24
0
        static S3()
        {
            _s3_bucket_name   = System.Configuration.ConfigurationManager.AppSettings["S3:BucketName"];
            _s3_bucket_region = ConfigurationManager.AppSettings["S3:BucketRegion"];

            using (var db = new SDCContext())
            {
                _s3_access_key        = db.Settings.Find("s3_access_key").Value;
                _s3_secret_access_key = db.Settings.Find("s3_secret_access_key").Value;
            }
        }
Exemple #25
0
        static S3()
        {
            _s3_bucket_name = System.Configuration.ConfigurationManager.AppSettings["S3:BucketName"];
            _s3_bucket_region = ConfigurationManager.AppSettings["S3:BucketRegion"];

            using (var db = new SDCContext())
            {
                _s3_access_key = db.Settings.Find("s3_access_key").Value;
                _s3_secret_access_key = db.Settings.Find("s3_secret_access_key").Value;
            }
        }
Exemple #26
0
 public void EFProjections_Test()
 {
     //I want to see if querying the db with projections
     //will load and keep the objects in the db context.
     //I assume not.
     using (var db = new SDCContext())
     {
         Assert.IsTrue(db.Books.Local.Count == 0);
         var bookProjections = db.Books.Select(b => new BookProjection() { Title = b.Title }).ToList();
         Assert.IsTrue(db.Books.Local.Count == 0);
     }
 }
Exemple #27
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();
     }
 }
Exemple #28
0
 public static void AttachToContext(UserProfile profile, SDCContext db)
 {
     if (db.Set <UserProfile>().Local.Any(local => profile == local))
     {
         db.Entry <UserProfile>(profile).State = EntityState.Unchanged;
     }
     else
     {
         db.Set <UserProfile>().Attach(profile);
         db.Entry <UserProfile>(profile).State = EntityState.Unchanged;
     }
 }
Exemple #29
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;
            }
        }
Exemple #30
0
        public async void Task2_GetById_Return_NotFoundResult()
        {
            //Arrange
            var Id = 32;

            _context    = new SDCContext(dbContextOptions);
            _controller = new CodeCategoriesController(_context);

            //Act
            var result = await _controller.GetCodeCategory(Id);

            //Assert
            Assert.IsType <NotFoundResult>(result);
        }
Exemple #31
0
        public async void Task1_GetById_Return_OkResult()
        {
            //Arrange
            var Id = 1;

            _context    = new SDCContext(dbContextOptions);
            _controller = new ClientsController(_context);

            //Act
            var result = await _controller.GetClient(Id);

            //Assert
            Assert.IsType <OkObjectResult>(result);
        }
        public async void Task2_GetById_Return_NotFoundResult()
        {
            //Arrange
            var Id = 82;

            _context    = new SDCContext(dbContextOptions);
            _controller = new SupplierLoginsController(_context);

            //Act
            var result = await _controller.GetSupplierLogin(Id);

            //Assert
            Assert.IsType <NotFoundResult>(result);
        }
        public async void Task1_GetById_Return_OkResult()
        {
            //Arrange
            var categoryId = 1;
            var codeId     = 1;

            _context    = new SDCContext(dbContextOptions);
            _controller = new CodeListsController(_context);

            //Act
            var result = await _controller.GetCodeList(categoryId, codeId);

            //Assert
            Assert.IsType <OkObjectResult>(result);
        }
Exemple #34
0
        public async void Task2_GetById_Return_NotFoundResult()
        {
            //Arrange
            var productId  = "28B1PO";
            var supplierId = 2;

            _context    = new SDCContext(dbContextOptions);
            _controller = new ProductsController(_context);

            //Act
            var result = await _controller.GetProduct(productId, supplierId);

            //Assert
            Assert.IsType <NotFoundResult>(result);
        }
        public async void Task2_GetById_Return_NotFoundResult()
        {
            //Arrange
            var projectId = 2;
            var orderId   = 2;

            _context    = new SDCContext(dbContextOptions);
            _controller = new PurchaseOrdersController(_context);

            //Act
            var result = await _controller.GetPurchaseOrder(projectId, orderId);

            //Assert
            Assert.IsType <NotFoundResult>(result);
        }
Exemple #36
0
 public void EFProjections_Test()
 {
     //I want to see if querying the db with projections
     //will load and keep the objects in the db context.
     //I assume not.
     using (var db = new SDCContext())
     {
         Assert.IsTrue(db.Books.Local.Count == 0);
         var bookProjections = db.Books.Select(b => new BookProjection()
         {
             Title = b.Title
         }).ToList();
         Assert.IsTrue(db.Books.Local.Count == 0);
     }
 }
Exemple #37
0
        public JsonResult GetGenresJson(string term = "")
        {
            using (var db = new SDCContext())
            {
                var genres =
                    (from g in db.Genres
                     orderby g.Name
                     where (String.IsNullOrEmpty(term) || g.Name.Contains(term))
                     select new
                     {
                         label = g.Name,
                         value = g.Id
                     }).ToArray();

                return Json(genres, JsonRequestBehavior.AllowGet);
            }
        }
Exemple #38
0
        public void AddBook_Test()
        {
            BookController c = CreateController<BookController>();
            BookViewModel vm; int bookCount;

            using (var db = new SDCContext())
            {
                bookCount = db.Books.Count();

                var profile = db.UserProfiles.Find(1);
                var shelf = db.Shelves.FirstOrDefault(p => p.Owner.UserId == profile.UserId);
                var twoGenres = db.Genres.Take(2)
                    .ToList();

                var twoAuthors = db.Authors.OrderBy(a => Guid.NewGuid().ToString())
                    .Take(2)
                    .ToList();

                var publisher = db.Publishers.Take(1)
                    .First();

                var language = db.Languages
                    .Where(l=>l.IsVisible)
                    .OrderBy(l => Guid.NewGuid().ToString())
                    .First();

                vm = new BookViewModel()
                {
                    Title = Guid.NewGuid().ToString(),
                    Year = 2015,
                    Genres = twoGenres,
                    Authors = twoAuthors,
                    Description = "Lorem ipsum",
                    Publisher = publisher,
                    Language = language,
                    ShelfId = shelf.Id,
                    ShelfName = shelf.Name,
                    ISBN = Guid.NewGuid().ToString(),
                    AddedDate = DateTime.Now
                };
            }

            c.AddBook(vm);
            Assert.AreEqual(bookCount + 1, new SDCContext().Books.Count());
        }
Exemple #39
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();
        }
Exemple #40
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");
        }
Exemple #41
0
        public JsonResult GetAuthorsJson(string term = "")
        {
            using(var db = new SDCContext())
            {
                var authors =
                    (from a in db.Authors
                     orderby a.Name
                     where
                        a.IsVerified &&
                        (String.IsNullOrEmpty(term) || a.Name.Contains(term))
                     select new
                     {
                         label = a.Name,
                         value = a.Id
                     }).ToArray();

                return Json(authors, JsonRequestBehavior.AllowGet);
            }
        }
Exemple #42
0
        public JsonResult GetPublishersJson(string term = "")
        {
            using(var db = new SDCContext())
            {
                var publishers =
                    (from p in db.Publishers
                     orderby p.Name
                     where
                        p.IsVerified &&
                        (String.IsNullOrEmpty(term) || p.Name.Contains(term))
                     select new
                     {
                         label = p.Name,
                         value = p.Id
                     }).ToArray();

                return Json(publishers, JsonRequestBehavior.AllowGet);
            }
        }
Exemple #43
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();
        }
Exemple #44
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 });
        }
Exemple #45
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();
        }
Exemple #46
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;
            }
        }
Exemple #47
0
        public JsonResult GetAllAuthorsJson()
        {
            using (var db = new SDCContext())
            {
                bool filterOnlyWithBooks = false;
                bool.TryParse(this.Request.QueryString["onlyWithBooks"], out filterOnlyWithBooks);

                int skip = Int32.Parse(this.Request.QueryString["start"]);
                int take = Int32.Parse(this.Request.QueryString["length"]);
                int draw = Int32.Parse(this.Request.QueryString["draw"]);

                string nameFilter = Request.QueryString["search[value]"];

                var allAuthorsQuery = db.Authors
                    .Where(p => (!filterOnlyWithBooks || p.Books.Count > 0) && (String.IsNullOrEmpty(nameFilter) || p.Name.Contains(nameFilter)))
                    .AsQueryable();

                string orderByField = TranslateColumnOrderBy(Request.QueryString["order[0][column]"]);
                string orderDirection = TranslateColumnOrderDirection(Request.QueryString["order[0][dir]"]);

                var orderedQuery = allAuthorsQuery.OrderByAnyDirection(orderByField, orderDirection);

                int filteredCount = orderedQuery.Count();

                var allAuthors = orderedQuery
                    .Skip(skip).Take(take)
                    .Select(a => new
                    {
                        id = a.Id.ToString(),
                        name = a.Name,
                        isverified = a.IsVerified.ToString(),
                        bookcount = a.Books.Count.ToString(),
                        addedby = (a.AddedBy != null) ? a.AddedBy.UserName : "******",
                        addeddate = a.AddedDate.Value
                    }).ToArray();

                var o = new
                {
                    draw = draw,
                    recordsTotal = filteredCount,
                    recordsFiltered = filteredCount,
                    data = allAuthors.Select(a => new string[] {
                        a.id,
                        a.name,
                        a.isverified,
                        a.bookcount,
                        a.addedby,
                        a.addeddate.ToString(Library.G.DATE)
                    }).ToArray()
                };

                return Json(o, JsonRequestBehavior.AllowGet);
            }
        }
Exemple #48
0
 public static Country[] GetAll(SDCContext db, bool onlyVisible=true)
 {
     return db.Countries
         .Where(p=>p.IsVisible || !onlyVisible)
         .OrderBy(p => p.Name).ToArray();
 }
Exemple #49
0
 public static City[] GetAll(SDCContext db, string countryCode, bool onlyVisible = true)
 {
     return db.Cities
         .Where(p => p.Country.Code == countryCode && (p.IsVisible || !onlyVisible))
         .OrderBy(p => p.Name).ToArray();
 }
Exemple #50
0
 public static Language[] GetAll(SDCContext db, bool onlyVisible=true)
 {
     return db.Languages
         .Where(l=>l.IsVisible || !onlyVisible)
         .OrderBy(p => p.Top).ThenBy(p => p.Name).ToArray();
 }
Exemple #51
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();
            }
        }
Exemple #52
0
        public ActionResult ViewAuthor(int id, int page=1, int pagesize=0)
        {
            if (id == 0)
                return RedirectToAction("Index", "Home");

            var profile = (UserProfile)this.Session["UserInfo"];
            if (profile == null)
                return RedirectToAction("Index", "Home");

            if (pagesize < 1 || pagesize > 100)
                pagesize = profile.PageSize;

            using (var db = new SDCContext())
            {
                profile.UpdatePageSize(db, pagesize);

                var author = db.Authors
                    .Include(a => a.AddedBy)
                    .Include(a => a.LastModifiedBy)
                    .Include(a => a.Books)
                    .FirstOrDefault(a => a.Id == id);

                if (author == null)
                    return RedirectToAction("Index", "Home");

                int totalPages = ((int)Math.Ceiling((double)author.Books.Count / pagesize));
                if (page > totalPages)
                    page = totalPages;

                var model = AutoMapper.Mapper.Map<AuthorViewModel>(author);

                //actual pagination takes place here
                var show_books = author.Books
                        .OrderBy(b => b.AddedDate)
                        .Skip((page - 1) * pagesize)
                        .Take(pagesize)
                        .Select(b => AutoMapper.Mapper.Map<BookViewModel>(b));

                model.Pagination = new PaginationViewModel()
                {
                    Id = author.Id,
                    Action = "ViewAuthor",
                    Controller = "Authors",
                    Page = page,
                    PageSize = pagesize,
                    TotalPages = totalPages,
                    EntityCount = show_books.Count(),
                    EntityName = "Books"
                };

                ViewBag.Breadcrumbs = Breadcrumb.Generate(
                    "Authors", Url.Action("Index", "Authors"),
                    author.Name, "");

                return View(model);
            }
        }
Exemple #53
0
 public static Genre[] GetAll(SDCContext db)
 {
     return (from g in db.Genres
             orderby g.Name
             select g).ToArray();
 }
Exemple #54
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("/");
        }
Exemple #55
0
        public ActionResult ViewBook(int id = 0)
        {
            if (id == 0) //this should not happen
                return RedirectToAction("Index", "Home");

            var profile = (UserProfile)Session["UserInfo"];

            using (var db = new SDCContext())
            {
                ViewBag.Languages = db.Languages.Where(p=>p.IsVisible).OrderBy(p=>p.Code).ToList();
                ViewBag.Genres = db.Genres.OrderBy(p=>p.Name).ToList();

                var book = db.Books
                    .Include(b => b.Shelf)
                    .Include(b => b.Shelf.Owner)
                    .Include(b => b.Authors)
                    .Include(b => b.Genres)
                    .Include(b => b.Publisher)
                    .Include(b => b.Pictures)
                    .First(b => b.Id == id);

                bool showEditor = false;
                Boolean.TryParse(Request.QueryString["showEditor"], out showEditor);
                ViewBag.ShowEditor = showEditor;

                if(profile != null)
                {
                    ViewBag.Breadcrumbs = Breadcrumb.Generate(
                        "My shelves", Url.Action("Index", "Shelves"),
                        book.Shelf.Name, Url.Action("Details", "Shelves", new { id = book.Shelf.Id }),
                        book.Title, "");
                }
                else
                {
                    ViewBag.Breadcrumbs = Breadcrumb.Generate(
                        book.Shelf.Name, Url.Action("Details", "Shelves", new { id = book.Shelf.Id }),
                        book.Title, "");
                }

                return View(AutoMapper.Mapper.Map<BookViewModel>(book));
            }
        }
Exemple #56
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);
            }
        }
Exemple #57
0
        private void Scrape(SDCContext db, string url, ref int updated)
        {
            string token = "<ul>\n<li>";

            WebRequest req = WebRequest.Create(url);
            using (WebResponse response = req.GetResponse())
            using (var stream = response.GetResponseStream())
            using (var sr = new StreamReader(stream))
            {
                var html = sr.ReadToEnd();

                int idx = html.IndexOf(token);
                while (idx > 0)
                {
                    if (html.Length < idx + 1)
                        break;

                    html = html.Substring(idx + 1);
                    int idx_end = html.IndexOf("</ul>");

                    if (idx_end < 0)
                        break;

                    string list_html = html.Substring(0, idx_end);
                    string[] lines = list_html.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries); // assuming \r\n. good enough for now.
                    lines = lines.Where(p => p.StartsWith("<li><a")).ToArray();

                    string title_attr = "title=\"";

                    foreach (var l in lines)
                    {
                        string line = l;
                        int auth_start = line.IndexOf(title_attr) + title_attr.Length;
                        line = line.Substring(auth_start);

                        string auth = line.Substring(0, line.IndexOf("\""));

                        //if none of the authors that were loaded into the local set has the same name as the one found,
                        //then add it.
                        if (!db.Authors.Local.Any(p=>p.Name.ToLower().Equals(auth.ToLower())))
                        {
                            db.Authors.Local.Add(new Author()
                            {
                                Name = auth,
                                IsVerified = true
                            });
                        }

                    }

                }
            }
        }
Exemple #58
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;
            }
        }
Exemple #59
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;
            }
        }
Exemple #60
0
        public JsonResult GetBookJson(int id)
        {
            try {
                using (var db = new SDCContext())
                {
                    //feel like doing some projections? :D
                    //this will be more useful in the future
                    //when a book will have other entities attached to it
                    // such as transactions.
                    BookViewModel bookViewModel = db.Books.AsQueryable().Project()
                        .To<BookViewModel>()
                        .First(b => b.Id == id);

                    return Json(bookViewModel, JsonRequestBehavior.AllowGet);
                }
            }
            catch(Exception ex)
            {
                //todo: log
                throw ex;
            }
        }