/// <summary>
    /// Show graph in preview mode
    /// </summary>
    private void ShowPreview()
    {
        FormPanelHolder.Visible = false;
        pnlVersions.Visible     = false;

        if (mReportInfo != null)
        {
            pnlPreview.Visible = true;

            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow defaultValues = fi.GetDataRow(false);

            fi.LoadDefaultValues(defaultValues, true);

            ctrlReportGraph.ReportParameters = defaultValues;
            ctrlReportGraph.Visible          = true;

            // Prepare fully qualified graph name = with reportname
            string fullReportGraphName = mReportInfo.ReportName + "." + mReportGraphInfo.GraphName;
            ctrlReportGraph.ReportGraphInfo = mReportGraphInfo;
            ctrlReportGraph.Parameter       = fullReportGraphName;

            ctrlReportGraph.ReloadData(true);
        }
    }
    /// <summary>
    /// Loads DataRow for BasicForm with data from FormFieldInfo settings and optionally with form control's default values.
    /// </summary>
    /// <param name="loadDefaultValues">Indicates if data container should be initialized with form control's default data</param>
    private DataRowContainer GetData(bool loadDefaultValues)
    {
        DataRowContainer result = new DataRowContainer(FormInfo.GetDataRow(loadDefaultValues));

        if (loadDefaultValues)
        {
            // Load default values for visible properties (values of hidden form control properties shouldn't be stored in form definition)
            FormInfo.LoadDefaultValues(result, FormResolveTypeEnum.None, true);
        }

        if (Settings != null)
        {
            // Load settings of the existing field
            foreach (string columnName in Settings.Keys)
            {
                if (result.ContainsColumn(columnName))
                {
                    object value        = Settings[columnName];
                    var    settingField = FormInfo.GetFormField(columnName);

                    if (!String.IsNullOrEmpty(Convert.ToString(value)) && IsDataTypeValid(value, settingField))
                    {
                        result[columnName] = DataTypeManager.ConvertToSystemType(TypeEnum.Field, settingField.DataType, value, SystemContext.EnglishCulture);
                    }
                }
            }
        }
        return(result);
    }
Example #3
0
    /// <summary>
    /// Show preview
    /// </summary>
    private void ShowPreview()
    {
        divPanelHolder.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, true);

            // ReportGraph.ContextParameters
            ctrlReportTable.ReportParameters = dr;

            // Prepare fully qualified graph name = with reportname
            if (tableInfo != null)
            {
                string fullReportGraphName = reportInfo.ReportName + "." + tableInfo.TableName;
                ctrlReportTable.Parameter = fullReportGraphName;
            }
            ctrlReportTable.TableInfo = tableInfo;


            ctrlReportTable.ReloadData(true);
        }
    }
    /// <summary>
    /// Load parameters from data form.
    /// </summary>
    private void LoadParameters()
    {
        if (ReportInfo != null)
        {
            // Set the form
            FormInfo fi = new FormInfo(ReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow(false);
            if (!RequestHelper.IsPostBack() || ForceLoadDefaultValues || !DisplayFilter)
            {
                fi.LoadDefaultValues(dr, true);
            }
            else if ((!ForceLoadDefaultValues) && (formParameters.DataRow != null))
            {
                dr = formParameters.DataRow;
            }

            // Show filter - based on DisplayFilter and number of visible elements
            mDisplayFilterResult = DisplayFilter && (fi.GetFormElements(true, false).Any());

            formParameters.DataRow = dr;
            formParameters.SubmitButton.Visible = mDisplayFilterResult;
            formParameters.SubmitButton.RegisterHeaderAction = false;
            formParameters.FormInformation             = fi;
            formParameters.SubmitButton.ResourceString = "report_view.btnupdate";
            formParameters.SiteName = SiteContext.CurrentSiteName;
            formParameters.Mode     = FormModeEnum.Insert;
            formParameters.Visible  = mDisplayFilterResult;

            wasInit = true;
        }
    }
Example #5
0
    /// <summary>
    /// Load parameters from data form.
    /// </summary>
    protected void LoadParameters()
    {
        if (ReportInfo != null)
        {
            // Set the form
            FormInfo fi = new FormInfo(ReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow();
            if ((!RequestHelper.IsPostBack()) || (ForceLoadDefaultValues))
            {
                fi.LoadDefaultValues(dr, true);
            }
            else
            {
                if ((!ForceLoadDefaultValues) && (formElem.DataRow != null))
                {
                    dr = formElem.DataRow;
                }
            }

            // show filter - based on DisplayFilter and number of visible elements
            mDisplayFilterResult = DisplayFilter && (fi.GetFormElements(true, false).Count > 0);

            formElem.DataRow = dr;
            formElem.SubmitButton.Visible = mDisplayFilterResult;
            formElem.FormInformation      = fi;
            formElem.SubmitButton.Text    = GetString("Report_View.btnUpdate");
            formElem.SiteName             = CMSContext.CurrentSiteName;
            formElem.ShowPrivateFields    = true;
            formElem.Mode    = FormModeEnum.Insert;
            formElem.Visible = mDisplayFilterResult;
        }
    }
Example #6
0
    protected void lnkLoadDefaults_Click(object sender, EventArgs e)
    {
        // Get the web part form info
        FormInfo fi = GetWebPartFormInfo();

        if (fi != null)
        {
            // Create DataRow with default data
            var dr = fi.GetDataRow();

            // Load default values
            fi.LoadDefaultValues(dr);

            // Load overridden system values
            fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);

            // Load to the form
            form.LoadData(dr);
        }
    }
Example #7
0
    /// <summary>
    /// Combines widget info with default XML system propertiers.
    /// </summary>
    /// <param name="fi">Widget form info</param>
    /// <param name="wi">Widget info object</param>
    public DataRow CombineWithDefaultValues(FormInfo fi, WidgetInfo wi)
    {
        if ((!String.IsNullOrEmpty(wi.WidgetDefaultValues)) && (String.Compare(wi.WidgetDefaultValues, "<form></form>", false) != 0))
        {
            // Apply changed values
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr, wi.WidgetDefaultValues);

            return(dr);
        }

        return(fi.GetDataRow());
    }
    /// <summary>
    /// Initializes inner controls.
    /// </summary>
    /// <param name="forceReload">Indicates if form with parameters should be reloaded</param>
    private void InitializeControl(bool forceReload = false)
    {
        // Init rule selector
        uniSelector.Value = mSelectedRuleName;

        MacroRuleInfo mri = MacroRuleInfoProvider.GetMacroRuleInfo(mSelectedRuleName);

        if (mri != null)
        {
            // Show rule description
            ltlDescription.Text       = mri.MacroRuleDescription;
            txtErrorMsg.Value         = string.Empty;
            txtErrorMsg.WatermarkText = String.IsNullOrEmpty(DefaultErrorMessage) ? ResHelper.GetString("basicform.invalidinput") : DefaultErrorMessage;

            // Prepare form for rule parameters
            FormInfo fi = new FormInfo(mri.MacroRuleParameters);
            formProperties.FormInformation = fi;
            DataRow data = fi.GetDataRow();
            formProperties.DataRow = data;

            fi.LoadDefaultValues(formProperties.DataRow, FormResolveTypeEnum.AllFields);
            if ((mMacroRule != null) && (mMacroRuleTree != null) && mMacroRuleTree.RuleName.EqualsCSafe(mSelectedRuleName, true))
            {
                // Set params from rule given by Value property
                foreach (DictionaryEntry entry in mMacroRuleTree.Parameters)
                {
                    string             paramName = ValidationHelper.GetString(entry.Key, String.Empty);
                    MacroRuleParameter param     = entry.Value as MacroRuleParameter;

                    if ((param != null) && data.Table.Columns.Contains(paramName))
                    {
                        data[paramName] = param.Value;
                    }
                }

                txtErrorMsg.Value = mMacroRule.ErrorMessage;
            }

            if (forceReload)
            {
                // Reload params
                formProperties.ReloadData();
            }

            mParamsInitialized = true;
        }
    }
Example #9
0
    /// <summary>
    /// Adds widget.
    /// </summary>
    private void AddWidget()
    {
        int widgetID = ValidationHelper.GetInteger(WidgetId, 0);

        // Add web part to the currently selected zone under currently selected page
        if ((widgetID > 0) && !String.IsNullOrEmpty(ZoneId))
        {
            if (wi != null)
            {
                // Ensure layout zone flag
                if (QueryHelper.GetBoolean("layoutzone", false))
                {
                    WebPartZoneInstance zone = pti.EnsureZone(ZoneId);
                    zone.LayoutZone     = true;
                    zone.WidgetZoneType = zoneType;

                    // Ensure the layout zone flag in the original page template instance
                    WebPartZoneInstance zoneInstance = templateInstance.GetZone(ZoneId);
                    if (zoneInstance != null)
                    {
                        zoneInstance.LayoutZone = true;
                        zone.WidgetZoneType     = zoneType;
                    }
                }

                // Add the widget
                WebPartInstance newWidget = templateInstance.AddWidget(ZoneId, widgetID);
                if (newWidget != null)
                {
                    // Prepare the form info to get the default properties
                    FormInfo fi = new FormInfo(wi.WidgetProperties);

                    DataRow dr = fi.GetDataRow();
                    fi.LoadDefaultValues(dr);

                    newWidget.LoadProperties(dr);

                    // Add webpart to user's last recently used
                    CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName);

                    widgetInstance = newWidget;
                }
            }
        }
    }
    /// <summary>
    /// Loads DataRow for BasicForm with data from FormFieldInfo settings.
    /// </summary>
    private DataRowContainer GetData()
    {
        DataRowContainer result = new DataRowContainer(FormInfo.GetDataRow());

        FormInfo.LoadDefaultValues(result);

        if (Settings != null)
        {
            foreach (string columnName in result.ColumnNames)
            {
                if (Settings.ContainsKey(columnName) && !String.IsNullOrEmpty(Convert.ToString(Settings[columnName])))
                {
                    result[columnName] = Settings[columnName];
                }
            }
        }
        return(result);
    }
Example #11
0
    protected void lnkLoadDefaults_Click(object sender, EventArgs e)
    {
        // Get the web part form info
        FormInfo fi = GetWebPartFormInfo();

        if (fi != null)
        {
            // Create DataRow with default data
            var dr = fi.GetDataRow();

            // Load default values
            fi.LoadDefaultValues(dr);

            // Set web part ID
            dr["WebPartControlID"] = GetUniqueWebPartId();

            // Load to the form
            form.LoadData(dr);
        }
    }
Example #12
0
    /// <summary>
    /// Show preview.
    /// </summary>
    private void ShowPreview()
    {
        if (mReportInfo != null)
        {
            pnlPreview.Visible     = true;
            divPanelHolder.Visible = false;
            pnlVersions.Visible    = false;

            FormInfo fi            = new FormInfo(mReportInfo.ReportParameters);
            DataRow  defaultValues = fi.GetDataRow(false);

            fi.LoadDefaultValues(defaultValues, true);

            //reportGraph.ContextParameters
            ctrlReportValue.ReportParameters = defaultValues;

            ctrlReportValue.Visible   = true;
            ctrlReportValue.ValueInfo = mReportValueInfo;

            ctrlReportValue.ReloadData(true);
        }
    }
    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 ()");
        }
    }
    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(false);
                fi.LoadDefaultValues(defaultRow, true);

                // Load default parameters to items ,where displayed in edit form not checked
                List <IField> items = fi.ItemsList;
                foreach (IField 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 (); CloseDialog()");
        }
    }
