/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(ArrayList elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.CategoryCaption + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.Caption + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return(sb.ToString()); }
/// <summary> /// Exports properties given in the array list. /// </summary> /// <param name="elem">List of properties to export</param> /// <param name="webPart">WebPart instance with data</param> private string GetProperties(IEnumerable <IDataDefinitionItem> elem, WebPartInstance webPart) { StringBuilder sb = new StringBuilder(); // Iterate through all fields foreach (object o in elem) { FormCategoryInfo fci = o as FormCategoryInfo; if (fci != null) { // We have category now sb.Append(Environment.NewLine + fci.GetPropertyValue(FormCategoryPropertyEnum.Caption, MacroContext.CurrentResolver) + Environment.NewLine + Environment.NewLine + Environment.NewLine); } else { // Form element FormFieldInfo ffi = o as FormFieldInfo; if (ffi != null) { object value = webPart.GetValue(ffi.Name); sb.Append(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver) + ": " + (value == null ? "" : value.ToString()) + Environment.NewLine + Environment.NewLine); } } } return(sb.ToString()); }
public static List <IDataDefinitionItem> GetItemsToSync(string className) { var treeFormInfo = FormHelper.GetFormInfo("CMS.Tree", false); var documentFormInfo = FormHelper.GetFormInfo("CMS.Document", false); var formInfo = FormHelper.GetFormInfo(className, false); var systemCategory = new FormCategoryInfo { CategoryName = "System", }; var treeSystemItems = treeFormInfo.GetFields <FormFieldInfo>().Where(item => SystemFields.Contains(item.Name)); var documentSystemItems = documentFormInfo.GetFields <FormFieldInfo>().Where(item => SystemFields.Contains(item.Name)); var typeItems = formInfo.ItemsList.Where(item => { if (item is FormFieldInfo field) { // Do not include the ID field return(!field.PrimaryKey); } return(true); }); return(typeItems .Concat(new[] { systemCategory }) .Concat(treeSystemItems) .Concat(documentSystemItems) .ToList()); }
void form_OnAfterSave(object sender, EventArgs e) { if (mUIElementInfo != null) { XmlData data = new XmlData(); data.AllowMacros = true; // Store basic form data to XMLData structure DataRow drActual = form.DataRow; foreach (DataColumn dc in drActual.Table.Columns) { if ((dc.ColumnName != "CustomProperties") && (drActual[dc.ColumnName] != DBNull.Value) && (drActual[dc.ColumnName].ToString() != "")) { data[dc.ColumnName] = drActual[dc.ColumnName]; } // Append values from macro table object o = form.MacroTable[dc.ColumnName.ToLowerCSafe()]; if (o != null) { data[dc.ColumnName] = o; } } // Store category changes var categories = form.FormInformation.GetCategoryNames(); foreach (string category in categories) { FormCategoryInfo fci = form.FormInformation.GetFormCategory(category); if (ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.Collapsible, form.ContextResolver), false)) { bool collapsedByDefault = ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, form.ContextResolver), false); bool collapsed = form.IsCategoryCollapsed(category); if (collapsed != collapsedByDefault) { data[UIContextData.CATEGORYNAMEPREFIX + category] = collapsed; } } } data.MacroTable = form.MacroTable; // Add custom data XmlData customData = new XmlData(); customData.LoadData(ValidationHelper.GetString(drActual["CustomProperties"], String.Empty)); // Add (replace) default properties with custom data foreach (String col in customData.ColumnNames) { data[col] = customData[col]; } mUIElementInfo.ElementProperties = data.GetData(); mUIElementInfo.Update(); ShowChangesSaved(); } }
/// <summary> /// Creates category with variant attributes. /// </summary> /// <param name="optionsList">Product options</param> private void SetVariantAttributes(List <SKUInfo> optionsList) { // Get attributes category index - just before representing category var attrPos = editForm.FormInformation.ItemsList.FindIndex(f => (f is FormCategoryInfo) && ((FormCategoryInfo)f).CategoryName.EqualsCSafe("com.sku.representingcategory")); // Create attributes category var attCategory = new FormCategoryInfo() { CategoryName = "Attributes", IsDummy = true, }; attCategory.SetPropertyValue(FormCategoryPropertyEnum.Caption, HTMLHelper.HTMLEncode(GetString("com.variant.attributes"))); editForm.FormInformation.AddFormItem(attCategory, attrPos++); // Get variant categories var variantCategories = VariantHelper.GetProductVariantsCategories(ProductID, false); foreach (var category in variantCategories) { var option = optionsList.FirstOrDefault(o => o.SKUOptionCategoryID == category.CategoryID); if (option != null) { FormFieldInfo ffOption = new FormFieldInfo { Name = category.CategoryName, AllowEmpty = true, Size = 400, FieldType = FormFieldControlTypeEnum.LabelControl, DataType = FieldDataType.Text, IsDummyField = true, }; ffOption.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(option.SKUName))); // Show category live site display name instead of category display name in case it is available ffOption.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(category.CategoryTitle))); //Insert field to the form on specified position editForm.FormInformation.AddFormItem(ffOption, attrPos++); } } }
/// <summary> /// Creates category with variant attributes. /// </summary> /// <param name="optionsDs">Product options</param> private void SetVariantAttributes(IEnumerable <SKUInfo> optionsDs) { // Get attributes category index - just before representing category var attrPos = editForm.FormInformation.ItemsList.FindIndex(f => (f is FormCategoryInfo) && ((FormCategoryInfo)f).CategoryName.EqualsCSafe("com.sku.representingcategory")); // Create attributes category var attCategory = new FormCategoryInfo() { CategoryName = "Attributes", IsDummy = true, }; attCategory.SetPropertyValue(FormCategoryPropertyEnum.Caption, HTMLHelper.HTMLEncode(GetString("com.variant.attributes"))); editForm.FormInformation.AddFormItem(attCategory, attrPos++); foreach (var option in optionsDs) { if (option.Parent != null) { string categoryCodeName = option.Parent.Generalized.ObjectCodeName; options.Add(categoryCodeName, option); FormFieldInfo ffOption = new FormFieldInfo { Name = categoryCodeName, AllowEmpty = true, Size = 400, FieldType = FormFieldControlTypeEnum.LabelControl, DataType = FieldDataType.Text, IsDummyField = true, }; OptionCategoryInfo parentOptionCategory = (OptionCategoryInfo)option.Parent; ffOption.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(option.SKUName))); // Show category live site display name instead of category display name in case it is available ffOption.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(parentOptionCategory.CategoryTitle))); //Insert field to the form on specified position editForm.FormInformation.AddFormItem(ffOption, attrPos++); } } }
/// <summary> /// Initializes the form. /// </summary> /// <param name="basicForm">Form</param> /// <param name="dr">Data row with the data</param> /// <param name="fi">Form info</param> private void InitForm(BasicForm basicForm, DataRow dr, FormInfo fi) { if (basicForm != null) { basicForm.DataRow = dr; if (webPartInstance != null) { basicForm.MacroTable = webPartInstance.MacroTable; } else { basicForm.MacroTable = new Hashtable(StringComparer.InvariantCultureIgnoreCase); } if (!RequestHelper.IsPostBack() && (webPartInstance != null)) { fi = new FormInfo(fi.GetXmlDefinition()); // Load the collapsed/un-collapsed state of categories var categories = fi.GetCategoryNames(); foreach (string category in categories) { FormCategoryInfo fci = fi.GetFormCategory(category); if (ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.Collapsible, basicForm.ContextResolver), false) && ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, basicForm.ContextResolver), false) && ValidationHelper.GetBoolean(webPartInstance.GetValue("cat_open_" + category), false)) { fci.SetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, "false"); } } } basicForm.SubmitButton.Visible = false; basicForm.SiteName = SiteContext.CurrentSiteName; basicForm.FormInformation = fi; basicForm.ShowPrivateFields = true; basicForm.OnItemValidation += formElem_OnItemValidation; basicForm.ReloadData(); } }
/// <summary> /// Initializes the form. /// </summary> /// <param name="form">Form</param> /// <param name="dr">Data row with the data</param> /// <param name="fi">Form info</param> private void InitForm(BasicForm form, DataRow dr, FormInfo fi) { if (form != null) { form.DataRow = dr; if (webPartInstance != null) { form.MacroTable = webPartInstance.MacroTable; } else { form.MacroTable = new Hashtable(); } if (!RequestHelper.IsPostBack() && (webPartInstance != null)) { fi = new FormInfo(fi.GetXmlDefinition()); // Load the collapsed/un-collapsed state of categories var categories = fi.GetCategoryNames(); foreach (string category in categories) { FormCategoryInfo fci = fi.GetFormCategory(category); if (fci.CategoryCollapsible && fci.CategoryCollapsedByDefault && ValidationHelper.GetBoolean(webPartInstance.GetValue("cat_open_" + category), false)) { fci.CategoryCollapsedByDefault = false; } } } form.SubmitButton.Visible = false; form.SiteName = CMSContext.CurrentSiteName; form.FormInformation = fi; form.ShowPrivateFields = true; form.OnItemValidation += formElem_OnItemValidation; form.ReloadData(); } }
/// <summary> /// Saves collapsed/un-collapsed states of the categories /// </summary> /// <param name="basicForm">Form</param> private void SaveCategoryState(BasicForm basicForm) { // Save the collapsed/un-collapsed state of categories FormInfo fi = GetWebPartFormInfo(); var categories = fi.GetCategoryNames(); foreach (string category in categories) { FormCategoryInfo fci = fi.GetFormCategory(category); if (ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.Collapsible, basicForm.ContextResolver), false) && ValidationHelper.GetBoolean(fci.GetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, basicForm.ContextResolver), false)) { if (basicForm.IsCategoryCollapsed(category)) { webPartInstance.SetValue("cat_open_" + category, null); } else { webPartInstance.SetValue("cat_open_" + category, true); } } } }
/// <summary> /// Initializes controls for activity rule. /// </summary> /// <param name="selectedActivity">Activity selected in drop-down menu</param> private void InitActivitySettings(string selectedActivity) { // Init activity selector from edited object if any LoadEditedActivityRule(ref selectedActivity); string[] ignoredColumns = { "activitytype", "activitysiteid", "activityguid", "activityactivecontactid", "activityoriginalcontactid", "pagevisitid", "pagevisitactivityid", "searchid", "searchactivityid" }; string[] activitiesWithValue = { PredefinedActivityType.PURCHASE, PredefinedActivityType.PURCHASEDPRODUCT, PredefinedActivityType.RATING, PredefinedActivityType.POLL_VOTING, PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART }; // Get columns from OM_Activity (i.e. base table for all activities) ActivityTypeInfo ati = ActivityTypeInfoProvider.GetActivityTypeInfo(selectedActivity); var fi = new FormInfo(); // Get columns from additional table (if any) according to selected activity type bool extraFieldsAtEnd = true; FormInfo additionalFieldsForm = GetActivityAdditionalFields(selectedActivity, ref extraFieldsAtEnd); // Get the activity form elements FormInfo filterFieldsForm = FormHelper.GetFormInfo(ActivityInfo.OBJECT_TYPE, true); IList <IDataDefinitionItem> elements = filterFieldsForm.GetFormElements(true, false); FormCategoryInfo newCategory = null; foreach (IDataDefinitionItem elem in elements) { if (elem is FormCategoryInfo) { // Form category newCategory = (FormCategoryInfo)elem; } else if (elem is FormFieldInfo) { // Form field var ffi = (FormFieldInfo)elem; // Skip ignored columns if (ignoredColumns.Contains(ffi.Name.ToLowerCSafe())) { continue; } if ((!ffi.PrimaryKey) && (fi.GetFormField(ffi.Name) == null)) { // Skip fields with Guid data type if (ffi.DataType == FieldDataType.Guid) { continue; } // Sets control name based on given datatype of field. Can be overwritten if more proper control is available string controlName = GetControlNameForFieldDataType(ffi); if (!GetControlNameForActivities(ffi, ati, selectedActivity, activitiesWithValue, ref controlName)) { continue; } if (controlName != null) { // SKU selector for product ffi.Settings["controlname"] = controlName; ffi.Settings["allowempty"] = controlName.EqualsCSafe("skuselector", true); } // Ensure the category if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; // Extra fields at the beginning if ((!extraFieldsAtEnd) && (additionalFieldsForm != null)) { AddExtraActivityFields(ignoredColumns, fi, additionalFieldsForm); additionalFieldsForm = null; } } fi.AddFormItem(ffi); } } } // Extra fields at the end if ((extraFieldsAtEnd) && (additionalFieldsForm != null)) { // Ensure the category for extra fields if (newCategory != null) { fi.AddFormCategory(newCategory); } AddExtraActivityFields(ignoredColumns, fi, additionalFieldsForm); } LoadActivityForm(fi, selectedActivity); }
private string UpdateFormCategory(FormCategoryInfo updatedCategoryInfo) { categoryEdit.CategoryInfo = updatedCategoryInfo; categoryEdit.Save(); updatedCategoryInfo.IsDummy = IsDummyField; updatedCategoryInfo.IsExtra = IsExtraField; if (String.IsNullOrEmpty(updatedCategoryInfo.GetPropertyValue(FormCategoryPropertyEnum.Caption))) { return GetString("TemplateDesigner.ErrorCategoryNameEmpty"); } updatedCategoryInfo.CategoryName = IsNewItemEdited ? ValidationHelper.GetCodeName(updatedCategoryInfo.GetPropertyValue(FormCategoryPropertyEnum.Caption)) : fci.CategoryName; if ((IsNewItemEdited || updatedCategoryInfo.CategoryName != fci.CategoryName) && FormInfo.GetCategoryNames().Exists(x => x == updatedCategoryInfo.CategoryName)) { return GetString("TemplateDesigner.ErrorExistingCategoryName"); } if (IsNewItemEdited) { // Insert new category InsertFormItem(updatedCategoryInfo); } else { // Update current FormInfo.UpdateFormCategory(fci.CategoryName, updatedCategoryInfo); } // No error occurred return null; }
/// <summary> /// Save selected field. /// </summary> private bool SaveSelectedField() { DataClassInfo dci = null; bool updateInherited = false; // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { // FormFieldInfo structure with data from updated form FormFieldInfo ffiUpdated = null; // FormCategoryInfo structure with data from updated form FormCategoryInfo fciUpdated = null; // For some types of forms initialize table manager string tableName = null; TableManager tm = null; if (IsMainForm) { switch (mMode) { // Do nothing for WebPart case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: { // Fill ClassInfo structure with data from database dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci != null) { // Set table name tableName = dci.ClassTableName; tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); } else { ShowError(GetString("fieldeditor.notablename")); return false; } } break; } } // Load current XML form definition if (!LoadFormDefinition()) { // Form definition was not loaded return false; } string error = null; switch (SelectedItemType) { case FieldEditorSelectedItemEnum.Field: // Fill FormFieldInfo structure with original data ffi = FormInfo.GetFormField(SelectedItemName); // Fill FormFieldInfo structure with updated form data ffiUpdated = FillFormFieldInfoStructure(ffi); try { error = UpdateFormField(tm, tableName, ffiUpdated); } catch (Exception ex) { EventLogProvider.LogException("FieldEditor", "SAVE", ex); // User friendly message for not null setting of column if (!IsNewItemEdited && ffi.AllowEmpty && !ffiUpdated.AllowEmpty) { ShowError(GetString("FieldEditor.ColumnNotAcceptNull"), ex.Message); } else { ShowError(GetString("general.saveerror"), ex.Message); } return false; } break; case FieldEditorSelectedItemEnum.Category: // Fill FormCategoryInfo structure with original data fci = FormInfo.GetFormCategory(SelectedItemName); // Initialize new FormCategoryInfo structure fciUpdated = new FormCategoryInfo(); error = UpdateFormCategory(fciUpdated); break; } if (!String.IsNullOrEmpty(error)) { ShowError(error); return false; } // Make changes in database if (SelectedItemType != 0) { // Get updated definition FormDefinition = FormInfo.GetXmlDefinition(); if (IsMainForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: error = UpdateWebPartProperties(); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: error = UpdateDependencies(dci, tm, ffiUpdated, out updateInherited); break; } } if (!String.IsNullOrEmpty(error)) { ShowError("[FieldEditor.SaveSelectedField()]: " + error); return false; } } // All done and new item, fire OnFieldCreated event RaiseOnFieldCreated(ffiUpdated); // Reload field/category switch (SelectedItemType) { case FieldEditorSelectedItemEnum.Category: Reload(categPreffix + fciUpdated.CategoryName); break; case FieldEditorSelectedItemEnum.Field: Reload(fieldPreffix + ffiUpdated.Name); break; } // Commit the transaction tr.Commit(); } // Update inherited classes with new fields if (updateInherited) { FormHelper.UpdateInheritedClasses(dci); } return true; }
/// <summary> /// Fill form with selected category data. /// </summary> private void LoadSelectedCategory() { plcField.Visible = false; plcCategory.Visible = true; fci = FormInfo.GetFormCategory(SelectedItemName); categoryEdit.CategoryInfo = fci; categoryEdit.Reload(); if (fci != null) { HandleInherited(fci.IsInherited); IsDummyField = fci.IsDummy; IsExtraField = fci.IsExtra; IsDummyFieldFromMainForm = false; } else { LoadDefaultCategoryEditForm(); } }
/// <summary> /// Generate editor table. /// </summary> public void GenerateEditor() { // Get parent web part info WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(this.ParentWebPartID); FormInfo fi = null; if (wpi != null) { // Create form info and load xml definition fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); } else { fi = new FormInfo(SourceXMLDefinition); } if (fi != null) { // Get defintion elements ArrayList infos = fi.GetFormElements(true, false); // create table part Literal table1 = new Literal(); pnlEditor.Controls.Add(table1); table1.Text = "<table cellpadding=\"3\" >"; // Hashtable counter int i = 0; // Check all items in object array foreach (object contrl in infos) { // Generate row for form category if (contrl is FormCategoryInfo) { // Load castegory info FormCategoryInfo fci = contrl as FormCategoryInfo; if (fci != null) { // Create row html code Literal tabCat = new Literal(); pnlEditor.Controls.Add(tabCat); tabCat.Text = "<tr class=\"InheritCategory\"><td>"; // Create label control and insert it to the page Label lblCat = new Label(); this.pnlEditor.Controls.Add(lblCat); lblCat.Text = fci.CategoryName; lblCat.Font.Bold = true; // End row html code Literal tabCat2 = new Literal(); pnlEditor.Controls.Add(tabCat2); tabCat2.Text = "</td><td></td><td></td>"; } } else { // Get form field info FormFieldInfo ffi = contrl as FormFieldInfo; if (ffi != null) { // Check if is defined inherited default value bool doNotInherit = IsDefined(ffi.Name); // Get default value string inheritedDefaultValue = GetDefaultValue(ffi.Name); // Current hastable for client id Hashtable currentHashTable = new Hashtable(); // First item is name currentHashTable[0] = ffi.Name; // Begin new row and column Literal table2 = new Literal(); pnlEditor.Controls.Add(table2); table2.Text = "<tr class=\"InheritWebPart\"><td>"; // Property label Label lblName = new Label(); pnlEditor.Controls.Add(lblName); lblName.Text = ffi.Caption; if (!lblName.Text.EndsWith(":")) { lblName.Text += ":"; } // New column Literal table3 = new Literal(); pnlEditor.Controls.Add(table3); table3.Text = "</td><td>"; // Type string for javascript function string jsType = "textbox"; // Type switcher if (FormHelper.IsFieldOfType(ffi, FormFieldControlTypeEnum.CheckBoxControl)) { // Checkbox type field CheckBox chk = new CheckBox(); pnlEditor.Controls.Add(chk); chk.Checked = ValidationHelper.GetBoolean(ffi.DefaultValue, false); chk.InputAttributes.Add("disabled", "disabled"); chk.Attributes.Add("id", chk.ClientID + "_upperSpan"); if (doNotInherit) { chk.InputAttributes.Remove("disabled"); chk.Enabled = true; chk.Checked = ValidationHelper.GetBoolean(inheritedDefaultValue, false); } jsType = "checkbox"; currentHashTable[1] = chk.ClientID; } else if (FormHelper.IsFieldOfType(ffi, FormFieldControlTypeEnum.CalendarControl)) { // Date time picker DateTimePicker dtPick = new DateTimePicker(); pnlEditor.Controls.Add(dtPick); dtPick.SelectedDateTime = ValidationHelper.GetDateTime(ffi.DefaultValue, DataHelper.DATETIME_NOT_SELECTED); dtPick.Enabled = false; dtPick.SupportFolder = ResolveUrl("~/CMSAdminControls/Calendar"); if (doNotInherit) { dtPick.Enabled = true; dtPick.SelectedDateTime = ValidationHelper.GetDateTime(inheritedDefaultValue, DataHelper.DATETIME_NOT_SELECTED); } jsType = "calendar"; currentHashTable[1] = dtPick.ClientID; } else { // Other types represent by textbox TextBox txt = new TextBox(); pnlEditor.Controls.Add(txt); txt.Text = ffi.DefaultValue; txt.CssClass = "TextBoxField"; txt.Enabled = ffi.Enabled; txt.Enabled = false; if (ffi.DataType == FormFieldDataTypeEnum.LongText) { txt.TextMode = TextBoxMode.MultiLine; txt.Rows = 3; } if (doNotInherit) { txt.Enabled = true; txt.Text = inheritedDefaultValue; } currentHashTable[1] = txt.ClientID; } // New column Literal table4 = new Literal(); pnlEditor.Controls.Add(table4); table4.Text = "</td><td>" + ffi.DataType.ToString() + "</td><td>"; // Inherit chk CheckBox chkInher = new CheckBox(); pnlEditor.Controls.Add(chkInher); chkInher.Checked = true; // Uncheck checkbox if this property is not inherited if (doNotInherit) { chkInher.Checked = false; } chkInher.Text = GetString("DefaultValueEditor.Inherited"); // Set default value for javascript function string defValue = "'" + ffi.DefaultValue + "'"; if (jsType == "checkbox") { defValue = ValidationHelper.GetBoolean(ffi.DefaultValue, false).ToString().ToLower(); } // Add javascript attribute with js function call chkInher.Attributes.Add("onclick", "CheckClick(this, '" + currentHashTable[1].ToString() + "', " + defValue + ", '" + jsType + "' );"); // Inser current checkbox id currentHashTable[2] = chkInher.ClientID; // Add current hastable to the controls hashtable ((Hashtable)Controls)[i] = currentHashTable; // End current row Literal table5 = new Literal(); pnlEditor.Controls.Add(table5); table5.Text = "</td></tr>"; i++; } } } // End table part Literal table6 = new Literal(); pnlEditor.Controls.Add(table6); table6.Text = "</table>"; } }
/// <summary> /// Fill form with selected category data. /// </summary> private void LoadSelectedCategory() { plcAdvanced.Visible = false; plcSimple.Visible = false; plcCategory.Visible = true; fci = fi.GetFormCategory(SelectedItemName); if (fci != null) { HandleInherited(fci.IsInherited); categoryEdit.Value = fci.CategoryCaption; } else { LoadDefaultCategoryEditForm(); } }
protected void Page_Load(object sender, EventArgs e) { // Setup info/error message placeholder if (MessagesPlaceHolder != null) { MessagesPlaceHolder.UseRelativePlaceHolder = false; form.EnsureMessagesPlaceholder(MessagesPlaceHolder); } // Load default properties from XML XmlDocument xml = new XmlDocument(); xml.Load(ResolveUrl(HttpContext.Current.Server.MapPath(PortalFormHelper.BEFOREPROPERTIESDEFINITION))); // Load UI element and element's page template (if any) mUIElementInfo = UIElementInfoProvider.GetUIElementInfo(QueryHelper.GetInteger("elementID", 0)); if (mUIElementInfo != null) { PageTemplateInfo pti = null; if (mUIElementInfo.ElementType == UIElementTypeEnum.PageTemplate) { pti = PageTemplateInfoProvider.GetPageTemplateInfo(mUIElementInfo.ElementPageTemplateID); } form.Enabled = ((SystemContext.DevelopmentMode || mUIElementInfo.ElementIsCustom) && (!UIElementInfoProvider.AllowEditOnlyCurrentModule || (mUIElementInfo.ElementResourceID == QueryHelper.GetInteger("moduleId", 0)))); // Create form info FormInfo fi = (pti != null) ? pti.PageTemplatePropertiesForm : PortalFormHelper.GetUIElementDefaultPropertiesForm(UIElementPropertiesPosition.Both); form.FormInformation = fi; // Load data row from properties DataRow dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); if ((mUIElementInfo == null) || !mUIElementInfo.IsApplication) { fi.RemoveFormField("DescriptionLink"); } XmlData customData = new XmlData(); // Load element properties XmlData data = new XmlData(); data.AllowMacros = true; data.LoadData(mUIElementInfo.ElementProperties); form.MacroTable = data.MacroTable; // Fill template datarow with element's properties. If template does not contain such column, add it to custom foreach (String col in data.ColumnNames) { if (col.StartsWith(UIContextData.CATEGORYNAMEPREFIX, StringComparison.Ordinal)) { if (!RequestHelper.IsPostBack()) { String catName = col.Substring(UIContextData.CATEGORYNAMEPREFIX.Length); FormCategoryInfo fci = fi.GetFormCategory(catName); if (fci != null) { fci.SetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, ValidationHelper.GetBoolean(data[col], false).ToString().ToLowerInvariant()); } } } else { if (dr.Table.Columns.Contains(col)) { DataHelper.SetDataRowValue(dr, col, data[col]); } else { customData[col] = data[col]; } } } dr["CustomProperties"] = customData.GetData(); form.DataRow = dr; form.LoadData(dr); form.FormInformation = fi; // Master page style for margin CurrentMaster.PanelContent.CssClass = "WebpartProperties PageContent"; form.OnAfterSave += form_OnAfterSave; } else { EditedObject = null; } }
/// <summary> /// Generate document content. /// </summary> /// <param name="wpi">WebPart info</param> /// <param name="gd">Guid</param> /// <param name="category">Category</param> protected void GenerateDocContent(FormInfo fi) { if (fi == null) { return; } // Get defintion elements var infos = fi.GetFormElements(true, false); bool isOpenSubTable = false; string currentGuid = ""; // Used for filter empty categories String categoryHeader = String.Empty; // Check all items in object array foreach (object contrl in infos) { // Generate row for form category if (contrl is FormCategoryInfo) { // Load castegory info FormCategoryInfo fci = contrl as FormCategoryInfo; if (fci != null) { // Close table from last category if (isOpenSubTable) { content += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\"> </td><td colspan=\"2\" class=\"Center\"> </td><td class=\"PropertyRightBottom\"> </td></tr></table>"; isOpenSubTable = false; } if (currentGuid == "") { currentGuid = Guid.NewGuid().ToString().Replace("-", "_"); } // Generate table for current category categoryHeader = @"<br /> <table cellpadding=""0"" cellspacing=""0"" class=""CategoryTable""> <tr> <td class=""CategoryLeftBorder""> </td> <td class=""CategoryTextCell"">" + HTMLHelper.HTMLEncode(ResHelper.GetString(fci.CategoryName)) + @"</td> <td class=""CategoryRightBorder""> </td> </tr> </table>"; } } else { // Get form field info FormFieldInfo ffi = contrl as FormFieldInfo; if (ffi != null) { if (categoryHeader != String.Empty) { content += categoryHeader; categoryHeader = String.Empty; } if (!isOpenSubTable) { // Generate table for properties under one category isOpenSubTable = true; content += "" + "<table cellpadding=\"0\" cellspacing=\"0\" id=\"_" + currentGuid + "\" class=\"PropertiesTable\" >"; currentGuid = ""; } // Add ':' to caption string doubleDot = ""; if (!ffi.Caption.EndsWithCSafe(":")) { doubleDot = ":"; } content += @"<tr> <td class=""PropertyLeftBorder"" > </td> <td class=""PropertyContent"" style=""width:200px;"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ffi.Caption)) + doubleDot + @"</td> <td class=""PropertyRow"">" + HTMLHelper.HTMLEncode(resolver.ResolveMacros(DataHelper.GetNotEmpty(ffi.Description, GetString("WebPartDocumentation.DescriptionNoneAvailable")))) + @"</td> <td class=""PropertyRightBorder""> </td> </tr>"; if (ffi.Description == null || ffi.Description.Trim() == "") { undocumentedProperties++; } } } } // Close last category (if has any properties) if (isOpenSubTable) { content += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\"> </td><td colspan=\"2\" class=\"Center\"> </td><td class=\"PropertyRightBottom\"> </td></tr></table>"; } }
/// <summary> /// Generate properties. /// </summary> protected void GenerateProperties(FormInfo fi) { ltlProperties.Text = String.Empty; // Generate script to display and hide properties groups ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ShowHideProperties", ScriptHelper.GetScript(@" function ShowHideProperties(id) { var obj = document.getElementById(id); var objlink = document.getElementById(id+'_link'); if ((obj != null)&&(objlink != null)){ if (obj.style.display == 'none' ) { obj.style.display=''; objlink.innerHTML = '<img border=""0"" src=""" + minImg + @""" >'; } else {obj.style.display='none'; objlink.innerHTML = '<img border=""0"" src=""" + plImg + @""" >';} objlink.blur();}}")); // Get defintion elements var infos = fi.GetFormElements(true, false); bool isOpenSubTable = false; bool firstLoad = true; bool hasAnyProperties = false; string currentGuid = ""; string newCategory = null; // Check all items in object array foreach (IField contrl in infos) { // Generate row for form category if (contrl is FormCategoryInfo) { // Load castegory info FormCategoryInfo fci = contrl as FormCategoryInfo; if (fci != null) { if (isOpenSubTable) { ltlProperties.Text += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\"> </td><td colspan=\"2\" class=\"Center\"> </td><td class=\"PropertyRightBottom\"> </td></tr></table>"; isOpenSubTable = false; } if (currentGuid == "") { currentGuid = Guid.NewGuid().ToString().Replace("-", "_"); } // Generate properties content newCategory = @"<br /> <table cellpadding=""0"" cellspacing=""0"" class=""CategoryTable""> <tr> <td class=""CategoryLeftBorder""> </td> <td class=""CategoryTextCell"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(fci.GetPropertyValue(FormCategoryPropertyEnum.Caption, MacroContext.CurrentResolver))) + @"</td> <td class=""HiderCell""> <a id=""" + currentGuid + "_link\" href=\"#\" onclick=\"ShowHideProperties('" + currentGuid + @"'); return false;""> <img border=""0"" src=""" + minImg + @""" ></a> </td> <td class=""CategoryRightBorder""> </td> </tr> </table>"; } } else { hasAnyProperties = true; // Get form field info FormFieldInfo ffi = contrl as FormFieldInfo; if (ffi != null) { // If display only in dashboard and not dashbord zone (or none for admins) dont show if ((ffi.DisplayIn == "dashboard") && ((zoneType != WidgetZoneTypeEnum.Dashboard) && (zoneType != WidgetZoneTypeEnum.None))) { continue; } if (newCategory != null) { ltlProperties.Text += newCategory; newCategory = null; firstLoad = false; } else if (firstLoad) { if (currentGuid == "") { currentGuid = Guid.NewGuid().ToString().Replace("-", "_"); } // Generate properties content firstLoad = false; ltlProperties.Text += @"<br /> <table cellpadding=""0"" cellspacing=""0"" class=""CategoryTable""> <tr> <td class=""CategoryLeftBorder""> </td> <td class=""CategoryTextCell"">Default</td> <td class=""HiderCell""> <a id=""" + currentGuid + "_link\" href=\"#\" onclick=\"ShowHideProperties('" + currentGuid + @"'); return false;""> <img border=""0"" src=""" + minImg + @""" ></a> </td> <td class=""CategoryRightBorder""> </td> </tr> </table>"; } if (!isOpenSubTable) { isOpenSubTable = true; ltlProperties.Text += "" + "<table cellpadding=\"0\" cellspacing=\"0\" id=\"" + currentGuid + "\" class=\"PropertiesTable\" >"; currentGuid = ""; } string doubleDot = ""; if (!ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver).EndsWithCSafe(":")) { doubleDot = ":"; } string fieldDescription = ResHelper.LocalizeString(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldDescription, MacroContext.CurrentResolver)); ltlProperties.Text += @"<tr> <td class=""PropertyLeftBorder"" > </td> <td class=""PropertyContent"" style=""width:200px;"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver))) + doubleDot + @"</td> <td class=""PropertyRow"">" + HTMLHelper.HTMLEncode(DataHelper.GetNotEmpty(fieldDescription, GetString("WebPartDocumentation.DescriptionNoneAvailable"))) + @"</td> <td class=""PropertyRightBorder""> </td> </tr>"; } } } if (isOpenSubTable) { ltlProperties.Text += "<tr class=\"PropertyBottom\"><td class=\"PropertyLeftBottom\"> </td><td colspan=\"2\" class=\"Center\"> </td><td class=\"PropertyRightBottom\"> </td></tr></table>"; } if (!hasAnyProperties) { ltlProperties.Text = "<br /><div style=\"padding-left:5px;padding-right:5px; font-weight: bold;\">" + GetString("documentation.nopropertiesavaible") + "</div>"; } }
/// <summary> /// Saves the given DataRow data to the web part properties. /// </summary> /// <param name="form">Form to save</param> private void SaveFormToWebPart(BasicForm form) { if (form.Visible && (webPartInstance != null)) { // Keep the old ID to check the change of the ID string oldId = webPartInstance.ControlID.ToLowerCSafe(); DataRow dr = form.DataRow; foreach (DataColumn column in dr.Table.Columns) { webPartInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()]; webPartInstance.SetValue(column.ColumnName, dr[column]); // If name changed, move the content if (column.ColumnName.ToLowerCSafe() == "webpartcontrolid") { try { string newId = null; if (!IsNewVariant) { newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe(); } // Name changed if ((!string.IsNullOrEmpty(newId)) && (newId != oldId)) { if (!IsNewWebPart && !IsNewVariant) { mWebPartIdChanged = true; } WebpartId = newId; // Move the document content if present string currentContent = (string)(pi.EditableWebParts[oldId]); if (currentContent != null) { TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree); // Move the content in the page info pi.EditableWebParts[oldId] = null; pi.EditableWebParts[newId] = currentContent; // Update the document node.SetValue("DocumentContent", pi.GetContentXml()); DocumentHelper.UpdateDocument(node, tree); } // Change the underlying zone names if layout web part if ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout)) { string prefix = oldId + "_"; foreach (WebPartZoneInstance zone in pti.WebPartZones) { if (zone.ZoneID.StartsWithCSafe(prefix, true)) { // Change the zone prefix to the new one zone.ZoneID = newId + "_" + zone.ZoneID.Substring(prefix.Length); } } } } } catch (Exception ex) { EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Content", "CHANGEWEBPART", ex); } } } // Save the collapsed/un-collapsed state of categories FormInfo fi = GetWebPartFormInfo(); var categories = fi.GetCategoryNames(); foreach (string category in categories) { FormCategoryInfo fci = fi.GetFormCategory(category); if (fci.CategoryCollapsible && fci.CategoryCollapsedByDefault) { if (form.IsCategoryCollapsed(category)) { webPartInstance.SetValue("cat_open_" + category, null); } else { webPartInstance.SetValue("cat_open_" + category, true); } } } } }
/// <summary> /// Generate editor table. /// </summary> public void GenerateEditor() { FormInfo fi = null; // Call handlers if (OnEditorLoaded != null) { fi = OnEditorLoaded(); } else { // Get parent web part info WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(ParentWebPartID); if (wpi != null) { // Create form info and load xml definition fi = PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); } else { fi = new FormInfo(SourceXMLDefinition); } } if (fi != null) { dr = fi.GetDataRow(false); // Get definition elements var infos = fi.GetFormElements(true, false); // create table part Literal table1 = new Literal(); pnlEditor.Controls.Add(table1); table1.Text = "<table cellpadding=\"3\">"; // Hashtable counter int i = 0; bool categoryExists = false; // Check all items in object array foreach (object contrl in infos) { // Generate row for form category if (contrl is FormCategoryInfo) { // Load category info FormCategoryInfo fci = contrl as FormCategoryInfo; if (fci != null) { CreateCategory(fci.CategoryCaption); categoryExists = true; } } else { // Ensure the default category if (!categoryExists) { CreateCategory(GetString("General.General")); categoryExists = true; } // Get form field info FormFieldInfo ffi = contrl as FormFieldInfo; if (ffi != null) { CreateField(ffi, ref i); } } } // End table part Literal table6 = new Literal(); pnlEditor.Controls.Add(table6); table6.Text = "</table>"; } }
/// <summary> /// Initializes controls for activity rule. /// </summary> private void InitActivityRuleControls(string selectedActivityType) { ucActivityType.OnSelectedIndexChanged += new EventHandler(ucActivityType_OnSelectedIndexChanged); // Init activity selector from edited object if any string activityType = selectedActivityType; if ((EditForm.EditedObject != null) && !RequestHelper.IsPostBack()) { ucActivityType.Value = ValidationHelper.GetString(EditForm.Data["RuleParameter"], PredefinedActivityType.ABUSE_REPORT); activityType = ucActivityType.SelectedValue; PreviousActivityType = activityType; } // List of ignored columns string ignoredColumns = "|activitytype|activitysiteid|activityguid|activityactivecontactid|activityoriginalcontactid|pagevisitid|pagevisitactivityid|searchid|searchactivityid|"; // List of activities with "ActivityValue" StringBuilder sb = new StringBuilder(); sb.Append("|"); sb.Append(PredefinedActivityType.PURCHASE); sb.Append("|"); sb.Append(PredefinedActivityType.PURCHASEDPRODUCT); sb.Append("|"); sb.Append(PredefinedActivityType.RATING); sb.Append("|"); sb.Append(PredefinedActivityType.POLL_VOTING); sb.Append("|"); sb.Append(PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART); sb.Append("|"); string showActivityValueFor = sb.ToString(); // Get columns from OM_Activity (i.e. base table for all activities) ActivityTypeInfo ati = ActivityTypeInfoProvider.GetActivityTypeInfo(activityType); FormInfo fi = new FormInfo(null); // Get columns from additional table (if any) according to selected activity type (page visit, search) FormInfo additionalFieldsForm = null; bool extraFieldsAtEnd = true; switch (activityType) { case PredefinedActivityType.PAGE_VISIT: case PredefinedActivityType.LANDING_PAGE: // Page visits additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.PAGEVISIT, false); break; case PredefinedActivityType.INTERNAL_SEARCH: case PredefinedActivityType.EXTERNAL_SEARCH: // Search additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.SEARCH, false); extraFieldsAtEnd = false; break; } // Get the activity form elements FormInfo filterFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.ACTIVITY, true); var elements = filterFieldsForm.GetFormElements(true, false); FormCategoryInfo newCategory = null; string caption = null; string captionKey = null; foreach (var elem in elements) { if (elem is FormCategoryInfo) { // Form category newCategory = (FormCategoryInfo)elem; } else if (elem is FormFieldInfo) { // Form field FormFieldInfo ffi = (FormFieldInfo)elem; // Skip ignored columns if (ignoredColumns.IndexOfCSafe("|" + ffi.Name.ToLowerCSafe() + "|") >= 0) { continue; } string controlName = null; if (!ffi.PrimaryKey && (fi.GetFormField(ffi.Name) == null)) { // Set default filters switch (ffi.DataType) { case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: controlName = "textfilter"; ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator"; break; case FormFieldDataTypeEnum.DateTime: controlName = "datetimefilter"; ffi.Settings["SecondDateFieldName"] = ffi.Name + ".seconddatetime"; break; case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: controlName = "numberfilter"; ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator"; break; case FormFieldDataTypeEnum.GUID: continue; } // For item ID and detail ID fields use control defined in activity type if (CMSString.Compare(ffi.Name, "ActivityItemID", true) == 0) { if (ati.ActivityTypeMainFormControl == null) { continue; } if (ati.ActivityTypeMainFormControl != String.Empty) { // Check if user defined control exists FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeMainFormControl); if (fui != null) { controlName = ati.ActivityTypeMainFormControl; } } // Set detailed caption captionKey = "activityitem." + activityType; caption = GetString(captionKey); if (!caption.EqualsCSafe(captionKey, true)) { ffi.Caption = caption; } } else if (CMSString.Compare(ffi.Name, "ActivityItemDetailID", true) == 0) { if (ati.ActivityTypeDetailFormControl == null) { continue; } if (ati.ActivityTypeDetailFormControl != String.Empty) { // Check if user defined control exists FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeDetailFormControl); if (fui != null) { controlName = ati.ActivityTypeDetailFormControl; } } // Set detailed caption captionKey = "activityitemdetail." + activityType; caption = GetString(captionKey); if (!caption.EqualsCSafe(captionKey, true)) { ffi.Caption = caption; } } else if (CMSString.Compare(ffi.Name, "ActivityNodeID", true) == 0) { // Document selector for NodeID controlName = "selectdocument"; } else if (CMSString.Compare(ffi.Name, "ActivityCulture", true) == 0) { // Culture selector for culture controlName = "sitecultureselector"; } else if (CMSString.Compare(ffi.Name, "ActivityValue", true) == 0) { // Show activity value only for relevant activity types if (!ati.ActivityTypeIsCustom && (showActivityValueFor.IndexOfCSafe("|" + activityType + "|", true) < 0)) { continue; } } if (controlName != null) { // SKU selector for product ffi.Settings["controlname"] = controlName; if (CMSString.Compare(controlName, "skuselector", true) == 0) { ffi.Settings["allowempty"] = true; } } // Ensure the category if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; // // Extra fields at the beginning if (!extraFieldsAtEnd && (additionalFieldsForm != null)) { AddExtraFields(ignoredColumns, fi, additionalFieldsForm); additionalFieldsForm = null; } } fi.AddFormField(ffi); } } } // Extra fields at end if (extraFieldsAtEnd && (additionalFieldsForm != null)) { // Ensure the category for extra fields if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; } AddExtraFields(ignoredColumns, fi, additionalFieldsForm); } LoadForm(activityFormCondition, fi, activityType); }
/// <summary> /// Initializes controls for activity rule. /// </summary> /// <param name="selectedActivity">Activity selected in drop-down menu</param> private void InitActivitySettings(string selectedActivity) { // Init activity selector from edited object if any LoadEditedActivityRule(ref selectedActivity); List <string> ignoredColumns = new List <string> { "activitytype", "activitysiteid", "activitycontactid", }; string[] activitiesWithValue = { PredefinedActivityType.PURCHASE, PredefinedActivityType.PURCHASEDPRODUCT, PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART }; // Get columns from OM_Activity (i.e. base table for all activities) ActivityTypeInfo ati = ActivityTypeInfo.Provider.Get(selectedActivity); var fi = new FormInfo(); // Get the activity form elements FormInfo filterFieldsForm = FormHelper.GetFormInfo(ActivityInfo.OBJECT_TYPE, true); IList <IDataDefinitionItem> elements = filterFieldsForm.GetFormElements(true, false); if ((selectedActivity != PredefinedActivityType.PAGE_VISIT) && (selectedActivity != PredefinedActivityType.LANDING_PAGE)) { // Show these fields only for 'Page visit' and 'Landing page' ignoredColumns.AddRange(new[] { "activityabvariantname" }); } FormCategoryInfo newCategory = null; foreach (IDataDefinitionItem elem in elements) { if (elem is FormCategoryInfo) { // Form category newCategory = (FormCategoryInfo)elem; } else if (elem is FormFieldInfo) { // Form field var ffi = (FormFieldInfo)elem; // Skip ignored columns if (ignoredColumns.Contains(ffi.Name, StringComparer.InvariantCultureIgnoreCase)) { continue; } if (!ffi.PrimaryKey && (fi.GetFormField(ffi.Name) == null)) { // Skip fields with Guid data type if (ffi.DataType == FieldDataType.Guid) { continue; } // Sets control name based on given datatype of field. Can be overwritten if more proper control is available string controlName = GetControlNameForFieldDataType(ffi); if (!GetControlNameForActivities(ffi, ati, selectedActivity, activitiesWithValue, ref controlName)) { continue; } if (controlName != null) { // SKU selector for product ffi.SetControlName(controlName); ffi.Settings["allowempty"] = ffi.HasFormFieldControlWithName("skuselector"); } // Ensure the category if (newCategory != null) { fi.AddFormCategory(newCategory); newCategory = null; } fi.AddFormItem(ffi); } } } LoadActivityForm(fi, selectedActivity); }
/// <summary> /// Save selected field. /// </summary> private void SaveSelectedField() { // FormFieldInfo structure with data from updated form FormFieldInfo ffiUpdated = null; // FormCategoryInfo structure with data from updated form FormCategoryInfo fciUpdated = null; // Determines whether it is a new attribute (or attribute to update) bool isNewItem = false; string errorMessage = null; DataClassInfo dci = null; WebPartInfo wpi = null; // Variables for changes in DB tables string tableName = null; string oldColumnName = null; string newColumnName = null; string newColumnSize = null; string newColumnType = null; string newColumnDefaultValue = null; // No default value bool newColumnAllowNull = true; if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: // Fill WebPartInfo structure with data from database wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Fill ClassInfo structure with data from database dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { // Set table name tableName = dci.ClassTableName; } else { lblError.Visible = true; lblError.ResourceString = "fieldeditor.notablename"; return; } break; } } // Load current xml form definition LoadFormDefinition(); if (SelectedItemType == FieldEditorSelectedItemEnum.Field) { // Fill FormFieldInfo structure with original data ffi = fi.GetFormField(SelectedItemName); // Fill FormFieldInfo structure with updated form data ffiUpdated = FillFormFieldInfoStructure(ffi); // Determine whether it is a new attribute or not isNewItem = (ffi == null); // Check if the attribute name already exists if (isNewItem || (ffi.Name.ToLower() != ffiUpdated.Name.ToLower())) { columnNames = fi.GetColumnNames(); if (columnNames != null) { foreach (string colName in columnNames) { // If name already exists if (ffiUpdated.Name.ToLower() == colName.ToLower()) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnName"; return; } } } // Check column name duplicity in JOINed tables if (!IsSystemFieldSelected) { // Check whether current column already exists in 'View_CMS_Tree_Joined' if (IsDocumentType && DocumentHelper.ColumnExistsInSystemTable(ffiUpdated.Name)) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable"; return; } // Check whether current column is uniquie in tables used to create views - applied only for system tables if ((Mode == FieldEditorModeEnum.SystemTable) && FormHelper.ColumnExistsInView(mClassName, ffiUpdated.Name)) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorExistingColumnInJoinedTable"; return; } } } // New node if (isNewItem) { ffiUpdated.PrimaryKey = this.IsPrimaryField; newColumnName = ffiUpdated.Name; newColumnAllowNull = ffiUpdated.AllowEmpty; // Set implicit default value if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue))) { if (!this.DevelopmentMode) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: case FormFieldDataTypeEnum.Decimal: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = "0"; break; case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.DocumentAttachments: newColumnDefaultValue = ""; break; case FormFieldDataTypeEnum.DateTime: newColumnDefaultValue = new DateTime(1970, 1, 1, 0, 0, 0).ToString(); break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: // 32 digits, empty Guid newColumnDefaultValue = Guid.Empty.ToString(); break; case FormFieldDataTypeEnum.Binary: newColumnDefaultValue = null; break; } } } // Check if default value is in required format else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue)) { // If default value is macro, don't try to ensure the type if (!ffiUpdated.IsMacro) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: try { int i = Int32.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = i.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger"); } break; case FormFieldDataTypeEnum.LongInteger: try { long longInt = long.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = longInt.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger"); } break; case FormFieldDataTypeEnum.Decimal: if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue)) { newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue); } else { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble"); } break; case FormFieldDataTypeEnum.DateTime: if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower())) { newColumnDefaultValue = ffiUpdated.DefaultValue; } else { try { DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = dat.ToString(); } catch { newColumnDefaultValue = DateTime.Now.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime"); } } break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: try { Guid g = new Guid(ffiUpdated.DefaultValue); newColumnDefaultValue = g.ToString(); } catch { newColumnDefaultValue = Guid.Empty.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid"); } break; case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = ffiUpdated.DefaultValue; break; } } } // Set column type and size LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize); if (string.IsNullOrEmpty(errorMessage)) { if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: // Add new column to specified table try { string newDBDefaultValue = null; // Check if it is not a macro if (ffiUpdated.IsMacro) { newDBDefaultValue = newColumnDefaultValue; } else { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Decimal: newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue); break; case FormFieldDataTypeEnum.DateTime: newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue); break; default: newDBDefaultValue = newColumnDefaultValue; break; } } if (!ffiUpdated.External) { if (this.DevelopmentMode) { TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue, false); } else { TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); } // Recreate the table PK constraint if (IsPrimaryField) { int pos = 0; FormFieldInfo[] pkFields = fi.GetFields(true, true, false, true); string[] primaryKeys = new string[pkFields.Length + 1]; foreach (FormFieldInfo pk in pkFields) { if (pk != null) { primaryKeys[pos++] = "[" + pk.Name + "]"; } } primaryKeys[pos] = "[" + newColumnName + "]"; TableManager.RecreatePKConstraint(tableName, primaryKeys, null); } } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; return; } break; } } } // Some error has occurred else { lblError.Visible = true; lblError.Text = errorMessage; return; } } // Existing node else { // Get info whether it is a primary key or system fild ffiUpdated.PrimaryKey = ffi.PrimaryKey; // If attribute is a primary key if (ffi.PrimaryKey) { // Check if the attribute type is integer number if (ffiUpdated.DataType != FormFieldDataTypeEnum.Integer) { errorMessage += GetString("TemplateDesigner.ErrorPKNotInteger") + " "; } // Check if allow empty is disabled if (ffiUpdated.AllowEmpty) { errorMessage += GetString("TemplateDesigner.ErrorPKAllowsNulls") + " "; } // Check that the field type is label string labelControlName = Enum.GetName(typeof(FormFieldControlTypeEnum), FormFieldControlTypeEnum.LabelControl).ToLower(); if ((ffiUpdated.FieldType != FormFieldControlTypeEnum.LabelControl) && ((ffiUpdated.FieldType != FormFieldControlTypeEnum.CustomUserControl) && (ffiUpdated.Settings["controlname"].ToString().ToLower() != labelControlName))) { errorMessage += GetString("TemplateDesigner.ErrorPKisNotLabel") + " "; } // Some error has occurred if (!string.IsNullOrEmpty(errorMessage)) { lblError.Visible = true; lblError.Text = GetString("TemplateDesigner.ErrorPKThisIsPK") + " " + errorMessage; return; } } // If table column update is needed if (((ffi.PrimaryKey) && (ffi.Name != ffiUpdated.Name)) || ((!ffi.PrimaryKey) && ((ffi.Name != ffiUpdated.Name) || (ffi.DataType != ffiUpdated.DataType) || (ffi.AllowEmpty != ffiUpdated.AllowEmpty) || (ffi.Size != ffiUpdated.Size) || ((ffi.DefaultValue != ffiUpdated.DefaultValue) || (ffiUpdated.DataType == FormFieldDataTypeEnum.Decimal))) ) ) { // Set variables needed for changes in DB oldColumnName = ffi.Name; newColumnName = ffiUpdated.Name; newColumnAllowNull = ffiUpdated.AllowEmpty; // Set implicit default value if (!(newColumnAllowNull) && (string.IsNullOrEmpty(ffiUpdated.DefaultValue))) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: case FormFieldDataTypeEnum.LongInteger: case FormFieldDataTypeEnum.Decimal: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = "0"; break; case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.LongText: newColumnDefaultValue = ""; break; case FormFieldDataTypeEnum.DateTime: newColumnDefaultValue = DateTime.Now.ToString(); break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: // 32 digits, empty Guid newColumnDefaultValue = Guid.Empty.ToString(); break; case FormFieldDataTypeEnum.Binary: newColumnDefaultValue = null; break; } } // Check if default value is in required format else if (!string.IsNullOrEmpty(ffiUpdated.DefaultValue)) { // If default value is macro, don't try to ensure the type if (!ffiUpdated.IsMacro) { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Integer: try { int i = Int32.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = i.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueInteger"); } break; case FormFieldDataTypeEnum.LongInteger: try { long longInt = long.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = longInt.ToString(); } catch { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueLongInteger"); } break; case FormFieldDataTypeEnum.Decimal: if (ValidationHelper.IsDouble(ffiUpdated.DefaultValue)) { newColumnDefaultValue = FormHelper.GetDoubleValueInDBCulture(ffiUpdated.DefaultValue); } else { newColumnDefaultValue = "0"; errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDouble"); } break; case FormFieldDataTypeEnum.DateTime: if ((ffiUpdated.DefaultValue.ToLower() == DateTimePicker.DATE_TODAY.ToLower()) || (ffiUpdated.DefaultValue.ToLower() == DateTimePicker.TIME_NOW.ToLower())) { newColumnDefaultValue = ffiUpdated.DefaultValue; } else { try { DateTime dat = DateTime.Parse(ffiUpdated.DefaultValue); newColumnDefaultValue = dat.ToString(); } catch { newColumnDefaultValue = DateTime.Now.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueDateTime"); } } break; case FormFieldDataTypeEnum.File: case FormFieldDataTypeEnum.GUID: try { Guid g = new Guid(ffiUpdated.DefaultValue); newColumnDefaultValue = g.ToString(); } catch { newColumnDefaultValue = Guid.Empty.ToString(); errorMessage = GetString("TemplateDesigner.ErrorDefaultValueGuid"); } break; case FormFieldDataTypeEnum.LongText: case FormFieldDataTypeEnum.Text: case FormFieldDataTypeEnum.Boolean: newColumnDefaultValue = ffiUpdated.DefaultValue; break; } } } // Set column type and size LoadColumnTypeAndSize(ffiUpdated.DataType, ffiUpdated.Size, ref newColumnType, ref newColumnSize); if (string.IsNullOrEmpty(errorMessage)) { if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: try { string newDBDefaultValue = null; // Check if it is not a macro if (ffiUpdated.IsMacro) { newDBDefaultValue = newColumnDefaultValue; } else { switch (ffiUpdated.DataType) { case FormFieldDataTypeEnum.Decimal: newDBDefaultValue = FormHelper.GetDoubleValueInDBCulture(newColumnDefaultValue); break; case FormFieldDataTypeEnum.DateTime: newDBDefaultValue = FormHelper.GetDateTimeValueInDBCulture(newColumnDefaultValue); break; default: newDBDefaultValue = newColumnDefaultValue; break; } } if (ffiUpdated.External) { if (!ffi.External) { // Drop old column from table TableManager.DropTableColumn(tableName, ffi.Name); } } else { if (ffi.External) { // Add table column TableManager.AddTableColumn(tableName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); } else { // Change table column TableManager.AlterTableColumn(tableName, oldColumnName, newColumnName, newColumnType, newColumnAllowNull, newDBDefaultValue); if (OnFieldNameChanged != null) { OnFieldNameChanged(this, oldColumnName, newColumnName); } } } } catch (Exception ex) { // User friendly message for not null setting of column if (ffi.AllowEmpty && !newColumnAllowNull) { lblError.Visible = true; lblError.ResourceString = "FieldEditor.ColumnNotAcceptNull"; lblError.ToolTip = ex.Message; } else { lblError.Visible = true; lblError.Text = ex.Message; } return; } break; } } } // Some error has occurred else { lblError.Visible = true; lblError.Text = errorMessage; return; } } // End update needed } // End existing node // Insert new field if (isNewItem) { InsertFormItem(ffiUpdated); } // Update current field else { fi.UpdateFormField(ffi.Name, ffiUpdated); } } else if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { // Fill FormCategoryInfo structure with original data fci = fi.GetFormCategory(SelectedItemName); // Determine whether it is a new attribute or not isNewItem = (fci == null); // Fill FormCategoryInfo structure with updated form data fciUpdated = new FormCategoryInfo(); fciUpdated.CategoryCaption = categoryEdit.Value.Replace("'", ""); // Check if the category caption is empty if (string.IsNullOrEmpty(fciUpdated.CategoryCaption)) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorCategoryNameEmpty"; return; } if (isNewItem) { // Use category caption for name attribut fciUpdated.CategoryName = fciUpdated.CategoryCaption; } else { fciUpdated.CategoryName = SelectedItemName; } if (isNewItem) { // Get form category names string[] categoryNames = fi.GetCategoryNames(); if (categoryNames != null) { // Check if the category name is unique foreach (string name in categoryNames) { // If name already exists return error if (fciUpdated.CategoryName == name) { lblError.Visible = true; lblError.ResourceString = "TemplateDesigner.ErrorExistingCategoryName"; return; } } } // Insert new category InsertFormItem(fciUpdated); } else { // Update current fi.UpdateFormCategory(fci.CategoryName, fciUpdated); } } // Make changes in database if (SelectedItemType != 0) { // Get updated definition FormDefinition = fi.GetXmlDefinition(); string error = null; if (!IsAlternativeForm) { switch (mMode) { case FieldEditorModeEnum.WebPartProperties: if (wpi != null) { // Update xml definition wpi.WebPartProperties = FormDefinition; try { WebPartInfoProvider.SetWebPartInfo(wpi); } catch (Exception ex) { error = ex.Message; } } else { error = GetString("FieldEditor.WebpartNotFound"); } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: if (dci != null) { // Update xml definition dci.ClassFormDefinition = FormDefinition; // Update xml schema dci.ClassXmlSchema = TableManager.GetXmlSchema(dci.ClassTableName); // When updating existing field if (ffi != null) { // Update ClassNodeNameSource field if (dci.ClassNodeNameSource == ffi.Name) { dci.ClassNodeNameSource = ffiUpdated.Name; } } bool fieldType = (SelectedItemType == FieldEditorSelectedItemEnum.Field); // Update changes in DB try { // Save the data class DataClassInfoProvider.SetDataClass(dci); // Generate the class code GenerateCode(); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); } catch (Exception ex) { error = ex.Message; } if (fieldType) { // Generate default view if (mMode == FieldEditorModeEnum.BizFormDefinition) { SqlGenerator.GenerateDefaultView(dci, CMSContext.CurrentSiteName); } else { SqlGenerator.GenerateDefaultView(dci, null); } // Regenerate queries SqlGenerator.GenerateDefaultQueries(dci, true, true); } // Updates custom views if ((mMode == FieldEditorModeEnum.SystemTable) || (mMode == FieldEditorModeEnum.ClassFormDefinition)) { try { TableManager.RefreshCustomViews(dci.ClassTableName); string lowClassName = dci.ClassName.ToLower(); if (lowClassName == "cms.document" || lowClassName == "cms.tree") { TableManager.RefreshDocumentViews(); } } catch (Exception ex) { error = ResHelper.GetString("fieldeditor.refreshingviewsfailed"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("Field Editor", "EXCEPTION", ex); } } } else { error = GetString("FieldEditor.ClassNotFound"); } break; } } if (!string.IsNullOrEmpty(error)) { lblError.Visible = true; lblError.Text = "[FieldEditor.SaveSelectedField()]: " + error; } else { IsNewItemEdited = false; if (SelectedItemType == FieldEditorSelectedItemEnum.Category) { Reload(categPreffix + fciUpdated.CategoryName); } else if (SelectedItemType == FieldEditorSelectedItemEnum.Field) { Reload(fieldPreffix + ffiUpdated.Name); } lblError.Visible = false; lblInfo.Visible = true; lblInfo.ResourceString = "general.changessaved"; } } // All done and new item, fire OnFieldCreated event if (isNewItem && (ffiUpdated != null)) { RaiseOnFieldCreated(ffiUpdated); } }
/// <summary> /// Creates category with variant attributes. /// </summary> /// <param name="optionsDs">Product options</param> private void SetVariantAttributes(IEnumerable<SKUInfo> optionsDs) { // Get attributes category index - just before representing category var attrPos = editForm.FormInformation.ItemsList.FindIndex(f => (f is FormCategoryInfo) && ((FormCategoryInfo)f).CategoryName.EqualsCSafe("com.sku.representingcategory")); // Create attributes category var attCategory = new FormCategoryInfo() { CategoryName = "Attributes", IsDummy = true, }; attCategory.SetPropertyValue(FormCategoryPropertyEnum.Caption, HTMLHelper.HTMLEncode(GetString("com.variant.attributes"))); editForm.FormInformation.AddFormItem(attCategory, attrPos++); foreach (var option in optionsDs) { if (option.Parent != null) { string categoryCodeName = option.Parent.Generalized.ObjectCodeName; options.Add(categoryCodeName, option); FormFieldInfo ffOption = new FormFieldInfo { Name = categoryCodeName, AllowEmpty = true, Size = 400, FieldType = FormFieldControlTypeEnum.LabelControl, DataType = FieldDataType.Text, IsDummyField = true, }; OptionCategoryInfo parentOptionCategory = (OptionCategoryInfo)option.Parent; ffOption.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(option.SKUName))); // Show category live site display name instead of category display name in case it is available ffOption.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, HTMLHelper.HTMLEncode(ResHelper.LocalizeString(parentOptionCategory.CategoryTitle))); //Insert field to the form on specified position editForm.FormInformation.AddFormItem(ffOption, attrPos++); } } }