//Get Order (Cart) public async Task <ActionResult> HomeCart() { HomeCartViewModel model = new HomeCartViewModel { Order = new ModelLibrary.Order { ItemsList = new List <ModelLibrary.OrderLineItem>() }, TotalPrice = 0 }; if (Session["orderId"] != null) { model.Order = await _orderProxy.GetOrderByIdAsync((int)Session["orderId"]); model.TotalPrice = model.Order.TotalPriceCent; } return(View(model)); }
public IActionResult Cart(int?id) { // the current cart is stored as a cookie string cartCookie = Request.Cookies["nw_cart"] ?? string.Empty; // if visitor clicked Add to Card button if (id.HasValue) { if (string.IsNullOrWhiteSpace(cartCookie)) { cartCookie = id.ToString(); } else { string[] ids = cartCookie.Split('-'); if (!ids.Contains(id.ToString())) { cartCookie = string.Join('-', cartCookie, id.ToString()); } Response.Cookies.Append("nw_cart", cartCookie); } } var model = new HomeCartViewModel { Cart = new Cart { Items = Enumerable.Empty <CartItem>() }, Recommendations = new List <EnrichedRecommendation>() }; if (cartCookie.Length > 0) { model.Cart.Items = cartCookie.Split('-').Select(item => new CartItem { ProductID = int.Parse(item), ProductName = db.Products.Find(int.Parse(item)).ProductName } ); } if (System.IO.File.Exists(GetDataPath("germany-model.zip"))) { var mlContext = new MLContext(); ITransformer modelGermany; using (var stream = new FileStream( path: GetDataPath("germany-model.zip"), mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read)) { modelGermany = mlContext.Model.Load(stream, out DataViewSchema schema); } var predictionEngine = mlContext.Model.CreatePredictionEngine <ProductCobought, Recommendation>(modelGermany); var products = db.Products.ToArray(); foreach (var item in model.Cart.Items) { var topThree = products.Select(product => predictionEngine.Predict( new ProductCobought { ProductID = (uint)item.ProductID, CoboughtProductID = (uint)product.ProductID } )) .OrderByDescending(x => x.Score) .Take(3) .ToArray(); model.Recommendations.AddRange(topThree.Select(rec => new EnrichedRecommendation { CoboughtProductID = rec.CoboughtProductID, Score = rec.Score, ProductName = db.Products.Find((int)rec.CoboughtProductID).ProductName }) ); } // show the best three product recommendations model.Recommendations = model.Recommendations .OrderByDescending(rec => rec.Score) .Take(3) .ToList(); } return(View(model)); }
/* * Ürün kartı gösteren Action Metodu. * Burayı yazarken yer yer beynim yandı. */ public IActionResult Cart(int?id) { // O anki Cart bilgisini cookie'de saklıyor string cartCookie = Request.Cookies["basket_items"] ?? string.Empty; /* * Sepete eklenen ürünler bu örnek özelinde bir cookie'de duruyorlar. * Cart action metoduna gelen id değeri boş değilse */ if (id.HasValue) { if (string.IsNullOrWhiteSpace(cartCookie)) { cartCookie = id.ToString(); } else // ve ürün sepeti çerezinin içerisinde veriler varsa { string[] ids = cartCookie.Split('|'); // pipe karakterine göre içeriği split ediyoruz if (!ids.Contains(id.ToString())) // gelen id bu çerez içerisinde yoksa(yani ürün sepette değilse) { cartCookie = string.Join('|', cartCookie, id.ToString()); // çerezin sonuna ürün numarasını (ProductID) ekliyoruz } } // Çeresin güncel halinide basket_items anahtar değeri ile Response.Cookies koleksiyonuna ekliyoruz Response.Cookies.Append("basket_items", cartCookie); } // Önerileri ve güncel sepet içeriğini tutan model nesnesini örnekliyoruz // İlerleyen aşamalarda Recommendations ile belirtilen öneriler kısmı da doldurulacak var model = new HomeCartViewModel { Cart = new Cart { Items = Enumerable.Empty <CartItem>() }, Recommendations = new List <EnrichedRecommendation>() }; // Çerez içeriğini ele aldığımız kısım if (cartCookie.Length > 0) { /* * Çerez listesini pipe işaretine göre böldükten sonra * Her bir ID'yi ve bundan yararlanarak bulacağımız ürün adını * CartItem nesnelerini örneklemek için kullanıyoruz * dolayısıyla Cart modelindeki Items koleksiyonunu çerezdeki ürün bilgileri ile doldurmuş olduk */ model.Cart.Items = cartCookie.Split('|').Select(item => new CartItem { ProductID = int.Parse(item), ProductName = _db.Products.Find(int.Parse(item)).ProductName }); } /* * Şimdi eğitilmiş modelimizi devreye almaktayız. * uk-model.zip'i kullanıyoruz. TrainModels bizim için gerekli model eğitimlerini * tamamlayıp ülkelere göre ayrı zip dosyalarının oluşturulmasını sağlamıştı. */ if (System.IO.File.Exists(GetDataSetPath("uk-model.zip"))) // UK Model eğitilmişse { var mlContext = new MLContext(); // MLContext nesnesi ITransformer modelUK; // uk-model.zip dosyasını kullanarak tahminleme motoru için gerekli model nesnesini yüklüyoruz using (var stream = new FileStream( path: GetDataSetPath("uk-model.zip"), mode: FileMode.Open, access: FileAccess.Read, share: FileShare.Read)) { modelUK = mlContext.Model.Load(stream, out DataViewSchema schema); } // Burası önemli! Tahminleme motorunu aktifleştiriyoruz var predictionEngine = mlContext.Model.CreatePredictionEngine <ProductRelation, Recommendation>(modelUK); // Şimdi var olan ürün listesini ele alalım var products = _db.Products.ToArray(); /* * Sepete eklenen her ürün için tahmin motorunu kullanarak öneriler alınacak. * Bu öneriler Modelimizdeki Recommendations isimli liste üzerinde değerlendiriliyor. * Ekleme sırasında yapılan skorlamaya göre en olası 3 ürün Recommendations listesinde bırakılıyor. */ foreach (var item in model.Cart.Items) // Çerezlerden yüklenen ürün listesindeki herbir öğeyi al { /* * Ürünlerdeki ProductID değerini RelatedProductID olarak alıp çerezden gelen listedeki ProductID ile * ilişkilendirip tahminleme motorundan bir tahminleme yapmasını istiyoruz. * Bu ilişki skorlara göre tersten sıralanıyor ve ilk üçü alınıyor. Yani en olası üçlü. */ var topThree = products .Select(product => predictionEngine.Predict( new ProductRelation { ProductID = (uint)item.ProductID, RelatedProductID = (uint)product.ProductID }) ) .OrderByDescending(x => x.Score) .Take(3) .ToArray(); /* * Öneriler id ve skor duran standart output nesnesine düşer. * Ürün bilgisini de buraya katmak istediğimizden * Recommendation sınıfından türeyen EnrichedRecommendation isimli bir sınıf daha var. * Herbir ürün için bu öneriler oluşur ama... */ model.Recommendations.AddRange(topThree .Select(rec => new EnrichedRecommendation { RelatedProductID = rec.RelatedProductID, Score = rec.Score, ProductName = _db.Products.Find((int)rec.RelatedProductID).ProductName })); } // ...ama tüm önerilerden en iyi üçü gereklidir. O nedenle son listeden tekrar top 3 yapılmış durumda model.Recommendations = model.Recommendations .OrderByDescending(rec => rec.Score) .Take(3) .ToList(); } return(View(model)); }