Beispiel #1
0
        public ActionResult Select()
        {
            var userRowKey              = (Membership.GetUser().ProviderUserKey as string);
            var companySubscription     = new CompanySubscriptionRepository().GetAll().Where(c => c.CompanyRowKey == userRowKey).SingleOrDefault();
            var subscriptionProductList = new SubscriptionProductRepository().GetAll();

            if (companySubscription != null)
            {
                if (!(companySubscription.StartDateTime.AddYears(1) >= DateTime.UtcNow))
                {
                    companySubscription = null;//subscription is expired so make null
                }
            }

            if (companySubscription != null)
            {
                var CurrentSubscriptionDescription    = string.Empty;
                var currentCompanySubscriptionProduct = subscriptionProductList.Where(s => s.ID == companySubscription.ProductID).Single();

                //subscription is valid
                ViewBag.CurrentSubscriptionDescription = currentCompanySubscriptionProduct.Name;
                ViewBag.UpgradeSubscription            = companySubscription.RowKey;

                return(MenuView(subscriptionProductList.Where(product => (product.Level > currentCompanySubscriptionProduct.Level)).ToArray(), "MY PROFILE", "SubMenuMyProfile", "None"));
            }
            else
            {
                //subscription is expired or does not exist
                ViewBag.CurrentSubscriptionDescription = "Bronze Subscription (Free)";
                ViewBag.UpgradeSubscription            = "none";

                return(MenuView(subscriptionProductList.ToArray(), "MY PROFILE", "SubMenuMyProfile", "None"));
            }
        }
Beispiel #2
0
        private void ProcessUpgrade(string transactionID)
        {
            var transaction = new TransactionRepository().GetTransactionsByTransactionID(transactionID).Where(t => t.Description.ToLower().Trim() == Status_Submit.ToLower().Trim()).SingleOrDefault();

            if (transaction == null)
            {
                throw new Exception("ProcessUpgrade() => Unable to find transaction: " + transactionID);
            }

            var product = new SubscriptionProductRepository().GetAll().Where(p => p.ID.ToLower().Trim() == transaction.ProductID.ToLower().Trim()).SingleOrDefault();

            if (product == null)
            {
                throw new Exception("ProcessUpgrade() => Unable to find product: " + transaction.ProductID);
            }

            var company = new CompanyRepository().GetByRowKey(transaction.CompanyID);

            string chamber1Rowkey = null;
            string chamber2Rowkey = null;
            string chamber3Rowkey = null;
            string chamber4Rowkey = null;

            if (company.ChamberID != null)
            {
                var chamber1 = new CompanyRepository().GetByRowKey(company.ChamberID);

                if (chamber1.ChamberID != null)
                {
                    var chamber2 = new CompanyRepository().GetByRowKey(chamber1.ChamberID);
                    chamber1Rowkey = chamber1.RowKey;

                    if (chamber2.ChamberID != null)
                    {
                        var chamber3 = new CompanyRepository().GetByRowKey(chamber2.ChamberID);
                        chamber2Rowkey = chamber2.RowKey;

                        if (chamber3 != null)
                        {
                            var chamber4 = new CompanyRepository().GetByRowKey(chamber3.ChamberID);
                            chamber3Rowkey = chamber3.RowKey;

                            if (chamber4 != null)
                            {
                                chamber4Rowkey = chamber4.RowKey;
                            }
                        }
                    }
                }
            }

            var companySubscription = new CompanySubscriptionRepository().GetAll().Where(c => c.CompanyRowKey == company.RowKey).SingleOrDefault();

            if (companySubscription != null)
            {
                new CompanySubscriptionRepository().Delete(companySubscription);
            }

            new CompanySubscriptionRepository().Save(new Models.CompanySubscriptionModel(product.ID, chamber1Rowkey, chamber2Rowkey, chamber3Rowkey, chamber4Rowkey, transactionID, company.RowKey));
        }
