private static void SyncBrokers(HttpClient httpClient, IRepository consoleRepository)
		{
			DatabaseInit._LogHandler.WriteLog("SyncBrokers()", LogSeverity.Information, LogCategory.DataAccess);

			var response = httpClient.GetAsync("rest/api/broker").Result;

			if (response.IsSuccessStatusCode)
			{
				var serviceBrokers = response.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.Broker>>().Result;

				foreach (var serviceBroker in serviceBrokers)
				{
					if (!consoleRepository.Query<Broker>().Any(cb => cb.BrokerSequenceId == serviceBroker.Id))
					{
						consoleRepository.Add(new Broker
						{
							BrokerSequenceId = serviceBroker.Id,
							Name = serviceBroker.Name,
							Code = serviceBroker.Code,
							Psu = serviceBroker.Psu,
							GroupCode = serviceBroker.GrpCd
						});
					}
					else
					{
						var consoleBroker = consoleRepository.Query<Broker>()
						                                     .FirstOrDefault(cb => cb.BrokerSequenceId == serviceBroker.Id);

						if (consoleBroker != null)
						{
							consoleBroker.Code = serviceBroker.Code;
							consoleBroker.GroupCode = serviceBroker.GrpCd;
							consoleBroker.Name = serviceBroker.Name;
							consoleBroker.Psu = serviceBroker.Psu;

							consoleRepository.Attach(consoleBroker);
						}
					}
				}
			}
			else
			{
				DatabaseInit._LogHandler.WriteLog("Get rest/api/broker failed", LogSeverity.Warning, LogCategory.DataAccess);
			}
		}
Exemplo n.º 2
0
        public HomeModule(IRepository repository)
        {
            Get["/"] = p =>
                {
                    var feeds = repository.Query(new GetFeedsQuery()).ToArray();

                    return Negotiate
                        .WithModel(feeds)
                        .WithView("home.cshtml");
                };
        }
        private static void UpdateSipAddresses(IRepository consoleRepository)
        {
            Dictionary<String, String> userSipAddresses = DatabaseInit.GetUserSipAddresses();
            foreach (User u in consoleRepository.Query<User>(u => u.IsActive))
	        {
                String shortName = WebSiteModuleManager.ExtractUserName(u.DomainLogon);
                if (userSipAddresses.ContainsKey(shortName))
                {
                    String sipAddress = userSipAddresses[shortName];
                    if (String.IsNullOrEmpty(u.SipAddress))
                    {
                        if (!String.IsNullOrEmpty(sipAddress))
                            u.SipAddress = sipAddress;
                    }
                    else
                    {
                        if (!u.SipAddress.Equals(sipAddress, StringComparison.InvariantCultureIgnoreCase))
                            u.SipAddress = sipAddress;
                    }
                }
	        }            
        }
 private static void UpdateUserPictures(IRepository consoleRepository)
 {
     Dictionary<String, byte[]> userPictures = DatabaseInit.GetUserPictures();
     foreach (User u in consoleRepository.Query<User>(u => u.IsActive))
     {
         String shortName = WebSiteModuleManager.ExtractUserName(u.DomainLogon);
         if (userPictures.ContainsKey(shortName))
         {
             byte[] userPic = userPictures[shortName];
             if ((userPic != null) && (userPic.Length > 0))
             {
                 if ((u.UserThumbnail == null) || (u.UserThumbnail.Length <= 0))
                 {
                     u.UserThumbnail = userPic;
                 }
                 else
                 {
                     if (!u.UserThumbnail.Equals(userPic))
                         u.UserThumbnail = userPic;
                 }
             }
         }
     }  
 }
		private static void SyncCOBs(HttpClient httpClient, IRepository consoleRepository)
		{
			DatabaseInit._LogHandler.WriteLog("SyncCOBs()", LogSeverity.Information, LogCategory.DataAccess);

			var response = httpClient.GetAsync("rest/api/cob").Result;

			if (response.IsSuccessStatusCode)
			{
				var serviceCOBs = response.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.COB>>().Result;

				foreach (var serviceCOB in serviceCOBs.Where(sc => !consoleRepository.Query<COB>()
				                                                                     .Any(cc => cc.Id == sc.Code)))
				{
					consoleRepository.Add(new COB
					{
						Id = serviceCOB.Code,
						Narrative = serviceCOB.Name
					});
				}
			}
			else
			{
				DatabaseInit._LogHandler.WriteLog("Get rest/api/cob failed", LogSeverity.Warning, LogCategory.DataAccess);
			}
		}
Exemplo n.º 6
0
 public static WorkflowActivity GetByUniqueId(this IRepository <WorkflowActivity> repository, Guid workflowActivityId, bool optimization = true)
 {
     return(repository.Query(x => x.UniqueId == workflowActivityId, optimization: optimization).Include(x => x.WorkflowAuthorizations).SelectAsQueryable().SingleOrDefault());
 }
Exemplo n.º 7
0
 public IQueryable <Cart> Query()
 {
     return(_cartRepository.Query());
 }
Exemplo n.º 8
0
 public UrlSlug Get(long entityId, long entityTypeId)
 {
     return(_urlSlugRepository.Query().FirstOrDefault(x => x.EntityId == entityId && x.EntityTypeId == entityTypeId));
 }
