예제 #1
0
        protected void btnDel_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;

            int id    = Convert.ToInt32(btn.CommandArgument.ToString());
            int count = 0;
            List <CustomProduct> carts = (List <CustomProduct>)Session["carts"];
            Product product            = new Product();

            foreach (CustomProduct custom in carts)
            {
                if (custom.product.id == id)
                {
                    product = custom.product;
                    count   = custom.Count;
                    break;
                }
            }

            carts = CustomProduct.removeAllProduct(product, carts);

            int cartsCount = (int)Session["cartsCount"];

            cartsCount -= count;

            Session["cartsCount"] = cartsCount;
            Session["carts"]      = carts;

            resetValue();
        }
        public static CustomProductViewModel Convert(CustomProduct product)
        {
            CustomProductViewModel model = new CustomProductViewModel();

            model.Id          = product.Id;
            model.CategoryId  = product.CategoryId;
            model.Name        = product.Name;
            model.Description = product.Description;
            model.Subtitle    = product.Subtitle;
            model.ImageSrc    = product.ImageSrc;
            model.Price       = product?.Price;
            model.IsOnSale    = product.IsOnSale;
            model.IsInStock   = product.IsInStock;
            model.Type        = product.Type;
            model.Category    = CategoryConverter.Convert(product.Category);
            if (product.MixCategories != null)
            {
                model.MixCategories = MixCategoryConverter.ConvertList(product.MixCategories);
            }
            model.Tags = TagConverter.ConvertList(product.Tags);
            if (product.SelectOptions != null)
            {
                model.SelectOptions = CustomSelectOptionConverter.ConvertList(product.SelectOptions);
            }

            return(model);
        }
예제 #3
0
        protected void plusProductCart_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton          btn     = (ImageButton)sender;
            int                  id      = Convert.ToInt32(btn.CommandArgument.ToString());
            List <CustomProduct> carts   = (List <CustomProduct>)Session["carts"];
            Product              product = new Product();

            foreach (CustomProduct custom in carts)
            {
                if (custom.product.id == id)
                {
                    product = custom.product;
                    break;
                }
            }

            carts = CustomProduct.addAProduct(product, carts);

            int cartsCount = (int)Session["cartsCount"];

            cartsCount++;

            Session["cartsCount"] = cartsCount;
            Session["carts"]      = carts;

            resetValue();
        }
예제 #4
0
        public ActionResult CustomProduct(CustomProduct customProduct)
        {
            string email = User.Identity.Name;
            User   user  = db.Users.FirstOrDefault(x => x.Email == email);

            if (ModelState.IsValid)
            {
                using (CustomProductContext db = new CustomProductContext())
                {
                    db.CustomProducts.Add(new CustomProduct
                    {
                        Name     = customProduct.Name,
                        Calories = customProduct.Calories,
                        Fats     = customProduct.Fats,
                        Protein  = customProduct.Protein,
                        Carbs    = customProduct.Carbs,
                        Fiber    = customProduct.Fiber,
                        Iron     = customProduct.Iron,
                        Calcium  = customProduct.Calcium,
                        VitA     = customProduct.VitA,
                        VitC     = customProduct.VitC,
                        VitB12   = customProduct.VitB12,
                        Folate   = customProduct.Folate,
                        UserId   = user.UserId
                    });
                    db.SaveChanges();
                    customProduct = db.CustomProducts.Where(u => u.Name == customProduct.Name && u.Calories == customProduct.Calories && u.Fats == customProduct.Fats &&
                                                            u.Protein == customProduct.Protein && u.Carbs == customProduct.Carbs && u.Fiber == customProduct.Fiber && u.Iron == customProduct.Iron &&
                                                            u.Calcium == customProduct.Calcium && u.VitA == customProduct.VitA && u.VitC == customProduct.VitC && u.VitB12 == customProduct.VitB12 &&
                                                            u.Folate == customProduct.Folate && u.UserId == user.UserId).FirstOrDefault();
                }
            }
            return(View(customProduct));
        }
예제 #5
0
        public async Task AcceptToPreparation(CustomProduct product, int technologistId)
        {
            product.TechnologistId       = technologistId;
            product.PreparationStartDate = DateTime.Now;

            _repository.CustomProduct.UpdateProduct(product);
            await _repository.SaveAsync();
        }
예제 #6
0
 // 不加过滤器的用法  不需要再全局Global中注册 需要在WebAPIConfig中加并添加注解 对所有方法接口奏效
 //MVC中不能这么用 必须全局注册下 并加注解    FluentValidationModelValidatorProvider.Configure();
 // 此接口也可以调用 验证因为全局注册了 !ModelState.IsValid 会主动调用
 public IHttpActionResult Post([FromBody] CustomProduct model)
 {
     if (!ModelState.IsValid) // 主动走RuleFor规则校验 这句话主动调用!!!!!
     {
         return(BadRequest(ModelState));
     }
     return(Ok(model));
 }
예제 #7
0
            public override CustomProduct Clone()
            {
                CustomProduct clone = this.MemberwiseClone() as CustomProduct;

                clone.obj       = this.obj.Clone() as SomeType;
                clone.CreatedAt = DateTime.Now;
                return(clone);
                // return this.MemberwiseClone() as CustomProduct; // Deep copy problem
            }
예제 #8
0
        /// <summary>
        /// Get custom product property
        /// </summary>
        /// <param name="productDescription">Custom product</param>
        /// <param name="propertyName">Property name</param>
        /// <returns>Property value</returns>
        private string GetCustomProductProperty(CustomProduct productDescription, string propertyName)
        {
            if (productDescription.CustomProductProperties == null || !productDescription.CustomProductProperties.Cast <Property>().Any(cpp => cpp.Name == propertyName))
            {
                throw new AtomiaProvisioningException(string.Format("Custom product {0} has no propertiy {1} defined in AtomiaProvisioning section.", productDescription.Name, propertyName));
            }

            return(productDescription.CustomProductProperties[propertyName].Value);
        }
