Example #1
0
        public ActionResult NewsletterSubscribe(NewsletterRegistration model)
        {
            using (var db = new SiteDbContext())
            {
                var ifEmailExist = db.NewsletterRegistration
                                   .Any(r => r.Email.Equals(model.Email));

                if (!ifEmailExist)
                {
                    NewsletterRegistration newRegistration = new NewsletterRegistration
                    {
                        Email     = model.Email,
                        SecretKey = Guid.NewGuid().ToString()
                    };

                    db.NewsletterRegistration.Add(newRegistration);
                    db.SaveChanges();

                    return(Json("Inscription effectuée !", JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json("L'adresse email est déjà inscrite !", JsonRequestBehavior.AllowGet));
                }
            }
        }
Example #2
0
        public ActionResult Articles(string searchTerm = null)
        {
            using (var context = new SiteDbContext())
            {
                if (searchTerm != null)
                {
                    ViewBag.searchTerm = searchTerm;
                }

                List <ArticlesViewModel> model = new List <ArticlesViewModel>();
                model = context.Articles
                        .Where(r => searchTerm == null || r.Title.StartsWith(searchTerm))
                        .OrderByDescending(r => r.Id)
                        .Select(r => new ArticlesViewModel
                {
                    Id           = r.Id,
                    Title        = r.Title,
                    Date         = r.Date,
                    Views        = r.Views,
                    PublishState = r.PublishState
                }).ToList();

                return(View(model));
            }
        }
Example #3
0
        public ActionResult GetStatistics(string currencyname)
        {
            var db = new SiteDbContext();

            var OpenOrders = db.LimitOrders.Where(cur => cur.Currency == currencyname).ToList();

            var SellOrders = OpenOrders.Where(or => or.OrderType == "Sell").ToList();
            var BuyOrders  = OpenOrders.Where(or => or.OrderType == "Buy").ToList();



            if (OpenOrders.Count <= 0)
            {
                return(Json(null, JsonRequestBehavior.AllowGet));
            }


            var Data = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                SellOrders = SellOrders.Count,
                BuyOrders  = BuyOrders.Count
            }
                                                                   , new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            });

            return(Json(Data, JsonRequestBehavior.AllowGet));
        }
Example #4
0
        public ActionResult Index()
        {
            if (!Request.IsAuthenticated)
            {
                HomeAuthenticated model = new HomeAuthenticated();

                var btc = CoinValues.GetStatistic().Where(c => c.Name.Contains("Bitcoin")).First();
                model.Bitcoin = btc;

                return(View(model));
            }
            else
            {
                SiteDbContext db   = new SiteDbContext();
                var           user = db.Users.Find(User.Identity.GetUserId());
                user.Transactions = user.Transactions;
                user.Wallet       = user.Wallet;


                HomeAuthenticated model = new HomeAuthenticated();
                model.UserData = db.Users.Find(User.Identity.GetUserId());
                model.Bitcoin  = CoinValues.GetStatistic().Where(c => c.Name.Contains("Bitcoin")).First();

                var TotalBalanceUSD = ProfileController.CalculateTotalBalance(user);

                model.TotalBalance = TotalBalanceUSD;

                return(View(model));
            }
        }
Example #5
0
        // GET: Article
        public ActionResult Detail(string id)
        {
            using (var context = new SiteDbContext())
            {
                id = HttpUtility.UrlDecode(id);
                Articles model = context.Articles
                                 .Where(r => r.Title == id).FirstOrDefault();

                if (model == null)
                {
                    return(RedirectToAction("Index", "Article"));
                }

                if (model.PublishState == 0 && !(User.IsInRole("administrator") || User.IsInRole("writer")))
                {
                    return(RedirectToAction("Index", "Article"));
                }

                var applicationDbContext = HttpContext.GetOwinContext().Get <ApplicationDbContext>();
                var author = applicationDbContext.Users
                             .Where(r => r.Id == model.AuthorId)
                             .Select(r => r.UserName).ToArray()[0];

                ViewBag.Author = author;
                ViewBag.Id     = model.Id;
                ViewBag.Tags   = model.Tags;

                return(View(model));
            }
        }
Example #6
0
        // GET: Admin/DeletePost
        public ActionResult DeletePost(int id)
        {
            using (var context = new SiteDbContext())
            {
                Articles post = context.Articles.Find(id);

                string path = System.IO.Path.Combine(Server.MapPath("~/Images/Uploads/Articles/Header/"), post.Id.ToString());
                if (System.IO.File.Exists(path + "x1280.jpeg"))
                {
                    System.IO.File.Delete(path + "x1280.jpeg");
                }

                if (System.IO.File.Exists(path + "x800.jpeg"))
                {
                    System.IO.File.Delete(path + "x800.jpeg");
                }

                if (System.IO.File.Exists(path + "x320.jpeg"))
                {
                    System.IO.File.Delete(path + "x320.jpeg");
                }

                context.Entry(post).State = System.Data.Entity.EntityState.Deleted;
                context.SaveChanges();
            }

            UpdateSitemapXML();
            return(RedirectToAction("Articles", "Admin"));
        }