Exemplo n.º 9
0
        public async Task CreateOrder(User user, Address billingAddress, Address shippingAddress)
        {
            var cart = _cartRepository
                       .Query()
                       .Include(c => c.Items).ThenInclude(x => x.Product)
                       .Where(x => x.UserId == user.Id && x.IsActive).FirstOrDefault();

            if (cart == null)
            {
                throw new ApplicationException($"Cart of user {user.Id} can no be found");
            }

            decimal discount = 0;

            if (!string.IsNullOrWhiteSpace(cart.CouponCode))
            {
                var couponValidationResult = await _couponService.Validate(cart.CouponCode);

                if (couponValidationResult.Succeeded)
                {
                    discount = couponValidationResult.DiscountAmount;
                    _couponService.AddCouponUsage(user.Id, couponValidationResult.CouponId);
                }
                else
                {
                    throw new ApplicationException($"Unable to apply coupon {cart.CouponCode}. {couponValidationResult.ErrorMessage}");
                }
            }

            var orderBillingAddress = new OrderAddress()
            {
                AddressLine1      = billingAddress.AddressLine1,
                ContactName       = billingAddress.ContactName,
                CountryId         = billingAddress.CountryId,
                StateOrProvinceId = billingAddress.StateOrProvinceId,
                DistrictId        = billingAddress.DistrictId,
                Phone             = billingAddress.Phone
            };

            var orderShippingAddress = new OrderAddress()
            {
                AddressLine1      = shippingAddress.AddressLine1,
                ContactName       = shippingAddress.ContactName,
                CountryId         = shippingAddress.CountryId,
                StateOrProvinceId = shippingAddress.StateOrProvinceId,
                DistrictId        = shippingAddress.DistrictId,
                Phone             = shippingAddress.Phone
            };

            var order = new Order
            {
                CreatedOn       = DateTimeOffset.Now,
                CreatedById     = user.Id,
                BillingAddress  = orderBillingAddress,
                ShippingAddress = orderShippingAddress
            };

            foreach (var cartItem in cart.Items)
            {
                var orderItem = new OrderItem
                {
                    Product      = cartItem.Product,
                    ProductPrice = cartItem.Product.Price,
                    Quantity     = cartItem.Quantity
                };
                order.AddOrderItem(orderItem);
            }

            order.CouponCode           = cart.CouponCode;
            order.CouponRuleName       = cart.CouponRuleName;
            order.Discount             = discount;
            order.SubTotal             = order.OrderItems.Sum(x => x.ProductPrice * x.Quantity);
            order.SubTotalWithDiscount = order.SubTotal - discount;
            _orderRepository.Add(order);

            cart.IsActive = false;

            var vendorIds = cart.Items.Where(x => x.Product.VendorId.HasValue).Select(x => x.Product.VendorId.Value).Distinct();

            foreach (var vendorId in vendorIds)
            {
                var subOrder = new Order
                {
                    CreatedOn       = DateTimeOffset.Now,
                    CreatedById     = user.Id,
                    BillingAddress  = orderBillingAddress,
                    ShippingAddress = orderShippingAddress,
                    VendorId        = vendorId,
                    Parent          = order
                };

                foreach (var cartItem in cart.Items.Where(x => x.Product.VendorId == vendorId))
                {
                    var orderItem = new OrderItem
                    {
                        Product      = cartItem.Product,
                        ProductPrice = cartItem.Product.Price,
                        Quantity     = cartItem.Quantity
                    };

                    subOrder.AddOrderItem(orderItem);
                }

                subOrder.SubTotal = subOrder.OrderItems.Sum(x => x.ProductPrice * x.Quantity);
                _orderRepository.Add(subOrder);
            }

            _orderRepository.SaveChange();
        }
Exemplo n.º 10
0
        public int FindPreDefinedDay(Equipments model)
        {
            int equipmentType = (int)model.Type;

            return(_equipmentTypesRepository.Query(x => x.Id == equipmentType).Single().PreDefinedDay);
        }
        public List <Product> GetProductsByGroupName(string groupName = "")
        {
            var products = productRepository.Query().Include(p => p.Group).Where(p => p.Group.Name.Contains(groupName)).ToList();

            return(products);
        }
Exemplo n.º 12
0
 public virtual IQueryable <T> Query(Func <T, bool> criteria)
 {
     return(_BaseRepo.Query(criteria));
 }
Exemplo n.º 13
0
        public async Task <Media> SaveMediaAsync(Stream mediaBinaryStream, string fileName, string mimeType = null)
        {
            var   hsMd5 = string.Empty;
            var   size  = 0;
            Media media = null;

            var filePath = Path.Combine(GlobalConfiguration.WebRootPath, MediaRootFoler, fileName);

            using (var output = new FileStream(filePath, FileMode.Create))
            {
                //if (!File.Exists(filePath))

                await mediaBinaryStream.CopyToAsync(output);

                var bytes = new byte[mediaBinaryStream.Length];
                mediaBinaryStream.Read(bytes, 0, bytes.Length);
                hsMd5 = Md5Helper.Encrypt(bytes);
                size  = bytes.Length;
            }

            if (!string.IsNullOrWhiteSpace(hsMd5))
            {
                media = await _mediaRepository.Query(c => c.Md5 == hsMd5 || c.FileName == fileName).FirstOrDefaultAsync();
            }

            if (media == null)
            {
                media = new Media()
                {
                    MediaType = MediaType.File,
                    FileName  = fileName,
                    FileSize  = size,
                    Hash      = "",
                    Url       = $"{host.Trim('/')}/{MediaRootFoler}/{fileName}",
                    Path      = $"/{MediaRootFoler}/{fileName}",
                    Host      = host,
                    Md5       = hsMd5
                };
                if (!string.IsNullOrWhiteSpace(mimeType))
                {
                    mimeType = mimeType.Trim().ToLower();
                    if (mimeType.StartsWith("video"))
                    {
                        media.MediaType = MediaType.Video;
                    }
                    else if (mimeType.StartsWith("image"))
                    {
                        media.MediaType = MediaType.Image;
                    }
                    else
                    {
                        media.MediaType = MediaType.File;
                    }
                }
                _mediaRepository.Add(media);
            }
            else
            {
                media.Url  = $"{host.Trim('/')}/{MediaRootFoler}/{fileName}";
                media.Path = $"/{MediaRootFoler}/{fileName}";
                media.Host = host;
            }

            await _mediaRepository.SaveChangesAsync();

            return(media);
        }