예제 #9
0
        public ActionResult Index()
        {
            User user;
            int  c = 0, f = 0, p = 0, car = 0;
            List <DefaultProduct> d_products = new List <DefaultProduct> {
            };
            List <CustomProduct> c_products  = new List <CustomProduct> {
            };

            using (UserContext db = new UserContext())
            {
                user = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
            }
            if (user.Sex == null || user.Height == null || user.Weight == null)
            {
                return(HttpNotFound());
            }
            var daybook = dbDaybook.Daybooks.Where(x => x.UserId == user.UserId);

            foreach (var item in daybook)
            {
                if (item.Custom == false)
                {
                    DefaultProduct defaultProduct = dbDefaultProduct.DefaultProducts.Find(item.ProductId);
                    c   += defaultProduct.Calories * (item.Gram / 100);
                    f   += defaultProduct.Fats * (item.Gram / 100);
                    p   += defaultProduct.Protein * (item.Gram / 100);
                    car += defaultProduct.Carbs * (item.Gram / 100);
                    d_products.Add(defaultProduct);
                }
                else
                {
                    CustomProduct customProduct = dbCustomProduct.CustomProducts.Find(item.ProductId);
                    c   += customProduct.Calories * (item.Gram / 100);
                    f   += customProduct.Fats * (item.Gram / 100);
                    p   += customProduct.Protein * (item.Gram / 100);
                    car += customProduct.Carbs * (item.Gram / 100);
                    c_products.Add(customProduct);
                }
            }
            ViewBag.c        = c;
            ViewBag.f        = f;
            ViewBag.p        = p;
            ViewBag.car      = car;
            ViewBag.dp       = d_products;
            ViewBag.cp       = c_products;
            ViewBag.Daybook  = daybook;
            ViewBag.Calories = (int)((user.Weight * 10 + (user.Height * 6.25) -
                                      ((DateTime.UtcNow.Month < user.BirthDate.Month || (DateTime.UtcNow.Month == user.BirthDate.Month && DateTime.UtcNow.Day < user.BirthDate.Day)) ?
                                       (DateTime.UtcNow.Year - user.BirthDate.Year) : (DateTime.UtcNow.Year - user.BirthDate.Year) - 1) +
                                      (user.Sex == true ? 5 : -161)) * 1.2 - c);

            ViewBag.DefaultProducts = dbDefaultProduct.DefaultProducts.ToList().ToList();
            ViewBag.CustomProducts  = dbCustomProduct.CustomProducts.Where(x => x.UserId == user.UserId).ToList();
            return(View());
        }
예제 #10
0
        static void TestPrototype()
        {
            var           p            = new SomeType();
            CustomProduct product      = new CustomProduct(p);
            CustomProduct productClone = product.Clone();

            (productClone.obj as SomeType).Name = "New name";
            Console.WriteLine(product.ToString());
            Console.WriteLine(productClone.ToString());
        }
예제 #11
0
        public async Task AddSolution(CustomProduct product, CustomProductAddSolutionDto solution)
        {
            product.PreparationCompletionDate = DateTime.Now;
            product.Status = CustomProductStatus.Prepared;
            product.SolutionDescription = solution.SolutionDescription;
            await _service.UploadSolutionFilesAsync(product.CustomProductId, solution.Files);

            _repository.CustomProduct.Update(product);
            await _repository.SaveAsync();
        }
예제 #12
0
 private IDs GetStoreIDs(CustomProduct product)
 {
     IDs ids = new IDs();
     foreach (KeyValuePair<string, string> storeIDs in product.storeIDs)
     {
         string storeName = storeIDs.Key;
         string storeID = storeIDs.Value;
         ids.Add(storeID, storeName);
     }
     return ids;
 }
예제 #13
0
        private async Task <CustomProductViewModel> GetCustomSackProdctAsync(CancellationToken ct = default)
        {
            CustomProduct customSack = await this._customProductRepository.GetCustomSackAsync(ct);

            List <MixCategory> mixCategories = await this._mixCategoryRepository.GetAllByProductIdAsync(customSack.Id);

            foreach (MixCategory category in mixCategories)
            {
                category.Ingredients = await this._ingredientRepository.GetAllByMixCategoryIdAsync(category.Id, ct);
            }

            customSack.MixCategories = mixCategories;

            CustomProductViewModel customSackView = CustomProductConverter.Convert(customSack);

            if (customSackView.IsOnSale == true)
            {
                List <SaleItem> sales = await this._saleItemRepository.GetByCustomProductId(customSack.Id);

                List <SaleItemViewModel> saleViews = new List <SaleItemViewModel>();
                foreach (SaleItem sale in sales)
                {
                    SaleItemViewModel saleView = SaleItemConverter.Convert(sale);
                    // if sale item is a promo code
                    if (sale.Type == OfferType.PromoCode)
                    {
                        // ensure promo code id exists on
                        if (String.IsNullOrEmpty(sale.PromoCodeId) == false)
                        {
                            PromoCodeViewModel promoViewModel = PromoCodeConverter.Convert(await this._promoCodeRepository.GetByIdAsync(sale.PromoCodeId, ct));
                            // check if promo is valid
                            if (promoViewModel.ExpireDate > DateTime.Now)
                            {
                                saleView.PromoCode = promoViewModel;
                                saleViews.Add(saleView);
                            }
                        }
                    }
                    else
                    {
                        // if sale is valid
                        if (sale.ExpireDate > DateTime.Now)
                        {
                            saleViews.Add(saleView);
                        }
                    }
                }
                customSackView.Sales = saleViews;
            }

            return(customSackView);
        }
예제 #14
0
        public ActionResult DeleteProduct()
        {
            User user;
            int  allCalories = 0, fats = 0, protein = 0, carbs = 0;

            using (UserContext db = new UserContext())
            {
                user = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
            }
            string         id             = Request.QueryString["id"];
            DaybookProduct daybookProduct = dbDaybook.Daybooks.Find(Convert.ToInt32(id));

            dbDaybook.Daybooks.Remove(daybookProduct);
            dbDaybook.SaveChanges();

            var daybook = dbDaybook.Daybooks.Where(x => x.UserId == user.UserId);

            foreach (var item in daybook)
            {
                if (item.Custom == false)
                {
                    DefaultProduct defaultP = dbDefaultProduct.DefaultProducts.Find(item.ProductId);
                    allCalories += defaultP.Calories * (item.Gram / 100);
                    fats        += defaultP.Fats * (item.Gram / 100);
                    protein     += defaultP.Protein * (item.Gram / 100);
                    carbs       += defaultP.Carbs * (item.Gram / 100);
                }
                else
                {
                    CustomProduct customP = dbCustomProduct.CustomProducts.Find(item.ProductId);
                    allCalories += customP.Calories * (item.Gram / 100);
                    fats        += customP.Fats * (item.Gram / 100);
                    protein     += customP.Protein * (item.Gram / 100);
                    carbs       += customP.Carbs * (item.Gram / 100);
                }
            }

            int caloriesNeeded = (int)((user.Weight * 10 + (user.Height * 6.25) -
                                        ((DateTime.UtcNow.Month < user.BirthDate.Month || (DateTime.UtcNow.Month == user.BirthDate.Month && DateTime.UtcNow.Day < user.BirthDate.Day)) ?
                                         (DateTime.UtcNow.Year - user.BirthDate.Year) : (DateTime.UtcNow.Year - user.BirthDate.Year) - 1) +
                                        (user.Sex == true ? 5 : -161)) * 1.2) - allCalories;

            return(Json(new
            {
                caloriesNeeded,
                allCalories,
                fats,
                protein,
                carbs
            }, JsonRequestBehavior.AllowGet));
        }
예제 #15
0
        /// <summary>
        /// Prepares the service.
        /// </summary>
        /// <param name="productDescription">The product description.</param>
        /// <param name="account">The account.</param>
        /// <param name="serviceKey">The service key.</param>
        /// <param name="parentService">The parent service.</param>
        /// <returns>Prepared service.</returns>
        private ProvisioningService PrepareService(CustomProduct productDescription, BoAccount account, string serviceKey, ProvisioningService parentService)
        {
            string serviceName = string.Empty;

            if (productDescription.CustomProductProperties.Cast <Property>().Any(customProductProperty => customProductProperty.Name == serviceKey))
            {
                serviceName = productDescription.CustomProductProperties[serviceKey].Value;
            }

            if (string.IsNullOrEmpty(serviceName))
            {
                throw new AtomiaProvisioningException(string.Format("Cannot add {0} service. Property {1} is not defined in AtomiaProvisioning section.", productDescription.ProvisioningService, serviceKey));
            }

            return(this.coreService.CreateService(serviceName, parentService, account.Name));
        }
