예제 #1
0
        public static ReportExportResult ExportReportToFormat(ReportViewerModel model, string format, int?startPage = 0, int?endPage = 0)
        {
            ReportExportResult exportResult = new ReportExportResult();

            try
            {
                string resultHTML;
                ReportViewerForCore.ReportExecutionService.TrustedUserHeader trusteduserHeader = null;

                var url = AddCharacterStartEnd(model.ServerUrl, false, true, "/") + "ReportExecution2005.asmx";
                var basicHttpBinding = _initializeHttpBinding(url, model);
                var service          = new ReportExecutionService.ReportExecutionServiceSoapClient(basicHttpBinding, new System.ServiceModel.EndpointAddress(url));
                service.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                service.ClientCredentials.Windows.ClientCredential          = (System.Net.NetworkCredential)(model.Credentials ?? System.Net.CredentialCache.DefaultCredentials);

                // https://stackoverflow.com/questions/44036903/using-reporting-services-ssrs-as-a-reference-in-an-asp-net-core-site/49202193
                service.Endpoint.EndpointBehaviors.Add(new ReportingServicesEndpointBehavior());

                var definedReportParameters = GetReportParameters(model, true);
                exportResult.CurrentPage = (startPage.ToInt32() <= 0 ? 1 : startPage.ToInt32());
                exportResult.SetParameters(definedReportParameters, model.Parameters);

                if (startPage == 0)
                {
                    startPage = 1;
                }

                if (endPage == 0)
                {
                    endPage = startPage;
                }

                if (string.IsNullOrWhiteSpace(format))
                {
                    format = "HTML5";
                }

                string outputFormat   = $"<OutputFormat>{format}</OutputFormat>";
                string encodingFormat = $"<Encoding>{model.Encoding.EncodingName}</Encoding>";

                /* Remueve tagas HTML, Body y otros, y retorna tabla para ser ebebida en una pagina */
                string htmlFragment = (((format.ToUpper() == "HTML4.0" || format.ToUpper() == "HTML5") && model.UseCustomReportImagePath == false && model.ViewMode == ReportViewModes.View) ? "<HTMLFragment>true</HTMLFragment>" : "");

                string deviceConfig = "<ExpandContent>true</ExpandContent><AccessibleTablix>g</AccessibleTablix>";
                deviceConfig += "<StyleStream>false</StyleStream><StreamRoot>/</StreamRoot>";
                deviceConfig  = "<Parameters>Collapsed</Parameters>";

                var deviceInfo = $"<DeviceInfo>{outputFormat}{encodingFormat}<Toolbar>false</Toolbar>{htmlFragment}{deviceConfig}</DeviceInfo>";
                if (model.ViewMode == ReportViewModes.View && startPage.HasValue && startPage > 0)
                {
                    if (model.EnablePaging)
                    {
                        deviceInfo = $"<DeviceInfo>{outputFormat}<Toolbar>false</Toolbar>{htmlFragment}{deviceConfig}<Section>{startPage}</Section></DeviceInfo>";
                    }
                    else
                    {
                        deviceInfo = $"<DeviceInfo>{outputFormat}<Toolbar>false</Toolbar>{htmlFragment}{deviceConfig}</DeviceInfo>";
                    }
                }

                var reportParameters = new List <ReportExecutionService.ParameterValue>();
                foreach (var parameter in exportResult.Parameters)
                {
                    bool addedParameter = false;
                    foreach (var value in parameter.SelectedValues)
                    {
                        var reportParameter = new ReportExecutionService.ParameterValue();
                        reportParameter.Name  = parameter.Name;
                        reportParameter.Value = value;
                        reportParameters.Add(reportParameter);

                        addedParameter = true;
                    }

                    if (!addedParameter)
                    {
                        var reportParameter = new ReportExecutionService.ParameterValue();
                        reportParameter.Name = parameter.Name;
                        reportParameters.Add(reportParameter);
                    }
                }

                ReportViewerForCore.ReportExecutionService.ServerInfoHeader serverInfoHeader = new ReportViewerForCore.ReportExecutionService.ServerInfoHeader();
                ReportExecutionService.ExecutionHeader    executionHeader = new ReportExecutionService.ExecutionHeader();
                ReportExecutionService.ExecutionInfo      executionInfo   = new ReportExecutionService.ExecutionInfo();
                ReportExecutionService.LoadReportResponse loadResponse    = new ReportExecutionService.LoadReportResponse();
                ReportExecutionService.Render2Response    render2Response;
                string   historyID = null;
                string   extension = null;
                string   encoding  = null;
                string   mimeType  = null;
                string[] streamIDs = null;
                ReportExecutionService.Warning[] warnings = null;

                try
                {
                    //executionHeader = service.LoadReport(trusteduserHeader, model.ReportPath, historyID, out serverInfoHeader, out executionInfo);

                    loadResponse    = service.LoadReportAsync(trusteduserHeader, model.ReportPath, historyID).Result;
                    executionInfo   = loadResponse.executionInfo;
                    executionHeader = loadResponse.ExecutionHeader;

                    //var executionParameterResult = service.SetReportParameters(executionInfo.ExecutionID, reportParameters.ToArray(), "en-us").Result;
                    serverInfoHeader = service.SetExecutionParameters(executionHeader, trusteduserHeader, reportParameters.ToArray(), "en-us", out executionInfo);

                    if (model.EnablePaging)
                    {
                        var render2Request = new ReportExecutionService.Render2Request(executionHeader, trusteduserHeader, format, deviceInfo, ReportExecutionService.PageCountMode.Actual);
                        //var render2Response = service.Render2(executionInfo.ExecutionID, render2Request).Result;
                        render2Response = service.Render2Async(render2Request).Result;

                        extension = render2Response.Extension;
                        mimeType  = render2Response.MimeType;
                        encoding  = render2Response.Encoding;
                        warnings  = render2Response.Warnings;
                        streamIDs = render2Response.StreamIds;

                        exportResult.ReportData = render2Response.Result;
                    }
                    else
                    {
                        var renderRequest = new ReportExecutionService.RenderRequest(executionHeader, trusteduserHeader, format, deviceInfo);
                        //var renderResponse = service.Render(executionInfo.ExecutionID, renderRequest).Result;
                        var renderResponse = service.RenderAsync(renderRequest).Result;

                        extension = renderResponse.Extension;
                        mimeType  = renderResponse.MimeType;
                        encoding  = renderResponse.Encoding;
                        warnings  = renderResponse.Warnings;
                        streamIDs = renderResponse.StreamIds;

                        exportResult.ReportData = renderResponse.Result;
                    }

                    resultHTML = model.Encoding.GetString(exportResult.ReportData);
                    //executionInfo = service.GetExecutionInfo(executionHeader.ExecutionID).Result;
                }
                catch (Exception ex2)
                {
                    Console.WriteLine(ex2.Message);
                }

                exportResult.ExecutionInfo = executionInfo;
                exportResult.Format        = format;
                exportResult.MimeType      = mimeType;
                exportResult.StreamIDs     = (streamIDs == null ? new List <string>() : streamIDs.ToList());
                exportResult.Warnings      = (warnings == null ? new List <ReportExecutionService.Warning>() : warnings.ToList());

                if (executionInfo != null)
                {
                    exportResult.TotalPages = executionInfo.NumPages;
                }

                resultHTML = model.Encoding.GetString(exportResult.ReportData);

                return(exportResult);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(exportResult);
            }
        }