Exemplo n.º 14
0
        private async Task <Cart> GetCartFrDb(long cartId)
        {
            return(await _repository.Query().Where(x => x.CartId == cartId).Include(x => x.Items).ThenInclude(x => x.Product).FirstOrDefaultAsync());

            /*Include(x => x.Items).ThenInclude(x => x.Product).FirstOrDefaultAsync();*/
        }
Exemplo n.º 15
0
 public static IQueryable <Category> GetByUniqueId(this IRepository <Category> repository, Guid uniqueId)
 {
     return(repository.Query(x => x.UniqueId == uniqueId)
            .SelectAsQueryable());
 }
Exemplo n.º 16
0
 public static IQueryable <Category> GetById(this IRepository <Category> repository, short idCategory)
 {
     return(repository.Query(x => x.EntityShortId == idCategory)
            .SelectAsQueryable());
 }
Exemplo n.º 17
0
 public static Category GetDefaultCategoryByTenantAOOId(this IRepository <Category> repository, Guid tenantAOOId, bool optimization = false)
 {
     return(repository.Query(x => x.TenantAOO.UniqueId == tenantAOOId && x.Parent == null, optimization: optimization).SelectAsQueryable().FirstOrDefault());
 }
Exemplo n.º 18
0
 public static IQueryable <Category> GetByUniqueId(this IRepository <Category> repository, Guid categoryUniqueId, bool optimization = false)
 {
     return(repository.Query(x => x.UniqueId == categoryUniqueId, optimization: optimization)
            .SelectAsQueryable());
 }
		private static void SyncUnderwriters(HttpClient httpClient, IRepository consoleRepository)
		{
			DatabaseInit._LogHandler.WriteLog("SyncUnderwriters()", LogSeverity.Information, LogCategory.DataAccess);

			var response = httpClient.GetAsync("rest/api/underwriter").Result;

			if (response.IsSuccessStatusCode)
			{
				var serviceUnderwriters = response.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.Underwriter>>().Result;

				foreach (var serviceUnderwriter in serviceUnderwriters)
				{
					if (!consoleRepository.Query<Underwriter>().Any(cu => cu.Code == serviceUnderwriter.Code))
					{
						consoleRepository.Add(new Underwriter
						{
							Code = serviceUnderwriter.Code,
							Name = serviceUnderwriter.Name
						});
					}
					else
					{
						var consoleUnderwriter = consoleRepository.Query<Underwriter>()
						                                          .FirstOrDefault(b => b.Code == serviceUnderwriter.Code);

						if (consoleUnderwriter != null)
						{
							consoleUnderwriter.Code = serviceUnderwriter.Code;
							consoleUnderwriter.Name = serviceUnderwriter.Name;

							consoleRepository.Attach(consoleUnderwriter);
						}
					}
				}
			}
			else
			{
				DatabaseInit._LogHandler.WriteLog("Get rest/api/underwriter failed", LogSeverity.Warning, LogCategory.DataAccess);
			}
		}
Exemplo n.º 20
0
 public IEnumerable <LocationDTO> GetLocations()
 {
     return(locationRepo.Query().Select(e => new LocationDTO().InjectFrom(e) as LocationDTO));
 }
 public SalesTaxGroupProduct Find(string Name)
 {
     return(_SalesTaxGroupProductRepository.Query().Get().Where(i => i.SalesTaxGroupProductName == Name).FirstOrDefault());
 }
