/// <summary> /// General method for donwload files or display report throught SSRS /// </summary> /// <param name="reportName"></param> /// <param name="numberScroll"></param> /// <param name="reportYear"></param> /// <returns></returns> //[FileDownloadCompleteFilter] public async Task <ActionResult> Reports(string reportName, int numberScroll, int reportYear) { const string serverName = @"DB2"; const string folderName = @"Orders"; var browsInfo = new BrowserInfoDTO() { Name = this.Request.Browser.Browser, Version = this.Request.Browser.Version }; //link to SSRS buil-in repors (default for integer) if (numberScroll == 0 || reportYear == 0) { return(this.View("Reports", (object)string.Format( @"http://{0}/ReportServer/Pages/ReportViewer.aspx?/{1}/{2}&{3}", serverName, folderName, reportName, @"rs:Command=Render") )); } //get report with parameters try { var typle = await this._bussinesEngage.GetNomenclatureReports(browsInfo, numberScroll, reportYear, serverName, folderName, reportName); //name file (with encoding) this.Response.AddHeader("Content-Disposition", typle.Item2); //For js spinner and complete download callback this.Response.Cookies.Clear(); this.Response.AppendCookie(new HttpCookie("SSRSfileDownloadToken", "true")); return(this.File(typle.Item1, @"application/vnd.ms-excel")); } catch (Exception exc) { //TempData[@"message"] = (@"Невозможно вывести отчёт. Ошибка! Возможно не указан перечень: " + exc.Message); Log.DebugFormat(@"Ошибка при получении отчёта {0}. Oшибка: {1}", reportName, exc.Message); //it returns log txt file with error description return(this.GetLog()); } }
/// <summary> /// Get report from SSRS (it's I/O operation from remote server, thus i use async method) /// The main reason to use 'Tuple' type is async. (it doesn't work with ref and out => i use 'tuple' as workaround) /// </summary> /// <param name="brInfo"></param> /// <param name="numberScroll"></param> /// <param name="reportYear"></param> /// <param name="serverName"></param> /// <param name="folderName"></param> /// <param name="reportName"></param> /// <param name="defaultParameters"></param> /// <returns></returns> public async Task <Tuple <byte[], string> > GetNomenclatureReports(BrowserInfoDTO brInfo, int numberScroll, int reportYear, string serverName, string folderName, string reportName, string defaultParameters = "rs:Format=Excel") { string nameFile, filterParameters; var selScroll = this.GetNomenclatureByNumber(numberScroll, reportYear); //dictionary name/title file (!Tips: required complex solution in case of scalability) switch (reportName) { case @"krt_Naftan_Gu12": nameFile = string.Format(@"Расшифровка сбора 099 за {0} месяц", CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(selScroll.DTBUHOTCHET.Month)); filterParameters = $@"period={selScroll.DTBUHOTCHET.Date}"; break; case @"krt_Naftan_BookkeeperReport": nameFile = $@"Бухгалтерский отчёт по переченю №{numberScroll}.xls"; filterParameters = $@"nkrt={numberScroll}&year={reportYear}"; break; case @"krt_Naftan_act_of_Reconciliation": nameFile = string.Format(@"Реестр электронного представления перечней ОРЦ за {0} {1} года.xls", selScroll.DTBUHOTCHET.ToString("MMMM"), selScroll.DTBUHOTCHET.Year); filterParameters = string.Format(@"month={0}&year={1}", selScroll.DTBUHOTCHET.Month, selScroll.DTBUHOTCHET.Year); break; case @"KRT_Analys_ORC": nameFile = string.Format(@"Отчёт Анализа ЭСЧФ по перечню №{0}.xls", numberScroll); filterParameters = string.Format(@"key={0}&startDate={1}", selScroll.KEYKRT, selScroll.DTBUHOTCHET.Date); break; default: nameFile = string.Format(@"Отчёт о ошибках по переченю №{0}.xls", numberScroll); filterParameters = string.Format(@"nkrt={0}&year={1}", numberScroll, reportYear); break; } //generate url for ssrs string urlReportString = string.Format(@"http://{0}/ReportServer?/{1}/{2}&{3}&{4}", serverName, folderName, reportName, defaultParameters, filterParameters); //Changing "attach;" to "inline;" will cause the file to open in the browser instead of the browser prompting to save the file. //encode the filename parameter of Content-Disposition header in HTTP (for support different browser) string headersInfo; if (brInfo.Name == "IE" && (brInfo.Version == "7.0" || brInfo.Version == "8.0")) { headersInfo = "attachment; filename=" + Uri.EscapeDataString(nameFile); } else if (brInfo.Name == "Safari") { headersInfo = "attachment; filename=" + nameFile; } else { headersInfo = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(nameFile); } //WebClient client = new WebClient { UseDefaultCredentials = true }; /*System administrator can't resolve problem with old report (Kerberos don't work on domain folder)*/ WebClient client = new WebClient { Credentials = new CredentialCache { { new Uri("http://db2"), @"ntlm", new NetworkCredential(@"CPN", @"1111", @"LAN") } } }; byte[] result; try { //byte output result = await client.DownloadDataTaskAsync(urlReportString); } catch (Exception ex) { //log url this._engage.Log.DebugFormat($"Attempt to receive report with url: {urlReportString}, but it throws exception: {ex.Message}"); result = Encoding.ASCII.GetBytes(ex.Message); } return(new Tuple <byte[], string>(result, headersInfo)); }
public void ReportHttpClient() { const string serverName = @"db2"; const string folderName = @"Orders"; const string reportName = @"krt_Naftan_Guild18Report"; DateTime reportPeriod = new DateTime(2017, 1, 1); var brInfo = new BrowserInfoDTO { Name = "Test", Version = "Test" }; var period = reportPeriod; //DateTime.ParseExact(reportPeriod, "dd-MM-yyyy", new CultureInfo("ru", true)); const string defaultParameters = @"rs:Format=Excel"; string filterParameters = @"reportPeriod=" + period.ToString("MM.01.yyyy"); //http://db2/ReportServer?/Orders/krt_Naftan_Guild18Report&rs:Format=Excel&reportPeriod=01-01-2016 string urlReportString = string.Format(@"http://{0}/ReportServer?/{1}/{2}&{3}&{4}", serverName, folderName, reportName, defaultParameters, filterParameters); string nameFile = string.Format(@"Отчёт {0} за {1} {2}г.xls", reportName, period.ToString("MMMM"), period.Year); //Changing "attach;" to "inline;" will cause the file to open in the browser instead of the browser prompting to save the file. //encode the filename parameter of Content-Disposition header in HTTP (for support different browser) string contentDisposition; if (brInfo.Name == "IE" && (new[] { "7.0", "8.0" }).Contains(brInfo.Version)) { contentDisposition = "attachment; filename=" + Uri.EscapeDataString(nameFile); } else if (brInfo.Name == "Safari") { contentDisposition = "attachment; filename=" + nameFile; } else { contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(nameFile); } byte[] data = { }; var exc = String.Empty; using (var handler = new HttpClientHandler { UseDefaultCredentials = true }) using (var httpClient = new HttpClient(handler) { BaseAddress = new Uri("http://db2") }) { try { var responseTask = httpClient.GetByteArrayAsync(urlReportString); responseTask.Wait(); data = responseTask.Result; } catch (Exception exMsg) { exc = exMsg.Message; } } if (data.Length > 0) { //For js spinner and complete download callback Assert.IsTrue(data.Length > 0); } else { Assert.IsTrue(exc != String.Empty); } }
public void ReportWebClient() { const string serverName = @"db2"; const string folderName = @"Orders"; const string reportName = @"krt_Naftan_Guild18Report"; DateTime reportPeriod = new DateTime(2017, 4, 1); var brInfo = new BrowserInfoDTO { Name = "Test", Version = "Test" }; var period = reportPeriod; //DateTime.ParseExact(reportPeriod, "dd-MM-yyyy", new CultureInfo("ru", true)); const string defaultParameters = @"rs:Format=Excel"; string filterParameters = @"reportPeriod=" + period.ToString("MM.01.yyyy"); //http://db2/ReportServer?/Orders/krt_Naftan_Guild18Report&rs:Format=Excel&reportPeriod=01-01-2016 string urlReportString = string.Format(@"http://{0}/ReportServer?/{1}/{2}&{3}&{4}", serverName, folderName, reportName, defaultParameters, filterParameters); WebClient client = new WebClient { UseDefaultCredentials = true }; /*System administrator can't resolve problem with old report (Kerberos don't work on domain folder)*/ //WebClient client = new WebClient { // Credentials = new CredentialCache { { new Uri("http://db2"), @"ntlm", new NetworkCredential(@"CPN", @"1111", @"LAN") } } //}; string nameFile = string.Format(@"Отчёт {0} за {1} {2}г.xls", reportName, period.ToString("MMMM"), period.Year); //Changing "attach;" to "inline;" will cause the file to open in the browser instead of the browser prompting to save the file. //encode the filename parameter of Content-Disposition header in HTTP (for support different browser) string contentDisposition; if (brInfo.Name == "IE" && (brInfo.Version == "7.0" || brInfo.Version == "8.0")) { contentDisposition = "attachment; filename=" + Uri.EscapeDataString(nameFile); } else if (brInfo.Name == "Safari") { contentDisposition = "attachment; filename=" + nameFile; } else { contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(nameFile); } //name file (with encoding) client.Headers.Add("Content-Disposition", contentDisposition); byte[] data = { }; var exc = String.Empty; try { data = client.DownloadData(urlReportString); } catch (Exception exMsg) { exc = exMsg.Message; } if (data.Length > 0) { //For js spinner and complete download callback Assert.IsTrue(data.Length > 0); } Assert.IsTrue(exc != String.Empty); }