예제 #2
0
        /// <summary>
        /// Searches a specific report for your provided searchText and returns the page that it located the text on.
        /// </summary>
        /// <param name="model"></param>
        /// <param name="searchText">The text that you want to search in the report</param>
        /// <param name="startPage">Starting page for the search to begin from.</param>
        /// <returns></returns>
        public static int?FindStringInReport(ReportViewerModel model, string searchText, int?startPage = 0)
        {
            try
            {
                int endPage;
                ReportViewerForCore.ReportExecutionService.TrustedUserHeader trusteduserHeader = null;

                var url = AddCharacterStartEnd(model.ServerUrl, false, true, "/") + "ReportExecution2005.asmx";

                var basicHttpBinding = _initializeHttpBinding(url, model);
                var service          = new ReportExecutionService.ReportExecutionServiceSoapClient(basicHttpBinding, new System.ServiceModel.EndpointAddress(url));
                service.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                service.ClientCredentials.Windows.ClientCredential          = (System.Net.NetworkCredential)(model.Credentials ?? System.Net.CredentialCache.DefaultCredentials);

                // https://stackoverflow.com/questions/44036903/using-reporting-services-ssrs-as-a-reference-in-an-asp-net-core-site/49202193
                service.Endpoint.EndpointBehaviors.Add(new ReportingServicesEndpointBehavior());

                var definedReportParameters = GetReportParameters(model, true);

                if (!startPage.HasValue || startPage == 0)
                {
                    startPage = 1;
                }

                var exportResult = new ReportExportResult();
                exportResult.CurrentPage = startPage.ToInt32();
                exportResult.SetParameters(definedReportParameters, model.Parameters);

                var format         = "HTML5";
                var outputFormat   = $"<OutputFormat>{format}</OutputFormat>";
                var encodingFormat = $"<Encoding>{model.Encoding.EncodingName}</Encoding>";
                var htmlFragment   = (((format.ToUpper() == "HTML4.0" || format.ToUpper() == "HTML5") && model.UseCustomReportImagePath == false && model.ViewMode == ReportViewModes.View) ? "<HTMLFragment>true</HTMLFragment>" : "");

                var deviceInfo = $"<DeviceInfo>{outputFormat}{encodingFormat}<Toolbar>False</Toolbar>{htmlFragment}</DeviceInfo>";
                if (model.ViewMode == ReportViewModes.View && startPage.HasValue && startPage > 0)
                {
                    deviceInfo = $"<DeviceInfo>{outputFormat}<Toolbar>False</Toolbar>{htmlFragment}<Section>{startPage}</Section></DeviceInfo>";
                }

                var reportParameters = new List <ReportExecutionService.ParameterValue>();
                foreach (var parameter in exportResult.Parameters)
                {
                    bool addedParameter = false;
                    foreach (var value in parameter.SelectedValues)
                    {
                        var reportParameter = new ReportExecutionService.ParameterValue();
                        reportParameter.Name  = parameter.Name;
                        reportParameter.Value = value;
                        reportParameters.Add(reportParameter);

                        addedParameter = true;
                    }

                    if (!addedParameter)
                    {
                        var reportParameter = new ReportExecutionService.ParameterValue();
                        reportParameter.Name = parameter.Name;
                        reportParameters.Add(reportParameter);
                    }
                }

                ReportViewerForCore.ReportExecutionService.ServerInfoHeader serverInfoHeader = new ReportViewerForCore.ReportExecutionService.ServerInfoHeader();
                ReportExecutionService.ExecutionHeader    executionHeader = new ReportExecutionService.ExecutionHeader();
                ReportExecutionService.ExecutionInfo      executionInfo   = new ReportExecutionService.ExecutionInfo();
                ReportExecutionService.LoadReportResponse loadResponse    = new ReportExecutionService.LoadReportResponse();
                ReportExecutionService.Render2Response    render2Response;
                string   historyID = null;
                string   extension = null;
                string   encoding  = null;
                string   mimeType  = null;
                string[] streamIDs = null;
                ReportExecutionService.Warning[] warnings = null;

                try
                {
                    //executionHeader = service.LoadReport(trusteduserHeader, model.ReportPath, historyID, out serverInfoHeader, out executionInfo);
                    loadResponse    = service.LoadReportAsync(trusteduserHeader, model.ReportPath, historyID).Result;
                    executionInfo   = loadResponse.executionInfo;
                    executionHeader = loadResponse.ExecutionHeader;

                    //var executionParameterResult = service.SetReportParameters(executionInfo.ExecutionID, reportParameters.ToArray(), "en-us").Result;
                    serverInfoHeader = service.SetExecutionParameters(executionHeader, trusteduserHeader, reportParameters.ToArray(), "en-us", out executionInfo);

                    var render2Request = new ReportExecutionService.Render2Request(executionHeader, trusteduserHeader, format, deviceInfo, ReportExecutionService.PageCountMode.Actual);
                    //var render2Response = service.Render2(executionInfo.ExecutionID, render2Request).Result;
                    render2Response = service.Render2Async(render2Request).Result;

                    extension = render2Response.Extension;
                    mimeType  = render2Response.MimeType;
                    encoding  = render2Response.Encoding;
                    warnings  = render2Response.Warnings;
                    streamIDs = render2Response.StreamIds;

                    // executionInfo = service.GetExecutionInfo(executionHeader.ExecutionID).Result;

                    endPage = executionInfo.NumPages;
                    if (endPage < 1)
                    {
                        endPage = startPage.Value;
                    }

                    return(service.FindStringAsync(executionHeader, trusteduserHeader, startPage.Value, endPage, searchText).Result.PageNumber);
                }
                catch (Exception ex2)
                {
                    Console.WriteLine(ex2.Message);
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(0);
            }
        }
예제 #3
0
    public string RenderReport(string reportpath, SSRSExportType ExportType)
    {
        using (ReportExecutionService.ReportExecutionServiceSoapClient res = new   ReportExecutionService.ReportExecutionServiceSoapClient("ReportExecutionServiceSoap"))
        {
            ReportExecutionService.ExecutionHeader   ExecutionHeader   = new ReportExecutionService.ExecutionHeader();
            ReportExecutionService.TrustedUserHeader TrusteduserHeader = new ReportExecutionService.TrustedUserHeader();

            res.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

            ReportServerCreds rsc = GetReportCreds();
            res.ClientCredentials.Windows.ClientCredential.Domain   = rsc.Domain;
            res.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
            res.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;


            res.Open();
            ReportExecutionService.ExecutionInfo ei = new ReportExecutionService.ExecutionInfo();

            string format     = null;
            string deviceinfo = null;
            string mimetype   = null;

            if (ExportType.ToString().ToLower() == "html")
            {
                format     = "HTML4.0";
                deviceinfo = @"<DeviceInfo><StreamRoot>/</StreamRoot><HTMLFragment>True</HTMLFragment></DeviceInfo>";
            }
            else if (ExportType.ToString().ToLower() == "pdf")
            {
                format   = "PDF";
                mimetype = "";
            }


            byte[] results   = null;
            string extension = null;
            string Encoding  = null;
            ReportExecutionService.Warning[] warnings;
            string[] streamids = null;
            string   historyid = null;
            ReportExecutionService.ExecutionHeader  Eheader;
            ReportExecutionService.ServerInfoHeader serverinfoheader;
            ReportExecutionService.ExecutionInfo    executioninfo;



            // Get available parameters from specified report.
            ParameterValue[]        paramvalues = null;
            DataSourceCredentials[] dscreds     = null;
            ReportParameter[]       rparams     = null;

            using (ReportService.ReportingService2005SoapClient lrs = new ReportService.ReportingService2005SoapClient("ReportingService2005Soap"))
            {
                lrs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
                lrs.ClientCredentials.Windows.ClientCredential.Domain   = rsc.Domain;
                lrs.ClientCredentials.Windows.ClientCredential.UserName = rsc.UserName;
                lrs.ClientCredentials.Windows.ClientCredential.Password = rsc.Password;


                lrs.GetReportParameters(reportpath, historyid, false, paramvalues, dscreds, out rparams);
            }



            // Set report parameters here
            //List<ReportExecutionService.ParameterValue> parametervalues = new List<ReportExecutionService.ParameterValue>();

            //string enumber = Session["ENumber"] as string;
            //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = enumber });

            //if (date != null)
            //{
            //    DateTime dt = DateTime.Today;
            //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "AttendanceDate", Value = dt.ToString("MM/dd/yyyy")});
            //}

            //if (ContainsParameter(rparams, "DEEWRID"))
            //{
            //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "DEEWRID", Value = deewrid });
            //}

            //if (ContainsParameter(rparams, "BaseHostURL"))
            //{
            //                        parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "BaseHostURL", Value = string.Concat("http://", Request.Url.Authority) });
            //}


            //parametervalues.Add(new ReportExecutionService.ParameterValue() {Name="AttendanceDate",Value=null });
            //parametervalues.Add(new ReportExecutionService.ParameterValue() { Name = "ENumber", Value = "E1013" });



            try
            {
                Eheader          = res.LoadReport(TrusteduserHeader, reportpath, historyid, out serverinfoheader, out executioninfo);
                serverinfoheader = res.SetExecutionParameters(Eheader, TrusteduserHeader, parametervalues.ToArray(), null, out executioninfo);
                res.Render(Eheader, TrusteduserHeader, format, deviceinfo, out results, out extension, out mimetype, out Encoding, out warnings, out streamids);

                string exportfilename = string.Concat(enumber, reportpath);

                if (ExportType.ToString().ToLower() == "html")
                {
                    //write html
                    string html = string.Empty;
                    html = System.Text.Encoding.Default.GetString(results);

                    html = GetReportImages(res, Eheader, TrusteduserHeader, format, streamids, html);

                    return(html);
                }
                else if (ExportType.ToString().ToLower() == "pdf")
                {
                    //write to pdf


                    Response.Buffer = true;
                    Response.Clear();
                    Response.ContentType = mimetype;



                    //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.pdf", exportfilename));
                    Response.BinaryWrite(results);
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception e)
            {
                Response.Write(e.Message);
            }
        }
    }