Example #15
0
    /// <summary>
    /// Show preview.
    /// </summary>
    private void ShowPreview()
    {
        if (reportInfo != null)
        {
            pnlPreview.Visible     = true;
            divPanelHolder.Visible = false;
            categoryList.Visible   = false;
            pnlVersions.Visible    = false;

            FormInfo fi = new FormInfo(reportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow();

            fi.LoadDefaultValues(dr, true);

            //reportGraph.ContextParameters
            ctrlReportValue.ReportParameters = dr;

            ctrlReportValue.Visible   = true;
            ctrlReportValue.ValueInfo = valueInfo;

            ctrlReportValue.ReloadData(true);
        }
    }
    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>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        try
        {
            // Load value info object
            ReportValueInfo rvi = ValueInfo;

            if (rvi != null)
            {
                //Test security
                ReportInfo ri = ReportInfoProvider.GetReportInfo(rvi.ValueReportID);
                if (ri.ReportAccess != ReportAccessEnum.All)
                {
                    if (!CMSContext.CurrentUser.IsAuthenticated())
                    {
                        this.Visible = false;
                        return;
                    }
                }

                ContextResolver resolver = CMSContext.CurrentResolver;
                // Resolve dynamic data macros
                if (DynamicMacros != null)
                {
                    for (int i = 0; i <= this.DynamicMacros.GetUpperBound(0); i++)
                    {
                        resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                    }
                }

                this.QueryIsStoredProcedure = rvi.ValueQueryIsStoredProcedure;
                this.QueryText = resolver.ResolveMacros(rvi.ValueQuery);

                //Set default parametrs directly if not set
                if (this.ReportParameters == null)
                {
                    if (ri != null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If datasource is emptry, create empty dataset
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                // Set literal text
                string value = rvi.ValueFormatString;
                if ((value == null) || (value == ""))
                {
                    value = ValidationHelper.GetString(ds.Tables[0].Rows[0][0], "");
                }
                else
                {
                    value = string.Format(value, ds.Tables[0].Rows[0].ItemArray);
                }

                lblValue.Text = HTMLHelper.HTMLEncode(ResolveMacros(value));
            }
        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportValue.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report value", "E", ex);
        }
    }
Example #18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Hashtable decodedProperties = new Hashtable();

        foreach (DictionaryEntry param in mProperties)
        {
            // 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);
        }
        mProperties = decodedProperties;

        string widgetName = ValidationHelper.GetString(mProperties["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
        {
            // Merge widget and it's parent webpart properties
            string properties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, wi.WidgetProperties);

            // Prepare form
            WidgetZoneTypeEnum zoneType           = WidgetZoneTypeEnum.Editor;
            FormInfo           zoneTypeDefinition = PortalHelper.GetPositionFormInfo(zoneType);
            FormInfo           fi = FormHelper.GetWidgetFormInfo(wi.WidgetName, Enum.GetName(typeof(WidgetZoneTypeEnum), zoneType), properties, zoneTypeDefinition, true);

            // Apply changed values
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr);

            // Incorporate inline parameters to datarow
            string publicFields = ";containertitle;container;";
            if (wi.WidgetPublicFileds != null)
            {
                publicFields += ";" + wi.WidgetPublicFileds.ToLower() + ";";
            }

            // Load the webpart(widget) control
            string url = WebPartInfoProvider.GetWebPartUrl(wpi, false);

            CMSAbstractWebPart control = (CMSAbstractWebPart)Page.LoadControl(url);
            control.PartInstance = new WebPartInstance();

            // Set all form values to webpart
            foreach (DataColumn column in dr.Table.Columns)
            {
                object value      = dr[column];
                string columnName = column.ColumnName.ToLower();

                //Resolve set values by user
                if (mProperties.Contains(columnName))
                {
                    FormFieldInfo ffi = fi.GetFormField(columnName);
                    if ((ffi != null) && ffi.Visible && (!ffi.DisplayIn.Contains(FormInfo.DISPLAY_CONTEXT_DASHBOARD)))
                    {
                        value = mProperties[columnName];
                    }
                }

                // Resolve macros in defined in default values
                if (!String.IsNullOrEmpty(value as string))
                {
                    // Do not resolve macros for public fields
                    if (publicFields.IndexOf(";" + columnName + ";") < 0)
                    {
                        // Check whether current column
                        bool avoidInjection = control.SQLProperties.Contains(";" + columnName + ";");

                        // Resolve macros
                        value = control.ContextResolver.ResolveMacros(value.ToString(), avoidInjection);
                    }
                }

                control.PartInstance.SetValue(column.ColumnName, value);
            }

            // Load webpart content
            control.OnContentLoaded();

            // Add webpart to controls collection
            this.Controls.Add(control);
        }

        catch (Exception ex)
        {
            AddErrorWebPart("widget.failedtoload", ex);
        }
    }
    /// <summary>
    /// Show graph
    /// </summary>
    private void ShowPreview()
    {
        // Color picker preview issue
        DisplayEditControls(false);

        pnlVersions.Visible = false;
        if (mReportInfo != null)
        {
            pnlPreview.Visible = true;

            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);
            // Get DataRow with required columns
            DataRow dr = fi.GetDataRow(false);

            fi.LoadDefaultValues(dr, true);

            ctrlReportGraph.ReportParameters = dr;

            ctrlReportGraph.Visible = true;

            // Prepare fully qualified graph name = with ReportName
            string fullReportGraphName = mReportInfo.ReportName + "." + mReportGraphInfo.GraphName;
            ctrlReportGraph.GraphInfo = mReportGraphInfo;
            ctrlReportGraph.Parameter = fullReportGraphName;

            ctrlReportGraph.ReloadData(true);
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        pnlReports.Attributes.Add("style", "margin-bottom:3px");

        string reportName = ValidationHelper.GetString(usReports.Value, String.Empty);
        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(CurrentGuid());
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr);
            bool itemVisible = false;
            List<IFormItem> items = fi.ItemsList;
            foreach (IFormItem 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
        {
            if (ReportID == 0)
            {
                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();

        if (ri == null)
        {
            string[,] itemSpecialFields = new string[1, 2];
            itemSpecialFields[0, 0] = "(" + firstItemText + ")";
            itemSpecialFields[0, 1] = "0";
            usItems.SpecialFields = itemSpecialFields;
        }

        if (ShowItemSelector)
        {
            ReloadItems();
        }

        if (setValues)
        {
            WindowHelper.Add(CurrentGuid(), CurrentDataSet);
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "OpenModalWindowReportItem", ScriptHelper.GetScript("modalDialog('" + ResolveUrl("~/CMSModules/Reporting/Dialogs/ReportParametersSelector.aspx?ReportID=" + ReportID + "&guid=" + CurrentGuid().ToString()) + "','ReportParametersDialog', 700, 500);"));
            keepDataInWindowsHelper = true;
        }

        // Apply reportid condition if report was selected via uniselector
        if (ri != null)
        {
            FormInfo fi = new FormInfo(ri.ReportParameters);
            DataRow dr = fi.GetDataRow();
            DataSet ds = CurrentDataSet;

            ViewState["ParametersXmlData"] = null;
            ViewState["ParametersXmlSchema"] = null;

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                ViewState["ParametersXmlData"] = ds.GetXml();
                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);
    }
    /// <summary>
    /// Load parameters from data form.
    /// </summary>
    protected void LoadParameters()
    {
        if (ReportInfo != null)
        {
            // Set the form
            FormInfo fi = new FormInfo(ReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow();
            if (!RequestHelper.IsPostBack() || ForceLoadDefaultValues || !DisplayFilter)
            {
                fi.LoadDefaultValues(dr, true);
            }
            else
            {
                if ((!ForceLoadDefaultValues) && (formElem.DataRow != null))
                {
                    dr = formElem.DataRow;
                }
            }

            // show filter - based on DisplayFilter and number of visible elements
            mDisplayFilterResult = DisplayFilter && (fi.GetFormElements(true, false).Any());

            formElem.DataRow = dr;
            formElem.SubmitButton.Visible = mDisplayFilterResult;
            formElem.SubmitButton.RegisterHeaderAction = false;
            formElem.FormInformation = fi;
            formElem.SubmitButton.Text = GetString("Report_View.btnUpdate");
            formElem.SiteName = CMSContext.CurrentSiteName;
            formElem.ShowPrivateFields = true;
            formElem.Mode = FormModeEnum.Insert;
            formElem.Visible = mDisplayFilterResult;
        }
    }
Example #22
0
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if ((GraphImageWidth != 0) && (ComputedWidth == 0))
        {
            // Graph width is computed no need to create graph
            return;
        }

        Visible = true;

        errorOccurred = false;

        try
        {
            ReportTableName = Parameter;

            EnsureTableInfo();
            EnsureChildControls();

            //Test security
            if (TableInfo != null)
            {
                ri = ReportInfoProvider.GetReportInfo(TableInfo.TableReportID);
                if (ri != null)
                {
                    if (ri.ReportAccess != ReportAccessEnum.All)
                    {
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            Visible = false;
                            return;
                        }
                    }

                    EnableSubscription = EnableSubscription && (ValidationHelper.GetBoolean(TableInfo.TableSettings["SubscriptionEnabled"], true) && ri.ReportEnableSubscription);
                    if (EmailMode && !EnableSubscription)
                    {
                        this.Visible = false;
                        return;
                    }

                    //Set default parametrs directly if not set
                    if (ReportParameters == null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        ReportParameters = fi.GetDataRow(false);
                        fi.LoadDefaultValues(ReportParameters, true);
                    }

                    ApplyTimeParameters();
                }
            }

            // Only use base parameters in case of stored procedure
            if (QueryIsStoredProcedure)
            {
                AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
            }

            // Load data
            DataSet ds = LoadData();

            // If no data load, set empty dataset
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                if (EmailMode && SendOnlyNonEmptyDataSource)
                {
                    Visible = false;
                    return;
                }

                string noRecordText = ValidationHelper.GetString(TableInfo.TableSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    GridViewObject.Visible = false;
                    lblInfo.Text           = CMSContext.ResolveMacros(noRecordText);
                    plcInfo.Visible        = true;
                    EnableExport           = false;
                    return;
                }

                if (!EmailMode)
                {
                    Visible = false;
                }
            }
            else
            {
                GridViewObject.Visible = true;
                // Resolve macros in column names
                int i = 0;
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName == "Column" + ((int)(i + 1)).ToString())
                    {
                        dc.ColumnName = ResolveMacros(ds.Tables[0].Rows[0][i].ToString());
                    }
                    else
                    {
                        dc.ColumnName = ResolveMacros(dc.ColumnName);
                    }
                    i++;
                }

                // Resolve macros in dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dc.DataType.FullName.ToLowerCSafe() == "system.string")
                        {
                            dr[dc.ColumnName] = ResolveMacros(ValidationHelper.GetString(dr[dc.ColumnName], ""));
                        }
                    }
                }

                if (EmailMode)
                {
                    // For some email formats, export data in csv format
                    EmailFormatEnum format = EmailHelper.GetEmailFormat(ReportSubscriptionSiteID);

                    if ((format == EmailFormatEnum.Both) || (format == EmailFormatEnum.PlainText))
                    {
                        using (MemoryStream ms = MemoryStream.New())
                        {
                            DataExportHelper deh  = new DataExportHelper(ds);
                            byte[]           data = deh.ExportToCSV(ds, 0, ms, true);
                            ReportSubscriptionSender.AddToRequest(ri.ReportName, "t" + TableInfo.TableName, data);
                        }
                    }

                    // For plain text email show table only as attachment
                    if (format == EmailFormatEnum.PlainText)
                    {
                        menuCont.Visible = false;
                        ltlEmail.Visible = true;
                        ltlEmail.Text    = String.Format(GetString("reportsubscription.attachment"), TableInfo.TableName);
                        return;
                    }

                    GenerateTableForEmail(ds);
                    menuCont.Visible = false;
                    return;
                }
            }

            ApplyStyles();

            // Databind to gridview control
            GridViewObject.DataSource = ds;
            EnsurePageIndex();
            GridViewObject.DataBind();

            if ((TableFirstColumnWidth != Unit.Empty) && (GridViewObject.Rows.Count > 0))
            {
                GridViewObject.Rows[0].Cells[0].Width = TableFirstColumnWidth;
            }
        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text    = "[ReportTable.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report table", "E", ex);
            errorOccurred = true;
        }
    }
    /// <summary>
    /// Returns report graph.
    /// </summary>
    private void GetReportGraph(ReportGraphInfo reportGraph)
    {
        // Check whether report graph is defined
        if (reportGraph == null)
        {
            return;
        }

        report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID);
        //check graph security settings
        if (report.ReportAccess != ReportAccessEnum.All)
        {
            if (!CMSContext.CurrentUser.IsAuthenticated())
            {
                Visible = false;
                return;
            }
        }

        EnableSubscription = (EnableSubscription && ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["SubscriptionEnabled"], true) && report.ReportEnableSubscription);
        if (EmailMode && !EnableSubscription)
        {
            this.Visible = false;
            return;
        }

        //Set default parametrs directly if not set
        if (ReportParameters == null)
        {
            //Load ReportInfo
            if (report != null)
            {
                FormInfo fi = new FormInfo(report.ReportParameters);
                // Get datarow with required columns
                ReportParameters = fi.GetDataRow(false);
                fi.LoadDefaultValues(ReportParameters, true);
            }
        }

        // Only use base parameters in case of stored procedure
        if (QueryIsStoredProcedure)
        {
            AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
        }

        // Indicaates whether exception was throw during data loading
        errorOccurred = false;

        // Create graph data
        try
        {
            ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();
            //Resolve parameters in query
            resolver.SourceParameters = AllParameters.ToArray();

            // Resolve dynamic data macros
            if (DynamicMacros != null)
            {
                for (int i = 0; i <= DynamicMacros.GetUpperBound(0); i++)
                {
                    resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                }
            }

            //Prepare query attributes
            QueryText = resolver.ResolveMacros(reportGraph.GraphQuery);
            QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure;

            // Load data
            DataSource = LoadData();

            if (DataHelper.DataSourceIsEmpty(DataSource) && EmailMode && SendOnlyNonEmptyDataSource)
            {
                Visible = false;
                return;
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Get report graph", "E", ex);
            lblError.Text = ex.Message;
            lblError.Visible = true;
            errorOccurred = true;
        }
    }
