/// <summary>
    /// adding a new product
    /// </summary>
    protected void btnAddProduct_Click(object sender, EventArgs e)
    {
        try
        {
            int counter = 1;
            Category c = new Category();
            properties = c.getCategoryProperties(categories[categoriesNamesDDL.SelectedValue.ToString()]);
            propertiesOfCategory = new Dictionary<int, string>();
            foreach (KeyValuePair<string, int> pair in properties)//getting the propery id and its description
            {
                TextBox tb = Page.FindControl("txProperty" + counter) as TextBox;
                if (tb != null)
                {
                    string property = tb.Text;
                    ProductProperty productProp = new ProductProperty();
                    productProp.Description = property;
                    Property pr = new Property();
                    pr.Name = pair.Key;
                    propertiesOfCategory.Add(properties[pr.Name], productProp.Description);
                }
                counter++;
            }

            Product product = new Product();
            product.Id = Convert.ToInt32(productIdTB.Text);
            product.Name = productNameTB.Text;
            product.Description = productDescriptionTB.Text;
            DateTime currentTime = DateTime.Now;
            product.DateModified = currentTime;
            InsertPictureToDirectory();
            product.ImageUrl = ProductpicPath;
            product.Price = Convert.ToDouble(ProductPriceTB.Text);
            if (discountTB.Text == "") { }
            else
                product.Discount = discountTB.Text;
            int numOfRows = product.insertNewProduct(product, categories[categoriesNamesDDL.SelectedValue.ToString()], propertiesOfCategory, "Email");
            if (numOfRows > 0)//מוציא הודעה האם המוצר הוכנס כמו שצריך
            {
                ProductInsertedName.InnerHtml = product.Name;
                Session.Add("numOfRows", numOfRows);
                Session.Add("product", product);
                Response.Redirect("CatalogManager.aspx");
            }
        }
        catch (Exception)
        {

        }
    }
        private void PopulateMultipleChoice(ProductProperty p)
        {
            this.lstDefaultValue.DataSource     = p.Choices;
            this.lstDefaultValue.DataTextField  = "ChoiceName";
            this.lstDefaultValue.DataValueField = "id";
            this.lstDefaultValue.DataBind();

            foreach (System.Web.UI.WebControls.ListItem li in lstDefaultValue.Items)
            {
                if (li.Value == DefaultValueField.Text.Trim())
                {
                    lstDefaultValue.ClearSelection();
                    li.Selected = true;
                }
            }
        }
        public ProductProperty ConvertProductViewModelToProductProperty(ProductViewModel product)
        {
            var model = new ProductProperty()
            {
                RamSlots       = product.RamSlots,
                Processor      = product.Processor,
                ScreenSize     = product.ScreenSize,
                UsbPorts       = product.UsbPorts,
                BrandId        = product.BrandId,
                ComputerTypeId = product.ComputerTypeId,
                ProductId      = product.ProductId,
                Id             = product.Id
            };

            return(model);
        }
示例#4
0
    private static ListItem[] GetPropertyTypes()
    {
        List <ListItem> propertyTypes           = new List <ListItem>();
        Collection <ProductProperty> properties = ProductProperty.FindAll();

        foreach (ProductProperty property in properties)
        {
            propertyTypes.Add(new ListItem(property.DisplayName, property.Bvin));
        }
        if (propertyTypes.Count == 0)
        {
            propertyTypes.Add(new ListItem("- n/a -", string.Empty));
        }

        return(propertyTypes.ToArray());
    }
示例#5
0
        public ActionResult EditProperty(ProductProperty productPro)
        {
            var result = db.ProductProperties.Where(x => x.ProperID == productPro.ProperID);

            foreach (var item in result)
            {
                item.ProperName  = productPro.ProperName;
                item.IMG         = productPro.IMG;
                item.Price       = productPro.Price;
                item.Quantity    = productPro.Quantity;
                item.TypeID      = productPro.TypeID;
                item.Description = productPro.Description;
            }
            db.SaveChanges();
            return(Content("修改成功"));
        }
示例#6
0
        public async Task UpdatePropertyInProductAsync(string productKey, ProductProperty property, DateTime modifiedOn)
        {
            var product = await _dataAccess.SelectByKeyAsync <Domain.Entities.Product>(productKey);

            product.Properties.ForEach(p =>
            {
                if (p.Name == property.Name)
                {
                    p = property;
                }
            });

            product.ModifiedOn = modifiedOn;

            await _dataAccess.UpdateAsync(product, productKey);
        }
        protected void btnSave_Click(System.Object sender, System.Web.UI.ImageClickEventArgs e)
        {
            msg.ClearMessage();
            ProductProperty prop = new ProductProperty();

            prop = MTApp.CatalogServices.ProductProperties.Find((long)ViewState["ID"]);
            if (prop != null)
            {
                prop.PropertyName         = PropertyNameField.Text;
                prop.DisplayName          = DisplayNameField.Text;
                prop.DisplayOnSite        = chkDisplayOnSite.Checked;
                prop.DisplayToDropShipper = chkDisplayToDropShipper.Checked;
                switch (prop.TypeCode)
                {
                case ProductPropertyType.CurrencyField:
                    prop.CultureCode  = lstCultureCode.SelectedValue;
                    prop.DefaultValue = DefaultValueField.Text.Trim();
                    break;

                case ProductPropertyType.MultipleChoiceField:
                    prop.DefaultValue = lstDefaultValue.SelectedValue;
                    break;

                case ProductPropertyType.DateField:
                    prop.DefaultValue = string.Format("{0:d}", DefaultDate.SelectedDate);
                    break;

                case ProductPropertyType.TextField:
                    prop.DefaultValue = DefaultValueField.Text.Trim();
                    break;
                }
                if (MTApp.CatalogServices.ProductProperties.Update(prop) == true)
                {
                    prop = null;
                    Response.Redirect("~/BVAdmin/Catalog/ProductTypeProperties.aspx");
                }
                else
                {
                    prop = null;
                    msg.ShowError("Error: Couldn't Save Property!");
                }
            }
            else
            {
                msg.ShowError("Couldn't Load Property to Update!");
            }
        }
        private void LoadProperty(ProductProperty prop)
        {
            if (prop != null)
            {
                this.PropertyNameField.Text          = prop.PropertyName;
                this.DisplayNameField.Text           = prop.DisplayName;
                this.chkDisplayOnSite.Checked        = prop.DisplayOnSite;
                this.chkDisplayToDropShipper.Checked = prop.DisplayToDropShipper;
                this.DefaultValueField.Text          = prop.DefaultValue;

                foreach (System.Web.UI.WebControls.ListItem li in lstCultureCode.Items)
                {
                    if (li.Value == prop.CultureCode)
                    {
                        lstCultureCode.ClearSelection();
                        li.Selected = true;
                    }
                }

                this.DefaultValueField.TextMode = TextBoxMode.MultiLine;
                //Me.DefaultDate.SetYearRange(Date.Now.Year - 50, Date.Now.Year + 50)

                if (prop.TypeCode == ProductPropertyType.DateField)
                {
                    System.DateTime d = new System.DateTime();
                    d = System.DateTime.Now;
                    try
                    {
                        if (prop.DefaultValue.Trim().Length > 0)
                        {
                            d = System.DateTime.Parse(prop.DefaultValue);
                        }
                    }
                    catch (Exception ex)
                    {
                        MerchantTribe.Commerce.EventLog.LogEvent(ex);
                    }
                    this.DefaultDate.SelectedDate = d;
                }

                DisplayProperControls(prop);
            }
            else
            {
                msg.ShowError("Unable to load Product Property ID " + (string)ViewState["ID"]);
            }
        }
        private void AddProductProperties(Product product, ProductViewModel sfProduct)
        {
            if (sfProduct.Item.CustomFields.Count == 0)
            {
                return;
            }

            // All properties are currently imported as ShortText properties
            var dataType = _session.Query <DataType>().FirstOrDefault(x => x.TypeName == "ShortText");

            foreach (var customProperty in sfProduct.Item.CustomFields)
            {
                if (customProperty.Key == "Department")
                {
                    continue;
                }

                var property =
                    product.ProductDefinition.ProductDefinitionFields.FirstOrDefault(x => x.Name == customProperty.Key);

                if (property == null)
                {
                    property = new ProductDefinitionField
                    {
                        DisplayOnSite     = true,
                        Deleted           = false,
                        RenderInEditor    = true,
                        IsVariantProperty = false,
                        SortOrder         = 0,
                        Name         = customProperty.Key,
                        DataType     = dataType,
                        Multilingual = true
                    };
                    product.ProductDefinition.AddProductDefinitionField(property);
                }

                var propertyValue          = GetPropertyValue(customProperty);
                var currentProductProperty = new ProductProperty
                {
                    Value = propertyValue,
                    ProductDefinitionField = property,
                    Product = product
                };

                product.AddProductProperty(currentProductProperty);
            }
        }
