protected void Button1_Click(object sender, EventArgs e) { ReportExecutionService reportExecutionService = new ReportExecutionService(); // Web Service proxy reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107"); string reportPath = "/ReconCurrent/ReconInvest"; string format = "PDF"; // Render arguments byte[] result = null; string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ParameterValue[] parameters = new ParameterValue[4]; parameters[0] = new ParameterValue(); parameters[0].Name = "StartDate"; parameters[1] = new ParameterValue(); parameters[1].Name = "EndDate"; parameters[2] = new ParameterValue(); parameters[2].Name = "IsinCode"; parameters[3] = new ParameterValue(); parameters[3].Name = "AccountNumber"; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); reportExecutionService.ExecutionHeaderValue = execHeader; execInfo = reportExecutionService.LoadReport(reportPath, historyID); String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID; parameters[0].Value = DatePickerBegin.SelectedDate.ToShortDateString(); parameters[1].Value = DatePickerEnd.SelectedDate.ToShortDateString(); parameters[3].Value = ddlAccount.SelectedValue.ToString(); parameters[2].Value = ddlInstrument.SelectedValue.ToString(); reportExecutionService.SetExecutionParameters(parameters, "nl-nl"); result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); //Response.Flush(); //Response.Close(); }
public static byte[] Render(string ssrUrl, ExportFormat exportFormat, Dictionary <string, string> parametersAndValues, string reportName, ICredentials credentials) { using (var reportExecution = new ReportExecutionService(ssrUrl) { Credentials = credentials ?? CredentialCache.DefaultCredentials }) { string encoding; string mimeType; string extension; Warning[] warnings; string[] streamIDs; reportExecution.LoadReport(reportName, null); if (parametersAndValues.Count > 0) { var parameters = new ParameterValue[parametersAndValues.Count]; var i = 0; foreach (var paramsAndValues in parametersAndValues) { parameters[i] = new ParameterValue { Name = paramsAndValues.Key, Value = paramsAndValues.Value }; i++; } reportExecution.SetExecutionParameters(parameters, "en-us"); } var results = reportExecution.Render(exportFormat.ToString(), null, out extension, out mimeType, out encoding, out warnings, out streamIDs); return(results); } }
//private rs2005.ReportingService2005 rs; public ReporteSSRS(ConexionAFuenteDatos Conexion, Parametros Param) { _SrvrName = Conexion.ServerAddress; _DbName = Conexion.Intercompany; _IdUsuario = Conexion.Usuario; _Password = Conexion.Password; _IntegratedSecurity = Conexion.IntegratedSecurity; _rutaYReporteSSRS = Param.rutaReporteSSRS; _listaDefParamReporte = Param.ListaParametrosRepSSRS; _param = Param; try { _rsExec = new ReportExecutionService(); // Create a new proxy to the web service _rsExec.Credentials = CredentialCache.DefaultCredentials; // Authenticate to the Web service using Windows credentials if (Param.reporteador.Equals("SSRS")) { _rsExec.Url = Param.SSRSServer + "/ReportExecution2005.asmx"; // Assign the URL of the Web service _ei = _rsExec.LoadReport(_rutaYReporteSSRS, _historyID); // Load the selected report. } } catch (Exception Rp) { ultimoMensaje = "Error al inicializar el reporte [ReporteSSRS]" + Rp.Message; numError++; } }
public byte[][] RenderReport(string reportPath, int id, string docType, short paperSize, bool save) { string historyID = null; string deviceInfo = ""; //@"<DeviceInfo><DpiX>300</DpiX><DpiY>300</DpiY></DeviceInfo> "; Byte[] results; const string format = "IMAGE"; string encoding = String.Empty; string mimeType = String.Empty; string extension = String.Empty; Warning[] warnings = null; string[] streamIDs = null; System.Collections.Generic.List <byte[]> list = new System.Collections.Generic.List <byte[]>(); try { ParameterValue[] rp = new ParameterValue[2]; rp.SetValue(new ParameterValue { Name = "id", Value = id.ToString() }, 0); rp.SetValue(new ParameterValue { Name = "DT", Value = DateTime.Now.ToString() }, 1); ei = res.LoadReport(reportPath, historyID); res.SetExecutionParameters(rp, "ru-ru"); int page = 0; while (true) { deviceInfo = string.Format(@"<DeviceInfo><OutputFormat>{0}</OutputFormat><PrintDpiX>300</PrintDpiX><PrintDpiY>300</PrintDpiY><StartPage>{1}</StartPage></DeviceInfo>", docType, ++page); results = res.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); ExecutionInfo2 ei2 = res.GetExecutionInfo2(); if (results != null && results.Length > 0) { list.Add(results); } else { break; } } m_numberOfPages = list.Count; if (m_numberOfPages > 0) { return(list.ToArray()); } else { return(null); } } catch (Exception ex) { throw new Kesco.Lib.Log.DetailedException(ex.Message, ex, Kesco.Lib.Log.Priority.ExternalError, string.Format("Parameters - reportPath (URL): {0} DocumentID: {1} DocumentType: {2}", reportPath, id, docType)); } }
/// <summary> /// Gerar arquivo binário conforme formato e caminho do relatório especificado e seus parâmetros /// </summary> /// <param name="formato"></param> /// <param name="caminho"></param> /// <param name="parametros"></param> /// <returns></returns> public byte[] RelatorioBinarioRS(string formato, string caminho, List <ParametroRelatorio> parametros) { var rs = new ReportExecutionService { Credentials = CredentialCache.DefaultNetworkCredentials, Url = GerenciadorConfiguracao.ServidorDeRelatorio }; string PastaDoRelatorio = GerenciadorConfiguracao.PastaDoRelatorio; byte[] result = null; string reportPath = PastaDoRelatorio + caminho; string format = formato; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var executionParams = new List <ParameterValue>(); foreach (var parametro in parametros) { executionParams.Add(new ParameterValue { Name = parametro.IdParametro, Value = parametro.Valor != null ? parametro.Valor.ToString() : null }); } string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; var execInfo = new ExecutionInfo(); var execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(executionParams.ToArray(), "pt-BR"); String SessionId = rs.ExecutionHeaderValue.ExecutionID; try { result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); } catch (Exception ex) { throw new Exception($"Não foi possível gerar o relatório erro do servidor : {ex.RecuperarMsgExcecaoAninhada()}"); } return(result); }
public void ProcessRequest(HttpContext context) { ReportExecutionService rs = new ReportExecutionService(); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); string historyId = null, encoding = ""; string reportPath = "/wismusta/DistrictAuditionStatistics"; //string extension = "PDF"; //string mimeType = "pdf"; string extension = ""; string mimeType = ""; string devInfo = "False"; Warning[] warning = null; string[] streamId = null; byte[] result = null; rs.Url = "http://sunflower.arvixe.com/ReportServer_SQL_Service/ReportExecution2005.asmx?wsdl"; //add credentials rs.Credentials = new NetworkCredential("wismusta_reportservr", "33wi8mu8ta44", "sunflower.arvixe.com"); //add parameters ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = "auditionOrgId"; parameters[0].Value = "1036"; rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyId); rs.SetExecutionParameters(parameters, "en-us"); result = rs.Render("PDF", devInfo, out extension, out mimeType, out encoding, out warning, out streamId); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.AppendHeader("content-length", result.Length.ToString()); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.BinaryWrite(result); HttpContext.Current.Response.End(); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.ClearContent(); //HttpContext.Current.Response.AddHeader("Pragma", "public"); //HttpContext.Current.Response.AddHeader("Content-Description", "File Transfer"); //HttpContext.Current.Response.AddHeader("X-Download-Options", "noopen"); //HttpContext.Current.Response.AddHeader("X-Content-Type-Options", "nosniff"); //HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=Student_History_Rpt.pdf"); //HttpContext.Current.Response.AppendHeader("content-length", result.Length.ToString()); //HttpContext.Current.Response.ContentType("application/excel"); //HttpContext.Current.Response.BinaryWrite(result); //HttpContext.Current.Response.End(); //HttpContext.Current.Response.Flush(); }
public static Byte[] DownloadExcel(System.Web.HttpContextBase httpContext, ReportExecutionBE reportexecution) { var rs = ReportWebServiceInstance(httpContext); var rsExec = new ReportExecutionService(); rsExec.Timeout = System.Threading.Timeout.Infinite; rsExec.Credentials = rs.Credentials; byte[] result = null; string format = "EXCEL"; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string extension; string encoding; string mimeType; ReportExecution.Warning[] warnings = null; string[] streamIDs = null; ExecutionInfo execInfo = new ExecutionInfo(); //var output = new HttpResponseMessage(); try { ReportExecution.ExecutionInfo ei = rsExec.LoadReport(reportexecution.ReportPath, null); List <ReportExecution.ParameterValue> parameters = new List <ReportExecution.ParameterValue>(); for (int i = 0; i < reportexecution.Parameters.Count; ++i) { for (int j = 0; j < reportexecution.Parameters[i].Value.Length; ++j) { ReportExecution.ParameterValue item = new ReportExecution.ParameterValue(); item.Name = reportexecution.Parameters[i].Name; item.Label = reportexecution.Parameters[i].Label; item.Value = reportexecution.Parameters[i].Value[j]; parameters.Add(item); } } ReportExecution.ParameterValue[] parametersExec = parameters.ToArray(); rsExec.SetExecutionParameters(parametersExec, "en-us"); result = rsExec.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rsExec.GetExecutionInfo(); } catch (SoapException ex) { //output = new HttpResponseMessage(HttpStatusCode.BadRequest); LoggingHelper.LogException("Unable to generate the excel file.", ex); } //return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", reportexecution.ReportName + "-" + execInfo.ExecutionDateTime + ".xlsx"); return(result); }
public static bool ReportExists(string reportPath, string ssrsUrl) { var rs = new ReportExecutionService(); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; rs.Url = ssrsUrl; byte[] result = null; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; string format = "XML"; ParameterValue[] parameters = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; try { execInfo = rs.LoadReport(reportPath, historyID); } catch (SoapException e) { if (e.Detail.OuterXml.Contains("rsItemNotFound")) { Console.WriteLine("Report: {0} not found", reportPath); } else { Console.WriteLine(e.Detail.OuterXml); } return(false); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } return(true); }
public byte[] CreateQuoteSheetPdf(CreateQuoteSheetDto dto, bool isDeclinature) { var parameters = new List <ParameterValue>(); var reportPath = dto.QuoteSheetTemplateUrl ?? ConfigurationManager.AppSettings["QuoteSheetReportPath"]; using (var reportService = new ReportExecutionService()) { reportService.PreAuthenticate = true; reportService.Credentials = CredentialCache.DefaultCredentials; foreach (var option in dto.OptionList) { parameters.AddRange(option.OptionVersionNumberList.Select(versionNumber => new ParameterValue { Name = "OptionVersions", Value = option.OptionId + "," + versionNumber })); } parameters.Add(new ParameterValue { Name = "QuoteType", Value = dto.QuoteSheetTemplateName }); parameters.Add(new ParameterValue { Name = "isDeclinature", Value = isDeclinature? "True":"False" }); reportService.LoadReport(reportPath, null); reportService.SetExecutionParameters(parameters.ToArray(), "en-gb"); String extension, encoding, mimetype; String[] streamIds; Warning[] warnings; return(reportService.Render("PDF", null, out extension, out encoding, out mimetype, out warnings, out streamIds)); } }
/// <summary> /// Executes report and returns file /// </summary> /// <param name="path">Path to report</param> /// <param name="format">Format</param> /// <param name="parameters">List of parameters</param> /// <returns>Array of bytes</returns> public byte[] ExportReport(string path, string format, List <SsrsParameter> parameters) { string reportPath = path; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>Full</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.Warning[] warnings = null; string[] streamIDs = null; ReportExecutionService res = new ReportExecutionService(); res.Url = ConfigurationManager.AppSettings["ReportingServiceExecutionUrl"]; res.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ReportingServiceLogin"], ConfigurationManager.AppSettings["ReportingServicePassword"], ConfigurationManager.AppSettings["ReportingServiceDomain"]); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); res.ExecutionHeaderValue = execHeader; execInfo = res.LoadReport(reportPath, historyID); if (parameters.Count > 0) { ParameterValue[] plist = new ParameterValue[parameters.Count]; for (var i = 0; i < parameters.Count; i++) { plist[i] = new ParameterValue { Name = parameters[i].Name, Value = parameters[i].Value }; i++; } res.SetExecutionParameters(plist, "en-us"); } return(res.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs)); }
protected void Page_Load(object sender, EventArgs e) { ReportExecutionService rs = new ReportExecutionService(); //set parameters and report settings string reportPath = "/StudentHistory"; rs.Url = "http://sunflower.arvixe.com/ReportServer_SQL_Service/ReportExecution2005.asmx?wsdl"; DataSourceCredentials credentials = new DataSourceCredentials(); credentials.DataSourceName = "sunflower.arvixe.com"; credentials.UserName = "******"; credentials.Password = "******"; rs.SetExecutionCredentials(new DataSourceCredentials[] { credentials }); ExecutionInfo info = new ExecutionInfo(); ExecutionHeader header = new ExecutionHeader(); string historyId = "", extension = "", mimeType = "", encoding = "", devInfo = "False"; string[] streamId; Warning[] warning; byte[] result; ParameterValue param = new ParameterValue(); param.Name = "@auditionOrgId"; param.Value = "1036"; rs.ExecutionHeaderValue = header; info = rs.LoadReport(reportPath, historyId); rs.SetExecutionParameters(new ParameterValue[] { param }, "en-us"); result = rs.Render("PDF", devInfo, out extension, out mimeType, out encoding, out warning, out streamId); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); Response.Flush(); }
/// <summary> /// Get report with format /// </summary> /// <param name="reportName">Actual Report Name</param> /// <param name="filters">Report Filters</param> /// <param name="reportExportType">Report Format</param> /// <returns></returns> public static byte[] GetReport(string reportName, ReportExportTypes reportExportType = ReportExportTypes.Pdf, ParameterValue[] filters = null) { var rs = new ReportExecutionService(); //set report name var reportAbsoluteName = ReportLocalPath + "/" + reportName; //set ssrs service uri rs.Url = ReportServiceUrl + "/" + ReportServiceName; //set authentication rs.Credentials = CredentialCache.DefaultCredentials; var nc = new NetworkCredential(ReportUser, ReportPass, ReportDomain); rs.Credentials = nc; //set render args string deviceInfo = null; var format = reportExportType.ToString().ToUpper(); if (format == "HTML") { deviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; format = "HTML4.0"; } //load report rs.LoadReport(reportAbsoluteName, null); //set filters if (filters != null) { rs.SetExecutionParameters(filters, ReportParamsCulture); } Warning[] warnings; string[] streamIDs; string extension; string mimeType; string encoding; var results = rs.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); return(results); }
private byte[] RunReport(string reportPath, ReportFormat format, ICollection <KeyValuePair <string, object> > parameters) { var service = new ReportExecutionService { Credentials = System.Net.CredentialCache.DefaultCredentials, Url = _reportExecutionUrl, ExecutionHeaderValue = new ExecutionHeader() }; service.LoadReport(reportPath, null); // Prepare report parameters. if (parameters != null && parameters.Count > 0) { var parameterValues = new ParameterValue[parameters.Count]; var index = 0; foreach (var parameterPair in parameters) { parameterValues[index] = new ParameterValue { Name = parameterPair.Key, Value = parameterPair.Value == null ? null : parameterPair.Value.ToString() }; ++index; } service.SetExecutionParameters(parameterValues, "en-us"); } const string deviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings; string[] streamIds; return(service.Render(GetFormat(format), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIds)); }
public byte[] GetReport(string reportname, Types type, Dictionary <string, dynamic> dparams) { if (string.IsNullOrEmpty(m_res.Url) || string.IsNullOrEmpty(GMConfig.ReportsFolder)) { throw new ApplicationException(m_exconfig); } byte[] rv = null; if (!string.IsNullOrEmpty(GMConfig.ReportUser) && !string.IsNullOrEmpty(GMConfig.ReportPwd)) { m_res.Credentials = new NetworkCredential(GMConfig.ReportUser, GMConfig.ReportPwd, string.Empty); } else { m_res.Credentials = System.Net.CredentialCache.DefaultCredentials; } m_res.ExecutionHeaderValue = new ExecutionHeader(); string historyid = null, encoding, mimetype, extension; Warning[] warnings = null; string[] streamids = null; try { m_res.Timeout = -1; m_res.LoadReport(string.Format("/{0}/{1}", GMConfig.ReportsFolder, reportname), historyid); m_res.SetExecutionParameters(GetParams(dparams), "en-us"); rv = m_res.Render(m_rtypes[type], m_deviceinfo, out extension, out mimetype, out encoding, out warnings, out streamids); } catch (SoapException e) { throw new ApplicationException(e.Detail.OuterXml, e); } return(rv); }
protected void Button1_Click(object sender, EventArgs e) { ReportExecutionService reportExecutionService = new ReportExecutionService(); // Web Service proxy reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107"); string reportPath = "/ReconCurrent/ReconCurrent"; string format = "PDF"; // Render arguments byte[] result = null; string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); reportExecutionService.ExecutionHeaderValue = execHeader; execInfo = reportExecutionService.LoadReport(reportPath, historyID); String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID; result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); //Response.Flush(); //Response.Close(); }
private void btnSend_Click(object sender, EventArgs e) { bool userok = GetUserVerify(); bool sqlok = BuildSQL(); if (!userok) { return; } if (!sqlok) { return; } if (string.IsNullOrWhiteSpace(networkdomain) || string.IsNullOrWhiteSpace(networkuser) || string.IsNullOrWhiteSpace(networkpassword)) { MessageBox.Show("Network Authentication is not available to send reports", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //check if report type is selected or not if (cmbRptType.SelectedIndex < 0) { MessageBox.Show("Please Select the Report Type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string err = string.Empty; switch (cmbRptType.SelectedItem.ToString()) { case "Monthly Attendance Report": err = ValidateMonthlyAttd(); break; /* optional */ case "Daily Performance Report": err = ValidateDailyPerformance(); break; /* optional */ case "Monthly Lunch Halfday Report": err = ValidateDailyPerformance(); break; /* optional */ } if (!string.IsNullOrEmpty(err)) { MessageBox.Show(err, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } /* now lock all controls */ btnAdd.Enabled = false; btnRemove.Enabled = false; cmbRptType.Enabled = false; txtUserName.Enabled = false; txtPassword.Enabled = false; btnReset.Enabled = false; lstWrkGrp.Enabled = false; btnSend.Enabled = false; DataSet ds = Utils.Helper.GetData(subscrsql, Utils.Helper.constr); bool hasRows = ds.Tables.Cast <DataTable>().Any(table => table.Rows.Count != 0); if (!hasRows) { MessageBox.Show("No any Subscription found in selected criteria", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } pBar1.Minimum = 0; pBar1.Maximum = ds.Tables[0].Rows.Count; pBar1.Value = 0; foreach (DataRow row in ds.Tables[0].Rows) { NetworkCredential clientCredentials = new NetworkCredential(networkuser, networkpassword, networkdomain); ReportingService2010 rs = new ReportingService2010(); rs.Credentials = clientCredentials; //rs.Url = "http://172.16.12.47/reportserver/reportservice2010.asmx"; rs.Url = Globals.G_ReportServiceURL; ReportExecutionService rsExec = new ReportExecutionService(); rsExec.Credentials = clientCredentials; //rsExec.Url = "http://172.16.12.47/reportserver/reportexecution2005.asmx"; rsExec.Url = Globals.G_ReportSerExeUrl; string historyID = null; string reportPath = string.Empty; string deviceInfo = null; string extension; string encoding; string mimeType; Warning[] warnings = null; string[] streamIDs = null; string format = "EXCEL"; Byte[] results; string subscrid = row["SubScriptionID"].ToString(); switch (cmbRptType.SelectedItem.ToString()) { case "Monthly Attendance Report": reportPath = "/Attendance/Automail Reports/Monthly Attendance Report"; rsExec.LoadReport(reportPath, historyID); ParameterValue[] executionParams = new ParameterValue[4]; executionParams[0] = new ParameterValue(); executionParams[0].Name = "WrkGrp"; executionParams[0].Value = row["Param1WrkGrp"].ToString(); executionParams[1] = new ParameterValue(); executionParams[1].Name = "SubScriptionID"; executionParams[1].Value = row["SubScriptionID"].ToString(); executionParams[2] = new ParameterValue(); executionParams[2].Name = "FromDt"; executionParams[2].Value = txtDtFrom.Value.ToString("yyyy-MM-dd"); executionParams[3] = new ParameterValue(); executionParams[3].Name = "ToDate"; executionParams[3].Value = txtDtTo.Value.ToString("yyyy-MM-dd"); rsExec.SetExecutionParameters(executionParams, "en-us"); string substr1 = "Monthly Attendance Report For " + txtDtFrom.Value.ToString("dd-MMM") + " To " + txtDtTo.Value.ToString("dd-MMM"); results = rsExec.Render(format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs); MailAttachment m = new MailAttachment(results, "Monthly Attendance Report.xls"); Email(row["EmailTo"].ToString(), row["EmailCopy"].ToString(), row["BCCTo"].ToString(), "Monthly Attendance Report", substr1, "*****@*****.**", "Attendance IPU", "", "", subscrid, m); break; /* optional */ case "Daily Performance Report": reportPath = "/Attendance/Automail Reports/New Daily Performance Report With Date Para"; rsExec.LoadReport(reportPath, historyID); ParameterValue[] executionParams1 = new ParameterValue[3]; executionParams1[0] = new ParameterValue(); executionParams1[0].Name = "WrkGrp"; executionParams1[0].Value = row["Param1WrkGrp"].ToString(); executionParams1[1] = new ParameterValue(); executionParams1[1].Name = "SubScriptionID"; executionParams1[1].Value = row["SubScriptionID"].ToString(); executionParams1[2] = new ParameterValue(); executionParams1[2].Name = "tDate"; executionParams1[2].Value = txtDtFrom.Value.ToString("yyyy-MM-dd"); rsExec.SetExecutionParameters(executionParams1, "en-us"); string substr2 = "Daily Performance Report For " + txtDtFrom.Value.ToString("dd-MMM"); results = rsExec.Render(format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs); MailAttachment m1 = new MailAttachment(results, "Daily Performance Report.xls"); Email(row["EmailTo"].ToString(), row["EmailCopy"].ToString(), row["BCCTo"].ToString(), "Daily Performance Report", substr2, "*****@*****.**", "Attendance IPU", "", "", subscrid, m1); break; /* optional */ case "Monthly Lunch Halfday Report": reportPath = "/Attendance/Automail Reports/Monthly Lunch Halfday Report"; rsExec.LoadReport(reportPath, historyID); ParameterValue[] executionParams2 = new ParameterValue[4]; executionParams2[0] = new ParameterValue(); executionParams2[0].Name = "WrkGrp"; executionParams2[0].Value = row["Param1WrkGrp"].ToString(); executionParams2[1] = new ParameterValue(); executionParams2[1].Name = "SubScriptionID"; executionParams2[1].Value = row["SubScriptionID"].ToString(); executionParams2[2] = new ParameterValue(); executionParams2[2].Name = "pFromDt"; executionParams2[2].Value = txtDtFrom.Value.ToString("yyyy-MM-dd"); executionParams2[3] = new ParameterValue(); executionParams2[3].Name = "pToDt"; executionParams2[3].Value = txtDtTo.Value.ToString("yyyy-MM-dd"); rsExec.SetExecutionParameters(executionParams2, "en-us"); string substr3 = "Monthly Lunch Halfday Report For " + txtDtFrom.Value.ToString("dd-MMM") + " To " + txtDtTo.Value.ToString("dd-MMM"); results = rsExec.Render(format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs); MailAttachment m2 = new MailAttachment(results, "Monthly Lunch Halfday Report.xls"); Email(row["EmailTo"].ToString(), row["EmailCopy"].ToString(), row["BCCTo"].ToString(), "Monthly Lunch Halfday Report", substr3, "*****@*****.**", "Attendance IPU", "", "", subscrid, m2); break; } lblSid.Text = "Exec : SID - " + subscrid; lblSid.Update(); pBar1.Value += 1; if (string.IsNullOrEmpty(reportPath)) { break; } } /* now unlock all controls */ btnAdd.Enabled = true; btnRemove.Enabled = true; cmbRptType.Enabled = true; txtUserName.Enabled = true; txtPassword.Enabled = true; btnReset.Enabled = true; lstWrkGrp.Enabled = true; btnSend.Enabled = true; }
public RSExecutionInfo LoadReport(string Report, string HistoryID) { ExecutionInfo outval = rs.LoadReport(Report, HistoryID); return((RSExecutionInfo)Converter.Convert(outval)); }
/// <summary> /// Runs reports in SSRS and creates them in a specific folder /// </summary> /// <param name="reportPath">File system location to create the report</param> /// <param name="fileName">The name of the file to create</param> /// <param name="exportFormat">Format of file to export</param> /// <param name="hospitalListName">The parameter to use for the hospital name</param> private static void CreateFiles(string reportPath, string fileName, string exportFormat, string hospitalListName) { //var csvMappingFile = ConfigurationManager.AppSettings["ReportExtractorOutputFormat"]; DataTable hospitalMapping = GetDataTableFromCsvFile(ConfigurationManager.AppSettings["ReportExtractorOutputFormat"]); DataTable excludedHospitals = GetDataTableFromCsvFile(ConfigurationManager.AppSettings["excludedHospitals"]); var excludedHospitalsList = excludedHospitals.AsEnumerable().Select(row => row.Field <string>("sourceID")).ToArray(); var rs = new ReportExecutionService { Credentials = new NetworkCredential( ConfigurationManager.AppSettings["NetworkCredentialUsername"].ToString( CultureInfo.InvariantCulture), ConfigurationManager.AppSettings["NetworkCredentialPassword"].ToString( CultureInfo.InvariantCulture)), Url = Properties.Settings.Default.ServiceURL }; rs.Timeout = Int32.Parse(ConfigurationManager.AppSettings["ReportTimeoutInMillis"]); //Render arguments const string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; var execInfo = rs.LoadReport(reportPath, null); // Run the report extractor for every valid hospital foreach ( ValidValue sourceId in execInfo.Parameters.Where(i => i.Name == hospitalListName).Select(i => i.ValidValues).First() .Where(i => !excludedHospitalsList.Contains(i.Value))) { Log.Info(String.Format("Starting report execution process: {0}-{1}-{2}", reportPath, sourceId.Value, rs.ExecutionHeaderValue.ExecutionID)); //Prepare report parameter. var parameters = new ParameterValue[1]; parameters[0] = new ParameterValue { Name = hospitalListName, Value = sourceId.Value }; rs.SetExecutionParameters(parameters, "en-us"); string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; var result = rs.Render(exportFormat, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); // Write the contents of the report to an Excel file. Log.Info(String.Format("Starting create file process: {0}-{1}-{2}-{3}", reportPath, sourceId.Value, rs.ExecutionHeaderValue.ExecutionID, fileName)); var id = sourceId; var sourceCode = (from hospital in hospitalMapping.AsEnumerable() where hospital.Field <string>("SourceID") == id.Value select hospital.Field <string>("SourceCode")).First(); var id1 = sourceId; var hospitalSystem = (hospitalMapping.AsEnumerable() .Where(hospital => hospital.Field <string>("SourceID") == id1.Value) .Select(hospital => hospital.Field <string>("hospitalSystem"))).First(); string[] fromArray = execInfo.Parameters.Where(i => i.Name.ToLower() == "from").Select(i => i.DefaultValues).First(); string from = fromArray[0]; DateTime fromTime = Convert.ToDateTime(from); string[] toArray = execInfo.Parameters.Where(i => i.Name.ToLower() == "to").Select(i => i.DefaultValues).First(); string to = toArray[0]; DateTime toTime = Convert.ToDateTime(to); try { var stream = File.Create(String.Format(fileName, hospitalSystem, sourceId.Value + " " + sourceCode, fromTime.ToString("yy-MM"), toTime.ToString("yy-MM"), DateTime.Now.ToString("yyyy-MM-dd"), sourceId.Value, sourceCode), result.Length); stream.Write(result, 0, result.Length); stream.Close(); } catch (DirectoryNotFoundException ex) { } } }
public void GeneratingReport(SqlConnection devcon, string directoryPath) { ReportExecutionService rsForxls = new ReportExecutionService(); byte[] bytes = null; string ReportPath = ConfigurationManager.AppSettings["ReportPath"]; string format = "EXCEL"; string historyID = null; string devInfo = @"<DeviceInfo><StreamRoot>/RSWebServiceXS/</StreamRoot><NoHeader>true</NoHeader></DeviceInfo>"; string reportUserName = ConfigurationManager.AppSettings["ReportUserName"]; string reportPassword = ConfigurationManager.AppSettings["ReportPassword"]; string domain = ConfigurationManager.AppSettings["Domain"]; NetworkCredential objCredentials = new NetworkCredential(reportUserName, reportPassword, domain); rsForxls.Credentials = objCredentials; //Assigning the parameters string statementDate = GetStatementDate(); ParameterValue[] parameters = new ParameterValue[5]; parameters[0] = new ParameterValue(); parameters[0].Name = "AccountNumber"; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } foreach (string key in ConfigurationManager.AppSettings) { if (key.StartsWith("AccountNumber")) { parameters[0].Value = ConfigurationManager.AppSettings[key]; parameters[1] = new ParameterValue(); parameters[1].Name = "ReportType"; parameters[1].Value = "NEWFFS"; parameters[2] = new ParameterValue(); parameters[2].Name = "IncludeSalesTax"; parameters[2].Value = ConfigurationManager.AppSettings["IncludeSalesTax"]; parameters[3] = new ParameterValue(); parameters[3].Name = "StatementDate"; parameters[3].Value = statementDate; parameters[4] = new ParameterValue(); parameters[4].Name = "IsExcel"; parameters[4].Value = ConfigurationManager.AppSettings["IsExcel"]; string extension; string encoding; string mimeType; Warning[] warnings = null; string[] streamIDs = null; rsForxls.LoadReport(ReportPath, historyID); rsForxls.SetExecutionParameters(parameters, "en-us"); try { bytes = rsForxls.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); string file = directoryPath; if (parameters[0].Value == ConfigurationManager.AppSettings["AccountNumber1"]) { file = file + "LakeSide.xls"; } else if (parameters[0].Value == ConfigurationManager.AppSettings["AccountNumber2"]) { file = file + "Meadow View.xls"; } else if (parameters[0].Value == ConfigurationManager.AppSettings["AccountNumber3"]) { file = file + "The Glen Snf.xls"; } else if (parameters[0].Value == ConfigurationManager.AppSettings["AccountNumber4"]) { file = file + "The Glen PC.xls"; } byte[] fileData = bytes; using (System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite)) { using (System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs)) { bw.Write(fileData); bw.Close(); } } } catch (SoapException e) { Console.WriteLine(e.Detail.OuterXml); } } } }
public ActionResult GenerateReport(ITABUWiseReportModel objITABUWiseModel) { // ITABUWiseReportModel objITABUWise = new ITABUWiseReportModel(); try { #region Declarations string encoding; string mimeType; string extension; string fileNamePath1 = ""; string historyID = null; Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.Warning[] warnings = null; string[] streamIDs = null; string reportPath = ""; string reportName = "ITABusinessVerticalWise"; string strGetCurrentDate = DateTime.Now.ToString("MMMM") + " " + DateTime.Now.ToString("dd") + " " + DateTime.Now.Year.ToString(); string strPath = ConfigurationManager.AppSettings["ReportsPath"].ToString() + strGetCurrentDate; byte[] result = null; string format = "EXCEL"; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); ReportExecutionService rs = new ReportExecutionService(); #endregion if (!Directory.Exists(strPath)) { //Create Reports Folder with Current Date Directory.CreateDirectory(strPath); } //strPath = string.Format("{0}\\{1}_{2}", strPath, objITABUWiseModel.YearId, objITABUWiseModel.Quarter); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; rs.Url = ConfigurationManager.AppSettings["ReportExecutionService2012"].ToString(); reportPath = "/TrainingModuleReports/" + reportName; RMS.Common.Master objMaster = new Common.Master(); System.Data.DataTable dt = objMaster.FillDropDownList("105"); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); ParameterValue[] parametersBusinessverticals = null; foreach (DataRow dr in dt.Rows) { fileNamePath1 = strPath + "\\" + reportName + "_" + Convert.ToString(dr["MasterName"]).Trim() + ".xlsx"; if (!System.IO.File.Exists(fileNamePath1)) { parametersBusinessverticals = new ParameterValue[3]; parametersBusinessverticals[0] = new ParameterValue(); parametersBusinessverticals[0].Name = "StartYear"; parametersBusinessverticals[0].Value = objITABUWiseModel.YearId; parametersBusinessverticals[1] = new ParameterValue(); parametersBusinessverticals[1].Name = "Quarter"; parametersBusinessverticals[1].Value = objITABUWiseModel.Quarter; parametersBusinessverticals[2] = new ParameterValue(); parametersBusinessverticals[2].Name = "BusinessVertical"; parametersBusinessverticals[2].Value = Convert.ToString(dr["MasterId"]); rs.SetExecutionParameters(parametersBusinessverticals, "en-us"); rs.Timeout = 3600000; //60 mins result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); using (FileStream stream = System.IO.File.Create(fileNamePath1, result.Length)) { stream.Write(result, 0, result.Length); stream.Close(); } } } objITABUWiseModel.Message = string.Format("Reports Generated Sucessfully at Location {0}", strPath); return(View(objITABUWiseModel)); } catch (Exception ex) { throw new RaveHRException(ex.Message, ex, Sources.BusinessLayer, "ReportController", "GenerateReport", EventIDConstants.TRAINING_PRESENTATION_LAYER); } }
private byte[] GetRsReport_New(MD_ReportItem _reportItem, string Format) { byte[] results; ReportExecutionService rs = new ReportExecutionService(); rs.Credentials = new System.Net.NetworkCredential(RsConfig.Name, RsConfig.Pass); rs.Url = RsConfig.RsURL; // Render arguments byte[] result = null; string reportPath = "/海关总署缉私局/" + _reportItem.ReportName.ReportName; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; // Prepare report parameter. ReportService2008.ParameterValue[] param = new ReportService2008.ParameterValue[3]; param[0] = new ReportService2008.ParameterValue(); param[0].Name = "Report_Parameter_Year"; param[0].Value = _reportItem.StartDate.Year.ToString(); param[1] = new ReportService2008.ParameterValue(); param[1].Name = "Report_Parameter_month"; param[1].Value = _reportItem.StartDate.Month.ToString("D2"); param[2] = new ReportService2008.ParameterValue(); param[2].Name = "Report_Parameter_Dw"; param[2].Value = _reportItem.ReportDWID; ReportService2008.DataSourceCredentials[] credentials = null; string showHideToggle = null; string encoding; string mimeType; string extension; ReportService2008.Warning[] warnings = null; ReportService2008.ParameterValue[] reportHistoryParameters = null; string[] streamIDs = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(param, "en-us"); String SessionId = rs.ExecutionHeaderValue.ExecutionID; try { result = rs.Render(Format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); //Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime); } catch (SoapException e) { OralceLogWriter.WriteSystemLog(e.Detail.OuterXml, "ERROR"); } return(result); }
protected override void Execute(CodeActivityContext executionContext) { var tracingService = executionContext.GetExtension <ITracingService>(); var context = executionContext.GetExtension <IWorkflowContext>(); var serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); var service = serviceFactory.CreateOrganizationService(context.UserId); try { Guid RecordId = context.PrimaryEntityId; string _rpName = RptName.Get <string>(executionContext); string _appNum = AppNum.Get <string>(executionContext); byte[] result = null; ReportExecutionService rs = new ReportExecutionService(); rs.Credentials = new NetworkCredential("<Username>", "<Password>", "<Domain>"); rs.Url = "<Org_URL>/ReportExecution2005.asmx"; tracingService.Trace(context.OrganizationName); string reportPath = "/" + context.OrganizationName + "_MSCRM/" + _rpName; string format = "PDF"; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = "id"; parameters[0].Value = RecordId.ToString(); tracingService.Trace("Id passed: " + RecordId.ToString()); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(parameters, "en-us"); String SessionId = rs.ExecutionHeaderValue.ExecutionID; result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.Rootobject response = this.GetStamp(Convert.ToBase64String(result), Convert.ToInt32(result.Length.ToString()), _appNum, "<Token>", "<BlockChain_URL>"); string StamppedFile = response.UploadZipHash; //Create email activity Entity attachment = new Entity("activitymimeattachment"); attachment["objectid"] = Email.Get <EntityReference>(executionContext); attachment["objecttypecode"] = "email"; attachment["filename"] = "الشهادة.pdf"; attachment["subject"] = "لمن يهمه الأمر"; attachment["body"] = System.Convert.ToBase64String(response.StampContent); try { service.Create(attachment); } catch (Exception ex) { throw new Exception(string.Format("Error creating attachment - {0}", ex.Message)); } try { service.Execute(new SendEmailRequest() { EmailId = Email.Get <EntityReference>(executionContext).Id, IssueSend = true, TrackingToken = string.Empty }); } catch (Exception ex) { throw new Exception(string.Format("Error sending email - {0}", ex.Message)); } } catch (Exception err) { throw new Exception("Exception" + err); } }
/// <summary> /// Get report with format /// </summary> /// <param name="reportName">Actual Report Name</param> /// <param name="filters">Report Filters</param> /// <param name="reportExportType">Report Format</param> /// <returns></returns> public static byte[] GetReport(string reportName, ReportExportTypes reportExportType = ReportExportTypes.Pdf, ParameterValue[] filters = null) { var rs = new ReportExecutionService(); //set report name var reportAbsoluteName = ReportLocalPath + "/" + reportName; //set ssrs service uri rs.Url = ReportServiceUrl + "/" + ReportServiceName; //set authentication rs.Credentials = CredentialCache.DefaultCredentials; var nc = new NetworkCredential(ReportUser, ReportPass, ReportDomain); rs.Credentials = nc; //set render args string deviceInfo = null; var format = reportExportType.ToString().ToUpper(); if (format == "HTML") { deviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; format = "HTML4.0"; } //load report rs.LoadReport(reportAbsoluteName, null); //set filters if (filters != null) rs.SetExecutionParameters(filters, ReportParamsCulture); Warning[] warnings; string[] streamIDs; string extension; string mimeType; string encoding; var results = rs.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); return results; }
public static string GetReportDataModel(DateTime startDate, DateTime endDate, string nodeId, string appId, //string segmentId, //string schemeId, string cultureInfo, string strategy ) { ReportingStartDate = startDate; ReportingEndDate = endDate; ReportingAppID = appId; ParameterValue[] paramval = new ParameterValue[0]; UserDTO user = FormsAuthenticationWrapper.User; var userApplications = (UserDTO)HttpContext.Current.Session["user"]; // userApplications.Accounts var reportPathPrefix = ""; var reportName = string.Empty; // the node id should reference feature enum versus primary key switch (nodeId) { case "1": case "9004": reportPathPrefix = ConfigurationManager.AppSettings["ReportPrefix"]; reportName = "RecommendationDemand"; paramval = new ParameterValue[4]; paramval[0] = new ParameterValue(); paramval[0].Name = "account"; paramval[0].Value = user.LastAccountID; paramval[1] = new ParameterValue(); paramval[1].Name = "applicationid"; paramval[1].Value = appId.ToLower(); paramval[2] = new ParameterValue(); paramval[2].Name = "startdate"; paramval[2].Value = ReportingStartDate.ToShortDateString(); paramval[3] = new ParameterValue(); paramval[3].Name = "enddate"; paramval[3].Value = ReportingEndDate.ToShortDateString(); break; case "2": case "9005": reportPathPrefix = ConfigurationManager.AppSettings["ReportPrefix"]; reportName = "RecommendationDetail"; paramval = new ParameterValue[4]; paramval[0] = new ParameterValue(); paramval[0].Name = "account"; paramval[0].Value = user.LastAccountID; paramval[1] = new ParameterValue(); paramval[1].Name = "app_id"; paramval[1].Value = appId.ToLower(); paramval[2] = new ParameterValue(); paramval[2].Name = "startdate"; paramval[2].Value = ReportingStartDate.ToShortDateString(); paramval[3] = new ParameterValue(); paramval[3].Name = "enddate"; paramval[3].Value = ReportingEndDate.ToShortDateString(); break; case "3": case "9006": reportPathPrefix = ConfigurationManager.AppSettings["ReportPrefix"]; reportName = "RecommendedItems"; paramval = new ParameterValue[4]; paramval[0] = new ParameterValue(); paramval[0].Name = "Account_ID"; paramval[0].Value = user.LastAccountID; // "Nike" paramval[1] = new ParameterValue(); paramval[1].Name = "ApplicationID"; paramval[1].Value = appId.ToLower(); // "Nike01US" paramval[2] = new ParameterValue(); paramval[2].Name = "T_Start"; paramval[2].Value = ReportingStartDate.ToShortDateString(); //paramval[3] = new ParameterValue(); //paramval[3].Name = "Scheme_ID"; //paramval[3].Value = schemeId; // "All Schemes" paramval[3] = new ParameterValue(); paramval[3].Name = "T_End"; paramval[3].Value = ReportingEndDate.ToShortDateString(); paramval[4] = new ParameterValue(); paramval[4].Name = "Segment"; paramval[4].Value = "All Segments"; break; case "4": case "9007": reportPathPrefix = ConfigurationManager.AppSettings["ReportPrefix"]; reportName = "StrategyComparison"; paramval = new ParameterValue[7]; paramval[0] = new ParameterValue(); paramval[0].Name = "Account_ID"; paramval[0].Value = user.LastAccountID; paramval[1] = new ParameterValue(); paramval[1].Name = "ApplicationID"; paramval[1].Value = appId.ToLower(); paramval[2] = new ParameterValue(); paramval[2].Name = "T_Start"; paramval[2].Value = ReportingStartDate.ToShortDateString(); //paramval[3] = new ParameterValue(); //paramval[3].Name = "Scheme_ID"; //paramval[3].Value = schemeId; // "All Schemes" paramval[3] = new ParameterValue(); paramval[3].Name = "T_End"; paramval[3].Value = ReportingEndDate.ToShortDateString(); paramval[4] = new ParameterValue(); paramval[4].Name = "Strategy_Status"; paramval[4].Value = strategy; paramval[5] = new ParameterValue(); paramval[5].Name = "Tag"; paramval[5].Value = "Ungroup"; paramval[6] = new ParameterValue(); paramval[6].Name = "GroupByTag"; paramval[6].Value = "0"; break; } Warning[] warnings = null; string[] streamIDs = null; string encoding = string.Empty; string mimeType = string.Empty; string extension = string.Empty; var reportHtml = string.Empty; try { var rs = new ReportExecutionService(); var reportUsername = ConfigurationManager.AppSettings["ReportUsername"]; var reportPassword = ConfigurationManager.AppSettings["ReportPassword"]; var reportDomain = ConfigurationManager.AppSettings["ReportDomain"]; rs.Credentials = new NetworkCredential(reportUsername, reportPassword, reportDomain); rs.LoadReport(string.Format("{0}{1}", reportPathPrefix, reportName), null); rs.SetExecutionParameters(paramval, "en-us"); reportHtml = System.Text.Encoding.Default.GetString(rs.Render("HTML4.0", string.Empty, out extension, out encoding, out mimeType, out warnings, out streamIDs)); rs.Timeout = 10000; } catch (Exception ex) { _certonaService.Abort(); throw; } return(reportHtml); }
public static void SendMailReport(string reportName, string reportTitle, List <ParameterValue> parameters, string company, string emailTo, string Subject, string body) { string deviceInfo = null; string extension = string.Empty; string mimeType = string.Empty; string encoding = string.Empty; Warning[] warnings = null; string[] streamIDs = null; string historyId = null; Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us"); // Create a Report Execution object var rsExec = new ReportExecutionService() { ExecutionHeaderValue = new ExecutionHeader(), Timeout = Timeout.Infinite }; rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials; rsExec.Url = ReportServer + "/ReportExecution2005.asmx"; // Load the report ExecutionInfo execInfo = rsExec.LoadReport("/Report/" + reportName, historyId); TblCompany companyRow; using (var context = new WorkFlowManagerDBEntities()) { companyRow = context.TblCompanies.FirstOrDefault(x => x.DbName == company); } string Ip = companyRow.Ip + companyRow.Port; foreach (var item in execInfo.Parameters) { try { if (item.Name == "Ip" && !string.IsNullOrWhiteSpace(Ip)) { parameters.Add(new ParameterValue() { Name = item.Name, Value = Ip }); continue; } if (item.Name == "Database" && !string.IsNullOrWhiteSpace(company)) { parameters.Add(new ParameterValue() { Name = item.Name, Value = company }); continue; } //parameters.Add(new Microsoft.Reporting.WebForms.ReportParameter(item.Name, para[count])); } catch (Exception) { } } rsExec.SetExecutionParameters(parameters.ToArray(), "en-us"); // get pdf of report byte[] results = rsExec.Render("PDF", deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); //Walla...almost no code, it's easy to manage and your done. //Take the bytes and add as an attachment to a MailMessage(SMTP): var attach = new Attachment(new MemoryStream(results), string.Format("{0}.pdf", reportTitle)); string emailFrom; var service = new GlOperations.GlService(); try { emailFrom = service.GetRetailChainSetupByCode("CashDepositeFromMail", company).sSetupValue; } catch (Exception ex) { new AssistanceService().SaveLog(JsonConvert.SerializeObject(ex), 0); emailFrom = "*****@*****.**"; } SendEmail(attach, emailFrom, emailTo.Split(';').ToList(), Subject, body); }
static void Main() { //Definición de variables. string reportName = ""; dynamic items; string printer; List <ParameterValue> parameters = new List <ParameterValue>(); //Lee el archivo JSON using (StreamReader r = new StreamReader(Path.GetTempPath() + "Param.json")){ string json = r.ReadToEnd(); items = JsonConvert.DeserializeObject(json); } JObject jObject = JObject.Parse(items.ToString()); foreach (JProperty parsedObject in jObject.Properties()) { string key = parsedObject.Name; switch (key) { // All the parameters used on the file are listed in this case case "report": { reportName = parsedObject.Value.ToString(); break; } case "params": { foreach (JObject parsedObjParams in JArray.Parse(parsedObject.Value.ToString())) { foreach (JProperty parsedPropParams in parsedObjParams.Properties()) { string keyParam = parsedPropParams.Name; string valueParam = ""; if (parsedPropParams.Value.Type == JTokenType.Array) { foreach (var value in parsedPropParams.Value) { parameters.Add(new ParameterValue { Name = keyParam, Value = value.ToString() }); } } else { valueParam = parsedPropParams.Value.ToString(); parameters.Add(new ParameterValue { Name = keyParam, Value = valueParam }); } } } break; } case "printer": { printer = parsedObject.Value.ToString(); break; } default: { Console.WriteLine("Hola se ha metido a default ;)"); break; } } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Creates object from WSDL reference of reporting services ReportExecutionService rs = new ReportExecutionService(); //get the credentials of the logged user rs.Credentials = CredentialCache.DefaultCredentials; //Url de reporting services http://<server>/<Web Service URL>/reportexecution2005.asmx rs.Url = ConfigurationManager.AppSettings["urlReporting"]; rs.ExecutionHeaderValue = new ExecutionHeader(); var executionInfo = new ExecutionInfo(); executionInfo = rs.LoadReport(reportName, null); rs.SetExecutionParameters(parameters.ToArray(), "en-US"); // Reporting services call variables string deviceInfo = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string mimeType; string encoding; string[] streamId; Warning[] warning; var result = rs.Render("PDF", deviceInfo, out mimeType, out encoding, out encoding, out warning, out streamId); string todayFile = DateTimeOffset.UtcNow.ToString(); Console.WriteLine("Today: "); Console.WriteLine(todayFile); File.WriteAllBytes(Path.GetTempPath() + todayFile, result); PdfDocument doc = new PdfDocument(); PrinterSettings ps = new PrinterSettings(); //Printer.SetDefaultPrinter(printer); Printer.SetDefaultPrinter("Microsoft Print to PDF"); doc.LoadFromFile(Path.GetTempPath() + todayFile); doc.Print(); File.Delete(Path.GetTempPath() + todayFile); //Inicializa objeto para imprimir //PrintDocument document1 = new PrintDocument(); //Se Inicializan las configuraciones de la impresión //PrinterSettings ps = new PrinterSettings(); // Selecciona Ms Print to PDF como impresora Default (aqui iría el nombre de la impresora de cheques) //Printer.SetDefaultPrinter("Microsoft Print to PDF"); //Se guardan la configuración //document1.PrinterSettings = ps; //Imprime //document1.Print(); //Application.Run(new Form1()); // Impresión con render //PrintExample pe = new PrintExample(); // The name of the printer should be added here; //this could be a local or network printer. //pe.PrintReport(@"Microsoft Print to PDF"); }
private Exception RunSSRSReport(ReportParameters Report, ActivityRun activityRun, reportFormat format) { rsExec = new ReportExecutionService(); rsExec.Url = Properties.Settings.Default.RE2005_ReportExecutionService; rsExec.UseDefaultCredentials = true; string historyID = null; string deviceInfo = null; Byte[] results; string encoding = String.Empty; string mimeType = String.Empty; string extension = String.Empty; Warning[] warnings = null; string[] streamIDs = null; var p = ""; for (int i = 0; i < Report.Parameters.Count; i++) { p = "Param[" + i.ToString() + "]" + Report.Parameters[i].Name + "|" + Report.Parameters[i].Value.ToString() + Environment.NewLine + p; } // Path of the Report - XLS, PDF etc. Report.OutputFilePath = GetOutputFileName(Report); string FilePath = outputFolder + Report.OutputFilePath + "." + format.ToString().ToLower(); // Name of the report - Please note this is not the RDL file. string _reportName = @"/GenevaReports/" + Report.Name; try { ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID); ParameterValue[] parameters = new ParameterValue[Report.Parameters.Count]; for (int i = 0; i < Report.Parameters.Count; i++) { parameters[i] = new ParameterValue(); parameters[i].Name = Report.Parameters[i].Name; parameters[i].Value = (string)Report.Parameters[i].Value; } rsExec.SetExecutionParameters(parameters, "en-IE"); DataSourceCredentials dataSourceCredentials2 = new DataSourceCredentials(); dataSourceCredentials2.DataSourceName = Properties.Settings.Default.DataSourceName; dataSourceCredentials2.UserName = Properties.Settings.Default.GenevaUser; dataSourceCredentials2.Password = Properties.Settings.Default.GenevaPass; DataSourceCredentials[] _credentials2 = new DataSourceCredentials[] { dataSourceCredentials2 }; var c = ""; for (int i = 0; i < _credentials2.Length; i++) { c = "_credentials2[" + i.ToString() + "]:" + _credentials2[i].DataSourceName + "|" + _credentials2[i].UserName + "|" + _credentials2[i].Password + "|" + Environment.NewLine + c; } rsExec.SetExecutionCredentials(_credentials2); //rsExec.UseDefaultCredentials = true; results = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); using (FileStream stream = File.OpenWrite(FilePath)) { stream.Write(results, 0, results.Length); } } catch (Exception ex) { status = "--- ERROR ---" + Environment.NewLine + "Running PDF Report: " + Report.Name + Environment.NewLine + ex.Message + Environment.NewLine + "--------------" + Environment.NewLine + status + Environment.NewLine; return(new Exception(status)); } return(null); }
public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) { //initialize report execution service string RSExecURL = @"http://" + Server + "/ReportServer/ReportExecution2005.asmx"; ReportExecutionService RSExec2005 = new ReportExecutionService(); RSExec2005.Credentials = System.Net.CredentialCache.DefaultCredentials; RSExec2005.Url = RSExecURL; //prepare variables byte[] Results = null; Warning[] warnings = null; string encoding; string mimetype; string[] streamids = null; string extension; try { ExecutionInfo Info = new ExecutionInfo(); Info = RSExec2005.LoadReport(SelectedReport, null); if (DtParameters != null) { if (DtParameters.Rows.Count > 0) { List <Tuple <string, string> > lstParameters = new List <Tuple <string, string> >(); foreach (DataRow row in DtParameters.Rows) { if (row["ParameterValue"] != null) { if (!string.IsNullOrEmpty(row["ParameterValue"].ToString())) { //the parameter value has to be a variable string pName = row["ParameterName"].ToString(); Variables varPValue = null; variableDispenser.LockOneForRead(row["ParameterValue"].ToString(), ref varPValue); string pValue = varPValue[0].Value.ToString(); lstParameters.Add(Tuple.Create(pName, pValue)); } } } ParameterValue[] Parameters; if (lstParameters.Count > 0) { Parameters = new ParameterValue[lstParameters.Count]; for (int i = 0; i < lstParameters.Count; i++) { Parameters[i] = new ParameterValue(); Parameters[i].Name = lstParameters[i].Item1; Parameters[i].Value = lstParameters[i].Item2; } RSExec2005.SetExecutionParameters(Parameters, "en-us"); } } } //output format and name Variables varFileFormat = null; variableDispenser.LockOneForRead(FileFormat, ref varFileFormat); Variables varFileName = null; variableDispenser.LockOneForRead(FileName, ref varFileName); Results = RSExec2005.Render(varFileFormat[0].Value.ToString(), null, out extension, out mimetype, out encoding, out warnings, out streamids); Info = RSExec2005.GetExecutionInfo(); FileStream FS = File.Create(varFileName[0].Value.ToString(), Results.Length); FS.Write(Results, 0, Results.Length); FS.Close(); return(DTSExecResult.Success); } catch (Exception ex) { componentEvents.FireError(0, "Reporting Service Task", "Task Error: " + ex.ToString(), "", -1); return(DTSExecResult.Failure); } }
public void SenderMarkerMail(string reportName, string subject, string body, int markerHeader) { string deviceInfo = null; var extension = String.Empty; var mimeType = String.Empty; var encoding = String.Empty; Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.Warning[] warnings = null; string[] streamIDs = null; string historyId = null; var rsExec = new ReportExecutionService(); rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials; using (var context = new WorkFlowManagerDBEntities()) { if (string.IsNullOrEmpty(ReportServer)) { ReportServer = context.tblChainSetups.SingleOrDefault(x => x.sGlobalSettingCode == "ReportServer").sSetupValue; } } rsExec.Url = ReportServer + "/ReportExecution2005.asmx"; // Load the report var execInfo = rsExec.LoadReport("/Report/" + reportName, historyId); var para = new ObservableCollection <string> { markerHeader.ToString() }; var parameters = new ParameterValue[para.Count]; foreach (var row in para) { var index = para.IndexOf(row); parameters[0] = new ParameterValue(); parameters[index].Value = row; parameters[index].Name = execInfo.Parameters[index].Name; // paramters) { Name = , Value = row } }, "en-us"); } rsExec.SetExecutionParameters(parameters, "en-us"); // get pdf of report var results = rsExec.Render("PDF", deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); //Walla...almost no code, it's easy to manage and your done. //Take the bytes and add as an attachment to a MailMessage(SMTP): var attach = new Attachment(new MemoryStream(results), String.Format("{0}.pdf", reportName)); string emailFrom; var emailTo = new List <string>(); using (var model = new WorkFlowManagerDBEntities()) { emailFrom = "*****@*****.**"; var brandsectionMail = model.TblMarkerMails; foreach (var variable in brandsectionMail.Select(x => x.Emp)) { emailTo.Add(model.Employees.FirstOrDefault(x => x.EMPLID == variable).Email); } } SendEmail(attach, emailFrom, emailTo, subject, body); }
/// <summary> /// This first version of RenderReport is strictly for legacy support of NIFTransferShipment. NIFTransferShipment should be re-worked to use the rendorReport /// version that accepts an array of ParameterValues. /// </summary> /// <param name="reportPath"></param> /// <param name="identifier"></param> /// <returns></returns> public byte[][] renderReport(string reportPath, ParameterValue[] reportParameters) { // Private variables for rendering string historyID = null; ExecutionHeader execHeader = new ExecutionHeader(); try { rs.Timeout = 300000; rs.ExecutionHeaderValue = execHeader; ExecutionInfo execInfo = new ExecutionInfo(); execInfo = rs.LoadReport(reportPath, historyID); if (reportParameters != null) { rs.SetExecutionParameters(reportParameters, "en-us"); } Byte[][] pages = new Byte[0][]; string format = "IMAGE"; int numberOfPages = 1; byte[] currentPageStream = new byte[1] { 0x00 }; // this single byte will prime the while loop string extension = null; string encoding = null; string mimeType = null; string[] streamIDs = null; Warning[] warnings = null; while (currentPageStream.Length > 0) { string deviceInfo = String.Format(@"<DeviceInfo><OutputFormat>EMF</OutputFormat><PrintDpiX>96</PrintDpiX><PrintDpiY>96</PrintDpiY><StartPage>{0}</StartPage></DeviceInfo>", numberOfPages); //Execute the report and get page count. currentPageStream = rs.Render( format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); if (currentPageStream.Length == 0 && numberOfPages == 1) { break; // nothing rendered } if (currentPageStream.Length > 0) { Array.Resize(ref pages, pages.Length + 1); pages[pages.Length - 1] = currentPageStream; numberOfPages++; } } m_numberOfPages = numberOfPages - 1; return(pages); } catch (SoapException ex) { eventLog.WriteEntry(ex.Detail.InnerXml, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Detail.InnerXml); } catch (Exception ex) { eventLog.WriteEntry(ex.Message, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Message); } finally { } return(null); }
protected static string GetReport(string reportpath, string format, List <RC_ParamReports> Param, string NameFile) { ReportExecutionService re2005 = new ReportExecutionService(); re2005.Credentials = CredentialCache.DefaultCredentials; // Render arguments byte[] result = null; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; // Prepare report parameter ReportExecution2005.ParameterValue[] parameters = new ReportExecution2005.ParameterValue[Param.Count]; for (int i = 0; i < Param.Count; i++) { parameters[i] = new ReportExecution2005.ParameterValue(); parameters[i].Name = Param[i].Name; parameters[i].Value = GetParamValue(Param[i].Type, Param[i].ValueFix, Param[i].ValueExpression, Param[i].Format); Console.WriteLine("Param[i].Name = {0}; Param[i].ValueExpression = {1}; Param[i].ValueCatalog = {2}; Param[i].ValueFix = {3}", Param[i].Name, Param[i].ValueExpression, Param[i].ValueCatalog, Param[i].ValueFix); Console.WriteLine("parameters[i].Name = {0}; parameters[i].Value = {1}", parameters[i].Name, parameters[i].Value); } //Блок херни ReportExecution2005.DataSourceCredentials[] credentials = null; string showHideToggle = null; string encoding; string mimeType; string extension = ""; ReportExecution2005.Warning[] warnings = null; ReportExecution2005.ParameterValue[] reportHistoryParameters = null; string[] streamIDs = null; // ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); try {// re2005.ExecutionHeaderValue = execHeader; execInfo = re2005.LoadReport(reportpath, historyID); re2005.SetExecutionParameters(parameters, "ru-RU"); String SessionId = re2005.ExecutionHeaderValue.ExecutionID; ///Console.WriteLine("SessionID: {0}", re2005.ExecutionHeaderValue.ExecutionID); result = re2005.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); ///Console.WriteLine("format = {0}; devInfo = {1}; extension = {2}; encoding = {3}; mimeType = {4}; warnings = {5}; streamIDs = {6}", format, devInfo, extension, encoding, mimeType, warnings, streamIDs); } catch (SoapException e) { Console.WriteLine(e.Detail.OuterXml); } catch (Exception e) { Console.WriteLine(e.Message); } ///finally { Console.WriteLine(e.Message); } // Write the contents of the report to an MHTML file. try { using (FileStream stream = System.IO.File.Create(NameFile, result.Length)) { ///Console.WriteLine("File created."); stream.Write(result, 0, result.Length); Console.WriteLine("Result written to the file {0}.", NameFile); // stream.Close(); } } catch (Exception e) { Console.WriteLine("ОШИБКА " + e.Message); } return(NameFile); }
public void SendMailReportPo(string reportName, string subject, string body, int tblAuthUser, TblSalesOrder salesOrder) { string deviceInfo = null; var extension = String.Empty; var mimeType = String.Empty; var encoding = String.Empty; Warning[] warnings = null; string[] streamIDs = null; string historyId = null; // Create a Report Execution object var rsExec = new ReportExecutionService(); rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials; using (var context = new WorkFlowManagerDBEntities()) { if (string.IsNullOrEmpty(ReportServer)) { ReportServer = context.tblChainSetups.SingleOrDefault(x => x.sGlobalSettingCode == "ReportServer").sSetupValue; } } rsExec.Url = ReportServer + "/ReportExecution2005.asmx"; // Load the report var execInfo = rsExec.LoadReport("/Report/" + reportName, historyId); var para = new ObservableCollection <string> { salesOrder.Iserial.ToString() }; var parameters = new ParameterValue[para.Count]; foreach (var row in para) { var index = para.IndexOf(row); parameters[0] = new ParameterValue(); parameters[index].Value = row; parameters[index].Name = execInfo.Parameters[index].Name; // paramters) { Name = , Value = row } }, "en-us"); } rsExec.SetExecutionParameters(parameters, "en-us"); // get pdf of report var results = rsExec.Render("PDF", deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); //Walla...almost no code, it's easy to manage and your done. //Take the bytes and add as an attachment to a MailMessage(SMTP): var attach = new Attachment(new MemoryStream(results), String.Format("{0}.pdf", reportName)); string emailFrom; var emailTo = new List <string>(); using (var model = new WorkFlowManagerDBEntities()) { try { var code = model.TblAuthUsers.FirstOrDefault(w => w.Iserial == tblAuthUser).Code; //emailFrom = "*****@*****.**";// emailFrom = model.Employees.FirstOrDefault(x => x.EMPLID == code).Email; var style = model.TblStyles.FirstOrDefault(x => x.Iserial == salesOrder.TblStyle); var brandsectionMail = model.TblBrandSectionMails.Where( x => x.TblBrand == style.Brand && x.TblLkpBrandSection == style.TblLkpBrandSection); foreach (var variable in brandsectionMail.Select(x => x.Emp)) { //emailTo.Add("*****@*****.**");// emailTo.Add(model.Employees.FirstOrDefault(x => x.EMPLID == variable).Email); } } catch (Exception) { emailFrom = model.Employees.FirstOrDefault(x => x.EMPLID == "0158").Email; } } //string emailTo; //using (var Model = new WorkFlowManagerDBEntities()) //{ // emailTo = "*****@*****.**"; // // emailFrom = Model.Employees.FirstOrDefault(x => x.EMPLID == EmpCode).Email; //} SendEmail(attach, emailFrom, emailTo, subject, body); }
public byte[] RenderReport(string url, string reportPath, ReportParameter[] parameters, string formatType, bool humanReadablePdf, IDTSComponentEvents componentEvents) { bool refire = false; byte[] retVal; componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Create the instance of the WS - " + string.Format("{0}ReportExecution2005.asmx", (url.Substring(url.Length - 1, 1) == "/") ? url : url + "/"), string.Empty, 0, ref refire); using (var rs = new ReportExecutionService { Credentials = CredentialCache.DefaultCredentials, Url = string.Format("{0}ReportExecution2005.asmx", (url.Substring(url.Length - 1, 1) == "/") ? url : url + "/") }) { const string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings; string[] streamIDs; var execHeader = new ExecutionHeader(); componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Load the report from " + reportPath, string.Empty, 0, ref refire); var execInfo = rs.LoadReport(reportPath, historyID); componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Set parameters", string.Empty, 0, ref refire); rs.SetExecutionParameters(parameters.Select(p => new ParameterValue { Label = p.Name, Name = p.Name, Value = p.Value }).ToArray(), "en-EN"); rs.ExecutionHeaderValue = execHeader; rs.ExecutionHeaderValue.ExecutionID = execInfo.ExecutionID; componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Render the report", string.Empty, 0, ref refire); retVal = rs.Render(formatType, (humanReadablePdf) ? DeviceSettings : null, out extension, out encoding, out mimeType, out warnings, out streamIDs); } return(retVal); }