예제 #16
0
        /// <summary>
        /// Gets the product property.
        /// </summary>
        /// <param name="productDescription">The product description.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns>Property of the product.</returns>
        private static string GetProductProperty(CustomProduct productDescription, string propertyName)
        {
            string propertyValue = string.Empty;

            if (productDescription.CustomProductProperties.Cast <Property>().Any(customProductProperty => customProductProperty.Name == propertyName))
            {
                propertyValue = productDescription.CustomProductProperties[propertyName].Value;
            }

            if (string.IsNullOrEmpty(propertyValue))
            {
                throw new AtomiaProvisioningException(string.Format("Cannot add {0} service. Property {1} is not defined in AtomiaProvisioning section.", productDescription.ProvisioningService, propertyName));
            }

            return(propertyValue);
        }
예제 #17
0
        [ValidateModelStateFilter]   // // 加过滤器的用法  必须在Global中注册
        public ActionResult Create([System.Web.Http.FromBody] CustomProduct product)
        {
            //CustomerValidator validator = new CustomerValidator();
            //ValidationResult results = validator.Validate(customer);
            if (!ModelState.IsValid) ///此句话很重要 加上会不用过滤器直接走校验规则坏处是每个Action都要写一遍 所以添加全局验证Filter拦截中写上统一的
            {
                var errors = ModelState.Values.Select(x => x.Errors).First().ToString();
                ViewBag.err = errors == "" ? "无错误" : errors;

                var response = new HttpResponseMessage();
                response.Content    = new StringContent(string.Join("\n", errors));
                response.StatusCode = HttpStatusCode.BadRequest;

                throw new System.Web.Http.HttpResponseException(response);
            }
            return(View(product));
        }
예제 #18
0
        /// <summary>
        /// Adds the service.
        /// </summary>
        /// <param name="account">The account.</param>
        /// <param name="productDescription">The product description.</param>
        /// <param name="parentServiceKey">The parent service key.</param>
        /// <param name="serviceKey">The service key.</param>
        /// <param name="name">The name.</param>
        /// <param name="requestId">The request unique identifier.</param>
        /// <returns>Added service</returns>
        private ProvisioningService CreateService(BoAccount account, CustomProduct productDescription, string parentServiceKey, string serviceKey, string name, ref string requestId)
        {
            ProvisioningService parentService = this.FindService(productDescription, parentServiceKey, "rootService", account);
            ProvisioningService service       = this.PrepareService(productDescription, account, serviceKey, parentService);

            string nameValue = this.GetServiceName(account.Name, parentService, serviceKey, name);

            service.properties.First(p => p.Name == "CustomParam1").propStringValue = nameValue;
            service.properties.First(p => p.Name == "CustomParam2").propStringValue = nameValue;

            if (!string.IsNullOrEmpty(requestId))
            {
                return(this.coreService.AddServiceAsync(service, parentService, account.Name, null, ref requestId));
            }

            return(this.coreService.AddService(service, parentService, account.Name, null));
        }
예제 #19
0
        /// <summary>
        /// Gets the service.
        /// </summary>
        /// <param name="subscription">The subscription.</param>
        /// <param name="productDescription">The product description.</param>
        /// <param name="account">The account.</param>
        /// <returns></returns>
        private ProvisioningService GetService(Subscription subscription, CustomProduct productDescription, BoAccount account)
        {
            if (subscription.CustomAttributes == null || !subscription.CustomAttributes.ContainsKey("ServiceId"))
            {
                throw new AtomiaProvisioningException(string.Format("Cannot get service {0}. Subscription has no custom attribute ServiceId.", productDescription.ProvisioningService));
            }

            string serviceId            = subscription.CustomAttributes["ServiceId"];
            ProvisioningService service = this.coreService.GetServiceById(serviceId, account.Name);

            if (service == null)
            {
                throw new AtomiaProvisioningException(string.Format("Cannot find service with id {0} for account {1}.", serviceId, account.Name));
            }

            return(service);
        }
예제 #20
0
        protected void btnAddToCart_Click(object sender, EventArgs e)
        {
            Button  btn                = (Button)sender;
            int     id                 = Convert.ToInt32(btn.CommandArgument.ToString());
            Product product            = new Product();
            List <CustomProduct> carts = (List <CustomProduct>)Session["carts"];

            if (carts == null)
            {
                carts = new List <CustomProduct>();
            }

            using (SqlConnection sqlConn = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    sqlConn.Open();
                    cmd.Connection  = sqlConn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "getProductById";
                    cmd.Parameters.Add(new SqlParameter("@id", id));
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        product.id          = Int32.Parse(reader[0].ToString());
                        product.name        = reader[1].ToString();
                        product.images      = reader[2].ToString();
                        product.description = reader[3].ToString();
                        product.price       = Int32.Parse(reader[4].ToString());
                        product.quantity    = Int32.Parse(reader[5].ToString());
                        product.guarantee   = reader[6].ToString();
                    }
                }
            }
            int count = (int)Session["cartsCount"];

            carts = CustomProduct.addAProduct(product, carts);
            count++;

            Session["cartsCount"] = count;
            Session["carts"]      = carts;
            Response.Write("<script> alert('Thêm vào giỏ hàng thành công!'); window.location='http://localhost:54996/Client/HomePage.aspx';</script>");
        }
예제 #21
0
        /// <summary>
        /// Finds the service.
        /// </summary>
        /// <param name="productDescription">The product description.</param>
        /// <param name="parentServiceKey">The parent service key.</param>
        /// <param name="rootServiceKey">The root service key.</param>
        /// <param name="account">The account.</param>
        /// <returns>Service that was found using parent services.</returns>
        private ProvisioningService FindService(CustomProduct productDescription, string parentServiceKey, string rootServiceKey, BoAccount account)
        {
            string parentServiceName  = GetProductProperty(productDescription, parentServiceKey);
            string servicePath        = productDescription.CustomProductProperties[rootServiceKey].Value;
            ServiceSearchCriteria ssc = new ServiceSearchCriteria
            {
                ParentService = null,
                ServiceName   = parentServiceName,
                ServicePath   = servicePath
            };

            ProvisioningService[] parentService = this.coreService.FindServicesByPath(new[] { ssc }, null, account.Name, null, true);
            if (parentService == null || parentService.Length < 1)
            {
                throw new AtomiaProvisioningException(string.Format("Cannot add {0} service. Account {1} doesn't have {2} service provisioned.", productDescription.ProvisioningService, account.Name, parentServiceName));
            }

            return(parentService[0]);
        }