示例#10
0
        /// <summary>
        /// 转换到数据库使用的集合
        /// </summary>
        /// <param name="values">编辑后的商品属性对应的属性值列表</param>
        /// <param name="property">商品属性</param>
        /// <returns></returns>
        public static ISet <ProductPropertyValue> ToDatabaseSet(
            this IList <ProductPropertyValueForEdit> values, ProductProperty property)
        {
            if (values == null)
            {
                return(new HashSet <ProductPropertyValue>());
            }
            var set       = property.PropertyValues ?? new HashSet <ProductPropertyValue>();
            var addValues = new List <ProductPropertyValue>();
            var now       = DateTime.UtcNow;

            for (int i = 0; i < values.Count; ++i)
            {
                var value = values[i];
                if (value.Id == null)
                {
                    // 添加属性值(临时)
                    addValues.Add(new ProductPropertyValue()
                    {
                        Id           = GuidUtils.SequentialGuid(now),
                        Name         = value.Name,
                        Property     = property,
                        DisplayOrder = i,
                        CreateTime   = now,
                        UpdateTime   = now,
                        Remark       = value.Remark
                    });
                }
                else
                {
                    // 更新属性值
                    var updateValue = set.First(p => p.Id == value.Id);
                    updateValue.Name         = value.Name;
                    updateValue.DisplayOrder = i;
                    updateValue.UpdateTime   = now;
                    updateValue.Remark       = value.Remark;
                }
            }
            // 删除属性值
            var aliveIds     = new HashSet <Guid>(values.Where(v => v.Id != null).Select(v => v.Id.Value));
            var deleteValues = set.Where(p => !aliveIds.Contains(p.Id)).ToList();

            deleteValues.ForEach(v => set.Remove(v));
            // 添加属性值
            addValues.ForEach(v => set.Add(v));
            return(set);
        }
示例#11
0
        protected void btnNew_Click(object sender, EventArgs e)
        {
            var p = new ProductProperty();

            p.DisplayName = Localization.GetString("NewProperty");
            p.TypeCode    = (ProductPropertyType)int.Parse(lstPropertyType.SelectedValue);
            var success = HccApp.CatalogServices.ProductProperties.Create(p);

            if (success)
            {
                Response.Redirect("ProductTypePropertiesEdit.aspx?id=" + p.Id);
            }
            else
            {
                msg.ShowError(Localization.GetString("CreateError"));
            }
        }
示例#12
0
        //Product property delete button action
        public async Task <IActionResult> RemoveProductProperty(int id)
        {
            ProductProperty property = await _productService.FindProductPropertyByIdAsync(id);

            int productId = property.ProductId;

            try
            {
                await _productService.DeleteProductProperty(property.Id);

                return(RedirectToAction(nameof(ManageProperties), new { id = productId }));
            }
            catch (Exception)
            {
                return(RedirectToAction(nameof(Index)));
            }
        }
        protected void btnNew_Click(object sender, EventArgs e)
        {
            var p = new ProductProperty();

            p.DisplayName = "New Property";
            p.TypeCode    = (ProductPropertyType)int.Parse(lstPropertyType.SelectedValue);
            var success = HccApp.CatalogServices.ProductProperties.Create(p);

            if (success)
            {
                Response.Redirect("ProductTypePropertiesEdit.aspx?id=" + p.Id);
            }
            else
            {
                msg.ShowError("Error while attempting to create new property.");
            }
        }
        private void InitSpecificSettings(ProductProperty property)
        {
            switch (property.TypeCode)
            {
            case ProductPropertyType.CurrencyField:
                mvTypeSettings.SetActiveView(vCurrency);

                var liCultureCode = lstCultureCode.Items.FindByValue(property.CultureCode);
                if (liCultureCode != null)
                {
                    liCultureCode.Selected = true;
                }
                txtDefaultCurrencyValue.Text = property.DefaultValue;
                break;

            case ProductPropertyType.DateField:
                mvTypeSettings.SetActiveView(vDate);

                if (!string.IsNullOrEmpty(property.DefaultValue))
                {
                    DateTime selectedDate;
                    if (
                        !DateTime.TryParse(property.DefaultValue, CultureInfo.InvariantCulture, DateTimeStyles.None,
                                           out selectedDate))
                    {
                        selectedDate = DateTime.Now;
                    }
                    radDefaultDate.SelectedDate = selectedDate;
                }
                break;

            case ProductPropertyType.MultipleChoiceField:
                mvTypeSettings.SetActiveView(vMultipleChoice);

                PopulateMultipleChoice(property);
                break;

            case ProductPropertyType.TextField:
                mvTypeSettings.SetActiveView(vText);

                chkIsLocalizable.Checked = property.IsLocalizable;
                var realValue = property.IsLocalizable ? property.DefaultLocalizableValue : property.DefaultValue;
                txtDefaultTextValue.Text = realValue;
                break;
            }
        }
        protected void btnNew_Click(System.Object sender, System.Web.UI.ImageClickEventArgs e)
        {
            msg.ClearMessage();

            ProductProperty p = new ProductProperty();

            p.DisplayName = "New Property";
            p.TypeCode    = (ProductPropertyType)int.Parse(lstProductType.SelectedValue);
            if (MTApp.CatalogServices.ProductProperties.Create(p) == true)
            {
                FillList();
            }
            else
            {
                msg.ShowError("Error while attempting to create new property.");
            }
        }
示例#16
0
        public ProductModel getDetailInfo(string id)
        {
            ProductModel info = new ProductModel();
            Sql          sql  = new Sql("select * from product  where id= @0 ", id);

            using (var db = base.getDatabase())
            {
                product pro = db.FirstOrDefault <product>(sql);
                info.id          = pro.id;
                info.name        = pro.name;
                info.price       = pro.price;
                info.stock       = pro.stock;
                info.category_id = (int)pro.category_id;
                info.summary     = pro.summary;


                info.main_img_url = base.imgUrl + pro.main_img_url;
                Sql proimage = new Sql("SELECT pi.* ,url FROM `product_image` pi  inner join image i on pi.img_id = i.id where product_id = @0  order by pi.`order`", id);
                List <ProductImage> pimagelist = new List <ProductImage>();
                var proimagelist = db.Fetch <dynamic>(proimage);
                for (int i = 0; i < proimagelist.Count; i++)
                {
                    ProductImage pImage = new ProductImage();
                    pImage.id    = proimagelist[i].id;
                    pImage.order = proimagelist[i].order;
                    pImage.url   = base.imgUrl + proimagelist[i].url;
                    pimagelist.Add(pImage);
                }
                info.images = pimagelist;
                Sql propro = new Sql("SELECT  *   FROM `product_property`   where product_id = @0  order by  `id`", id);
                List <ProductProperty> pprolist = new List <ProductProperty>();
                var proprolist = db.Fetch <dynamic>(propro);
                for (int i = 0; i < proprolist.Count; i++)
                {
                    ProductProperty pPro = new ProductProperty();
                    pPro.id     = proprolist[i].id;
                    pPro.name   = proprolist[i].name;
                    pPro.detail = proprolist[i].detail;

                    pprolist.Add(pPro);
                }
                info.properties = pprolist;
            }
            return(info);
        }