Example #24
0
    /// <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 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;
                }
            }
        }

        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, true);

                        // 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)
                    {
                        CMSPage.EditedObject = null;
                        return;
                    }
                }

                // Keep xml version
                if (webPartInstance != null)
                {
                    xmlVersion = webPartInstance.XMLVersion;
                }

                // Get the form info
                FormInfo fi = GetWebPartFormInfo();

                // Get the form definition
                if (fi != null)
                {
                    form.AllowMacroEditing = ((WebPartTypeEnum)wpi.WebPartType != WebPartTypeEnum.Wireframe);

                    // Get data row with required columns
                    DataRow dr = fi.GetDataRow(true, wpi.WebPartDefaultValues);

                    if (IsNewWebPart || (xmlVersion > 0))
                    {
                        fi.LoadDefaultValues(dr);

                        // Load overridden system values
                        fi.LoadDefaultValues(dr, wpi.WebPartDefaultValues);
                    }

                    if (IsNewWebPart)
                    {
                        // Set control ID
                        FormFieldInfo ffi = fi.GetFormField("WebPartControlID");
                        if (ffi != null)
                        {
                            ffi.DefaultValue = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                            fi.UpdateFormField("WebPartControlID", ffi);
                        }
                    }

                    // Load values from existing web part
                    LoadDataRowFromWebPart(dr, webPartInstance, fi);

                    // Set a unique WebPartControlID for the new variant
                    if (IsNewVariant)
                    {
                        // Set control ID
                        dr["WebPartControlID"] = WebPartZoneInstance.GetUniqueWebPartId(wpi.WebPartName, templateInstance);
                    }

                    // Init the form
                    InitForm(form, dr, fi);

                    AddExportLink();
                }
                else
                {
                    CMSPage.EditedObject = null;
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ucSelectString.Scope = ReportInfo.OBJECT_TYPE;
        ConnectionStringRow.Visible = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.reporting", "SetConnectionString");
        txtQuery.FullScreenParentElementID = pnlWebPartForm_Properties.ClientID;

        // Test permission for query
        txtQuery.Enabled = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Reporting", "EditSQLQueries");

        versionList.OnAfterRollback += versionList_onAfterRollback;

        PageTitle.HelpTopicName = HELP_TOPIC_LINK;

        // Register common resize and refresh scripts
        RegisterResizeAndRollbackScript("divFooter", divScrolable.ClientID);

        tabControlElem.TabItems.Add(new UITabItem
        {
            Text = GetString("general.general")
        });

        tabControlElem.TabItems.Add(new UITabItem
        {
            Text = GetString("general.preview")
        });

        tabControlElem.UsePostback = true;

        rfvCodeName.ErrorMessage = GetString("general.requirescodename");
        rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname");

        Save += (s, ea) =>
        {
            if (SetData(true))
            {
                ltlScript.Text += ScriptHelper.GetScript("window.RefreshContent();CloseDialog();");
            }
        };

        int reportId = QueryHelper.GetInteger("reportid", 0);
        bool preview = QueryHelper.GetBoolean("preview", false);
        if (reportId > 0)
        {
            mReportInfo = ReportInfoProvider.GetReportInfo(reportId);
        }

        // If preview by URL -> select preview tab
        bool isPreview = QueryHelper.GetBoolean("preview", false);
        if (isPreview && !RequestHelper.IsPostBack())
        {
            tabControlElem.SelectedTab = 1;
        }

        if (PersistentEditedObject == null)
        {
            if (mReportInfo != null) // Must be valid reportid parameter
            {
                int id = QueryHelper.GetInteger("objectid", 0);

                // Try to load tableName from hidden field (adding new graph & preview)
                if (id == 0)
                {
                    id = ValidationHelper.GetInteger(txtNewTableHidden.Value, 0);
                }

                if (id > 0)
                {
                    PersistentEditedObject = ReportTableInfoProvider.GetReportTableInfo(id);
                    mReportTableInfo = PersistentEditedObject as ReportTableInfo;
                }
            }
        }
        else
        {
            mReportTableInfo = PersistentEditedObject as ReportTableInfo;
        }

        if (mReportInfo != null)
        {
            ucSelectString.DefaultConnectionString = mReportInfo.ReportConnectionString;

            // Control text initializations
            if (mReportTableInfo != null)
            {
                PageTitle.TitleText = GetString("Reporting_ReportTable_Edit.TitleText");
                mTableId = mReportTableInfo.TableID;

                if (ObjectVersionManager.DisplayVersionsTab(mReportTableInfo))
                {
                    tabControlElem.TabItems.Add(new UITabItem
                    {
                        Text = GetString("objectversioning.tabtitle")
                    });

                    versionList.Object = mReportTableInfo;
                    versionList.IsLiveSite = false;
                }
            }
            else // New item
            {
                PageTitle.TitleText = GetString("Reporting_ReportTable_Edit.NewItemTitleText");
                if (!RequestHelper.IsPostBack())
                {
                    ucSelectString.Value = String.Empty;
                    txtPageSize.Text = "15";
                    txtQueryNoRecordText.Text = GetString("attachmentswebpart.nodatafound");
                    chkExportEnable.Checked = true;
                    chkSubscription.Checked = true;
                }
            }

            if (!RequestHelper.IsPostBack())
            {
                ControlsHelper.FillListControlWithEnum<PagerButtons>(drpPageMode, "PagerButtons");
                // Preselect page numbers paging
                drpPageMode.SelectedValue = ((int)PagerButtons.Numeric).ToString();

                LoadData();
            }
        }

        if ((preview) && (!RequestHelper.IsPostBack()))
        {
            tabControlElem.SelectedTab = 1;
            ShowPreview();
        }

        // In case of preview paging without saving table
        if (RequestHelper.IsPostBack() && tabControlElem.SelectedTab == 1)
        {
            // Reload default parameters
            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);

            // Get datarow with required columns
            ctrlReportTable.ReportParameters = fi.GetDataRow(false);
            fi.LoadDefaultValues(ctrlReportTable.ReportParameters, true);

            // Collect data and put them in table info
            SetData();
            ctrlReportTable.TableInfo = mReportTableInfo;
        }

        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");
    }