Example #7
0
        // GET: Tag
        public ActionResult Tag(string id)
        {
            using (var context = new SiteDbContext())
            {
                id          = HttpUtility.UrlDecode(id);
                ViewBag.Tag = id;

                List <ArticlesViewModel> model = context.Articles
                                                 .OrderByDescending(r => r.Id)
                                                 .Where(r => r.Tags.Contains(id) && r.PublishState == 2)
                                                 .Select(r => new ArticlesViewModel
                {
                    Id           = r.Id,
                    Title        = r.Title,
                    Description  = r.Description,
                    Date         = r.Date,
                    Views        = r.Views,
                    PublishState = r.PublishState
                }).Take(10).ToList();

                if (model == null)
                {
                    return(RedirectToAction("Index", "Article"));
                }

                return(View(model));
            }
        }
Example #8
0
        public ActionResult Post(int?id)
        {
            List <SelectListItem> items = new List <SelectListItem>();

            items.Add(new SelectListItem {
                Text = "Preview (visible seulement pour rédacteur)", Value = "0", Selected = true
            });
            items.Add(new SelectListItem {
                Text = "Non répertoriée", Value = "1"
            });
            items.Add(new SelectListItem {
                Text = "En ligne", Value = "2"
            });
            ViewBag.State = items;

            if (id != null)
            {
                using (var context = new SiteDbContext())
                {
                    Articles model = context.Articles.Find(id);
                    ViewBag.Edition = true;

                    return(View(model));
                }
            }
            else
            {
                return(View());
            }
        }
