protected void Page_Load(object sender, EventArgs e) { if (BaseInfo == null) { ShowError(GetString("codegenerator.objectwasnotloaded")); txtCode.Visible = false; return; } DataClassInfo dci = GetDataClassInfo(); if (dci != null) { mClassName = dci.ClassName; string formDefinition = dci.ClassFormDefinition; var fi = new FormInfo(formDefinition); mCode = GetCode(fi); txtCode.Text = mCode; HeaderActions.AddAction(new HeaderAction() { Text = GetString("codegenerator.downloadfile"), CommandName = DOWNLOAD_FILE, OnClientClick = "window.noProgress = true;" }); HeaderActions.ActionPerformed += HeaderActions_ActionPerformed; } }
/// <summary> /// CreateForm /// </summary> /// <param name="formInfo"></param> /// <returns></returns> public static Form CreateForm(FormInfo formInfo) { if (formInfo == null) { throw new ArgumentNullException("formInfo"); } if (string.IsNullOrEmpty(formInfo.ClassName)) { throw new ArgumentException("FormInfo of " + formInfo.Name + " 's ClassName must not be null!"); } Form form = null; if (formInfo.ClassName.EndsWith(".py")) { form = ServiceProvider.GetService<IFileScript>().ExecuteFile(formInfo.ClassName, new Dictionary<string, object> { { "Params", formInfo.Params } }) as Form; } else { if (!string.IsNullOrEmpty(formInfo.Params)) { form = Feng.Utils.ReflectionHelper.CreateInstanceFromType(Feng.Utils.ReflectionHelper.GetTypeFromName(formInfo.ClassName), formInfo.Params.Split(new char[] { ';' })) as Form; } else { form = Feng.Utils.ReflectionHelper.CreateInstanceFromType(Feng.Utils.ReflectionHelper.GetTypeFromName(formInfo.ClassName)) as Form; } } return form; }
/// <summary> /// Generates default form definition. /// </summary> private void GenerateDefinition() { // Get info on the class var classInfo = DataClassInfoProvider.GetDataClassInfo(QueryHelper.GetInteger("classid", 0)); if (classInfo == null) { return; } var manager = new TableManager(classInfo.ClassConnectionString); // Update schema and definition for existing class classInfo.ClassXmlSchema = manager.GetXmlSchema(classInfo.ClassTableName); var fi = new FormInfo(); try { fi.LoadFromDataStructure(classInfo.ClassTableName, manager, true); } catch (Exception ex) { // Show error message if something caused unhandled exception LogAndShowError("ClassFields", "GenerateDefinition", ex); return; } classInfo.ClassFormDefinition = fi.GetXmlDefinition(); DataClassInfoProvider.SetDataClassInfo(classInfo); URLHelper.Redirect(URLHelper.AddParameterToUrl(RequestContext.CurrentURL, "gen", "1")); }
internal FormInfo Parse() { var rslt = new FormInfo(); rslt.Id = this.Id; rslt.DataId = this.DataId; return rslt; }
protected override void OnPreInit(EventArgs e) { base.OnPreInit(e); SetCulture(); IFormatProvider culture = DateTimeHelper.DefaultIFormatProvider; IFormatProvider currentCulture = new System.Globalization.CultureInfo(System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag); reportId = ValidationHelper.GetInteger(Request.QueryString["reportid"], 0); ReportInfo ri = ReportInfoProvider.GetReportInfo(reportId); if (ri != null) { string[] httpParameters = ValidationHelper.GetString(Request.QueryString["parameters"], "").Split(";".ToCharArray()); FormInfo fi = new FormInfo(ri.ReportParameters); // Get datarow with required columns DataRow dr = fi.GetDataRow(); if (httpParameters.Length > 1) { string[] parameters = new string[httpParameters.Length / 2]; // Put values to given data row for (int i = 0; i < httpParameters.Length; i = i + 2) { if (dr.Table.Columns.Contains(httpParameters[i])) { if (dr.Table.Columns[httpParameters[i]].DataType != typeof(DateTime)) { dr[httpParameters[i]] = httpParameters[i + 1]; } else { if (httpParameters[i + 1] != String.Empty) { dr[httpParameters[i]] = Convert.ToDateTime(httpParameters[i + 1], culture).ToString(currentCulture); } } } } dr.AcceptChanges(); DisplayReport1.LoadFormParameters = false; DisplayReport1.ReportName = ri.ReportName; DisplayReport1.DisplayFilter = false; DisplayReport1.ReportParameters = dr; } else { DisplayReport1.ReportName = ri.ReportName; DisplayReport1.DisplayFilter = false; } this.Page.Title = GetString("Report_Print.lblPrintReport") + " " + ri.ReportDisplayName; } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); var dci = DataClassInfoProvider.GetDataClass(FormClassNames.FirstOrDefault()); var FormDefinition = dci.ClassFormDefinition; var fi = new FormInfo(FormDefinition); lstFields.DataSource = fi.ItemsList.Select(x => new ListItem { Text = x.ToString(), Value = x.ToString() }).ToList(); lstFields.DataBind(); }
/// <summary> /// Returns new instance of resolver for given class (includes all fields, etc.). /// </summary> /// <param name="formInfo">FormInfo</param> private static ContextResolver GetFormResolver(FormInfo formInfo) { ContextResolver mContextResolver = GetDefaultResolver(); var controlPlaceholder = new EditingFormControl(); foreach (var fieldInfo in formInfo.ItemsList.OfType<FormFieldInfo>()) { mContextResolver.SetNamedSourceData(fieldInfo.Name, controlPlaceholder); } return mContextResolver; }
private string GetCode(FormInfo formInfo) { switch (BaseInfo.TypeInfo.ObjectType) { case BizFormInfo.OBJECT_TYPE: return FormInfoClassGenerator.GetOnlineForm(mClassName, formInfo); case DataClassInfo.OBJECT_TYPE_DOCUMENTTYPE: return FormInfoClassGenerator.GetDocumentType(mClassName, formInfo); case DataClassInfo.OBJECT_TYPE_CUSTOMTABLE: return FormInfoClassGenerator.GetCustomTable(mClassName, formInfo); } return null; }
/// <summary> /// Generates the web part code. /// </summary> protected void GenerateCode() { string templateFile = MapPath("~/App_Data/CodeTemplates/WebPart"); string baseControl = txtBaseControl.Text.Trim(); WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(webpartId); if (wpi != null) { // Generate the ASCX string ascx = File.ReadAllText(templateFile + ".ascx.template"); // Prepare the path string path = URLHelper.UnResolveUrl(WebPartInfoProvider.GetWebPartUrl(wpi), SettingsKeyProvider.ApplicationPath); // Prepare the class name string className = path.Trim('~', '/'); if (className.EndsWith(".ascx")) { className = className.Substring(0, className.Length - 5); } className = className.Replace("/", "_"); ascx = Regex.Replace(ascx, "(Inherits)=\"[^\"]+\"", "$1=\"" + className + "\""); ascx = Regex.Replace(ascx, "(CodeFile|CodeBehind)=\"[^\"]+\"", "$1=\"" + path + "\""); this.txtASCX.Text = ascx; // Generate the code string code = File.ReadAllText(templateFile + ".ascx.cs.template"); code = Regex.Replace(code, "( class\\s+)[^\\s]+", "$1" + className); // Prepare the properties FormInfo fi = new FormInfo(wpi.WebPartProperties); StringBuilder sbInit = new StringBuilder(); string propertiesCode = CodeGenerator.GetPropertiesCode(fi, true, baseControl, sbInit); // Replace in code code = code.Replace("// ##PROPERTIES##", propertiesCode); code = code.Replace("// ##SETUP##", sbInit.ToString()); this.txtCS.Text = code; } }
protected void btnOK_Click(object sender, EventArgs e) { // If data are valid if (bfParameters.ValidateData()) { // Fill BasicForm with user data bfParameters.SaveData(null); if (bfParameters.DataRow != null) { int reportID = QueryHelper.GetInteger("ReportID", 0); ReportInfo ri = ReportInfoProvider.GetReportInfo(reportID); if (ri == null) { return; } FormInfo fi = new FormInfo(ri.ReportParameters); DataRow defaultRow = fi.GetDataRow(); fi.LoadDefaultValues(defaultRow); // Load default parameters to items ,where displayed in edit form not checked List<FormItem> items = fi.ItemsList; foreach (FormItem item in items) { FormFieldInfo ffi = item as FormFieldInfo; if ((ffi != null) && (!ffi.Visible)) { bfParameters.DataRow[ffi.Name] = defaultRow[ffi.Name]; } } WindowHelper.Add(hdnGuid.Value, bfParameters.DataRow.Table.DataSet); } // Refreshh opener update panel script ltlScript.Text = ScriptHelper.GetScript("wopener.refresh (); window.close ()"); } }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> /// <param name="webPart">Source web part</param> /// <param name="formInfo">Web part form info</param> private void LoadDataRowFromWebPart(DataRow dr, WebPartInstance webPart, FormInfo formInfo) { if (webPart != null) { foreach (DataColumn column in dr.Table.Columns) { try { bool load = true; // switch by xml version switch (xmlVersion) { case 1: load = webPart.Properties.Contains(column.ColumnName.ToLowerCSafe()) || column.ColumnName.EqualsCSafe("webpartcontrolid", true); break; // Version 0 default: // Load default value for Boolean type in old XML version if ((column.DataType == typeof(bool)) && !webPart.Properties.Contains(column.ColumnName.ToLowerCSafe())) { FormFieldInfo ffi = formInfo.GetFormField(column.ColumnName); if (ffi != null) { webPart.SetValue(column.ColumnName, ffi.GetPropertyValue(FormFieldPropertyEnum.DefaultValue)); } } break; } if (load) { var value = webPart.GetValue(column.ColumnName); // Convert value into default format if ((value != null) && (ValidationHelper.GetString(value, String.Empty) != String.Empty)) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.MinValue, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } } catch (Exception ex) { EventLogProvider.LogException("WebPartProperties", "LOADDATAROW", ex); } } } }
protected void EditForm_OnBeforeSave(object sender, EventArgs e) { MacroRuleInfo info = Control.EditedObject as MacroRuleInfo; if (info != null) { // Generate automatic fields when present in UserText FormEngineUserControl control = Control.FieldControls["MacroRuleText"]; if (control != null) { string userText = ValidationHelper.GetString(control.Value, String.Empty); if (!string.IsNullOrEmpty(userText)) { Regex regex = RegexHelper.GetRegex("\\{[-_a-zA-Z0-9]*\\}"); MatchCollection match = regex.Matches(userText); if (match.Count > 0) { FormInfo fi = new FormInfo(info.MacroRuleParameters); foreach (Match m in match) { foreach (Capture c in m.Captures) { string name = c.Value.Substring(1, c.Value.Length - 2).ToLowerCSafe(); FormFieldInfo ffi = fi.GetFormField(name); if (ffi == null) { ffi = new FormFieldInfo(); ffi.Name = name; ffi.DataType = FieldDataType.Text; ffi.Size = 100; ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "select operation"); ffi.AllowEmpty = true; switch (name) { case "_is": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, ";is"); ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";is\r\n!;is not"; break; case "_was": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, ";was"); ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";was\r\n!;was not"; break; case "_will": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, ";will"); ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";will\r\n!;will not"; break; case "_has": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, ";has"); ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";has\r\n!;does not have"; break; case "_perfectum": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, ";has"); ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";has\r\n!;has not"; break; case "_any": ffi.SetPropertyValue(FormFieldPropertyEnum.DefaultValue, "false;any"); ffi.Settings["controlname"] = "macro_any-all_bool_selector"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = "false;any\r\ntrue;all"; break; default: ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl; ffi.Size = 1000; ffi.SetPropertyValue(FormFieldPropertyEnum.FieldCaption, "enter text"); break; } fi.AddFormItem(ffi); } } } info.MacroRuleParameters = fi.GetXmlDefinition(); } } } } Control.EditedObject.SetValue("MacroRuleIsCustom", !SystemContext.DevelopmentMode); }
/// <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 <IField> elements = filterFieldsForm.GetFormElements(true, false); FormCategoryInfo newCategory = null; foreach (IField 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); }
protected void gridData_OnLoadColumns() { if (CustomTableClassInfo != null) { // Update the actions command argument foreach (Action action in gridData.GridActions.Actions) { action.CommandArgument = ti.IDColumn; } string columnNames = null; List <string> columnList = null; string columns = CustomTableClassInfo.ClassShowColumns; if (string.IsNullOrEmpty(columns)) { columnList = new List <string>(); columnList.AddRange(GetExistingColumns(false).Take(5)); // Show info message ShowInformation(GetString("customtable.columnscount.default")); } else { // Get existing columns names List <string> existingColumns = GetExistingColumns(true); // Get selected columns List <string> selectedColumns = GetSelectedColumns(columns); columnList = new List <string>(); StringBuilder sb = new StringBuilder(); // Remove non-existing columns foreach (string col in selectedColumns) { int index = existingColumns.BinarySearch(col, StringComparer.InvariantCultureIgnoreCase); if (index >= 0) { string colName = existingColumns[index]; columnList.Add(colName); sb.Append(",[", colName, "]"); } } // Ensure item order column selectedColumns.Sort(); if ((selectedColumns.BinarySearch("ItemOrder", StringComparer.InvariantCultureIgnoreCase) < 0) && HasItemOrderField) { sb.Append(",[ItemOrder]"); } // Ensure itemid column if (selectedColumns.BinarySearch(ti.IDColumn, StringComparer.InvariantCultureIgnoreCase) < 0) { sb.Insert(0, ",[" + ti.IDColumn + "]"); } columnNames = sb.ToString().TrimStart(','); } // Loop trough all columns for (int i = 0; i < columnList.Count; i++) { string column = columnList[i]; // Get field caption FormFieldInfo ffi = FormInfo.GetFormField(column); string fieldCaption = string.Empty; if (ffi == null) { fieldCaption = column; } else { fieldCaption = (ffi.Caption == string.Empty) ? column : ResHelper.LocalizeString(ffi.Caption); } Column columnDefinition = new Column { Caption = fieldCaption, Source = column, ExternalSourceName = column, AllowSorting = true, Wrap = false }; if (i == columnList.Count - 1) { // Stretch last column columnDefinition.Width = "100%"; } gridData.GridColumns.Columns.Add(columnDefinition); } // Set column names gridData.Columns = columnNames; } }
/// <summary> /// OnInit. /// </summary> protected override void OnInit(EventArgs e) { ScriptHelper.RegisterWOpenerScript(Page); PageTitle.TitleText = ResHelper.GetString("rep.webparts.reportparameterstitle"); // Load data for this form int reportID = QueryHelper.GetInteger("ReportID", 0); hdnGuid.Value = QueryHelper.GetString("GUID", String.Empty); ReportInfo ri = ReportInfoProvider.GetReportInfo(reportID); if (ri == null) { return; } FormInfo fi = new FormInfo(ri.ReportParameters); bfParameters.FormInformation = fi; bfParameters.SubmitButton.Visible = false; bfParameters.Mode = FormModeEnum.Update; // Get dataset from cache DataSet ds = (DataSet)WindowHelper.GetItem(hdnGuid.Value); DataRow dr = fi.GetDataRow(false); fi.LoadDefaultValues(dr, true); if (ds == null) { if (dr.ItemArray.Length > 0) { // Set up grid bfParameters.DataRow = RequestHelper.IsPostBack() ? fi.GetDataRow(false) : dr; } } // Set data set given from cache if ((ds != null) && (ds.Tables.Count > 0) && (ds.Tables[0].Rows.Count > 0)) { //Merge with default data from report MergeDefaultValuesWithData(dr, ds.Tables[0].Rows[0]); //Set row to basic form bfParameters.DataRow = dr; } // Test if there is any item visible in report parameters bool itemVisible = false; List <IDataDefinitionItem> items = fi.ItemsList; foreach (IDataDefinitionItem item in items) { FormFieldInfo ffi = item as FormFieldInfo; if (ffi != null && ffi.Visible) { itemVisible = true; break; } } if (!itemVisible) { ShowInformation(GetString("rep.parameters.noparameters")); } base.OnInit(e); }
/// <summary> /// Generate properties. /// </summary> protected void GenerateProperties(FormInfo fi) { // 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 (IFormItem 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.CategoryCaption)) + @"</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.Caption.EndsWithCSafe(":")) { doubleDot = ":"; } ltlProperties.Text += @"<tr> <td class=""PropertyLeftBorder"" > </td> <td class=""PropertyContent"" style=""width:200px;"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ffi.Caption)) + doubleDot + @"</td> <td class=""PropertyRow"">" + HTMLHelper.HTMLEncode(ResHelper.LocalizeString(DataHelper.GetNotEmpty(ffi.Description, 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>"; } }
public void BindData() { if (WebpartId != "") { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId); if (pi == null) { this.Visible = false; return; } // Get page template info pti = pi.PageTemplateInfo; if (pti != null) { // Get web part instance webPart = pti.GetWebPart(InstanceGUID, WebpartId); if (webPart == null) { return; } // Get the web part info WebPartInfo wpi = WebPartInfoProvider.GetBaseWebPart(webPart.WebPartType); if (wpi == null) { return; } // Get webpart properties (XML) string wpProperties = wpi.WebPartProperties; FormInfo fi = FormHelper.GetWebPartFormInfo(wpi.WebPartName + FormHelper.CORE, wpi.WebPartProperties, null, null, false); // Get datarow with required columns DataRow dr = fi.GetDataRow(); // Bind drop down list if (!RequestHelper.IsPostBack()) { DataTable dropTable = new DataTable(); dropTable.Columns.Add("name"); foreach (DataColumn column in dr.Table.Columns) { dropTable.Rows.Add(column.ColumnName); } dropTable.DefaultView.Sort = "name"; drpProperty.DataTextField = "name"; drpProperty.DataValueField = "name"; drpProperty.DataSource = dropTable.DefaultView; drpProperty.DataBind(); } // Bind grid view DataTable table = new DataTable(); table.Columns.Add("LocalProperty"); table.Columns.Add("SourceProperty"); bindings = webPart.Bindings; foreach (DataColumn column in dr.Table.Columns) { string propertyName = column.ColumnName.ToLower(); if (bindings.ContainsKey(propertyName)) { WebPartBindingInfo bi = (WebPartBindingInfo)bindings[propertyName]; table.Rows.Add(column.ColumnName, bi.SourceWebPart + "." + bi.SourceProperty); } } gvBinding.DataSource = table; gvBinding.DataBind(); } } }
public async Task SendNotifyAsync(FormInfo formInfo, List <TableStyle> styles, DataInfo dataInfo) { if (formInfo.IsAdministratorSmsNotify && !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyTplId) && !string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyMobile)) { var isSmsEnabled = await _smsManager.IsEnabledAsync(); if (isSmsEnabled) { var parameters = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(formInfo.AdministratorSmsNotifyKeys)) { var keys = formInfo.AdministratorSmsNotifyKeys.Split(','); foreach (var key in keys) { if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id))) { parameters.Add(key, dataInfo.Id.ToString()); } else if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.CreatedDate))) { if (dataInfo.CreatedDate.HasValue) { parameters.Add(key, dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm")); } } else { var value = dataInfo.Get <string>(key); parameters.Add(key, value); } } } await _smsManager.SendAsync(formInfo.AdministratorSmsNotifyMobile, formInfo.AdministratorSmsNotifyTplId, parameters); } } if (formInfo.IsAdministratorMailNotify && !string.IsNullOrEmpty(formInfo.AdministratorMailNotifyAddress)) { var isMailEnabled = await _mailManager.IsEnabledAsync(); if (isMailEnabled) { var templateHtml = await GetMailTemplateHtmlAsync(); var listHtml = await GetMailListHtmlAsync(); var keyValueList = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("编号", dataInfo.Guid) }; if (dataInfo.CreatedDate.HasValue) { keyValueList.Add(new KeyValuePair <string, string>("提交时间", dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm"))); } foreach (var style in styles) { keyValueList.Add(new KeyValuePair <string, string>(style.DisplayName, dataInfo.Get <string>(style.AttributeName))); } var list = new StringBuilder(); foreach (var kv in keyValueList) { list.Append(listHtml.Replace("{{key}}", kv.Key).Replace("{{value}}", kv.Value)); } var subject = !string.IsNullOrEmpty(formInfo.AdministratorMailTitle) ? formInfo.AdministratorMailTitle : "[SSCMS] 通知邮件"; var htmlBody = templateHtml .Replace("{{title}}", formInfo.Title) .Replace("{{list}}", list.ToString()); await _mailManager.SendAsync(formInfo.AdministratorMailNotifyAddress, subject, htmlBody); } } if (formInfo.IsUserSmsNotify && !string.IsNullOrEmpty(formInfo.UserSmsNotifyTplId) && !string.IsNullOrEmpty(formInfo.UserSmsNotifyMobileName)) { var isSmsEnabled = await _smsManager.IsEnabledAsync(); if (isSmsEnabled) { var parameters = new Dictionary <string, string>(); if (!string.IsNullOrEmpty(formInfo.UserSmsNotifyKeys)) { var keys = formInfo.UserSmsNotifyKeys.Split(','); foreach (var key in keys) { if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.Id))) { parameters.Add(key, dataInfo.Id.ToString()); } else if (StringUtils.EqualsIgnoreCase(key, nameof(DataInfo.CreatedDate))) { if (dataInfo.CreatedDate.HasValue) { parameters.Add(key, dataInfo.CreatedDate.Value.ToString("yyyy-MM-dd HH:mm")); } } else { var value = dataInfo.Get <string>(key); parameters.Add(key, value); } } } var mobile = dataInfo.Get <string>(formInfo.UserSmsNotifyMobileName); if (!string.IsNullOrEmpty(mobile)) { await _smsManager.SendAsync(mobile, formInfo.UserSmsNotifyTplId, parameters); } } } }
/// <summary> /// Reloads control with new data. /// </summary> private void ReloadData() { tblDocument.Rows.Clear(); DataClassInfo ci = DataClassInfoProvider.GetDataClass(Node.NodeClassName); if (ci != null) { fi = FormHelper.GetFormInfo(ci.ClassName, false); TableHeaderCell labelCell = new TableHeaderCell(); TableHeaderCell valueCell = null; // Add header column with version number if (CompareNode == null) { labelCell.Text = GetString("General.FieldName"); labelCell.EnableViewState = false; valueCell = new TableHeaderCell(); valueCell.EnableViewState = false; valueCell.Text = GetString("General.Value"); // Add table header AddRow(labelCell, valueCell, "UniGridHead", false); } else { labelCell.Text = GetString("lock.versionnumber"); valueCell = GetRollbackTableHeaderCell("source", Node.DocumentID, versionHistoryId); TableHeaderCell valueCompare = GetRollbackTableHeaderCell("compare", CompareNode.DocumentID, versionCompare); // Add table header AddRow(labelCell, valueCell, valueCompare, true, "UniGridHead", false); } if (ci.ClassIsProduct) { // Add coupled class fields ClassStructureInfo skuCsi = ClassStructureInfo.GetClassInfo("ecommerce.sku"); if (skuCsi != null) { foreach (string col in skuCsi.ColumnNames) { AddField(Node, CompareNode, col); } } } if (ci.ClassIsCoupledClass) { // Add coupled class fields ClassStructureInfo coupledCsi = ClassStructureInfo.GetClassInfo(Node.NodeClassName); if (coupledCsi != null) { foreach (string col in coupledCsi.ColumnNames) { // If comparing with other version and current coupled column is not versioned do not display it if (!((CompareNode != null) && !(VersionManager.IsVersionedCoupledColumn(Node.NodeClassName, col)))) { AddField(Node, CompareNode, col); } } } } // Add versioned document class fields ClassStructureInfo docCsi = ClassStructureInfo.GetClassInfo("cms.document"); if (docCsi != null) { foreach (string col in docCsi.ColumnNames) { // If comparing with other version and current document column is not versioned do not display it // One exception is DocumentNamePath column which will be displayed even if it is not marked as a versioned column if (!((CompareNode != null) && (!(VersionManager.IsVersionedDocumentColumn(col) || (col.ToLowerCSafe() == "documentnamepath"))))) { AddField(Node, CompareNode, col); } } } // Add versioned document class fields ClassStructureInfo treeCsi = ClassStructureInfo.GetClassInfo("cms.tree"); if (treeCsi != null) { foreach (string col in treeCsi.ColumnNames) { // Do not display cms_tree columns when comparing with other version // cms_tree columns are not versioned if (CompareNode == null) { AddField(Node, CompareNode, col); } } } // Add unsorted attachments to the table AddField(Node, CompareNode, UNSORTED); } }
/// <summary> /// Loads the web part form. /// </summary> protected void LoadForm() { // Load settings if (!string.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWebPart = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!string.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Indicates whether the new variant should be chosen when closing this dialog selectNewVariant = IsNewVariant; // Try to find the web part variant in the database and set its VariantID if (IsNewVariant) { Hashtable varProperties = WindowHelper.GetItem("variantProperties") as Hashtable; if (varProperties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(varProperties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(VariantMode, PageTemplateID, variantName, true); // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } if (!String.IsNullOrEmpty(WebPartID)) { // Get the page info pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateID, CultureCode); if (pi != null) { // Get template pti = pi.UsedPageTemplateInfo; // Get template instance templateInstance = pti.TemplateInstance; if (!IsNewWebPart) { // Standard zone webPartInstance = templateInstance.GetWebPart(InstanceGUID, WebPartID); // If the web part not found, try to find it among the MVT/CP variants if (webPartInstance == null) { // MVT/CP variant templateInstance.LoadVariants(false, VariantModeEnum.None); webPartInstance = templateInstance.GetWebPart(InstanceGUID, -1, 0); // Set the VariantMode according to the selected web part/zone variant if ((webPartInstance != null) && (webPartInstance.ParentZone != null)) { VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode; } else { VariantMode = VariantModeEnum.None; } } else { // Ensure that the ZoneVarianID is not set when the web part was found in a regular zone ZoneVariantID = 0; } if ((VariantID > 0) && (webPartInstance != null) && (webPartInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { webPartInstance = webPartInstance.FindVariant(VariantID); } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } if (webPartInstance == null) { UIContext.EditedObject = null; return; } } mainWebPartInstance = webPartInstance; // Keep xml version if (webPartInstance != null) { xmlVersion = webPartInstance.XMLVersion; // If data source ID set, edit the data source if (NestedWebPartID > 0) { webPartInstance = webPartInstance.NestedWebParts[NestedWebPartKey] ?? new WebPartInstance() { InstanceGUID = Guid.NewGuid() }; } } // Get the form info FormInfo fi = GetWebPartFormInfo(); // Get the form definition if (fi != null) { fi.ContextResolver.Settings.RelatedObject = templateInstance; form.AllowMacroEditing = ((WebPartTypeEnum)wpi.WebPartType != WebPartTypeEnum.Wireframe); // Get data row with required columns DataRow dr = fi.GetDataRow(true); if (IsNewWebPart || (xmlVersion > 0)) { fi.LoadDefaultValues(dr); } // Load values from existing web part LoadDataRowFromWebPart(dr, webPartInstance, fi); // Set a unique WebPartControlID for the new variant if (IsNewVariant || IsNewWebPart) { // Set control ID dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance); } // Init the form InitForm(form, dr, fi); AddExportLink(); } else { UIContext.EditedObject = null; } } } }
protected void Page_Load(object sender, EventArgs e) { string aliasPath = QueryHelper.GetString("aliaspath", ""); string webpartId = QueryHelper.GetString("webpartid", ""); string zoneId = QueryHelper.GetString("zoneid", ""); Guid webpartGuid = QueryHelper.GetGuid("webpartguid", Guid.Empty); int templateId = QueryHelper.GetInteger("templateId", 0); PageTemplateInfo pti = null; if (templateId > 0) { pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId); } if (pti == null) { PageInfo pi = PageInfoProvider.GetPageInfo(SiteContext.CurrentSiteName, aliasPath, LocalizationContext.PreferredCultureCode, null, SiteContext.CurrentSite.CombineWithDefaultCulture); if (pi != null) { pti = pi.UsedPageTemplateInfo; } } if (pti != null) { // Get web part WebPartInstance webPart = pti.TemplateInstance.GetWebPart(webpartGuid, webpartId); if (webPart != null) { StringBuilder sb = new StringBuilder(); Hashtable properties = webPart.Properties; // Get the webpart object WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (wi != null) { // Add the header sb.Append("Webpart properties (" + wi.WebPartDisplayName + ")" + Environment.NewLine + Environment.NewLine); sb.Append("Alias path: " + aliasPath + Environment.NewLine); sb.Append("Zone ID: " + zoneId + Environment.NewLine + Environment.NewLine); string wpProperties = "<default></default>"; // Get the form info object and load it with the data if (wi.WebPartParentID > 0) { // Load parent properties WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (wpi != null) { wpProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WebPartProperties); } } else { wpProperties = wi.WebPartProperties; } FormInfo fi = new FormInfo(wpProperties); // General properties of webparts string beforeFormDefinition = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wi.WebPartType, PropertiesPosition.Before); string afterFormDefinition = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wi.WebPartType, PropertiesPosition.After); // General properties before custom if (!String.IsNullOrEmpty(beforeFormDefinition)) { // Load before definition fi = new FormInfo(FormHelper.MergeFormDefinitions(beforeFormDefinition, wpProperties, true)); // Add Default category for first before items sb.Append(Environment.NewLine + "Default" + Environment.NewLine + Environment.NewLine + Environment.NewLine); } // General properties after custom if (!String.IsNullOrEmpty(afterFormDefinition)) { // Load after definition fi = new FormInfo(FormHelper.MergeFormDefinitions(fi.GetXmlDefinition(), afterFormDefinition, true)); } // Generate all properties sb.Append(GetProperties(fi.GetFormElements(true, false), webPart)); // Send the text file to the user to download UTF8Encoding enc = new UTF8Encoding(); byte[] file = enc.GetBytes(sb.ToString()); Response.AddHeader("Content-disposition", "attachment; filename=webpartproperties_" + HTTPHelper.GetDispositionFilename(webPart.ControlID) + ".txt"); Response.ContentType = "text/plain"; Response.BinaryWrite(file); RequestHelper.EndResponse(); } } } }
/// <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> /// Init event handler. /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); // Setup basic form on live site formCustom.AllowMacroEditing = false; formCustom.IsLiveSite = IsLiveSite; // Load settings if (!String.IsNullOrEmpty(Request.Form[hdnIsNewWebPart.UniqueID])) { IsNewWidget = ValidationHelper.GetBoolean(Request.Form[hdnIsNewWebPart.UniqueID], false); } if (!String.IsNullOrEmpty(Request.Form[hdnInstanceGUID.UniqueID])) { InstanceGUID = ValidationHelper.GetGuid(Request.Form[hdnInstanceGUID.UniqueID], Guid.Empty); } // Try to find the widget variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = 0; if (VariantMode == VariantModeEnum.MVT) { variantIdFromDB = ModuleCommands.OnlineMarketingGetMVTVariantId(PageTemplateId, variantName); } else if (VariantMode == VariantModeEnum.ContentPersonalization) { variantIdFromDB = ModuleCommands.OnlineMarketingGetContentPersonalizationVariantId(PageTemplateId, variantName); } // Set the variant id from the database if (variantIdFromDB > 0) { VariantID = variantIdFromDB; IsNewVariant = false; } } } EnsureDashboard(); if (!String.IsNullOrEmpty(WidgetId) && !IsInline) { // Get pageinfo try { pi = CMSWebPartPropertiesPage.GetPageInfo(AliasPath, PageTemplateId); } catch (PageNotFoundException) { // Do not throw exception if page info not found (e.g. bad alias path) } if (pi == null) { lblInfo.Text = GetString("Widgets.Properties.aliasnotfound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } // Get template pti = pi.PageTemplateInfo; // Get template instance templateInstance = CMSPortalManager.GetTemplateInstanceForEditing(pi); if (!IsNewWidget) { // Get the instance of widget widgetInstance = templateInstance.GetWebPart(InstanceGUID, WidgetId); if (widgetInstance == null) { lblInfo.Text = GetString("Widgets.Properties.WidgetNotFound"); lblInfo.Visible = true; pnlFormArea.Visible = false; return; } if ((VariantID > 0) && (widgetInstance != null) && (widgetInstance.PartInstanceVariants != null)) { // Check OnlineMarketing permissions. if (CheckPermissions("Read")) { widgetInstance = pi.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId); widgetInstance = widgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID)); // Set the widget variant mode if (widgetInstance != null) { VariantMode = widgetInstance.VariantMode; } } else { // Not authorised for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (VariantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } // Get widget info by widget name(widget type) wi = WidgetInfoProvider.GetWidgetInfo(widgetInstance.WebPartType); } // Widget instance hasn't created yet else { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } CMSPage.EditedObject = wi; zoneType = ZoneType; // Get the zone to which it inserts WebPartZoneInstance zone = templateInstance.GetZone(ZoneId); if ((zoneType == WidgetZoneTypeEnum.None) && (zone != null)) { zoneType = zone.WidgetZoneType; } // Check security CurrentUserInfo currentUser = CMSContext.CurrentUser; switch (zoneType) { // Group zone => Only group widgets and group admin case WidgetZoneTypeEnum.Group: // Should always be, only group widget are allowed in group zone if (!wi.WidgetForGroup || (!currentUser.IsGroupAdministrator(pi.NodeGroupId) && ((CMSContext.ViewMode != ViewModeEnum.Design) || ((CMSContext.ViewMode == ViewModeEnum.Design) && (!currentUser.IsAuthorizedPerResource("CMS.Design", "Design")))))) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for editor zones case WidgetZoneTypeEnum.Editor: if (!wi.WidgetForEditor) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for user zones case WidgetZoneTypeEnum.User: if (!wi.WidgetForUser) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; // Widget must be allowed for dasboard zones case WidgetZoneTypeEnum.Dashboard: if (!wi.WidgetForDashboard) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } break; } // Check security if ((zoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { if (OnNotAllowed != null) { OnNotAllowed(this, null); } } // Get form schemas wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); FormInfo zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties FormFieldInfo[] ffi = fi.GetFields(true, false); if ((ffi == null) || (ffi.Length == 0)) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = CombineWithDefaultValues(fi, wi); // Load default values for new widget if (IsNewWidget) { fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); // Overide default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(wi.WidgetDisplayName)); } // Load values from existing widget LoadDataRowFromWidget(dr); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } if (IsInline) { //Load text definition from session string definition = ValidationHelper.GetString(SessionHelper.GetValue("WidgetDefinition"), string.Empty); if (String.IsNullOrEmpty(definition)) { definition = Request.Form[hdnWidgetDefinition.UniqueID]; } else { hdnWidgetDefinition.Value = definition; } Hashtable parameters = null; if (IsNewWidget) { // new wdiget - load widget info by id if (!String.IsNullOrEmpty(WidgetId)) { wi = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0)); } else { // Try to get widget from codename mName = QueryHelper.GetString("WidgetName", String.Empty); wi = WidgetInfoProvider.GetWidgetInfo(mName); } } else { if (definition == null) { ShowError("widget.failedtoload"); return; } //parse defininiton parameters = CMSDialogHelper.GetHashTableFromString(definition); //trim control name if (parameters["name"] != null) { mName = parameters["name"].ToString(); } wi = WidgetInfoProvider.GetWidgetInfo(mName); } if (wi == null) { ShowError("widget.failedtoload"); return; } //If widget cant be used asi inline if (!wi.WidgetForInline) { ShowError("widget.cantbeusedasinline"); return; } //Test permission for user CurrentUserInfo currentUser = CMSContext.CurrentUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(wi, currentUser.UserID, currentUser.IsAuthenticated())) { mIsValidWidget = false; OnNotAllowed(this, null); } //If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.IsEditor) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); FormInfo zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType); FormInfo fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), widgetProperties, zoneTypeDefinition, true); if (fi != null) { // Check if there are some editable properties mFields = fi.GetFields(true, true); if ((mFields == null) || (mFields.Length == 0)) { lblInfo.Visible = true; lblInfo.Text = GetString("widgets.emptyproperties"); } // Get datarows with required columns DataRow dr = CombineWithDefaultValues(fi, wi); if (IsNewWidget) { // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); } else { foreach (string key in parameters.Keys) { string value = parameters[key].ToString(); // Test if given property exists if (dr.Table.Columns.Contains(key) && !String.IsNullOrEmpty(value)) { try { dr[key] = value; } catch { } } } } // Overide default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); // Init HTML toolbar if exists InitHTMLToobar(fi); // Init the form InitForm(formCustom, dr, fi); // Set the context name formCustom.ControlContext.ContextName = CMS.SiteProvider.ControlContext.WIDGET_PROPERTIES; } } }
protected override string GetFileToSavePath(FormInfo formInfo) { return(Path.Combine(formInfo.BasePath, $"{formInfo.NameSpaceName}.IRepository\\{formInfo.NameSpaceName}.IRepository.csproj")); }
/// <summary> /// Returns name of the primary key column. /// </summary> /// <param name="fi">Form info</param> /// <param name="bizFormName">Bizform code name</param> private static string GetPrimaryColumn(FormInfo fi, string bizFormName) { string result = null; if ((fi != null) && (!string.IsNullOrEmpty(bizFormName))) { // Seek primary key column in all fields var query = from field in fi.GetFields(true, true) where field.PrimaryKey == true select field.Name; // Try to get field with the name 'bizformnameID' result = query.FirstOrDefault(x => x.ToLowerCSafe() == (bizFormName + "ID").ToLowerCSafe()); if (String.IsNullOrEmpty(result)) { result = query.FirstOrDefault(); } } return result; }
/// <summary> /// Loads form with specific settings for rule of type Activity. /// </summary> /// <param name="fi">FormInfo containing information about activity</param> /// <param name="activityType">Type of activity</param> private void LoadActivityForm(FormInfo fi, string activityType) { LoadForm(activityFormCondition, fi, activityType); }
/// <summary> /// Import files. /// </summary> private void Import(object parameter) { try { object[] parameters = (object[])parameter; string[] items = (string[])parameters[0]; CurrentUserInfo currentUser = (CurrentUserInfo)parameters[3]; if ((items.Length > 0) && (currentUser != null)) { resultListValues.Clear(); errorFiles.Clear(); hdnValue.Value = null; hdnSelected.Value = null; string siteName = CMSContext.CurrentSiteName; string targetAliasPath = ValidationHelper.GetString(parameters[1], null); bool imported = false; // Flag - true if one file was imported at least bool importError = false; // Flag - true when import failed TreeProvider tree = new TreeProvider(currentUser); TreeNode tn = tree.SelectSingleNode(siteName, targetAliasPath, TreeProvider.ALL_CULTURES, true, null, false); if (tn != null) { // Check if CMS.File document type exist and check if document contains required columns (FileName, FileAttachment) DataClassInfo fileClassInfo = DataClassInfoProvider.GetDataClass("CMS.File"); if (fileClassInfo == null) { AddError(GetString("newfile.classcmsfileismissing")); return; } else { FormInfo fi = new FormInfo(fileClassInfo.ClassFormDefinition); FormFieldInfo fileFfi = null; FormFieldInfo attachFfi = null; if (fi != null) { fileFfi = fi.GetFormField("FileName"); attachFfi = fi.GetFormField("FileAttachment"); } if ((fi == null) || (fileFfi == null) || (attachFfi == null)) { AddError(GetString("newfile.someofrequiredfieldsmissing")); return; } } DataClassInfo dci = DataClassInfoProvider.GetDataClass(tn.NodeClassName); if (dci != null) { // Check if "file" and "folder" are allowed as a child document under selected document type bool fileAllowed = false; bool folderAllowed = false; DataClassInfo folderClassInfo = DataClassInfoProvider.GetDataClass("CMS.Folder"); if ((fileClassInfo != null) || (folderClassInfo != null)) { string[] paths; foreach (string fullFileName in items) { paths = fullFileName.Substring(rootPath.Length).Split('\\'); // Check file if (paths.Length == 1) { if (!fileAllowed && (fileClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, fileClassInfo.ClassID)) { AddError(GetString("Tools.FileImport.NotAllowedChildClass")); return; } else { fileAllowed = true; } } // Check folder if (paths.Length > 1) { if (!folderAllowed && (folderClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, folderClassInfo.ClassID)) { AddError(GetString("Tools.FileImport.FolderNotAllowedChildClass")); return; } else { folderAllowed = true; } } if (fileAllowed && folderAllowed) { break; } } } // Check if user is allowed to create new file document if (fileAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.File")) { AddError(GetString("accessdenied.notallowedtocreatedocument")); return; } // Check if user is allowed to create new folder document if (folderAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.Folder")) { AddError(GetString("accessdenied.notallowedtocreatedocument")); return; } } string cultureCode = ValidationHelper.GetString(parameters[2], ""); string[] fileList = new string[1]; string[] relativePathList = new string[1]; // Begin log AddLog(GetString("tools.fileimport.importingprogress")); string msgImported = GetString("Tools.FileImport.Imported"); string msgFailed = GetString("Tools.FileImport.Failed"); // Insert files selected in datagrid to list of files to import foreach (string fullFileName in items) { // Import selected files only fileList[0] = fullFileName; relativePathList[0] = fullFileName.Substring(rootPath.Length); // Remove extension if needed if (!chkIncludeExtension.Checked) { relativePathList[0] = Regex.Replace(relativePathList[0], "(.*)\\..*", "$1"); } try { FileImport.ImportFiles(siteName, targetAliasPath, cultureCode, fileList, relativePathList, currentUser.UserID, chkDeleteImported.Checked); // Import of a file succeeded, fill the output lists resultListValues.Add(new string[] { fullFileName, msgImported, true.ToString() }); imported = true; // One file was imported AddLog(HTMLHelper.HTMLEncode(fullFileName)); } catch (Exception ex) { // File import failed errorFiles.Add(fullFileName); importError = true; // Fill the output lists resultListValues.Add(new string[] { fullFileName, msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")", false.ToString() }); AddError(msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")"); // Abort importing the rest of files for serious exceptions if (!(ex is UnauthorizedAccessException)) { return; } } } } // Specified alias path not found else { AddError(GetString("Tools.FileImport.AliasPathNotFound")); return; } if (filesList.Count > 0) { if (!importError) { if (imported) { AddError(GetString("Tools.FileImport.FilesWereImported")); return; } } else { AddError(GetString("Tools.FileImport.FilesNotImported")); return; } } } // No items selected to import else { AddError(GetString("Tools.FileImport.FilesNotImported")); return; } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled } else { // Log error LogExceptionToEventLog(ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex); } }
/// <summary> /// Generates the web part code. /// </summary> /// <param name="wpi">Web part info</param> /// <param name="baseControl">Base control nested within the web part</param> /// <param name="ascx">Returning ASCX code</param> /// <param name="code">Returning code behind</param> /// <param name="designer">Returning designer file</param> public static void GenerateWebPartCode(WebPartInfo wpi, string baseControl, out string ascx, out string code, out string designer) { code = ""; ascx = ""; designer = ""; if (wpi != null) { string templateFile = HttpContext.Current.Server.MapPath("~/App_Data/CodeTemplates/WebPart"); // Generate the ASCX ascx = File.ReadAllText(templateFile + ".ascx.template"); // Prepare the path string path = URLHelper.UnResolveUrl(WebPartInfoProvider.GetWebPartUrl(wpi), SettingsKeyProvider.ApplicationPath); // Prepare the class name string className = path.Trim('~', '/'); if (className.EndsWithCSafe(".ascx")) { className = className.Substring(0, className.Length - 5); } className = ValidationHelper.GetIdentifier(className, "_"); ascx = Regex.Replace(ascx, "(Inherits)=\"[^\"]+\"", "$1=\"" + className + "\""); // Replace the code file / code behind bool webApp = CMSContext.IsWebApplication; string fileAttr = "CodeFile"; //if (webApp) //{ // fileAttr = "CodeBehind"; //} ascx = Regex.Replace(ascx, "(CodeFile|CodeBehind)=\"[^\"]+\"", fileAttr + "=\"" + path + ".cs\""); // Generate the code code = File.ReadAllText(templateFile + ".ascx.cs.template"); code = Regex.Replace(code, "( class\\s+)[^\\s]+", "$1" + className); // Prepare the properties FormInfo fi = new FormInfo(wpi.WebPartProperties); StringBuilder sbInit = new StringBuilder(); string propertiesCode = CodeGenerator.GetPropertiesCode(fi, true, baseControl, sbInit, true); // Replace in code code = code.Replace("// ##PROPERTIES##", propertiesCode); code = code.Replace("// ##SETUP##", sbInit.ToString()); // Generate the designer if (webApp) { designer = File.ReadAllText(templateFile + ".ascx.designer.cs.template"); designer = Regex.Replace(designer, "( class\\s+)[^\\s]+", "$1" + className); } } }
/// <summary> /// Creates and initializes a new instance of the Panel class with the specified Data.com contact mapping, and returns it. /// </summary> /// <param name="formInfo">The CMS contact form info.</param> /// <param name="entityInfo">The Data.com contact entity info.</param> /// <param name="mapping">The Data.com contact mapping.</param> /// <returns>A new instance of the Panel class initialized with the specified Data.com contact mapping.</returns> private Panel CreateMappingPanel(FormInfo formInfo, EntityInfo entityInfo, EntityMapping mapping) { Panel mappingPanel = new Panel { CssClass = "mapping"}; mappingPanel.Controls.Add(CreateHeaderPanel()); foreach (IField formItem in formInfo.ItemsList) { FormFieldInfo formField = formItem as FormFieldInfo; if (formField != null) { EntityMappingItem mappingItem = mapping.GetItem(formField.Name); if (mappingItem != null) { EntityAttributeInfo entityAttribute = entityInfo.GetAttributeInfo(mappingItem.EntityAttributeName); if (entityAttribute != null) { Panel row = new Panel { CssClass = "control-group-inline" }; mappingPanel.Controls.Add(row); Panel formFieldPanel = new Panel { CssClass = "input-width-60 cms-form-group-text" }; row.Controls.Add(formFieldPanel); formFieldPanel.Controls.Add(new Literal { Text = ResHelper.LocalizeString(formField.GetDisplayName(MacroContext.CurrentResolver)) }); Panel entityAttributePanel = new Panel { CssClass = "input-width-60 cms-form-group-text" }; row.Controls.Add(entityAttributePanel); entityAttributePanel.Controls.Add(new Literal { Text = ResHelper.LocalizeString(entityAttribute.DisplayName) }); } } } } return mappingPanel; }
protected void EditForm_OnBeforeSave(object sender, EventArgs e) { MacroRuleInfo info = EditForm.EditedObject as MacroRuleInfo; if (info != null) { // Generate automatic fields when present in UserText FormEngineUserControl control = EditForm.FieldControls["MacroRuleText"]; if (control != null) { string userText = ValidationHelper.GetString(control.Value, ""); if (!string.IsNullOrEmpty(userText)) { Regex regex = RegexHelper.GetRegex("\\{[-_a-zA-Z0-9]*\\}"); MatchCollection match = regex.Matches(userText); if (match.Count > 0) { FormInfo fi = new FormInfo(info.MacroRuleParameters); foreach (Match m in match) { foreach (Capture c in m.Captures) { string name = c.Value.Substring(1, c.Value.Length - 2).ToLowerCSafe(); FormFieldInfo ffi = fi.GetFormField(name); if (ffi == null) { ffi = new FormFieldInfo(); ffi.Name = name; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 100; ffi.FieldType = FormFieldControlTypeEnum.CustomUserControl; ffi.Caption = "select operation"; ffi.AllowEmpty = true; switch (name) { case "_is": ffi.DefaultValue = ";is"; ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";is\r\n!;is not"; break; case "_was": ffi.DefaultValue = ";was"; ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";was\r\n!;was not"; break; case "_will": ffi.DefaultValue = ";will"; ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";will\r\n!;will not"; break; case "_has": ffi.DefaultValue = ";has"; ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";has\r\n!;does not have"; break; case "_perfectum": ffi.DefaultValue = ";has"; ffi.Settings["controlname"] = "MacroNegationOperator"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = ";has\r\n!;has not"; break; case "_any": ffi.DefaultValue = "false;any"; ffi.Settings["controlname"] = "macro_any-all_bool_selector"; ffi.Settings["EditText"] = "false"; ffi.Settings["Options"] = "false;any\r\ntrue;all"; break; default: ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl; ffi.Size = 1000; ffi.Caption = "enter text"; break; } fi.AddFormField(ffi); } } } info.MacroRuleParameters = fi.GetXmlDefinition(); } } } } if (!string.IsNullOrEmpty(ResourceName)) { EditForm.EditedObject.SetValue("MacroRuleResourceName", ResourceName); } EditForm.EditedObject.SetValue("MacroRuleIsCustom", !SettingsKeyProvider.DevelopmentMode); }
/// <summary> /// Adds the inline widget without the properties dialog. /// </summary> /// <param name="widgetId">The widget id</param> private string AddInlineWidgetWithoutDialog(int widgetId) { string script = string.Empty; if (widgetId > 0) { // New widget - load widget info by id WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetId); if ((wi != null) && wi.WidgetForInline) { // Test permission for user var currentUser = MembershipContext.AuthenticatedUser; if (!WidgetRoleInfoProvider.IsWidgetAllowed(widgetId, currentUser.UserID, AuthenticationHelper.IsAuthenticated())) { return(string.Empty); } // If user is editor, more properties are shown WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.User; if (currentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName)) { zoneType = WidgetZoneTypeEnum.Editor; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); // Merge the parent web part properties definition with the widget properties definition string widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); // Create the FormInfo for the current widget properties definition FormInfo fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, zoneType, widgetProperties, true); DataRow dr = null; if (fi != null) { // Get data rows with required columns dr = PortalHelper.CombineWithDefaultValues(fi, wi); // Load default values for new widget fi.LoadDefaultValues(dr, FormResolveTypeEnum.Visible); // Override default value and set title as widget display name DataHelper.SetDataRowValue(dr, "WidgetTitle", wi.WidgetDisplayName); } // Save inline widget script script = PortalHelper.GetAddInlineWidgetScript(wi, dr, fi.GetFields(true, true)); script += " CloseDialog(false);"; if (!string.IsNullOrEmpty(script)) { // Add to recently used widgets collection MembershipContext.AuthenticatedUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName); } } } return(script); }
protected void Page_Load(object sender, EventArgs e) { usReports.OnSelectionChanged += usReports_OnSelectionChanged; string [,]specialFields = new string [1,2]; pnlReports.Attributes.Add("style", "margin-bottom:3px"); string reportName = ValidationHelper.GetString(usReports.Value, String.Empty); ReportInfo ri = ReportInfoProvider.GetReportInfo(reportName); if (ri != null) { usItems.Enabled = true; //test if there is any item visible in report parameters FormInfo fi = new FormInfo(ri.ReportParameters); //Get dataset from cache DataSet ds = (DataSet)WindowHelper.GetItem(hdnGuid.Value); DataRow dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); bool itemVisible = false; List<FormItem> items = fi.ItemsList; foreach (FormItem item in items) { FormFieldInfo ffi = item as FormFieldInfo; if (ffi != null) { if (ffi.Visible) { itemVisible = true; break; } } } ReportID = ri.ReportID; if (!itemVisible) { plcParametersButtons.Visible = false; } else { plcParametersButtons.Visible = true; } } else { plcParametersButtons.Visible = false; usItems.Enabled = false; } ltlScript.Text = ScriptHelper.GetScript("function refresh () {" + ControlsHelper.GetPostBackEventReference(pnlUpdate, String.Empty) + "}"); usReports.DropDownSingleSelect.AutoPostBack = true; if (!mDisplay) { pnlReports.Visible = false; plcParametersButtons.Visible = false; usItems.Enabled = true; } if (!ShowItemSelector) { pnlItems.Visible = false; } usItems.IsLiveSite = IsLiveSite; usReports.IsLiveSite = IsLiveSite; ugParameters.GridName = "~/CMSModules/Reporting/FormControls/ReportParametersList.xml"; ugParameters.ZeroRowsText = String.Empty; ugParameters.PageSize = "##ALL##"; ugParameters.Pager.DefaultPageSize = -1; BuildConditions(); // First item as "please select string" - not default "none" usItems.AllowEmpty = false; usReports.AllowEmpty = false; specialFields[0, 0] = "(" + GetString("rep.pleaseselect") + ")"; specialFields[0, 1] = "0"; usReports.SpecialFields = specialFields; if (ri == null) { string[,] itemSpecialFields = new string[1, 2]; itemSpecialFields[0, 0] = "(" + firstItemText + ")"; itemSpecialFields[0, 1] = "0"; usItems.SpecialFields = itemSpecialFields; } if (ShowItemSelector) { ReloadItems(); } }
/// <summary> /// Loads custom fields collisions. /// </summary> private void LoadCustomFields() { // Check if contact has any custom fields FormInfo formInfo = FormHelper.GetFormInfo(mParentContact.ClassName, false); var list = formInfo.GetFormElements(true, false, true); if (list.OfType <FormFieldInfo>().Any()) { FormFieldInfo ffi; Literal content; LocalizedLabel lbl; CMSTextBox txt; content = new Literal(); content.Text = "<div class=\"form-horizontal form-merge-collisions\">"; plcCustomFields.Controls.Add(content); foreach (IField item in list) { ffi = item as FormFieldInfo; if (ffi != null) { // Display layout content = new Literal(); content.Text = "<div class=\"form-group\"><div class=\"editing-form-label-cell\">"; plcCustomFields.Controls.Add(content); lbl = new LocalizedLabel(); lbl.Text = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver); lbl.DisplayColon = true; lbl.EnableViewState = false; lbl.CssClass = "control-label"; content = new Literal(); content.Text = "</div><div class=\"editing-form-value-cell\"><div class=\"control-group-inline-forced\">"; txt = new CMSTextBox(); txt.ID = "txt" + ffi.Name; lbl.AssociatedControlID = txt.ID; plcCustomFields.Controls.Add(lbl); plcCustomFields.Controls.Add(content); plcCustomFields.Controls.Add(txt); mCustomFields.Add(ffi.Name, new object[] { txt, ffi.DataType }); DataTable dt; // Get grouped dataset if (DataTypeManager.IsString(TypeEnum.Field, ffi.DataType)) { dt = SortGroupContactsByColumn(ffi.Name + SqlHelper.ORDERBY_ASC, ffi.Name + " NOT LIKE ''", ffi.Name); } else { dt = SortGroupContactsByColumn(ffi.Name + SqlHelper.ORDERBY_ASC, ffi.Name + " IS NOT NULL", ffi.Name); } // Load value into textbox txt.Text = ValidationHelper.GetString(mParentContact.GetValue(ffi.Name), null); if (string.IsNullOrEmpty(txt.Text) && (dt.Rows.Count > 0)) { txt.Text = ValidationHelper.GetString(dt.Rows[0][ffi.Name], null); } var img = new HtmlGenericControl("i"); img.Attributes["class"] = "validation-warning icon-exclamation-triangle form-control-icon"; DisplayTooltip(img, dt, ffi.Name, ValidationHelper.GetString(mParentContact.GetValue(ffi.Name), ""), ffi.DataType); plcCustomFields.Controls.Add(img); content = new Literal(); content.Text = "</div></div></div>"; plcCustomFields.Controls.Add(content); mMergedContacts.Tables[0].DefaultView.RowFilter = null; } } content = new Literal(); content.Text = "</div>"; plcCustomFields.Controls.Add(content); } else { tabCustomFields.Visible = false; tabCustomFields.HeaderText = null; } }
/// <summary> /// Initializes the HTML toolbar. /// </summary> /// <param name="form">Form information</param> private void InitHTMLToobar(FormInfo form) { // Display / hide the HTML editor toolbar area if (form.UsesHtmlArea()) { plcToolbar.Visible = true; } }
/// <summary> /// Import files. /// </summary> private void Import(object parameter) { try { object[] parameters = (object[])parameter; string[] items = (string[])parameters[0]; CurrentUserInfo currentUser = (CurrentUserInfo)parameters[3]; if ((items.Length > 0) && (currentUser != null)) { resultListIndex = null; resultListValues = null; errorFiles = null; hdnValue.Value = null; hdnSelected.Value = null; string siteName = CMSContext.CurrentSiteName; string targetAliasPath = ValidationHelper.GetString(parameters[1], null); bool imported = false; // Flag - true if one file was imported at least bool importError = false; // Flag - true when import failed TreeProvider tree = new TreeProvider(currentUser); TreeNode tn = tree.SelectSingleNode(siteName, targetAliasPath, TreeProvider.ALL_CULTURES, true, null, false); if (tn != null) { // Check if CMS.File document type exist and check if document contains required columns (FileName, FileAttachment) DataClassInfo fileClassInfo = DataClassInfoProvider.GetDataClass("CMS.File"); if (fileClassInfo == null) { AddError(GetString("newfile.classcmsfileismissing")); return; } else { FormInfo fi = new FormInfo(fileClassInfo.ClassFormDefinition); FormFieldInfo fileFfi = null; FormFieldInfo attachFfi = null; if (fi != null) { fileFfi = fi.GetFormField("FileName"); attachFfi = fi.GetFormField("FileAttachment"); } if ((fi == null) || (fileFfi == null) || (attachFfi == null)) { AddError(GetString("newfile.someofrequiredfieldsmissing")); return; } } DataClassInfo dci = DataClassInfoProvider.GetDataClass(tn.NodeClassName); if (dci != null) { // Check if "file" and "folder" are allowed as a child document under selected document type bool fileAllowed = false; bool folderAllowed = false; DataClassInfo folderClassInfo = DataClassInfoProvider.GetDataClass("CMS.Folder"); if ((fileClassInfo != null) || (folderClassInfo != null)) { string[] paths; foreach (string fullFileName in items) { paths = fullFileName.Substring(rootPath.Length).Split('\\'); // Check file if (paths.Length == 1) { if (!fileAllowed && (fileClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, fileClassInfo.ClassID)) { AddError(GetString("Tools.FileImport.NotAllowedChildClass")); return; } else { fileAllowed = true; } } // Check folder if (paths.Length > 1) { if (!folderAllowed && (folderClassInfo != null) && !DataClassInfoProvider.IsChildClassAllowed(dci.ClassID, folderClassInfo.ClassID)) { AddError(GetString("Tools.FileImport.FolderNotAllowedChildClass")); return; } else { folderAllowed = true; } } if (fileAllowed && folderAllowed) { break; } } } // Check if user is allowed to create new file document if (fileAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.File")) { AddError(GetString("accessdenied.notallowedtocreatedocument")); return; } // Check if user is allowed to create new folder document if (folderAllowed && !currentUser.IsAuthorizedToCreateNewDocument(tn, "CMS.Folder")) { AddError(GetString("accessdenied.notallowedtocreatedocument")); return; } } string cultureCode = ValidationHelper.GetString(parameters[2], ""); string[] fileList = new string[1]; string[] relativePathList = new string[1]; // Begin log AddLog(GetString("tools.fileimport.importingprogress")); if (items.Length > 0) { // Initialize output arrays - we have atleast 1 file if (resultListIndex == null) { resultListIndex = new ArrayList(); } if (resultListValues == null) { resultListValues = new ArrayList(); } } string msgImported = GetString("Tools.FileImport.Imported"); string msgFailed = GetString("Tools.FileImport.Failed"); // Insert files selected in datagrid to list of files to import foreach (string fullFileName in items) { // Import selected files only fileList[0] = fullFileName; relativePathList[0] = fullFileName.Substring(rootPath.Length); // Remove extension if needed if (!chkIncludeExtension.Checked) { relativePathList[0] = Regex.Replace(relativePathList[0], "(.*)\\..*", "$1"); } try { FileImport.ImportFiles(siteName, targetAliasPath, cultureCode, fileList, relativePathList, currentUser.UserID, chkDeleteImported.Checked); // Import of a file succeeded, fill the output lists resultListIndex.Add(fullFileName); resultListValues.Add(new string[] { fullFileName, msgImported, true.ToString() }); imported = true; // One file was imported AddLog(HTMLHelper.HTMLEncode(fullFileName)); } catch (Exception ex) { // File import failed if (errorFiles == null) { errorFiles = new ArrayList(); } errorFiles.Add(fullFileName); importError = true; // Fill the output lists resultListIndex.Add(fullFileName); resultListValues.Add(new string[] { fullFileName, msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")", false.ToString() }); AddError(msgFailed + " (" + HTMLHelper.HTMLEncode(ex.Message) + ")"); // Abort importing the rest of files for serious exceptions if (!(ex is UnauthorizedAccessException)) { return; } } } } // Specified alias path not found else { AddError(GetString("Tools.FileImport.AliasPathNotFound")); return; } if (filesList.Count > 0) { if (!importError) { if (imported) { AddError(GetString("Tools.FileImport.FilesWereImported")); return; } } else { AddError(GetString("Tools.FileImport.FilesNotImported")); return; } } } // No items selected to import else { AddError(GetString("Tools.FileImport.FilesNotImported")); return; } } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled } else { // Log error LogExceptionToEventLog(ex); } } catch (Exception ex) { // Log error LogExceptionToEventLog(ex); } }
public static void Update60() { EventLogProvider evp = new EventLogProvider(); evp.LogEvent("I", DateTime.Now, "Upgrade to 6.0", "Upgrade - Start"); DataClassInfo dci = null; #region "CMS.UserSettings" try { dci = DataClassInfoProvider.GetDataClass("cms.usersettings"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "UserAuthenticationGUID"; ffi.DataType = FormFieldDataTypeEnum.GUID; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "UserBounces"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl; ffi.Visible = false; ffi.Caption = "UserBounces"; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "UserLinkedInID"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 100; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "UserLogActivities"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "UserPasswordRequestHash"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 100; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("CMS_UserSettings"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("CMS_UserSettings"); } } } catch (Exception ex) { evp.LogEvent("CMS.UserSettings - Upgrade", "Upgrade", ex); } #endregion #region "Ecommerce - Customer" try { dci = DataClassInfoProvider.GetDataClass("ecommerce.customer"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "CustomerSiteID"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.TextBoxControl; ffi.Visible = false; fi.AddFormField(ffi); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassFormDefinition = fi.GetXmlDefinition(); dci.ClassXmlSchema = tm.GetXmlSchema("COM_Customer"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("COM_Customer"); } } } catch (Exception ex) { evp.LogEvent("Ecommerce.Customer - Upgrade", "Upgrade", ex); } #endregion #region "Ecommerce - Order" try { dci = DataClassInfoProvider.GetDataClass("ecommerce.order"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "OrderCulture"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 10; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderIsPaid"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderTotalPriceInMainCurrency"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = fi.GetFormField("OrderStatusID"); if (ffi != null) { ffi.AllowEmpty = true; fi.UpdateFormField("OrderStatusID", ffi); } ffi = fi.GetFormField("OrderShippingAddressID"); if (ffi != null) { ffi.AllowEmpty = true; fi.UpdateFormField("OrderShippingAddressID", ffi); } dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("COM_Order"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("COM_Order"); } } } catch (Exception ex) { evp.LogEvent("Ecommerce.Order - Upgrade", "Upgrade", ex); } #endregion #region "Ecommerce - OrderItem" try { dci = DataClassInfoProvider.GetDataClass("ecommerce.orderitem"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "OrderItemBundleGUID"; ffi.DataType = FormFieldDataTypeEnum.GUID; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemIsPrivate"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemPrice"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemSendNotification"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemSKU"; ffi.DataType = FormFieldDataTypeEnum.LongText; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemText"; ffi.DataType = FormFieldDataTypeEnum.LongText; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemTotalPriceInMainCurrency"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "OrderItemValidTo"; ffi.DataType = FormFieldDataTypeEnum.DateTime; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("COM_OrderItem"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("COM_OrderItem"); } } } catch (Exception ex) { evp.LogEvent("Ecommerce.OrderItem - Upgrade", "Upgrade", ex); } #endregion #region "Ecommerce - Shopping cart item" try { dci = DataClassInfoProvider.GetDataClass("ecommerce.shoppingcartitem"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "CartItemBundleGUID"; ffi.DataType = FormFieldDataTypeEnum.GUID; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "CartItemIsPrivate"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "CartItemPrice"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "CartItemText"; ffi.DataType = FormFieldDataTypeEnum.LongText; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "CartItemValidTo"; ffi.DataType = FormFieldDataTypeEnum.DateTime; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = fi.GetFormField("CartItemGuid"); if (ffi != null) { ffi.AllowEmpty = true; fi.UpdateFormField("CartItemGuid", ffi); } dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("COM_ShoppingCartSKU"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("COM_ShoppingCartSKU"); } } } catch (Exception ex) { evp.LogEvent("Ecommerce.ShoppingCartItem - Upgrade", "Upgrade", ex); } #endregion #region "Ecommerce - SKU" try { dci = DataClassInfoProvider.GetDataClass("ecommerce.sku"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "SKUBundleInventoryType"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 50; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUConversionName"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 100; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUConversionValue"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 200; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUMaxDownloads"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUMaxItemsInOrder"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUMaxPrice"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUMembershipGUID"; ffi.DataType = FormFieldDataTypeEnum.GUID; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUMinPrice"; ffi.DataType = FormFieldDataTypeEnum.Decimal; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUNeedsShipping"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUPrivateDonation"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUProductType"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 50; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUSiteID"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUValidFor"; ffi.DataType = FormFieldDataTypeEnum.Integer; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUValidity"; ffi.DataType = FormFieldDataTypeEnum.Text; ffi.Size = 50; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = new FormFieldInfo(); ffi.Name = "SKUValidUntil"; ffi.DataType = FormFieldDataTypeEnum.DateTime; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); ffi = fi.GetFormField("SKUDepartmentID"); if (ffi != null) { ffi.AllowEmpty = true; fi.UpdateFormField("SKUDepartmentID", ffi); } dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("COM_SKU"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("COM_SKU"); } } } catch (Exception ex) { evp.LogEvent("Ecommerce.SKU - Upgrade", "Upgrade", ex); } #endregion #region "Community - Group" try { dci = DataClassInfoProvider.GetDataClass("Community.Group"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "GroupLogActivity"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.CheckBoxControl; ffi.Visible = true; ffi.DefaultValue = "true"; ffi.Caption = "GroupLogActivity"; fi.AddFormField(ffi); dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("Community_Group"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("Community_Group"); } } } catch (Exception ex) { evp.LogEvent("Community.Group - Upgrade", "Upgrade", ex); } #endregion #region "Newsletter - Subscriber" try { dci = DataClassInfoProvider.GetDataClass("newsletter.subscriber"); if (dci != null) { FormInfo fi = new FormInfo(dci.ClassFormDefinition); if (fi != null) { FormFieldInfo ffi = new FormFieldInfo(); ffi.Name = "SubscriberBounces"; ffi.DataType = FormFieldDataTypeEnum.Boolean; ffi.AllowEmpty = true; ffi.PublicField = false; ffi.System = true; ffi.FieldType = FormFieldControlTypeEnum.LabelControl; ffi.Visible = false; fi.AddFormField(ffi); dci.ClassFormDefinition = fi.GetXmlDefinition(); TableManager tm = new TableManager(dci.ClassConnectionString); dci.ClassXmlSchema = tm.GetXmlSchema("Newsletter_Subscriber"); DataClassInfoProvider.SetDataClass(dci); // Generate queries SqlGenerator.GenerateDefaultQueries(dci, true, false); tm.RefreshCustomViews("Newsletter_Subscriber"); } } } catch (Exception ex) { evp.LogEvent("Newsletter.Subscriber - Upgrade", "Upgrade", ex); } #endregion #region "CMS.Document" try { dci = DataClassInfoProvider.GetDataClass("cms.document"); if (dci != null) { SearchSettings ss = dci.ClassSearchSettingsInfos; SearchSettingsInfo ssi = ss.GetSettingsInfo("42f446ee-9818-4596-8124-54a38f64aa05"); if (ssi != null) { ssi.Searchable = true; ss.SetSettingsInfo(ssi); } DataClassInfoProvider.SetDataClass(dci); } } catch (Exception ex) { evp.LogEvent("CMS.Document - Upgrade", "Upgrade", ex); } #endregion // Set the path to the upgrade package mUpgradePackagePath = HttpContext.Current.Server.MapPath("~/CMSSiteUtils/Import/upgrade_55R2_60.zip"); mWebsitePath = HttpContext.Current.Server.MapPath("~/"); TableManager dtm = new TableManager(null); // Update all views dtm.RefreshDocumentViews(); // Set data version ObjectHelper.SetSettingsKeyValue("CMSDataVersion", "6.0"); // Clear hashtables CMSObjectHelper.ClearHashtables(); // Clear the cache CacheHelper.ClearCache(null, true); // Drop the routes CMSMvcHandler.DropAllRoutes(); // Init the Mimetype helper (required for the Import) MimeTypeHelper.LoadMimeTypes(); CMSThread thread = new CMSThread(Upgrade60Import); thread.Start(); }
protected void Page_Load(object sender, EventArgs e) { StringSafeDictionary <object> decodedProperties = new StringSafeDictionary <object>(); foreach (DictionaryEntry param in Properties) { // Decode special CK editor char String str = String.Empty; if (param.Value != null) { str = param.Value.ToString().Replace("%25", "%"); } decodedProperties[param.Key] = HttpUtility.UrlDecode(str); } Properties = decodedProperties; string widgetName = ValidationHelper.GetString(Properties["name"], String.Empty); // Widget name must be specified if (String.IsNullOrEmpty(widgetName)) { AddErrorWebPart("widgets.invalidname", null); return; } WidgetInfo wi = WidgetInfoProvider.GetWidgetInfo(widgetName); if (wi == null) { AddErrorWebPart("widget.failedtoload", null); return; } WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(wi.WidgetWebPartID); if (wpi == null) { return; } //no widgets can be used as inline if (!wi.WidgetForInline) { AddErrorWebPart("widgets.cantbeusedasinline", null); return; } try { FormInfo fi = null; DataRow dr = null; using (var cs = new CachedSection <FormInfo>(ref fi, 1440, (PortalContext.ViewMode == ViewModeEnum.LiveSite), null, "inlinewidgetcontrol", wi.WidgetID, wpi.WebPartID)) { if (cs.LoadData) { // Merge widget and it's parent webpart properties string props = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties); // Prepare form const WidgetZoneTypeEnum zoneType = WidgetZoneTypeEnum.Editor; fi = PortalFormHelper.GetWidgetFormInfo(wi.WidgetName, zoneType, props, true, wi.WidgetDefaultValues); // Apply changed values dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.webpart|byid|" + wpi.WebPartID + "\n" + "cms.widget|byid|" + wi.WidgetID); } cs.Data = fi; } } // Get datarow if (dr == null) { dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); } // Incorporate inline parameters to datarow string publicFields = ";containertitle;container;"; if (wi.WidgetPublicFileds != null) { publicFields += ";" + wi.WidgetPublicFileds.ToLowerCSafe() + ";"; } // Load the widget control string url = null; // Set widget layout WebPartLayoutInfo wpli = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(wi.WidgetLayoutID); if (wpli != null) { // Load specific layout through virtual path url = wpli.Generalized.GetVirtualFileRelativePath(WebPartLayoutInfo.EXTERNAL_COLUMN_CODE, wpli.WebPartLayoutVersionGUID); } else { // Load regularly url = WebPartInfoProvider.GetWebPartUrl(wpi, false); } CMSAbstractWebPart control = (CMSAbstractWebPart)Page.LoadUserControl(url); control.PartInstance = new WebPartInstance(); // Use current page placeholder control.PagePlaceholder = PortalHelper.FindParentPlaceholder(this); // Set all form values to webpart foreach (DataColumn column in dr.Table.Columns) { object value = dr[column]; string columnName = column.ColumnName.ToLowerCSafe(); //Resolve set values by user if (Properties.Contains(columnName)) { FormFieldInfo ffi = fi.GetFormField(columnName); if ((ffi != null) && ffi.Visible && ((ffi.DisplayIn == null) || !ffi.DisplayIn.Contains(FormInfo.DISPLAY_CONTEXT_DASHBOARD))) { value = Properties[columnName]; } } // Resolve macros in defined in default values if (!String.IsNullOrEmpty(value as string)) { // Do not resolve macros for public fields if (publicFields.IndexOfCSafe(";" + columnName + ";") < 0) { // Check whether current column bool avoidInjection = control.SQLProperties.Contains(";" + columnName + ";"); // Resolve macros MacroSettings settings = new MacroSettings() { AvoidInjection = avoidInjection, }; value = control.ContextResolver.ResolveMacros(value.ToString(), settings); } } control.PartInstance.SetValue(column.ColumnName, value); } control.PartInstance.IsWidget = true; // Load webpart content control.OnContentLoaded(); // Add webpart to controls collection Controls.Add(control); // Handle DisableViewstate setting control.EnableViewState = !control.DisableViewState; } catch (Exception ex) { AddErrorWebPart("widget.failedtoload", ex); } }
/// <summary> /// Adds the extra activity fields to the rule settings form. /// </summary> /// <param name="ignoredColumns">Collection of columns, which shouldn't be added</param> /// <param name="fi">Form info used for adding extra fields</param> /// <param name="additionalFieldsForm">Collection of extra fields</param> private static void AddExtraActivityFields(IEnumerable <string> ignoredColumns, FormInfo fi, FormInfo additionalFieldsForm) { if (additionalFieldsForm != null) { IEnumerable <FormFieldInfo> formFields = additionalFieldsForm.GetFields(true, false) .Where(f => !ignoredColumns.Contains(f.Name.ToLowerCSafe()) ); foreach (FormFieldInfo ffi in formFields) { ffi.Settings["controlname"] = GetControlNameForFieldDataType(ffi); fi.AddFormItem(ffi); } } }
private void ProcessAjaxPostBack() { if (RequestHelper.IsPostBack()) { string eventArgument = Request.Params.Get("__EVENTARGUMENT"); if (!string.IsNullOrEmpty(eventArgument)) { string errorMessage; string[] data = eventArgument.Split(':'); switch (data[0]) { case "loadSettings": { FieldName = data[1]; LoadSettings(FieldName); } break; case "remove": { // Hide selected field from form FieldName = string.Empty; errorMessage = HideField(data[2]); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } mReloadForm = true; pnlSettings.Update(); } break; case "hideSettingsPanel": { FieldName = string.Empty; pnlSettings.Update(); } break; case "saveSettings": { FormFieldInfo ffi = FormInfo.GetFormField(FieldName); FormFieldInfo originalFieldInfo = (FormFieldInfo)ffi.Clone(); pnlSettings.SaveSettings(ffi); errorMessage = SaveFormDefinition(originalFieldInfo, ffi); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } mReloadField = true; } break; case "addField": { FormFieldInfo ffi = PrepareNewField(data[1]); FieldName = ffi.Name; errorMessage = AddField(ffi, data[2], ValidationHelper.GetInteger(data[3], -1)); if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); return; } LoadSettings(FieldName); mReloadForm = true; } break; } } } }
/// <summary> /// Adds form field info to the form to the specified position. /// </summary> /// <param name="ffi">Form field info which will be added</param> /// <param name="category">Category name</param> /// <param name="position">Field position in the category</param> private string AddField(FormFieldInfo ffi, string category, int position) { if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.form", "EditForm")) { RedirectToAccessDenied("cms.form", "EditForm"); } var dci = DataClassInfoProvider.GetDataClassInfo(ClassName); if (dci != null) { RaiseBeforeDefinitionUpdate(); // Ensure the transaction using (var tr = new CMSLateBoundTransaction()) { // Raise event for field addition using (var h = DataDefinitionItemEvents.AddItem.StartEvent(dci, ffi)) { string columnType = DataTypeManager.GetSqlType(ffi.DataType, ffi.Size, ffi.Precision); TableManager tm = new TableManager(dci.ClassConnectionString); tr.BeginTransaction(); // Add new column tm.AddTableColumn(dci.ClassTableName, ffi.Name, columnType, true, null); // Add field to form FormInfo.AddFormItem(ffi); if (!String.IsNullOrEmpty(category) || position >= 0) { FormInfo.MoveFormFieldToPositionInCategory(ffi.Name, category, position); } // Update form definition dci.ClassFormDefinition = FormInfo.GetXmlDefinition(); // Update class schema dci.ClassXmlSchema = tm.GetXmlSchema(dci.ClassTableName); try { // Save the class data DataClassInfoProvider.SetDataClassInfo(dci); } catch (Exception) { return(GetString("FormBuilder.ErrorSavingForm")); } h.FinishEvent(); } QueryInfoProvider.ClearDefaultQueries(dci, true, true); // Hide field for alternative forms that require it FormHelper.HideFieldInAlternativeForms(ffi, dci); // Commit the transaction tr.Commit(); } ClearHashtables(); RaiseAfterDefinitionUpdate(); // Update inherited classes with new fields FormHelper.UpdateInheritedClasses(dci); } else { return(GetString("FormBuilder.ErrorSavingForm")); } return(string.Empty); }
/// <summary> /// Fills list of available fields. /// </summary> protected void FillFieldsList() { FormInfo fi = null; FormFieldInfo[] visibleFields = null; DataClassInfo dci = DataClassInfoProvider.GetDataClass(DataClassID); if (dci != null) { // Load form definition string formDefinition = dci.ClassFormDefinition; if (IsAlternative) { // Get alternative form definition and merge if with the original one AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(ObjectID); if (afi.FormCoupledClassID > 0) { // If coupled class is defined combine form definitions DataClassInfo coupledDci = DataClassInfoProvider.GetDataClass(afi.FormCoupledClassID); if (coupledDci != null) { formDefinition = FormHelper.MergeFormDefinitions(formDefinition, coupledDci.ClassFormDefinition, true); } } // Merge class and alternative form definitions formDefinition = FormHelper.MergeFormDefinitions(formDefinition, afi.FormDefinition); } fi = new FormInfo(formDefinition); // Get visible fields visibleFields = fi.GetFields(true, false); lstAvailableFields.Items.Clear(); if (FormType == FORMTYPE_DOCUMENT) { if (dci.ClassNodeNameSource == "") //if node name source is not set { lstAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentName"), "DocumentName")); } } if (visibleFields != null) { // Add public visible fields to the list foreach (FormFieldInfo ffi in visibleFields) { lstAvailableFields.Items.Add(new ListItem(ffi.Name, ffi.Name)); } } if (FormType == FORMTYPE_DOCUMENT) { if (dci.ClassUsePublishFromTo) { lstAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentPublishFrom"), "DocumentPublishFrom")); lstAvailableFields.Items.Add(new ListItem(GetString("DocumentType_Edit_Form.DocumentPublishTo"), "DocumentPublishTo")); } } lstAvailableFields.SelectedIndex = 0; } }
protected override string GetFileToSavePath(FormInfo formInfo) { return(Path.Combine(formInfo.BasePath, $"{formInfo.NameSpaceName}.Entity\\{formInfo.TableName}.cs")); }
protected override void OnPreRender(EventArgs e) { //apply reportid condition if report was selected wia uniselector string reportName = ValidationHelper.GetString(usReports.Value, String.Empty); ReportInfo ri = ReportInfoProvider.GetReportInfo(reportName); if (ri != null) { FormInfo fi = new FormInfo(ri.ReportParameters); DataRow dr = fi.GetDataRow(); DataSet ds = this.CurrentDataSet; this.ViewState["ParametersXmlData"] = null; this.ViewState["ParametersXmlSchema"] = null; if (!DataHelper.DataSourceIsEmpty(ds)) { this.ViewState["ParametersXmlData"] = ds.GetXml(); this.ViewState["ParametersXmlSchema"] = ds.GetXmlSchema(); } if (!keepDataInWindowsHelper) { WindowHelper.Remove(CurrentGuid().ToString()); } if (!DataHelper.DataSourceIsEmpty(ds)) { ds = DataHelper.DataSetPivot(ds, new string[] { "ParameterName", "ParameterValue" }); ugParameters.DataSource = ds; ugParameters.ReloadData(); pnlParameters.Visible = true; } else { pnlParameters.Visible = false; } } else { pnlParameters.Visible = false; } base.OnPreRender(e); }
public string GetContent(FormInfo formInfo) { return(CreateContent(formInfo)); }
/// <summary> /// Initializes the form. /// </summary> /// <param name="form">Form</param> /// <param name="dr">Datarow with the data</param> /// <param name="fi">Form info</param> private void InitForm(BasicForm form, DataRow dr, FormInfo fi) { form.DataRow = dr; form.MacroTable = widgetInstance != null ? widgetInstance.MacroTable : new Hashtable(StringComparer.InvariantCultureIgnoreCase); form.SubmitButton.Visible = false; form.SiteName = SiteContext.CurrentSiteName; form.FormInformation = fi; form.ShowPrivateFields = true; form.OnItemValidation += formElem_OnItemValidation; form.Mode = IsNewWidget ? FormModeEnum.Insert : FormModeEnum.Update; form.ReloadData(); }
private bool FillLBForms() { if (allModifying) { return(false); } LB_Forms.DataSource = null; LB_Forms.Items.Clear(); int fspecies = LB_Species.SelectedIndex + 1; var bspecies = Dex.GetBaseSpecies(fspecies); bool hasForms = FormInfo.HasFormSelection(SAV.Personal[bspecies], bspecies, 7); LB_Forms.Enabled = hasForms; if (!hasForms) { return(false); } var ds = FormConverter.GetFormList(bspecies, GameInfo.Strings.types, GameInfo.Strings.forms, Main.GenderSymbols, SAV.Generation).ToList(); if (ds.Count == 1 && string.IsNullOrEmpty(ds[0])) { // empty LB_Forms.Enabled = false; return(false); } // sanity check forms -- SM does not have totem form dex bits int count = SAV.Personal[bspecies].FormCount; if (count < ds.Count) { ds.RemoveAt(count); // remove last } LB_Forms.DataSource = ds; if (fspecies <= SAV.MaxSpeciesID) { LB_Forms.SelectedIndex = 0; } else { int fc = SAV.Personal[bspecies].FormCount; if (fc <= 1) { return(true); } int f = Dex.DexFormIndexFetcher(bspecies, fc, SAV.MaxSpeciesID - 1); if (f < 0) { return(true); // bit index valid } if (f > fspecies - LB_Forms.Items.Count - 1) { LB_Forms.SelectedIndex = fspecies - f - 1; } else { LB_Forms.SelectedIndex = -1; } } return(true); }
/// <summary> /// Loads the data row data from given web part instance. /// </summary> /// <param name="dr">DataRow to fill</param> private void LoadDataRowFromWidget(DataRow dr, FormInfo fi) { if (widgetInstance != null) { foreach (DataColumn column in dr.Table.Columns) { try { bool load = true; // switch by xml version switch (xmlVersion) { case 1: load = widgetInstance.Properties.Contains(column.ColumnName.ToLowerCSafe()) || column.ColumnName.EqualsCSafe("webpartcontrolid", true); break; // Version 0 default: // Load default value for Boolean type in old XML version if ((column.DataType == typeof(bool)) && !widgetInstance.Properties.Contains(column.ColumnName.ToLowerCSafe())) { FormFieldInfo ffi = fi.GetFormField(column.ColumnName); if (ffi != null) { widgetInstance.SetValue(column.ColumnName, ffi.GetPropertyValue(FormFieldPropertyEnum.DefaultValue)); } } break; } if (load) { object value = widgetInstance.GetValue(column.ColumnName); // Convert value into default format if ((value != null) && (value.ToString() != "")) { if (column.DataType == typeof(decimal)) { value = ValidationHelper.GetDouble(value, 0, "en-us"); } if (column.DataType == typeof(DateTime)) { value = ValidationHelper.GetDateTime(value, DateTime.Now, "en-us"); } } DataHelper.SetDataRowValue(dr, column.ColumnName, value); } } catch { } } } }
/// <summary> /// Initializes controls on the page. /// </summary> protected void InitializeControls() { DataClassInfo classInfo = DataClassInfoProvider.GetDataClass(ClassName); if (classInfo == null) { return; } // Set class names fldAddress1.ClassName = ClassName; fldAddress2.ClassName = ClassName; fldBirthday.ClassName = ClassName; fldBusinessPhone.ClassName = ClassName; fldCity.ClassName = ClassName; fldCountry.ClassName = ClassName; fldEmail.ClassName = ClassName; fldFirstName.ClassName = ClassName; fldGender.ClassName = ClassName; fldHomePhone.ClassName = ClassName; fldJobTitle.ClassName = ClassName; fldLastName.ClassName = ClassName; fldMiddleName.ClassName = ClassName; fldMobilePhone.ClassName = ClassName; fldSalutation.ClassName = ClassName; fldState.ClassName = ClassName; fldTitleAfter.ClassName = ClassName; fldTitleBefore.ClassName = ClassName; fldURL.ClassName = ClassName; fldZip.ClassName = ClassName; if (!string.IsNullOrEmpty(classInfo.ClassContactMapping)) { // Prepare form info based on mapping data FormInfo mapInfo = new FormInfo(classInfo.ClassContactMapping); if (mapInfo.ItemsList.Count > 0) { FormEngineUserControl customControl = null; // Get all mapped fields FormFieldInfo[] fields = mapInfo.GetFields(true, true); // Name property contains a column of contact object // and MappedToField property contains form field mapped to the contact column foreach (FormFieldInfo ffi in fields) { // Set mapping values... switch (ffi.Name.ToLower()) { case "contactaddress1": // ... Address1 fldAddress1.Value = ffi.MappedToField; break; case "contactaddress2": // ... Address2 fldAddress2.Value = ffi.MappedToField; break; case "contactbirthday": // ... birthday fldBirthday.Value = ffi.MappedToField; break; case "contactbusinessphone": // ... business phone fldBusinessPhone.Value = ffi.MappedToField; break; case "contactcity": // ... city fldCity.Value = ffi.MappedToField; break; case "contactcountryid": // ... country fldCountry.Value = ffi.MappedToField; break; case "contactemail": // ... email fldEmail.Value = ffi.MappedToField; break; case "contactfirstname": // ... first name fldFirstName.Value = ffi.MappedToField; break; case "contactgender": // ... gender fldGender.Value = ffi.MappedToField; break; case "contacthomephone": // ... home phone fldHomePhone.Value = ffi.MappedToField; break; case "contactjobtitle": // ... job title fldJobTitle.Value = ffi.MappedToField; break; case "contactlastname": // ... last name fldLastName.Value = ffi.MappedToField; break; case "contactmiddlename": // ... middle name fldMiddleName.Value = ffi.MappedToField; break; case "contactmobilephone": // ... mobile phone fldMobilePhone.Value = ffi.MappedToField; break; case "contactsalutation": // ... salutation fldSalutation.Value = ffi.MappedToField; break; case "contactstateid": // ... state fldState.Value = ffi.MappedToField; break; case "contacttitleafter": // ... title after fldTitleAfter.Value = ffi.MappedToField; break; case "contacttitlebefore": // ... title before fldTitleBefore.Value = ffi.MappedToField; break; case "contactwebsite": // ... web site fldURL.Value = ffi.MappedToField; break; case "contactzip": // ... ZIP fldZip.Value = ffi.MappedToField; break; default: // ... contact's custom fields if (customControls != null) { customControl = (FormEngineUserControl)customControls[ffi.Name]; if (customControl != null) { customControl.Value = ffi.MappedToField; } } break; } } } } }
/// <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(); } }
protected void Page_Load(object sender, EventArgs e) { // Get custom table id from url customTableId = QueryHelper.GetInteger("customtableid", 0); dci = DataClassInfoProvider.GetDataClassInfo(customTableId); // Set edited object EditedObject = dci; // If class exists and is custom table if ((dci != null) && dci.ClassIsCustomTable) { // Ensure that object belongs to current site or user has access to site manager if (!CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && (dci.AssignedSites[SiteContext.CurrentSiteName] == null)) { RedirectToInformation(GetString("general.notassigned")); } PageTitle.TitleText = GetString("customtable.data.selectdisplayedfields"); CurrentMaster.DisplayActionsPanel = true; // Check 'Read' permission if (!dci.CheckPermissions(PermissionsEnum.Read, SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser)) { ShowError(String.Format(GetString("customtable.permissiondenied.read"), dci.ClassName)); plcContent.Visible = false; return; } HeaderActions.AddAction(new HeaderAction { Text = GetString("UniSelector.SelectAll"), OnClientClick = "ChangeFields(true); return false;", ButtonStyle = ButtonStyle.Default, }); HeaderActions.AddAction(new HeaderAction { Text = GetString("UniSelector.DeselectAll"), OnClientClick = "ChangeFields(false); return false;", ButtonStyle = ButtonStyle.Default, }); if (!RequestHelper.IsPostBack()) { Hashtable reportFields = new Hashtable(); // Get report fields if (!String.IsNullOrEmpty(dci.ClassShowColumns)) { reportFields.Clear(); foreach (string field in dci.ClassShowColumns.Split(';')) { // Add field key to hastable reportFields[field] = null; } } // Get columns names FormInfo fi = FormHelper.GetFormInfo(dci.ClassName, false); var columnNames = fi.GetColumnNames(false); if (columnNames != null) { MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + dci.ClassName); FormFieldInfo ffi; ListItem item; foreach (string name in columnNames) { ffi = fi.GetFormField(name); // Add checkboxes to the list item = new ListItem(HTMLHelper.HTMLEncode(ResHelper.LocalizeString(GetFieldCaption(ffi, name, resolver))), name); if (reportFields.Contains(name)) { // Select checkbox if field is reported item.Selected = true; } chkListFields.Items.Add(item); } } } } else { ShowError(GetString("customtable.notcustomtable")); CurrentMaster.FooterContainer.Visible = false; } }
/// <summary> /// Show graph in preview mode /// </summary> private void ShowPreview() { FormPanelHolder.Visible = false; categoryList.Visible = false; pnlVersions.Visible = false; if (reportInfo != null) { pnlPreview.Visible = true; FormInfo fi = new FormInfo(reportInfo.ReportParameters); // Get datarow with required columns DataRow dr = fi.GetDataRow(); fi.LoadDefaultValues(dr); ctrlReportGraph.ReportParameters = dr; ctrlReportGraph.Visible = true; // Prepare fully qualified graph name = with reportname string fullReportGraphName = reportInfo.ReportName + "." + graphInfo.GraphName; ctrlReportGraph.ReportGraphInfo = graphInfo; ctrlReportGraph.Parameter = fullReportGraphName; ctrlReportGraph.ReloadData(true); } }
/// <summary> /// OnInit event (BasicForm initialization). /// </summary> protected override void OnInit(EventArgs e) { base.OnInit(e); string zoneId = QueryHelper.GetString("zoneid", ""); string aliasPath = QueryHelper.GetString("aliaspath", ""); int templateId = QueryHelper.GetInteger("templateid", 0); string culture = QueryHelper.GetString("culture", LocalizationContext.PreferredCultureCode); mZoneVariantID = QueryHelper.GetInteger("variantid", 0); mIsNewVariant = QueryHelper.GetBoolean("isnewvariant", false); variantMode = VariantModeFunctions.GetVariantModeEnum(QueryHelper.GetString("variantmode", string.Empty)); // When displaying an existing variant of a web part, get the variant mode for its original web part if (ZoneVariantID > 0) { PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateId); if ((pti != null) && ((pti.TemplateInstance != null))) { // Get the original webpart and retrieve its variant mode WebPartZoneInstance zoneInstance = pti.TemplateInstance.GetZone(zoneId); if ((zoneInstance != null) && (zoneInstance.VariantMode != VariantModeEnum.None)) { variantMode = zoneInstance.VariantMode; } } } // Try to find the zone variant in the database and set its VariantID if (IsNewVariant) { Hashtable properties = WindowHelper.GetItem("variantProperties") as Hashtable; if (properties != null) { // Get the variant code name from the WindowHelper string variantName = ValidationHelper.GetString(properties["codename"], string.Empty); // Check if the variant exists in the database int variantIdFromDB = VariantHelper.GetVariantID(variantMode, templateId, variantName, true); // Set the variant id from the database if (variantIdFromDB > 0) { mZoneVariantID = variantIdFromDB; mIsNewVariant = false; } } } if (!String.IsNullOrEmpty(zoneId)) { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("webpartzone.notfound")); pnlFormArea.Visible = false; return; } // Get template pti = pi.UsedPageTemplateInfo; if (pti != null) { // Get web part zone pti.TemplateInstance.EnsureZone(zoneId); webPartZone = pti.TemplateInstance.GetZone(zoneId); if ((ZoneVariantID > 0) && (webPartZone != null) && (webPartZone.ZoneInstanceVariants != null)) { // Check OnlineMarketing permissions if (CheckPermissions("Read")) { webPartZone = webPartZone.ZoneInstanceVariants.Find(v => v.VariantID.Equals(ZoneVariantID)); } else { // Not authorized for OnlineMarketing - Manage. RedirectToInformation(String.Format(GetString("general.permissionresource"), "Read", (variantMode == VariantModeEnum.ContentPersonalization) ? "CMS.ContentPersonalization" : "CMS.MVTest")); } } if (webPartZone == null) { ShowInformation(GetString("webpartzone.notfound")); pnlFormArea.Visible = false; return; } FormInfo fi = BuildFormInfo(webPartZone); // Get the DataRow and fill the data row with values DataRow dr = fi.GetDataRow(); foreach (DataColumn column in dr.Table.Columns) { try { DataHelper.SetDataRowValue(dr, column.ColumnName, webPartZone.GetValue(column.ColumnName)); } catch { } } // Initialize Form formElem.DataRow = dr; formElem.MacroTable = webPartZone.MacroTable; formElem.SubmitButton.Visible = false; formElem.SiteName = SiteContext.CurrentSiteName; formElem.FormInformation = fi; formElem.ShowPrivateFields = true; formElem.OnAfterDataLoad += formElem_OnAfterDataLoad; // HTML editor toolbar if (fi.UsesHtmlArea()) { plcToolbarPadding.Visible = true; plcToolbar.Visible = true; pnlFormArea.Height = 285; } } } }
/// <summary> /// Loads the from definition from selected parameter into a BasicForm control. /// </summary> /// <param name="actual">If true, data from actual hiddens are loaded</param> private void LoadFormDefinition(bool actual) { MacroRuleTree selected = GetSelected((actual ? hdnParamSelected.Value : hdnLastSelected.Value)); if (selected != null) { string paramName = (actual ? hdnParam.Value.ToLowerCSafe() : hdnLastParam.Value.ToLowerCSafe()); MacroRuleParameter param = selected.Parameters[paramName]; if (param != null) { FormInfo fi = new FormInfo(selected.RuleParameters); FormFieldInfo ffi = fi.GetFormField(paramName); if (ffi != null) { fi = new FormInfo(); fi.AddFormItem(ffi); // Add fake DisplayName field FormFieldInfo displayName = new FormFieldInfo(); displayName.Visible = false; displayName.Name = "DisplayName"; displayName.DataType = FieldDataType.Text; fi.AddFormItem(displayName); DataRow row = fi.GetDataRow().Table.NewRow(); if (ffi.AllowEmpty && String.IsNullOrEmpty(param.Value)) { if (!DataTypeManager.IsString(TypeEnum.Field, ffi.DataType)) { row[paramName] = DBNull.Value; } } else { // Convert to a proper type var val = DataTypeManager.ConvertToSystemType(TypeEnum.Field, ffi.DataType, param.Value, CultureHelper.EnglishCulture); if (val != null) { row[paramName] = val; } } formElem.DataRow = row; formElem.FormInformation = fi; formElem.ReloadData(); } } } }
protected void gridData_OnLoadColumns() { if ((bfi != null) && (FormInfo != null)) { // Update the actions command argument foreach (var action in gridData.GridActions.Actions) { ((Action)action).CommandArgument = primaryColumn; } // Get existing columns names var columnList = GetExistingColumns(); string columns = bfi.FormReportFields; if (!string.IsNullOrEmpty(columns)) { var selectedColumns = GetSelectedColumns(columns); columnList = columnList.Intersect(selectedColumns, StringComparer.InvariantCultureIgnoreCase).ToList(); // Set columns which should be retrieved in query and ensure primary column gridData.Columns = (!columnList.Contains(primaryColumn, StringComparer.InvariantCultureIgnoreCase) ? "[" + primaryColumn + "],[" : "[") + columnList.Join("],[") + "]"; } // Get macro resolver for current form MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(FormHelper.FORM_PREFIX + dci.ClassName); // Loop trough all columns int lastIndex = columnList.Count - 1; for (int i = 0; i <= lastIndex; i++) { string column = columnList[i]; // Get field caption FormFieldInfo ffi = FormInfo.GetFormField(column); string fieldCaption; if (ffi == null) { fieldCaption = column; } else { string caption = ffi.GetDisplayName(resolver); fieldCaption = (String.IsNullOrEmpty(caption)) ? column : ResHelper.LocalizeString(caption); } Column columnDefinition = new Column { Caption = fieldCaption, Source = column, ExternalSourceName = ((ffi != null) && ffi.DataType.Equals(FieldDataType.Date, StringComparison.OrdinalIgnoreCase)) ? DATE_TRANSFORMATION : null, AllowSorting = true, Wrap = false }; if (i == lastIndex) { // Stretch last column columnDefinition.Width = "100%"; } gridData.GridColumns.Columns.Add(columnDefinition); } } }
/// <summary> /// Returns the form definition for the web part zone properties. /// </summary> private FormInfo BuildFormInfo(WebPartZoneInstance webPartZone) { FormInfo fi = null; string formDefinition = String.Empty; // Dashboard zone properties if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.Dashboard)) { formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "Dashboard.xml"); } // UI page template properties else if ((pti != null) && (pti.PageTemplateType == PageTemplateTypeEnum.UI)) { formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "UI.xml"); } // Classic web part/widget properties else { formDefinition = PortalFormHelper.LoadProperties("WebPartZone", "Standard.xml"); } if (!String.IsNullOrEmpty(formDefinition)) { // Load properties fi = new FormInfo(formDefinition); fi.UpdateExistingFields(fi); DataRow dr = fi.GetDataRow(); LoadDataRowFromWebPartZone(dr, webPartZone); } return fi; }
/// <summary> /// Get form columns. /// </summary> private List <string> GetExistingColumns() { return(FormInfo?.GetColumnNames(false, i => i.System)); }
/// <summary> /// Returns form info with webpart properties. /// </summary> /// <param name="wpi">Web part info</param> protected FormInfo GetWebPartProperties(WebPartInfo wpi) { if (wpi != null) { // Before form string before = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.Before); FormInfo bfi = new FormInfo(before); // After form string after = PortalFormHelper.GetWebPartProperties((WebPartTypeEnum)wpi.WebPartType, PropertiesPosition.After); FormInfo afi = new FormInfo(after); // Add general category to first items in webpart without category string properties = wpi.WebPartProperties; if (!string.IsNullOrEmpty(properties) && (!properties.StartsWithCSafe("<form><category", true))) { properties = properties.Insert(6, "<category name=\"" + GetString("general.general") + "\" />"); } return PortalFormHelper.GetWebPartFormInfo(wpi.WebPartName, properties, bfi, afi, true); } return null; }
private void EnsureCmsUserAzureCustomField() { var cmsUserDataClass = DataClassInfoProvider.GetDataClassInfo("cms.user"); if (cmsUserDataClass == null) { return; } var formInfo = new FormInfo(cmsUserDataClass.ClassFormDefinition); if (formInfo.FieldExists("AzureADUsername")) { EventLogProvider.LogInformation("AzureADAuthentication", "Skip Create Field", "AzureADUsername"); return; } // Create "AzureADUsername" field if it doesn't exist EventLogProvider.LogInformation("AzureADAuthentication", "Create Field", "AzureADUsername"); var azureAdUsernameTextField = new FormFieldInfo { Name = "AzureADUsername", DataType = "text", Size = 200, Precision = -1, AllowEmpty = true, DefaultValue = string.Empty, System = false, FieldType = FormFieldControlTypeEnum.TextBoxControl, Visible = true, Caption = "Azure AD Username", Enabled = true }; using (var tr = new CMSLateBoundTransaction()) { var tm = new TableManager(cmsUserDataClass.ClassConnectionString); tr.BeginTransaction(); var newFieldHandler = (AbstractAdvancedHandler)null; try { newFieldHandler = DataDefinitionItemEvents.AddItem.StartEvent(cmsUserDataClass, azureAdUsernameTextField); var sqlType = DataTypeManager.GetSqlType(azureAdUsernameTextField.DataType, azureAdUsernameTextField.Size, azureAdUsernameTextField.Precision); tm.AddTableColumn(cmsUserDataClass.ClassTableName, azureAdUsernameTextField.Name, sqlType, azureAdUsernameTextField.AllowEmpty, azureAdUsernameTextField.DefaultValue); formInfo.AddFormItem(azureAdUsernameTextField); cmsUserDataClass.ClassFormDefinition = formInfo.GetXmlDefinition(); cmsUserDataClass.ClassXmlSchema = tm.GetXmlSchema(cmsUserDataClass.ClassTableName); DataClassInfoProvider.SetDataClassInfo(cmsUserDataClass); FormHelper.UpdateInheritedClasses(cmsUserDataClass); QueryInfoProvider.ClearDefaultQueries(cmsUserDataClass, true, true); newFieldHandler.FinishEvent(); tr.Commit(); ClearHashtables("cms.user"); } catch (Exception ex) { EventLogProvider.LogException("AzureADAuthentication", "Create Field", ex); } finally { newFieldHandler?.Dispose(); } } }
/// <summary> /// Load xml definition of the form. /// </summary> private void LoadFormDefinition() { bool isError = false; switch (mMode) { case FieldEditorModeEnum.General: // Definition is loaded from external xml break; case FieldEditorModeEnum.WebPartProperties: if (!IsAlternativeForm) { // Load xml definition from webpartinfo WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(mWebPartId); if (wpi != null) { FormDefinition = wpi.WebPartProperties; } else { isError = true; } } break; case FieldEditorModeEnum.ClassFormDefinition: case FieldEditorModeEnum.BizFormDefinition: case FieldEditorModeEnum.SystemTable: case FieldEditorModeEnum.CustomTable: if (!IsAlternativeForm) { // Load xml definition from Classinfo DataClassInfo dci = DataClassInfoProvider.GetDataClass(mClassName); if (dci != null) { FormDefinition = dci.ClassFormDefinition; } else { isError = true; } } break; } if (isError) { lblError.Visible = true; lblError.Text = "[ FieldEditor.LoadFormDefinition() ]: " + GetString("FieldEditor.XmlDefinitionNotLoaded"); } fi = new FormInfo(FormDefinition); }
/// <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.LocalizeString(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.GetPropertyValue(FormFieldPropertyEnum.FieldCaption, MacroContext.CurrentResolver).EndsWithCSafe(":")) { doubleDot = ":"; } string fieldDescription = ffi.GetPropertyValue(FormFieldPropertyEnum.FieldDescription, resolver); content += @"<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(ResHelper.LocalizeString(fieldDescription), GetString("WebPartDocumentation.DescriptionNoneAvailable"))) + @"</td> <td class=""PropertyRightBorder""> </td> </tr>"; if (fieldDescription == null || fieldDescription.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>"; } }