Example #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ucSelectString.Scope               = ReportInfo.OBJECT_TYPE;
        ConnectionStringRow.Visible        = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.reporting", "SetConnectionString");
        txtQuery.FullScreenParentElementID = pnlWebPartForm_Properties.ClientID;

        // Test permission for query
        txtQuery.Enabled = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.Reporting", "EditSQLQueries");

        versionList.OnAfterRollback += versionList_onAfterRollback;

        PageTitle.HelpTopicName = HELP_TOPIC_LINK;

        // Register common resize and refresh scripts
        RegisterResizeAndRollbackScript("divFooter", divScrolable.ClientID);

        tabControlElem.TabItems.Add(new UITabItem
        {
            Text = GetString("general.general")
        });

        tabControlElem.TabItems.Add(new UITabItem
        {
            Text = GetString("general.preview")
        });

        tabControlElem.UsePostback = true;

        rfvCodeName.ErrorMessage    = GetString("general.requirescodename");
        rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname");

        Save += (s, ea) =>
        {
            if (SetData(true))
            {
                ltlScript.Text += ScriptHelper.GetScript("window.RefreshContent();CloseDialog();");
            }
        };

        int  reportId = QueryHelper.GetInteger("reportid", 0);
        bool preview  = QueryHelper.GetBoolean("preview", false);

        if (reportId > 0)
        {
            mReportInfo = ReportInfoProvider.GetReportInfo(reportId);
        }

        // If preview by URL -> select preview tab
        bool isPreview = QueryHelper.GetBoolean("preview", false);

        if (isPreview && !RequestHelper.IsPostBack())
        {
            tabControlElem.SelectedTab = 1;
        }

        if (PersistentEditedObject == null)
        {
            if (mReportInfo != null) // Must be valid reportid parameter
            {
                int id = QueryHelper.GetInteger("objectid", 0);

                // Try to load tableName from hidden field (adding new graph & preview)
                if (id == 0)
                {
                    id = ValidationHelper.GetInteger(txtNewTableHidden.Value, 0);
                }

                if (id > 0)
                {
                    PersistentEditedObject = ReportTableInfoProvider.GetReportTableInfo(id);
                    mReportTableInfo       = PersistentEditedObject as ReportTableInfo;
                }
            }
        }
        else
        {
            mReportTableInfo = PersistentEditedObject as ReportTableInfo;
        }

        if (mReportInfo != null)
        {
            ucSelectString.DefaultConnectionString = mReportInfo.ReportConnectionString;

            // Control text initializations
            if (mReportTableInfo != null)
            {
                PageTitle.TitleText = GetString("Reporting_ReportTable_Edit.TitleText");
                mTableId            = mReportTableInfo.TableID;

                if (ObjectVersionManager.DisplayVersionsTab(mReportTableInfo))
                {
                    tabControlElem.TabItems.Add(new UITabItem
                    {
                        Text = GetString("objectversioning.tabtitle")
                    });

                    versionList.Object     = mReportTableInfo;
                    versionList.IsLiveSite = false;
                }
            }
            else // New item
            {
                PageTitle.TitleText = GetString("Reporting_ReportTable_Edit.NewItemTitleText");
                if (!RequestHelper.IsPostBack())
                {
                    ucSelectString.Value      = String.Empty;
                    txtPageSize.Text          = "15";
                    txtQueryNoRecordText.Text = GetString("attachmentswebpart.nodatafound");
                    chkExportEnable.Checked   = true;
                    chkSubscription.Checked   = true;
                }
            }

            if (!RequestHelper.IsPostBack())
            {
                ControlsHelper.FillListControlWithEnum <PagerButtons>(drpPageMode, "PagerButtons");
                // Preselect page numbers paging
                drpPageMode.SelectedValue = ((int)PagerButtons.Numeric).ToString();

                LoadData();
            }
        }

        if ((preview) && (!RequestHelper.IsPostBack()))
        {
            tabControlElem.SelectedTab = 1;
            ShowPreview();
        }

        // In case of preview paging without saving table
        if (RequestHelper.IsPostBack() && tabControlElem.SelectedTab == 1)
        {
            // Reload default parameters
            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);

            // Get datarow with required columns
            ctrlReportTable.ReportParameters = fi.GetDataRow(false);
            fi.LoadDefaultValues(ctrlReportTable.ReportParameters, true);

            // Collect data and put them in table info
            SetData();
            ctrlReportTable.TableInfo = mReportTableInfo;
        }

        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");
        CurrentMaster.PanelContent.RemoveCssClass("ModalDialogContent");
    }
    /// <summary>
    /// Returns report graph.
    /// </summary>
    private void GetReportGraph(ReportGraphInfo reportGraph)
    {
        Visible = true;
        ucChart.Visible = true;

        int correctWidth = 0;
        if (ComputedWidth != 0)
        {
            correctWidth = ModifyGraphInfo();
        }

        if (Width != String.Empty)
        {
            int graphWidth = ValidationHelper.GetInteger(Width, 0);
            if (graphWidth != 0)
            {
                reportGraph.GraphWidth = graphWidth;
            }
        }

        if (Height != 0)
        {
            reportGraph.GraphHeight = Height;
        }

        ReportGraph graph = new ReportGraph();
        graph.ChartControl = ucChart;

        report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID);
        if (report == null)
        {
            return;
        }

        // Check graph security settings
        if (report.ReportAccess != ReportAccessEnum.All)
        {
            if (!CMSContext.CurrentUser.IsAuthenticated())
            {
                Visible = false;
                return;
            }
        }

        // Set default parametrs directly if not set
        if (ReportParameters == null)
        {
            // Load ReportInfo
            if (report != null)
            {
                FormInfo fi = new FormInfo(report.ReportParameters);

                // Get datarow with required columns
                ReportParameters = fi.GetDataRow(false);
                fi.LoadDefaultValues(ReportParameters, true);
            }
        }

        // If used via widget - this function ensure showing specific interval from actual time (f.e. last 6 weeks)
        ApplyTimeParameters();

        // Only use base parameters in case of stored procedure
        if (QueryIsStoredProcedure)
        {
            AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
        }

        ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();

        errorOccurred = false;

        // Create graph image
        try
        {
            // Resolve parameters in query
            resolver.SourceParameters = AllParameters.ToArray();

            // Resolve dynamic data macros
            if (DynamicMacros != null)
            {
                for (int i = 0; i <= DynamicMacros.GetUpperBound(0); i++)
                {
                    resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                }
            }

            // Prepare query attributes
            QueryText = resolver.ResolveMacros(reportGraph.GraphQuery);
            QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure;

            // LoadData
            DataSet dsGraphData = LoadData();

            // Empty dataset, and flag not send empty dataset is set
            if (SendOnlyNonEmptyDataSource && EmailMode && DataHelper.DataSourceIsEmpty(dsGraphData))
            {
                Visible = false;
                return;
            }

            // Test if dataset is empty
            if (DataHelper.DataSourceIsEmpty(dsGraphData))
            {
                string noRecordText = CMSContext.ResolveMacros(ValidationHelper.GetString(reportGraph.GraphSettings["QueryNoRecordText"], String.Empty));
                if (noRecordText != String.Empty)
                {
                    ltlEmail.Text = noRecordText;
                    lblInfo.Text = noRecordText;
                    ucChart.Visible = false;
                    menuCont.MenuID = String.Empty;
                    EnableExport = false;
                    plcInfo.Visible = true;
                }
                else
                {
                    Visible = false;
                }
            }
            else
            {
                // Create Chart
                graph.CorrectWidth = correctWidth;
                if (EmailMode)
                {
                    byte[] data = graph.CreateChart(reportGraph, dsGraphData, resolver, true);
                    ltlEmail.Text = "##InlineImage##" + reportGraph.GraphName + "##InlineImage##";
                    ReportSubscriptionSender.AddToRequest(report.ReportName, "g" + reportGraph.GraphName, data);
                }
                else
                {
                    graph.CreateChart(reportGraph, dsGraphData, resolver);
                }
            }

            // Check if subscription is allowed
            EnableSubscription = (EnableSubscription && ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["SubscriptionEnabled"], true) && report.ReportEnableSubscription);
            if (EmailMode && !EnableSubscription)
            {
                this.Visible = false;
                return;
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Get report graph", "E", ex);
            graph.CorrectWidth = correctWidth;
            graph.CreateInvalidDataGraph(reportGraph, "Reporting.Graph.InvalidDataGraph", false);
            errorOccurred = true;
        }
    }
