public EmailUsController(ILogger <EmailUsController> logger, IEmailService emailService, WebsiteDataContext db, IRecaptchaService reCAPTCHA) { _Logger = logger; _EmailService = emailService; _Db = db; _Recaptcha = reCAPTCHA; }
private void ProcessSelectors(WebsiteDataContext context, XmlElement selectors) { var selectorCollection = XDocument.Parse(selectors.OuterXml).Element("selectors").Elements("selector"); foreach (var selector in selectorCollection) { #region selector int?selectorID = selector.Attribute("id").Try <XAttribute, int?>(c => int.Parse(c.Value), null); if (!selectorID.HasValue) { continue; } Selector sel = (from s in context.Selectors where s.SelectorID == selectorID select s).FirstOrDefault(); if (sel == null) { sel = new Selector() { SelectorID = selectorID.Value }; context.Selectors.InsertOnSubmit(sel); } sel.Name = selector.Value; #endregion } }
protected override void Process() { foreach (Connector connector in Connectors.Where(x => ((ConnectorType)x.ConnectorType).Has(ConnectorType.WebAssortment) && x.Selectors)) { #if DEBUG if (connector.ConnectorID != 1) { continue; } #endif using ( WebsiteDataContext context = new WebsiteDataContext( ConfigurationManager.ConnectionStrings[connector.Connection].ConnectionString)) { log.DebugFormat("Start Selector Product import for {0}", connector.Name); try { DateTime start = DateTime.Now; log.DebugFormat("Start Selector Product:{0}", start); AssortmentServiceSoapClient soap = new AssortmentServiceSoapClient(); XDocument products; var selectorIDs = (from s in context.Selectors select s.SelectorID).ToList(); foreach (int selectorID in selectorIDs) { products = new XDocument(soap.GetSelectorProducts(connector.ConnectorID, selectorID)); Processor processor = new Processor(products, log, connector); log.Debug("Start import brands"); processor.ImportBrands(); log.Debug("Finished import brands"); log.Debug("Start import productgroups"); processor.ImportProductGroups(false); log.Debug("Finished import productgroups"); log.Debug("Start import Products"); processor.ImportSelectorProducts(); log.Debug("Finished import Products"); //log.Debug("Start import Attributes"); //processor.ProcessAttributes(soap, connector, false, null, false); //log.Debug("Finished import Attributes"); //processor.CleanUpProducts(); //processor.CleanUpProductGroupMapping(); } } catch (Exception ex) { log.Error("Error import Selector Products", ex); } log.DebugFormat("Finish Process Selector Product for {0}", connector.Name); } } }
public MediaController(WebsiteDataContext Db, ILogger <MediaController> Logger, IHostingEnvironment HostingEnv, IConfiguration Config) { _Db = Db; _Logger = Logger; _HostingEnv = HostingEnv; _Config = Config; }
public Task Invoke(HttpContext httpContext, WebsiteDataContext db, IConfiguration config, IEmailService smtp) { if (httpContext.User.Identity.IsAuthenticated) { Account account = db.Accounts.Find(httpContext.User.AccountId()); if (account.ForcePasswordReset) { //Clear old tokens List <PasswordReset> oldTokens = db.PasswordResets.Where(c => c.Account.Id == account.Id).ToList() ?? new List <PasswordReset>(); foreach (PasswordReset token in oldTokens) { token.ExpiresAt = DateTime.UtcNow; } // Get new token PasswordReset newToken = new PasswordReset( account, DateTime.UtcNow.AddMinutes(config["LoginSettings:PasswordResetTokenLength"].ToInt()) ); // Update database db.PasswordResets.Add(newToken); db.SaveChanges(); // send password reset email smtp.SendPasswordResetEmailAsync(newToken, httpContext.Request.BaseUrl()); httpContext.SignOutAsync(); httpContext.Response.Redirect("/error/password-reset"); } } return(_next(httpContext)); }
public RequestPasswordResetController(WebsiteDataContext db, IConfiguration configuration, IEmailService emailService, ILogger <RequestPasswordResetController> logger) { _Db = db; _Config = configuration; _EmailService = emailService; _Logger = logger; }
protected override void Process() { log.Info("Starting import of AlaTest product reviews"); AssortmentServiceSoapClient client = new AssortmentServiceSoapClient(); try { var reviews = client.GetProductReviews(); foreach (Connector connector in base.Connectors.Where(c => c.ConnectorType.Has(ConnectorType.WebAssortment))) { using (WebsiteDataContext context = new WebsiteDataContext(ConfigurationManager.ConnectionStrings[connector.Connection].ConnectionString)) { XDocument reviewsDoc = XDocument.Parse(reviews.OuterXml); foreach (var productReviewElement in reviewsDoc.Element("ProductReviews").Elements("Product")) { #region Product reviews var product = (from p in context.Products where p.ManufacturerID == productReviewElement.Attribute("vendorItemNumber").Value select p).FirstOrDefault(); if (product != null) { var ProductReview = (from pr in context.AlatestReviews where pr.ProductID == product.ProductID select pr).FirstOrDefault(); if (ProductReview == null) { ProductReview = new AlatestReview { Product = product }; context.AlatestReviews.InsertOnSubmit(ProductReview); } ProductReview.Review = productReviewElement.Try(c => c.Element("Review").Value, string.Empty); ProductReview.ReviewSnippet = productReviewElement.Try(c => c.Element("ReviewSnippet").Value, string.Empty); } #endregion } try { using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, TimeSpan.FromMinutes(3))) { context.SubmitChanges(); ts.Complete(); } } catch (Exception e) { log.Error("Saving product reviews to the database failed for connector" + connector.Name, e); } } } } catch (Exception e) { log.Fatal("Downloading product reviews failed", e); } }
public RegistrationController(WebsiteDataContext db, IConfiguration configuration, IEmailService emailService, IPasswordHasher <Account> hasher, ILogger <RegistrationController> logger) { _Db = db; _EmailService = emailService; _Hasher = hasher; _Logger = logger; _Config = configuration; }
public EmailService(IViewRenderer viewRenderer, IEmailConfiguration emailConfig, IHostingEnvironment env, ILogger <EmailService> logger, WebsiteDataContext db) { _ViewRender = viewRenderer; _EmailConfig = emailConfig; _Logger = logger; _Db = db; _env = env; }
private void ProcessBrandImages(Connector connector) { using (WebsiteDataContext context = new WebsiteDataContext(connector.ConnectionString)) { var brandImages = (from r in images.Root.Elements("Brands").Elements("BrandMedia") select int.Parse(r.Attribute("BrandID").Value)).Distinct().ToArray(); var brands = (from b in context.Brands select b).ToList(); var existingProducts = (from c in context.ImageStores where c.ImageType == ImageType.BrandImage.ToString() select c).Distinct().ToDictionary(c => c.BrandCode, c => c); string imageDirectory = GetConfiguration().AppSettings.Settings["ImageDirectory"].Value; foreach (var r in images.Root.Elements("Brands").Elements("BrandMedia")) { //log.DebugFormat("Get BrandImage for {0} url: {1}", r.Attribute("BrandVendorCode").Value, r.Value); try { if (!string.IsNullOrEmpty(r.Value)) { string url = GetImage(r.Value, ImageType.BrandImage, r.Attribute("BrandID").Value, null, imageDirectory); if (!string.IsNullOrEmpty(url)) { ImageStore brandImage = null; if (existingProducts.ContainsKey(r.Attribute("BrandVendorCode").Value)) { brandImage = existingProducts[r.Attribute("BrandVendorCode").Value]; brandImage.ImageUrl = url; brandImage.BrandCode = r.Attribute("BrandVendorCode").Value; brandImage.BrandID = brands.Where(x => x.BrandCode == r.Attribute("BrandVendorCode").Value).Select(x => x.BrandID).FirstOrDefault(); } else { brandImage = new ImageStore() { BrandID = brands.Where(x => x.BrandCode == r.Attribute("BrandVendorCode").Value).Select(x => x.BrandID).FirstOrDefault(), BrandCode = r.Attribute("BrandVendorCode").Value, ImageUrl = url, ImageType = ImageType.BrandImage.ToString() }; context.ImageStores.InsertOnSubmit(brandImage); } } } } catch (Exception ex) { log.Error(ex); } } context.SubmitChanges(); } }
public NavbarService(WebsiteDataContext db) { _Db = db; navItems = _Db.NavItems .Include(nav => nav.Page) .Include(nav => nav.NavItemPages) .ThenInclude(nip => nip.Page).ToList(); }
public async Task <bool> AddVoteAsync(string userId, string category) { using (var context = new WebsiteDataContext()) { context.Mobro2016Votes.AddOrUpdate(new Mobro2016Vote(userId, category)); var _ = await context.SaveChangesAsync().ConfigureAwait(false); } return(true); }
public void ProcessRelatedProducts(WebsiteDataContext context, ConcentratorSelectorService.SelectorServiceSoapClient client, int connectorID) { var selectorIDs = (from s in context.Selectors select s.SelectorID).ToList(); foreach (int selectorID in selectorIDs) { var products = client.FindProduct(selectorID, string.Empty, connectorID); foreach (var manufacturerID in products) { #region Product var product = (from p in context.Products where p.ManufacturerID == manufacturerID select p).FirstOrDefault(); if (product == null) { continue; } #region related products var relatedProducts = client.FindCompatibleProducts(selectorID, product.ManufacturerID, connectorID); foreach (var relatedProductID in relatedProducts) { var relatedProduct = (from rp in context.Products where rp.ManufacturerID == relatedProductID.ToString() select rp).FirstOrDefault(); if (relatedProduct == null) { continue; //if no product exists move on to next one } //insert related product RelatedProduct relatedProd = (from rp in context.RelatedProducts where rp.ProductID == product.ProductID && rp.RelatedProductID == relatedProduct.ProductID select rp).FirstOrDefault(); if (relatedProd == null) { context.RelatedProducts.InsertOnSubmit(new RelatedProduct { ProductID = product.ProductID, RelatedProductID = relatedProduct.ProductID, SelectorID = selectorID }); } } #endregion #endregion } } }
private void ProcessProductGroupImages(Connector connector) { using (WebsiteDataContext context = new WebsiteDataContext(connector.ConnectionString)) { var productGroupImages = (from r in images.Root.Elements("ProductGroups").Elements("ProductGroupImage") select int.Parse(r.Attribute("ProductGroupID").Value)).ToArray(); var existingProducts = (from c in context.ImageStores where c.ProductGroupID.HasValue && productGroupImages.Contains(c.ProductGroupID.Value) && c.ManufacturerID == null && c.CustomerProductID == null select c).ToDictionary(c => c.ProductGroupID.Value, c => c); string imageDirectory = GetConfiguration().AppSettings.Settings["ImageDirectory"].Value; foreach (var r in images.Root.Elements("ProductGroups").Elements("ProductGroupImage")) { //log.DebugFormat("Get ProductGroup for {0} url: {1}", r.Attribute("ProductGroupID").Value, r.Value); try { if (!string.IsNullOrEmpty(r.Value)) { string url = GetImage(r.Value, ImageType.ProductGroupImage, r.Attribute("ProductGroupID").Value, null, imageDirectory); if (!string.IsNullOrEmpty(url)) { ImageStore productGroupImage = null; if (existingProducts.ContainsKey(int.Parse(r.Attribute("ProductGroupID").Value))) { productGroupImage = existingProducts[int.Parse(r.Attribute("ProductGroupID").Value)]; productGroupImage.ImageUrl = url; } else { productGroupImage = new ImageStore() { ProductGroupID = int.Parse(r.Attribute("ProductGroupID").Value), ImageUrl = url, ImageType = ImageType.ProductGroupImage.ToString() }; context.ImageStores.InsertOnSubmit(productGroupImage); } } } } catch (Exception ex) { log.Error(ex); } } context.SubmitChanges(); } }
// Get bounding box for this track, for map display in the CMS public double[,] GetBoundingBox(WebsiteDataContext ctx) { ctx.Entry(this).Collection(t => t.Activities).Load(); if (Activities.Count <= 0) { return(null); } double[] xVals = Activities.Select(a => a.CoordX).ToArray(); double[] yVals = Activities.Select(a => a.CoordY).ToArray(); return(new double[, ] { { xVals.Min(), yVals.Max() }, { xVals.Max(), yVals.Min() } }); }
protected override void Process() { ConcentratorSelectorService.SelectorServiceSoapClient serviceClient = new Spider.WebsiteImport.ConcentratorSelectorService.SelectorServiceSoapClient(); using (WebsiteDataContext context = new WebsiteDataContext()) { try { log.InfoFormat("Starting import of related products"); ProcessRelatedProducts(context, serviceClient, 1); context.SubmitChanges(); log.InfoFormat("Finished import of related products"); } catch (Exception e) { log.Error("Importing of related products for connector " + Name + "failed ", e); } } }
public async Task ResetAsync() { using (var context = new WebsiteDataContext()) { context.Mobro2016Votes.RemoveRange(context.Mobro2016Votes.AsEnumerable()); var _ = await context.SaveChangesAsync().ConfigureAwait(false); } using (var context = new WebsiteDataContext()) { this.AddVote(context, Guid.NewGuid().ToString(), "barry-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "biker-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "groucho-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "logan-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "mutton-chops-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "price-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "stark-stache"); this.AddVote(context, Guid.NewGuid().ToString(), "tai-chi-master-stache"); var _ = await context.SaveChangesAsync().ConfigureAwait(false); } }
public async Task <IDictionary <string, int> > GetVoteCountByCategoryAsync() { var result = new Dictionary <string, int>(); using (var context = new WebsiteDataContext()) { var countsByCategory = from vote in context.Mobro2016Votes group vote by vote.Category into category select new { Name = category.Key, Count = category.Count() }; result = countsByCategory.ToDictionary(_ => _.Name, _ => _.Count); } if (result.Count == 0) { await this.ResetAsync().ConfigureAwait(false); } return(result); }
private void ProcessXML() { log.Info("Start import of expert product reviews"); AssortmentServiceSoapClient client = new AssortmentServiceSoapClient(); var message = client.GetExpertProductReviews(); XDocument reviews = XDocument.Parse(message); var productReviews = (from p in reviews.Element("ExpertReviews").Element("Products").Elements("Product") select new { ConcentratorID = int.Parse(p.Attribute("ID").Value), Reviews = from r in p.Element("Reviews").Elements("Review") let sourceID = int.Parse(r.Attribute("SourceID").Value) select new { CustomID = r.Attribute("ConcentratorID").Value, SourceID = sourceID, isSummary = bool.Parse(r.Attribute("isSummary").Value), Author = r.Element("Author").Value, Date = r.Element("Date").Value, Title = r.Element("Title").Value, Summary = r.Element("Summary").Value, Verdict = r.Element("Verdict").Value, ReviewURL = r.Element("ReviewURL").Value, RatingImageURL = r.Element("RatingImageURL").Value, Rating = r.Element("Rating").Try <XElement, int?>(c => int.Parse(c.Value), null), Source = (from s in reviews.Element("ExpertReviews").Element("Sources").Elements("Source") where int.Parse(s.Attribute("ID").Value) == sourceID select new { Name = s.Element("Name").Value, LanguageCode = s.Element("LanguageCode").Value, CountryCode = s.Element("CountryCode").Value, SourceURL = s.Element("SourceURL").Value, SourceLogoURL = s.Element("SourceLogoURL").Value, SourceRank = s.Element("SourceRank").Try <XElement, int?>(c => int.Parse(c.Value), null) }).FirstOrDefault() } } ); foreach (Connector connector in base.Connectors.Where(x => ((ConnectorType)x.ConnectorType).Has(ConnectorType.Reviews))) { log.InfoFormat("Start expert product review import for connector {0}", connector.Name); DateTime start = DateTime.Now; using (WebsiteDataContext context = new WebsiteDataContext(ConfigurationManager.ConnectionStrings[connector.Connection].ConnectionString)) { var productIDs = (from p in context.Products select p.ConcentratorProductID).ToList(); var sources = (from s in context.ReviewSources select s).ToList(); productIDs.Sort(); foreach (var product in productReviews) { if (!productIDs.Contains(product.ConcentratorID)) { continue; } var productItem = (from p in context.Products where p.ConcentratorProductID == product.ConcentratorID select p).FirstOrDefault(); foreach (var review in product.Reviews) { #region Source var src = sources.FirstOrDefault(c => c.CustomSourceID == review.SourceID); if (src == null) { src = new ReviewSource { CustomSourceID = review.SourceID }; context.ReviewSources.InsertOnSubmit(src); sources.Add(src); } src.CountryCode = review.Source.CountryCode; src.LanguageCode = review.Source.LanguageCode; src.Name = review.Source.Name; src.SourceLogoUrl = review.Source.SourceLogoURL; src.SourceRank = review.Source.SourceRank; src.SourceUrl = review.Source.SourceURL; #endregion var reviewItem = (from s in context.AlatestExpertReviews where s.CustomID == review.CustomID select s).FirstOrDefault(); if (reviewItem == null) { reviewItem = new AlatestExpertReview() { Product = productItem, ReviewSource = src, CustomID = review.CustomID }; context.AlatestExpertReviews.InsertOnSubmit(reviewItem); } reviewItem.Author = review.Author; DateTime date; DateTime.TryParse(review.Date, out date); reviewItem.Date = review.Date.Try <string, DateTime?>(c => DateTime.Parse(c), null); reviewItem.isSummary = review.isSummary; reviewItem.Rating = review.Rating; reviewItem.RatingImageURL = review.RatingImageURL; reviewItem.ReviewURL = review.ReviewURL; reviewItem.Summary = review.Summary; reviewItem.Title = review.Title; reviewItem.Verdict = review.Verdict; } } try { using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Suppress, TimeSpan.FromMinutes(5))) { context.SubmitChanges(); } } catch (Exception e) { log.AuditError("Import of alatest expert reviews failed for connector: " + connector.Name, e, "Import Expert Reviews"); } } } }
private void ProcessProductImages(Connector connector) { using (WebsiteDataContext context = new WebsiteDataContext(connector.ConnectionString)) { var productImages = (from r in images.Root.Elements("Products").Elements("ProductImage") select new { ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value), Sequence = r.Attribute("Sequence").Value }).ToList().OrderByDescending(x => x.ConcentratorProductID); var websiteProducts = (from p in context.Products where p.ConcentratorProductID.HasValue select p).ToList(); var ImageDB = (from i in context.ImageStores where i.ImageType == ImageType.ProductImage.ToString() select i).ToList(); List <ImageStore> existingProducts = new List <ImageStore>(); foreach (var prod in productImages) { var websiteProduct = (from p in websiteProducts where p.ConcentratorProductID.Value == prod.ConcentratorProductID select p).FirstOrDefault(); if (websiteProduct != null) { var product = (from p in ImageDB where p.CustomerProductID == websiteProduct.ProductID.ToString() && p.Sequence == int.Parse(prod.Sequence) select p).FirstOrDefault(); if (product != null) { existingProducts.Add(product); } } } int counter = productImages.Count(); int showMessage = 0; string imageDirectory = GetConfiguration().AppSettings.Settings["ImageDirectory"].Value; foreach (var r in images.Root.Elements("Products").Elements("ProductImage").OrderByDescending(x => x.Attribute("ProductID").Value)) { var websiteProduct = (from p in websiteProducts where p.ConcentratorProductID.Value == int.Parse(r.Attribute("ProductID").Value) select p).FirstOrDefault(); try { if (!string.IsNullOrEmpty(r.Value) && websiteProduct != null) { string url = GetImage(r.Value, ImageType.ProductImage, r.Attribute("ProductID").Value, int.Parse(r.Attribute("Sequence").Value), imageDirectory); if (!string.IsNullOrEmpty(url)) { ImageStore productImage = existingProducts.Where(x => x.Sequence == int.Parse(r.Attribute("Sequence").Value) && x.CustomerProductID == websiteProduct.ProductID.ToString()).FirstOrDefault(); if (productImage != null) { productImage.ImageUrl = url; productImage.BrandID = int.Parse(r.Attribute("BrandID").Value); productImage.ManufacturerID = r.Attribute("ManufacturerID").Value; productImage.Sequence = int.Parse(r.Attribute("Sequence").Value); productImage.ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value); } else { productImage = new ImageStore() { ImageUrl = url, BrandID = int.Parse(r.Attribute("BrandID").Value), CustomerProductID = websiteProduct.ProductID.ToString(), ManufacturerID = r.Attribute("ManufacturerID").Value, ImageType = ImageType.ProductImage.ToString(), Sequence = int.Parse(r.Attribute("Sequence").Value), ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value) }; context.ImageStores.InsertOnSubmit(productImage); } } counter--; showMessage++; if (showMessage == 500) { log.InfoFormat("{0} images to process", counter); showMessage = 0; } } } catch (Exception ex) { log.Error(ex); } context.SubmitChanges(); } // context.SubmitChanges(); } }
public static void Seed(WebsiteDataContext context) { // Check whether database has already got data in it. Config cfg = context.Config.Find(1); if (cfg != null) { return; } //------------------------------------------------------------------ StreamReader mediaJson = new StreamReader(Path.Combine(basePath, "media.json")); List <MediaSeeder> media = JsonConvert.DeserializeObject <List <MediaSeeder> >(mediaJson.ReadToEnd()); mediaJson.Close(); List <ImageMedia> images = media.Where(m => m.MediaType.Category == MediaCategory.Image).Select(m => (ImageMedia)m.ToBaseMedia()).ToList(); List <AudioMedia> audios = media.Where(m => m.MediaType.Category == MediaCategory.Audio).Select(m => (AudioMedia)m.ToBaseMedia()).ToList(); context.AddRangeWithIdentityInsert(images, "Media"); context.AddRangeWithIdentityInsert(audios, "Media"); //------------------------------------------------------------------ StreamReader categoriesJson = new StreamReader(Path.Combine(basePath, "categories.json")); List <FactFileCategory> categories = JsonConvert.DeserializeObject <List <FactFileCategory> >(categoriesJson.ReadToEnd()); categoriesJson.Close(); context.AddRangeWithIdentityInsert(categories, "FactFileCategories"); //----------------------------------------------------------------- StreamReader entriesJson = new StreamReader(Path.Combine(basePath, "entries.json")); List <EntrySeeder> entries = JsonConvert.DeserializeObject <List <EntrySeeder> >(entriesJson.ReadToEnd()); entriesJson.Close(); context.AddRangeWithIdentityInsert(entries.Select(e => e.ToFactFileEntry()), "FactFileEntries"); context.AddRange(entries.Select(e => e.GetFactFileEntryImages())?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1)); context.AddRange(entries.Select(e => e.GetFactFileNuggets())?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1)); //------------------------------------------------------------------ StreamReader tracksJson = new StreamReader(Path.Combine(basePath, "tracks.json")); List <TrackSeeder> tracks = JsonConvert.DeserializeObject <List <TrackSeeder> >(tracksJson.ReadToEnd()); tracksJson.Close(); context.AddRangeWithIdentityInsert(tracks.Select(t => t.ToTrack()), "Tracks"); context.AddRangeWithIdentityInsert(tracks.Select(t => t.GetActivities())?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1), "Activities"); context.AddRange(tracks.Select(t => t.GetActivityImages())?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1)); //------------------------------------------------------------------- StreamReader quizzesJson = new StreamReader(Path.Combine(basePath, "quizzes.json")); List <QuizSeeder> quizzes = JsonConvert.DeserializeObject <List <QuizSeeder> >(quizzesJson.ReadToEnd()); quizzesJson.Close(); context.AddRangeWithIdentityInsert(quizzes.Select(q => q.ToQuiz()), "Quizzes"); // Intially we cannot save correct answer IDs due to foreign key constraint. Will save without and add later. context.AddRangeWithIdentityInsert(quizzes.Select(q => q.GetQuestions(includeCorrectAnswers: false))?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1), "QuizQuestions"); context.AddRangeWithIdentityInsert(quizzes.Select(q => q.GetAnswers())?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1), "QuizAnswers"); //-------------------------------------------------------------------- context.Add(new Config { MasterUnlockCode = "quizmaster" }); context.SaveChanges(); // Detach all entries from the tracker so that we can update questions with their correct answer IDs. List <EntityEntry> entityEntries = context.ChangeTracker.Entries().ToList(); foreach (var entry in entityEntries) { entry.State = EntityState.Detached; } context.UpdateRange(quizzes.Select(q => q.GetQuestions(includeCorrectAnswers: true))?.Aggregate((l1, l2) => l2 != null ? l1.Concat(l2).ToList() : l1)); // Save the database with the added correct answer IDs. context.SaveChanges(); }
void AddVote(WebsiteDataContext context, string userId, string category) { context.Mobro2016Votes.AddOrUpdate(new Mobro2016Vote(userId, category)); }
protected override void Process() { foreach (Connector connector in Connectors.Where(x => x.ZipCodes)) { log.DebugFormat("Start Process zipcode import for {0}", connector.Name); DateTime start = DateTime.Now; try { using (ZipCodesSoapClient soap = new ZipCodesSoapClient()) { using (WebsiteDataContext context = new WebsiteDataContext(ConfigurationManager.ConnectionStrings[connector.Connection].ConnectionString)) { var zips = (from p in context.Postcodes select p).ToList(); var ms = soap.GetZipcodes(); Stream s = new MemoryStream(ms); XmlSerializer x = new XmlSerializer(typeof(Postcode)); List <Postcode> importZips = (List <Postcode>)x.Deserialize(s); foreach (var newzip in importZips) { var existingVar = (from c in zips where c.ZipCodeID == newzip.ZipCodeID select c).FirstOrDefault(); if (existingVar == null) { log.DebugFormat("Try inserting new zipcode {0}", newzip.PCWIJK); Postcode newZipCode = new Postcode { PCWIJK = newzip.PCWIJK, PCLETTER = newzip.PCLETTER, PCREEKSID = newzip.PCREEKSID, PCREEKSVAN = newzip.PCREEKSVAN, PCREEKSTOT = newzip.PCREEKSTOT, PCCITYTPG = newzip.PCCITYTPG, PCCITYNEN = newzip.PCCITYNEN, PCSTRTPG = newzip.PCSTRTPG, PCSTRNEN = newzip.PCSTRNEN, PCSTROFF = newzip.PCSTROFF, PCCITYEXT = newzip.PCCITYEXT, PCGEMEENTEID = newzip.PCGEMEENTEID, PCGEMEENTENAAM = newzip.PCGEMEENTENAAM, PCPROVINCIE = newzip.PCPROVINCIE.Value, PCCEBUCO = newzip.PCCEBUCO, PCSTREXT = newzip.PCSTREXT }; context.Postcodes.InsertOnSubmit(newZipCode); } else { existingVar.PCWIJK = newzip.PCWIJK; existingVar.PCLETTER = newzip.PCLETTER; existingVar.PCREEKSID = newzip.PCREEKSID.Value; existingVar.PCREEKSVAN = newzip.PCREEKSVAN; existingVar.PCREEKSTOT = newzip.PCREEKSTOT; existingVar.PCCITYTPG = newzip.PCCITYTPG; existingVar.PCCITYNEN = newzip.PCCITYNEN; existingVar.PCSTRTPG = newzip.PCSTRTPG; existingVar.PCSTRNEN = newzip.PCSTRNEN; existingVar.PCSTROFF = newzip.PCSTROFF; existingVar.PCCITYEXT = newzip.PCCITYEXT; existingVar.PCGEMEENTEID = newzip.PCGEMEENTEID; existingVar.PCGEMEENTENAAM = newzip.PCGEMEENTENAAM; existingVar.PCPROVINCIE = newzip.PCPROVINCIE.Value; existingVar.PCCEBUCO = newzip.PCCEBUCO; existingVar.PCSTREXT = newzip.PCSTREXT; } context.SubmitChanges(); } } } } catch (Exception ex) { log.Fatal(ex); } log.DebugFormat("Finish Process zipcode import for {0}", connector.Name); } }
private void ProcessBrandImages(Connector connector) { using (WebsiteDataContext context = new WebsiteDataContext(connector.ConnectionString)) { var brandImages = (from r in images.Root.Elements("Brands").Elements("BrandMedia") select int.Parse(r.Attribute("BrandID").Value)).Distinct().ToArray(); var brands = (from b in context.Brands select b).ToList(); var existingProducts = (from c in context.ImageStores where c.ImageType == ImageType.BrandImage.ToString() select c).ToList(); var unusedImages = existingProducts; string imageDirectory = GetConfiguration().AppSettings.Settings["ImageDirectory"].Value; foreach (var r in images.Root.Elements("Brands").Elements("BrandMedia")) { //log.DebugFormat("Get BrandImage for {0} url: {1}", r.Attribute("BrandVendorCode").Value, r.Value); try { if (!string.IsNullOrEmpty(r.Value)) { //string url = GetImage(r.Value, ImageType.BrandImage, r.Attribute("BrandID").Value, null, imageDirectory); string url = r.Value; if (!string.IsNullOrEmpty(url)) { ImageStore brandImage = existingProducts.FirstOrDefault(x => x.BrandCode == r.Attribute("BrandID").Value); if (brandImage != null) { if ( brandImage.ImageUrl != url || brandImage.BrandCode != r.Attribute("BrandID").Value || brandImage.BrandID != brands.Where(x => x.BrandCode == r.Attribute("BrandID").Value).Select(x => x.BrandID).FirstOrDefault() ) { brandImage.ImageUrl = url; brandImage.BrandCode = r.Attribute("BrandID").Value; brandImage.BrandID = brands.Where(x => x.BrandCode == r.Attribute("BrandID").Value).Select(x => x.BrandID).FirstOrDefault(); brandImage.LastModificationTime = DateTime.Now; } unusedImages.Remove(brandImage); } else { brandImage = new ImageStore() { BrandID = brands.Where(x => x.BrandCode == r.Attribute("BrandID").Value).Select(x => x.BrandID).FirstOrDefault(), BrandCode = r.Attribute("BrandID").Value, ImageUrl = url, ImageType = ImageType.BrandImage.ToString(), LastModificationTime = DateTime.Now }; context.ImageStores.InsertOnSubmit(brandImage); } } } } catch (Exception ex) { log.Error(ex); } } context.SubmitChanges(); //try //{ // log.DebugFormat("Try To delete {0} brand images", unusedImages.Count); // context.ImageStores.DeleteAllOnSubmit(unusedImages); // context.SubmitChanges(); //} //catch (Exception ex) //{ // log.Error("Error delete unused images", ex); //} } }
public AccountController(WebsiteDataContext db, IPasswordHasher <Account> hasher, ILogger <AccountController> logger) { _Db = db; _Hasher = hasher; _Logger = logger; }
public WebsiteRepository(WebsiteDataContext context) { m_context = context; }
public void Init() { WebsiteDataContext context = new WebsiteDataContext(); m_repository = new WebsiteRepository(context); }
public PageController(WebsiteDataContext db, ILogger <PageController> logger) { _Db = db; _Logger = logger; }
public TrackController(WebsiteDataContext db, ILogger <TrackController> logger) { _Db = db; _Logger = logger; }
private void ProcessProductImages(Connector connector) { using (WebsiteDataContext context = new WebsiteDataContext(connector.ConnectionString)) { var productImages = (from r in images.Root.Elements("Products").Elements("ProductMedia") select new { ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value), Sequence = r.Attribute("Sequence").Value }).ToList().OrderByDescending(x => x.ConcentratorProductID); var websiteProducts = (from p in context.Products where p.ConcentratorProductID.HasValue select p).ToList(); var ImageDB = (from i in context.ImageStores where i.ImageType == ImageType.ProductImage.ToString() select i).ToList(); var unusedImages = ImageDB; var brands = (from b in context.Brands select b).ToList(); List <ImageStore> existingProducts = new List <ImageStore>(); foreach (var prod in productImages) { var websiteProduct = (from p in websiteProducts where p.ConcentratorProductID.Value == prod.ConcentratorProductID select p).OrderByDescending(x => x.IsVisible).FirstOrDefault(); if (websiteProduct != null) { var product = (from p in ImageDB where p.ConcentratorProductID == prod.ConcentratorProductID && p.Sequence == int.Parse(prod.Sequence) select p).FirstOrDefault(); if (product != null) { existingProducts.Add(product); } } } int counter = productImages.Count(); int showMessage = 0; bool succes = true; //string imageDirectory = GetConfiguration().AppSettings.Settings["ImageDirectory"].Value; foreach (var r in images.Root.Elements("Products").Elements("ProductMedia").OrderByDescending(x => x.Attribute("ProductID").Value)) { var websiteProduct = (from p in websiteProducts where p.ConcentratorProductID.Value == int.Parse(r.Attribute("ProductID").Value) select p).OrderByDescending(x => x.IsVisible).FirstOrDefault(); try { if (!string.IsNullOrEmpty(r.Value) && websiteProduct != null) { //string url = GetImage(r.Value, ImageType.ProductImage, r.Attribute("ProductID").Value, int.Parse(r.Attribute("Sequence").Value), imageDirectory); string url = r.Value; if (!string.IsNullOrEmpty(url)) { ImageStore productImage = existingProducts.Where(x => x.ConcentratorProductID.Value == int.Parse(r.Attribute("ProductID").Value) && x.Sequence == int.Parse(r.Attribute("Sequence").Value)).FirstOrDefault(); if (productImage != null) { if (productImage.ImageUrl != url || productImage.BrandID != int.Parse(r.Attribute("BrandID").Value) || productImage.ManufacturerID != r.Attribute("ManufacturerID").Value || productImage.Sequence != int.Parse(r.Attribute("Sequence").Value) || productImage.ConcentratorProductID != int.Parse(r.Attribute("ProductID").Value) ) { productImage.ImageUrl = url; productImage.BrandID = int.Parse(r.Attribute("BrandID").Value); productImage.ManufacturerID = r.Attribute("ManufacturerID").Value; productImage.Sequence = int.Parse(r.Attribute("Sequence").Value); productImage.ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value); productImage.LastModificationTime = DateTime.Now; } unusedImages.Remove(productImage); } else { productImage = new ImageStore() { ImageUrl = url, BrandID = int.Parse(r.Attribute("BrandID").Value), CustomerProductID = websiteProduct.ProductID.ToString(), ManufacturerID = r.Attribute("ManufacturerID").Value, ImageType = ImageType.ProductImage.ToString(), Sequence = int.Parse(r.Attribute("Sequence").Value), ConcentratorProductID = int.Parse(r.Attribute("ProductID").Value), LastModificationTime = DateTime.Now }; context.ImageStores.InsertOnSubmit(productImage); } } counter--; showMessage++; if (showMessage == 500) { log.InfoFormat("{0} images to process", counter); showMessage = 0; } } context.SubmitChanges(); } catch (Exception ex) { succes = false; log.Error(ex); } } try { if (succes) { if (Processor.TableExists(context, "AuctionProducts")) { var auctionImages = (from a in context.AuctionProducts join i in context.ImageStores on a.Product.ConcentratorProductID equals i.ConcentratorProductID select i).ToList(); unusedImages = unusedImages.Except(auctionImages).ToList(); } if (Processor.TableExists(context, "RelatedProducts")) { var relatedproducts = (from r in context.RelatedProducts join i in context.ImageStores on r.Product.ConcentratorProductID equals i.ConcentratorProductID select i).ToList(); unusedImages = unusedImages.Except(relatedproducts).ToList(); } log.DebugFormat("Try To delete {0} product images", unusedImages.Count); context.ImageStores.DeleteAllOnSubmit(unusedImages); context.SubmitChanges(); } } catch (Exception ex) { log.Error("Error delete unused images", ex); } } }
public NavbarSettingsController(WebsiteDataContext db, ILogger <NavbarSettingsController> logger) { _Db = db; _Logger = logger; }
public UsersController(WebsiteDataContext db, IEmailService emailService, ILogger <UsersController> logger) { _Db = db; _EmailService = emailService; _Logger = logger; }