예제 #22
0
        protected void minusProductCart_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton          btn     = (ImageButton)sender;
            int                  count   = 0;
            int                  id      = Convert.ToInt32(btn.CommandArgument.ToString());
            List <CustomProduct> carts   = (List <CustomProduct>)Session["carts"];
            Product              product = new Product();

            foreach (CustomProduct custom in carts)
            {
                if (custom.product.id == id)
                {
                    product = custom.product;
                    count   = custom.Count;
                    break;
                }
            }

            if (count == 1)
            {
                btnDel.CommandArgument = Convert.ToString(id);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "none",
                                                    "<script type=\"text/javascript\" language=\"Javascript\" >"
                                                    + "$('#myModal').modal('show');</script>", false);
                return;
            }
            carts = CustomProduct.removeAProduct(product, carts);

            int cartsCount = (int)Session["cartsCount"];

            cartsCount--;

            Session["cartsCount"] = cartsCount;
            Session["carts"]      = carts;

            resetValue();
        }
예제 #23
0
        public ActionResult AddProduct()
        {
            User user;
            int  id;
            int  allCalories = 0, fats = 0, protein = 0, carbs = 0;

            using (UserContext db = new UserContext())
            {
                user = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name);
            }

            string selectId = Request.QueryString["id"];
            string product  = Request.QueryString["product"];
            int    gram     = Convert.ToInt32(Request.QueryString["g"]);

            if (Convert.ToBoolean(product))
            {
                CustomProduct customProduct;
                using (CustomProductContext dbCustomProduct = new CustomProductContext())
                {
                    customProduct = dbCustomProduct.CustomProducts.Find(Convert.ToInt32(selectId));
                }
                using (DaybookContext dbDaybook = new DaybookContext())
                {
                    DaybookProduct daybookProduct = new DaybookProduct {
                        UserId = user.UserId, ProductId = customProduct.Id, Custom = Convert.ToBoolean(product), Gram = gram
                    };
                    dbDaybook.Daybooks.Add(daybookProduct);
                    dbDaybook.SaveChanges();
                    id = daybookProduct.Id;
                }

                var daybook = dbDaybook.Daybooks.Where(x => x.UserId == user.UserId);
                foreach (var item in daybook)
                {
                    if (item.Custom == false)
                    {
                        DefaultProduct defaultP = dbDefaultProduct.DefaultProducts.Find(item.ProductId);
                        allCalories += defaultP.Calories * (item.Gram / 100);
                        fats        += defaultP.Fats * (item.Gram / 100);
                        protein     += defaultP.Protein * (item.Gram / 100);
                        carbs       += defaultP.Carbs * (item.Gram / 100);
                    }
                    else
                    {
                        CustomProduct customP = dbCustomProduct.CustomProducts.Find(item.ProductId);
                        allCalories += customP.Calories * (item.Gram / 100);
                        fats        += customP.Fats * (item.Gram / 100);
                        protein     += customP.Protein * (item.Gram / 100);
                        carbs       += customP.Carbs * (item.Gram / 100);
                    }
                }

                int caloriesNeeded = (int)((user.Weight * 10 + (user.Height * 6.25) -
                                            ((DateTime.UtcNow.Month < user.BirthDate.Month || (DateTime.UtcNow.Month == user.BirthDate.Month && DateTime.UtcNow.Day < user.BirthDate.Day)) ?
                                             (DateTime.UtcNow.Year - user.BirthDate.Year) : (DateTime.UtcNow.Year - user.BirthDate.Year) - 1) +
                                            (user.Sex == true ? 5 : -161)) * 1.2) - allCalories;

                return(Json(new
                {
                    addId = id,
                    addName = customProduct.Name,
                    addCalories = customProduct.Calories * gram / 100,
                    addFats = customProduct.Fats * gram / 100,
                    addProtein = customProduct.Protein * gram / 100,
                    addCarbs = customProduct.Carbs * gram / 100,
                    caloriesNeeded,
                    allCalories,
                    fats,
                    protein,
                    carbs
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                DefaultProduct defaultProduct;
                using (DefaultProductContext dbDefaultProduct = new DefaultProductContext())
                {
                    defaultProduct = dbDefaultProduct.DefaultProducts.Find(Convert.ToInt32(selectId));
                }
                using (DaybookContext dbDaybook = new DaybookContext())
                {
                    DaybookProduct daybookProduct = new DaybookProduct {
                        UserId = user.UserId, ProductId = defaultProduct.Id, Custom = Convert.ToBoolean(product), Gram = gram
                    };
                    dbDaybook.Daybooks.Add(daybookProduct);
                    dbDaybook.SaveChanges();
                    id = daybookProduct.Id;
                }

                var daybook = dbDaybook.Daybooks.Where(x => x.UserId == user.UserId);
                foreach (var item in daybook)
                {
                    if (item.Custom == false)
                    {
                        DefaultProduct defaultP = dbDefaultProduct.DefaultProducts.Find(item.ProductId);
                        allCalories += defaultP.Calories * (item.Gram / 100);
                        fats        += defaultP.Fats * (item.Gram / 100);
                        protein     += defaultP.Protein * (item.Gram / 100);
                        carbs       += defaultP.Carbs * (item.Gram / 100);
                    }
                    else
                    {
                        CustomProduct customP = dbCustomProduct.CustomProducts.Find(item.ProductId);
                        allCalories += customP.Calories * (item.Gram / 100);
                        fats        += customP.Fats * (item.Gram / 100);
                        protein     += customP.Protein * (item.Gram / 100);
                        carbs       += customP.Carbs * (item.Gram / 100);
                    }
                }

                int caloriesNeeded = (int)((user.Weight * 10 + (user.Height * 6.25) -
                                            ((DateTime.UtcNow.Month < user.BirthDate.Month || (DateTime.UtcNow.Month == user.BirthDate.Month && DateTime.UtcNow.Day < user.BirthDate.Day)) ?
                                             (DateTime.UtcNow.Year - user.BirthDate.Year) : (DateTime.UtcNow.Year - user.BirthDate.Year) - 1) +
                                            (user.Sex == true ? 5 : -161)) * 1.2) - allCalories;

                return(Json(new
                {
                    addId = id,
                    addName = defaultProduct.Name,
                    addCalories = defaultProduct.Calories * gram / 100,
                    addFats = defaultProduct.Fats * gram / 100,
                    addProtein = defaultProduct.Protein * gram / 100,
                    addCarbs = defaultProduct.Carbs * gram / 100,
                    caloriesNeeded,
                    allCalories,
                    fats,
                    protein,
                    carbs
                }, JsonRequestBehavior.AllowGet));
            }
        }
예제 #24
0
    private void ExportOrders(int?orderId)
    {
        var orders        = new List <CustomOrder>();
        var products      = new List <CustomProduct>();
        var productExtras = new List <CustomProductExtra>();

        var orderCust = AppLogic.GetString("CMD.StoreCustomerID", SkinID, LocaleSetting);
        var program   = AppLogic.GetString("CMD.StoreProgramNumber", SkinID, LocaleSetting);

        var dateString = "";

        //call sproc and get list of orders
        using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["DBConn"]))
        {
            //string query = "exec custom_GetOrder @OrderID";
            string query = orderId.HasValue ? "exec custom_GetOrdersForExport @OrderID" : "exec custom_GetOrdersForExport";

            SqlCommand command = new SqlCommand(query, connection);
            if (orderId.HasValue)
            {
                command.Parameters.AddWithValue("@OrderID", orderId.Value);
            }
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();

            try
            {
                while (reader.Read())
                {
                    //Orders
                    var orderNumber         = Convert.ToInt32(reader["OrderNumber"]);
                    var orderDate           = Convert.ToDateTime(reader["OrderDate"]);
                    var email               = reader["Email"].ToString();
                    var customerId          = Convert.ToInt32(reader["CustomerID"]);
                    var billingCompany      = reader["BillingCompany"] != null ? reader["BillingCompany"].ToString() : "";
                    var billingFirstName    = reader["BillingFirstName"] != null ? reader["BillingFirstName"].ToString() : "";
                    var billingLastName     = reader["BillingLastName"] != null ? reader["BillingLastName"].ToString() : "";
                    var billingAddress1     = reader["BillingAddress1"] != null ? reader["BillingAddress1"].ToString() : "";
                    var billingAddress2     = reader["BillingAddress2"] != null ? reader["BillingAddress2"].ToString() : "";
                    var billingSuite        = reader["BillingSuite"] != null ? reader["BillingSuite"].ToString() : "";
                    var billingCity         = reader["BillingCity"] != null ? reader["BillingCity"].ToString() : "";
                    var billingState        = reader["BillingState"] != null ? reader["BillingState"].ToString() : "";
                    var billingZip          = reader["BillingZip"] != null ? reader["BillingZip"].ToString() : "";
                    var billingCountry      = reader["BillingCountry"] != null ? reader["BillingCountry"].ToString() : "";
                    var billingPhone        = reader["BillingPhone"] != null ? reader["BillingPhone"].ToString() : "";
                    var cardType            = reader["CardType"] != null ? reader["CardType"].ToString() : "";
                    var cardName            = reader["CardName"] != null ? reader["CardName"].ToString() : "";
                    var last4               = reader["Last4"] != null ? reader["Last4"].ToString() : "";
                    var cardExpirationMonth = reader["CardExpirationMonth"] != null ? reader["CardExpirationMonth"].ToString() : "";
                    var cardExpirationYear  = reader["CardExpirationYear"] != null ? reader["CardExpirationYear"].ToString() : "";
                    var authorizationCode   = reader["AuthorizationCode"] != null ? reader["AuthorizationCode"].ToString() : "";
                    var paymentGateway      = reader["PaymentGateway"] != null ? reader["PaymentGateway"].ToString() : "";
                    var transactionState    = reader["TransactionState"] != null ? reader["TransactionState"].ToString() : "";
                    var shippingCompany     = reader["ShippingCompany"] != null ? reader["ShippingCompany"].ToString() : "";
                    var shippingFirstName   = reader["ShippingFirstName"] != null ? reader["ShippingFirstName"].ToString() : "";
                    var shippingLastName    = reader["ShippingLastName"] != null ? reader["ShippingLastName"].ToString() : "";
                    var shippingAddress1    = reader["ShippingAddress1"] != null ? reader["ShippingAddress1"].ToString() : "";
                    var shippingAddress2    = reader["ShippingAddress2"] != null ? reader["ShippingAddress2"].ToString() : "";
                    var shippingSuite       = reader["ShippingSuite"] != null ? reader["ShippingSuite"].ToString() : "";
                    var shippingCity        = reader["ShippingCity"] != null ? reader["ShippingCity"].ToString() : "";
                    var shippingState       = reader["ShippingState"] != null ? reader["ShippingState"].ToString() : "";
                    var shippingZip         = reader["ShippingZip"] != null ? reader["ShippingZip"].ToString() : "";
                    var shippingCountry     = reader["ShippingCountry"] != null ? reader["ShippingCountry"].ToString() : "";
                    var shippingPhone       = reader["ShippingPhone"] != null ? reader["ShippingPhone"].ToString() : "";
                    var shippingMethod      = reader["ShippingMethod"] != null ? reader["ShippingMethod"].ToString() : "";
                    var orderSubTotal       = Convert.ToDecimal(reader["OrderSubTotal"]);
                    var orderTax            = Convert.ToDecimal(reader["OrderTax"]);
                    var orderShippingCosts  = Convert.ToDecimal(reader["OrderShippingCosts"]);
                    var orderTotal          = Convert.ToDecimal(reader["OrderTotal"]);
                    var taxRate             = Convert.ToDecimal(reader["TaxRate"]);

                    dateString         = orderDate.ToShortDateString().Replace("/", "-");
                    cardExpirationYear = !String.IsNullOrEmpty(cardExpirationYear) ? cardExpirationYear.Substring(2) : cardExpirationYear;

                    var order = new CustomOrder
                    {
                        OrderID             = orderNumber,
                        OrderDate           = orderDate,
                        Email               = email,
                        CustomerID          = customerId,
                        BillingCompany      = billingCompany,
                        BillingFirstName    = billingFirstName,
                        BillingLastName     = billingLastName,
                        BillingAddress1     = billingAddress1,
                        BillingAddress2     = billingAddress2,
                        BillingSuite        = billingSuite,
                        BillingCity         = billingCity,
                        BillingState        = billingState,
                        BillingZip          = billingZip,
                        BillingCountry      = CustomOrder.ConvertCountryCode(billingCountry),
                        BillingPhone        = billingPhone,
                        CardType            = cardType,
                        CardName            = cardName,
                        Last4               = last4,
                        CardExpirationMonth = cardExpirationMonth,
                        CardExpirationYear  = cardExpirationYear,
                        AuthorizationCode   = authorizationCode,
                        PaymentGateway      = paymentGateway,
                        TransactionState    = transactionState,
                        ShippingCompany     = shippingCompany,
                        ShippingFirstName   = shippingFirstName,
                        ShippingLastName    = shippingLastName,
                        ShippingAddress1    = shippingAddress1,
                        ShippingAddress2    = shippingAddress2,
                        ShippingSuite       = shippingSuite,
                        ShippingCity        = shippingCity,
                        ShippingState       = shippingState,
                        ShippingZip         = shippingZip,
                        ShippingCountry     = CustomOrder.ConvertCountryCode(shippingCountry),
                        ShippingPhone       = shippingPhone,
                        ShippingMethod      = shippingMethod,
                        OrderSubtotal       = orderSubTotal,
                        OrderTax            = orderTax,
                        OrderShippingCosts  = orderShippingCosts,
                        OrderTotal          = orderTotal,
                        TaxRate             = taxRate
                    };

                    orders.Add(order);
                }

                reader.NextResult();

                while (reader.Read())
                {
                    //Products
                    var orderNumber                = Convert.ToInt32(reader["OrderNumber"]);
                    var productId                  = Convert.ToInt32(reader["ProductID"]);
                    var orderedProductName         = reader["OrderedProductName"].ToString();
                    var quantity                   = Convert.ToInt32(reader["Quantity"]);
                    var chosenColorSKUModifier     = reader["ChosenColorSKUModifier"] != null ? reader["ChosenColorSKUModifier"].ToString() : "";
                    var chosenSizeSKUModifier      = reader["ChosenSizeSKUModifier"] != null ? reader["ChosenSizeSKUModifier"].ToString() : "";
                    var orderedProductSKU          = reader["OrderedProductSKU"] != null ? reader["OrderedProductSKU"].ToString() : "";
                    var orderedProductPrice        = Convert.ToDecimal(reader["OrderedProductPrice"]);
                    var orderedProductRegularPrice = Convert.ToDecimal(reader["OrderedProductRegularPrice"]);

                    var product = new CustomProduct
                    {
                        OrderID                    = orderNumber,
                        ProductID                  = productId,
                        OrderedProductName         = orderedProductName,
                        Quantity                   = quantity,
                        ChosenColorSKUModifier     = chosenColorSKUModifier,
                        ChosenSizeSKUModifier      = chosenSizeSKUModifier,
                        OrderedProductSKU          = orderedProductSKU,
                        OrderedProductPrice        = orderedProductPrice,
                        OrderedProductRegularPrice = orderedProductRegularPrice
                    };

                    products.Add(product);
                }

                reader.NextResult();

                while (reader.Read())
                {
                    //Product Extras
                    var productId = Convert.ToInt32(reader["ProductID"]);
                    var partId    = Convert.ToInt32(reader["PartID"]);
                    var kitId     = reader["KitID"].ToString();
                    var quantity  = Convert.ToInt32(reader["Quantity"]);
                    var color     = reader["Color"].ToString();

                    var productExtra = new CustomProductExtra
                    {
                        ProductID = productId,
                        PartID    = partId,
                        KitID     = kitId,
                        Quantity  = quantity,
                        Color     = color
                    };

                    productExtras.Add(productExtra);
                }
            }
            finally
            {
                reader.Close();
            }
        }

        StringWriter  stringWriter  = new StringWriter();
        XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

        xmlTextWriter.Formatting = Formatting.Indented;
        xmlTextWriter.WriteStartDocument();
        xmlTextWriter.WriteStartElement("orders");

        //loop thru and build xml
        foreach (var order in orders)
        {
            xmlTextWriter.WriteStartElement("order");

            xmlTextWriter.WriteElementString("version", "");
            xmlTextWriter.WriteElementString("rectype", "B");
            xmlTextWriter.WriteElementString("seqno", "1");
            xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("orddate", order.OrderDate.ToString("M/d/yy"));
            xmlTextWriter.WriteElementString("loginid", order.Email);
            xmlTextWriter.WriteElementString("email", order.Email);
            xmlTextWriter.WriteElementString("ordcust", orderCust);

            xmlTextWriter.WriteElementString("bcompany", order.BillingCompany);
            xmlTextWriter.WriteElementString("battn", (order.BillingFirstName + " " + order.BillingLastName).Trim());
            xmlTextWriter.WriteElementString("baddr1", order.BillingAddress1);
            xmlTextWriter.WriteElementString("baddr2", (order.BillingAddress2 + " " + order.BillingSuite).Trim());
            xmlTextWriter.WriteElementString("bcity", order.BillingCity);
            xmlTextWriter.WriteElementString("bstate", order.BillingState);
            xmlTextWriter.WriteElementString("bzip", order.BillingZip);
            xmlTextWriter.WriteElementString("bcountry", CustomOrder.ConvertCountryCode(order.BillingCountry));
            xmlTextWriter.WriteElementString("bphone", order.BillingPhone);

            xmlTextWriter.WriteElementString("cctype", CustomOrder.ConvertCCType(order.CardType));
            xmlTextWriter.WriteElementString("ccname", order.CardType);
            xmlTextWriter.WriteElementString("ccnum", order.Last4);
            xmlTextWriter.WriteElementString("ccexpire", String.Format("{0}{1}", order.CardExpirationMonth, order.CardExpirationYear));
            xmlTextWriter.WriteElementString("ccauthzano", order.AuthorizationCode);
            xmlTextWriter.WriteElementString("ccauthrefer", order.PaymentGateway);
            xmlTextWriter.WriteElementString("ccsettled", order.TransactionState == "CAPTURED" ? "Y" : "N");

            xmlTextWriter.WriteElementString("program", program);
            xmlTextWriter.WriteElementString("shipamt", order.OrderShippingCosts.ToString("F"));
            xmlTextWriter.WriteElementString("shipdesc", CustomOrder.ConvertShippingMethod(order.ShippingMethod));
            xmlTextWriter.WriteElementString("taxamt", order.OrderTax.ToString("F"));
            xmlTextWriter.WriteElementString("grdtotal", order.OrderTotal.ToString("F"));

            List <string> alpha1 = new List <string>();
            List <string> alpha2 = new List <string>();
            List <string> alpha3 = new List <string>();

            var items = products.Where(p => p.OrderID == order.OrderID);

            foreach (var item in items)
            {
                alpha1.Add(item.OrderedProductSKU);
                alpha2.Add(item.OrderedProductName);
                alpha3.Add(item.ChosenColorSKUModifier);
            }

            xmlTextWriter.WriteElementString("alpha1", String.Join(",", alpha1.ToArray()));
            xmlTextWriter.WriteElementString("alpha2", String.Join(",", alpha2.ToArray()));
            xmlTextWriter.WriteElementString("alpha3", String.Join(",", alpha3.ToArray()));

            xmlTextWriter.WriteElementString("num1", "");
            xmlTextWriter.WriteElementString("num2", "");
            xmlTextWriter.WriteElementString("num3", "");

            xmlTextWriter.WriteElementString("date1", "");
            xmlTextWriter.WriteElementString("date2", "");
            xmlTextWriter.WriteElementString("date3", "");

            //shiptos
            xmlTextWriter.WriteStartElement("shiptos");
            xmlTextWriter.WriteStartElement("shipto");

            xmlTextWriter.WriteElementString("rectype", "S");
            xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("seqno", "1");
            xmlTextWriter.WriteElementString("shipdate", "");
            xmlTextWriter.WriteElementString("scompany", order.ShippingCompany);
            xmlTextWriter.WriteElementString("sname", (order.ShippingFirstName + " " + order.ShippingLastName).Trim());
            xmlTextWriter.WriteElementString("saddr1", order.ShippingAddress1);
            xmlTextWriter.WriteElementString("saddr2", (order.ShippingAddress2 + " " + order.ShippingSuite).Trim());
            xmlTextWriter.WriteElementString("scity", order.ShippingCity);
            xmlTextWriter.WriteElementString("sstate", order.ShippingState);
            xmlTextWriter.WriteElementString("szip", order.ShippingZip);
            xmlTextWriter.WriteElementString("scountry", CustomOrder.ConvertCountryCode(order.ShippingCountry));
            xmlTextWriter.WriteElementString("sphone", order.ShippingPhone);
            xmlTextWriter.WriteElementString("shipdesc", CustomOrder.ConvertShippingMethod(order.ShippingMethod));
            xmlTextWriter.WriteElementString("comres", "R");
            xmlTextWriter.WriteElementString("shipamt", order.OrderShippingCosts.ToString("F"));
            xmlTextWriter.WriteElementString("taxcode1", "");
            xmlTextWriter.WriteElementString("taxcode2", "");

            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();

            foreach (var item in items)
            {
                xmlTextWriter.WriteStartElement("items");

                var extras = productExtras.Where(x => x.ProductID == item.ProductID && x.Color == item.ChosenColorSKUModifier);

                //get quantity and use as multiplier for extras
                var multiplier = item.Quantity;

                var color  = item.ChosenColorSKUModifier == null ? "" : item.ChosenColorSKUModifier;
                var size   = item.ChosenSizeSKUModifier == null ? "" : item.ChosenSizeSKUModifier;
                var itemno = item.OrderedProductSKU;
                if (!String.IsNullOrEmpty(color))
                {
                    itemno = itemno.Replace(color, "");
                }
                if (!String.IsNullOrEmpty(size))
                {
                    itemno = itemno.Replace(size, "");
                }
                var subno = size + color;

                xmlTextWriter.WriteStartElement("item");
                xmlTextWriter.WriteElementString("rectype", "I");
                xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
                xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
                xmlTextWriter.WriteElementString("seqno", "1");
                xmlTextWriter.WriteElementString("itemno", itemno);
                xmlTextWriter.WriteElementString("subno", subno);
                xmlTextWriter.WriteElementString("itemcustno", "0");
                xmlTextWriter.WriteElementString("qtyord", item.Quantity.ToString());
                xmlTextWriter.WriteElementString("taxable", "");
                //xmlTextWriter.WriteElementString("itemprice", item.OrderedProductPrice.ToString("F"));
                xmlTextWriter.WriteElementString("itemprice", item.OrderedProductRegularPrice.ToString("F"));
                xmlTextWriter.WriteElementString("pointqty", "0.0000");
                xmlTextWriter.WriteElementString("personalization", "N");

                xmlTextWriter.WriteEndElement();

                foreach (var extra in extras)
                {
                    xmlTextWriter.WriteStartElement("item");
                    xmlTextWriter.WriteElementString("rectype", "I");
                    xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
                    xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
                    xmlTextWriter.WriteElementString("seqno", "1");
                    xmlTextWriter.WriteElementString("itemno", extra.PartID.ToString());
                    xmlTextWriter.WriteElementString("subno", "");
                    xmlTextWriter.WriteElementString("itemcustno", "0");
                    xmlTextWriter.WriteElementString("qtyord", (extra.Quantity * multiplier).ToString());
                    xmlTextWriter.WriteElementString("taxable", "");
                    xmlTextWriter.WriteElementString("itemprice", "0.00");
                    xmlTextWriter.WriteElementString("pointqty", "0.0000");
                    xmlTextWriter.WriteElementString("personalization", "N");

                    xmlTextWriter.WriteEndElement();
                }

                xmlTextWriter.WriteEndElement();
            }

            //instructions
            xmlTextWriter.WriteStartElement("instructions");

            xmlTextWriter.WriteElementString("rectype", "C");
            xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("impinst", "");
            xmlTextWriter.WriteElementString("spclinst", "");

            xmlTextWriter.WriteEndElement();

            //taxes
            xmlTextWriter.WriteStartElement("taxes");
            xmlTextWriter.WriteStartElement("tax");

            xmlTextWriter.WriteElementString("rectype", "T");
            xmlTextWriter.WriteElementString("ordno", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("webtrack", order.OrderID.ToString());
            xmlTextWriter.WriteElementString("taxcode", (order.TaxRate / 100).ToString());
            xmlTextWriter.WriteElementString("taxrate", order.TaxRate.ToString());

            xmlTextWriter.WriteEndElement();
            xmlTextWriter.WriteEndElement();

            xmlTextWriter.WriteEndElement();
        }

        xmlTextWriter.WriteEndElement();
        xmlTextWriter.WriteEndDocument();

        var fileName = orderId.HasValue ? dateString + "." + orderId.Value.ToString() + ".xml" : "export.orders.all.xml";

        //write to screen
        Response.Clear();
        Response.ContentType = "text/xml";
        Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        Response.Write(stringWriter.ToString().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "<?xml version=\"1.0\"?>"));
        Response.End();
    }