示例#17
0
        StackLayout Entry_Row_Layout(ProductProperty Bind_Context)
        {
            var stack = new StackLayout {
                BackgroundColor = Color.White, Orientation = StackOrientation.Horizontal, HeightRequest = 60, Margin = 0, HorizontalOptions = LayoutOptions.FillAndExpand, Padding = new Thickness(20, 0, 20, 0)
            };

            if (Bind_Context == null)
            {
                return(stack);
            }

            Entry entry = null;

            if (Bind_Context.IsNumberKeyboard)
            {
                entry = new NumberEntry(12)
                {
                    IsEnabled = controlEnabled, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 40, VerticalOptions = LayoutOptions.Center, TextColor = (Color)App.Current.Resources["GreyishBrown"], FontFamily = "SanFranciscoDisplay-Regular", PlaceholderColor = Color.FromRgb(179, 179, 179)
                };
                entry.Keyboard = Keyboard.Numeric;
            }
            else
            {
                entry = new Entry()
                {
                    IsEnabled = controlEnabled, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 40, VerticalOptions = LayoutOptions.Center, TextColor = (Color)App.Current.Resources["GreyishBrown"], FontFamily = "SanFranciscoDisplay-Regular", PlaceholderColor = Color.FromRgb(179, 179, 179)
                };
            }

            entry.SetBinding(Entry.TextProperty, "PropertyValue", BindingMode.TwoWay);
            entry.BindingContext = Bind_Context;

            var label = new Label {
                FontFamily = "SanFranciscoDisplay-Regular", HorizontalOptions = LayoutOptions.Start, VerticalOptions = LayoutOptions.Center, TextColor = (Color)App.Current.Resources["GreyishBrown"]
            };

            label.SetBinding(Label.TextProperty, Settings.DeviceLanguage == "en" ? "PropertyName" : "PropertyName_FR");
            label.BindingContext = Bind_Context;


            stack.Children.Add(label);
            stack.Children.Add(entry);

            return(stack);
        }
 public void Add(ProductProperty item)
 {
     //var comm = this.GetCommand("sp_HtmlPage_Insert");
     //if (comm == null) return;
     //comm.AddParameter<string>(this.Factory, "HtmlPageTitle", item.HtmlPageTitle);
     //comm.AddParameter<string>(this.Factory, "HtmlPageShortName", item.HtmlPageShortName);
     //comm.AddParameter<string>(this.Factory, "HtmlPageSummary", item.HtmlPageSummary);
     //comm.AddParameter<string>(this.Factory, "HtmlPageDescription", item.HtmlPageDescription);
     //comm.AddParameter<string>(this.Factory, "HtmlPageKeyword", item.HtmlPageKeyword);
     //comm.AddParameter<string>(this.Factory, "HtmlPageBody", item.HtmlPageBody);
     //comm.AddParameter<int>(this.Factory, "OrderNo", item.OrderNo);
     //comm.AddParameter<bool>(this.Factory, "IsActive", item.IsActive);
     //comm.AddParameter<string>(this.Factory, "HtmlPageImage", item.HtmlPageImage);
     //comm.AddParameter<string>(this.Factory, "CreateBy", item.CreateBy);
     //comm.AddParameter<string>(this.Factory, "Culture", Culture);
     //comm.SafeExecuteNonQuery();
     throw new NotImplementedException();
 }
        public static ProductProperty PopulatePropertyFromIDataReader(IDataReader dr)
        {
            ProductProperty property = new ProductProperty();

            property.PropertyID        = DataRecordHelper.GetInt32(dr, "PropertyID");
            property.PropertyName      = DataRecordHelper.GetString(dr, "PropertyName");
            property.PropertyDesc      = DataRecordHelper.GetString(dr, "PropertyDesc");
            property.CategoryID        = DataRecordHelper.GetInt32(dr, "CategoryID");
            property.DimensionEnabled  = (ComponentStatus)DataRecordHelper.GetInt32(dr, "DimensionEnabled");
            property.SubCategoryHidden = (SubCategoryHiddenType)DataRecordHelper.GetInt32(dr, "SubCategoryHidden");
            property.DisplayOrder      = DataRecordHelper.GetInt32(dr, "DisplayOrder");
            property.PropertyStatus    = (ComponentStatus)DataRecordHelper.GetInt32(dr, "PropertyStatus");
            property.CreateTime        = DataRecordHelper.GetDateTime(dr, "CreateTime");
            property.CreateUser        = DataRecordHelper.GetInt32(dr, "CreateUser");
            property.UpdateTime        = DataRecordHelper.GetDateTime(dr, "UpdateTime");
            property.UpdateUser        = DataRecordHelper.GetInt32(dr, "UpdateUser");
            return(property);
        }
示例#20
0
        private void UpdateProductProperties(Product currentProduct, Product newProduct, ProductDefinition productDefinition)
        {
            if (productDefinition == null)
            {
                return;
            }

            if (currentProduct.ProductDefinition.Name != productDefinition.Name)
            {
                currentProduct.ProductDefinition = productDefinition;
            }

            var newProductProperties = newProduct.ProductProperties;

            foreach (var newProperty in newProductProperties)
            {
                var currentProductProperty = _currentProductsProperties.SingleOrDefault(
                    x => !x.ProductDefinitionField.Deleted && (x.ProductDefinitionField.Name == newProperty.ProductDefinitionField.Name));

                if (currentProductProperty != null) // Update
                {
                    currentProductProperty.Value = newProperty.Value;
                    _session.Update(currentProductProperty);
                }
                else // Insert
                {
                    var productDefinitionField =
                        _currentProductProductDefinitionFields
                        .SingleOrDefault(x => x.Name == newProperty.ProductDefinitionField.Name);

                    if (productDefinitionField != null) // Field exist, insert it.
                    {
                        currentProductProperty = new ProductProperty
                        {
                            ProductDefinitionField = productDefinitionField,
                            Value = newProperty.Value
                        };
                        currentProduct.AddProductProperty(currentProductProperty);
                        _session.Insert(currentProductProperty);
                    }
                }
            }
        }
 public void HandleUpdate(UpdateProductCommand command, IAppUnitOfWorkFactory uowFactory)
 {
     using (IAppUnitOfWork uow = uowFactory.Create())
     {
         Product product = uow.ProductRepository.Get(command.ProductId, Product.IncludeAll);
         Company company = uow.CompanyRepository.Get(command.CompanyId);
         if (company == null)
         {
             throw new DomainException("The assigned company not found");
         }
         User updater = uow.Users.FirstOrDefault(u => u.Id == command.UpdatedByUserId);
         if (updater == null)
         {
             throw new DomainException("Can not find updater");
         }
         // Delete properties
         foreach (ProductProperty removedProperty in product.Properties.Where(oldP => !command.Properties.Any(newP => newP.Id == oldP.Id)).ToList())
         {
             product.Properties.Remove(removedProperty);
             uow.ProductPropertyRepository.Remove(removedProperty);
         }
         // Update existing properties
         foreach (ProductProperty existProperty in product.Properties)
         {
             ProductProperty updatedProperty = command.Properties.SingleOrDefault(pp => pp.Id == existProperty.Id);
             existProperty.Name  = updatedProperty.Name;
             existProperty.Value = updatedProperty.Value;
         }
         // Add new properties
         foreach (ProductProperty property in command.Properties.Where(pp => pp.Id == 0))
         {
             product.Properties.Add(property);
         }
         product.Company   = company;
         product.Name      = command.Name;
         product.Comment   = command.Comment;
         product.Quantity  = command.Quantity;
         product.Sku       = command.Sku;
         product.IsActive  = command.IsActive;
         product.UpdatedAt = DateTime.Now;
         uow.SaveChanges();
     }
 }
