using System; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using CMS.CMSHelper; using CMS.DataEngine; using CMS.EventLog; using CMS.FormEngine; using CMS.GlobalHelper; using CMS.Reporting; using CMS.WebAnalytics; using CMS.EmailEngine; public partial class CMSModules_Reporting_Controls_HtmlBarGraph : AbstractReportControl { #region "Variables" private ReportGraphInfo mReportGraphInfo; private string mParameter = String.Empty; private ContextResolver itemResolver = null; private ReportCustomData reportSettings = null; private ReportInfo report = null; /// /// Indicates whether exception was thrown during data loading /// private bool errorOccurred = false; #endregion #region "Properties" /// /// Gets or sets the graph datasource. /// public DataSet DataSource { get; set; } /// /// Report HTML graph connection string. /// public override string ConnectionString { get { String graphConn = (ReportGraphInfo == null) ? String.Empty : ReportGraphInfo.GraphConnectionString; if (String.IsNullOrEmpty(graphConn)) { return (report == null) ? String.Empty : report.ReportConnectionString; } return graphConn; } } /// /// Returns graph info from DB or from memory. /// public ReportGraphInfo ReportGraphInfo { get { // If graph info is not set already if (mReportGraphInfo == null) { mReportGraphInfo = ReportGraphInfoProvider.GetReportGraphInfo(Parameter); } return mReportGraphInfo; } set { mReportGraphInfo = value; } } /// /// Graph name - prevent using viewstate (problems with displayreportcontrol and postback). /// public override string Parameter { get { return mParameter; } set { mParameter = value; } } /// /// Gets the graph settings for current report, if report is not defined returns an empty object. /// private ReportCustomData ReportSettings { get { // If graph info is defined, return graph settings if (ReportGraphInfo != null) { return ReportGraphInfo.GraphSettings; } // Create empty object if (reportSettings == null) { reportSettings = new ReportCustomData(); } return reportSettings; } } #endregion #region "Methods" /// /// Ensures graph HTML code. /// protected void EnsureGraph() { ItemType = ReportItemType.HtmlGraph; // Get html graph content string content = Generate(); // If graph is not defined display info message if (String.IsNullOrEmpty(content)) { // Check whether no data text is defiend if (!String.IsNullOrEmpty(ReportSettings["QueryNoRecordText"])) { // Display no data text plcInfo.Visible = true; lblInfo.Text = HTMLHelper.HTMLEncode(CMSContext.ResolveMacros(ReportSettings["QueryNoRecordText"])); EnableExport = false; } } // Display graph else { // Set generated HTML to the literal control ltlGraph.Text = content; } if (EmailMode) { menuCont.Visible = false; ltlEmail.Text = content; ltlEmail.Visible = true; } } /// /// Reloads data. /// /// Indicates whether data should be loaded forcibly public override void ReloadData(bool forceLoad) { base.ReloadData(forceLoad); if ((GraphImageWidth != 0) && (ComputedWidth == 0)) { // Graph width is computed no need to create graph return; } GetReportGraph(ReportGraphInfo); EnsureGraph(); } protected override void OnPreRender(EventArgs e) { imgInfo.ImageUrl = GetImageUrl("/Objects/Reporting_ReportGraph/object.png"); if (report != null) { if (ReportGraphInfo != null) { EnableSubscription = (EnableSubscription && ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["SubscriptionEnabled"], true) && report.ReportEnableSubscription); EnableExport = (EnableExport && ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["ExportEnabled"], false)); // Register context menu for export and subscription - if allowed RegisterSubscriptionScript(ReportGraphInfo.GraphReportID, "graphid", ReportGraphInfo.GraphID, menuCont); } // Export data if (!errorOccurred) { ProcessExport(ValidationHelper.GetCodeName(report.ReportDisplayName)); } } base.OnPreRender(e); } /// /// Returns report graph. /// private void GetReportGraph(ReportGraphInfo reportGraph) { // Check whether report graph is defined if (reportGraph == null) { return; } report = ReportInfoProvider.GetReportInfo(reportGraph.GraphReportID); if (report == null) { return; } // Check graph security settings if (!(CheckReportAccess(report) && CheckEmailModeSubscription(report, ValidationHelper.GetBoolean(ReportGraphInfo.GraphSettings["SubscriptionEnabled"], true)))) { 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 QueryIsStoredProcedure = reportGraph.GraphQueryIsStoredProcedure; 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); // 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; } } /// /// Returns true if graph belongs to report. /// /// Report to validate public override bool IsValid(ReportInfo report) { ReportGraphInfo rgi = ReportGraphInfo; // Test validity if ((report != null) && (rgi != null) && (report.ReportID == rgi.GraphReportID)) { return true; } return false; } /// /// Generates graph html code. /// public string Generate() { // Check whether dataset contains at least one row if (DataHelper.DataSourceIsEmpty(DataSource)) { if (EmailMode && SendOnlyNonEmptyDataSource) { Visible = false; return String.Empty; } return String.Empty; } // Do not generate graph for email and plain text if (EmailMode) { EmailFormatEnum format = EmailHelper.GetEmailFormat(ReportSubscriptionSiteID); if (format == EmailFormatEnum.PlainText) { return GetString("subscription.htmlnotsupportedforplain"); } } #region "max & sum computing" // Find max value and sum from current dataset double max = 0.0; double sum = 0.0; // Loop thru all data rows foreach (DataRow dr in DataSource.Tables[0].Rows) { // Loop thru all columns foreach (DataColumn dc in DataSource.Tables[0].Columns) { // Skip first column with data name if (dc.Ordinal > 0) { // Get column value double value = ValidationHelper.GetDouble(dr[dc.ColumnName], 0.0); sum += value; // Set max value from current value if is higher than current max value if (max < value) { max = value; } } } } #endregion // Initialize string builder StringBuilder sb = new StringBuilder(1024); sb.AppendLine(""); bool displayLegend = ValidationHelper.GetBoolean(ReportSettings["DisplayLegend"], false); bool headerDisplayed = !String.IsNullOrEmpty(ReportGraphInfo.GraphTitle) || displayLegend; #region "Legend/Title row" if (headerDisplayed) { sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); } #endregion string rowClass = "ReportBarGraphNameCellFirst"; string itemValueFormat = ReportSettings["ItemValueFormat"]; // Loop thru all data rows for (int i = DataSource.Tables[0].Rows.Count - 1; i >= 0; i--) { // Get current datarow DataRow dr = DataSource.Tables[0].Rows[i]; sb.AppendLine(""); // Loop thru all columns in current dataset foreach (DataColumn dc in DataSource.Tables[0].Columns) { // Generate data name cell if (dc.Ordinal == 0) { sb.AppendLine(""); } else { // Generate open cell tag if (dc.Ordinal == 1) { sb.AppendLine(""); sb.AppendLine(""); // Clear first row class rowClass = String.Empty; } sb.AppendLine("
"); if (EmailMode) { sb.AppendLine(""); string legendText = HTMLHelper.HTMLEncode(ReportSettings["LegendTitle"]); if (!String.IsNullOrEmpty(legendText)) { legendText += ":"; sb.AppendLine(""); } // Loop thru all columns in reverse order due to similarity with graph representation for (int i = DataSource.Tables[0].Columns.Count - 1; i > 0; i--) { DataColumn dc = DataSource.Tables[0].Columns[i]; string backColorClass = GetColorClass(i); sb.AppendLine(""); } sb.AppendLine("
"); sb.AppendLine("
" + HTMLHelper.HTMLEncode(CMSContext.CurrentResolver.ResolveMacros(ReportGraphInfo.GraphTitle)) + "
" + legendText + "
"); sb.AppendLine("
   
"); sb.AppendLine(HTMLHelper.HTMLEncode(dc.ColumnName)); sb.AppendLine("  
"); } else { // Graph title sb.AppendLine("
" + HTMLHelper.HTMLEncode(CMSContext.CurrentResolver.ResolveMacros(ReportGraphInfo.GraphTitle)) + "
"); // Check whether legend should be displayed if (displayLegend) { // Loop thru all columns in reverse order due to similarity with graph representation for (int i = DataSource.Tables[0].Columns.Count - 1; i > 0; i--) { DataColumn dc = DataSource.Tables[0].Columns[i]; string backColorClass = GetColorClass(i); sb.AppendLine("
"); sb.AppendLine("
 
"); sb.AppendLine(HTMLHelper.HTMLEncode(dc.ColumnName)); sb.AppendLine("
"); } string legendText = HTMLHelper.HTMLEncode(ReportSettings["LegendTitle"]); if (!String.IsNullOrEmpty(legendText)) { legendText += ":"; } sb.AppendLine("
" + legendText + "
"); } } sb.AppendLine("
"); // Get column name string name = dr[dc.ColumnName].ToString(); // Get string format = ReportSettings["SeriesItemNameFormat"]; #region "Item name formating" // Check whether format is defined if (!String.IsNullOrEmpty(format)) { // Convert to specific type if (ValidationHelper.IsDateTime(name)) { DateTime dt = ValidationHelper.GetDateTime(name, DateTimeHelper.ZERO_TIME); name = dt.ToString(format); } else { name = String.Format(name, format); ; } } #endregion // Name value sb.AppendLine(HTMLHelper.HTMLEncode(name)); sb.AppendLine(""); } // Generate cell data divider else { sb.AppendLine("
"); } // Default width type string widthType = "%"; // Default width value double widthValue = 0.0; // Current value double currentValue = ValidationHelper.GetDouble(dr[dc.ColumnName], 0.0); // If current value is defined compute reltive width if (currentValue > 0.0) { // Relative width widthValue = (currentValue / max) * 80; // If value is defined but relative width is lower than 1, generate simple line if (widthValue < 1) { widthValue = 1; widthType = "px"; } // Get background color for current column string backColorClass = GetColorClass(dc.Ordinal); // Item link string itemLink = ReportSettings["SeriesItemLink"]; // Item tooltip string itemToolTip = ReportSettings["SeriesItemToolTip"]; if (!EmailMode) { if (!String.IsNullOrEmpty(itemLink)) { sb.AppendLine(""); } if (!String.IsNullOrEmpty(itemToolTip)) { itemToolTip = " title=\"" + ResolveCustomMacros(itemToolTip.Replace("\"", String.Empty), dr, dc.ColumnName, sum) + "\""; } //
- bar sb.AppendLine(@"
 
"); // Check whether item value should be displayed if (!String.IsNullOrEmpty(itemValueFormat)) { string itemValue = ResolveCustomMacros(itemValueFormat, dr, dc.ColumnName, sum); //
- item value sb.AppendLine(@"
" + itemValue + "
"); } if (!String.IsNullOrEmpty(itemLink)) { sb.AppendLine("
"); } } else { sb.AppendLine(@""); // Check whether item value should be displayed if (!String.IsNullOrEmpty(itemValueFormat)) { string itemValue = ResolveCustomMacros(itemValueFormat, dr, dc.ColumnName, sum); sb.AppendLine(""); } sb.AppendLine("
" + itemValue + "
"); } } else { sb.AppendLine(@"
 
"); } } } sb.AppendLine("
"); return sb.ToString(); } /// /// Resolve custom macros for specified input value. /// /// Value to resolve /// Current data row /// Column name /// Summary of all items private string ResolveCustomMacros(string value, DataRow dr, string columnName, double sum) { // Ensure resolver if (itemResolver == null) { itemResolver = CMSContext.CurrentResolver.CreateContextChild(); } // Get current item value double itemvalue = ValidationHelper.GetDouble(dr[columnName], 0.0); // Custom macros definition string[,] macros = new string[4, 2]; macros[0, 0] = "xval"; macros[0, 1] = Convert.ToString(dr[0]); macros[1, 0] = "yval"; macros[1, 1] = Convert.ToString(itemvalue); macros[2, 0] = "ser"; macros[2, 1] = columnName; macros[3, 0] = "pval"; macros[3, 1] = Convert.ToString(itemvalue / sum * 100); // Set custom macros itemResolver.SourceParameters = macros; // Resolve macros return itemResolver.ResolveMacros(value); } /// /// Returns html color value for specific position. /// /// Column position private string GetColorClass(int position) { String css = EmailMode ? String.Empty : "ReportBarGraphItem "; return css + "ReportBarGraphItem" + position; } #endregion }