예제 #25
0
        /// <summary>
        /// Adds the product.
        /// </summary>
        /// <param name="subscription">The subscription.</param>
        /// <param name="mainSubscription">The main subscription.</param>
        /// <param name="account">The account.</param>
        /// <param name="productDescription">The product description.</param>
        /// <param name="additionalData">The additional data.</param>
        /// <returns>Added service.</returns>
        public ProvisioningService AddProduct(Subscription subscription, Subscription mainSubscription, BoAccount account, CustomProduct productDescription, Dictionary <string, object> additionalData)
        {
            if (productDescription.CustomProductProperties == null)
            {
                throw new AtomiaProvisioningException(string.Format("Cannot add {0} service. Custom product {1} has no properties defined in AtomiaProvisioning section.", productDescription.ProvisioningService, productDescription.Name));
            }

            if (subscription.CustomAttributes == null || !subscription.CustomAttributes.ContainsKey("CustomAttributeParam"))
            {
                throw new AtomiaProvisioningException(string.Format("Cannot add {0} service. Subscription does not have custom attribute CustomAttributeParam.", productDescription.ProvisioningService));
            }

            string packageName = GetCustomProductProperty(productDescription, "defaultPackageName");

            if (subscription.CustomAttributes != null && subscription.CustomAttributes.Any(ca => ca.Key == "ProvisioningPackage"))
            {
                packageName = subscription.CustomAttributes["ProvisioningPackage"];
            }
            // Ensuring that package exist, if not then adds that package
            EnsurePackageExist(packageName, account.Name);

            string customAttributeParam = subscription.CustomAttributes["CustomAttributeParam"].ToLowerInvariant();
            string customServiceName    = GetProductProperty(productDescription, "linuxInstance"); // linuxInstance or windowsInstance

            ProvisioningService parentService = this.FindService(productDescription, "parentService", "rootService", account);

            ProvisioningService customService = this.coreService.CreateService(customServiceName, parentService, account.Name);

            FillServiceProperties(customService, subscription.CustomAttributes);

            customService.properties.First(p => p.Name == "Name").propStringValue = subscription.CustomAttributes.ContainsKey("CustomAttribute1")
                         ? subscription.CustomAttributes["CustomAttribute1"]
                         : this.GetServiceName(account.Name, parentService, customServiceName, customAttributeParam);

            ProvisioningService service = null;
            string requestId            = string.Empty;

            try
            {
                // Add services.


                customService.properties.First(p => p.Name == "CustomParam").propStringValue = customAttributeParam;

                service = this.coreService.AddServiceAsync(customService, parentService, account.Name, null, ref requestId);

                this.coreService.EndProvisioningRequestAsync(account.Name, requestId);

                subscription.CustomAttributes["ProvisioningRequestId"] = requestId;
                subscription.ProvisioningStatus = Subscription.ProvisioningStatusProvisioningInitiated;
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(requestId))
                {
                    string reason;
                    this.coreService.CancelProvisioningRequest(out reason, account.Name, requestId);
                }

                throw new AtomiaProvisioningException(ex.Message, ex);
            }

            return(service);
        }