示例#22
0
    void BindData()
    {
        ProductCategory category = ProductCategories.GetCategory(id);
        ProductCategory parent   = null;
        ProductProperty property = null;

        if (category != null)
        {
            btnPost.Text         = "修改";
            txtCategoryName.Text = category.CategoryName;
            txtCategoryDesc.Text = category.CategoryDesc;
            txtDisplayOrder.Text = category.DisplayOrder.ToString();
            parent   = ProductCategories.GetCategory(category.ParentID);
            property = ProductProperties.GetProperty(category.PropertyID);
        }
        if (parent == null)
        {
            parent = ProductCategories.GetCategory(parentID);
        }
        if (parent != null)
        {
            ltParCategory.Text     = parent.CategoryName;
            ltParCategoryDesc.Text = parent.CategoryDesc;
        }
        else
        {
            parentName.Visible = false;
            parentDesc.Visible = false;
        }
        if (property == null)
        {
            property = ProductProperties.GetProperty(propertyID);
        }
        if (property != null)
        {
            ltPropertyName.Text = property.PropertyName;
        }
        else
        {
            propertyName.Visible = false;
        }
    }
        public async Task AddOrUpdateProductPropertyAsync(ProductProperty property, [Validate(true, 36, 36)] string productKey)
        {
            var keyValidation      = productKey.Validate();
            var propertyValidation = property.Validate();

            if (keyValidation.IsValid() && propertyValidation.IsValid())
            {
                var product = await _repository.GetProductByKeyAsync(productKey);

                if (product != null)
                {
                    if (product.Properties.Select(p => p.Name).Contains(property.Name))
                    {
                        product.Properties.ForEach(p =>
                        {
                            if (p.Name == property.Name)
                            {
                                p.Value = property.Value;
                            }
                        });
                    }
                    else
                    {
                        product.Properties.Add(property);
                    }

                    product.ModifiedOn = DateTime.Now;

                    await _repository.UpdateProductAsync(product, productKey);

                    var args = new AddOrUpdateProductPropertyEventArgs {
                        ProductKey = productKey, Property = property
                    };

                    PropertyAddedOrUpdatedInProduct?.Invoke(this, args);
                }
            }
            else
            {
                throw new EntityException(keyValidation.Aggregate(propertyValidation));
            }
        }
 protected void btnDelete_Click(System.Object sender, System.Web.UI.ImageClickEventArgs e)
 {
     if (this.lstDefaultValue.Items.Count > 0)
     {
         ProductProperty prop = new ProductProperty();
         prop = MTApp.CatalogServices.ProductProperties.Find((long)ViewState["ID"]);
         if (prop != null)
         {
             long choiceId           = long.Parse(lstDefaultValue.SelectedValue);
             ProductPropertyChoice c = prop.Choices.Where(y => y.Id == choiceId).FirstOrDefault();
             if (c != null)
             {
                 prop.Choices.Remove(c);
                 MTApp.CatalogServices.ProductProperties.Update(prop);
                 localProperty = prop;
             }
             PopulateMultipleChoice(prop);
         }
     }
 }
示例#25
0
        /// <summary>
        /// Add the specified object.
        /// </summary>
        /// <param name="productProperty">product property object.</param>
        /// <returns>Add the specified</returns>
        public bool Add(ProductProperty productProperty)
        {
            using (var data = new themanorContext())
            {
                bool rt = false;
                try
                {
                    data.ProductProperty.Add(productProperty);
                    data.SaveChanges();

                    rt = true;
                }
                catch (Exception)
                {
                    rt = false;
                }

                return(rt);
            }
        }
示例#26
0
        // List or Find Single
        public override string GetAction(string parameters, System.Collections.Specialized.NameValueCollection querystring)
        {
            string data = string.Empty;

            if (string.Empty == (parameters ?? string.Empty))
            {
                // List
                ApiResponse <List <ProductPropertyDTO> > response = new ApiResponse <List <ProductPropertyDTO> >();

                List <ProductProperty>    results = MTApp.CatalogServices.ProductProperties.FindAll();
                List <ProductPropertyDTO> dto     = new List <ProductPropertyDTO>();

                foreach (ProductProperty item in results)
                {
                    dto.Add(item.ToDto());
                }
                response.Content = dto;
                data             = MerchantTribe.Web.Json.ObjectToJson(response);
            }
            else
            {
                // Find One Specific Category
                ApiResponse <ProductPropertyDTO> response = new ApiResponse <ProductPropertyDTO>();
                string ids = FirstParameter(parameters);
                long   id  = 0;
                long.TryParse(ids, out id);
                ProductProperty item = MTApp.CatalogServices.ProductProperties.Find(id);
                if (item == null)
                {
                    response.Errors.Add(new ApiError("NULL", "Could not locate that item. Check id and try again."));
                }
                else
                {
                    response.Content = item.ToDto();
                }
                data = MerchantTribe.Web.Json.ObjectToJson(response);
            }

            return(data);
        }
示例#27
0
        /// <summary>
        /// 获取编辑时使用的Html
        /// </summary>
        /// <param name="property">商品属性</param>
        /// <param name="category">商品类目</param>
        /// <returns></returns>
        public static HtmlString GetEditHtml(this ProductProperty property, ProductCategory category)
        {
            var    templateManager = Application.Ioc.Resolve <TemplateManager>();
            var    categoryManager = Application.Ioc.Resolve <ProductCategoryManager>();
            var    propertyValues  = property.OrderedPropertyValues().ToList();
            string templatePath    = null;

            if (property.ControlType == ProductPropertyControlType.TextBox)
            {
                // 文本框
                templatePath = "shopping.product/property_editor.textbox.html";
            }
            else if (property.ControlType == ProductPropertyControlType.CheckBox)
            {
                // 多选框
                templatePath = "shopping.product/property_editor.checkbox.html";
            }
            else if (property.ControlType == ProductPropertyControlType.RadioButton)
            {
                // 单选按钮
                templatePath = "shopping.product/property_editor.radiobutton.html";
            }
            else if (property.ControlType == ProductPropertyControlType.DropdownList)
            {
                // 下拉框
                templatePath = "shopping.product/property_editor.dropdownlist.html";
            }
            else if (property.ControlType == ProductPropertyControlType.EditableDropdownList)
            {
                // 可编辑的下拉框
                templatePath = "shopping.product/property_editor.editable_dropdownlist.html";
            }
            else
            {
                throw new NotSupportedException(string.Format(
                                                    "unsupported property control type {0}", property.ControlType));
            }
            return(new HtmlString(templateManager.RenderTemplate(
                                      templatePath, new { property, propertyValues, category })));
        }
