Exemplo n.º 1
0
 public static ReportExportResult ExportReportToFormat(ReportViewerModel model, ReportFormats format, int?startPage = 0, int?endPage = 0)
 {
     return(ExportReportToFormat(model, format.GetName(), startPage, endPage));
 }
Exemplo n.º 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)
        {
            var service = _initializeReportExecutionService(model);

            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         = "HTML4.0";
            var outputFormat   = $"<OutputFormat>{format}</OutputFormat>";
            var encodingFormat = $"<Encoding>{model.Encoding.EncodingName}</Encoding>";
            var htmlFragment   = ((format.ToUpper() == "HTML4.0" && model.UseCustomReportImagePath == false && model.ViewMode == ReportViewModes.View) ? "<HTMLFragment>true</HTMLFragment>" : "");
            var deviceInfo     = $"<DeviceInfo>{outputFormat}<Toolbar>False</Toolbar>{htmlFragment}</DeviceInfo>";

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

            var reportParameters = new List <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            service.ExecutionHeaderValue = executionHeader;

            ReportServiceExecution.ExecutionInfo executionInfo = null;
            string extension = null;
            string encoding  = null;
            string mimeType  = null;

            string[] streamIDs = null;
            ReportServiceExecution.Warning[] warnings = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReport(model.ReportPath, historyID);
                service.SetExecutionParameters(reportParameters.ToArray(), "en-us");

                var result = service.Render2(format, deviceInfo, ReportServiceExecution.PageCountMode.Actual, out extension, out mimeType, out encoding, out warnings, out streamIDs);

                executionInfo = service.GetExecutionInfo();

                return(service.FindString(startPage.ToInt32(), executionInfo.NumPages, searchText));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
Exemplo n.º 3
0
        private static ReportServiceExecution.ReportExecutionService _initializeReportExecutionService(ReportViewerModel model)
        {
            var service = new ReportServiceExecution.ReportExecutionService();

            service.Url         = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";
            service.Credentials = model.Credentials ?? System.Net.CredentialCache.DefaultCredentials;
            if (model.Timeout.HasValue)
            {
                service.Timeout = model.Timeout.Value;
            }

            return(service);
        }
        public static ReportExportResult ExportReportToFormat(ReportViewerModel model, string format, int?startPage = 0, int?endPage = 0)
        {
            var service = new ReportServiceExecution.ReportExecutionService();

            service.Url         = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";
            service.Credentials = model.Credentials ?? System.Net.CredentialCache.DefaultCredentials;

            var definedReportParameters = GetReportParameters(model, true);

            var exportResult = new ReportExportResult();

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

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

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

            var outputFormat = $"<OutputFormat>{format}</OutputFormat>";
            var htmlFragment = ((format.ToUpper() == "HTML4.0" && model.UseCustomReportImagePath == false && model.ViewMode == ReportViewModes.View) ? "<HTMLFragment>true</HTMLFragment>" : "");
            var deviceInfo   = $"<DeviceInfo>{outputFormat}<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 <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            service.ExecutionHeaderValue = executionHeader;

            ReportServiceExecution.ExecutionInfo executionInfo = null;
            string extension = null;
            string encoding  = null;
            string mimeType  = null;

            string[] streamIDs = null;
            ReportServiceExecution.Warning[] warnings = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReport(model.ReportPath, historyID);
                service.SetExecutionParameters(reportParameters.ToArray(), "en-us");

                var result = service.Render2(format, deviceInfo, ReportServiceExecution.PageCountMode.Actual, out extension, out mimeType, out encoding, out warnings, out streamIDs);

                executionInfo = service.GetExecutionInfo();

                exportResult.ReportData = result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.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 <ReportServiceExecution.Warning>() : warnings.ToList());

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

            return(exportResult);
        }