예제 #26
0
 private void LoadProductByProductGroup()
 {
     using (var db = new SlaughterhouseEntities())
     {
         var receive = db.receives.Where(p => p.receive_no == lblReceiveNo.Text).SingleOrDefault();
         //int stock_qty = receive.receive_item.Where(p => p.product_code.Equals(product.product_code)).Sum(p => p.receive_qty);
         //decimal stock_wgh = receive.receive_item.Where(p => p.product_code.Equals(product.product_code)).Sum(p => p.receive_wgh);
         //var receive_item = receive.receive_item.Where(p => p.product_code.Equals(product.product_code)).LastOrDefault();
         //int remain_qty = receive.farm_qty - stock_qty;
         lblReceiveNo.Text = receive.receive_no;
         lblFarm.Text      = receive.farm.farm_name;
         //lblBreeder.Text = receive.breeder.breeder_name;
         //lblTruckNo.Text = receive.truck.truck_no;
         lblLotNo.Text   = receive.lot_no;
         lblFarmQty.Text = receive.farm_qty.ToComma();
         //lblFactoryQty.Text = stock_qty.ToComma();
         //lblFactoryWgh.Text = stock_wgh.ToFormat2Decimal();
         //lblRemainQty.Text = remain_qty.ToComma();
         var products = db.products.Where(p => p.product_group_code == coreProduct.product_group_code).ToList();
         flowLayoutPanel1.Controls.Clear();
         buttons = new List <System.Windows.Forms.Button>();
         var coreProductQty = 0;
         customProducts.Clear();
         //bool foundByProductCompleted = false;
         foreach (var product in products)
         {
             var sqlParams = new[] {
                 new MySqlParameter("@product_code", product.product_code),
                 new MySqlParameter("@lot_no", receive.lot_no)
             };
             var sql        = "SELECT sum(qty) AS qty FROM slaughterhouse.barcode where product_code=@product_code  and lot_no =@lot_no group by product_code";
             var receiveQty = db.Database.SqlQuery <int>(sql, sqlParams).SingleOrDefault();
             if (product.product_code == CoreProductCode)
             {
                 coreProductQty = receiveQty;
             }
             var btn = new System.Windows.Forms.Button
             {
                 Text      = $"{product.product_code}\r{product.product_name} ({receiveQty})",
                 Width     = 180,
                 Height    = 80,
                 FlatStyle = FlatStyle.Flat,
                 Font      = new Font("Kanit", 14),
                 BackColor = Color.White,
                 Tag       = product.product_code
             };
             var customProduct = new CustomProduct
             {
                 ProductCode = product.product_code,
                 ProductName = product.product_name,
                 ReciveQty   = receiveQty
             };
             customProducts.Add(customProduct);
             buttons.Add(btn);
             btn.Click += Btn_Click;
             //check ถ้าเครื่องในชุด + จำนวนเครื่องในชนิดนั้น ถ้าเท่ากับจำนวนฟาร์ม ห้ามเลือกได้
             //if ((customProduct.ReciveQty + coreProductQty) >= receive.farm_qty)
             //{
             //    btn.Enabled = false;
             //    btn.BackColor = Color.Gray;
             //    foundByProductCompleted = true;
             //}
         }
         // check จำนวนเครื่องในชุด + เครื่องในแต่ละชนิด ถ้ามากกว่าหรือเท่ากับ จำนวนฟาร์ม เครื่องในชุดห้ามเลือกได้
         //if (foundByProductCompleted)
         //{
         //    var btn = buttons.Where(p => p.Tag.ToString() == CoreProductCode).SingleOrDefault();
         //    btn.Enabled = false;
         //    btn.BackColor = Color.Gray;
         //}
         DisplayPaging();
     }
     lblMessage.Text = Constants.START_WAITING;
 }