Exemplo n.º 22
0
        // TODO separate getting product thumbnail, varation options from here
        public async Task <CartVm> GetActiveCartDetails(long customerId, long createdById)
        {
            //var carrito = DataCarrito();
            //if (carrito == null)
            //{
            //    return null;
            //}
            //else {
            //    return carrito;
            //}

            // datos del carrito se cargan aqui
            var cart = await GetActiveCart(customerId, createdById);

            if (cart == null)
            {
                return(null);
            }

            var cartVm = new CartVm(_currencyService)
            {
                Id         = cart.Id,
                CouponCode = cart.CouponCode,
                IsProductPriceIncludeTax = cart.IsProductPriceIncludeTax,
                TaxAmount      = cart.TaxAmount,
                ShippingAmount = cart.ShippingAmount,
                OrderNote      = cart.OrderNote
            };

            //tenemos que cargar aqui los datos del carrito, tenemos la ID de los productos en el Cart.Items
            // recorremos el array.
            cartVm.Items = _cartItemRepository
                           .Query()
                           .Where(x => x.CartId == cart.Id).ToList()
                           .Select(x => new CartItemVm(_currencyService)
            {
                Id        = x.Id,
                ProductId = x.ProductId,
                // ProductName = x.Product.Name,
                //ProductPrice = x.Product.Price,
                //ProductStockQuantity = x.Product.StockQuantity,
                //ProductStockTrackingIsEnabled = x.Product.StockTrackingIsEnabled,
                //IsProductAvailabeToOrder = x.Product.IsAllowToOrder && x.Product.IsPublished && !x.Product.IsDeleted,
                Quantity = x.Quantity
            }).ToList();



            //codigo origen
            //cartVm.Items = _cartItemRepository
            //    .Query()
            //    .Include(x => x.Product).ThenInclude(p => p.ThumbnailImage)
            //    .Include(x => x.Product).ThenInclude(p => p.OptionCombinations).ThenInclude(o => o.Option)
            //    .Where(x => x.CartId == cart.Id).ToList()
            //    .Select(x => new CartItemVm(_currencyService)
            //    {
            //        Id = x.Id,
            //        ProductId = x.ProductId,
            //        ProductName = x.Product.Name,
            //        ProductPrice = x.Product.Price,
            //        ProductStockQuantity = x.Product.StockQuantity,
            //        ProductStockTrackingIsEnabled = x.Product.StockTrackingIsEnabled,
            //        IsProductAvailabeToOrder = x.Product.IsAllowToOrder && x.Product.IsPublished && !x.Product.IsDeleted,
            //        ProductImage = _mediaService.GetThumbnailUrl(x.Product.ThumbnailImage),
            //        Quantity = x.Quantity,
            //        VariationOptions = CartItemVm.GetVariationOption(x.Product)
            //    }).ToList();

            cartVm.SubTotal = cartVm.Items.Sum(x => x.Quantity * x.ProductPrice);
            if (!string.IsNullOrWhiteSpace(cartVm.CouponCode))
            {
                var cartInfoForCoupon = new CartInfoForCoupon
                {
                    Items = cartVm.Items.Select(x => new CartItemForCoupon {
                        ProductId = x.ProductId, Quantity = x.Quantity
                    }).ToList()
                };
                var couponValidationResult = await _couponService.Validate(customerId, cartVm.CouponCode, cartInfoForCoupon);

                if (couponValidationResult.Succeeded)
                {
                    cartVm.Discount = couponValidationResult.DiscountAmount;
                }
                else
                {
                    cartVm.CouponValidationErrorMessage = couponValidationResult.ErrorMessage;
                }
            }

            return(cartVm);
        }
        public IActionResult Get()
        {
            var options = _productOptionRepository.Query();

            return(Json(options));
        }
Exemplo n.º 24
0
        public IActionResult Get()
        {
            var categoryList = _contactRepository.Query().Where(x => !x.IsDeleted).ToList();

            return(Json(categoryList));
        }
        public async Task <IActionResult> Get(long id)
        {
            var product = _productRepository.Query()
                          .Include(x => x.ThumbnailImage)
                          .Include(x => x.Medias).ThenInclude(m => m.Media)
                          .Include(x => x.ProductLinks).ThenInclude(p => p.LinkedProduct)
                          .Include(x => x.OptionValues).ThenInclude(o => o.Option)
                          .Include(x => x.AttributeValues).ThenInclude(a => a.Attribute).ThenInclude(g => g.Group)
                          .Include(x => x.Categories)
                          .FirstOrDefault(x => x.Id == id);

            var currentUser = await _workContext.GetCurrentUser();

            if (!User.IsInRole("admin") && product.VendorId != currentUser.VendorId)
            {
                return(new BadRequestObjectResult(new { error = "You don't have permission to manage this product" }));
            }

            var productVm = new ProductVm
            {
                Id                = product.Id,
                Name              = product.Name,
                ShortDescription  = product.ShortDescription,
                Description       = product.Description,
                Specification     = product.Specification,
                OldPrice          = product.OldPrice,
                Price             = product.Price,
                SpecialPrice      = product.SpecialPrice,
                SpecialPriceStart = product.SpecialPriceStart,
                SpecialPriceEnd   = product.SpecialPriceEnd,
                IsFeatured        = product.IsFeatured,
                IsPublished       = product.IsPublished,
                IsCallForPricing  = product.IsCallForPricing,
                IsAllowToOrder    = product.IsAllowToOrder,
                IsOutOfStock      = product.StockQuantity == 0,
                CategoryIds       = product.Categories.Select(x => x.CategoryId).ToList(),
                ThumbnailImageUrl = _mediaService.GetThumbnailUrl(product.ThumbnailImage),
                BrandId           = product.BrandId
            };

            foreach (var productMedia in product.Medias.Where(x => x.Media.MediaType == MediaType.Image))
            {
                productVm.ProductImages.Add(new ProductMediaVm
                {
                    Id       = productMedia.Id,
                    MediaUrl = _mediaService.GetThumbnailUrl(productMedia.Media)
                });
            }

            foreach (var productMedia in product.Medias.Where(x => x.Media.MediaType == MediaType.File))
            {
                productVm.ProductDocuments.Add(new ProductMediaVm
                {
                    Id       = productMedia.Id,
                    Caption  = productMedia.Media.Caption,
                    MediaUrl = _mediaService.GetMediaUrl(productMedia.Media)
                });
            }


            productVm.Options = product.OptionValues.OrderBy(x => x.SortIndex).Select(x =>
                                                                                      new ProductOptionVm
            {
                Id     = x.OptionId,
                Name   = x.Option.Name,
                Values = JsonConvert.DeserializeObject <IList <string> >(x.Value)
            }).ToList();

            foreach (var variation in product.ProductLinks.Where(x => x.LinkType == ProductLinkType.Super).Select(x => x.LinkedProduct).Where(x => !x.IsDeleted).OrderBy(x => x.Id))
            {
                productVm.Variations.Add(new ProductVariationVm
                {
                    Id                 = variation.Id,
                    Name               = variation.Name,
                    Price              = variation.Price,
                    OldPrice           = variation.OldPrice,
                    NormalizedName     = variation.NormalizedName,
                    OptionCombinations = variation.OptionCombinations.Select(x => new ProductOptionCombinationVm
                    {
                        OptionId   = x.OptionId,
                        OptionName = x.Option.Name,
                        Value      = x.Value,
                        SortIndex  = x.SortIndex
                    }).OrderBy(x => x.SortIndex).ToList()
                });
            }

            foreach (var relatedProduct in product.ProductLinks.Where(x => x.LinkType == ProductLinkType.Relation).Select(x => x.LinkedProduct).Where(x => !x.IsDeleted).OrderBy(x => x.Id))
            {
                productVm.RelatedProducts.Add(new RelatedProductVm
                {
                    Id   = relatedProduct.Id,
                    Name = relatedProduct.Name
                });
            }

            productVm.Attributes = product.AttributeValues.Select(x => new ProductAttributeVm
            {
                AttributeValueId = x.Id,
                Id        = x.AttributeId,
                Name      = x.Attribute.Name,
                GroupName = x.Attribute.Group.Name,
                Value     = x.Value
            }).ToList();

            return(Json(productVm));
        }