Example #28
0
    /// <summary>
    /// Loads data for advanced mode
    /// </summary>
    private void LoadData()
    {
        if (!RequestHelper.IsPostBack())
        {
            if (mReportSubscriptionInfo.ReportSubscriptionID > 0)
            {
                // Initial settings
                ucInterval.ScheduleInterval = mReportSubscriptionInfo.ReportSubscriptionInterval;
                chkEnabled.Checked          = mReportSubscriptionInfo.ReportSubscriptionEnabled;
                txtEmail.Text       = mReportSubscriptionInfo.ReportSubscriptionEmail;
                txtSubject.Text     = mReportSubscriptionInfo.ReportSubscriptionSubject;
                chkNonEmpty.Checked = mReportSubscriptionInfo.ReportSubscriptionOnlyNonEmpty;
                ucMacroEditor.Text  = mReportSubscriptionInfo.ReportSubscriptionCondition;
            }
            else
            {
                // New item
                chkEnabled.Checked       = true;
                txtEmail.Text            = MembershipContext.AuthenticatedUser.Email;
                txtSubject.Text          = ResHelper.LocalizeString(Report.ReportDisplayName);
                chkNonEmpty.Checked      = true;
                ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY;
            }

            FillItems();
        }

        if ((Report != null) && !String.IsNullOrEmpty(Report.ReportParameters) && (Report.ReportParameters != "<form></form>"))
        {
            // Convert field "DateFrom" and "DateTo" to string to be able to display macros
            FormInfo      fi  = new FormInfo(Report.ReportParameters);
            FormFieldInfo ffi = fi.GetFormField("FromDate");

            if (ffi != null)
            {
                ffi.DataType  = FieldDataType.Text;
                ffi.FieldType = FormFieldControlTypeEnum.CalendarControl;
                ffi.Settings["AllowMacros"] = true;
                ffi.Size       = 400;
                ffi.AllowEmpty = true;
                ffi.Visible    = false;
            }

            ffi = fi.GetFormField("ToDate");
            if (ffi != null)
            {
                ffi.DataType  = FieldDataType.Text;
                ffi.FieldType = FormFieldControlTypeEnum.CalendarControl;
                ffi.Settings["AllowMacros"] = true;
                ffi.Size       = 400;
                ffi.AllowEmpty = true;
                ffi.Visible    = false;
            }

            // Get datarow from forminfo (it contains report parameters passed by querystring)
            DataRow defaultValues = fi.GetDataRow(false);

            // Load default values
            fi.LoadDefaultValues(defaultValues, true);

            // Display basic form, only if any item is visible
            bool display = false;
            foreach (FormFieldInfo field in fi.ItemsList)
            {
                if (field.Visible)
                {
                    display = true;
                    break;
                }
            }

            pnlParametersEnvelope.Visible = display;

            // Loop through all nodes is subscription's XML parameters and replace report's value with current subscription's ones.
            if (mReportSubscriptionInfo.ReportSubscriptionID > 0)
            {
                if (!String.IsNullOrEmpty(mReportSubscriptionInfo.ReportSubscriptionParameters))
                {
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(mReportSubscriptionInfo.ReportSubscriptionParameters);
                    foreach (DataColumn col in defaultValues.Table.Columns)
                    {
                        XmlNode node = xml.SelectSingleNode("/Root/" + col.ColumnName);
                        if (node != null)
                        {
                            // In case of different data types use try catch block
                            try
                            {
                                defaultValues[col.ColumnName] = DataHelper.ConvertValue(node.InnerText, col.DataType);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }


            mParameters             = defaultValues;
            pnlFromToParams.Visible = !SetTimeControls();

            // Set basic form parameters
            formElem.DataRow = defaultValues;
            formElem.SubmitButton.Visible = false;
            formElem.SubmitButton.RegisterHeaderAction = false;
            formElem.FormInformation = fi;
            formElem.SiteName        = SiteContext.CurrentSiteName;
            formElem.Mode            = FormModeEnum.Update;
            formElem.Visible         = true;
        }
        else
        {
            pnlParametersEnvelope.Visible = false;
            pnlFromToParams.Visible       = false;
        }
    }
    /// <summary>
    /// Loads data for advanced mode
    /// </summary>
    private void LoadData()
    {
        if (!RequestHelper.IsPostBack())
        {
            if (mReportSubscriptionInfo.ReportSubscriptionID > 0)
            {
                // Initial settings
                ucInterval.ScheduleInterval = mReportSubscriptionInfo.ReportSubscriptionInterval;
                chkEnabled.Checked = mReportSubscriptionInfo.ReportSubscriptionEnabled;
                txtEmail.Text = mReportSubscriptionInfo.ReportSubscriptionEmail;
                txtSubject.Text = mReportSubscriptionInfo.ReportSubscriptionSubject;
                chkNonEmpty.Checked = mReportSubscriptionInfo.ReportSubscriptionOnlyNonEmpty;
                ucMacroEditor.Text = mReportSubscriptionInfo.ReportSubscriptionCondition;
            }
            else
            {
                // New item
                chkEnabled.Checked = true;
                txtEmail.Text = MembershipContext.AuthenticatedUser.Email;
                txtSubject.Text = ResHelper.LocalizeString(Report.ReportDisplayName);
                chkNonEmpty.Checked = true;
                ucInterval.DefaultPeriod = SchedulingHelper.PERIOD_DAY;
            }

            FillItems();
        }

        if ((Report != null) && !String.IsNullOrEmpty(Report.ReportParameters) && (Report.ReportParameters != "<form></form>"))
        {
            // Convert field "DateFrom" and "DateTo" to string to be able to display macros
            FormInfo fi = new FormInfo(Report.ReportParameters);
            FormFieldInfo ffi = fi.GetFormField("FromDate");

            if (ffi != null)
            {
                ffi.DataType = FieldDataType.Text;
                ffi.FieldType = FormFieldControlTypeEnum.CalendarControl;
                ffi.Settings["AllowMacros"] = true;
                ffi.Size = 400;
                ffi.AllowEmpty = true;
                ffi.Visible = false;
            }

            ffi = fi.GetFormField("ToDate");
            if (ffi != null)
            {
                ffi.DataType = FieldDataType.Text;
                ffi.FieldType = FormFieldControlTypeEnum.CalendarControl;
                ffi.Settings["AllowMacros"] = true;
                ffi.Size = 400;
                ffi.AllowEmpty = true;
                ffi.Visible = false;
            }

            // Get datarow from forminfo (it contains report parameters passed by querystring)
            DataRow defaultValues = fi.GetDataRow(false);

            // Load default values
            fi.LoadDefaultValues(defaultValues, true);

            // Display basic form, only if any item is visible
            bool display = false;
            foreach (FormFieldInfo field in fi.ItemsList)
            {
                if (field.Visible)
                {
                    display = true;
                    break;
                }
            }

            pnlParametersEnvelope.Visible = display;

            // Loop through all nodes is subscription's XML parameters and replace report's value with current subscription's ones.
            if (mReportSubscriptionInfo.ReportSubscriptionID > 0)
            {
                if (!String.IsNullOrEmpty(mReportSubscriptionInfo.ReportSubscriptionParameters))
                {
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(mReportSubscriptionInfo.ReportSubscriptionParameters);
                    foreach (DataColumn col in defaultValues.Table.Columns)
                    {
                        XmlNode node = xml.SelectSingleNode("/Root/" + col.ColumnName);
                        if (node != null)
                        {
                            // In case of different data types use try catch block
                            try
                            {
                                defaultValues[col.ColumnName] = DataHelper.ConvertValue(node.InnerText, col.DataType);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                }
            }

            mParameters = defaultValues;
            pnlFromToParams.Visible = !SetTimeControls();

            // Set basic form parameters
            formElem.DataRow = defaultValues;
            formElem.SubmitButton.Visible = false;
            formElem.SubmitButton.RegisterHeaderAction = false;
            formElem.FormInformation = fi;
            formElem.SiteName = SiteContext.CurrentSiteName;
            formElem.Mode = FormModeEnum.Update;
            formElem.Visible = true;
        }
        else
        {
            pnlParametersEnvelope.Visible = false;
            pnlFromToParams.Visible = false;
        }
    }
    /// <summary>
    /// Show preview.
    /// </summary>
    private void ShowPreview()
    {
        if (mReportInfo != null)
        {
            pnlPreview.Visible = true;
            divPanelHolder.Visible = false;
            pnlVersions.Visible = false;

            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);
            DataRow defaultValues = fi.GetDataRow(false);

            fi.LoadDefaultValues(defaultValues, true);

            //reportGraph.ContextParameters
            ctrlReportValue.ReportParameters = defaultValues;

            ctrlReportValue.Visible = true;
            ctrlReportValue.ValueInfo = mReportValueInfo;

            ctrlReportValue.ReloadData(true);
        }
    }
Example #31
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Test permission for query
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Reporting", "EditSQLQueries"))
        {
            txtQuery.Enabled = false;
        }
        else
        {
            txtQuery.Enabled = true;
        }

        versionList.OnAfterRollback += new EventHandler(versionList_onAfterRollback);

        // Own javascript tab change handling -> because tab control raises changetab after prerender - too late
        // Own selected tab change handling
        RegisterTabScript(hdnSelectedTab.ClientID, tabControlElem);

        // Register common resize and refresh scripts
        RegisterResizeAndRollbackScript(divFooter.ClientID, divScrolable.ClientID);

        string[,] tabs = new string[4, 4];
        tabs[0, 0] = GetString("general.general");
        tabs[0, 1] = "SetHelpTopic('helpTopic', 'report_table_properties')";
        tabs[1, 0] = GetString("general.preview");
        tabs[0, 1] = "SetHelpTopic('helpTopic', 'report_table_properties')";

        tabControlElem.Tabs = tabs;
        tabControlElem.UsePostback = true;
        CurrentMaster.Title.HelpName = "helpTopic";
        CurrentMaster.Title.HelpTopicName = "report_table_properties";
        CurrentMaster.Title.TitleCssClass = "PageTitleHeader";

        rfvCodeName.ErrorMessage = GetString("general.requirescodename");
        rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname");
        btnApply.Text = GetString("General.apply");
        btnOk.Text = GetString("General.OK");
        btnCancel.Text = GetString("General.Cancel");

        int reportId = QueryHelper.GetInteger("reportid", 0);
        bool preview = QueryHelper.GetBoolean("preview", false);
        if (reportId > 0)
        {
            reportInfo = ReportInfoProvider.GetReportInfo(reportId);
        }

        // If preview by URL -> select preview tab
        bool isPreview = QueryHelper.GetBoolean("preview", false);
        if (isPreview && !RequestHelper.IsPostBack())
        {
            SelectedTab = 1;
        }

        if (PersistentEditedObject == null)
        {
            if (reportInfo != null) // Must be valid reportid parameter
            {
                string tableName = ValidationHelper.GetString(Request.QueryString["itemname"], "");

                // Try to load tableName from hidden field (adding new graph & preview)
                if (tableName == String.Empty)
                {
                    tableName = txtNewTableHidden.Value;
                }

                if (ValidationHelper.IsIdentifier(tableName))
                {
                    PersistentEditedObject = ReportTableInfoProvider.GetReportTableInfo(reportInfo.ReportName + "." + tableName);
                    tableInfo = PersistentEditedObject as ReportTableInfo;
                }
            }
        }
        else
        {
            tableInfo = PersistentEditedObject as ReportTableInfo;
        }

        if (reportInfo != null)
        {
            // Control text initializations
            if (tableInfo != null)
            {
                CurrentMaster.Title.TitleText = GetString("Reporting_ReportTable_Edit.TitleText");
                CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Reporting_ReportTable/object.png");

                tableId = tableInfo.TableID;

                if (ObjectVersionManager.DisplayVersionsTab(tableInfo))
                {
                    tabs[2, 0] = GetString("objectversioning.tabtitle");
                    tabs[2, 1] = "SetHelpTopic('helpTopic', 'objectversioning_general');";

                    versionList.Object = tableInfo;
                    versionList.IsLiveSite = false;
                }
            }
            else // New item
            {
                CurrentMaster.Title.TitleText = GetString("Reporting_ReportTable_Edit.NewItemTitleText");
                CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Reporting_ReportTable/new.png");

                if (!RequestHelper.IsPostBack())
                {
                    txtPageSize.Text = "15";
                    txtQueryNoRecordText.Text = GetString("attachmentswebpart.nodatafound");
                    chkExportEnable.Checked = true;
                }

                newTable = true;
            }

            // Set help key
            CurrentMaster.Title.HelpTopicName = "report_table_properties";

            if (!RequestHelper.IsPostBack())
            {
                DataHelper.FillListControlWithEnum(typeof(PagerButtons), drpPageMode, "PagerButtons.", null);
                // Preselect page numbers paging
                drpPageMode.SelectedValue = ((int)PagerButtons.Numeric).ToString();

                LoadData();
            }
        }

        if ((preview) && (!RequestHelper.IsPostBack()))
        {
            tabControlElem.SelectedTab = 1;
            ShowPreview();
        }

        // In case of preview paging without saving table
        if (RequestHelper.IsPostBack() && tabControlElem.SelectedTab == 1)
        {
            // Reload deafult parameters
            FormInfo fi = new FormInfo(reportInfo.ReportParameters);
            // Get datarow with required columns
            ctrlReportTable.ReportParameters = fi.GetDataRow();
            fi.LoadDefaultValues(ctrlReportTable.ReportParameters, true);

            // Colect data and put them in talbe info
            Save(false);
            ctrlReportTable.TableInfo = tableInfo;
        }
    }
Example #32
0
    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>
    /// Initializes inner controls.
    /// </summary>
    /// <param name="forceReload">Indicates if form with parameters should be reloaded</param>
    private void InitializeControl(bool forceReload = false)
    {
        // Init rule selector
        uniSelector.Value = mSelectedRuleName;

        MacroRuleInfo mri = MacroRuleInfoProvider.GetMacroRuleInfo(mSelectedRuleName);
        if (mri != null)
        {
            // Show rule description
            ltlDescription.Text = mri.MacroRuleDescription;
            txtErrorMsg.Value = string.Empty;
            txtErrorMsg.WatermarkText = string.IsNullOrEmpty(DefaultErrorMessage) ? ResHelper.GetString("basicform.invalidinput") : DefaultErrorMessage;

            // Prepare form for rule parameters
            FormInfo fi = new FormInfo(mri.MacroRuleParameters);
            formProperties.FormInformation = fi;
            DataRow data = fi.GetDataRow();
            formProperties.DataRow = data;

            fi.LoadDefaultValues(formProperties.DataRow, FormResolveTypeEnum.AllFields);
            if ((mMacroRule != null) && (mMacroRuleTree != null) && mMacroRuleTree.RuleName.EqualsCSafe(mSelectedRuleName, true))
            {
                // Set params from rule given by Value property
                foreach (DictionaryEntry entry in mMacroRuleTree.Parameters)
                {
                    string paramName = ValidationHelper.GetString(entry.Key, string.Empty);
                    MacroRuleParameter param = entry.Value as MacroRuleParameter;

                    if ((param != null) && data.Table.Columns.Contains(paramName))
                    {
                        data[paramName] = param.Value;
                    }
                }

                txtErrorMsg.Value = mMacroRule.ErrorMessage;
            }

            if (forceReload)
            {
                // Reload params
                formProperties.ReloadData();
            }

            mParamsInitialized = true;
        }
    }
Example #34
0
    /// <summary>
    /// Returns report graph.
    /// </summary>
    private void GetReportGraph(ReportGraphInfo reportGraph)
    {
        Visible         = true;
        ucChart.Visible = true;

        int correctWidth = 0;

        if (ComputedWidth != 0)
        {
            correctWidth = ModifyGraphInfo();
        }

        if (Width != String.Empty)
        {
            int graphWidth = ValidationHelper.GetInteger(Width, 0);
            if (graphWidth != 0)
            {
                reportGraph.GraphWidth = graphWidth;
            }
        }

        if (Height != 0)
        {
            reportGraph.GraphHeight = Height;
        }

        ReportGraph graph = new ReportGraph();

        graph.ChartControl = ucChart;

        ReportInfo report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID);

        if (report == null)
        {
            return;
        }

        // Check graph security settings
        if (report.ReportAccess != ReportAccessEnum.All)
        {
            if (!CMSContext.CurrentUser.IsAuthenticated())
            {
                Visible = false;
                return;
            }
        }

        // Set default parametrs directly if not set
        if (ReportParameters == null)
        {
            // Load ReportInfo
            if (report != null)
            {
                FormInfo fi = new FormInfo(report.ReportParameters);
                // Get datarow with required columns
                ReportParameters = fi.GetDataRow();
                fi.LoadDefaultValues(ReportParameters, true);
            }
        }

        // If used via widget - this function ensure showing specific interval from actual time (f.e. last 6 weeks)
        ApplyTimeParameters();

        // Only use base parameters in case of stored procedure
        if (QueryIsStoredProcedure)
        {
            AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
        }

        ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();

        // Indicaates whether exception was throw during data loading
        bool errorOccurred = false;

        // Create graph image
        try
        {
            // Resolve parameters in query
            resolver.SourceParameters = AllParameters.ToArray();

            // Resolve dynamic data macros
            if (DynamicMacros != null)
            {
                for (int i = 0; i <= DynamicMacros.GetUpperBound(0); i++)
                {
                    resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                }
            }

            // Prepare query attributes
            QueryText = resolver.ResolveMacros(reportGraph.GraphQuery);
            QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure;

            // LoadData
            DataSet dsGraphData = LoadData();

            // Test if dataset is empty
            if (DataHelper.DataSourceIsEmpty(dsGraphData))
            {
                string noRecordText = ValidationHelper.GetString(reportGraph.GraphSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    lblInfo.Text    = noRecordText;
                    lblInfo.Visible = true;
                    ucChart.Visible = false;
                    menuCont.MenuID = String.Empty;
                    return;
                }
                Visible = false;
            }
            else
            {
                // Create Chart
                graph.CorrectWidth = correctWidth;
                graph.CreateChart(reportGraph, dsGraphData, resolver);
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Get report graph", "E", ex);
            graph.CorrectWidth = correctWidth;
            graph.CreateInvalidDataGraph(reportGraph, "Reporting.Graph.InvalidDataGraph", false);
            errorOccurred = true;
        }

        // Export data
        if ((report != null) && (!errorOccurred))
        {
            ProcessExport(ValidationHelper.GetCodeName(report.ReportDisplayName));
        }
    }
Example #35
0
    protected override void OnPreRender(EventArgs e)
    {
        pnlReports.Attributes.Add("style", "margin-bottom:3px");

        string reportName = ValidationHelper.GetString(usReports.Value, String.Empty);

        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(CurrentGuid());
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr);
            bool             itemVisible = false;
            List <IFormItem> items       = fi.ItemsList;
            foreach (IFormItem 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
        {
            if (ReportID == 0)
            {
                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();

        if (ri == null)
        {
            string[,] itemSpecialFields = new string[1, 2];
            itemSpecialFields[0, 0]     = "(" + firstItemText + ")";
            itemSpecialFields[0, 1]     = "0";
            usItems.SpecialFields       = itemSpecialFields;
        }

        if (ShowItemSelector)
        {
            ReloadItems();
        }

        if (setValues)
        {
            WindowHelper.Add(CurrentGuid(), CurrentDataSet);
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "OpenModalWindowReportItem", ScriptHelper.GetScript("modalDialog('" + ResolveUrl("~/CMSModules/Reporting/Dialogs/ReportParametersSelector.aspx?ReportID=" + ReportID + "&guid=" + CurrentGuid().ToString()) + "','ReportParametersDialog', 700, 500);"));
            keepDataInWindowsHelper = true;
        }

        // Apply reportid condition if report was selected via uniselector
        if (ri != null)
        {
            FormInfo fi = new FormInfo(ri.ReportParameters);
            DataRow  dr = fi.GetDataRow();
            DataSet  ds = CurrentDataSet;

            ViewState["ParametersXmlData"]   = null;
            ViewState["ParametersXmlSchema"] = null;

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                ViewState["ParametersXmlData"]   = ds.GetXml();
                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);
    }
Example #36
0
    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[(string)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 widget.
    /// </summary>
    private void AddWidget()
    {
        int widgetID = ValidationHelper.GetInteger(WidgetId, 0);

        // Add web part to the currently selected zone under currently selected page
        if ((widgetID > 0) && !String.IsNullOrEmpty(ZoneId))
        {
            if (wi != null)
            {
                // Ensure layout zone flag
                if (QueryHelper.GetBoolean("layoutzone", false))
                {
                    WebPartZoneInstance zone = pti.EnsureZone(ZoneId);
                    zone.LayoutZone = true;
                    zone.WidgetZoneType = zoneType;

                    // Ensure the layout zone flag in the original page template instance
                    WebPartZoneInstance zoneInstance = templateInstance.GetZone(ZoneId);
                    if (zoneInstance != null)
                    {
                        zoneInstance.LayoutZone = true;
                        zone.WidgetZoneType = zoneType;
                    }
                }

                // Add the widget
                WebPartInstance newWidget = templateInstance.AddWidget(ZoneId, widgetID);
                if (newWidget != null)
                {
                    // Prepare the form info to get the default properties
                    FormInfo fi = new FormInfo(wi.WidgetProperties);

                    DataRow dr = fi.GetDataRow();
                    fi.LoadDefaultValues(dr);

                    newWidget.LoadProperties(dr);

                    // Add webpart to user's last recently used
                    CMSContext.CurrentUser.UserSettings.UpdateRecentlyUsedWidget(wi.WidgetName);

                    widgetInstance = newWidget;
                }
            }
        }
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if ((GraphImageWidth != 0) && (ComputedWidth == 0))
        {
            // Graph width is computed no need to create graph
            return;
        }

        Visible = true;

        errorOccurred = false;

        try
        {
            ReportTableName = Parameter;

            EnsureTableInfo();
            EnsureChildControls();

            //Test security
            if (TableInfo != null)
            {
                ri = ReportInfoProvider.GetReportInfo(TableInfo.TableReportID);
                if (ri != null)
                {
                    if (ri.ReportAccess != ReportAccessEnum.All)
                    {
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            Visible = false;
                            return;
                        }
                    }

                    EnableSubscription = EnableSubscription && (ValidationHelper.GetBoolean(TableInfo.TableSettings["SubscriptionEnabled"], true) && ri.ReportEnableSubscription);
                    if (EmailMode && !EnableSubscription)
                    {
                        this.Visible = false;
                        return;
                    }

                    //Set default parametrs directly if not set
                    if (ReportParameters == null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        ReportParameters = fi.GetDataRow(false);
                        fi.LoadDefaultValues(ReportParameters, true);
                    }

                    ApplyTimeParameters();
                }
            }

            // Only use base parameters in case of stored procedure
            if (QueryIsStoredProcedure)
            {
                AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
            }

            // Load data
            DataSet ds = LoadData();

            // If no data load, set empty dataset
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                if (EmailMode && SendOnlyNonEmptyDataSource)
                {
                    Visible = false;
                    return;
                }

                string noRecordText = ValidationHelper.GetString(TableInfo.TableSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    GridViewObject.Visible = false;
                    lblInfo.Text = CMSContext.ResolveMacros(noRecordText);
                    plcInfo.Visible = true;
                    EnableExport = false;
                    return;
                }

                if (!EmailMode)
                {
                    Visible = false;
                }
            }
            else
            {
                GridViewObject.Visible = true;
                // Resolve macros in column names
                int i = 0;
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName == "Column" + ((int)(i + 1)).ToString())
                    {
                        dc.ColumnName = ResolveMacros(ds.Tables[0].Rows[0][i].ToString());
                    }
                    else
                    {
                        dc.ColumnName = ResolveMacros(dc.ColumnName);
                    }
                    i++;
                }

                // Resolve macros in dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dc.DataType.FullName.ToLowerCSafe() == "system.string")
                        {
                            dr[dc.ColumnName] = ResolveMacros(ValidationHelper.GetString(dr[dc.ColumnName], ""));
                        }
                    }
                }

                if (EmailMode)
                {
                    // For some email formats, export data in csv format
                    EmailFormatEnum format = EmailHelper.GetEmailFormat(ReportSubscriptionSiteID);

                    if ((format == EmailFormatEnum.Both) || (format == EmailFormatEnum.PlainText))
                    {
                        using (MemoryStream ms = MemoryStream.New())
                        {
                            DataExportHelper deh = new DataExportHelper(ds);
                            byte[] data = deh.ExportToCSV(ds, 0, ms, true);
                            ReportSubscriptionSender.AddToRequest(ri.ReportName, "t" + TableInfo.TableName, data);
                        }
                    }

                    // For plain text email show table only as attachment
                    if (format == EmailFormatEnum.PlainText)
                    {
                        menuCont.Visible = false;
                        ltlEmail.Visible = true;
                        ltlEmail.Text = String.Format(GetString("reportsubscription.attachment"), TableInfo.TableName);
                        return;
                    }

                    GenerateTableForEmail(ds);
                    menuCont.Visible = false;
                    return;
                }
            }

            ApplyStyles();

            // Databind to gridview control
            GridViewObject.DataSource = ds;
            EnsurePageIndex();
            GridViewObject.DataBind();

            if ((TableFirstColumnWidth != Unit.Empty) && (GridViewObject.Rows.Count > 0))
            {
                GridViewObject.Rows[0].Cells[0].Width = TableFirstColumnWidth;
            }
        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportTable.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report table", "E", ex);
            errorOccurred = true;
        }
    }
Example #39
0
    /// <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);
    }
    /// <summary>
    /// Loads the widget form.
    /// </summary>
    private void LoadForm()
    {
        // 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 = VariantHelper.GetVariantID(VariantMode, PageTemplateId, variantName, false);

                // Set the variant id from the database
                if (variantIdFromDB > 0)
                {
                    VariantID    = variantIdFromDB;
                    IsNewVariant = false;
                }
            }
        }

        EnsureDashboard();

        if (!String.IsNullOrEmpty(WidgetId) && !IsInline)
        {
            if (CurrentPageInfo == null)
            {
                ShowError(GetString("Widgets.Properties.aliasnotfound"));
                pnlFormArea.Visible = false;
                return;
            }

            // Get template instance
            mTemplateInstance = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo);

            if (!IsNewWidget)
            {
                // Get the instance of widget
                mWidgetInstance = mTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                if (mWidgetInstance == null)
                {
                    ShowError(GetString("Widgets.Properties.WidgetNotFound"));
                    pnlFormArea.Visible = false;
                    return;
                }

                if ((VariantID > 0) && (mWidgetInstance != null) && (mWidgetInstance.PartInstanceVariants != null))
                {
                    // Check OnlineMarketing permissions.
                    if (CheckPermissions("Read"))
                    {
                        mWidgetInstance = CurrentPageInfo.DocumentTemplateInstance.GetWebPart(InstanceGUID, WidgetId);
                        mWidgetInstance = mWidgetInstance.PartInstanceVariants.Find(v => v.VariantID.Equals(VariantID));
                        // Set the widget variant mode
                        if (mWidgetInstance != null)
                        {
                            VariantMode = mWidgetInstance.VariantMode;
                        }
                    }
                    else
                    {
                        // Not authorized 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)
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(mWidgetInstance.WebPartType);
            }
            // Widget instance hasn't created yet
            else
            {
                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
            }

            // Keep xml version
            if (mWidgetInstance != null)
            {
                mXmlVersion = mWidgetInstance.XMLVersion;
            }

            UIContext.EditedObject = mWidgetInfo;

            // Get the zone to which it inserts
            WebPartZoneInstance zone = mTemplateInstance.GetZone(ZoneId);
            if ((ZoneType == WidgetZoneTypeEnum.None) && (zone != null))
            {
                ZoneType = zone.WidgetZoneType;
            }

            // Check security
            var currentUser = MembershipContext.AuthenticatedUser;

            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 (!mWidgetInfo.WidgetForGroup || (!currentUser.IsGroupAdministrator(CurrentPageInfo.NodeGroupID) && ((PortalContext.ViewMode != ViewModeEnum.Design) || ((PortalContext.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 (!mWidgetInfo.WidgetForEditor)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for user zones
            case WidgetZoneTypeEnum.User:
                if (!mWidgetInfo.WidgetForUser)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;

            // Widget must be allowed for dashboard zones
            case WidgetZoneTypeEnum.Dashboard:
                if (!mWidgetInfo.WidgetForDashboard)
                {
                    if (OnNotAllowed != null)
                    {
                        OnNotAllowed(this, null);
                    }
                }
                break;
            }

            // Check security
            if ((ZoneType != WidgetZoneTypeEnum.Group) && !WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                if (OnNotAllowed != null)
                {
                    OnNotAllowed(this, null);
                }
            }

            // Get form schemas
            mWebPartInfo = WebPartInfoProvider.GetWebPartInfo(mWidgetInfo.WidgetWebPartID);
            string   widgetProperties = FormHelper.MergeFormDefinitions(mWebPartInfo.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, ZoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);

            if (fi != null)
            {
                fi.ContextResolver.Settings.RelatedObject = mTemplateInstance;

                // Check if there are some editable properties
                var ffi = fi.GetFields(true, false);
                if ((ffi == null) || (ffi.Count == 0))
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                DataRow dr = fi.GetDataRow();

                // Load overridden values for new widget
                if (IsNewWidget || (mXmlVersion > 0))
                {
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }

                if (IsNewWidget)
                {
                    // Override default value and set title as widget display name
                    DataHelper.SetDataRowValue(dr, "WidgetTitle", ResHelper.LocalizeString(mWidgetInfo.WidgetDisplayName));
                }

                // Load values from existing widget
                LoadDataRowFromWidget(dr, fi);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.Base.Web.UI.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;
            string    widgetName = String.Empty;



            if (IsNewWidget)
            {
                // New widget - load widget info by id
                if (!String.IsNullOrEmpty(WidgetId))
                {
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(ValidationHelper.GetInteger(WidgetId, 0));
                }
                else
                {
                    // Try to get widget from codename
                    widgetName  = QueryHelper.GetString("WidgetName", String.Empty);
                    mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
                }
            }
            else
            {
                if (definition == null)
                {
                    DisplayError("widget.failedtoload");
                    return;
                }

                // Parse definition
                parameters = CMSDialogHelper.GetHashTableFromString(definition);

                // Trim control name
                if (parameters["name"] != null)
                {
                    widgetName = parameters["name"].ToString();
                }

                mWidgetInfo = WidgetInfoProvider.GetWidgetInfo(widgetName);
            }
            if (mWidgetInfo == null)
            {
                DisplayError("widget.failedtoload");
                return;
            }

            // If widget cant be used as inline
            if (!mWidgetInfo.WidgetForInline)
            {
                DisplayError("widget.cantbeusedasinline");
                return;
            }


            // Test permission for user
            var currentUser = MembershipContext.AuthenticatedUser;
            if (!WidgetRoleInfoProvider.IsWidgetAllowed(mWidgetInfo, currentUser.UserID, AuthenticationHelper.IsAuthenticated()))
            {
                mIsValidWidget = false;
                OnNotAllowed(this, null);
            }

            // 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(mWidgetInfo.WidgetWebPartID);
            string      widgetProperties = FormHelper.MergeFormDefinitions(wpi.WebPartProperties, mWidgetInfo.WidgetProperties);
            FormInfo    fi = PortalFormHelper.GetWidgetFormInfo(mWidgetInfo.WidgetName, zoneType, widgetProperties, true, mWidgetInfo.WidgetDefaultValues);
            if (fi != null)
            {
                // Check if there are some editable properties
                mFields = fi.GetFields(true, true);
                if ((mFields == null) || !mFields.Any())
                {
                    ShowInformation(GetString("widgets.emptyproperties"));
                }

                // Get datarows with required columns
                DataRow dr = PortalHelper.CombineWithDefaultValues(fi, mWidgetInfo);

                if (IsNewWidget)
                {
                    // Load default values for new widget
                    fi.LoadDefaultValues(dr, FormResolveTypeEnum.WidgetVisible);
                }
                else
                {
                    foreach (string key in parameters.Keys)
                    {
                        object value = parameters[key];
                        // Test if given property exists
                        if (dr.Table.Columns.Contains(key) && (value != null))
                        {
                            try
                            {
                                dr[key] = DataHelper.ConvertValue(value, dr.Table.Columns[key].DataType);
                            }
                            catch
                            {
                            }
                        }
                    }
                }

                // Override default value and set title as widget display name
                DataHelper.SetDataRowValue(dr, "WidgetTitle", mWidgetInfo.WidgetDisplayName);

                // Init HTML toolbar if exists
                InitHTMLToobar(fi);

                // Init the form
                InitForm(formCustom, dr, fi);

                // Set the context name
                formCustom.ControlContext.ContextName = CMS.Base.Web.UI.ControlContext.WIDGET_PROPERTIES;
            }
        }
    }
    /// <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);
    }
Example #42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Setup info/error message placeholder
        if (MessagesPlaceHolder != null)
        {
            MessagesPlaceHolder.UseRelativePlaceHolder = false;
            form.EnsureMessagesPlaceholder(MessagesPlaceHolder);
        }

        // Load default properties from XML
        XmlDocument xml = new XmlDocument();

        xml.Load(ResolveUrl(HttpContext.Current.Server.MapPath(PortalFormHelper.BEFOREPROPERTIESDEFINITION)));

        // Load UI element and element's page template (if any)
        mUIElementInfo = UIElementInfoProvider.GetUIElementInfo(QueryHelper.GetInteger("elementID", 0));

        if (mUIElementInfo != null)
        {
            PageTemplateInfo pti = null;
            if (mUIElementInfo.ElementType == UIElementTypeEnum.PageTemplate)
            {
                pti = PageTemplateInfoProvider.GetPageTemplateInfo(mUIElementInfo.ElementPageTemplateID);
            }

            form.Enabled = ((SystemContext.DevelopmentMode || mUIElementInfo.ElementIsCustom) && (!UIElementInfoProvider.AllowEditOnlyCurrentModule || (mUIElementInfo.ElementResourceID == QueryHelper.GetInteger("moduleId", 0))));

            // Create form info
            FormInfo fi = (pti != null) ? pti.PageTemplatePropertiesForm : PortalFormHelper.GetUIElementDefaultPropertiesForm(UIElementPropertiesPosition.Both);
            form.FormInformation = fi;

            // Load data row from properties
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr);
            if ((mUIElementInfo == null) || !mUIElementInfo.IsApplication)
            {
                fi.RemoveFormField("DescriptionLink");
            }

            XmlData customData = new XmlData();

            // Load element properties
            XmlData data = new XmlData();
            data.AllowMacros = true;
            data.LoadData(mUIElementInfo.ElementProperties);

            form.MacroTable = data.MacroTable;

            // Fill template datarow with element's properties. If template does not contain such column, add it to custom
            foreach (String col in data.ColumnNames)
            {
                if (col.StartsWith(UIContextData.CATEGORYNAMEPREFIX, StringComparison.Ordinal))
                {
                    if (!RequestHelper.IsPostBack())
                    {
                        String           catName = col.Substring(UIContextData.CATEGORYNAMEPREFIX.Length);
                        FormCategoryInfo fci     = fi.GetFormCategory(catName);
                        if (fci != null)
                        {
                            fci.SetPropertyValue(FormCategoryPropertyEnum.CollapsedByDefault, ValidationHelper.GetBoolean(data[col], false).ToString().ToLowerInvariant());
                        }
                    }
                }
                else
                {
                    if (dr.Table.Columns.Contains(col))
                    {
                        DataHelper.SetDataRowValue(dr, col, data[col]);
                    }
                    else
                    {
                        customData[col] = data[col];
                    }
                }
            }

            dr["CustomProperties"] = customData.GetData();

            form.DataRow = dr;
            form.LoadData(dr);
            form.FormInformation = fi;

            // Master page style for margin
            CurrentMaster.PanelContent.CssClass = "WebpartProperties PageContent";

            form.OnAfterSave += form_OnAfterSave;
        }
        else
        {
            EditedObject = null;
        }
    }
    /// <summary>
    /// Load parameters from data form.
    /// </summary>
    private void LoadParameters()
    {
        if (ReportInfo != null)
        {
            // Set the form
            FormInfo fi = new FormInfo(ReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow(false);
            if (!RequestHelper.IsPostBack() || ForceLoadDefaultValues || !DisplayFilter)
            {
                fi.LoadDefaultValues(dr, true);
            }
            else if ((!ForceLoadDefaultValues) && (formParameters.DataRow != null))
            {
                dr = formParameters.DataRow;
            }

            // Show filter - based on DisplayFilter and number of visible elements
            mDisplayFilterResult = DisplayFilter && (fi.GetFormElements(true, false).Any());

            formParameters.DataRow = dr;
            formParameters.SubmitButton.Visible = mDisplayFilterResult;
            formParameters.SubmitButton.RegisterHeaderAction = false;
            formParameters.FormInformation = fi;
            formParameters.SubmitButton.ResourceString = "report_view.btnupdate";
            formParameters.SiteName = SiteContext.CurrentSiteName;
            formParameters.Mode = FormModeEnum.Insert;
            formParameters.Visible = mDisplayFilterResult;

            wasInit = true;
        }
    }
    /// <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>
    /// Reload data.
    /// </summary>
    public override void ReloadData(bool forceLoad)
    {
        if ((GraphImageWidth != 0) && (ComputedWidth == 0))
        {
            // Graph width is computed no need to create graph
            return;
        }

        this.Visible = true;

        // Indicaates whether exception was throw during data loading
        bool errorOccurred = false;
        ReportInfo ri = null;

        try
        {
            this.ReportTableName = this.Parameter;

            this.EnsureTableInfo();
            this.EnsureChildControls();

            //Test security
            if (TableInfo != null)
            {
                ri = ReportInfoProvider.GetReportInfo(TableInfo.TableReportID);
                if (ri != null)
                {
                    if (ri.ReportAccess != ReportAccessEnum.All)
                    {
                        if (!CMSContext.CurrentUser.IsAuthenticated())
                        {
                            this.Visible = false;
                            return;
                        }
                    }

                    //Set default parametrs directly if not set
                    if (this.ReportParameters == null)
                    {
                        FormInfo fi = new FormInfo(ri.ReportParameters);
                        // Get datarow with required columns
                        this.ReportParameters = fi.GetDataRow();
                        fi.LoadDefaultValues(this.ReportParameters);
                    }

                    ApplyTimeParameters();
                }
            }

            // Only use base parameters in case of stored procedure
            if (this.QueryIsStoredProcedure)
            {
                this.AllParameters = SpecialFunctions.ConvertDataRowToParams(this.ReportParameters, null);
            }

            // Load data
            DataSet ds = this.LoadData();

            // If no data load, set empty dataset
            if (DataHelper.DataSourceIsEmpty(ds))
            {
                string noRecordText = ValidationHelper.GetString(TableInfo.TableSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    GridViewObject.Visible = false;
                    lblInfo.Text = noRecordText;
                    lblInfo.Visible = true;
                    return;
                }

                this.Visible = false;
            }
            else
            {
                GridViewObject.Visible = true;
                // Resolve macros in column names
                int i = 0;
                foreach (DataColumn dc in ds.Tables[0].Columns)
                {
                    if (dc.ColumnName == "Column" + ((int)(i + 1)).ToString())
                    {
                        dc.ColumnName = ResolveMacros(ds.Tables[0].Rows[0][i].ToString());
                    }
                    else
                    {
                        dc.ColumnName = ResolveMacros(dc.ColumnName);
                    }
                    i++;
                }

                // Resolve macros in dataset
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        if (dc.DataType.FullName.ToLower() == "system.string")
                        {
                            dr[dc.ColumnName] = ResolveMacros(ValidationHelper.GetString(dr[dc.ColumnName], ""));
                        }
                    }
                }
            }

            ApplyStyles();

            // Databind to gridview control
            GridViewObject.DataSource = ds;
            this.EnsurePageIndex();
            GridViewObject.DataBind();

            if ((TableFirstColumnWidth != Unit.Empty) && (GridViewObject.Rows.Count > 0))
            {
                GridViewObject.Rows[0].Cells[0].Width = TableFirstColumnWidth;
            }

        }
        catch (Exception ex)
        {
            // Display error message, if data load fail
            lblError.Visible = true;
            lblError.Text = "[ReportTable.ascx] Error loading the data: " + ex.Message;
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Report table", "E", ex);
            errorOccurred = true;
        }

        // Export data
        if ((ri != null) && (!errorOccurred))
        {
            ProcessExport(ValidationHelper.GetCodeName(ri.ReportDisplayName));
        }
    }
Example #46
0
    /// <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)
            {
                ShowError(GetString("general.pagenotfound"));
                pnlExport.Visible = false;
                return;
            }

            // 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

                    // Clone templateInstance to avoid caching of the temporary template instance loaded with CP/MVT variants
                    var tempTemplateInstance = templateInstance.Clone();
                    tempTemplateInstance.LoadVariants(false, VariantModeEnum.None);

                    webPartInstance = tempTemplateInstance.GetWebPart(InstanceGUID, -1);

                    // Set the VariantMode according to the selected web part/zone variant
                    if (webPartInstance?.ParentZone != null)
                    {
                        VariantMode = (webPartInstance.VariantMode != VariantModeEnum.None) ? webPartInstance.VariantMode : webPartInstance.ParentZone.VariantMode;
                    }
                    else
                    {
                        VariantMode = VariantModeEnum.None;
                    }
                }
                else
                {
                    // Ensure that the ZoneVariantID is not set when the web part was found in a regular zone
                    ZoneVariantID = 0;
                }

                if ((VariantID > 0) && 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;
                }
            }

            // Keep xml version
            if (webPartInstance != null)
            {
                xmlVersion = webPartInstance.XMLVersion;
            }

            // Get the form info
            FormInfo fi = GetWebPartFormInfo();

            // Get the form definition
            if (fi != null)
            {
                fi.ContextResolver.Settings.RelatedObject = templateInstance;
                form.AllowMacroEditing = true;

                // Get data row with required columns
                DataRow dr = fi.GetDataRow();

                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)
                {
                    dr["WebPartControlID"] = GetUniqueWebPartId();
                }

                // Init the form
                InitForm(form, dr, fi);

                DisplayExportPropertiesButton();
            }
            else
            {
                UIContext.EditedObject = null;
            }
        }
    }
    /// <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 <IField> items       = fi.ItemsList;

        foreach (IField 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>
    /// Combines widget info with default XML system propertiers.
    /// </summary>
    /// <param name="fi">Widget form info</param>
    /// <param name="wi">Widget info object</param>
    public DataRow CombineWithDefaultValues(FormInfo fi, WidgetInfo wi)
    {
        if ((!String.IsNullOrEmpty(wi.WidgetDefaultValues)) && (String.Compare(wi.WidgetDefaultValues, "<form></form>", false) != 0))
        {
            // Apply changed values
            DataRow dr = fi.GetDataRow();
            fi.LoadDefaultValues(dr, wi.WidgetDefaultValues);

            return dr;
        }

        return fi.GetDataRow();
    }
    /// <summary>
    /// Show preview
    /// </summary>
    private void ShowPreview()
    {
        divPanelHolder.Visible = false;
        pnlVersions.Visible = false;

        if (mReportInfo != null)
        {
            pnlPreview.Visible = true;

            FormInfo fi = new FormInfo(mReportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow defaultValues = fi.GetDataRow(false);

            fi.LoadDefaultValues(defaultValues, true);

            // ReportGraph.ContextParameters
            ctrlReportTable.ReportParameters = defaultValues;

            // Prepare fully qualified graph name = with reportname
            if (mReportTableInfo != null)
            {
                string fullReportGraphName = mReportInfo.ReportName + "." + mReportTableInfo.TableName;
                ctrlReportTable.Parameter = fullReportGraphName;
            }
            ctrlReportTable.TableInfo = mReportTableInfo;

            ctrlReportTable.ReloadData(true);
        }
    }
Example #50
0
    /// <summary>
    /// Returns report graph.
    /// </summary>
    private void GetReportGraph(ReportGraphInfo reportGraph)
    {
        // Check whether report graph is defined
        if (reportGraph == null)
        {
            return;
        }

        report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID);
        //check graph security settings
        if (report.ReportAccess != ReportAccessEnum.All)
        {
            if (!CMSContext.CurrentUser.IsAuthenticated())
            {
                Visible = false;
                return;
            }
        }

        EnableSubscription = (EnableSubscription && ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["SubscriptionEnabled"], true) && report.ReportEnableSubscription);
        if (EmailMode && !EnableSubscription)
        {
            this.Visible = false;
            return;
        }

        //Set default parametrs directly if not set
        if (ReportParameters == null)
        {
            //Load ReportInfo
            if (report != null)
            {
                FormInfo fi = new FormInfo(report.ReportParameters);
                // Get datarow with required columns
                ReportParameters = fi.GetDataRow(false);
                fi.LoadDefaultValues(ReportParameters, true);
            }
        }

        // Only use base parameters in case of stored procedure
        if (QueryIsStoredProcedure)
        {
            AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
        }

        // Indicaates whether exception was throw during data loading
        errorOccurred = false;

        // Create graph data
        try
        {
            ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();
            //Resolve parameters in query
            resolver.SourceParameters = AllParameters.ToArray();

            // Resolve dynamic data macros
            if (DynamicMacros != null)
            {
                for (int i = 0; i <= DynamicMacros.GetUpperBound(0); i++)
                {
                    resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                }
            }

            //Prepare query attributes
            QueryText = resolver.ResolveMacros(reportGraph.GraphQuery);
            QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure;

            // Load data
            DataSource = LoadData();

            if (DataHelper.DataSourceIsEmpty(DataSource) && EmailMode && SendOnlyNonEmptyDataSource)
            {
                Visible = false;
                return;
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Get report graph", "E", ex);
            lblError.Text    = ex.Message;
            lblError.Visible = true;
            errorOccurred    = true;
        }
    }
    /// <summary>
    /// Show preview.
    /// </summary>
    private void ShowPreview()
    {
        if (reportInfo != null)
        {
            pnlPreview.Visible = true;
            divPanelHolder.Visible = false;
            categoryList.Visible = false;
            pnlVersions.Visible = false;

            FormInfo fi = new FormInfo(reportInfo.ReportParameters);
            // Get datarow with required columns
            DataRow dr = fi.GetDataRow();

            fi.LoadDefaultValues(dr);

            //reportGraph.ContextParameters
            ctrlReportValue.ReportParameters = dr;

            ctrlReportValue.Visible = true;
            ctrlReportValue.ValueInfo = valueInfo;

            ctrlReportValue.ReloadData(true);
        }
    }
Example #52
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Test permission for query
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.Reporting", "EditSQLQueries"))
        {
            txtQuery.Enabled = false;
        }
        else
        {
            txtQuery.Enabled = true;
        }

        versionList.OnAfterRollback += new EventHandler(versionList_onAfterRollback);

        // Own javascript tab change handling -> because tab control raises changetab after prerender - too late
        // Own selected tab change handling
        RegisterTabScript(hdnSelectedTab.ClientID, tabControlElem);

        // Register common resize and refresh scripts
        RegisterResizeAndRollbackScript(divFooter.ClientID, divScrolable.ClientID);

        string[,] tabs = new string[4, 4];
        tabs[0, 0]     = GetString("general.general");
        tabs[0, 1]     = "SetHelpTopic('helpTopic', 'report_table_properties')";
        tabs[1, 0]     = GetString("general.preview");
        tabs[0, 1]     = "SetHelpTopic('helpTopic', 'report_table_properties')";

        tabControlElem.Tabs               = tabs;
        tabControlElem.UsePostback        = true;
        CurrentMaster.Title.HelpName      = "helpTopic";
        CurrentMaster.Title.HelpTopicName = "report_table_properties";
        CurrentMaster.Title.TitleCssClass = "PageTitleHeader";

        rfvCodeName.ErrorMessage    = GetString("general.requirescodename");
        rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname");
        btnApply.Text  = GetString("General.apply");
        btnOk.Text     = GetString("General.OK");
        btnCancel.Text = GetString("General.Cancel");

        int  reportId = QueryHelper.GetInteger("reportid", 0);
        bool preview  = QueryHelper.GetBoolean("preview", false);

        if (reportId > 0)
        {
            reportInfo = ReportInfoProvider.GetReportInfo(reportId);
        }

        // If preview by URL -> select preview tab
        bool isPreview = QueryHelper.GetBoolean("preview", false);

        if (isPreview && !RequestHelper.IsPostBack())
        {
            SelectedTab = 1;
        }

        if (PersistentEditedObject == null)
        {
            if (reportInfo != null) // Must be valid reportid parameter
            {
                string tableName = ValidationHelper.GetString(Request.QueryString["itemname"], "");

                // Try to load tableName from hidden field (adding new graph & preview)
                if (tableName == String.Empty)
                {
                    tableName = txtNewTableHidden.Value;
                }

                if (ValidationHelper.IsIdentifier(tableName))
                {
                    PersistentEditedObject = ReportTableInfoProvider.GetReportTableInfo(reportInfo.ReportName + "." + tableName);
                    tableInfo = PersistentEditedObject as ReportTableInfo;
                }
            }
        }
        else
        {
            tableInfo = PersistentEditedObject as ReportTableInfo;
        }

        if (reportInfo != null)
        {
            // Control text initializations
            if (tableInfo != null)
            {
                CurrentMaster.Title.TitleText  = GetString("Reporting_ReportTable_Edit.TitleText");
                CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Reporting_ReportTable/object.png");

                tableId = tableInfo.TableID;

                if (ObjectVersionManager.DisplayVersionsTab(tableInfo))
                {
                    tabs[2, 0] = GetString("objectversioning.tabtitle");
                    tabs[2, 1] = "SetHelpTopic('helpTopic', 'objectversioning_general');";

                    versionList.Object     = tableInfo;
                    versionList.IsLiveSite = false;
                }
            }
            else // New item
            {
                CurrentMaster.Title.TitleText  = GetString("Reporting_ReportTable_Edit.NewItemTitleText");
                CurrentMaster.Title.TitleImage = GetImageUrl("Objects/Reporting_ReportTable/new.png");

                if (!RequestHelper.IsPostBack())
                {
                    txtPageSize.Text          = "15";
                    txtQueryNoRecordText.Text = GetString("attachmentswebpart.nodatafound");
                    chkExportEnable.Checked   = true;
                }

                newTable = true;
            }

            // Set help key
            CurrentMaster.Title.HelpTopicName = "report_table_properties";

            if (!RequestHelper.IsPostBack())
            {
                DataHelper.FillListControlWithEnum(typeof(PagerButtons), drpPageMode, "PagerButtons.", null);
                // Preselect page numbers paging
                drpPageMode.SelectedValue = ((int)PagerButtons.Numeric).ToString();

                LoadData();
            }
        }

        if ((preview) && (!RequestHelper.IsPostBack()))
        {
            tabControlElem.SelectedTab = 1;
            ShowPreview();
        }

        // In case of preview paging without saving table
        if (RequestHelper.IsPostBack() && tabControlElem.SelectedTab == 1)
        {
            // Reload deafult parameters
            FormInfo fi = new FormInfo(reportInfo.ReportParameters);
            // Get datarow with required columns
            ctrlReportTable.ReportParameters = fi.GetDataRow();
            fi.LoadDefaultValues(ctrlReportTable.ReportParameters, true);

            // Colect data and put them in talbe info
            Save(false);
            ctrlReportTable.TableInfo = tableInfo;
        }
    }
    /// <summary>
    /// Returns report graph.
    /// </summary>
    private void GetReportGraph(ReportGraphInfo reportGraph)
    {
        Visible = true;
        ucChart.Visible = true;

        int correctWidth = 0;
        if (ComputedWidth != 0)
        {
            correctWidth = ModifyGraphInfo();
        }

        if (Width != String.Empty)
        {
            int graphWidth = ValidationHelper.GetInteger(Width, 0);
            if (graphWidth != 0)
            {
                reportGraph.GraphWidth = graphWidth;
            }
        }

        if (Height != 0)
        {
            reportGraph.GraphHeight = Height;
        }

        ReportGraph graph = new ReportGraph();
        graph.ChartControl = ucChart;

        ReportInfo report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID);
        if (report == null)
        {
            return;
        }

        // Check graph security settings
        if (report.ReportAccess != ReportAccessEnum.All)
        {
            if (!CMSContext.CurrentUser.IsAuthenticated())
            {
                Visible = false;
                return;
            }
        }

        // Set default parametrs directly if not set
        if (ReportParameters == null)
        {
            // Load ReportInfo
            if (report != null)
            {
                FormInfo fi = new FormInfo(report.ReportParameters);
                // Get datarow with required columns
                ReportParameters = fi.GetDataRow();
                fi.LoadDefaultValues(ReportParameters);
            }
        }

        // If used via widget - this function ensure showing specific interval from actual time (f.e. last 6 weeks)
        ApplyTimeParameters();

        // Only use base parameters in case of stored procedure
        if (QueryIsStoredProcedure)
        {
            AllParameters = SpecialFunctions.ConvertDataRowToParams(ReportParameters, null);
        }

        ContextResolver resolver = CMSContext.CurrentResolver.CreateContextChild();

        // Indicaates whether exception was throw during data loading
        bool errorOccurred = false;

        // Create graph image
        try
        {
            // Resolve parameters in query
            resolver.SourceParameters = AllParameters.ToArray();

            // Resolve dynamic data macros
            if (DynamicMacros != null)
            {
                for (int i = 0; i <= DynamicMacros.GetUpperBound(0); i++)
                {
                    resolver.AddDynamicParameter(DynamicMacros[i, 0], DynamicMacros[i, 1]);
                }
            }

            // Prepare query attributes
            QueryText = resolver.ResolveMacros(reportGraph.GraphQuery);
            QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure;

            // LoadData
            DataSet dsGraphData = LoadData();

            // Test if dataset is empty
            if (DataHelper.DataSourceIsEmpty(dsGraphData))
            {
                string noRecordText = ValidationHelper.GetString(reportGraph.GraphSettings["QueryNoRecordText"], String.Empty);
                if (noRecordText != String.Empty)
                {
                    lblInfo.Text = noRecordText;
                    lblInfo.Visible = true;
                    ucChart.Visible = false;
                    menuCont.MenuID = String.Empty;
                    return;
                }
                Visible = false;
            }
            else
            {
                // Create Chart
                graph.CorrectWidth = correctWidth;
                graph.CreateChart(reportGraph, dsGraphData, resolver);
            }
        }
        catch (Exception ex)
        {
            EventLogProvider ev = new EventLogProvider();
            ev.LogEvent("Get report graph", "E", ex);
            graph.CorrectWidth = correctWidth;
            graph.CreateInvalidDataGraph(reportGraph, "Reporting.Graph.InvalidDataGraph", false);
            errorOccurred = true;
        }

        // Export data
        if ((report != null) && (!errorOccurred))
        {
            ProcessExport(ValidationHelper.GetCodeName(report.ReportDisplayName));
        }
    }