Beispiel #3
0
        public ActionResult Purchase(string ProductID, string UpgradeProductID)//TODO: add validation of upgradeproductid for current company - for security reasons
        {
            if (ProductID != null && UpgradeProductID != null)
            {
                var userRowKey = (Membership.GetUser().ProviderUserKey as string);
                var company    = new CompanyRepository().GetByRowKey(userRowKey);
                if (company == null)
                {
                    return(RedirectToAction("UpdateDetailsRequest"));//company details do not exist
                }

                var selectedSubscriptionProduct = new SubscriptionProductRepository().GetAll().Where(product => product.ID == ProductID).SingleOrDefault();
                if (selectedSubscriptionProduct == null)
                {
                    return(RedirectToAction("Select"));//selected productid is invalid
                }

                CompanySubscriptionModel existingSubscription = null;
                if (UpgradeProductID != "none")
                {
                    existingSubscription = new CompanySubscriptionRepository().GetByRowKey(UpgradeProductID);
                }

                var purchaseViewModel = new PurchaseViewModel {
                    AccountsEmail = company.AccountsEmail, Name = company.Name, VatNumber = company.VatNumber, SelectedProduct = selectedSubscriptionProduct
                };

                if (existingSubscription == null)
                {
                    ViewBag.IsProrata           = false;
                    ViewBag.ProrataDiscount     = "ZAR 0.00";
                    purchaseViewModel.AmountDue = selectedSubscriptionProduct.Price;
                }
                else
                {
                    //calculate prorata discount amount

                    var    subscriptionDaysRemaining = (existingSubscription.StartDateTime.AddYears(1).Subtract(DateTime.UtcNow)).Days;
                    double subscriptionCostPerDay    = new SubscriptionProductRepository().GetAll().Where(s => s.ID == existingSubscription.ProductID).Single().Price / 366;
                    double amountRemaining           = subscriptionDaysRemaining * subscriptionCostPerDay;

                    CultureInfo cultureInfo = new CultureInfo("en-US");
                    cultureInfo.NumberFormat.CurrencySymbol = string.Empty;
                    Thread.CurrentThread.CurrentCulture     = cultureInfo;

                    string discountRounded = String.Format("{0:C}", Convert.ToInt32(amountRemaining / 100));

                    ViewBag.IsProrata       = true;
                    ViewBag.ProrataDiscount = "ZAR " + discountRounded;
                    double amountDue = Convert.ToDouble(selectedSubscriptionProduct.Price) / 100 - Convert.ToDouble(discountRounded);
                    purchaseViewModel.AmountDue = Convert.ToInt32(amountDue * 100);
                }

                return(MenuView(purchaseViewModel, "FIND A PRODUCT", "SubMenuFindAProduct", string.Empty));
            }
            else
            {//no product selected or upgrade product is null (should be 'none')
                return(RedirectToAction("Select"));
            }
        }