Exemplo n.º 26
0
 public IEnumerable <ProductResponse> GetAll()
 {
     return(_productRepository.Query().Select(ProductResponse.Expression).ToList());
 }
 public static void Main(params string[] args)
 {
     IRepository <User> repo = GetUserRepository();     // dynamically construct user repository
     var query = repo.Query()
                 .Where(user => user.Name.ToLower().Contains("jack"));
 }
Exemplo n.º 28
0
        // TODO separate getting product thumbnail, varation options from here
        public async Task <CartVm> GetActiveCartDetails(long customerId, long createdById)
        {
            var cart = await GetActiveCart(customerId, createdById);

            if (cart == null)
            {
                return(null);
            }

            var cartVm = new CartVm(_currencyService)
            {
                Id         = cart.Id,
                CouponCode = cart.CouponCode,
                IsProductPriceIncludeTax = cart.IsProductPriceIncludeTax,
                TaxAmount        = cart.TaxAmount,
                ShippingAmount   = cart.ShippingAmount,
                OrderNote        = cart.OrderNote,
                LockedOnCheckout = cart.LockedOnCheckout
            };

            cartVm.Items = _cartItemRepository
                           .Query()
                           .Include(x => x.Product).ThenInclude(p => p.ThumbnailImage)
                           .Include(x => x.Product).ThenInclude(p => p.OptionCombinations).ThenInclude(o => o.Option)
                           .Where(x => x.CartId == cart.Id).ToList()
                           .Select(x => new CartItemVm(_currencyService)
            {
                Id                            = x.Id,
                ProductId                     = x.ProductId,
                ProductName                   = x.Product.Name,
                ProductPrice                  = x.Product.Price,
                ProductStockQuantity          = x.Product.StockQuantity,
                ProductStockTrackingIsEnabled = x.Product.StockTrackingIsEnabled,
                IsProductAvailabeToOrder      = x.Product.IsAllowToOrder && x.Product.IsPublished && !x.Product.IsDeleted,
                ProductImage                  = _mediaService.GetThumbnailUrl(x.Product.ThumbnailImage),
                Quantity                      = x.Quantity,
                VariationOptions              = CartItemVm.GetVariationOption(x.Product)
            }).ToList();

            cartVm.SubTotal = cartVm.Items.Sum(x => x.Quantity * x.ProductPrice);
            if (!string.IsNullOrWhiteSpace(cartVm.CouponCode))
            {
                var cartInfoForCoupon = new CartInfoForCoupon
                {
                    Items = cartVm.Items.Select(x => new CartItemForCoupon {
                        ProductId = x.ProductId, Quantity = x.Quantity
                    }).ToList()
                };
                var couponValidationResult = await _couponService.Validate(customerId, cartVm.CouponCode, cartInfoForCoupon);

                if (couponValidationResult.Succeeded)
                {
                    cartVm.Discount = couponValidationResult.DiscountAmount;
                }
                else
                {
                    cartVm.CouponValidationErrorMessage = couponValidationResult.ErrorMessage;
                }
            }

            return(cartVm);
        }
Exemplo n.º 29
0
 public Division Find(string Name)
 {
     return(_DivisionRepository.Query().Get().Where(i => i.DivisionName == Name).FirstOrDefault());
 }
        private void SetupSubstitutions()
        {
            uow = Substitute.For<IUnitOfWork>();

            tokenService = Substitute.For<IRepository<ApiToken>>();
            tokenService.Query().Returns(FakeTokens);

            uow.GetRepository<ApiToken>().Returns(tokenService);
        }