示例#28
0
        /// <summary>
        /// Gets the type of the property by.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>the type of the property</returns>
        public List <ProductProperty> GetPropertyByType(string type)
        {
            using (var data = new themanorContext())
            {
                try
                {
                    //// First, check the cache
                    List <ProductProperty> c_gen = new List <ProductProperty>();

                    if (c_gen == null)
                    {
                        c_gen = new List <ProductProperty>();
                        var lst = (from pp in data.ProductProperty
                                   group pp by new { pp.Type, pp.Value, pp.Name } into gpp
                                   select new { Type = gpp.Key.Type, Name = gpp.Key.Name, Value = gpp.Key.Value }).Where(c => c.Type == type).ToList();

                        if (lst.Count > 0)
                        {
                            foreach (var it in lst)
                            {
                                ProductProperty c_p = new ProductProperty();
                                c_p.Name      = it.Name;
                                c_p.Value     = it.Value;
                                c_p.Type      = it.Type;
                                c_p.ProId     = 999999;
                                c_p.ProductId = 999999;
                                c_gen.Add(c_p);
                            }
                        }
                    }

                    return(c_gen);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
        public void Add(ProductProperty item, string Culture)
        {
            var comm = this.GetCommand("sp_ProductProperty_Insert");

            if (comm == null)
            {
                return;
            }
            comm.AddParameter <string>(this.Factory, "ProductPropertyTitle", item.ProductPropertyTitle);
            comm.AddParameter <string>(this.Factory, "ProductPropertyBody", item.ProductPropertyBody);
            comm.AddParameter <string>(this.Factory, "ProductCode", item.ProductCode);
            comm.AddParameter <string>(this.Factory, "ProductName", item.ProductName);
            comm.AddParameter <int>(this.Factory, "OrderNo", item.OrderNo);

            comm.AddParameter <bool>(this.Factory, "IsActive", item.IsActive);
            comm.AddParameter <int>(this.Factory, "ProducerId", item.ProducerId);
            comm.AddParameter <int>(this.Factory, "PrdCategoryId", item.PrdCategoryId);
            comm.AddParameter <string>(this.Factory, "ShortName", item.ShortName);
            comm.AddParameter <string>(this.Factory, "Culture", Culture);
            comm.SafeExecuteNonQuery();
            //throw new NotImplementedException();
        }
        private void DisplayProperControls(ProductProperty prop)
        {
            ProductPropertyType typeCode = prop.TypeCode;

            this.pnlChoiceControls.Visible = false;
            pnlCultureCode.Visible         = false;
            this.DefaultDate.Visible       = false;

            switch (typeCode)
            {
            case ProductPropertyType.CurrencyField:
                pnlCultureCode.Visible    = true;
                DefaultValueField.Visible = true;
                lstDefaultValue.Visible   = false;
                ChoiceNote.InnerText      = "Default Value";
                break;

            case ProductPropertyType.DateField:
                DefaultValueField.Visible = false;
                lstDefaultValue.Visible   = false;
                this.DefaultDate.Visible  = true;
                ChoiceNote.InnerText      = "Default Value";
                break;

            case ProductPropertyType.MultipleChoiceField:
                lstDefaultValue.Visible   = true;
                DefaultValueField.Visible = false;
                PopulateMultipleChoice(prop);
                ChoiceNote.InnerText           = "To select a default simply select the item in the list before you hit save.";
                this.pnlChoiceControls.Visible = true;
                break;

            case ProductPropertyType.TextField:
                DefaultValueField.Visible = true;
                lstDefaultValue.Visible   = false;
                ChoiceNote.InnerText      = "Default Value";
                break;
            }
        }
示例#31
0
        public bool DeleteContent(string productId)
        {
            try
            {
                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                Product      product      = new Product(siteSettings.SiteId, Convert.ToInt32(productId));

                if (product != null && product.ProductId != -1)
                {
                    ProductHelper.DeleteFolder(siteSettings.SiteId, product.ProductId);

                    ContentMedia.DeleteByContent(product.ProductGuid);
                    ShoppingCartItem.DeleteByProduct(product.ProductId);

                    var listAtributes = ContentAttribute.GetByContentAsc(product.ProductGuid);
                    foreach (ContentAttribute item in listAtributes)
                    {
                        ContentLanguage.DeleteByContent(item.Guid);
                    }
                    ContentAttribute.DeleteByContent(product.ProductGuid);
                    ContentLanguage.DeleteByContent(product.ProductGuid);

                    ProductProperty.DeleteByProduct(product.ProductId);
                    FriendlyUrl.DeleteByPageGuid(product.ProductGuid);

                    ProductComment.DeleteByProduct(product.ProductId);
                    TagItem.DeleteByItem(product.ProductGuid);

                    FileAttachment.DeleteByItem(product.ProductGuid);
                    RelatedItem.DeleteByItem(product.ProductGuid);

                    product.Delete();
                }
            }
            catch (Exception) { return(false); }

            return(true);
        }
示例#32
0
        public void AddProperty(Guid productID, string propertyName, string propertyValue, bool isImportant)
        {
            using (ShopDataContext db = new ShopDataContext())
            {
                var prod = db.Products.FirstOrDefault(p => p.ProductID == productID);
                BL.ProductProperty pr = new ProductProperty()
                                            {
                                                PropertyName = propertyName,
                                                PropertyValue = propertyValue,
                                                IsImportant = isImportant,
                                                PropertyID = Guid.NewGuid()
                                            };

                BL.ProductsRefProperty propRef = new ProductsRefProperty()
                                                     {
                                                         ID = Guid.NewGuid(),
                                                         ProductID = prod.ProductID,
                                                         ProductPropertiesID = pr.PropertyID
                                                     };

                switch (propertyName)
                {
                    case BL.ProductPropertyConstants.ProductPhotoOriginal:
                        propRef.Sort = prod.ProductProperties.Count(p => p.PropertyName == BL.ProductPropertyConstants.ProductPhotoOriginal);
                        break;
                    case BL.ProductPropertyConstants.ProductPhotoPreview:
                        propRef.Sort = 0;
                        break;
                    case BL.ProductPropertyConstants.ProductDescription:
                        propRef.Sort = 0;
                        break;
                    default:
                        propRef.Sort = prod.ProductProperties.Count(p =>
                                             p.PropertyName != BL.ProductPropertyConstants.ProductDescription
                                             && p.PropertyName != BL.ProductPropertyConstants.ProductPhotoOriginal
                                             && p.PropertyName != BL.ProductPropertyConstants.ProductPhotoPreview);
                        break;
                }

                prod.ProductProperties.Add(pr);
                prod.ProductsRefProperies.Add(propRef);
                db.SubmitChanges();
            }
        }
示例#33
0
文件: Products.cs 项目: adizka/iShop
        public void CopyProperties(Guid fromID, Guid toID)
        {
            using (ShopDataContext db = new ShopDataContext())
            {
                var fromProd = db.Products.First(p => p.ProductID == fromID);
                var toProd = db.Products.First(p => p.ProductID == toID);

                List<BL.ProductProperty> newProps = new List<BL.ProductProperty>();
                List<BL.ProductsRefProperty> newRefs = new List<ProductsRefProperty>();

                foreach (var item in fromProd.ProductProperties.Where(p =>
                        p.PropertyName != ProductPropertyConstants.ProductPhotoPreview
                        && p.PropertyName != ProductPropertyConstants.ProductPhotoOriginal
                        && p.PropertyName != ProductPropertyConstants.ProductDescription
                        && p.PropertyName != ProductPropertyConstants.ProductPhotoOriginal2
                        && p.PropertyName != ProductPropertyConstants.ProductPhotoOriginal3).OrderBy(pp => pp.Sort))
                {
                    var newProp = new ProductProperty()
                    {
                        IsImportant = item.IsImportant,
                        PropertyID = Guid.NewGuid(),
                        PropertyName = item.PropertyName,
                        PropertyValue = item.PropertyValue,
                        Sort = newProps.Count
                    };
                    newProps.Add(newProp);
                    newRefs.Add(new ProductsRefProperty()
                    {
                        ID = Guid.NewGuid(),
                        ProductPropertiesID = newProp.PropertyID,
                        Sort = newRefs.Count
                    });
                }
                toProd.ProductProperties.AddRange(newProps);
                toProd.ProductsRefProperies.AddRange(newRefs);

                db.SubmitChanges();
            }
        }
示例#34
0
        /// <summary>
        /// Копирование продукта внутри того же класса с заданием
        /// новой версии. Копируются внешние и внутренние свойства 
        /// продукта. Можно указать новое значение словаря _dictNomen.
        /// </summary>
        /// <param name="oldProductID"></param>
        /// <param name="newVersion"></param>
        /// <returns>Guid созданного при копировании продукта</returns>
        public Guid CopyProduct(Guid oldProductID, int newVersion, Guid newDictNomen, Guid userID)
        {
            /* создать запись в dbo.Products */
            Guid newProductID;
            Product newProduct, oldProduct;

            using (CommonDomain commonDomain = new CommonDomain())
            {
                // копируем запись в таблице Product
                oldProduct = commonDomain.Products.SingleOrDefault(p => p.ID == oldProductID);
                newProductID = commonDomain.AddNewProduct(oldProductID, true, Guid.Empty.Equals(newDictNomen) ? oldProduct._dictNomenID.Value : newDictNomen, userID);
                newProduct = commonDomain.Products.SingleOrDefault(p => p.ID == newProductID);

                // копируем ссылки на словари
                newProduct._dictNomen1ID = oldProduct._dictNomen1ID;
                newProduct._dictPVDID = oldProduct._dictPVDID;
                newProduct._dictSFID = oldProduct._dictSFID;
                newProduct._dictUMID = oldProduct._dictUMID;

                /*newProduct.cod_Asp = oldProduct.cod_Asp;
                newProduct.cod_Nomen_Asp = oldProduct.cod_Nomen_Asp;
                newProduct.cod_Nomen1_Asp = oldProduct.cod_Nomen1_Asp;*/
                commonDomain.SubmitChanges();
            }

            /* скопировать все поля в dbo.ProductProperty */
            using (CommonDomain domain = new CommonDomain())
            {
                List<ProductProperty> props = domain.ProductProperties.Where(p => p.ProductID == oldProductID).ToList();
                foreach (ProductProperty prop in props)
                {
                    ProductProperty newProp = new ProductProperty();
                    newProp.ID = Guid.NewGuid();
                    newProp.PropertyID = prop.PropertyID;
                    newProp.ProductID = newProduct.ID;
                    newProp.Value = prop.Value;
                    if (prop.PropertyID == new Guid("BBE170B0-28E4-4738-B365-1038B03F4552")) // основная версия
                    {
                        newProp.Value = "0";
                    }
                    if (prop.PropertyID == new Guid("0789DB1A-9BAA-4574-B405-AE570C746C03")) // версия
                    {
                        newProp.Value = newVersion.ToString();
                    }
                    if (prop.PropertyID == new Guid("3EA753C8-2B06-41DA-B3DB-421D110B079E")) // дата изменения продукта
                    {
                        // управляется триггером
                        continue;
                    }
                    domain.ProductProperties.InsertOnSubmit(newProp);
                }
                domain.SubmitChanges();
            }

            /* вернуть ID созданного продукта */
            return newProductID;
        }
示例#35
0
        protected void SaveButton_Click(object sender, EventArgs e)
        {
            //if (this.IsNew)
            //{
                string version = null;
                string nomenValue = null;
                CustomValidator validator1 = null;
                CustomValidator validator2 = null;
                #region Get the @version
                foreach (RepeaterItem item in GeneralPropertyRepeater.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Guid id = new Guid((item.FindControl("HiddenID") as HiddenField).Value);
                        if (id == new Guid("0789DB1A-9BAA-4574-B405-AE570C746C03"))
                        {
                            EditControl editControl = item.FindControl("PropertyValueAdv") as EditControl;
                            if (!editControl.Validate()) return;
                            version = editControl.Value.ToString().Trim();
                            //version = (item.FindControl("PropertyValue") as TextBox).Text.Trim();
                            validator1 = item.FindControl("UniqueValueValidator") as CustomValidator;
                        }
                    }
                }
                #endregion
                #region Get the @nomenValue
                foreach (RepeaterItem item in DictionaryPropertyRepeater.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Guid dictId = new Guid((item.FindControl("HiddenTreeID") as HiddenField).Value);
                        if (dictId == new Guid("316C6BC7-D883-44C8-AAE0-602F49C73595"))
                        {
                            nomenValue = (item.FindControl("HiddenID") as HiddenField).Value;
                            validator2 = item.FindControl("UniqueValueValidator") as CustomValidator;
                        }
                    }
                }
                #endregion
                #region Check the unique @version && @nomenValue
                if (version != null && nomenValue != null && validator1 != null && validator2 != null)
                {
                    using (ProductProvider provider = new ProductProvider())
                    {
                        var q = from p in provider.Products
                                join pp in provider.ProductProperties on p.ID equals pp.ProductID
                                where pp.PropertyID == new Guid("0789DB1A-9BAA-4574-B405-AE570C746C03") //&& p.ID == this.RequestProductID
                                && pp.Value == version && p._dictNomenID == new Guid(nomenValue)
                                select p;
                        List<Product> list = q.ToList();
                        if (list.Count > 0 && this.IsNew)
                        {
                            validator1.IsValid = false;
                            validator2.IsValid = false;
                            return;
                        }
                        else if (list.Count > 0 && list.Where(p => p.ID == this.RequestProductID).Count() == 0)
                        {
                            validator1.IsValid = false;
                            validator2.IsValid = false;
                            return;
                        }
                    }
                }
                else
                {
                    return;
                }
                #endregion
                #region Check the main version canceling...
                string mainVersionValue = null;
                CustomValidator mainVersionValidator = null;
                foreach (RepeaterItem item in GeneralPropertyRepeater.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Guid id = new Guid((item.FindControl("HiddenID") as HiddenField).Value);
                        if (id == new Guid("bbe170b0-28e4-4738-b365-1038b03f4552"))
                        {
                            EditControl editControl = item.FindControl("PropertyValueAdv") as EditControl;
                            if (!editControl.Validate()) return;
                            mainVersionValue = editControl.Value.ToString().Trim();
                            mainVersionValidator = item.FindControl("UniqueValueValidator") as CustomValidator;
                        }
                    }
                }
                if (mainVersionValue != null && mainVersionValidator != null && !this.IsNew)
                {
                    using (ProductProvider provider = new ProductProvider())
                    {
                        var q = from p in provider.ProductProperties
                                where p.PropertyID == new Guid("bbe170b0-28e4-4738-b365-1038b03f4552")
                                && p.ProductID == this.RequestProductID
                                select p;
                        List<ProductProperty> list = q.ToList();
                        if (list.Count == 1)
                        {
                            // попытка изменить основную версию
                            if (list.First().Value == "1")
                            {
                                mainVersionValidator.IsValid = false;
                                return;
                            }
                        }
                    }
                }
                #endregion
                //}
            if (this.IsNew)
            {
                using (ProductProvider provider = new ProductProvider())
                {
                    Guid newID = provider.AddNewProduct(this.RequestProductID, User.ID);
                    if (this.IsWithConfs)
                    {
                        // копирование по аналогу вместе с составом
                        provider.CopyConfiguration(this.RequestProductID, newID, this.User.ID);
                    }
                    newProductID = newID;
                }
            }

            using (ProductProvider provider = new ProductProvider())
            {
                Product editedProduct = provider.GetProduct(RequestProductID);
                if (editedProduct.userID != User.ID)
                {
                    editedProduct.userID = User.ID;
                    provider.SubmitChanges();
                }
            }

            #region update dictionary values
            using (DictionaryProvider provider = new DictionaryProvider())
            {
                foreach (RepeaterItem item in DictionaryPropertyRepeater.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Guid dictId = new Guid((item.FindControl("HiddenTreeID") as HiddenField).Value);
                        string valueString = (item.FindControl("HiddenID") as HiddenField).Value;
                        DictionaryTree dict = provider.DictionaryTrees.Single(d => d.ID == dictId);
                        if (!string.IsNullOrEmpty(valueString) && !(new Guid(valueString).Equals(Guid.Empty)))
                        {
                            provider.SetProductDictioanryValue(this.RequestProductID, dict.FK, valueString.Trim(), User.ID);
                        }
                        else
                        {
                            provider.DeleteProductDictionaryValue(this.RequestProductID, dict.FK, User.ID);
                        }
                    }
                }
                provider.SubmitChanges();
            }
            #endregion

            #region update properties values
            using (ProductProvider provider = new ProductProvider())
            {
                bool settingMainVersion = false;

                foreach (RepeaterItem item in GeneralPropertyRepeater.Items)
                {
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        Guid id = new Guid((item.FindControl("HiddenID") as HiddenField).Value);
                        //string value = (item.FindControl("PropertyValue") as TextBox).Text.Trim();
                        EditControl editControl = item.FindControl("PropertyValueAdv") as EditControl;
                        if (!editControl.IsEmpty && !editControl.Validate())
                        {
                            continue;
                        }

                        // Если поле "Вес по приказу" не заполнено, то заполняем его из номенклатуры
                        if (id == new Guid("AC37F816-E4C1-4751-99ED-6180D7CCA142") && editControl.IsEmpty)
                        {
                            Product prod = provider.GetProduct(this.RequestProductID);
                            if (prod._dictNomen.pw.HasValue)
                            {
                                editControl.Value = prod._dictNomen.pw.Value.ToString(CultureInfo.InvariantCulture).Replace(".", ",");
                            }

                        }

                        if (editControl.IsEmpty)
                        {
                            ProductProperty prop = provider.ProductProperties.SingleOrDefault(pp => pp.PropertyID == id && pp.ProductID == this.RequestProductID);
                            if (prop != null)
                            {
                                provider.ProductProperties.DeleteOnSubmit(prop);
                                provider.SubmitChanges();
                            }
                            continue;
                        }

                        string value = editControl.Value.ToString().Trim();
                        if (editControl.ControlType == TypeEnum.Datetime)
                        {
                            DateTime dt = DateTime.ParseExact(value, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                            if (dt == DateTime.MinValue) value = string.Empty;
                            else value = dt.ToString("yyyy-MM-dd hh:mm:ss.fff");
                        }

                        // установка признака "Основная версия"
                        if (id == new Guid ("BBE170B0-28E4-4738-B365-1038B03F4552") && value == "1")
                        {
                            settingMainVersion = true;
                        }

                        ProductProperty property = provider.ProductProperties.SingleOrDefault(pp => pp.PropertyID == id && pp.ProductID == this.RequestProductID);
                        if (property != null)
                        {
                            if (property.Value != value)
                            {
                                Aspect.Utility.TraceHelper.Log(User.ID, "Продукт: {0}. Свойство изменино: {1}. Старое значение {2}. Новое значение {3}", this.RequestProductID, property.Property.Name, property.Value, value);
                            }
                            property.Value = value;
                        }
                        else
                        {
                            property = new ProductProperty()
                            {
                                ID = Guid.NewGuid(),
                                ProductID = this.RequestProductID,
                                PropertyID = id,
                                Value = value
                            };
                            provider.ProductProperties.InsertOnSubmit(property);
                            Property prop = provider.Properties.Single(p => p.ID == id);
                            Aspect.Utility.TraceHelper.Log(User.ID, "Продукт: {0}. Свойство изменино: {1}. Старое значение NULL. Новое значение {2}", this.RequestProductID, prop.Name, value);
                        }
                        provider.SubmitChanges();
                    }
                }

                // Переносим вес из продуктов в _dictNomen, если там он отсутствует (0 или null)
                if (settingMainVersion)
                {
                    try
                    {
                        // Пытаемся получить свойство с весом если оно есть
                        string raw_pw = (from p in provider.Products
                                      join pp in provider.ProductProperties on p.ID equals pp.ProductID
                                      where p.ID == this.RequestProductID && pp.PropertyID == new Guid("AC37F816-E4C1-4751-99ED-6180D7CCA142")
                                      select pp.Value).Single();
                        decimal prod_pw = Convert.ToDecimal(raw_pw.Replace(',', '.'), CultureInfo.InvariantCulture);

                        // Если свойство есть переносим его
                        if (prod_pw != 0)
                        {
                            _dictNomen dict = (from p in provider.Products
                                               join d in provider._dictNomens on p._dictNomenID equals d.ID
                                               where p.ID == this.RequestProductID
                                               select d).Single();
                            dict.pw = prod_pw;
                            provider.SubmitChanges();
                        }
                    }
                    catch
                    {
                        // перехватываем исключение, так как веса у продукта может вовсе и не быть
                    }
                }
            }
            #endregion

            if (this.IsNew)
            {
                // добавить свойство "пустой состав"
                if (!this.IsWithConfs)
                {
                    using (CommonDomain provider = new CommonDomain())
                    {
                        var properties = from props in provider.ProductProperties
                                         where props.PropertyID == new Guid("00ACC1C7-6857-4317-8713-8B8D9479C5CC") // Свойство "Наличие состава"
                                         && props.ProductID == RequestProductID
                                         select props;

                        if (properties.Count() > 1)
                        {
                            // если несколько одинаковых свойств - генерируем исключение
                            throw new Exception("У продукта не может быть больше одного свойства \"Наличие состава\"!");
                        }
                        else if (properties.Count() == 1)
                        {
                            // если только одно свойство - редактируем его, и сохраняемся
                            properties.First().Value = "-";
                        } else
                        {
                            // если нет ниодного свойства, создаём его с нужным нам значеним
                            provider.ProductProperties.InsertOnSubmit(new ProductProperty()
                            {
                                ID = Guid.NewGuid(),
                                ProductID = RequestProductID,
                                PropertyID = new Guid("00ACC1C7-6857-4317-8713-8B8D9479C5CC"),
                                Value = "-"
                            });

                        }
                        provider.SubmitChanges();
                    }
                }

                // перенаправить на редактирование
                Response.Redirect(string.Format("Edit.aspx?ID={0}", this.RequestProductID));
                return;
            }
            if(Page.IsValid) this.DataLoad();
        }