예제 #27
0
        /// <summary>
        /// Removes the product.
        /// </summary>
        /// <param name="subscription">The subscription.</param>
        /// <param name="mainSubscription">The main subscription.</param>
        /// <param name="account">The account.</param>
        /// <param name="productDescription">The product description.</param>
        /// <param name="additionalData">The additional data.</param>
        /// <returns>Service that was removed.</returns>
        public ProvisioningService RemoveProduct(Subscription subscription, Subscription mainSubscription, BoAccount account, CustomProduct productDescription, Dictionary <string, object> additionalData)
        {
            ProvisioningService service = this.GetService(subscription, productDescription, account);

            try
            {
                this.coreService.DeleteService(service, account.Name);
            }
            catch (Exception ex)
            {
                throw new AtomiaProvisioningException(ex.Message, ex);
            }

            return(service);
        }
예제 #28
0
 /// <summary>
 /// Gets the provisioning service.
 /// </summary>
 /// <param name="subscription">The subscription.</param>
 /// <param name="mainSubscription">The main subscription.</param>
 /// <param name="account">The account.</param>
 /// <param name="productDescription">The product description.</param>
 /// <param name="additionalData">The additional data.</param>
 /// <returns>THe service.</returns>
 public ProvisioningService GetProvisioningService(Subscription subscription, Subscription mainSubscription, BoAccount account, CustomProduct productDescription, Dictionary <string, object> additionalData)
 {
     throw new NotImplementedException();
 }