Beispiel #4
0
        public PartialViewResult GetSearchResultsAsPartialView(string country = "", int page = 1, int productsPerPage = 25, string categoryID = "#00000000-0000-0000-0000-000000000000", string searchText = "")
        {
            var companySubscriptionArray = CompanySubscriptionHelper.GetAllCompanySubscriptionsFromCache().ToArray();
            var countryArray             = new CountryRepository().GetAll().ToArray();
            var subscriptionProductArray = new SubscriptionProductRepository().GetAll().ToArray();
            var categoryArray            = CategoryHelper.GetAllCategoriesFromCache().ToArray();
            var productArray             = ProductHelper.GetAllProductsFromCache().ToArray();
            var companyArray             = CompanyHelper.GetAllCompaniesFromCache().Where(c => c.Country != null).ToArray();

            CategoryModel parentCategory  = null;
            var           cleanCategoryID = categoryID.Replace("#", string.Empty);

            //get parent category of sub categories
            if ((categoryID != null))
            {
                parentCategory = (from category in categoryArray
                                  where category.RowKey.Equals(cleanCategoryID)
                                  select category).SingleOrDefault();//will return null for all cateogries
            }

            //check if root category was selected
            if (parentCategory == null)
            {
                parentCategory = CategoryHelper.AllCategories;
            }
            var childCategoryArray = new List <CategoryModel>().ToArray();

            if (parentCategory != CategoryHelper.AllCategories)
            {
                childCategoryArray = (from child in categoryArray
                                      where child.ParentID == cleanCategoryID
                                      select child).ToArray();
            }
            else
            {
                childCategoryArray = (from child in categoryArray
                                      where child.ParentID == "0"
                                      select child).ToArray();
            }
            var categoryAndDescendantsList = CategoryHelper.GetAllDescendantsFlattened(cleanCategoryID, categoryArray, childCategoryArray).ToList();

            var results = new List <CompanyModel>();

            //search by searchtext
            if (searchText != string.Empty)
            {
                var companyFiltered_SearchText =
                    companyArray.Where(c => (
                                           c.Name.ToLower().Contains(searchText) ||
                                           c.ProductsOrServices.ToLower().Contains(searchText))
                                       ).Distinct().ToArray();

                if (country == string.Empty)
                {
                    results.AddRange(companyFiltered_SearchText.Distinct());
                }
                else
                {
                    results.AddRange(companyFiltered_SearchText.Where(c => c.Country.ToLower() == country.ToLower()).Distinct());
                }
            }
            else
            {//ignore searchtext
                if (country == string.Empty || country.ToLower() == "all countries")
                {
                    results.AddRange(companyArray);
                }
                else
                {
                    results.AddRange(companyArray.Where(c => c.Country.ToLower() == country.ToLower()));
                }
            }

            var resultsFiltered = new List <CompanyModel>();

            //filter results by category if specified
            if (parentCategory != CategoryHelper.AllCategories)
            {
                categoryAndDescendantsList.Add(parentCategory);
                resultsFiltered = results.Where(r =>
                                                ProductHelper.DoesHaveProductsInCategory(
                                                    productArray.Where(p => p.CompanyID == r.RowKey).ToArray(),
                                                    categoryAndDescendantsList.ToArray(),
                                                    companyArray,
                                                    r.RowKey
                                                    ))
                                  .Distinct().ToList();
            }
            else
            {
                resultsFiltered = results;
            }

            var companyresultArray = resultsFiltered.Select(c => new CompanyViewModel(c, companySubscriptionArray, countryArray, subscriptionProductArray)).ToArray();


            int totalPages = 1;

            if (companyArray.Count() != 0)
            {
                totalPages = companyresultArray.Count() / productsPerPage;
            }

            var pagedResultArray = companyresultArray.OrderBy(c => c.CompanyData.Name).Skip(productsPerPage * (page - 1)).Take(productsPerPage).ToArray();

            return(PartialView(new CompanySearchResultViewModel(pagedResultArray, productsPerPage, page, parentCategory, totalPages, companyresultArray.Count())));
        }