Exemplo n.º 5
0
        public static MvcHtmlString RenderReportViewer(this HtmlHelper helper, ReportViewerModel model, int?startPage = 1)
        {
            var sb = new StringBuilder();

            var reportServerDomainUri = new Uri(model.ServerUrl);
            var contentData           = ReportServiceHelpers.ExportReportToFormat(model, ReportFormats.Html4_0, startPage, startPage);

            sb.AppendLine("<form class='form-inline' id='frmReportViewer' name='frmReportViewer'>");
            sb.AppendLine("	<div class='ReportViewer row'>");
            sb.AppendLine("		<div class='ReportViewerHeader col-sm-12'>");
            sb.AppendLine("			<div class='ParametersContainer col-sm-12'>");
            sb.AppendLine("				<div class='Parameters col-sm-10'>");
            //Parameters start
            foreach (var reportParameter in contentData.Parameters)
            {
                sb.AppendLine("					<div class='Parameter col-md-6 col-sm-12'>");
                if (reportParameter.PromptUser || model.ShowHiddenParameters)
                {
                    sb.AppendLine($"						<div class='col-sm-4'><label for='{reportParameter.Name}'>{reportParameter.Prompt}</label></div>");

                    sb.AppendLine("							<div class='col-sm-8'>");
                    if (reportParameter.ValidValues != null && reportParameter.ValidValues.Any())
                    {
                        sb.AppendLine($"						<select id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' {(reportParameter.MultiValue == true ? "multiple='multiple'" : "")}>");
                        foreach (var value in reportParameter.ValidValues)
                        {
                            sb.AppendLine($"							<option value='{value.Value}' {(reportParameter.SelectedValues.Contains(value.Value) ? "selected='selected'" : "")}>{value.Key}</option>");
                        }
                        sb.AppendLine($"						</select>");
                    }
                    else
                    {
                        var selectedValue = reportParameter.SelectedValues.FirstOrDefault();

                        if (reportParameter.Type == ReportService.ParameterTypeEnum.Boolean)
                        {
                            sb.AppendLine($"						<input type='checkbox' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' {(selectedValue.ToBoolean() ? "checked='checked'" : "")} />");
                        }
                        else if (reportParameter.Type == ReportService.ParameterTypeEnum.DateTime)
                        {
                            sb.AppendLine($"						<input type='datetime' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' value='{selectedValue}' />");
                        }
                        else
                        {
                            sb.AppendLine($"						<input type='text' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' value='{selectedValue}' />");
                        }
                    }

                    sb.AppendLine("							</div>");
                }
                else
                {
                    if (reportParameter.ValidValues != null && reportParameter.ValidValues.Any())
                    {
                        var values = reportParameter.ValidValues.Where(x => x.Value != null).Select(x => x.Value).ToArray();
                        sb.AppendLine($"			<input type='hidden' id='{reportParameter.Name}' name='{reportParameter.Name}' value='{String.Join(",", values)}' />");
                    }
                    else
                    {
                        var selectedValue = reportParameter.SelectedValues.FirstOrDefault();

                        sb.AppendLine($"			<input type='hidden' id='{reportParameter.Name}' name='{reportParameter.Name}' value='{selectedValue}' />");
                    }
                }

                sb.AppendLine("					</div>");
            }

            sb.AppendLine("				</div>");

            sb.AppendLine("				<div class='ReportViewerViewReport col-sm-2 text-center'>");
            sb.AppendLine("					<button type='button' class='btn btn-primary ViewReport'>View Report</button>");
            sb.AppendLine("				</div>");
            sb.AppendLine("			</div>");

            sb.AppendLine("			<div class='ReportViewerToolbar col-sm-12'>");
            sb.AppendLine("				<div class='ReportViewerPager'>");
            sb.AppendLine("					<div class='btn-toolbar'>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine($"							<a href='#' title='First Page' class='btn btn-default FirstPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-step-backward'></span></a>");
            sb.AppendLine($"							<a href='#' title='Previous Page' class='btn btn-default PreviousPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-chevron-left'></span></a>");
            sb.AppendLine("						</div>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine($"							<span class='PagerNumbers'><input type='text' id='ReportViewerCurrentPage' name='ReportViewerCurrentPage' class='form-control' value='{contentData.CurrentPage}' /> of <span id='ReportViewerTotalPages'>{contentData.TotalPages}</span></span>");
            sb.AppendLine("						</div>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine($"							<a href='#' title='Next Page' class='btn btn-default NextPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-chevron-right'></span></a>");
            sb.AppendLine($"							<a href='#' title='Last Page' class='btn btn-default LastPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-step-forward'></span></a>");
            sb.AppendLine("						</div>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<span class='SearchText'>");
            sb.AppendLine($"								<input type='text' id='ReportViewerSearchText' name='ReportViewerSearchText' class='form-control' value='' />");
            sb.AppendLine($"								<a href='#' title='Find' class='btn btn-info FindTextButton'><span class='glyphicon glyphicon-search' style='padding-right: .5em;'></span>Find</a>");
            sb.AppendLine("							</span>");
            sb.AppendLine("						</div>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Export' class='dropdown-toggle btn btn-default' data-toggle='dropdown' role='button' aria-haspopup='true' area-expanded='false'>");
            sb.AppendLine("								<span class='glyphicon glyphicon-floppy-save' style='color: steelblue;'></span>");
            sb.AppendLine("								<span class='caret'></span>");
            sb.AppendLine("							</a>");
            sb.AppendLine("							<ul class='dropdown-menu'>");
            sb.AppendLine("								<li><a href='#' class='ExportCsv'>CSV (comma delimited)</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportExcelOpenXml'>Excel</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportMhtml'>MHTML (web archive)</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportPdf'>PDF</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportTiff'>TIFF file</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportWordOpenXml'>Word</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportXml'>XML file with report data</a></li>");
            sb.AppendLine("							</ul>");
            //sb.AppendLine("						</div>");
            //sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Refresh' class='btn btn-default Refresh'><span class='glyphicon glyphicon-refresh' style='color: green;'></span></a>");
            //sb.AppendLine("						</div>");
            //sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Print' class='btn btn-default Print'><span class='glyphicon glyphicon-print' style='color: grey;'></span></a>");
            sb.AppendLine("						</div>");
            sb.AppendLine("					</div>");
            sb.AppendLine("				</div>");
            sb.AppendLine("			</div>");
            sb.AppendLine("		</div>");
            sb.AppendLine("		<div class='ReportViewerContentContainer'>");
            sb.AppendLine("			<div class='ReportViewerContent'>");

            if (contentData.ReportData == null || contentData.ReportData.Length == 0)
            {
                sb.AppendLine("");
            }
            else
            {
                var content = Encoding.ASCII.GetString(contentData.ReportData);

                if (model.UseCustomReportImagePath && model.ReportImagePath.HasValue())
                {
                    content = ReportServiceHelpers.ReplaceImageUrls(model, content);
                }

                sb.AppendLine($"			{content}");
            }

            sb.AppendLine("			</div>");
            sb.AppendLine("		</div>");
            sb.AppendLine("	</div>");
            sb.AppendLine("</form>");

            return(new MvcHtmlString(sb.ToString()));
        }
Exemplo n.º 6
0
        public static string ParametersToHtmlString(System.Collections.Generic.List <ReportParameterInfo> parameters, ReportViewerModel model)
        {
            StringBuilder sb = new StringBuilder();

            if (parameters == null)
            {
                var contentData       = new ReportExportResult();
                var definedParameters = ReportServiceHelpers.GetReportParameters(model, true);
                contentData.SetParameters(definedParameters, model.Parameters);
                parameters = contentData.Parameters;
            }

            //Parameters start
            foreach (var reportParameter in parameters)
            {
                sb.AppendLine("					<div class='Parameter col-md-6 col-sm-12'>");
                if (reportParameter.PromptUser || model.ShowHiddenParameters)
                {
                    sb.AppendLine($"						<div class='col-sm-4'><label for='{reportParameter.Name}'>{reportParameter.Prompt.HtmlEncode()}</label></div>");

                    sb.AppendLine("							<div class='col-sm-8'>");
                    if (reportParameter.ValidValues != null && reportParameter.ValidValues.Any())
                    {
                        sb.AppendLine($"						<select id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' {(reportParameter.MultiValue == true ? "multiple='multiple'" : "")}>");
                        foreach (var value in reportParameter.ValidValues)
                        {
                            sb.AppendLine($"							<option value='{value.Value}' {(reportParameter.SelectedValues.Contains(value.Value) ? "selected='selected'" : "")}>{value.Label.HtmlEncode()}</option>");
                        }
                        sb.AppendLine($"						</select>");
                    }
                    else
                    {
                        var selectedValue = reportParameter.SelectedValues.FirstOrDefault();

                        if (reportParameter.Type == ReportService.ParameterTypeEnum.Boolean)
                        {
                            sb.AppendLine($"						<input type='checkbox' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' {(selectedValue.ToBoolean() ? "checked='checked'" : "")} />");
                        }
                        else if (reportParameter.Type == ReportService.ParameterTypeEnum.DateTime)
                        {
                            sb.AppendLine($"						<input type='datetime' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' value='{selectedValue}' />");
                        }
                        else
                        {
                            sb.AppendLine($"						<input type='text' id='{reportParameter.Name}' name='{reportParameter.Name}' class='form-control' value='{selectedValue}' />");
                        }
                    }

                    sb.AppendLine("							</div>");
                }
                else
                {
                    if (reportParameter.SelectedValues != null && reportParameter.SelectedValues.Any())
                    {
                        var values = reportParameter.SelectedValues.Where(x => x != null).Select(x => x).ToArray();
                        sb.AppendLine($"			<input type='hidden' id='{reportParameter.Name}' name='{reportParameter.Name}' value='{String.Join(",", values)}' />");
                    }
                }

                sb.AppendLine($"			<input type='hidden' id='ReportViewerEnablePaging' name='ReportViewerEnablePaging' value='{model.EnablePaging}' />");

                sb.AppendLine("					</div>");
            }

            return(sb.ToString());
        }
        /// <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)
        {
            var service = new ReportServiceExecution.ReportExecutionService();

            service.Url         = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";
            service.Credentials = model.Credentials ?? System.Net.CredentialCache.DefaultCredentials;

            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 deviceInfo = $"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";

            var reportParameters = new List <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            service.ExecutionHeaderValue = executionHeader;

            ReportServiceExecution.ExecutionInfo executionInfo = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReport(model.ReportPath, historyID);
                service.SetExecutionParameters(reportParameters.ToArray(), "en-us");

                return(service.FindString(startPage.ToInt32(), executionInfo.NumPages, searchText));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
Exemplo n.º 8
0
        public static MvcHtmlString RenderReportViewer(this HtmlHelper helper, ReportViewerModel model, int?startPage = 1)
        {
            var sb = new StringBuilder();

            var reportServerDomainUri = new Uri(model.ServerUrl);
            var contentData           = ReportServiceHelpers.ExportReportToFormat(model, ReportFormats.Html4_0, startPage, startPage);

            sb.AppendLine("<form class='form-inline' id='frmReportViewer' name='frmReportViewer'>");
            sb.AppendLine("	<div class='ReportViewer row'>");
            sb.AppendLine("		<div class='ReportViewerHeader row'>");
            sb.AppendLine("			<div class='ParametersContainer col-sm-12'>");
            sb.AppendLine("				<div class='Parameters col-sm-10'>");

            sb.AppendLine(ParametersToHtmlString(contentData.Parameters, model));

            sb.AppendLine("				</div>");

            sb.AppendLine("				<div class='ReportViewerViewReport col-sm-2 text-center'>");
            sb.AppendLine("					<button type='button' class='btn btn-primary ViewReport'>View Report</button>");
            sb.AppendLine("				</div>");
            sb.AppendLine("			</div>");

            sb.AppendLine("			<div class='ReportViewerToolbar row'>");
            sb.AppendLine("				<div class='ReportViewerPager'>");
            sb.AppendLine("					<div class='btn-toolbar'>");

            if (model.EnablePaging)
            {
                sb.AppendLine("						<div class='btn-group'>");
                sb.AppendLine($"							<a href='#' title='First Page' class='btn btn-default FirstPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-step-backward'></span></a>");
                sb.AppendLine($"							<a href='#' title='Previous Page' class='btn btn-default PreviousPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-chevron-left'></span></a>");
                sb.AppendLine("						</div>");
                sb.AppendLine("						<div class='btn-group'>");
                sb.AppendLine($"							<span class='PagerNumbers'><input type='text' id='ReportViewerCurrentPage' name='ReportViewerCurrentPage' class='form-control' value='{contentData.CurrentPage}' /> of <span id='ReportViewerTotalPages'>{contentData.TotalPages}</span></span>");
                sb.AppendLine("						</div>");
                sb.AppendLine("						<div class='btn-group'>");
                sb.AppendLine($"							<a href='#' title='Next Page' class='btn btn-default NextPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-chevron-right'></span></a>");
                sb.AppendLine($"							<a href='#' title='Last Page' class='btn btn-default LastPage'{(contentData.TotalPages == 1 ? " disabled='disabled'" : "")}><span class='glyphicon glyphicon-step-forward'></span></a>");
                sb.AppendLine("						</div>");
            }

            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<span class='SearchText'>");
            sb.AppendLine($"								<input type='text' id='ReportViewerSearchText' name='ReportViewerSearchText' class='form-control' value='' />");
            sb.AppendLine($"								<a href='#' title='Find' class='btn btn-info FindTextButton'><span class='glyphicon glyphicon-search' style='padding-right: .5em;'></span>Find</a>");
            sb.AppendLine("							</span>");
            sb.AppendLine("						</div>");
            sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Export' class='dropdown-toggle btn btn-default' data-toggle='dropdown' role='button' aria-haspopup='true' area-expanded='false'>");
            sb.AppendLine("								<span class='glyphicon glyphicon-floppy-save' style='color: steelblue;'></span>");
            sb.AppendLine("								<span class='caret'></span>");
            sb.AppendLine("							</a>");
            sb.AppendLine("							<ul class='dropdown-menu'>");
            sb.AppendLine("								<li><a href='#' class='ExportCsv'>CSV (comma delimited)</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportExcelOpenXml'>Excel</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportMhtml'>MHTML (web archive)</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportPdf'>PDF</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportTiff'>TIFF file</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportWordOpenXml'>Word</a></li>");
            sb.AppendLine("								<li><a href='#' class='ExportXml'>XML file with report data</a></li>");
            sb.AppendLine("							</ul>");
            //sb.AppendLine("						</div>");
            //sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Refresh' class='btn btn-default Refresh'><span class='glyphicon glyphicon-refresh' style='color: green;'></span></a>");
            //sb.AppendLine("						</div>");
            //sb.AppendLine("						<div class='btn-group'>");
            sb.AppendLine("							<a href='#' title='Print' class='btn btn-default Print'><span class='glyphicon glyphicon-print' style='color: grey;'></span></a>");
            sb.AppendLine("						</div>");
            sb.AppendLine("					</div>");
            sb.AppendLine("				</div>");
            sb.AppendLine("			</div>");
            sb.AppendLine("		</div>");
            sb.AppendLine("		<div class='ReportViewerContentContainer row'>");
            sb.AppendLine("			<div class='ReportViewerContent'>");

            if (model.IsMissingAnyRequiredParameterValues(contentData.Parameters))
            {
                sb.AppendLine("			<div class='ReportViewerInformation'>Please fill parameters and run the report...</div>");
            }
            else
            {
                if (model.AjaxLoadInitialReport)
                {
                    sb.AppendLine("			<script type='text/javascript'>$(document).ready(function () { viewReportPage(1); });</script>");
                }
                else
                {
                    if (contentData == null || contentData.ReportData == null || contentData.ReportData.Length == 0)
                    {
                        sb.AppendLine("");
                    }
                    else
                    {
                        var content = model.Encoding.GetString(contentData.ReportData);

                        if (model.UseCustomReportImagePath && model.ReportImagePath.HasValue())
                        {
                            content = ReportServiceHelpers.ReplaceImageUrls(model, content);
                        }

                        sb.AppendLine($"			{content}");
                    }
                }
            }

            sb.AppendLine("			</div>");
            sb.AppendLine("		</div>");
            sb.AppendLine("	</div>");
            sb.AppendLine("</form>");

            sb.AppendLine("<script type='text/javascript'>");
            sb.AppendLine("	function ReportViewer_Register_OnChanges() {");

            var dependencyFieldKeys = new List <string>();

            foreach (var parameter in contentData.Parameters.Where(x => x.Dependencies != null && x.Dependencies.Any()))
            {
                foreach (var key in parameter.Dependencies)
                {
                    if (!dependencyFieldKeys.Contains(key))
                    {
                        dependencyFieldKeys.Add(key);
                    }
                }
            }

            foreach (var queryParameter in contentData.Parameters.Where(x => dependencyFieldKeys.Contains(x.Name)))
            {
                sb.AppendLine("		$('#"+ queryParameter.Name + "').change(function () {");
                sb.AppendLine("			reloadParameters();");
                sb.AppendLine("		});");
            }

            sb.AppendLine("	}");

            sb.AppendLine("</script>");

            return(new MvcHtmlString(sb.ToString()));
        }
        /// <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)
        {
            var url = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";

            var basicHttpBinding = _initializeHttpBinding();
            var service          = new ReportServiceExecution.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);

            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 deviceInfo = $"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";

            var reportParameters = new List <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            ReportServiceExecution.ExecutionInfo executionInfo = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReportAsync(model.ReportPath, historyID).Result;
                executionHeader.ExecutionID = executionInfo.ExecutionID;
                var executionParameterResult = service.SetReportParameters(executionInfo.ExecutionID, reportParameters.ToArray(), "en-us").Result;

                return(service.FindString(executionInfo.ExecutionID, startPage.ToInt32(), executionInfo.NumPages, searchText).Result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
        public static ReportExportResult ExportReportToFormat(ReportViewerModel model, string format, int?startPage = 0, int?endPage = 0)
        {
            var definedReportParameters = GetReportParameters(model, true);

            var url = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";

            var basicHttpBinding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly);

            basicHttpBinding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
            basicHttpBinding.MaxReceivedMessageSize = int.MaxValue;
            var service = new ReportServiceExecution.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);

            var exportResult = new ReportExportResult();

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

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

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

            var outputFormat = $"<OutputFormat>{format}</OutputFormat>";
            var htmlFragment = ((format.ToUpper() == "HTML4.0" && model.UseCustomReportImagePath == false && model.ViewMode == ReportViewModes.View) ? "<HTMLFragment>true</HTMLFragment>" : "");
            var deviceInfo   = $"<DeviceInfo>{outputFormat}<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 <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            ReportServiceExecution.ExecutionInfo executionInfo = null;
            string extension = null;
            string encoding  = null;
            string mimeType  = null;

            string[] streamIDs = null;
            ReportServiceExecution.Warning[] warnings = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReportAsync(model.ReportPath, historyID).Result;
                executionHeader.ExecutionID = executionInfo.ExecutionID;

                var executionParameterResult = service.SetReportParameters(executionInfo.ExecutionID, reportParameters.ToArray(), "en-us").Result;

                var renderRequest = new ReportServiceExecution.Render2Request(format, deviceInfo, ReportServiceExecution.PageCountMode.Actual);
                var result        = service.Render2(executionInfo.ExecutionID, renderRequest).Result;

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

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

                exportResult.ReportData = result.Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.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 <ReportServiceExecution.Warning>() : warnings.ToList());

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

            return(exportResult);
        }
        /// <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)
        {
            var url = model.ServerUrl + ((model.ServerUrl.ToSafeString().EndsWith("/")) ? "" : "/") + "ReportExecution2005.asmx";

            var basicHttpBinding = _initializeHttpBinding(url, model);
            var service          = new ReportServiceExecution.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);*/
            service.ClientCredentials.UserName.UserName = model.Domain + "\\" + model.Username;
            service.ClientCredentials.UserName.Password = model.Password;
            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         = "HTML4.0";
            var outputFormat   = $"<OutputFormat>{format}</OutputFormat>";
            var encodingFormat = $"<Encoding>{model.Encoding.EncodingName}</Encoding>";
            var htmlFragment   = ((format.ToUpper() == "HTML4.0" && 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 <ReportServiceExecution.ParameterValue>();

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

                    addedParameter = true;
                }

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

            var executionHeader = new ReportServiceExecution.ExecutionHeader();

            ReportServiceExecution.ExecutionInfo executionInfo = null;
            string extension = null;
            string encoding  = null;
            string mimeType  = null;

            string[] streamIDs = null;
            ReportServiceExecution.Warning[] warnings = null;

            try
            {
                string historyID = null;
                executionInfo = service.LoadReportAsync(model.ReportPath, historyID).Result;
                executionHeader.ExecutionID = executionInfo.ExecutionID;
                var executionParameterResult = service.SetReportParameters(executionInfo.ExecutionID, reportParameters.ToArray(), "en-us").Result;

                var renderRequest = new ReportServiceExecution.Render2Request(format, deviceInfo, ReportServiceExecution.PageCountMode.Actual);
                var result        = service.Render2(executionInfo.ExecutionID, renderRequest).Result;

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

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

                return(service.FindString(executionInfo.ExecutionID, startPage.ToInt32(), executionInfo.NumPages, searchText).Result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(0);
        }
        private static System.ServiceModel.HttpBindingBase _initializeHttpBinding(string url, ReportViewerModel model)
        {
            if (url.ToLower().StartsWith("https"))
            {
                var binding = new System.ServiceModel.BasicHttpsBinding(System.ServiceModel.BasicHttpsSecurityMode.Transport);
                binding.Security.Transport.ClientCredentialType = model.ClientCredentialType;
                binding.MaxReceivedMessageSize = int.MaxValue;
                if (model.Timeout.HasValue)
                {
                    if (model.Timeout == System.Threading.Timeout.Infinite)
                    {
                        binding.CloseTimeout   = TimeSpan.MaxValue;
                        binding.OpenTimeout    = TimeSpan.MaxValue;
                        binding.ReceiveTimeout = TimeSpan.MaxValue;
                        binding.SendTimeout    = TimeSpan.MaxValue;
                    }
                    else
                    {
                        binding.CloseTimeout   = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.OpenTimeout    = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.ReceiveTimeout = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.SendTimeout    = new TimeSpan(0, 0, model.Timeout.Value);
                    }
                }

                return(binding);
            }
            else
            {
                var binding = new System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly);
                binding.Security.Transport.ClientCredentialType = model.ClientCredentialType;
                binding.MaxReceivedMessageSize = int.MaxValue;
                if (model.Timeout.HasValue)
                {
                    if (model.Timeout == System.Threading.Timeout.Infinite)
                    {
                        binding.CloseTimeout   = TimeSpan.MaxValue;
                        binding.OpenTimeout    = TimeSpan.MaxValue;
                        binding.ReceiveTimeout = TimeSpan.MaxValue;
                        binding.SendTimeout    = TimeSpan.MaxValue;
                    }
                    else
                    {
                        binding.CloseTimeout   = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.OpenTimeout    = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.ReceiveTimeout = new TimeSpan(0, 0, model.Timeout.Value);
                        binding.SendTimeout    = new TimeSpan(0, 0, model.Timeout.Value);
                    }
                }

                return(binding);
            }
        }