예제 #29
0
        /// <summary>
        /// Modifies the product.
        /// </summary>
        /// <param name="subscription">The subscription.</param>
        /// <param name="mainSubscription">The main subscription.</param>
        /// <param name="account">The account.</param>
        /// <param name="productDescription">The product description.</param>
        /// <param name="additionalData">The additional data.</param>
        /// <exception cref="ArgumentException"></exception>
        /// <returns>Modified service.</returns>
        public ProvisioningService ModifyProduct(Subscription subscription, Subscription mainSubscription, BoAccount account, CustomProduct productDescription, Dictionary <string, object> additionalData)
        {
            ProvisioningService service = null;

            if (additionalData == null || !additionalData.ContainsKey("ModifyOperation"))
            {
                throw new AtomiaProvisioningException(string.Format("Cannot modify {0} service. Additional data are null or does not contain ModifyOperation key.", productDescription.ProvisioningService));
            }

            string operation = additionalData["ModifyOperation"].ToString();
            ProvisioningService parentService = this.GetService(subscription, productDescription, account);
            string serviceName        = GetProductProperty(productDescription, "instanceService");
            ServiceSearchCriteria ssc = new ServiceSearchCriteria
            {
                ParentService = parentService,
                ServiceName   = serviceName
            };

            ProvisioningService[] foundServices = this.coreService.FindServicesByPath(new[] { ssc }, null, account.Name, null, true);
            if (foundServices == null || foundServices.Length == 0)
            {
                throw new NullReferenceException(string.Format("Cannot modify {0} service. Service {1} cannot be found on account {2}.", productDescription.ProvisioningService, serviceName, account.Name));
            }

            service = foundServices[0];
            switch (operation)
            {
            case "Suspend":
                parentService.properties.First(property => property.Name == "State").propStringValue = "Suspended";
                this.coreService.CallOperation("Stop", string.Empty, service, account.Name);
                break;

            case "Unsuspend":
                parentService.properties.First(property => property.Name == "State").propStringValue = "Ok";
                this.coreService.CallOperation("Start", string.Empty, service, account.Name);
                break;

            default:
                throw new ArgumentException(string.Format("Cannot modify {0} service. Unknown operation: {1}.", productDescription.ProvisioningService, operation));
            }

            try
            {
                return(this.coreService.ModifyService(parentService, account.Name));
            }
            catch (Exception ex)
            {
                throw new AtomiaProvisioningException(ex.Message, ex);
            }
        }