Exemplo n.º 31
0
        /// <summary>
        /// 从数据库获取最新功能信息
        /// </summary>
        /// <returns></returns>
        protected virtual TFunction[] GetFromDatabase()
        {
            IRepository <TFunction, Guid> repository = ScopedServiceProvider.GetService <IRepository <TFunction, Guid> >();

            return(repository.Query().ToArray());
        }
		private static void SyncNonLondonBrokers(HttpClient httpClient, IRepository consoleRepository)
		{
            DatabaseInit._LogHandler.WriteLog("SyncNonLondonBrokers()", LogSeverity.Information, LogCategory.DataAccess);

			var responseOffices = httpClient.GetAsync("rest/api/office").Result;

		    if (responseOffices.IsSuccessStatusCode)
		    {
		        var serviceOffices = responseOffices.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.Office>>().Result;

		        foreach (var serviceOffice in serviceOffices)
		        {
                    DatabaseInit._LogHandler.WriteLog("SyncNonLondonBrokers()_" + serviceOffice.Code, LogSeverity.Information, LogCategory.DataAccess);

                    var responseNonLondonBroker = httpClient.GetAsync("rest/api/NonLondonBroker?office=" + serviceOffice.Code).Result;

                    if (responseNonLondonBroker.IsSuccessStatusCode)
                    {
                        var serviceNonLondonBrokers = responseNonLondonBroker.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.NonLondonBroker>>().Result;

                        foreach (var serviceNonLondonBroker in serviceNonLondonBrokers)
                        {
                            if (serviceNonLondonBroker.Code == "NA") continue;
                            if (!consoleRepository.Query<NonLondonBroker>().Any(cb => cb.Code == serviceNonLondonBroker.Code))
                            {
                                consoleRepository.Add(new NonLondonBroker
                                {
                                    Name = serviceNonLondonBroker.Name,
                                    Code = serviceNonLondonBroker.Code,
                                });
                            }
                            else
                            {
                                var consoleNonLondonBroker = consoleRepository.Query<NonLondonBroker>()
                                                                     .FirstOrDefault(cb => cb.Code == serviceNonLondonBroker.Code);

                                if (consoleNonLondonBroker != null)
                                {
                                    consoleNonLondonBroker.Code = serviceNonLondonBroker.Code;
                                    consoleNonLondonBroker.Name = serviceNonLondonBroker.Name;

                                    consoleRepository.Attach(consoleNonLondonBroker);
                                }
                            }
                        }
                    }
                    else
                    {
                        DatabaseInit._LogHandler.WriteLog("Get rest/api/NonLondonBroker failed_" + serviceOffice.Code, LogSeverity.Warning, LogCategory.DataAccess);
                    } 
		        }

                if (!consoleRepository.Query<NonLondonBroker>().Any(cb => cb.Code == "NA"))
                {
                    consoleRepository.Add(new NonLondonBroker
                    {
                        Name = "Not Applicable",
                        Code = "NA",
                    });
                }


		    }
            else
            {
                DatabaseInit._LogHandler.WriteLog("Get rest/api/NonLondonBroker failed", LogSeverity.Warning, LogCategory.DataAccess);
            } 
		  
                
            
		}