Example #9
0
        public ActionResult UploadPic()
        {
            HttpPostedFileBase file = Request.Files["myFile"];

            int byteCount = file.ContentLength;

            if (file.ContentLength == 0)
            {
                return(Redirect(Request.UrlReferrer.PathAndQuery));
            }

            if (!CryptoMarketSimulator.HttpPostedFileBaseExtensions.IsImage(file))
            {
                return(Redirect(Request.UrlReferrer.PathAndQuery));
            }

            //check file was submitted
            if (file != null && file.ContentLength > 0)
            {
                using (var db = new SiteDbContext())
                {
                    var    currentuser = db.Users.Find(User.Identity.GetUserId());
                    string fname       = Path.GetFileName(file.FileName);
                    string extension   = Path.GetExtension(file.FileName);

                    file.SaveAs(Server.MapPath(Path.Combine("~/Resources/UsersImages/", currentuser.Id + extension)));
                    currentuser.ProfilePicture = "/Resources/UsersImages/" + currentuser.Id + extension;
                    db.SaveChanges();

                    return(Redirect(Request.UrlReferrer.PathAndQuery));
                }
            }
            return(Redirect(Request.UrlReferrer.PathAndQuery));
        }
        public ActionResult RefreshCurrency(string currencyname)
        {
            var  coins = CoinValues.GetValues().ToList();
            Coin coin  = coins
                         .Where(v => v.Name.Contains(currencyname))
                         .First();

            Coin Bitcoin = coins
                           .Where(v => v.Name == "Bitcoin".Replace(" ", string.Empty))
                           .First();

            decimal CurrencyUsdPrice = coin.Price;
            decimal BitcoinPrice     = Bitcoin.Price;

            var db   = new SiteDbContext();
            var user = db.Users.Find(User.Identity.GetUserId());

            var UserUsdBalance      = user.Balance * BitcoinPrice;
            var UserCurrencyBalance = user.Wallet[currencyname.Replace(" ", string.Empty)];

            var Data = Newtonsoft.Json.JsonConvert.SerializeObject(new
            {
                CurrencyUsdPrice    = CurrencyUsdPrice,
                BitcoinPrice        = BitcoinPrice,
                UserBtcBalance      = user.Balance,
                UserUsdBalance      = UserUsdBalance,
                UserCurrencyBalance = UserCurrencyBalance,
                UserOrders          = user.LimitOrders.ToList()
            }, new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            });

            return(Json(Data, JsonRequestBehavior.AllowGet));
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                if (model.AcceptTerms)
                {
                    var user = new ApplicationUser {
                        UserName = model.UserName, Email = model.Email, Register = DateTime.Now, SlotForCompanion = 0
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
                        // Send an email with this link
                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                        await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                                                          $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");

                        // await _signInManager.SignInAsync(user, isPersistent: false);
                        _logger.LogInformation(3, "User created a new account with password.");

                        // Setup Gold
                        Gold gold = new Gold()
                        {
                            UserId = user.Id,
                            Number = 0
                        };

                        // Setup Artifacts
                        Artifacts artifact = new Artifacts()
                        {
                            UserId = user.Id,
                            Number = 10
                        };

                        using (var context = new SiteDbContext())
                        {
                            context.Add(artifact);
                            context.Add(gold);
                            await context.SaveChangesAsync();
                        }

                        // Redirect
                        return(RedirectToLocal(returnUrl));
                    }
                    AddErrors(result);
                }
                else
                {
                    ModelState.AddModelError("AcceptTerms", "You must accept the Terms of Use");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #12
0
        public JsonResult UserTop5()
        {
            List <TopCurrency> top5 = new List <TopCurrency>();

            using (var db = new SiteDbContext())
            {
                var cuerrentuser = db.Users.Find(User.Identity.GetUserId());
                var res          = cuerrentuser.Transactions.GroupBy(t => t.Currency).OrderByDescending(g => g.Count()).Take(5).ToList();
                // IEnumerable<TopCurrency> smths = res.SelectMany(group => group);

                foreach (var group in res)
                {
                    var topcurrency = new TopCurrency();

                    foreach (var transaction in group)
                    {
                        topcurrency.Currency     = transaction.Currency;
                        topcurrency.Transactions = group.Count();
                    }
                    topcurrency.DollarsSpend = group.Sum(sum => sum.TotalUSD);
                    top5.Add(topcurrency);
                }
            }

            return(Json(top5, JsonRequestBehavior.AllowGet));
        }
Example #13
0
 private IEnumerable <HtmlBlock> QueryBySite(Site site)
 {
     return(SiteDbContext.CreateDbContext().HtmlBlocks
            .Where(it => it.SiteName == site.FullName)
            .ToArray()
            .Select(it => it.ToHtmlBlock()));
 }
Example #14
0
        public ActionResult Statistics(string currency)
        {
            var Currencies = CoinValues.GetStatistic().Where(cur => cur.Name == currency);

            var BitcoinPrice = CoinValues.GetValues().Where(c => c.Name == "Bitcoin").First().Price;

            if (currency == null || Currencies.Count() == 0 || Currencies.Count() > 1)
            {
                return(View("Index"));
            }

            Coin Currency                   = Currencies.First();
            var  db                         = new SiteDbContext();
            List <LimitOrder>  Orders       = db.LimitOrders.Where(c => c.Currency == Currency.Name).ToList();
            List <Transaction> Transactions = db.Transactions.Where(c => c.Currency == Currency.Name).ToList();


            Statistics statistics = new Statistics();

            statistics.Volume            = Transactions.Sum(tr => tr.TotalUSD);
            statistics.TotalTransactions = Transactions.Count;
            statistics.Currency          = Currency;
            statistics.OpenOrders        = Orders.Count;
            statistics.Orders            = Orders;
            statistics.Transactions      = Transactions.OrderByDescending(tr => tr.Date).ToList();
            statistics.BitcoinPrice      = BitcoinPrice;


            return(View(statistics));
        }
Example #15
0
        public ActionResult NewsletterUnsubscribe(string email, string guid)
        {
            email = HttpUtility.UrlDecode(email);
            guid  = HttpUtility.UrlDecode(guid);

            using (var db = new SiteDbContext())
            {
                var ifEmailExist = db.NewsletterRegistration
                                   .Any(r => r.Email.Equals(email));

                if (ifEmailExist)
                {
                    var userData = db.NewsletterRegistration.Where(r => r.Email.Equals(email)).FirstOrDefault();
                    if (userData.Email == email && userData.SecretKey == guid)
                    {
                        NewsletterRegistration newsletterAccount = db.NewsletterRegistration.Find(userData.Id);
                        db.Entry(newsletterAccount).State = System.Data.Entity.EntityState.Deleted;
                        db.SaveChanges();

                        ViewBag.Message = "Vous êtes maintenant désinscrit de la newsletter de Gamers Addict.";
                    }
                    else
                    {
                        ViewBag.Message = "Erreur dans clef secrète.";
                    }
                }
                else
                {
                    ViewBag.Message = "Vous n'êtes pas inscrit à la newsletter, désinscription impossible.";
                }
            }
            return(View());
        }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            // Return if there are already suppliers
            if (context.Suppliers.Any())
                return;

            // Hydrate supplier
            var hydrator = new Hydrator<Supplier>()
                .WithAmericanAddress(e => e.Address)
                .WithAmericanCity(e => e.City)
                .WithAmericanState(e => e.Region)
                .WithCustomGenerator(e => e.Country, new CountryGenerator())
                .WithCustomGenerator(e => e.ContactName, new ContactNameGenerator())
                .WithEmailAddress(e => e.ContactEmail)
                .WithAmericanPostalCode(e => e.PostalCode, 4)
                .WithAmericanPhone(e => e.Phone)
                .WithCustomGenerator(e => e.ContactTitle, new TitleGenerator())
                .Ignoring(e => e.CompanyName)
                .Ignoring(e => e.SupplierId)
                .Ignoring(e => e.Products)
                .GetList(sampleSize)
                .ToList();

            // Make sure every company name is unique
            var usedCompanyNames = new List<string>();

            foreach (var supplier in hydrator)
            {
                string name;
                do
                {
                    name = new CompanyNameGenerator().Generate();
                } while (usedCompanyNames.Contains(name));
                usedCompanyNames.Add(name);
                supplier.CompanyName = name;

                // See if this works
                supplier.Products = new List<Product>();
                // ReSharper disable once LoopCanBePartlyConvertedToQuery
                foreach (var i in Enumerable.Range(0, 4))
                {
                    var product = new Product
                    {
                        ProductName = new CatchPhraseGenerator().Generate(),
                        QuantityPerUnit = new IntegerGenerator() {MaximumValue = 10, MinimumValue = 1}.Generate(),
                        UnitPrice = new IntegerGenerator() { MaximumValue = 200, MinimumValue = 1 }.Generate(),
                    };

                    // Add Product to supplier
                    supplier.Products.Add(product);
                }

                // Add supplier to context
                context.Suppliers.Add(supplier);
            }

            // Save the changes
            context.SaveChanges();
        }