示例#36
0
        /// <summary>
        /// Установка "Веса по приказу" для первой версии продукта.
        /// </summary>
        /// <param name="dictNomenID"></param>
        /// <param name="newClassificationTreeID"></param>
        public void SetProductWeight(Guid dictNomenID, decimal weight)
        {
            // находим единственный продукт, соответствующий данной номенклатуре
            // если продуктов несколько вырабатается исключение
            Guid productID = Products.Where(p => p._dictNomenID == dictNomenID).Select(p => p.ID).Single();

            Guid weightPropertyID = new Guid ("AC37F816-E4C1-4751-99ED-6180D7CCA142");
            try
            {
                // ищем для продукта свойство "Вес по приказу" и устанавливаем его
                ProductProperty weightProperty = ProductProperties.Where(pp => pp.ProductID == productID && pp.PropertyID == weightPropertyID).Single();
                weightProperty.Value = weight.ToString().Replace(".", ",");
            }
            catch
            {
                // если свойство не найдено, создаём его и устанавливаем
                ProductProperty weightProperty = new ProductProperty();
                weightProperty.ID = Guid.NewGuid();
                weightProperty.ProductID = productID;
                weightProperty.PropertyID = weightPropertyID;
                weightProperty.Value = weight.ToString().Replace(".", ",");
                ProductProperties.InsertOnSubmit(weightProperty);
            }

            // подтверждаем изменения
            SubmitChanges();
        }