Exemplo n.º 33
0
        public HomeViewModel(ILog log, IAccount account, ILocalize localize, IApplication application, IHistory history,
                             INavigationService navigationService, IUser user, IRepository repository,
                             IList<IExerciseType> exerciseTypes, ISettings settings)
        {
            _log = log;
            _localize = localize;
            _application = application;
            Account = account;

            _history = history;
            _history.OnHistoryItemsChanged += _history_OnHistoryItemsChanged;
            _NavigationService = navigationService;
            User = user;
            ExerciseTypes = exerciseTypes;
            _repository = repository;
            _settings = settings;
            _settings.OnSettingsChanged += _settings_OnSettingsChanged;
            _settings.Load();
            _history.Load();

            _repository.Single<User>(1).ContinueWith(t =>
                {
                    var foundUser = t.Result;
                    if (foundUser == null)
                    {
                        //this is first load of the app, set it up
                        _repository.Insert<User>(this.User).ContinueWith(task =>
                            {
                                this.User = this.User;
                                Account.AccessToken = this.User.RunkeeperToken;

                            });
                    }
                    else
                    {
                        User = foundUser;
                        Account.AccessToken = foundUser.RunkeeperToken;
                    }
                });

            if (_exerciseTypes == null || _exerciseTypes.Count == 0 ||
                (_exerciseTypes.Count == 1 && _exerciseTypes[0].Id == 0))
            {
                if (HomeViewModel.cachedTypes != null)
                {
                    this.ExerciseTypes = HomeViewModel.cachedTypes;
                    _log.Info("cache hit");
                }
                else
                {
                    _log.Info("cache miss");
                    this.ExerciseTypes = DefaultTypes;
                    _log.Info("default types set, querying");
                    _repository.Query<ExerciseType>("select * from ExerciseType").ContinueWith(t =>
                        {
                            _log.Info("query complete");
                            var types = t.Result;
                            if (types == null || types.Count == 0)
                            {

                                _log.Info("db does not have Exercise types, loading default items");
                                foreach (var e in from tt in this.ExerciseTypes orderby tt.Id select tt)
                                {
                                    _repository.Insert<ExerciseType>(e);
                                }
                            }
                            else
                            {
                                _log.Info("all excecise types retreived from the db, update local data store");
                                this.ExerciseTypes = (from tt in types select tt).ToArray();
                            }
                            _log.Info("cache extypes to static var");
                            HomeViewModel.cachedTypes = ExerciseTypes;

                        });
                }
            }
        }
		private static void SyncOffices(HttpClient httpClient, IRepository consoleRepository)
		{
			DatabaseInit._LogHandler.WriteLog("SyncOffices()", LogSeverity.Information, LogCategory.DataAccess);

			var response = httpClient.GetAsync("rest/api/office").Result;

			if (response.IsSuccessStatusCode)
			{
				var serviceOffices = response.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.Office>>().Result;

				foreach (var serviceOffice in serviceOffices.Where(so => !consoleRepository.Query<Office>()
				                                                                           .Any(co => co.Id == so.Code)))
				{
					consoleRepository.Add(new Office
					{
						Id = serviceOffice.Code,
						Name = serviceOffice.Name,
						Title = serviceOffice.Name
					});
				}
			}
			else
			{
				DatabaseInit._LogHandler.WriteLog("Get rest/api/office failed", LogSeverity.Warning, LogCategory.DataAccess);
			}
		}
        /// <summary>
        /// The create new tags.
        /// </summary>
        /// <param name="tags">
        /// The tags.
        /// </param>
        /// <param name="tagRepository">
        /// The tag repository.
        /// </param>
        /// <returns>
        /// The <see cref="IList"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        private IList<Tag> CreateNewTags(IList<Tag> tags, IRepository<Tag, int> tagRepository)
        {
            if (tags == null)
            {
                throw new ArgumentNullException("tags");
            }

            IList<Tag> result = new List<Tag>(tags.Count);
            for (int i = 0; i < tags.Count; ++i)
            {
                string content = tags[i].Content;
                Tag temp =
                    tagRepository.Query()
                                 .Filter(p => p.Content.Equals(content, StringComparison.Ordinal))
                                 .Get()
                                 .FirstOrDefault();
                if (temp == null)
                {
                    tagRepository.Insert(tags[i]);
                    result.Add(tags[i]);
                }
                else
                {
                    result.Add(temp);
                }
            }

            return result;
        }
		private static void SyncRiskCodes(HttpClient httpClient, IRepository consoleRepository)
		{
			DatabaseInit._LogHandler.WriteLog("SyncRiskCodes()", LogSeverity.Information, LogCategory.DataAccess);

			var response = httpClient.GetAsync("rest/api/riskcode").Result;

			if (response.IsSuccessStatusCode)
			{
				var serviceRisks = response.Content.ReadAsAsync<IEnumerable<Validus.Services.Models.RiskCode>>().Result;

				foreach (var serviceRisk in serviceRisks)
				{
					if (!consoleRepository.Query<RiskCode>()
					                      .Any(crc => crc.Code == serviceRisk.Code))
					{
						consoleRepository.Add(new RiskCode
						{
							Code = serviceRisk.Code,
							Name = serviceRisk.Name
						});
					}
					else
					{
						var consoleRisk = consoleRepository.Query<RiskCode>()
						                                   .FirstOrDefault(crc => crc.Code == serviceRisk.Code);

						if (consoleRisk != null)
						{
							consoleRisk.Code = serviceRisk.Code;
							consoleRisk.Name = serviceRisk.Name;

							consoleRepository.Attach(consoleRisk);
						}
					}
				}
			}
			else
			{
				DatabaseInit._LogHandler.WriteLog("Get rest/api/riskcode failed", LogSeverity.Warning, LogCategory.DataAccess);
			}
		}
Exemplo n.º 37
0
        public async Task Delete(long id)
        {
            var category = _categoryRepository.Query().First(x => x.Id == id);

            await Delete(category);
        }
Exemplo n.º 38
0
        public IActionResult CategoryDetail(long id, SearchOption searchOption)
        {
            var category = _categoryRepository.Query().FirstOrDefault(x => x.Id == id);

            if (category == null)
            {
                return(Redirect("~/Error/FindNotFound"));
            }

            var model = new ProductsByCategory
            {
                CategoryId              = category.Id,
                ParentCategorId         = category.ParentId,
                CategoryName            = category.Name,
                CategorySlug            = category.Slug,
                CategoryMetaTitle       = category.MetaTitle,
                CategoryMetaKeywords    = category.MetaKeywords,
                CategoryMetaDescription = category.MetaDescription,
                CurrentSearchOption     = searchOption,
                FilterOption            = new FilterOption()
            };

            var query = _productRepository
                        .Query()
                        .Where(x => x.Categories.Any(c => c.CategoryId == category.Id) && x.IsPublished && x.IsVisibleIndividually);

            model.FilterOption.Price.MaxPrice = query.Select(x => x.Price).DefaultIfEmpty(0).Max();
            model.FilterOption.Price.MinPrice = query.Select(x => x.Price).DefaultIfEmpty(0).Min();

            if (searchOption.MinPrice.HasValue)
            {
                query = query.Where(x => x.Price >= searchOption.MinPrice.Value);
            }

            if (searchOption.MaxPrice.HasValue)
            {
                query = query.Where(x => x.Price <= searchOption.MaxPrice.Value);
            }

            AppendFilterOptionsToModel(model, query);

            var brands = searchOption.GetBrands();

            if (brands.Any())
            {
                var brandIs = _brandRepository.Query().Where(x => brands.Contains(x.Slug)).Select(x => x.Id).ToList();
                query = query.Where(x => x.BrandId.HasValue && brandIs.Contains(x.BrandId.Value));
            }

            model.TotalProduct = query.Count();
            var currentPageNum = searchOption.Page <= 0 ? 1 : searchOption.Page;
            var offset         = (_pageSize * currentPageNum) - _pageSize;

            while (currentPageNum > 1 && offset >= model.TotalProduct)
            {
                currentPageNum--;
                offset = (_pageSize * currentPageNum) - _pageSize;
            }

            query = query
                    .Include(x => x.Brand)
                    .Include(x => x.ThumbnailImage);

            query = AppySort(searchOption, query);

            var products = query
                           .Select(x => ProductThumbnail.FromProduct(x))
                           .Skip(offset)
                           .Take(_pageSize)
                           .ToList();

            foreach (var product in products)
            {
                product.ThumbnailUrl           = _mediaService.GetThumbnailUrl(product.ThumbnailImage);
                product.CalculatedProductPrice = _productPricingService.CalculateProductPrice(product);
            }

            model.Products = products;
            model.CurrentSearchOption.PageSize = _pageSize;
            model.CurrentSearchOption.Page     = currentPageNum;

            return(View(model));
        }