Example #17
0
 public bool IsEmailExist(string emailID)
 {
     using (SiteDbContext dc = new SiteDbContext())
     {
         var v = dc.Users.Where(a => a.EmailID == emailID).FirstOrDefault();
         return(v != null);
     }
 }
Example #18
0
        public Models.Page GetDraft(Models.Page page)
        {
            var entity = SiteDbContext.CreateDbContext().PageDrafts
                         .Where(it => it.SiteName == page.Site.FullName && it.FullName == page.FullName)
                         .FirstOrDefault();

            return(PageEntityHelper.ToPage(entity));
        }
Example #19
0
        public Models.HtmlBlock Get(Models.HtmlBlock dummy)
        {
            var entity = SiteDbContext.CreateDbContext().HtmlBlocks
                         .Where(it => it.SiteName == dummy.Site.FullName && it.Name == dummy.Name)
                         .FirstOrDefault();

            return(entity == null ? null : entity.ToHtmlBlock());
        }
Example #20
0
        public Models.User Get(Models.User dummy)
        {
            var entity = SiteDbContext.CreateDbContext().SiteUsers
                         .Where(it => it.SiteName == dummy.Site.FullName && it.UserName == dummy.UserName)
                         .FirstOrDefault();

            return(entity == null ? null : SiteUserHelper.ToUser(entity));
        }
Example #21
0
 public SiteMailClientsService(
     ITenant tenant, IHttpClientFactory httpClientFactory,
     SiteDbContext dbContext)
 {
     _tenant            = tenant;
     _dbContext         = dbContext;
     _httpClientFactory = httpClientFactory;
 }
Example #22
0
 public IEnumerable <Models.User> All(Models.Site site)
 {
     return(SiteDbContext.CreateDbContext().SiteUsers
            .Where(it => it.SiteName == site.FullName)
            .ToArray()
            .Select(it => SiteUserHelper.ToUser(it))
            .AsQueryable());
 }
        public ActionResult Sell(string amount, string name)
        {
            decimal d;

            if (!decimal.TryParse(amount, out d))
            {
                return(View("Index"));
            }

            var     userId        = User.Identity.GetUserId();
            decimal sold          = decimal.Parse(amount, CultureInfo.InvariantCulture);
            decimal currencyPrice = CoinValues.GetValues().Where(v => v.Name == name).First().Price;
            decimal bitcoin       = CoinValues.GetBtcValue().Price;

            decimal boughtPrice = sold * currencyPrice;
            decimal btcPrice    = boughtPrice / bitcoin;


            using (var db = new SiteDbContext())
            {
                var user    = db.Users.Find(userId);
                var userBTC = user.Balance;
                if (sold > user.Wallet[name.Replace(" ", string.Empty)] || sold < 0)
                {
                    return(View("Index"));
                }

                user.Wallet[name.Replace(" ", string.Empty)] -= sold;
                user.Balance += btcPrice;

                //add Transaction
                var transaction = new Transaction()
                {
                    Amount        = sold,
                    Currency      = name,
                    Date          = DateTime.Now,
                    User          = user,
                    Type          = "Sold",
                    CurrencyPrice = currencyPrice,
                    TotalUSD      = sold * currencyPrice
                };
                db.Transactions.Add(transaction);

                db.SaveChanges();

                var Data = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    CurrencyCurrentPrice = currencyPrice,
                    CurrencyBalance      = user.Wallet[name.Replace(" ", string.Empty)],
                    UserBtcBalance       = user.Balance,
                    UserUsdBalance       = user.Balance * CoinValues.GetBtcValue().Price
                });
                ViewBag.Result = "Successfully";

                return(Json(Data, JsonRequestBehavior.AllowGet));
            }
        }