Beispiel #5
0
        public JsonResult Edit(ProductViewModel product)
        {
            try
            {
                var userRowKey = (Membership.GetUser().ProviderUserKey as string);

                //ensure that user is only able to save products under there own company if not a webmaster
                if (!User.IsInRole("Webmaster"))
                {
                    if (product.ProductData.CompanyID != userRowKey)//CompanyRowKey <==> UserRowkey
                    {
                        return(Json(new { status = "error", message = "Product Save Failed - Security Violation Occurred. Your IP Address has been logged" }));
                    }
                }

                if ((product.photo != null) || (product.ProductData.PhotoUrl != null))//save only if photo allready exists or has been supplied
                {
                    if (product.photo != null)
                    {
                        BinaryReader b          = new BinaryReader(product.photo.InputStream);
                        byte[]       binData_IN = b.ReadBytes(product.photo.ContentLength);

                        MemoryStream mstream_input = new MemoryStream(binData_IN);

                        MemoryStream mstream_output_120 = new MemoryStream();
                        MemoryStream mstream_output_160 = new MemoryStream();
                        MemoryStream mstream_output_240 = new MemoryStream();

                        var settings120 = new ResizeSettings("maxwidth=120&maxheight=120&format=png");
                        ImageBuilder.Current.Build(mstream_input, mstream_output_120, settings120, false);
                        byte[] binData_OUT_120 = mstream_output_120.ToArray();

                        var settings160 = new ResizeSettings("maxwidth=160&maxheight=160&format=png");
                        mstream_input.Seek(0, SeekOrigin.Begin);
                        ImageBuilder.Current.Build(mstream_input, mstream_output_160, settings160, false);
                        byte[] binData_OUT_160 = mstream_output_160.ToArray();

                        var settings240 = new ResizeSettings("maxwidth=240&maxheight=240&format=png");
                        mstream_input.Seek(0, SeekOrigin.Begin);
                        ImageBuilder.Current.Build(mstream_input, mstream_output_240, settings240);
                        byte[] binData_OUT_240 = mstream_output_240.ToArray();

                        var             fileName  = Guid.NewGuid().ToString();
                        PhotoRepository photoRepo = new PhotoRepository();

                        product.ProductData.PhotoUrl = photoRepo.SavePhoto(binData_OUT_120, fileName + "120.png");
                        photoRepo.SavePhoto(binData_OUT_160, fileName + "160.png");
                        photoRepo.SavePhoto(binData_OUT_240, fileName + "240.png");
                    }

                    if (product.ProductData.CategoryID == null)
                    {
                        product.ProductData.CategoryID = Settings.Default.DefaultCategoryRowkey;
                    }

                    string featuredProductMessage = string.Empty;
                    if (product.IsFeaturedProduct)
                    {
                        var companySubscription = new CompanySubscriptionRepository().GetAll().Where(c => c.CompanyRowKey == userRowKey).SingleOrDefault();

                        if (companySubscription != null)
                        {
                            var subscription = new SubscriptionProductRepository().GetAll().Where(s => s.ID == companySubscription.ProductID).SingleOrDefault();

                            if (subscription != null)
                            {
                                //get featured product count for this company
                                var count = new ProductRepository().GetByCompanyRowKey(userRowKey).Where(p => p.FeaturedProductWeight >= 1).Count();

                                if (count >= subscription.MaxFeatured)
                                {
                                    product.ProductData.FeaturedProductWeight = 0;//max featured products limit exceeded
                                    featuredProductMessage = "Featured Products Limit Has Been Reached - Please Upgrade To Add More. Maximum allowed for your subscription is " + subscription.MaxFeatured;
                                }
                                else
                                {
                                    product.ProductData.FeaturedProductWeight = subscription.Level;
                                }
                            }
                        }
                    }
                    else
                    {
                        product.ProductData.FeaturedProductWeight = 0;
                    }

                    //swap out correct placeholder image
                    product.ProductData.PhotoUrl.ToLower().Trim().Replace(Settings.Default.NoImage240Url.ToLower().Trim(), Settings.Default.NoImage120Url.ToLower().Trim());


                    new ProductRepository().Save(product.ProductData);
                    //TODO: Delete old photo on save

                    return(Json(new { status = "success", message = "Product Saved Successfully", photourl = product.ProductData.PhotoUrl }, "text/html"));
                }
                else
                {
                    return(Json(new { status = "error", message = "Product Save Failed, Please Include A Photo." }, "text/html"));
                }
            }
            catch (ImageCorruptedException)
            {
                return(Json(new { status = "error", message = "Product Save Failed, error reading image file. Please try another image." }, "text/html"));
            }
            catch
            {
                return(Json(new { status = "error", message = "Product Save Failed, Please try again later." }, "text/html"));
            }
        }
