private void TestLocalReportParameters(LocalReport expected, LocalReport actual) { ReportParameterInfoCollection collection = actual.GetParameters(); IEnumerator <ReportParameterInfo> expectedEnum = expected.GetParameters().GetEnumerator(); IEnumerator <ReportParameterInfo> actualEnum = actual.GetParameters().GetEnumerator(); while (expectedEnum.MoveNext() && actualEnum.MoveNext()) { Assert.AreEqual(expectedEnum.Current.Name, actualEnum.Current.Name); Assert.AreEqual(expectedEnum.Current.Visible, actualEnum.Current.Visible); Assert.IsTrue(expectedEnum.Current.Values.SequenceEqual(actualEnum.Current.Values)); } }
/// <summary> /// Load a detailed diskspace report. /// </summary> /// <param name="reportName">Name of detailed diskspace report.</param> /// <param name="localReport"> /// Instance or <see cref="LocalReport"/> class. /// This instance serves as a container for report being loaded. /// </param> protected void BindHostingSpaceDiskspaceOverusageDetailsReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters // Note: here we are always in Drill-through mode. localReport.SetParameters(localReport.OriginalParametersToDrillthrough); string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0]; // 3. Update DataSet DataSet report = ES.Services.Packages .GetDiskspaceOverusageDetailsReport( PanelSecurity.SelectedUserId , int.Parse(hostingSpaceId) ); localReport.DataSources.Clear(); TranslateStatusField(report.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_HostingSpace", report.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_DiskspaceOverusage", report.Tables["DiskspaceOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", report.Tables["OverusageDetails"]); localReport.Refresh(); }
private void frmReportViewer_Load(object sender, EventArgs e) { if (_Report == null) { this.reportViewer1.LocalReport.ReportPath = sReportPath; //sReportPath; this.reportViewer1.LocalReport.SetParameters(new ReportParameter("Encabezado1", Parametros.ParametrosSucursal.EncabezadoFactura1)); this.reportViewer1.LocalReport.SetParameters(new ReportParameter("Encabezado2", Parametros.ParametrosSucursal.EncabezadoFactura2)); this.reportViewer1.LocalReport.SetParameters(new ReportParameter("Encabezado3", Parametros.ParametrosSucursal.EncabezadoFactura3)); if (sTitulo != "") { this.reportViewer1.LocalReport.SetParameters(new ReportParameter("Titulo", sTitulo)); } this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", dt)); this.reportViewer1.LocalReport.Refresh(); this.reportViewer1.RefreshReport(); this.reportViewer1.RefreshReport(); } else { //**************************** //assign report Path reportViewer1.LocalReport.ReportPath = _Report.ReportPath; //**************************** //**************************** //assign data-sources foreach (ReportDataSource MyDS in _Report.DataSources) { reportViewer1.LocalReport.DataSources.Add(MyDS); } //**************************** //**************************** //Assign parameters //get a list of actual parameters in the report, with the actual assigned value ReportParameterInfoCollection MyOrigParams = _Report.GetParameters(); //I didn't find simpler way to fetch params... //create a List of parameter [to feed the reportViewer] List <ReportParameter> MyListOfPArams = new List <ReportParameter>(); //for each params found through GetParameters(), add it to the List<> of params for (int i = 0; i < MyOrigParams.Count; i++) { MyListOfPArams.Add(new ReportParameter(MyOrigParams[i].Name, MyOrigParams[i].Values[0])); } //final assignation of the parameters reportViewer1.LocalReport.SetParameters(MyListOfPArams); //**************************** //show the report reportViewer1.RefreshReport(); } }
private void CompareLocalReport(LocalReport expected, LocalReport current) { Assert.AreEqual(expected.ReportPath, current.ReportPath); TestParameters(expected.GetParameters().ToList(), current.GetParameters().ToList()); TestDataSource(expected.DataSources.ToList(), current.DataSources.ToList()); }
private void RenderAllLocalReportPages(LocalReport localReport) { string deviceInfo = CreateEMFDeviceInfo(); ReportParameterInfoCollection rpc = (ReportParameterInfoCollection)localReport.GetParameters(); localReport.Render("IMAGE", deviceInfo, LocalReportCreateStreamCallback, out Warning[] warnings); }
/// <summary> /// Caso algum parâmetro esteja com valor vazio, preenche com ".". /// Caso tenha sido atribuído algum parâmetro que não exista no relatório, remove antes de renderizá-lo. /// Verifica também se faltou ser definido algum parâmetro no relatório, neste caso, lança exceção com o parâmetro que faltou. /// </summary> /// <param name="caminhoRelatorio"></param> /// <param name="lstParam"></param> private void VerificarParametros(LocalReport report, ref List <ReportParameter> lstParam) { // Pega os parâmetros do rdlc var parametrosRdlc = report.GetParameters(); if (parametrosRdlc == null) { report.Refresh(); parametrosRdlc = report.GetParameters(); if (parametrosRdlc == null) { return; } return; } // Caso tenha sido definido algum parâmetro a mais, remove da lista de parâmetros for (int i = 0; i < lstParam.Count; i++) { if (!parametrosRdlc.Select(f => f.Name.ToLower()).Contains(lstParam[i].Name.ToLower())) { lstParam.Remove(lstParam[i]); i--; } } // Caso tenha faltado definir algum parâmetro, avisa o usuário var parametrosNaoDefinidos = new List <string>(); foreach (var pRdlc in parametrosRdlc) { if (!lstParam.Select(f => f.Name.ToLower()).Contains(pRdlc.Name.ToLower())) { parametrosNaoDefinidos.Add(pRdlc.Name); } } if (parametrosNaoDefinidos.Count > 0) { throw new Exception(string.Format("Parâmetro{0} não definido{0}: {1}", parametrosNaoDefinidos.Count == 1 ? string.Empty : "s", string.Join(", ", parametrosNaoDefinidos))); } }
public static string GetReportParameter(LocalReport report, string paramname) { foreach (ReportParameterInfo param in report.GetParameters()) { if (0 == string.Compare(paramname, param.Name, true, CultureInfo.InvariantCulture)) { return(param.Values[0]); } } return(null); }
protected void BindHostingSpaceBandwidthOverusageDetailsReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters // Note: here we are always in Drill-through mode. localReport.SetParameters(localReport.OriginalParametersToDrillthrough); string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0]; List <ReportParameter> parameters = new List <ReportParameter>(); parameters.Add( new ReportParameter( ParameterBandwidthStartDate , startDateCalendar.SelectedDate.ToString() ) ); parameters.Add( new ReportParameter( ParameterBandwidthEndDate , endDateCalendar.SelectedDate.ToString() ) ); localReport.SetParameters(parameters); //3. Update data DataSet ds = ES.Services.Packages .GetBandwidthOverusageDetailsReport( PanelSecurity.SelectedUserId , int.Parse(hostingSpaceId) , startDateCalendar.SelectedDate , endDateCalendar.SelectedDate ); localReport.DataSources.Clear(); TranslateStatusField(ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_HostingSpace", ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_BandwidthOverusage", ds.Tables["BandwidthOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", ds.Tables["OverusageDetails"]); localReport.Refresh(); }
/// <summary> /// Copy the properties of the specified LocalReport to the LocalReport. /// </summary> /// <param name="localReport">The LocalReport that this method extends.</param> /// <param name="properties">The LocalReport whose properties should be copied to the LocalReport.</param> public static void SetProperties(this LocalReport localReport, LocalReport properties) { if (localReport == null) { throw new ArgumentNullException("localReport", "Value cannot be null."); } CopyPropertiesHelper.Copy <LocalReport>(ref localReport, properties); localReport.DataSources.Add(properties.DataSources.ToList()); try { localReport.SetParameters(properties.GetParameters()); } catch (MissingReportSourceException) { } //Do nothing }
private void rptView_Drillthrough(object sender, DrillthroughEventArgs e) { try { LocalReport DetailReport = (LocalReport)e.Report; MICS.Reports.PurchasedProducts.SalesDetailDataTable r = new PurchasedProducts.SalesDetailDataTable(); MICS.Reports.PurchasedProductsTableAdapters.SalesDetailsTableAdapter ad = new MICS.Reports.PurchasedProductsTableAdapters.SalesDetailsTableAdapter(); ad.SetTimeOut = 120; ReportParameterInfoCollection p = DetailReport.GetParameters(); string name = p[0].Name; string ParamValue = p[0].Values[0]; ad.FillByWhere(this.PurchasedProducts.SalesDetail, ParamValue); DetailReport.DataSources.Add(new ReportDataSource("PurchasedProducts_SalesDetail", ad.GetData())); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void FillData(NameValueCollection parameters) { foreach (var dsName in _localReport.GetDataSourceNames()) { _localReport.DataSources.Add(GetDataSource(dsName, parameters)); } List <ReportParameter> prms = new List <ReportParameter>(); foreach (var pi in _localReport.GetParameters()) { var key = parameters.AllKeys.FirstOrDefault(p => p.ToLower() == pi.Name.ToLower()); string[] value = null; if (!string.IsNullOrEmpty(key)) { value = parameters.GetValues(key) ?? new string[] { "" }; prms.Add(new ReportParameter(pi.Name, value)); } } _localReport.SetParameters(prms); }
/// <summary> /// Copy the properties of the specified LocalReport to the LocalReport. /// </summary> /// <param name="localReport">The LocalReport that this method extends.</param> /// <param name="properties">The LocalReport whose properties should be copied to the LocalReport.</param> public static void SetProperties(this LocalReport localReport, LocalReport properties) { if (localReport == null) { throw new ArgumentNullException("localReport", "Value cannot be null."); } CopyPropertiesHelper.Copy <LocalReport>(ref localReport, properties); localReport.DataSources.Add(properties.DataSources.ToList()); try { localReport.SetParameters(properties.GetParameters()); } catch (Exception ex) { string msg = ex.Message.ToString(); } }
protected override ReportData Render(PageRequest request, DataTable table, string reportTemplate, string reportFormat) { HttpContext context = HttpContext.Current; string q = context.Request["q"]; // render a report using Microsoft Report Viewer string mimeType = null; string encoding = null; string fileNameExtension = null; string[] streams = null; Warning[] warnings = null; byte[] data = null; using (LocalReport report = new LocalReport()) { report.EnableHyperlinks = true; report.EnableExternalImages = true; report.LoadReportDefinition(new StringReader(reportTemplate)); report.DataSources.Add(new ReportDataSource(request.Controller, table)); report.EnableExternalImages = true; foreach (ReportParameterInfo p in report.GetParameters()) { if (p.Name.Equals("FilterDetails") && !(String.IsNullOrEmpty(request.FilterDetails))) { report.SetParameters(new ReportParameter("FilterDetails", request.FilterDetails)); } if (p.Name.Equals("BaseUrl")) { string baseUrl = String.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, context.Request.ApplicationPath.TrimEnd('/')); report.SetParameters(new ReportParameter("BaseUrl", baseUrl)); } if (p.Name.Equals("Query") && !(String.IsNullOrEmpty(q))) { report.SetParameters(new ReportParameter("Query", HttpUtility.UrlEncode(q))); } } report.SetBasePermissionsForSandboxAppDomain(new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted)); data = report.Render(reportFormat, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); } return(new ReportData(data, mimeType, fileNameExtension, encoding)); }
/// <summary> /// Handles the Drillthrough event of the RptViewer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Microsoft.Reporting.WebForms.DrillthroughEventArgs"/> instance containing the event data.</param> private void RptViewer_Drillthrough(object sender, DrillthroughEventArgs e) { LocalReport lr = (LocalReport)e.Report; string photo = lr.GetParameters()["Photo"].Values[0].ToString(); //2014.02.17 paulus: 直接用 Photo as image Uri //string imageFolder = VWGContext.Current.Config.GetDirectory("RTImages"); //string imagePath = Path.Combine(Path.Combine(imageFolder, "Product"), photo); string imagePath = photo; ViewImage viewImage = new ViewImage(); viewImage.ImageName = imagePath; viewImage.ShowDialog(); e.Cancel = true; //LocalReport lr = (LocalReport)e.Report; //lr.DataSources.Clear(); //lr.DataSources.Add(new ReportDataSource(reportDatasourceName, dataSource)); }
/// <summary> /// Find Parameter. /// </summary> /// <param name="localReport">The local report instance.</param> /// <param name="name">The parameter's name.</param> /// <returns>Returns instance of ReportParameterInfo if found.</returns> private static ReportParameterInfo FindParameter(this LocalReport localReport, string name) { ReportParameterInfo result = null; if (null == localReport) { return(result); } ReportParameterInfoCollection parameters = localReport.GetParameters(); if (null != parameters && parameters.Count > 0) { result = parameters.FirstOrDefault( (ReportParameterInfo para) => { return(string.Compare(para.Name, name, true) == 0); }); } return(result); }
void IHttpHandler.ProcessRequest(HttpContext context) { string c = context.Request["c"]; string q = context.Request["q"]; PageRequest request = this.Request; if ((request == null) && (String.IsNullOrEmpty(c) || String.IsNullOrEmpty(q))) throw new Exception("Invalid report request."); // #pragma warning disable 0618 System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); // #pragma warning restore 0618 // create a data table for report string templateName = null; string aa = null; string reportFormat = null; if (request == null) { request = serializer.Deserialize<PageRequest>(q); templateName = context.Request.Form["a"]; aa = context.Request["aa"]; } else { templateName = this.Arguments.TemplateName; reportFormat = this.Arguments.Format; request.FilterDetails = this.Arguments.FilterDetails; } request.PageIndex = 0; request.PageSize = Int32.MaxValue; request.RequiresMetaData = true; // try to generate a report via a business rule ActionArgs args = null; if (!(String.IsNullOrEmpty(aa))) { args = serializer.Deserialize<ActionArgs>(aa); IDataController controller = ControllerFactory.CreateDataController(); ActionResult result = controller.Execute(args.Controller, args.View, args); if (!(String.IsNullOrEmpty(result.NavigateUrl))) { AppendDownloadTokenCookie(); context.Response.Redirect(result.NavigateUrl); } if (result.Canceled) { AppendDownloadTokenCookie(); return; } result.RaiseExceptionIfErrors(); // parse action data SortedDictionary<string, string> actionData = new SortedDictionary<string, string>(); ((DataControllerBase)(controller)).Config.ParseActionData(args.Path, actionData); List<string> filter = new List<string>(); foreach (string name in actionData.Keys) { string v = actionData[name]; if (name.StartsWith("_")) { if (name == "_controller") request.Controller = v; if (name == "_view") request.View = v; if (name == "_sortExpression") request.SortExpression = v; if (name == "_count") request.PageSize = Convert.ToInt32(v); if (name == "_template") templateName = v; } else if (v == "@Arguments_SelectedValues") if ((args.SelectedValues != null) && (args.SelectedValues.Length > 0)) { StringBuilder sb = new StringBuilder(); foreach (string key in args.SelectedValues) { if (sb.Length > 0) sb.Append("$or$"); sb.Append(key); } filter.Add(String.Format("{0}:$in${1}", name, sb.ToString())); } else return; else if (Regex.IsMatch(v, "^(\'|\").+(\'|\")$")) filter.Add(String.Format("{0}:={1}", name, v.Substring(1, (v.Length - 2)))); else if (args.Values != null) foreach (FieldValue fv in args.Values) if (fv.Name == v) filter.Add(String.Format("{0}:={1}", name, fv.Value)); request.Filter = filter.ToArray(); } } // load report definition string reportTemplate = Controller.CreateReportInstance(null, templateName, request.Controller, request.View); ViewPage page = ControllerFactory.CreateDataController().GetPage(request.Controller, request.View, request); DataTable table = page.ToDataTable(); // insert validation key reportTemplate = _validationKeyRegex.Replace(reportTemplate, String.Format("/Blob.ashx?_validationKey={0}&", BlobAdapter.ValidationKey)); // figure report output format if (this.Arguments == null) { Match m = Regex.Match(c, "^(ReportAs|Report)(Pdf|Excel|Image|Word|)$"); reportFormat = m.Groups[2].Value; } if (String.IsNullOrEmpty(reportFormat)) reportFormat = "Pdf"; // render a report string mimeType = null; string encoding = null; string fileNameExtension = null; string[] streams = null; Warning[] warnings = null; using (LocalReport report = new LocalReport()) { report.EnableHyperlinks = true; report.EnableExternalImages = true; report.LoadReportDefinition(new StringReader(reportTemplate)); report.DataSources.Add(new ReportDataSource(request.Controller, table)); report.EnableExternalImages = true; foreach (ReportParameterInfo p in report.GetParameters()) { if (p.Name.Equals("FilterDetails") && !(String.IsNullOrEmpty(request.FilterDetails))) report.SetParameters(new ReportParameter("FilterDetails", request.FilterDetails)); if (p.Name.Equals("BaseUrl")) { string baseUrl = String.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, context.Request.ApplicationPath.TrimEnd('/')); report.SetParameters(new ReportParameter("BaseUrl", baseUrl)); } if (p.Name.Equals("Query") && !(String.IsNullOrEmpty(q))) report.SetParameters(new ReportParameter("Query", HttpUtility.UrlEncode(q))); } report.SetBasePermissionsForSandboxAppDomain(new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted)); byte[] reportData = report.Render(reportFormat, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); if (this.Arguments != null) { this.Arguments.MimeType = mimeType; this.Arguments.FileNameExtension = fileNameExtension; this.Arguments.Encoding = encoding; this.OutputStream.Write(reportData, 0, reportData.Length); } else { // send report data to the client context.Response.Clear(); context.Response.ContentType = mimeType; context.Response.AddHeader("Content-Length", reportData.Length.ToString()); AppendDownloadTokenCookie(); string fileName = FormatFileName(context, request, fileNameExtension); if (String.IsNullOrEmpty(fileName)) { fileName = String.Format("{0}_{1}.{2}", request.Controller, request.View, fileNameExtension); if (args != null) fileName = GenerateOutputFileName(args, fileName); } context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName)); context.Response.OutputStream.Write(reportData, 0, reportData.Length); } } }
void IHttpHandler.ProcessRequest(HttpContext context) { string c = context.Request["c"]; string q = context.Request["q"]; PageRequest request = this.Request; if ((request == null) && (String.IsNullOrEmpty(c) || String.IsNullOrEmpty(q))) { throw new Exception("Invalid report request."); } // #pragma warning disable 0618 System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); // #pragma warning restore 0618 // create a data table for report string templateName = null; string aa = null; string reportFormat = null; if (request == null) { request = serializer.Deserialize <PageRequest>(q); templateName = context.Request.Form["a"]; aa = context.Request["aa"]; } else { templateName = this.Arguments.TemplateName; reportFormat = this.Arguments.Format; request.FilterDetails = this.Arguments.FilterDetails; } request.PageIndex = 0; request.PageSize = Int32.MaxValue; request.RequiresMetaData = true; // try to generate a report via a business rule ActionArgs args = null; if (!(String.IsNullOrEmpty(aa))) { args = serializer.Deserialize <ActionArgs>(aa); IDataController controller = ControllerFactory.CreateDataController(); ActionResult result = controller.Execute(args.Controller, args.View, args); if (!(String.IsNullOrEmpty(result.NavigateUrl))) { AppendDownloadTokenCookie(); context.Response.Redirect(result.NavigateUrl); } if (result.Canceled) { AppendDownloadTokenCookie(); return; } result.RaiseExceptionIfErrors(); // parse action data SortedDictionary <string, string> actionData = new SortedDictionary <string, string>(); ((DataControllerBase)(controller)).Config.ParseActionData(args.Path, actionData); List <string> filter = new List <string>(); foreach (string name in actionData.Keys) { string v = actionData[name]; if (name.StartsWith("_")) { if (name == "_controller") { request.Controller = v; } if (name == "_view") { request.View = v; } if (name == "_sortExpression") { request.SortExpression = v; } if (name == "_count") { request.PageSize = Convert.ToInt32(v); } if (name == "_template") { templateName = v; } } else if (v == "@Arguments_SelectedValues") { if ((args.SelectedValues != null) && (args.SelectedValues.Length > 0)) { StringBuilder sb = new StringBuilder(); foreach (string key in args.SelectedValues) { if (sb.Length > 0) { sb.Append("$or$"); } sb.Append(key); } filter.Add(String.Format("{0}:$in${1}", name, sb.ToString())); } else { return; } } else if (Regex.IsMatch(v, "^(\'|\").+(\'|\")$")) { filter.Add(String.Format("{0}:={1}", name, v.Substring(1, (v.Length - 2)))); } else if (args.Values != null) { foreach (FieldValue fv in args.Values) { if (fv.Name == v) { filter.Add(String.Format("{0}:={1}", name, fv.Value)); } } } request.Filter = filter.ToArray(); } } // load report definition string reportTemplate = Controller.CreateReportInstance(null, templateName, request.Controller, request.View); ViewPage page = ControllerFactory.CreateDataController().GetPage(request.Controller, request.View, request); DataTable table = page.ToDataTable(); // insert validation key reportTemplate = _validationKeyRegex.Replace(reportTemplate, String.Format("/Blob.ashx?_validationKey={0}&", BlobAdapter.ValidationKey)); // figure report output format if (this.Arguments == null) { Match m = Regex.Match(c, "^(ReportAs|Report)(Pdf|Excel|Image|Word|)$"); reportFormat = m.Groups[2].Value; } if (String.IsNullOrEmpty(reportFormat)) { reportFormat = "Pdf"; } // render a report string mimeType = null; string encoding = null; string fileNameExtension = null; string[] streams = null; Warning[] warnings = null; using (LocalReport report = new LocalReport()) { report.EnableHyperlinks = true; report.EnableExternalImages = true; report.LoadReportDefinition(new StringReader(reportTemplate)); report.DataSources.Add(new ReportDataSource(request.Controller, table)); report.EnableExternalImages = true; foreach (ReportParameterInfo p in report.GetParameters()) { if (p.Name.Equals("FilterDetails") && !(String.IsNullOrEmpty(request.FilterDetails))) { report.SetParameters(new ReportParameter("FilterDetails", request.FilterDetails)); } if (p.Name.Equals("BaseUrl")) { string baseUrl = String.Format("{0}://{1}{2}", context.Request.Url.Scheme, context.Request.Url.Authority, context.Request.ApplicationPath.TrimEnd('/')); report.SetParameters(new ReportParameter("BaseUrl", baseUrl)); } if (p.Name.Equals("Query") && !(String.IsNullOrEmpty(q))) { report.SetParameters(new ReportParameter("Query", HttpUtility.UrlEncode(q))); } } report.SetBasePermissionsForSandboxAppDomain(new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted)); byte[] reportData = report.Render(reportFormat, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); if (this.Arguments != null) { this.Arguments.MimeType = mimeType; this.Arguments.FileNameExtension = fileNameExtension; this.Arguments.Encoding = encoding; this.OutputStream.Write(reportData, 0, reportData.Length); } else { // send report data to the client context.Response.Clear(); context.Response.ContentType = mimeType; context.Response.AddHeader("Content-Length", reportData.Length.ToString()); AppendDownloadTokenCookie(); string fileName = FormatFileName(context, request, fileNameExtension); if (String.IsNullOrEmpty(fileName)) { fileName = String.Format("{0}_{1}.{2}", request.Controller, request.View, fileNameExtension); if (args != null) { fileName = GenerateOutputFileName(args, fileName); } } context.Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", fileName)); context.Response.OutputStream.Write(reportData, 0, reportData.Length); } } }
protected void BindHostingSpaceBandwidthOverusageDetailsReport(string reportName, LocalReport localReport) { // 1. Localize report localReport.DisplayName = reportName; localReport.LoadReportDefinition( ReportingServicesUtils.LoadReportFromFile( GetReportFullPath(reportName) , reportName , this ) ); // 2. Update parameters // Note: here we are always in Drill-through mode. localReport.SetParameters(localReport.OriginalParametersToDrillthrough); string hostingSpaceId = localReport.GetParameters()["HostingSpaceId"].Values[0]; List<ReportParameter> parameters = new List<ReportParameter>(); parameters.Add( new ReportParameter( ParameterBandwidthStartDate , startDateCalendar.SelectedDate.ToString() ) ); parameters.Add( new ReportParameter( ParameterBandwidthEndDate , endDateCalendar.SelectedDate.ToString() ) ); localReport.SetParameters(parameters); //3. Update data DataSet ds = ES.Services.Packages .GetBandwidthOverusageDetailsReport( PanelSecurity.SelectedUserId , int.Parse(hostingSpaceId) , startDateCalendar.SelectedDate , endDateCalendar.SelectedDate ); localReport.DataSources.Clear(); TranslateStatusField(ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_HostingSpace", ds.Tables["HostingSpace"]); BindDataTableToReport(localReport, "OverusageReport_BandwidthOverusage", ds.Tables["BandwidthOverusage"]); BindDataTableToReport(localReport, "OverusageReport_OverusageDetails", ds.Tables["OverusageDetails"]); localReport.Refresh(); }
/// <summary> /// Sets the local report parameters, post-query. /// </summary> private void SetReportParameters() { try { ReportParameterInfoCollection currentParams = _localReport.GetParameters(); ReportParameter rpCurrentParam; string paramValue = String.Empty; bool addParam = false; if (this._reportParameters == null) { this._reportParameters = new Dictionary <string, string>(); } else { this._reportParameters.Clear(); } foreach (ReportParameterInfo rp in currentParams) { addParam = false; switch (rp.Name) { case "LocaleCode": paramValue = currentParams["LocaleCode"].Values.Count == 0 ? Program.CurrentLanguage : currentParams["LocaleCode"].Values[0]; addParam = true; break; case "Start": paramValue = currentParams["Start"].Values.Count == 0 ? GetDateOffset(HelpersGUI.DateTimeToString(StartDatePicker.Value, Messages.DATEFORMAT_DMY, false)) : currentParams["Start"].Values[0]; addParam = true; break; case "End": paramValue = currentParams["End"].Values.Count == 0 ? GetDateOffset(HelpersGUI.DateTimeToString(EndDatePicker.Value, Messages.DATEFORMAT_DMY, false)) : currentParams["End"].Values[0]; addParam = true; break; case "GroupBy1": paramValue = currentParams["GroupBy1"].Values.Count == 0 ? "day" : currentParams["GroupBy1"].Values[0]; addParam = true; break; case "TopN": paramValue = currentParams["TopN"].Values.Count == 0 ? "100000" : currentParams["TopN"].Values[0]; addParam = true; break; case "PoolID": paramValue = currentParams["PoolID"].Values.Count == 0 ? _pool.uuid : currentParams["PoolID"].Values[0]; addParam = true; break; case "PoolName": paramValue = currentParams["PoolName"].Values.Count == 0 ? Helpers.GetName(_pool) : currentParams["PoolName"].Values[0]; addParam = true; break; case "HostID": paramValue = currentParams["HostID"].Values.Count == 0 ? ((Host)hostComboBox.SelectedItem).uuid : currentParams["HostID"].Values[0]; addParam = true; break; case "HostName": paramValue = currentParams["HostName"].Values.Count == 0 ? ((Host)hostComboBox.SelectedItem).name_label : currentParams["HostName"].Values[0]; addParam = true; break; case "Filter": paramValue = currentParams["Filter"].Values.Count == 0 ? (_selectedCustomFilters != null && _selectedCustomFilters.Count > 0 ? String.Join(DELIMETER, _selectedCustomFilters.ToArray()) : comboBoxView.SelectedIndex.ToString()) : currentParams["Filter"].Values[0]; addParam = true; break; case "UTCOffset": paramValue = currentParams["UTCOffset"].Values.Count == 0 ? _currentOffsetMinutes.ToString(): currentParams["UTCOffset"].Values[0]; addParam = true; break; } if (addParam) { rpCurrentParam = new ReportParameter(rp.Name, paramValue); _localReport.SetParameters(new Microsoft.Reporting.WinForms.ReportParameter[] { rpCurrentParam }); _reportParameters.Add(rp.Name, paramValue); } } } catch (LocalProcessingException ex) { log.Debug(ex, ex); throw new Exception(String.Format(Messages.WLB_REPORT_SET_PARAMS, ex.InnerException.InnerException.Message)); } catch (Exception ex) { log.Debug(ex, ex); throw new Exception(String.Format(Messages.WLB_REPORT_SET_PARAMS, ex.Message)); } }
public static bool GetReportParameters(LocalReport report, string reportparam, IWin32Window owner, ILogger logger) { fmReportParameters fmP = new fmReportParameters(); XmlDocument doc = new XmlDocument(); doc.Load(report.ReportPath); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); //nsmgr.AddNamespace("rds", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"); String strNameSpace = ReportUtil.GetReportNameSpace(doc); if (strNameSpace != null) { nsmgr.AddNamespace("rds", strNameSpace); } else { nsmgr.AddNamespace("rds", "http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition"); } string paramsxpath; if (0 == reportparam.Length) { paramsxpath = "//rds:Report//rds:ReportParameters/rds:ReportParameter[rds:Hidden='false' or not (rds:Hidden)]"; } else { paramsxpath = "//rds:Report//rds:ReportParameters/rds:ReportParameter[@Name='" + reportparam + "'and (rds:Hidden='false' or not (rds:Hidden))]"; } XmlNodeList nodes = doc.DocumentElement.SelectNodes(paramsxpath, nsmgr); //If no params, bail if ((null == nodes) || (0 == nodes.Count)) { logger.LogMessage(sqlnexus.Properties.Resources.Msg_NoParams, MessageOptions.Dialog); return(false); } int i = 0; foreach (XmlNode node in nodes) { fmP.tlpClient.RowCount += 1; object defval = null; object minval = null; object maxval = null; Label la = new Label(); la.AutoSize = true; fmP.tlpClient.Controls.Add(la, 0, i); la.Anchor = AnchorStyles.Left; la.Location = new Point(0, 3); XmlNode valnode = node.SelectSingleNode("rds:ValidValues", nsmgr); Control ctl = null; TrackBar tctl = null; if (null != valnode) //value list { ctl = new ComboBox(); ((ComboBox)ctl).Size = new Size(200, ((ComboBox)ctl).Size.Height); // ((ComboBox)ctl).DropDownStyle = ComboBoxStyle.DropDownList; XmlNode dsnode = valnode.SelectSingleNode("rds:DataSetReference/rds:DataSetName", nsmgr); if (null != dsnode) //value list from dataset { XmlNode vfnode = valnode.SelectSingleNode("rds:DataSetReference/rds:ValueField", nsmgr); XmlNode labelFieldNode = valnode.SelectSingleNode("rds:DataSetReference/rds:LabelField", nsmgr); System.Diagnostics.Debug.Assert(null != vfnode); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(fmNexus.GetQueryText(report.ReportPath, report.GetParameters(), dsnode.InnerText), Globals.credentialMgr.ConnectionString); da.Fill(dt); String DisplayMember = (labelFieldNode == null ? vfnode.InnerText.ToString() : labelFieldNode.InnerText.ToString()); String ValueMember = vfnode.InnerText.ToString(); ((ComboBox)ctl).DataSource = dt; ((ComboBox)ctl).DisplayMember = dt.Columns[DisplayMember].ColumnName; ((ComboBox)ctl).ValueMember = dt.Columns[ValueMember].ColumnName; foreach (DataRow r in dt.Rows) { if (null == minval) { minval = r[vfnode.InnerText].ToString(); } // ((ComboBox)ctl).Items.Add(r[vfnode.InnerText].ToString()); maxval = r[vfnode.InnerText].ToString(); } } else { XmlNodeList valnodes = valnode.SelectNodes("rds:ParameterValues//rds:Value", nsmgr); if ((null != valnodes) && (0 != valnodes.Count)) { foreach (XmlNode vnode in valnodes) { if (null == minval) { minval = vnode.InnerText; } ((ComboBox)ctl).Items.Add(vnode.InnerText); maxval = vnode.InnerText; } } } //Create an associated trackbar if there are 10 or more items //in the list DataTable myTable = (((ComboBox)ctl).DataSource as DataTable); Int32 itemCnt = 0; if (myTable != null) { itemCnt = myTable.Rows.Count; } if (((ComboBox)ctl).Items.Count >= 10 || itemCnt > 10) { tctl = new TrackBar(); if (itemCnt > 0) { tctl.Maximum = itemCnt - 1; } else { tctl.Maximum = ((ComboBox)ctl).Items.Count - 1; } tctl.AutoSize = false; tctl.Width = 300; tctl.TickStyle = TickStyle.None; tctl.Height = 30; tctl.Tag = ctl; fmP.tlpClient.Controls.Add(tctl, 2, i); tctl.Scroll += new System.EventHandler(fmP.trackBarComboBox_Scroll); } } //Get the current value if there is one defval = fmReportParameters.GetReportParameter(report, node.Attributes["Name"].Value); GetParameterVals(report.ReportPath, node.Attributes["Name"].Value, ref defval, ref minval, ref maxval); object def; if (0 == string.Compare(node["DataType"].InnerText, "datetime", true, CultureInfo.InvariantCulture)) { if (null == defval) { def = DateTime.Now; } else { def = Convert.ToDateTime(defval); } if (null == ctl) { ctl = new DateTimePicker(); ((DateTimePicker)ctl).Size = new Size(200, ((DateTimePicker)ctl).Size.Height); ((DateTimePicker)ctl).Value = Convert.ToDateTime(def); ((DateTimePicker)ctl).ValueChanged += new System.EventHandler(fmP.DateTimePicker_ValueChanged); //((DateTimePicker)ctl).Format = DateTimePickerFormat.Short; ((DateTimePicker)ctl).Format = DateTimePickerFormat.Custom; ((DateTimePicker)ctl).CustomFormat = "yyyy-MM-dd HH:mm:ss"; ((DateTimePicker)ctl).ShowUpDown = true; ////If no time supplied, use calendar format, else use time format //if (((DateTimePicker)ctl).Value.TimeOfDay == new TimeSpan(0, 0, 0)) // ((DateTimePicker)ctl).Format = DateTimePickerFormat.Short; if (null != minval) { ((DateTimePicker)ctl).MinDate = Convert.ToDateTime(minval); ((DateTimePicker)ctl).MaxDate = Convert.ToDateTime(maxval); tctl = new TrackBar(); tctl.Minimum = 0; tctl.Maximum = (int)(Convert.ToDateTime(maxval).Subtract(Convert.ToDateTime(minval)).TotalSeconds); tctl.TickStyle = TickStyle.None; // tctl.TickFrequency = tctl.Maximum / 25; tctl.AutoSize = false; tctl.Width = 300; tctl.Height = 30; tctl.Tag = ctl; ctl.Tag = tctl; fmP.tlpClient.Controls.Add(tctl, 2, i); tctl.Scroll += new System.EventHandler(fmP.trackBar_DateTimePickerScroll); fmP.DateTimePicker_ValueChanged(ctl, null); tctl = null; //Keep from being seen by combobox-specific code below } } else //combobox created above { ((ComboBox)ctl).Text = DateTimeUtil.USString(Convert.ToDateTime(def), "yyyy-MM-dd HH:mm:ss.fff"); //Convert.ToDateTime(def).ToString("yyyy-MM-dd HH:mm:ss.fff"); } } else if (0 == string.Compare(node["DataType"].InnerText, "boolean", true, CultureInfo.InvariantCulture)) { def = false; if (null == ctl) { ctl = new CheckBox(); } if (null == defval) { ((CheckBox)ctl).Checked = Convert.ToBoolean(def); } else { ((CheckBox)ctl).Checked = Convert.ToBoolean(defval); } } else if (0 == string.Compare(node["DataType"].InnerText, "integer", true, CultureInfo.InvariantCulture)) { def = "0"; //Masked text box requires strings if (null == ctl) { ctl = new MaskedTextBox(); ((MaskedTextBox)ctl).KeyPress += new System.Windows.Forms.KeyPressEventHandler(fmP.maskedTextBox1_IntegerKeyPress); ((MaskedTextBox)ctl).Size = new Size(200, ((MaskedTextBox)ctl).Size.Height); } if (ctl is ComboBox) { if (null == defval) { ((ComboBox)ctl).SelectedText = Convert.ToString(def); } else { ((ComboBox)ctl).SelectedText = Convert.ToString(defval); } } else if (ctl is TextBox) { ((TextBox)ctl).TextAlign = HorizontalAlignment.Right; if (null == defval) { ((TextBox)ctl).Text = Convert.ToString(def); } else { ((TextBox)ctl).Text = Convert.ToString(defval); } } else if (ctl is MaskedTextBox) { ((MaskedTextBox)ctl).TextAlign = HorizontalAlignment.Right; if (null == defval) { ((MaskedTextBox)ctl).Text = Convert.ToString(def); } else { ((MaskedTextBox)ctl).Text = Convert.ToString(defval); } } else { throw new ArgumentException("unknow control. fmReportParameter does not know how to handle this"); } } else if (0 == string.Compare(node["DataType"].InnerText, "float", true, CultureInfo.InvariantCulture)) { def = "0.00"; //Masked text box requires strings if (null == ctl) { ctl = new MaskedTextBox(); ((MaskedTextBox)ctl).KeyPress += new System.Windows.Forms.KeyPressEventHandler(fmP.maskedTextBox1_DecimalKeyPress); ((MaskedTextBox)ctl).Size = new Size(200, ((MaskedTextBox)ctl).Size.Height); } ((MaskedTextBox)ctl).TextAlign = HorizontalAlignment.Right; // ctl.DefaultCellStyle.Format = "f"; if (null == defval) { ((MaskedTextBox)ctl).Text = Convert.ToString(def); } else { ((MaskedTextBox)ctl).Text = Convert.ToString(defval); } } else //string or xml { def = ""; string defvalstr = (string)defval; if (null == ctl) { if ((null != defvalstr) && defvalstr.Length > 0 && ('<' == defvalstr[0]) && ('>' == defvalstr[defvalstr.Length - 1])) //xml { ctl = new DataGridView(); (ctl as DataGridView).RowHeadersVisible = false; (ctl as DataGridView).ScrollBars = ScrollBars.Both; (ctl as DataGridView).AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; System.IO.StringReader reader = new System.IO.StringReader(defvalstr); DataSet ds; if (0 == defvalstr.IndexOf("<SeriesList>")) //series list xml { ds = new DataSet("SeriesList"); DataTable dt = ds.Tables.Add("Series"); DataColumn dc = dt.Columns.Add("Selected", typeof(bool)); dc.ColumnMapping = MappingType.Attribute; dc = dt.Columns.Add("SeriesName", typeof(string)); dc.ColumnMapping = MappingType.Attribute; dc.ReadOnly = true; } else //regular xml { ds = new DataSet(); } ds.ReadXml(reader); DataView view1 = new DataView(ds.Tables[0]); view1.AllowDelete = false; view1.AllowNew = false; BindingSource bs = new BindingSource(); bs.DataSource = view1; (ctl as DataGridView).DataSource = bs; (ctl as DataGridView).Width = 400; (ctl as DataGridView).Height = 200; ctl.Tag = ds; } else //string { ctl = new TextBox(); ((TextBox)ctl).Size = new Size(200, ((TextBox)ctl).Size.Height); if (null == defval) { ((TextBox)ctl).Text = Convert.ToString(def); } else { ((TextBox)ctl).Text = defvalstr; } } } else //combobox from above { if (null == defval) { ((ComboBox)ctl).Text = Convert.ToString(def); } else { ((ComboBox)ctl).Text = Convert.ToString(defval); } } } if (null != tctl) //Can only be paired with a combobox { int j = ((ComboBox)ctl).Items.IndexOf(((ComboBox)ctl).Text); if (-1 == j) //Not found, probably due to time truncation; search for partial match { j = 0; foreach (string s in ((ComboBox)ctl).Items) { if (0 == string.Compare(((ComboBox)ctl).Text, s.Substring(0, ((ComboBox)ctl).Text.Length), true, CultureInfo.InvariantCulture)) { tctl.Value = j; break; } } } else { tctl.Value = j; } } ctl.Name = node.Attributes["Name"].Value; try { la.Text = node["Prompt"].InnerText; } catch (Exception ex) //May not have a prompt { System.Diagnostics.Debug.WriteLine(ex.Message); la.Text = node.Attributes["Name"].Value; } fmP.tlpClient.Controls.Add(ctl, 1, i); if (ctl is DataGridView) { (ctl as DataGridView).AutoSize = true; } i++; } if (DialogResult.OK == fmP.ShowDialog(owner)) { ReportParameter[] parameters = new ReportParameter[report.GetParameters().Count]; int j = 0; foreach (Control c in fmP.tlpClient.Controls) { string paramval = ""; if ((c is Label) || (c is TrackBar)) { continue; //ignore labels and trackbars } if (c is ComboBox) { ComboBox b = (ComboBox)c; if (b.SelectedValue != null && b.SelectedValue.ToString().Trim().Length > 0) { paramval = b.SelectedValue.ToString(); } else { paramval = ((ComboBox)c).Text; } } else if (c is TextBoxBase) { paramval = ((TextBoxBase)c).Text; } else if (c is DateTimePicker) { DateTimePicker pck = (DateTimePicker)c; paramval = DateTimeUtil.USString(pck.Value, "yyyy-MM-dd HH:mm:ss");// pck.Value.ToString("yyyy-MM-dd HH:mm:ss"); } else if (c is DataGridView) { paramval = (c.Tag as DataSet).GetXml(); } else if (c is CheckBox) { paramval = ((CheckBox)c).Checked.ToString(); } parameters[j++] = new ReportParameter((string)c.Name, paramval); } ReportParameter[] parametersclean = new ReportParameter[j]; for (int k = 0; k < j; k++) { parametersclean[k] = parameters[k]; } report.SetParameters(parametersclean); return(true); } else { return(false); } }
public InfReportOutput Render(InfReportFormat format) { if (string.IsNullOrWhiteSpace(FileName)) { throw new InvalidOperationException("The report file name property has not been set."); } if (FileName.StartsWith("/", StringComparison.Ordinal) && HttpContext.Current != null) { FileName = HttpContext.Current.Server.MapPath(FileName); } if (!File.Exists(FileName)) { throw new FileNotFoundException("The specified report file name does not exist. Be sure to provide the full path, and set the \"Build Action\" of the report file to \"Content\".", FileName); } try { using (var report = new LocalReport()) { report.ReportPath = FileName; foreach (var dataSourceName in report.GetDataSourceNames()) { if (!DataTables.Any(dt => dt.Key.Equals(dataSourceName, StringComparison.OrdinalIgnoreCase))) { var message = string.Format(CultureInfo.InvariantCulture, "No data table has been added for the report data source name \"{0}\".", dataSourceName); throw new InvalidOperationException(message); } } foreach (var parameter in report.GetParameters()) { if (!Parameters.Any(p => p.Key.Equals(parameter.Name, StringComparison.OrdinalIgnoreCase))) { var message = string.Format(CultureInfo.InvariantCulture, "No parameter has been added for the report parameter \"{0}\".", parameter.Name); throw new InvalidOperationException(message); } } report.EnableExternalImages = true; report.EnableHyperlinks = true; report.DataSources.Clear(); foreach (var item in DataTables) { report.DataSources.Add(new ReportDataSource(item.Key, item.Value)); } foreach (var item in Parameters) { report.SetParameters(new ReportParameter(item.Key, item.Value)); } if (!report.IsReadyForRendering) { throw new InvalidOperationException("The report is not ready for rendering. Check that all required data tables and parameters have been added."); } var reportBytes = new byte[0]; var mimeType = string.Empty; var fileExtension = string.Empty; var encoding = string.Empty; var streams = new string[0]; var warnings = new Warning[0]; report.Refresh(); reportBytes = report.Render( format.ToString(), string.Empty, // device info out mimeType, out encoding, out fileExtension, out streams, out warnings); if (warnings != null && warnings.Length > 0 && warnings.Any(w => w.Severity == Severity.Error)) { var message = new StringBuilder(); message.Append("The following error(s) occurred during report rendering: "); foreach (var warning in warnings.Where(w => w.Severity == Severity.Error)) { message.AppendFormat( CultureInfo.InvariantCulture, "code = \"{0}\"; object name = \"{1}\"; object type = \"{2}\"; message = \"{3}\".", warning.Code, warning.ObjectName, warning.ObjectType, warning.Message); } } return(new InfReportOutput { FileExtension = fileExtension, MimeType = mimeType, Encoding = encoding, ReportBytes = reportBytes }); } } catch (Exception ex) { InfLogger.Log(ex); throw; } }
public static bool GetReportParameters(LocalReport report, ILogger logger) { fmParameters fmP = new fmParameters(); XmlDocument doc = new XmlDocument(); doc.Load(report.ReportPath); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("rds", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition"); XmlNodeList nodes = doc.DocumentElement.SelectNodes("//rds:Report//rds:ReportParameters/rds:ReportParameter[rds:Hidden='false' or not (rds:Hidden)]", nsmgr); //If no params, bail if ((null == nodes) || (0 == nodes.Count)) { logger.LogMessage(sqlnexus.Properties.Resources.Msg_NoParams, MessageOptions.Dialog); return(false); } object[] row = new object[nodes.Count]; int i = 0; foreach (XmlNode node in nodes) { DataGridViewColumn col; XmlNode valnode = node.SelectSingleNode("rds:ValidValues", nsmgr); col = null; if (null != valnode) //value list { col = new DataGridViewComboBoxColumn(); XmlNode dsnode = valnode.SelectSingleNode("rds:DataSetReference/rds:DataSetName", nsmgr); if (null != dsnode) //value list from dataset { XmlNode vfnode = valnode.SelectSingleNode("rds:DataSetReference/rds:ValueField", nsmgr); System.Diagnostics.Debug.Assert(null != vfnode); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(dsnode.InnerText, Globals.ConnectionString); da.Fill(dt); foreach (DataRow r in dt.Rows) { ((DataGridViewComboBoxColumn)col).Items.Add(r[vfnode.InnerText].ToString()); } } else { XmlNodeList valnodes = valnode.SelectNodes("rds:ParameterValues//rds:Value", nsmgr); if ((null != valnodes) && (0 != valnodes.Count)) { foreach (XmlNode vnode in valnodes) { ((DataGridViewComboBoxColumn)col).Items.Add(vnode.InnerText); } } } } //Get the default value if there is one string defval = null; //Check for dataset first XmlNode dsetnode = node.SelectSingleNode("rds:DefaultValue/rds:DataSetReference/rds:DataSetName", nsmgr); if (null != dsetnode) //value from dataset { XmlNode vfnode = node.SelectSingleNode("rds:DefaultValue/rds:DataSetReference/rds:ValueField", nsmgr); System.Diagnostics.Debug.Assert(null != vfnode); DataTable dt = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(dsetnode.InnerText, Globals.ConnectionString); da.Fill(dt); defval = dt.Rows[0][vfnode.InnerText].ToString(); } else { XmlNode defvalue = node.SelectSingleNode("rds:DefaultValue//rds:Value", nsmgr); if (null != defvalue) { defval = defvalue.InnerText; } } object def; if (0 == string.Compare(node["DataType"].InnerText, "datetime", true, CultureInfo.InvariantCulture)) { def = DateTime.Now; if (null == col) { col = new DataGridViewCalendarColumn(); } col.DefaultCellStyle.Format = "s"; // ((DataGridViewCalendarColumn)col). if (null == defval) { row[i] = def; } else { row[i] = Convert.ToDateTime(defval); } } else if (0 == string.Compare(node["DataType"].InnerText, "boolean", true, CultureInfo.InvariantCulture)) { def = false; if (null == col) { col = new DataGridViewCheckBoxColumn(); } if (null == defval) { row[i] = def; } else { row[i] = Convert.ToBoolean(defval); } } else if (0 == string.Compare(node["DataType"].InnerText, "integer", true, CultureInfo.InvariantCulture)) { def = "0"; //Masked text box requires strings if (null == col) { col = new MaskedTextBoxColumn(); ((MaskedTextBoxColumn)col).Mask = "##########"; ((MaskedTextBoxColumn)col).TextAlign = HorizontalAlignment.Right; } col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; col.DefaultCellStyle.Format = "d"; if (null == defval) { row[i] = def; } else { row[i] = defval; } } else if (0 == string.Compare(node["DataType"].InnerText, "float", true, CultureInfo.InvariantCulture)) { def = "0.00"; //Masked text box requires strings if (null == col) { col = new MaskedTextBoxColumn(); ((MaskedTextBoxColumn)col).Mask = "##########.00"; ((MaskedTextBoxColumn)col).TextAlign = HorizontalAlignment.Right; } col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; col.DefaultCellStyle.Format = "f"; if (null == defval) { row[i] = def; } else { row[i] = defval; } } else //string { def = ""; if (null == col) { col = new DataGridViewTextBoxColumn(); } if (null == defval) { row[i] = def; } else { row[i] = defval; } } col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; col.DefaultCellStyle.NullValue = def; col.ValueType = def.GetType(); col.Name = node.Attributes["Name"].Value; try { col.ToolTipText = node["Prompt"].InnerText; } catch (Exception ex) //May not have a prompt { System.Diagnostics.Debug.WriteLine(ex.Message); } fmP.dvParams.Columns.Add(col); i++; } fmP.dvParams.Rows.Add(row); if (DialogResult.OK == fmP.ShowDialog()) { ReportParameter[] parameters = new ReportParameter[report.GetParameters().Count]; int j = 0; foreach (DataGridViewColumn c in fmP.dvParams.Columns) { parameters[j++] = new ReportParameter((string)c.Name, (string)fmP.dvParams.Rows[0].Cells[c.Name].Value.ToString()); } report.SetParameters(parameters); return(true); } else { return(false); } }
public string CallReports(string DocType, List <ReportParameter> reportParameters, bool isPortrait, string reportPath, DataTable dataTable, IEnumerable <dynamic> dataObject, string reportDataSetName) { int companyID = Convert.ToInt32(dictionary[9].Id == "" ? 0 : Convert.ToInt32(dictionary[9].Id)); int branchID = Convert.ToInt32(dictionary[10].Id == "" ? 0 : Convert.ToInt32(dictionary[10].Id)); string errorMessage = string.Empty; string fileString = string.Empty; try { LocalReport lr = new LocalReport(); ReportDataSource rd = new ReportDataSource(); string path = string.Empty; if (dataTable != null && dataTable.Rows.Count > 0 || dataObject != null && dataObject.Count() > 0) { path = reportPath; } else { if (isPortrait) { path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankPortrait.rdlc"); } else { path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankLandscape.rdlc"); } } if (System.IO.File.Exists(path)) { lr.EnableExternalImages = true; lr.ReportPath = path; //Set Default Report Parameter if (dataTable != null && dataTable.Rows.Count > 0 || dataObject != null && dataObject.Count() > 0) { var orgList = from c in db.SET_Company join cb in db.SET_CompanyBranch on c.CompanyID equals cb.CompanyID where cb.CompanyID == companyID && cb.BranchID == branchID select new { CompanyName = c.Name, BranchName = cb.Name }; var org = orgList.FirstOrDefault(); if (org != null) { reportParameters.Add(new ReportParameter("companyName", org.CompanyName.ToUpper())); reportParameters.Add(new ReportParameter("branchName", org.BranchName.ToUpper())); } // checking declared report parameters ReportParameterInfoCollection ps; ps = lr.GetParameters(); ReportParameter paramV = new ReportParameter(); foreach (ReportParameterInfo p in ps) { if (p.Name == "logo") { string logoPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/user_define/logo"), "r_logo.jpg"); if (System.IO.File.Exists(logoPath)) { reportParameters.Add(new ReportParameter("logo", "File:\\" + logoPath, true)); } } } lr.SetParameters(reportParameters); } } else { errorMessage = "File Not Exists."; } if (dataTable != null) { rd = new ReportDataSource(reportDataSetName, dataTable); } else if (dataObject != null) { rd = new ReportDataSource(reportDataSetName, dataObject); } lr.DataSources.Add(rd); // Convert Report To Base64String string reportType = DocType; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + DocType + "</OutputFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); fileString = Convert.ToBase64String(renderedBytes.ToArray()); return(fileString); } catch (Exception ex) { errorMessage = ex.Message; return(errorMessage); } }
public string CallReportsMultipleDS(string DocType, List <ReportParameter> reportParameters, bool isPortrait, string reportPath, IEnumerable <dynamic> dataObject1, IEnumerable <dynamic> dataObject2, string reportDS1, string reportDS2) { string errorMessage = string.Empty; string fileString = string.Empty; try { LocalReport lr = new LocalReport(); ReportDataSource rd = new ReportDataSource(); lr.EnableExternalImages = true; string path = string.Empty; if (dataObject1 != null && dataObject1.Count() > 0 || dataObject2 != null && dataObject2.Count() > 0) { path = reportPath; } else { if (isPortrait) { path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankPortrait.rdlc"); } else { path = Path.Combine(HttpContext.Current.Server.MapPath("~/Areas/Reports/RDLC"), "BlankLandscape.rdlc"); } } if (System.IO.File.Exists(path)) { lr.ReportPath = path; //Set Default Report Parameter if (dataObject1 != null && dataObject1.Count() > 0 || dataObject2 != null && dataObject2.Count() > 0) { var company = db.SET_Company.FirstOrDefault(); if (company != null) { string contactInfo = "Phone : " + company.ContactNo + " Email : " + company.EmailID; reportParameters.Add(new ReportParameter("orgName", company.Name)); reportParameters.Add(new ReportParameter("orgAddress", company.Address)); reportParameters.Add(new ReportParameter("orgContactInfo", contactInfo)); } // checking declared report parameters ReportParameterInfoCollection ps; ps = lr.GetParameters(); ReportParameter paramV = new ReportParameter(); foreach (ReportParameterInfo p in ps) { if (p.Name == "logo") { string logoPath = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/user_define/logo"), "r_logo.png"); if (System.IO.File.Exists(logoPath)) { reportParameters.Add(new ReportParameter("logo", "File:\\" + logoPath, true)); } } } lr.SetParameters(reportParameters); } } else { errorMessage = "File Not Exists."; } //if (dataObjectAsset != null) //{ // rd = new ReportDataSource(reportDSAsset, dataObjectAsset); //} //if (dataObjectLiabilities != null) //{ // rd = new ReportDataSource(reportDSLiabilites, dataObjectLiabilities); //} lr.DataSources.Clear(); ReportDataSource rd1 = new ReportDataSource(reportDS1, dataObject1); ReportDataSource rd2 = new ReportDataSource(reportDS2, dataObject2); lr.DataSources.Add(rd1); lr.DataSources.Add(rd2); // Convert Report To Base64String string reportType = DocType; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>" + DocType + "</OutputFormat>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); fileString = Convert.ToBase64String(renderedBytes.ToArray()); return(fileString); } catch (Exception ex) { errorMessage = ex.Message; return(errorMessage); } }