示例#37
0
        protected void Save_Click(object sender, EventArgs e)
        {
            this.Validate();
            if (this.IsValid)
            {
                // Проверяем, является ли продукт основной версией
                ProductProvider productProvider = new ProductProvider();
                if (productProvider.IsMainVersion(this.ProductID))
                {
                    LabelErrorMessage.Text = "[ ! ] Содержащий данную спецификацию продукт является основной версией. Сохранение отменено.";
                    return;
                }

                JavaScriptSerializer js = new JavaScriptSerializer();
                List<Dictionary<string, string>> rows = js.Deserialize<List<Dictionary<string, string>>>(hiddenStoreData.Value.ToString());
                EditConfigurationProvider provider = new EditConfigurationProvider();
                List<GridColumn> gridColumns = provider.GetGridColumns();

                // Сохраняем данные, полученные от пользователя в списке конфигураций
                List<Aspect.Domain.Configuration> result = new List<Aspect.Domain.Configuration>();
                #region convert Request to list of Configuration
                foreach (Dictionary<string, string> row in rows)
                {
                    Guid productID = new Guid(row["ID"]);
                    Aspect.Domain.Configuration conf = new Aspect.Domain.Configuration();
                    conf.ID = new Guid(row["ConfID"]);
                    conf.ProductID = productID;
                    conf.ProductOwnerID = this.ProductID;
                    conf.UserID = this.User.ID;

                    foreach (GridColumn column in gridColumns)
                    {
                        if (column is EditableGridColumn)
                        {
                            System.Reflection.PropertyInfo prop = typeof(Aspect.Domain.Configuration).GetProperty(column.DataItem);
                            if (prop.PropertyType == typeof(decimal) || prop.PropertyType == typeof(Nullable<decimal>))
                            {
                                prop.SetValue(conf, Convert.ToDecimal(row[column.DataItem]), null);
                            }
                            else if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(Nullable<int>))
                            {
                                prop.SetValue(conf, Convert.ToInt32(row[column.DataItem]), null);
                            }
                            else if (prop.PropertyType == typeof(Guid) || prop.PropertyType == typeof(Nullable<Guid>))
                            {
                                prop.SetValue(conf, new Guid(row[column.DataItem]), null);
                            }
                            else if (prop.PropertyType == typeof(Boolean) || prop.PropertyType == typeof(Nullable<Boolean>))
                            {
                                prop.SetValue(conf, Convert.ToBoolean(row[column.DataItem]), null);
                            }
                            else
                            {
                                prop.SetValue(conf, row[column.DataItem], null);
                            }
                        }
                    }

                    result.Add(conf);
                }
                #endregion

                using (CommonDomain domain = new CommonDomain())
                {
                    // Проверка на включение материалов
                    #region check_including_material
                    foreach (Aspect.Domain.Configuration conf in result)
                    {
                        Product prod = domain.Products.Single(p => p.ID == conf.ProductID);
                        if (prod._dictNomen.cod >= 1000000)
                        {
                            LabelErrorMessage.Text = "[ ! ] Обнаружены материалы в спецификации. Сохранение отменино.";
                            return;
                        }
                    }
                    #endregion

                    // Проверка на циклы
                    #region check_for_cycles
                    Guid dictNomenID = (Guid) (from p in domain.Products
                                               where p.ID == this.ProductID
                                               select p).Single()._dictNomenID;
                    foreach (Aspect.Domain.Configuration conf in result)
                    {
                        Product prod = domain.Products.Where(p => p.ID == conf.ProductID).Single();
                        if (dictNomenID == prod._dictNomenID)
                        {
                            LabelErrorMessage.Text = "[ ! ] Обнаружены циклические включения продуктов в спецификацию. Сохранение отменино.";
                            return;
                        }
                        if (fnCheckContains(dictNomenID, prod.ID))
                        {
                            LabelErrorMessage.Text = "[ ! ] Обнаружены циклические включения продуктов в спецификацию. Сохранение отменино.";
                            return;
                        }
                    }
                    #endregion
                }

                provider.SaveProductConfiguration(this.ProductID, result, this.User.ID);

                // установка признака "Основная версия"
                if (MadeBasicVersion.Checked)
                {
                    productProvider.SetMainVersion(this.User.ID, new List<Guid>{ProductID});
                }

                // устанавливаем основание изменений
                if (!String.IsNullOrEmpty(ReasonChanges.Text))
                {
                    ProductProperty reasonProperty = productProvider.ProductProperties.SingleOrDefault(
                        pr => pr.PropertyID == new Guid("C266B994-9740-41F6-94DD-07EA5B5FA34A")
                        && pr.ProductID == this.ProductID);

                    if (reasonProperty == null)
                    {
                        reasonProperty = new ProductProperty()
                        {
                            ID = Guid.NewGuid(),
                            PropertyID = new Guid("C266B994-9740-41F6-94DD-07EA5B5FA34A"),
                            ProductID = this.ProductID,
                            Value = ReasonChanges.Text
                        };
                        productProvider.ProductProperties.InsertOnSubmit(reasonProperty);
                    }
                    else
                    {
                        reasonProperty.Value = ReasonChanges.Text;
                    }
                    productProvider.SubmitChanges();
                }

                // Очищаем сообщение об ошибке и обновляем данные о спецификации
                LabelErrorMessage.Text = "";
                this.BindGridColumns2();
                this.BindData(new Dictionary<Guid, Guid>());
            }
        }