Beispiel #6
0
        public PartialViewResult GetSearchResultsAsPartialView(string country, int page = 1, int productsPerPage = 25, string categoryID = "#00000000-0000-0000-0000-000000000000", string searchText = "")
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            var allCategories           = CategoryHelper.GetAllCategoriesFromCache().ToArray();
            var allCompanies            = CompanyHelper.GetAllCompaniesFromCache().ToArray();
            var allSubscriptions        = CompanySubscriptionHelper.GetAllCompanySubscriptionsFromCache().ToArray();
            var allCountries            = new CountryRepository().GetAll().ToArray();
            var allSubscriptionProducts = new SubscriptionProductRepository().GetAll().ToArray();

            CategoryModel parentCategory  = null;
            var           cleanCategoryID = categoryID.Replace("#", string.Empty);

            //get parent category of sub categories
            if ((categoryID != null))
            {
                parentCategory = (from category in allCategories
                                  where category.RowKey.Equals(cleanCategoryID)
                                  select category).SingleOrDefault();//will return null for all cateogries
            }

            //check if root category was selected
            if (parentCategory == null)
            {
                parentCategory = CategoryHelper.AllCategories;
            }

            //var childCategoryArray = new CategoryModel[0];
            var childCategoryArray = new List <CategoryModel>().ToArray();

            if (parentCategory != CategoryHelper.AllCategories)
            {
                childCategoryArray = (from child in allCategories
                                      where child.ParentID == cleanCategoryID
                                      select child).ToArray();
            }
            else
            {
                childCategoryArray = (from child in allCategories
                                      where child.ParentID == "0"
                                      select child).ToArray();
            }

            var categoryAndDescendantsList = CategoryHelper.GetAllDescendantsFlattened(cleanCategoryID, allCategories, childCategoryArray).ToList();

            categoryAndDescendantsList.Add(parentCategory);
            var categoryAndDescendantsArray = categoryAndDescendantsList.ToArray();

            int resultsTotal;
            int productsDatabaseTotal;
            var results = ProductHelper.ProductSearch(categoryAndDescendantsArray, searchText, country, page, productsPerPage, allCompanies.ToArray(), null, out resultsTotal, out productsDatabaseTotal);
            List <ProductSearchResultModel> productSearchResults = new List <ProductSearchResultModel>();

            results.ToList().ForEach(productModel =>//TODO: Search on country criteria TODO: Cache company details for this loop and avoid getting all at start
            {
                var company = allCompanies.Where(f => f.RowKey == (productModel.CompanyID)).SingleOrDefault();

                if (company != null)//if company details have not been supplied - exclude products from the search results
                {
                    //get countryname and flagurl
                    string countryName = "Unknown";
                    string countryCode = "00";

                    if (company.Country != null)
                    {
                        var countryModel = allCountries.Where(c => c.Name.ToLower().Trim() == company.Country.ToLower().Trim()).SingleOrDefault();
                        if (countryModel != null)
                        {
                            countryCode = countryModel.Iso2DigitCode; countryName = countryModel.Name;
                        }                                                                                                    //country found so set name and code
                    }

                    //get subscription status
                    int companyLevel        = 0;
                    var companySubscription = allSubscriptions.Where(s => s.CompanyRowKey == company.RowKey).SingleOrDefault();
                    if (companySubscription != null)
                    {
                        if (!(companySubscription.StartDateTime.AddYears(1) >= DateTime.UtcNow))
                        {
                            companySubscription = null;//subscription is expired so make null
                        }
                        else
                        {
                            var companySubscriptionProduct = allSubscriptionProducts.Where(sp => sp.ID == companySubscription.ProductID).SingleOrDefault();
                            if (companySubscriptionProduct != null)
                            {
                                companyLevel = companySubscriptionProduct.Level;
                            }
                        }
                    }

                    var isVerified         = company.IsVerified;
                    var isChamberCertified = company.IsChamberCertified;
                    var isGreenCertified   = company.IsGreenCertified;

                    productSearchResults.Add(new ProductSearchResultModel
                    {
                        CompanyName              = company.Name,
                        Product                  = productModel,
                        BusinessType             = company.BusinessType,
                        IsChamberCertified       = isChamberCertified,
                        IsGreenCertified         = isGreenCertified,
                        IsVerified               = isVerified,
                        Country                  = countryName,
                        FlagUrl                  = Settings.Default.FlagUrlPath.ToLower().Trim().Replace("%countrycode%", countryCode).ToLower(),
                        CompanySubscriptionLevel = companyLevel,
                        CompanyID                = company.RowKey
                    });
                }
            });

            if (productSearchResults.Count() == 0)//set current page to zero if there are no results
            {
                page = 0;
            }

            var totalPages            = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(resultsTotal) / Convert.ToDouble(productsPerPage)));
            var searchResultViewModel = new ProductSearchResultViewModel(productSearchResults.ToArray(), productsPerPage, page, parentCategory, totalPages, resultsTotal);

            stopWatch.Stop();

            if (Settings.Default.IsDiagnosticsModeEnabled.ToLower() == "true")
            {
                searchResultViewModel.SearchDiagnosticInformation = "[" + DateTime.UtcNow.ToLongTimeString() + " UTC Searched " + productsDatabaseTotal.ToString() + " Products in " + stopWatch.ElapsedMilliseconds + "ms]";
            }

            return(PartialView(searchResultViewModel));
        }
