using System;
using System.Data;
using System.Text;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using CMS.CMSHelper;
using CMS.ExtendedControls;
using CMS.FormControls;
using CMS.GlobalHelper;
using CMS.SiteProvider;
using CMS.SettingsProvider;
using CMS.UIControls;
using CMS.FormEngine;
using CMS.ExtendedControls.DragAndDrop;
public partial class CMSAdminControls_UI_Macros_MacroRuleDesigner : FormEngineUserControl
{
#region "Variables"
private DragAndDropExtender extDragDrop = null;
private int counter = 0;
#endregion
#region "Properties"
///
/// Returns the representation of the designer tree. It returns the root of the whole tree.
///
public MacroRuleTree RuleTree
{
get
{
if (ViewState["RuleTree"] == null)
{
ViewState["RuleTree"] = new MacroRuleTree();
}
return (MacroRuleTree)ViewState["RuleTree"];
}
private set
{
ViewState["RuleTree"] = value;
}
}
///
/// Gets or sets name(s) of the Macro rule category(ies) which should be displayed in Rule designer. Items should be separated by semicolon.
///
public string RuleCategoryNames
{
get;
set;
}
///
/// Determines which rules to display. 0 means all rules, 1 means only rules which does not require context, 2 only rules which require context.
///
public int DisplayRuleType
{
get;
set;
}
///
/// Determines whether to show activity rules or not. This property is useful for OnlineMarketing macro category only.
///
public bool ShowActivityRules
{
get;
set;
}
///
/// Returns the resulting condition
///
public override object Value
{
get
{
string error = this.RuleTree.ValidateParameters();
if (!string.IsNullOrEmpty(error))
{
pnlMessagePlaceholder.ShowError(GetString("macros.macrorule.requiredparamsmissing"), null, null);
throw new Exception(error);
}
string condition = GetCondition();
if (!(MacroResolver.AllowOnlySimpleMacros || MacroResolver.IsSimpleMacro(condition)))
{
// Sign expression if needed
condition = MacroResolver.AddMacroSecurityParams(condition, CMSContext.CurrentUser.UserName);
}
return "Rule(\"" + MacroElement.EscapeSpecialChars(condition) + "\", \"" + MacroElement.EscapeSpecialChars(GetXML()) + "\")";
}
set
{
ParseFromExpression(ValidationHelper.GetString(value, ""));
}
}
///
/// Returns whether the parameter should be shown.
///
private bool ShowParameterEdit
{
get
{
return ValidationHelper.GetBoolean(hdnParamEditShown.Value, false);
}
set
{
hdnParamEditShown.Value = (value ? "1" : "0");
}
}
#endregion
#region "Page events"
protected void Page_Load(object sender, EventArgs e)
{
// Attach events
btnAutoIndent.Click += new ImageClickEventHandler(btnAutoIndent_Click);
btnDelete.Click += new ImageClickEventHandler(btnDelete_Click);
btnIndent.Click += new ImageClickEventHandler(btnIndent_Click);
btnUnindent.Click += new ImageClickEventHandler(btnUnindent_Click);
btnChangeOperator.Click += new EventHandler(btnChangeOperator_Click);
btnChangeParameter.Click += new EventHandler(btnChangeParameter_Click);
btnMove.Click += new EventHandler(btnMove_Click);
btnCancel.Click += new EventHandler(btnCancel_Click);
btnSetParameter.Click += new EventHandler(btnSetParameter_Click);
btnViewCode.Click += new ImageClickEventHandler(btnViewCode_Click);
btnAddClause.Click += new EventHandler(btnAddClause_Click);
btnClearAll.Click += new ImageClickEventHandler(btnClearAll_Click);
txtFilter.TextChanged += new EventHandler(btnFilter_Click);
btnFilter.Text = GetString("general.filter");
btnSetParameter.Text = GetString("general.ok");
btnCodeOK.Text = GetString("general.ok");
btnCancel.Text = GetString("general.cancel");
btnIndent.ToolTip = GetString("macros.macrorule.indent");
btnUnindent.ToolTip = GetString("macros.macrorule.unindent");
btnAutoIndent.ToolTip = GetString("macros.macrorule.autoindent");
btnDelete.ToolTip = GetString("general.delete");
btnClearAll.ToolTip = GetString("macro.macrorule.clearall");
btnViewCode.ToolTip = GetString("macros.macrorule.viewcode");
btnIndent.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }";
btnUnindent.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }";
btnDelete.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; } else { if (!confirm('" + GetString("macros.macrorule.deleteconfirmation") + "')) { return false; }}";
btnAutoIndent.OnClientClick = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.deleteautoindent")) + ")) { return false; }";
btnClearAll.OnClientClick = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.clearall.confirmation")) + ")) { return false; }";
btnViewCode.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/ViewCode.png");
btnAutoIndent.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/AutoIndent.png");
btnDelete.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/Delete.png");
btnClearAll.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/Clear.png");
btnIndent.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/Indent.png");
btnUnindent.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/Unindent.png");
lstRules.Attributes.Add("ondblclick", ControlsHelper.GetPostBackEventReference(btnAddClause, null));
pnlViewCode.Visible = false;
// Basic form
formElem.SubmitButton.Visible = false;
formElem.SiteName = CMSContext.CurrentSiteName;
titleElem.TitleText = GetString("macros.macrorule.changeparameter");
titleElem.TitleImage = GetImageUrl("Design/Controls/MacroRuleDesigner/viewcodebig.png");
imgAddClause.AlternateText = GetString("macros.macrorule.addclause");
imgAddClause.ToolTip = GetString("macros.macrorule.addclause");
imgAddClause.ImageUrl = GetImageUrl("/Design/Controls/MacroRuleDesigner/AddRule.png");
imgAddClause.Click += new ImageClickEventHandler(imgAddClause_Click);
// Drop cue
Panel pnlCue = new Panel();
pnlCue.ID = "pnlCue";
pnlCue.CssClass = "MacroRuleCue";
pnlCondtion.Controls.Add(pnlCue);
pnlCue.Controls.Add(new LiteralControl(" "));
pnlCue.Style.Add("display", "none");
// Create drag and drop extender
extDragDrop = new DragAndDropExtender();
extDragDrop.ID = "extDragDrop";
extDragDrop.TargetControlID = pnlCondtion.ID;
extDragDrop.DragItemClass = "MacroRule";
extDragDrop.DragItemHandleClass = "MacroRuleHandle";
extDragDrop.DropCueID = pnlCue.ID;
extDragDrop.OnClientDrop = "OnDropRule";
pnlCondtion.Controls.Add(extDragDrop);
// Load the rule set
if (!RequestHelper.IsPostBack())
{
string where = "MacroRuleResourceName IS NULL OR MacroRuleResourceName = ''";
if (!string.IsNullOrEmpty(RuleCategoryNames))
{
bool appendComma = false;
StringBuilder sb = new StringBuilder();
string[] names = RuleCategoryNames.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string n in names)
{
string name = "'" + SqlHelperClass.GetSafeQueryString(n.Trim(), false) + "'";
if (appendComma)
{
sb.Append(",");
}
sb.Append(name);
appendComma = true;
}
where = SqlHelperClass.AddWhereCondition(where, "MacroRuleResourceName IN (" + sb.ToString() + ")", "OR");
if (!ShowActivityRules)
{
where = SqlHelperClass.AddWhereCondition(where, "(MacroRuleName NOT LIKE 'CMSActivity%' OR MacroRuleResourceName <> 'cms.onlinemarketing' OR MacroRuleIsCustom = 1)", "AND");
}
switch (DisplayRuleType)
{
case 1:
where = SqlHelperClass.AddWhereCondition(where, "MacroRuleRequiresContext = 0", "AND");
break;
case 2:
where = SqlHelperClass.AddWhereCondition(where, "MacroRuleRequiresContext = 1", "AND");
break;
}
}
DataSet ds = MacroRuleInfoProvider.GetMacroRules(where, "MacroRuleDisplayName", 0, "MacroRuleID, MacroRuleDisplayName, MacroRuleDescription");
if (!DataHelper.DataSourceIsEmpty(ds))
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
ListItem item = new ListItem(dr["MacroRuleDisplayName"].ToString(), dr["MacroRuleID"].ToString());
item.Attributes.Add("title", ResHelper.LocalizeString(ValidationHelper.GetString(dr["MacroRuleDescription"], "")));
lstRules.Items.Add(item);
}
}
if (lstRules.Items.Count > 0)
{
lstRules.SelectedIndex = 0;
}
}
// Make sure that one user click somewhere else than to any rule, selection will disappear
pnlCondtion.Attributes["onclick"] = "if (!doNotDeselect && !isCTRL) { jQuery('.RuleSelected').removeClass('RuleSelected'); document.getElementById('" + hdnSelected.ClientID + "').value = ';'; }; doNotDeselect = false;";
LoadFormDefinition(false);
// Set the default button for parameter edit dialog so that ENTER key works to submit the parameter value
pnlParameterPopup.DefaultButton = btnSetParameter.ID;
// Ensure correct edit dialog show/hide (because of form controls which cause postback)
btnSetParameter.OnClientClick = "HideParamEdit();";
btnCancel.OnClientClick = "HideParamEdit();";
if (ShowParameterEdit)
{
mdlDialog.Show();
}
if (!string.IsNullOrEmpty(hdnScroll.Value))
{
// Preserve scroll position
ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "MacroRulesScroll", "setTimeout('setScrollPosition()', 100);", true);
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
RegisterScriptMethods();
if (this.RuleTree.Children.Count > 0)
{
this.ltlText.Text = GetResultHTML(this.RuleTree);
}
else
{
this.ltlText.Text = "" + GetString("macros.macrorule.emptycondition") + "";
}
}
///
/// Registers needed JS methods for operating the designer.
///
private void RegisterScriptMethods()
{
StringBuilder sb = new StringBuilder();
sb.Append(@"
var doNotDeselect = false;
function SelectRule(path, currentElem) {
doNotDeselect = true;
if (currentElem == null) {
return;
}
var hidden = document.getElementById('", hdnSelected.ClientID, @"');
if (hidden != null) {
if (!isCTRL) {
// Deselect all rules when CTRL is not pressed
jQuery('.RuleSelected').removeClass('RuleSelected');
hidden.value = '';
}
var orig = hidden.value;
var newText = hidden.value.replace(';' + path + ';', ';');
if (orig.length != newText.length) {
// If the rule was present it means it was selected, so deselect the item
currentElem.removeClass('RuleSelected');
} else {
// If the rule was not selected before, select it and add to the list of selected
currentElem.addClass('RuleSelected');
if (newText == '') {
newText = ';' + path + ';';
} else {
newText += path + ';';
}
}
hidden.value = newText;
}
}
function setScrollPosition() {
var hdnScroll = document.getElementById('", hdnScroll.ClientID, @"');
var scrollDiv = document.getElementById('scrollDiv');
if ((hdnScroll != null) && (scrollDiv != null)) {
if (hdnScroll.value != '') {
scrollDiv.scrollTop = hdnScroll.value;
}
}
}
function isNothingSelected() {
// If nothing is selected, do not allow to use buttons such as delete, indent, unindent
var newText = document.getElementById('", hdnSelected.ClientID, @"').value;
return (newText == '') || (newText == ';') || (newText == ';;');
}
");
sb.Append(
@"
var isCTRL = false;
jQuery(document).keyup(function(event) {
if (event.which == 17) {
isCTRL = false;
}
}).keydown(function(event) {
if (event.which == 17) {
isCTRL = true;
}
});
");
sb.Append(string.Format(
@"var targetPosition = new Array();
function OnDropRule(source, target) {{
var item = target.get_droppedItem();
var targetPos = target.get_position();
var hidden = document.getElementById('{0}')
if (hidden != null) {{
hidden.value = item.id + ';' + targetPosition[targetPos];
{1};
}}
}}", hdnParam.ClientID, ControlsHelper.GetPostBackEventReference(btnMove, null)));
sb.Append(
@"
if (window.recursiveDragAndDrop) {
window.recursiveDragAndDrop = true;
}
if (window.lastDragAndDropBehavior) {
lastDragAndDropBehavior._initializeDraggableItems();
}");
sb.Append(
@"
function ActivateBorder(elementId, className) {
var e = document.getElementById(elementId);
if (e != null) {
e.className = e.className.replace(className, className + 'Active');
}
}
function DeactivateBorder(elementId, className) {
var e = document.getElementById(elementId);
if (e != null) {
e.className = e.className.replace(className + 'Active', className);
}
}
");
sb.Append(
@"function ChangeOperator(path, operator) {
document.getElementById('", hdnOpSelected.ClientID, @"').value = path;
document.getElementById('", hdnParam.ClientID, @"').value = operator;
", ControlsHelper.GetPostBackEventReference(btnChangeOperator, null), @"
}");
sb.Append(
@"function ChangeParamValue(path, parameter) {
document.getElementById('", hdnParamSelected.ClientID, @"').value = path;
document.getElementById('", hdnParam.ClientID, @"').value = parameter;
", ControlsHelper.GetPostBackEventReference(btnChangeParameter, null), @"
}");
sb.Append(
@"function InitDesignerAreaSize() {
document.getElementById('", pnlCondtion.ClientID, @"').style.height = (document.body.clientHeight - 230) + 'px';
document.getElementById('", lstRules.ClientID, @"').style.height = (document.body.clientHeight - 208) + 'px';
}
");
sb.Append(
@"function HideParamEdit() {
document.getElementById('" + hdnParamEditShown.ClientID + @"').value = '0';
}
");
sb.Append(
@"jQuery('#scrollDiv').scroll(function() {
document.getElementById('" + hdnScroll.ClientID + @"').value = document.getElementById('scrollDiv').scrollTop;
});");
ScriptHelper.RegisterJQuery(this.Page);
ScriptHelper.RegisterClientScriptBlock(this.Page, typeof(string), "MacroRuleDesigner", ScriptHelper.GetScript(sb.ToString()));
ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "MacroRuleDesignerInit", "InitDesignerAreaSize()", true);
}
#endregion
#region "Sentences building"
///
/// Renders complete rule.
///
/// Rule to render
private string GetResultHTML(MacroRuleTree rule)
{
StringBuilder sb = new StringBuilder();
// Append operator
if (rule.Position > 0)
{
bool isAnd = (rule.Operator == "&&");
sb.Append("
", (isAnd ? "and" : "or"), "
");
}
if (rule.IsLeaf)
{
sb.Append("");
// Register position to a JS hashtable (for drag and drop purposes)
ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "targetPosition" + counter, "targetPosition[" + counter++ + "] = '" + rule.Parent.IDPath + ";" + rule.Position + "';", true);
sb.Append("
");
string handleParams = "";
string text = handleParams.Replace("##ID##", "0") + HTMLHelper.HTMLEncode(rule.RuleText) + "";
if (rule.Parameters != null)
{
int i = 1;
foreach (string key in rule.Parameters.Keys)
{
MacroRuleParameter p = (MacroRuleParameter)rule.Parameters[key];
string paramText = (string.IsNullOrEmpty(p.Text) ? p.DefaultText : p.Text.TrimStart('#'));
paramText = MacroRuleTree.GetParameterText(paramText, true, null, p.ValueType);
text = Regex.Replace(text, "\\{" + key + "\\}", "" + paramText + "" + handleParams, RegexOptions.IgnoreCase);
i++;
}
}
bool isSelected = hdnSelected.Value.Contains(";" + rule.IDPath + ";");
sb.Append("
", text, "
");
sb.Append("");
sb.Append("
");
}
else
{
foreach (MacroRuleTree child in rule.Children)
{
sb.Append(GetResultHTML(child));
}
}
return sb.ToString();
}
#endregion
#region "Button operations
protected void btnFilter_Click(object sender, EventArgs e)
{
string textToFind = txtFilter.Text.ToLowerCSafe();
foreach (ListItem item in lstRules.Items)
{
item.Enabled = item.Text.ToLowerCSafe().Contains(textToFind);
}
}
protected void btnClearAll_Click(object sender, ImageClickEventArgs e)
{
this.RuleTree = new MacroRuleTree();
hdnSelected.Value = "";
}
protected void btnViewCode_Click(object sender, ImageClickEventArgs e)
{
this.viewCodeElem.Text = this.RuleTree.GetCondition();
this.titleElem.TitleText = GetString("macros.macrorule.viewcodeheader");
this.pnlViewCode.Visible = true;
this.mdlDialog.Visible = true;
this.mdlDialog.Show();
}
protected void btnMove_Click(object sender, EventArgs e)
{
string[] parts = hdnParam.Value.Split(';');
if (parts.Length == 3)
{
int plusOne = parts[0].CompareToCSafe((string.IsNullOrEmpty(parts[1]) ? "" : parts[1] + ".") + parts[2]);
plusOne = (plusOne < 0 ? 1 : 0);
if (parts[1] == pnlCondtion.ClientID)
{
this.RuleTree.MoveNode(parts[0], "", ValidationHelper.GetInteger(parts[2], 0) + plusOne);
}
else
{
this.RuleTree.MoveNode(parts[0], parts[1], ValidationHelper.GetInteger(parts[2], 0) + plusOne);
}
// Clear selection
hdnSelected.Value = ";";
}
}
protected void btnChangeParameter_Click(object sender, EventArgs e)
{
LoadFormDefinition(true);
hdnLastSelected.Value = hdnParamSelected.Value;
hdnLastParam.Value = hdnParam.Value;
hdnParamEditShown.Value = "1";
this.titleElem.TitleText = GetString("macros.macrorule.changeparameter");
this.pnlModalProperty.Visible = true;
this.pnlFooter.Visible = true;
this.mdlDialog.Visible = true;
this.mdlDialog.Show();
}
protected void btnSetParameter_Click(object sender, EventArgs e)
{
MacroRuleTree selected = GetSelected(hdnParamSelected.Value);
if (selected != null)
{
string paramName = hdnParam.Value.ToLowerCSafe();
MacroRuleParameter param = (MacroRuleParameter)selected.Parameters[paramName];
if (param != null)
{
if (formElem.ValidateData())
{
// Load value from the form control
FormEngineUserControl ctrl = formElem.FieldControls[paramName];
if (ctrl != null)
{
// Get the values from form control
string displayName = ctrl.ValueDisplayName;
object val = ctrl.Value;
string value = null;
// Convert value to EN culture
if (ctrl.FieldInfo.DataType == FormFieldDataTypeEnum.DateTime)
{
value = ValidationHelper.GetDateTime(val, DataHelper.DATETIME_NOT_SELECTED).ToString(CultureHelper.EnglishCulture);
displayName = ValidationHelper.GetDateTime(displayName, DataHelper.DATETIME_NOT_SELECTED).ToString(CultureHelper.EnglishCulture);
}
else if (ctrl.FieldInfo.DataType == FormFieldDataTypeEnum.Decimal)
{
value = ValidationHelper.GetDouble(val, 0).ToString(CultureHelper.EnglishCulture);
displayName = ValidationHelper.GetDouble(displayName, 0).ToString(CultureHelper.EnglishCulture);
}
else
{
value = ValidationHelper.GetString(val, "");
}
if (String.IsNullOrEmpty(ctrl.ValueDisplayName))
{
displayName = value;
}
param.Value = value;
param.Text = displayName;
param.ValueType = ctrl.FieldInfo.DataType.ToString();
}
pnlModalProperty.Visible = false;
pnlFooter.Visible = false;
}
else
{
pnlModalProperty.Visible = true;
pnlFooter.Visible = true;
mdlDialog.Visible = true;
mdlDialog.Show();
}
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
pnlModalProperty.Visible = false;
pnlFooter.Visible = false;
}
protected void btnChangeOperator_Click(object sender, EventArgs e)
{
MacroRuleTree selected = GetSelected(hdnOpSelected.Value);
if (selected != null)
{
selected.Operator = hdnParam.Value;
if ((selected.Position == 1) && (selected.Parent != null))
{
// Change operator to previous sibling if we are changing the first operator in the group
// It's because if we switch those two it should have same opearators
selected.Parent.Children[0].Operator = selected.Operator;
}
}
}
protected void btnUnindent_Click(object sender, ImageClickEventArgs e)
{
List selected = GetSelected();
hdnSelected.Value = ";";
foreach (MacroRuleTree item in selected)
{
item.Unindent();
hdnSelected.Value += item.IDPath + ";";
}
}
protected void btnIndent_Click(object sender, ImageClickEventArgs e)
{
List selected = GetSelected();
hdnSelected.Value = ";";
foreach (MacroRuleTree item in selected)
{
item.Indent();
hdnSelected.Value += item.IDPath + ";";
}
}
protected void btnDelete_Click(object sender, ImageClickEventArgs e)
{
List selected = GetSelected();
foreach (MacroRuleTree item in selected)
{
if (item.Parent != null)
{
item.Parent.RemoveNode(item.Position);
}
}
hdnSelected.Value = "";
}
protected void btnAutoIndent_Click(object sender, ImageClickEventArgs e)
{
MacroRuleTree.RemoveBrackets(this.RuleTree);
this.RuleTree.AutoIndent();
}
protected void imgAddClause_Click(object sender, ImageClickEventArgs e)
{
AddClause();
}
protected void btnAddClause_Click(object sender, EventArgs e)
{
AddClause();
}
///
/// Adds a clause according to selected item.
///
private void AddClause()
{
MacroRuleInfo rule = MacroRuleInfoProvider.GetMacroRuleInfo(ValidationHelper.GetInteger(lstRules.SelectedValue, 0));
if (rule != null)
{
List selected = GetSelected();
if (selected.Count == 1)
{
MacroRuleTree item = selected[0];
if ((item != null) && (item.Parent != null))
{
item.Parent.AddRule(rule, item.Position + 1);
return;
}
}
// Add the rule at the root level, when no selected item
this.RuleTree.AddRule(rule, this.RuleTree.Children.Count);
}
}
#endregion
#region "General methods"
///
/// Returns true if at least one rule is selected.
///
private bool IsAnyRuleSelected()
{
return this.hdnSelected.Value.Trim(';') != "";
}
///
/// Gets the object from its IDPath.
///
/// IDPath of the rule
private MacroRuleTree GetSelected(string idPath)
{
if (!string.IsNullOrEmpty(idPath))
{
string[] parts = idPath.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
MacroRuleTree srcGroup = this.RuleTree;
foreach (string posStr in parts)
{
int pos = ValidationHelper.GetInteger(posStr, 0);
if (srcGroup.Children.Count > pos)
{
srcGroup = srcGroup.Children[pos];
}
}
return srcGroup;
}
return null;
}
///
/// Returns list of selected objects (gets IDPaths from hidden field).
///
private List GetSelected()
{
List selected = new List();
if (!string.IsNullOrEmpty(hdnSelected.Value))
{
string[] ids = hdnSelected.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// We need to sort the items, so as the items upper go sooner than items more down
Array.Sort(ids);
foreach (string id in ids)
{
selected.Add(GetSelected(id));
}
}
return selected;
}
///
/// Loads the from definition from selected parameter into a BasicForm control.
///
/// If true, data from actual hiddens are loaded
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 = (MacroRuleParameter)selected.Parameters[paramName];
if (param != null)
{
FormInfo fi = new FormInfo(selected.RuleParameters);
FormFieldInfo ffi = fi.GetFormField(paramName);
if (ffi != null)
{
fi = new FormInfo(null);
fi.AddFormField(ffi);
// Add fake DisplayName field
FormFieldInfo displayName = new FormFieldInfo();
displayName.Visible = false;
displayName.Name = "DisplayName";
displayName.DataType = FormFieldDataTypeEnum.Text;
fi.AddFormField(displayName);
DataRow row = fi.GetDataRow().Table.NewRow();
if (ffi.AllowEmpty && string.IsNullOrEmpty(param.Value))
{
if ((ffi.DataType != FormFieldDataTypeEnum.Text) && (ffi.DataType != FormFieldDataTypeEnum.LongText))
{
row[paramName] = DBNull.Value;
}
}
else
{
switch (ffi.DataType)
{
case FormFieldDataTypeEnum.Decimal:
row[paramName] = ValidationHelper.GetDouble(param.Value, 0, CultureHelper.EnglishCulture);
break;
case FormFieldDataTypeEnum.Boolean:
row[paramName] = ValidationHelper.GetBoolean(param.Value, false);
break;
case FormFieldDataTypeEnum.Integer:
row[paramName] = ValidationHelper.GetInteger(param.Value, 0);
break;
case FormFieldDataTypeEnum.DateTime:
row[paramName] = ValidationHelper.GetDateTime(param.Value, DataHelper.DATETIME_NOT_SELECTED, CultureHelper.EnglishCulture);
break;
case FormFieldDataTypeEnum.GUID:
Guid guid = ValidationHelper.GetGuid(param.Value, Guid.Empty);
if (guid != Guid.Empty)
{
row[paramName] = guid;
}
break;
default:
row[paramName] = param.Value;
break;
}
}
formElem.DataRow = row;
formElem.FormInformation = fi;
formElem.ReloadData();
}
}
}
}
#endregion
#region "Data methods"
///
/// Returns the condition of the whole rule.
///
public string GetCondition()
{
return this.RuleTree.GetCondition();
}
///
/// Returns the XML of the designer.
///
public string GetXML()
{
return this.RuleTree.GetXML();
}
///
/// Loads the designer from xml.
///
public void LoadFromXML(string xml)
{
try
{
ViewState["RuleTree"] = MacroRuleTree.BuildFromXML(xml);
}
catch { }
}
///
/// Extracs the condition from Rule method.
///
public string ConditionFromExpression(string expression)
{
MacroExpression xml = null;
try
{
xml = MacroExpression.ExtractParameter(expression, "rule", 1);
}
catch { }
string user = null;
if (xml == null)
{
return MacroResolver.RemoveMacroSecurityParams(expression, out user);
}
else
{
// Returns first parameter of the expression
return MacroResolver.RemoveMacroSecurityParams(ValidationHelper.GetString(xml.Value, ""), out user);
}
}
///
/// Parses the rule tree from Rule expression.
///
public void ParseFromExpression(string expression)
{
MacroExpression xml = MacroExpression.ExtractParameter(expression, "rule", 1);
if (xml != null)
{
// Load from the XML
if (xml.Type == ExpressionType.Value)
{
LoadFromXML(xml.Value.ToString());
return;
}
}
// If something went wrong, assign null to the state variable
ViewState["RuleTree"] = null;
}
#endregion
}