Exemplo n.º 39
0
        public static IQueryable <WorkflowActivity> GetAuthorized(this IRepository <WorkflowActivity> repository,
                                                                  WorkflowActivityFinderModel finder, string account, bool optimization = true)
        {
            IQueryable <WorkflowActivity> workflowActivities = repository
                                                               .Query(x => x.WorkflowAuthorizations.Any(y => y.Account.ToLower() == account.ToLower()), optimization: optimization)
                                                               .Include(x => x.DocumentUnitReferenced.Category)
                                                               .Include(x => x.DocumentUnitReferenced.Container)
                                                               .OrderBy(o => o.OrderByDescending(oo => oo.RegistrationDate))
                                                               .SelectAsQueryable();


            if (finder != null)
            {
                if (finder.IdWorkflowActivity.HasValue)
                {
                    workflowActivities = workflowActivities.Where(x => x.UniqueId == finder.IdWorkflowActivity.Value);
                }
                if (!string.IsNullOrWhiteSpace(finder.RegistrationUser))
                {
                    workflowActivities = workflowActivities.Where(x => x.RegistrationUser.Contains(finder.RegistrationUser.ToLower()));
                }
                if (finder.AuthorizeDateFrom.HasValue)
                {
                    workflowActivities = workflowActivities.Where(x => x.RegistrationDate >= finder.AuthorizeDateFrom.Value);
                }
                if (finder.AuthorizeDateTo.HasValue)
                {
                    workflowActivities = workflowActivities.Where(x => x.RegistrationDate <= finder.AuthorizeDateTo.Value);
                }
                if (!string.IsNullOrEmpty(finder.RequestorUsername))
                {
                    workflowActivities = workflowActivities.Where(x => x.WorkflowProperties.Any(y => y.Name == WorkflowPropertyHelper.DSW_PROPERTY_PROPOSER_USER && y.ValueString.Contains(finder.RequestorUsername)));
                }
                if (!string.IsNullOrEmpty(finder.RequestorRoleName))
                {
                    workflowActivities = workflowActivities.Where(x => x.DocumentUnitReferenced != null && x.DocumentUnitReferenced.Container.Name.Contains(finder.RequestorRoleName));
                }
                if (finder.Status.HasValue)
                {
                    WorkflowStatus workflowStatus = (WorkflowStatus)finder.Status.Value;
                    workflowActivities = workflowActivities.Where(x => x.WorkflowInstance.Status == workflowStatus);
                }

                if (!string.IsNullOrEmpty(finder.Note))
                {
                    workflowActivities = workflowActivities.Where(x => x.Note.Contains(finder.Note));
                }

                if (!string.IsNullOrEmpty(finder.Subject))
                {
                    workflowActivities = workflowActivities.Where(x => x.Subject.Contains(finder.Subject));
                }

                if (finder.Skip != null && finder.Top != null)
                {
                    workflowActivities = workflowActivities.Skip(finder.Skip.Value).Take(finder.Top.Value);
                }
            }

            return(workflowActivities);
        }
 private void GetCategoryData(IRepository _repository)
 {
     Categories = _repository.Query<Category>(x => x == x);
 }
 public IQueryable <EnterpriseType> Query(Expression <Func <EnterpriseType, bool> > predicate = null, bool readOnly = false, string included = "")
 {
     return(_baseRepository.Query(predicate, readOnly, included));
 }
Exemplo n.º 42
0
        /// <summary>
        /// 从数据库获取最新功能信息
        /// </summary>
        /// <returns></returns>
        protected virtual TFunction[] GetFromDatabase(IServiceProvider scopedProvider)
        {
            IRepository <TFunction, Guid> repository = scopedProvider.GetService <IRepository <TFunction, Guid> >();

            return(repository.Query(null, false).ToArray());
        }
Exemplo n.º 43
0
 public IQueryable <WidgetInstance> GetPublished()
 {
     return(_widgetInstanceRepository.Query().Where(x =>
                                                    x.PublishStart.HasValue && x.PublishStart < DateTimeOffset.Now &&
                                                    (!x.PublishEnd.HasValue || x.PublishEnd > DateTimeOffset.Now)));
 }