Beispiel #7
0
        public PartialViewResult GetEditFormAsPartialView(string id)
        {
            var userRowKey          = (Membership.GetUser().ProviderUserKey as string);
            var companySubscription = new CompanySubscriptionRepository().GetAll().Where(c => c.CompanyRowKey == userRowKey).SingleOrDefault();

            bool isSilverGoldPlatinum    = false;
            int  maxFeaturedProductCount = 0;

            if (companySubscription != null)
            {
                isSilverGoldPlatinum = true;
                var subscription = new SubscriptionProductRepository().GetAll().Where(p => p.ID == companySubscription.ProductID).SingleOrDefault();
                maxFeaturedProductCount = subscription.MaxFeatured;
            }

            HttpContext.Response.Expires = -1;
            HttpContext.Response.Cache.SetNoServerCaching();
            Response.Cache.SetAllowResponseInBrowserHistory(false);
            Response.CacheControl = "no-cache";
            Response.Cache.SetNoStore();

            var product = new ProductModel();

            if (id == null)
            {
                product = new ProductModel("My New Product", "Please enter a description...", @"http://matchmaker.blob.core.windows.net/image/NoImage240.jpg", (userRowKey as string));//CompanyRowKey <==> UserRowkey
            }
            else
            {
                var cleanid = id.Replace("#", string.Empty);//cleanup id string
                product = new ProductRepository().GetByRowKey(cleanid);
            }

            if (product != null)
            {
                if (product.FeaturedProductWeight == null)
                {
                    product.FeaturedProductWeight = 0;
                }

                string categoryName = string.Empty;

                if (product.CategoryID != null)
                {
                    categoryName = new CategoryRepository().GetByRowKey(product.CategoryID).Name;
                }

                var productViewModel = new ProductViewModel {
                    ProductData = product, CategoryName = categoryName, ShowFeaturedProductOption = isSilverGoldPlatinum, MaxFeaturedProductCount = maxFeaturedProductCount
                };

                if (productViewModel.ProductData.FeaturedProductWeight >= 1)
                {
                    productViewModel.IsFeaturedProduct = true;
                }
                else
                {
                    productViewModel.IsFeaturedProduct = false;
                }

                return(PartialView(productViewModel));
            }
            else
            {
                var blankProduct     = new ProductModel("My New Product", "Please enter a description", @"http://matchmaker.blob.core.windows.net/image/NoImage240.jpg", userRowKey);//CompanyRowKey <==> UserRowkey
                var productViewModel = new ProductViewModel {
                    ProductData = blankProduct, CategoryName = string.Empty, ShowFeaturedProductOption = isSilverGoldPlatinum, MaxFeaturedProductCount = maxFeaturedProductCount
                };
                return(PartialView(productViewModel));
            }
        }