Example #24
0
        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
        {
            bool   Status  = false;
            string message = "";

            // Model Validation
            if (ModelState.IsValid)
            {
                // Generate Random Avatar
                var    builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);
                Random rnd     = new Random();
                int    rndNum  = rnd.Next(0, 14);
                user.Avatar = builder.Host + ":" + builder.Port + "/Images/profileIcons/" + rndNum + ".svg";


                #region //Email is already Exist
                var isExist = IsEmailExist(user.EmailID);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return(View(user));
                }
                #endregion

                #region Generate Activation Code
                user.ActivationCode = Guid.NewGuid();
                #endregion

                #region  Password Hashing
                user.Password        = Crypto.Hash(user.Password);
                user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); //
                #endregion
                user.IsEmailVerified = false;

                #region Save to Database
                using (SiteDbContext dc = new SiteDbContext())
                {
                    dc.Users.Add(user);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
                    message = "Registration successfully done. Account activation link" +
                              " has been sent to your email: " + user.EmailID;
                    Status = true;
                }
                #endregion
            }
            else
            {
                message = "Invalid Request";
            }

            ViewBag.Message = message;
            ViewBag.Status  = Status;
            return(View(user));
        }
Example #25
0
 public static Dictionary<string, string> Config()
 {
     Dictionary<string, string> SettingsList = HttpContext.Current.Cache.Data("SettingsList", () =>
     {
         SiteDbContext db = new SiteDbContext();
         return (from s in db.Settings select s).ToDictionary(s => s.Name, s => s.Value);
     });
     return SettingsList;
 }
        public ActionResult ChangeEmail(ChangeEmailViewModel model)
        {
            if (ModelState.IsValid)
            {
                //Update Account
                var context = HttpContext.GetOwinContext().Get <ApplicationDbContext>();
                ApplicationUserManager _userManager = new ApplicationUserManager(new Microsoft.AspNet.Identity.EntityFramework.UserStore <ApplicationUser>(context));
                var user = _userManager.FindByName(User.Identity.Name);

                var oldEmail = user.Email;
                user.Email = model.Email;
                _userManager.Update(user);
                HttpContext.GetOwinContext().Get <ApplicationDbContext>().SaveChanges();

                //Update Newsletter
                using (var db = new SiteDbContext())
                {
                    var ifEmailExist = db.NewsletterRegistration
                                       .Any(r => r.Email.Equals(oldEmail));

                    if (ifEmailExist)
                    {
                        NewsletterRegistration newsletterRegistration = db.NewsletterRegistration
                                                                        .Where(r => r.Email == oldEmail)
                                                                        .Select(r => r).FirstOrDefault();

                        newsletterRegistration.Email = model.Email;

                        db.Entry(newsletterRegistration).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                //Update YouTube Alert
                using (var db = new SiteDbContext())
                {
                    var ifEmailExist = db.YouTubeAlertRegistration
                                       .Any(r => r.Email.Equals(oldEmail));

                    if (ifEmailExist)
                    {
                        YouTubeAlertRegistration youTubeAlertRegistration = db.YouTubeAlertRegistration
                                                                            .Where(r => r.Email == oldEmail)
                                                                            .Select(r => r).FirstOrDefault();

                        youTubeAlertRegistration.Email = model.Email;

                        db.Entry(youTubeAlertRegistration).State = System.Data.Entity.EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                return(RedirectToAction("Index", new { Message = "Adresse Email modifier avec succès !" }));
            }

            return(View(model));
        }
Example #27
0
 public IQueryable <ElementCategory> Categories()
 {
     return(SiteDbContext.CreateDbContext().LabelCategories
            .Where(it => it.SiteName == SiteName)
            .Select(it => new ElementCategory()
     {
         Category = it.CategoryName
     }).ToArray().AsQueryable());
 }
Example #28
0
        public void Localize(Models.Page o, Models.Site targetSite)
        {
            var dbContext = SiteDbContext.CreateDbContext();

            LocalizeWithChildPages(dbContext, o, targetSite);
            dbContext.SaveChanges();

            ClearCache();
        }
Example #29
0
        public void Move(Models.Site site, string pageFullName, string newParent)
        {
            var dbContext = SiteDbContext.CreateDbContext();

            MovePageRecursively(site, pageFullName, newParent, dbContext);

            dbContext.SaveChanges();

            ClearCache();
        }
Example #30
0
        /// <summary>
        /// 为什么要缓存Page表呢?
        /// 1. 因为在实际使用过程中发现,如果页面数量相对比较多的时候,第一次查找页面的过程中会调用很多次ChildPages,导致请求的效率很低,时间花费很高。
        /// 2. 目前的设计已经是假设页面数量不多的前提了。所以缓该表的数据量是可以接受的。
        /// </summary>
        private static List <PageEntity> GetCachedPageList()
        {
            var cacheObject = CacheManagerFactory.DefaultCacheManager.GlobalObjectCache();

            return(cacheObject.GetCache <List <PageEntity> >(cacheKey, () =>
            {
                return SiteDbContext.CreateDbContext().Pages.ToArray().Select(it => { it.PageObject = PageEntityHelper.ToPage(it); return it; })
                .ToList();
            }));
        }
Example #31
0
        public ActionResult RedactionToDoListDelete(int id)
        {
            using (var context = new SiteDbContext())
            {
                ItemsToDoList team = context.ItemsToDoList.Find(id);
                context.Entry(team).State = System.Data.Entity.EntityState.Deleted;
                context.SaveChanges();
            }

            return(RedirectToAction("Redaction", "Admin"));
        }
Example #32
0
 public IQueryable <Element> Elements()
 {
     return(SiteDbContext.CreateDbContext().Labels
            .Where(it => it.SiteName == SiteName)
            .Select(it => new Element()
     {
         Category = it.Category,
         Name = it.Name,
         Value = it.Value
     }).ToArray().AsQueryable());
 }
Example #33
0
 public void insertContact()
 {
     var Contact = new Entities.Contacts();
     TryUpdateModel(Contact);
     Contact.DateCreated = DateTime.Now;
     if (ModelState.IsValid)
     {
         SiteDbContext db = new SiteDbContext();
         db.Contacts.Add(Contact);
         db.SaveChanges();
         Response.Redirect("/contact?success=true");
     }
 }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            // If no Roles Exist return
            if (context.Roles.Any()) return;

            // Wire up Roles services
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            // Create the User Roles magically from the UserRoles class properties
            var properties = typeof(UserRoles).GetProperties();
            foreach (var prop in properties.Where(prop => roleManager.FindByName(prop.Name) == null))
            {
                roleManager.Create(new IdentityRole(prop.Name));
            }
        }
        /// <summary>
        ///     Seed the Database with Courses, A default user, and roles
        /// </summary>
        /// <param name="context">The context.</param>
        /// 
        public static void Seed(SiteDbContext context)
        {
            // Register Mappings
            AutoMapperConfig.RegisterMappings();

            // Seed the user roles
            new RoleSeeder().Seed(context, SampleSize);

            // Seed the users
            new UserSeeder().Seed(context, SampleSize);

            // Seed the Customers
            new CustomerSeeder().Seed(context, SampleSize);

            // Seed the Suppliers
            new SupplierSeeder().Seed(context, SampleSize);

            // Seed Headlines
            new HeadlineSeeder().Seed(context, SampleSize);
        }
Example #36
0
 public void LoadLoggedUser()
 {
     if (User.Identity.IsAuthenticated)
     {
         LoggedUser = UsersLogic.GetLoggedUser();
         SiteDbContext db = new SiteDbContext();
         LoggedUserLastOrder = db.Orders.Where(o => o.UserId == LoggedUser.UsersId).OrderByDescending(o => o.OrdersId).FirstOrDefault();
         //CheckoutForm.ChangeMode(LoggedUserLastOrder == null ? FormViewMode.Insert : FormViewMode.Edit);
         Literal checkoutMethodlbl = (Literal)CheckoutForm.FindControl("checkoutMethodlbl");
         checkoutMethodlbl.Text = GetLocalResourceObject("LoggedAs") + " " + LoggedUser.FirstName + " " + LoggedUser.LastName;
         GetDiv("PersonalDetailsPanel").Visible = false;
         HidePanel("checkoutMethod");
         HtmlAnchor checkoutMethodTitle = (HtmlAnchor)CheckoutForm.FindControl("checkoutMethodTitle");
         checkoutMethodTitle.Attributes["class"] = "panel-title collapsed";
         OpenPanel("billingInformation");
     }
     else
     {
         OpenPanel("checkoutMethod");
     }
 }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            var hydrator = new Hydrator<Headline>()
                .Ignoring(e => e.HeadlineId)
                .Ignoring( e => e.EditedById)
                .Ignoring( (e => e.SubmitedById))
                .WithCustomGenerator(e => e.Body, new CatchPhraseGenerator())
                .WithCustomGenerator(e => e.Title, new CatchPhraseGenerator())
                .WithDate(e => e.SubmittedOn, DateTime.Now.AddDays(-5), DateTime.Now.AddMinutes(-20)).GetList(sampleSize).ToList();

            hydrator.ForEach(e =>
            {
                e.HeadlineId = Guid.NewGuid().ToString();
                e.Title = Truncate(e.Title, 15);
                e.EditedOn = DateTime.Now;
                e.EditedById = "Admin";
                e.SubmitedById = "Admin";
                context.Headlines.Add(e);
            });

            context.SaveChanges();
        }
 public static string GetNewHeadlineId(SiteDbContext context)
 {
     return (context.Headlines.Count() + HeadlineStartId).ToString();
 }
Example #39
0
 public PaymentLogic(ref Orders Order)
 {
     var OrderPaymentMethod = Order.PaymentMethod;
     SiteDbContext db = new SiteDbContext();
     var PaymentMethodDetails = db.PaymentMethods.Where(p => p.Type == OrderPaymentMethod).FirstOrDefault();
     NameValueCollection Parameters = new NameValueCollection();
     if (PaymentMethodDetails!= null && PaymentMethodDetails.Parameters != null)
     {
         Parameters = HttpUtility.ParseQueryString(PaymentMethodDetails.Parameters.ToLower());
     }
     if (EqualPayment(Order.PaymentMethod, PaymentMethodsEnum.PayPal))
     {
         PaymentProvider = new PayPalProvider(Order, Parameters);
     }
     else if (EqualPayment(Order.PaymentMethod, PaymentMethodsEnum.CreditCard))
     {
         PaymentProvider = new ZCreditProvider(Order, Parameters);
     }
     else if(EqualPayment(Order.PaymentMethod,PaymentMethodsEnum.Bitcoin))
     {
         PaymentProvider = new CoinbaseProvider(Order, Parameters);
     }
 }
 public ProfileController(IAdminRepository adminRepository, SiteDbContext context)
 {
     AdminRepository = adminRepository;
     Context = context;
 }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            // If users exist, return
            if (context.Users.Any()) return;

            // Wire up user services
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            // Generate A Hashed password
            var hashedPassword = new PasswordHasher().HashPassword(DefaultPassword);

            // Create The administrator
            if (userManager.FindByEmail("*****@*****.**") == null)
            {
                // Populate the user object
                var user = CreateAdminUser("admin", "*****@*****.**", hashedPassword, EmployeeUtils.GetNewEmployeeId(context));

                // Set the GUID for the admin user to prevent issues with Identity between refreshes
                user.Id = ConfigurationManager.AppSettings["AdminGuid"];

                // Create the User
                userManager.Create(user, DefaultPassword);
                // Add the administrative role to the user
                userManager.AddToRole(user.Id, UserRoles.Administrator);
            }

            // If there is more then 1 user, return
            if (context.Users.Count() >= 2) return;

            // Create a random number generator
            var rand = new Random();

            // Create some Dummy users with account create view models
            var hydrator = new Hydrator<AccountCreateViewModel>()
                .Ignoring(u => u.ReportsToId)
                .Ignoring(u => u.ReportsTo)
                .Ignoring(u => u.Suboridnates)
                .Ignoring(u => u.CreatedCustomers)
                .WithAmericanAddress(u => u.Address)
                .WithAmericanCity(u => u.City)
                .WithAmericanState(u => u.Region)
                .WithCustomGenerator(u => u.Country, new CountryGenerator())
                .WithFirstName(u => u.FirstName)
                .WithLastName(u => u.LastName)
                .WithDate(u => u.HireDate, DateTime.Now.AddYears(-25), DateTime.Now)
                .WithDate(u => u.BirthDate, DateTime.Now.AddYears(-19), DateTime.Now.AddYears(50))
                .WithAmericanPostalCode(u => u.PostalCode, 1)
                .GetList(sampleSize)
                .ToList();

            // Map them to a Application User List
            var models = Mapper.Map<List<AccountCreateViewModel>, List<ApplicationUser>>(hydrator);

            // Fill in some missing fields and create the user
            models.ForEach(e =>
            {
                e.Title = "Employee";
                e.EmployeeId = EmployeeUtils.GetNewEmployeeId(context);
                e.UserName = (e.LastName + e.FirstName.First() + e.EmployeeId.Substring(3)).ToLower();
                e.Email = $"{e.UserName}@{DomainName}";
                e.PasswordHash = hashedPassword;

                // Title of salutation
                var values = Enum.GetValues(typeof(TitleOfCourtesyEnumeration));
                e.TitleOfCourtesy = (TitleOfCourtesyEnumeration)values.GetValue(rand.Next(values.Length));

                // All Seeded users report to admin
                e.ReportsToId = ConfigurationManager.AppSettings["AdminGuid"];

                // Create the user
                userManager.Create(e, DefaultPassword);
                // Add the user to the user role
                userManager.AddToRole(e.Id, UserRoles.User);
            });
        }
 public HeadlineRepository(SiteDbContext context)
 {
     _context = context;
 }
Example #43
0
        private void RemovePageWithChildPages(SiteDbContext dbContext, PageEntity entity)
        {
            dbContext.Pages.Remove(entity);

            var children = dbContext.Pages
              .Where(it => it.SiteName == entity.SiteName && it.ParentPage == entity.FullName)
              .ToArray();

            foreach (var item in children)
            {
                RemovePageWithChildPages(dbContext, item);
            }
        }
Example #44
0
 public void UpdateTicket(string AssetId, string IssueAddress)
 {
     Ticket.AssetId = AssetId;
     Ticket.IssueAddress = IssueAddress;
     Ticket.Issued += Amount;
     SiteDbContext db = new SiteDbContext();
     db.Entry<Entities.Tickets>(Ticket).State = System.Data.Entity.EntityState.Modified;
     db.SaveChanges();
 }
 // Get the next employee ID
 public static string GetNewEmployeeId(SiteDbContext context) => (context.Users.Count() + EmployeeIdStart).ToString();
Example #46
0
        private void MovePageRecursively(Models.Site site, string pageFullName, string newParent, SiteDbContext dbContext)
        {
            var oldPage = Get(new Page(site, pageFullName));
            var entity = PageEntityHelper.ToPageEntity<PageEntity>(oldPage);
            if (!string.IsNullOrEmpty(newParent))
            {
                var newPage = new Page(new Page(site, newParent), oldPage.Name);
                entity.FullName = newPage.FullName;
                entity.ParentPage = newPage.Parent.FullName;
            }
            else
            {
                entity.FullName = oldPage.Name;
                entity.ParentPage = "";
            }

            dbContext.Pages.Add(entity);

            foreach (var item in ChildPages(oldPage))
            {
                MovePageRecursively(site, item.FullName, entity.FullName, dbContext);
            }

            var oldEntity = dbContext.Pages
                   .Where(it => it.SiteName == oldPage.Site.FullName && it.FullName == oldPage.FullName)
                   .FirstOrDefault();
            if (oldEntity != null)
            {
                dbContext.Pages.Remove(oldEntity);
            }
        }
        public void Seed(SiteDbContext context, int sampleSize)
        {
            if (context.Customers.Any())
                return;

            var hydrator = new Hydrator<CustomerViewModel>()
                .WithAmericanAddress(e => e.Address)
                .WithAmericanCity(e => e.City)
                .WithAmericanState(e => e.Region)
                .WithCustomGenerator(e => e.Country, new CountryGenerator())
                .WithCustomGenerator(e => e.ContactName, new ContactNameGenerator())
                .WithEmailAddress(e => e.ContactEmail)
                .WithAmericanPostalCode(e => e.PostalCode, 4)
                .WithAmericanPhone(e => e.Phone)
                .WithCustomGenerator( e => e.ContactTitle, new TitleGenerator())
                .WithDate(e => e.CreatedOn,DateTime.Now.AddYears(-10),DateTime.Now)
                .Ignoring(e => e.CustomerId)
                .Ignoring(e => e.CreatedBy)
                .Ignoring(e => e.CompanyName)
                .GetList(sampleSize)
                .ToList();

            // Map the view models to models
            var models = AutoMapper.Mapper.Map<List<CustomerViewModel>, List<Customer>>(hydrator);

            // Make sure the company name remains unique
            string name;    // Current Name
            var usedCompanyNames = new List<string>();  // List of used names
            var nameGenerator = new CompanyNameGenerator(); // Name generator

            // Attempt to get the second user ID
            var createdByUserId = context.Users.OrderBy(e => e.FirstName).Skip(1).FirstOrDefault()?.Id;

            // If there are no Users, something went wrong
            if (createdByUserId == null)
            {
                throw new DatabaseSeedException();
            }

            // Go through every model
            models.ForEach(e =>
            {
                do
                {
                    // Generate a random company name
                    name = nameGenerator.Generate();
                }

                // Continue until we get a unused name
                while (usedCompanyNames.Contains(name));

                // Add the name to the list of used names
                usedCompanyNames.Add(name);

                // Assign the name to the Entity
                e.CompanyName = name;

                // Generate a slug for the Entity Based on the name
                e.Slug = name.GenerateSlug();

                // Set the Created By Id
                e.CreatedById = createdByUserId;

                // Add Customer to context
                context.Customers.AddOrUpdate(e);
            });

            // Save Changes
            context.SaveChanges();
        }
 public CustomerRepository(SiteDbContext context)
 {
     _context = context;
 }
Example #49
0
        private void LocalizeWithChildPages(SiteDbContext dbContext, Page page, Site targetSite)
        {
            var entity = dbContext.Pages
                .Where(it => it.SiteName == targetSite.FullName && it.FullName == page.FullName)
                .FirstOrDefault();
            if (entity == null)
            {
                page = Get(page);

                entity = PageEntityHelper.ToPageEntity<PageEntity>(page);
                entity.SiteName = targetSite.FullName;

                dbContext.Pages.Add(entity);

                foreach (var item in ChildPages(page))
                {
                    LocalizeWithChildPages(dbContext, item, targetSite);
                }
            }
        }