示例#38
0
        public void AddProductProperty(string propertyName, string propertyValue, Guid productID)
        {
            using (ShopDataContext db = new ShopDataContext())
            {
                BL.Product prod = db.Products.FirstOrDefault(p => p.ProductID == productID);
                if (prod == null)
                    return;

                BL.ProductsRefProperty refProp = new ProductsRefProperty()
                {
                    ID = Guid.NewGuid(),
                    Sort = prod.ProductsRefProperies.Count,
                    ProductID = productID
                };

                BL.ProductProperty prop = new ProductProperty()
                {
                    IsImportant = true,
                    PropertyID = Guid.NewGuid(),
                    PropertyName = BL.ProductPropertyConstants.ProductDescription,
                    PropertyValue = propertyValue,
                    Sort = prod.ProductProperties.Count,
                };
                prop.ProductsRefProperies.Add(refProp);
                prod.ProductProperties.Add(prop);
                db.SubmitChanges();
            }
        }
示例#39
0
        public bool AddProperties(Guid productID, List<BL.ProductProperty> props)
        {
            bool allRight = false;
            using (ShopDataContext db = new ShopDataContext())
            {
                BL.Product prod = db.Products.FirstOrDefault(p => p.ProductID == productID);
                if (prod != null)
                {
                    int index = 0;
                    foreach (var item in props)
                    {
                        BL.ProductProperty pr = new ProductProperty()
                                                    {
                                                        Sort = item.Sort,
                                                        PropertyName = item.PropertyName,
                                                        PropertyValue = item.PropertyValue,
                                                        IsImportant = item.IsImportant,
                                                        PropertyID = Guid.NewGuid()
                                                    };
                        prod.ProductProperties.Add(pr);
                        BL.ProductsRefProperty pref = new ProductsRefProperty()
                        {
                            ProductPropertiesID = pr.PropertyID,
                            Sort = index,
                            ID = Guid.NewGuid()
                        };
                        prod.ProductsRefProperies.Add(pref);

                        index++;
                    }
                    db.SubmitChanges();
                    allRight = true;
                }
            }
            return allRight;
        }