How display var-binary data to PDF in MVC? - asp.net-mvc

how to display var-binary data to PDF in MVC. can you share anybody how to display var-binary data as PDF in MVC
here i tried in MVC, but not display PDF.
MVC Code:
[HttpPost]
public ActionResult ViewPDF()
{
string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
TempData["Embed"] = string.Format(embed, VirtualPathUtility.ToAbsolute("~/Files/1.pdf"));
return RedirectToAction("Index");
}
here is calling physical path, but i need to read and display var-binary so can anybody share idea?.,
one more thing i displayed var-binary to PDF in asp.net application but unable to display in MVC.
> Asp.net code samples:-
window.open('http://localhost:58158/AspForms/pdf.aspx' + '?id=' + id, '', 'width=800, height=650, top=0, left=250, status=0,toolbar=0');
>
pdf popup page:
protected void Page_Load(object sender, EventArgs e)
{
string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"800px\" height=\"550px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), Request.QueryString["id"]);
}
FileCS.ashx:-
<%# WebHandler Language="C#" Class="FileCS" %>
using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public class FileCS : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
#region
int id = int.Parse(context.Request.QueryString["Id"]);
byte[] bytes = { };
string fileName = "", allow = "N";
string constr = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=#Id and Enabled = 1";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["PDFFile"];
fileName = "Report";
allow = "A";
}
}
con.Close();
}
}
if (allow == "A")
{
context.Response.Buffer = true;
context.Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
}
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
else
{
}
#endregion
}
public bool IsReusable
{
get
{
return false;
}
}
}
but in MVC unable to display var-binary to PDF...

popup view:
#using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
{
View PDF
}
on Scan controller:-
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB(4);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=#Id and Enabled = 1";
cmd.Parameters.AddWithValue("#Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["Scan_Pdf_File"];
}
}
con.Close();
}
}
return bytes;
#endregion
}

Related

uploading and reading from an excel file in asp.net core 2

previously Asp.Net MVC had this third party library which easily allowed uploading and reading from an excel file called Excel Data Reader. We didn't need to have the file on the local disk, which was great because my application needs to run on Azure.
However we are now porting this functionality to asp.net core 2, and it seems from searching that this is not possible. Does anybody know any libraries that would allow me to do this? Please note, I am not looking for solutions that read from a disk. I want to upload an excel file and read data from the stream directly.
I Could Read Excel File In 'Asp .Net Core' By This Code.
Import And Export Data Using EPPlus.Core.
[HttpPost]
public IActionResult ReadExcelFileAsync(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("File Not Selected");
string fileExtension = Path.GetExtension(file.FileName);
if (fileExtension != ".xls" && fileExtension != ".xlsx")
return Content("File Not Selected");
var rootFolder = #"D:\Files";
var fileName = file.FileName;
var filePath = Path.Combine(rootFolder, fileName);
var fileLocation = new FileInfo(filePath);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
if (file.Length <= 0)
return BadRequest(GlobalValidationMessage.FileNotFound);
using (ExcelPackage package = new ExcelPackage(fileLocation))
{
ExcelWorksheet workSheet = package.Workbook.Worksheets["Table1"];
//var workSheet = package.Workbook.Worksheets.First();
int totalRows = workSheet.Dimension.Rows;
var DataList = new List<Customers>();
for (int i = 2; i <= totalRows; i++)
{
DataList.Add(new Customers
{
CustomerName = workSheet.Cells[i, 1].Value.ToString(),
CustomerEmail = workSheet.Cells[i, 2].Value.ToString(),
CustomerCountry = workSheet.Cells[i, 3].Value.ToString()
});
}
_db.Customers.AddRange(customerList);
_db.SaveChanges();
}
return Ok();
}
I tried this code below (without using libs) for ASP.NET Core and it worked:
public ActionResult OnPostUpload(List<IFormFile> files)
{
try
{
var file = files.FirstOrDefault();
var inputstream = file.OpenReadStream();
XSSFWorkbook workbook = new XSSFWorkbook(stream);
var FIRST_ROW_NUMBER = {{firstRowWithValue}};
ISheet sheet = workbook.GetSheetAt(0);
// Example: var firstCellRow = (int)sheet.GetRow(0).GetCell(0).NumericCellValue;
for (int rowIdx = 2; rowIdx <= sheet.LastRowNum; rowIdx++)
{
IRow currentRow = sheet.GetRow(rowIdx);
if (currentRow == null || currentRow.Cells == null || currentRow.Cells.Count() < FIRST_ROW_NUMBER) break;
var df = new DataFormatter();
for (int cellNumber = {{firstCellWithValue}}; cellNumber < {{lastCellWithValue}}; cellNumber++)
{
//business logic & saving data to DB
}
}
}
catch(Exception ex)
{
throw new FileFormatException($"Error on file processing - {ex.Message}");
}
}
if we are talking about Razor Pages, here's a simple sample that I tested today..
Environ: .NET Core 3.1, VS 2019
A simple class
public class UserModel
{
public string Name { get; set; }
public string City { get; set; }
}
Index.cshtml.cs
usings..
using ExcelDataReader;
public void OnPost(IFormFile file)
{
List<UserModel> users = new List<UserModel>();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (var stream = new MemoryStream())
{
file.CopyTo(stream);
stream.Position = 0;
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
while (reader.Read()) //Each row of the file
{
users.Add(new UserModel { Name = reader.GetValue(0).ToString(), City = reader.GetValue(1).ToString()});
}
}
}
//users // you got the values here
}
Mark up in View
<form id="form1" method="post" enctype="multipart/form-data">
<div class="text-center">
<input type="file" id="file1" name="file" />
</div>
<script>
document.getElementById('file1').onchange = function () {
document.getElementById('form1').submit();
};
</script>
You would require ExcelDataReader nuget package, I used 3.6.0 version
github working code
Latest versions of ExcelDataReader support netstandard2.0, thus work with ASP.NET Core 2. It also targets netstandard1.3, so works with ASP.NET Core 1.x as well.
(not sure what you searched that said it is not possible, but that is clearly wrong)
First upload your excel file and read the excel file record using asp.net core 3.1.
using System;
using Microsoft.AspNetCore.Mvc;
using ExcelFileRead.Models;
using Microsoft.AspNetCore.Hosting;
using System.IO;
using OfficeOpenXml;
using System.Linq;
namespace ExcelFileRead.Controllers
{
public class HomeController : Controller
{
private readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public ActionResult File()
{
FileUploadViewModel model = new FileUploadViewModel();
return View(model);
}
[HttpPost]
public ActionResult File(FileUploadViewModel model)
{
string rootFolder = _hostingEnvironment.WebRootPath;
string fileName = Guid.NewGuid().ToString() + model.XlsFile.FileName;
FileInfo file = new FileInfo(Path.Combine(rootFolder, fileName));
using (var stream = new MemoryStream())
{
model.XlsFile.CopyToAsync(stream);
using (var package = new ExcelPackage(stream))
{
package.SaveAs(file);
}
}
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
{
//return or alert message here
}
else
{
var rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
model.StaffInfoViewModel.StaffList.Add(new StaffInfoViewModel
{
FirstName = (worksheet.Cells[row, 1].Value ?? string.Empty).ToString().Trim(),
LastName = (worksheet.Cells[row, 2].Value ?? string.Empty).ToString().Trim(),
Email = (worksheet.Cells[row, 3].Value ?? string.Empty).ToString().Trim(),
});
}
}
}
return View(model);
}
}
}
For more details(step by step)
https://findandsolve.com/articles/how-to-read-column-value-from-excel-in-aspnet-core-or-best-way-to-read-write-excel-file-in-dotnet-core

How to route to static page with out change url path in asp.net mvc3

Basically,I'm trying to route to a static page like this:
http://127.0.0.1/mypage
=route to=>
A static page in my website folder maybe http://127.0.0.1/static/mypage.html
I have tried:
Add a route role:
routes.MapRoute("StaticPage", "{pagename}", new { controller = "Common", action = "StaticPage" });
Add an action in Common Controller:
public ActionResult StaticPage(string pagename)
{
return Redirect("/static/" + pagename + ".html");
}
But it will change the url and cause twice request, is there any other way(no iframe in view) to remain the url?
Write the file to the response and then return an EmptyResult.
public ActionResult StaticPage(string pagename)
{
Response.WriteFile(Url.Content(string.Format("/static/{0}.html", pagename)));
return new EmptyResult();
}
You could simply have your controller return the contents of the desired file like so:
public ActionResult StaticPage(String pageName) {
return Content(GetFileContents("/static/" + pageName + ".html"));
}
public static string GetFileContents(string FileName)
{
StreamReader sr = null;
string FileContents = null;
try
{
FileStream fs = new FileStream(FileName, FileMode.Open,
FileAccess.Read);
sr = new StreamReader(fs);
FileContents = sr.ReadToEnd();
}
finally
{
if(sr != null)
sr.Close();
}
return FileContents;
}

DevExpress GridView ExportToPdf doesn't export filtered data MVC

I have a webpage with gridview from Devexpress and i've implemented export to pdf. But somehow I don't get the current filter, order or group setting. I'm wondering if there is something wrong with how i set my setting in code or something since I've googled a lot at seems like those options should be handled automatically in ExportToPdf as long as you have rigth setting. My _GripPartial.cshtml:
#Html.DevExpress().GridView(TreeMenuTest.Controllers.LogViewController.GridViewSettings).Bind(TreeMenuTest.Controllers.LogViewController.DataSource).GetHtml()
_LogView.cshtml:
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>}
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#Html.Action("Grid","LogView")
And finally LogViewController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using TreeMenuTest.Models;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using System.Globalization;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxClasses;
using DevExpress.XtraPrinting;
using DevExpress.XtraPrintingLinks;
using System.IO;
using System.Drawing.Printing;
namespace TreeMenuTest.Controllers
{
public class LogViewController : Controller
{
//
// GET: /LogView/
public static List<LoggingEvent> DataSource;
static GridViewSettings exportGridViewSettings;
public static GridViewSettings GridViewSettings
{
get
{
if (exportGridViewSettings == null)
exportGridViewSettings = GetGridViewSettings();
return exportGridViewSettings;
}
}
static GridViewSettings GetGridViewSettings()
{
GridViewSettings settings = new GridViewSettings();
settings.Name = "GridView";
settings.CallbackRouteValues = new { Controller = "LogView", Action = "Grid" };
settings.Width = Unit.Percentage(100);
settings.Theme = "BlackGlass";
settings.KeyFieldName = "Id";
settings.SettingsPager.Visible = true;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = true;
settings.SettingsPager.PageSize = 25;
settings.SettingsBehavior.ColumnResizeMode = ColumnResizeMode.Control;
settings.Settings.ShowHeaderFilterButton = true;
settings.SettingsPopup.HeaderFilter.Height = 200;
settings.SettingsExport.Landscape = true;
settings.SettingsExport.TopMargin = 0;
settings.SettingsExport.LeftMargin = 0;
settings.SettingsExport.RightMargin = 0;
settings.SettingsExport.BottomMargin = 0;
settings.SettingsExport.PaperKind = PaperKind.A4;
settings.SettingsExport.RenderBrick = (sender, e) =>
{
if (e.RowType == GridViewRowType.Data && e.VisibleIndex % 2 == 0)
e.BrickStyle.BackColor = System.Drawing.Color.FromArgb(0xEE, 0xEE, 0xEE);
};
settings.Columns.Add("Id");
settings.Columns.Add(column =>
{
column.FieldName = "Ts";
column.Settings.AutoFilterCondition = AutoFilterCondition.Like;
});
settings.Columns.Add("LogLevelText").Caption = "Level";
settings.Columns.Add("LoggerName");
settings.Columns.Add("Message");
settings.Columns.Add("ThreadName").Caption = "Thread";
settings.Columns.Add("UserName");
settings.Columns.Add("Domain");
settings.Columns.Add("ClassName");
settings.Columns.Add("FileName");
settings.Columns.Add("MethodName").Caption = "Method";
settings.Columns.Add("LineNumber").Caption = "Line";
settings.Columns.Add("LocalIP");
settings.Columns.Add("MachineName").Caption = "Machine";
settings.Columns.Add("UnikeName");
settings.Settings.ShowPreview = true;
settings.PreviewFieldName = "ExceptionString";
return settings;
}
public ActionResult Index()
{
return PartialView("_LogView");
}
public ActionResult Grid()
{
if (DataSource == null)
{
DataSource = GetAllEventsLast24h();
}
return PartialView("_GridPartial");
}
public ActionResult EmptyGrid()
{
DataSource = null;
return PartialView("_GridPartial");
}
public List<LoggingEvent> GetAllEventsLast24h() {
return GetEventsWithCommand("where Ts > '" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsOnDateTime(DateTime fromDate, DateTime toDate)
{
return GetEventsWithCommand("where Ts > '" + fromDate.ToString("yyyy-MM-dd HH:mm:ss") + "' AND Ts < '" + toDate.ToString("yyyy-MM-dd HH:mm:ss") + "';");
}
public List<LoggingEvent> GetEventsWithCommand(string where)
{
List<LoggingEvent> events = new List<LoggingEvent>();
SqlConnection myConnection = new SqlConnection("Data Source=xxx;user id=xxx;password=xxx;connection timeout=30");
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand command = new SqlCommand("SELECT Id,Ts,LogLevel,LoggerName,Message,ThreadName,UserName,ExceptionString,Domain,ClassName,FileName,MethodName,LineNumber,LocalIP,MachinName,UnikeName from dbo.LoggingEvent " + where);
command.Connection = myConnection;
myReader = command.ExecuteReader();
while (myReader.Read())
{
events.Add(LoggingEvent.ReadEntityFromDbReader(myReader));
}
myConnection.Close();
return events;
}
[HttpPost]
public ActionResult ReloadGrid(string fromDate, string toDate)
{
DateTime fromDateTime;
DateTime toDateTime;
if (!string.IsNullOrEmpty(fromDate) && !string.IsNullOrEmpty(toDate)) // todo
{
fromDateTime = ParseStringToDate(fromDate);
toDateTime = ParseStringToDate(toDate);
}
else// No dates specified = get last 24 hours
{
toDateTime = DateTime.Now;
fromDateTime = toDateTime.AddHours(-24);
}
if (fromDateTime.CompareTo(toDateTime) > 0)
{
// from date grater then todate, change places
DateTime temp = toDateTime;
toDateTime = fromDateTime;
fromDateTime = temp;
}
DataSource = GetEventsOnDateTime(fromDateTime, toDateTime);
return PartialView("_LogView");
}
public DateTime ParseStringToDate(string datetxt)// todo this is copy froim treemenuviewcontroller, create utilsclass
{
const string dateformat = "dd.MM.yyyy HH:mm"; // jquery datepicker
const string dateformat2 = "yyyy-MM-dd HH:mm";// chrome TODO different formats with different location setting?
DateTime dateTime;
try //todo error handling!
{
dateTime = DateTime.ParseExact(datetxt, dateformat, CultureInfo.InvariantCulture);
}
catch
{
dateTime = DateTime.ParseExact(datetxt, dateformat2, CultureInfo.InvariantCulture);
}
return dateTime;
}
public ActionResult ExportToPDF()
{
var printable = GridViewExtension.CreatePrintableObject(GridViewSettings, DataSource);
PrintingSystem ps = new PrintingSystem();
PrintableComponentLink link1 = new PrintableComponentLink(ps);
link1.Component = printable;
link1.PrintingSystem.Document.AutoFitToPagesWidth = 1;
link1.Landscape = true;
CompositeLink compositeLink = new CompositeLink(ps);
compositeLink.Links.Add(link1);
compositeLink.CreateDocument();
using (MemoryStream stream = new MemoryStream())
{
compositeLink.PrintingSystem.ExportToPdf(stream);
WriteToResponse("filename", true, "pdf", stream);
}
ps.Dispose();
return Index();
}
void WriteToResponse(string fileName, bool saveAsFile, string fileFormat, MemoryStream stream)
{
string disposition = saveAsFile ? "attachment" : "inline";
Response.Clear();
Response.Buffer = false;
Response.AppendHeader("Content-Type", string.Format("application/{0}", fileFormat));
Response.AppendHeader("Content-Transfer-Encoding", "binary");
Response.AppendHeader("Content-Disposition",
string.Format("{0}; filename={1}.{2}", disposition, fileName, fileFormat));
Response.BinaryWrite(stream.GetBuffer());
Response.End();
}
}
}
Any clues?
Ps. Asking me why I don't write to DevExpress support is not helpful, so please just don't comment at all.
Check the How to export GridView rows and keep end-user modifications (such as sorting, grouping, filtering, selection) KB Article and make sure if all the steps are implemented.
After help for #Mikhail i fix the issue by putting #Html.Action("Grid","LogView") in the Html.BeginForm in _Log.View.cshtml like that:
<div id="buttonReset" class ="gridBtn">
<input type="button" id ="ResetBtn" value="Reset Grid" onclick="javascript: ResetGrid()"/>
</div>
#using (Html.BeginForm("ExportToPDF", "LogView", FormMethod.Post))
{
<div id="buttonExport" class ="gridBtn">
<input type="submit" id ="ExportBtn" value="Export to pdf" />
</div>
#Html.Action("Grid","LogView")}

Rendering an RDLC report in HTML in ASP.NET MVC

I would like to render an RDLC report in HTML within an ASP.NET MVC project.
I successfully made a prototype that renders an RDLC report in PDF, Excel, and TIFF image, with the help of this article. But I was surprised that HTML is not one of the default available formats in LocalReport.Render().
I came across this article, which describes a trick to enable the rendering format of HTML4.0, but I think that is only for a ReportViewer control (I could be wrong though).
The question is, in MVC how to render an RDLC report in HTML just like a ReportView does (see the screenshot below)?
This is a simple task. You can follow the following steps.
Create a folder in your solution and give a name Reports.
Add a ASP.Net web form and named it ReportView.aspx
Create a Class ReportData and add it to the Reports folder. Add the following code
to the Class.
public class ReportData
{
public ReportData()
{
this.ReportParameters = new List<Parameter>();
this.DataParameters = new List<Parameter>();
}
public bool IsLocal { get; set; }
public string ReportName { get; set; }
public List<Parameter> ReportParameters { get; set; }
public List<Parameter> DataParameters { get; set; }
}
public class Parameter
{
public string ParameterName { get; set; }
public string Value { get; set; }
}
Add another Class and named it ReportBasePage.cs. Add the following code in this Class.
public class ReportBasePage : System.Web.UI.Page
{
protected ReportData ReportDataObj { get; set; }
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (HttpContext.Current != null)
if (HttpContext.Current.Session["ReportData"] != null)
{
ReportDataObj = HttpContext.Current.Session["ReportData"] as ReportData;
return;
}
ReportDataObj = new ReportData();
CaptureRouteData(Page.Request);
}
private void CaptureRouteData(HttpRequest request)
{
var mode = (request.QueryString["rptmode"] + "").Trim();
ReportDataObj.IsLocal = mode == "local" ? true : false;
ReportDataObj.ReportName = request.QueryString["reportname"] + "";
string dquerystr = request.QueryString["parameters"] + "";
if (!String.IsNullOrEmpty(dquerystr.Trim()))
{
var param1 = dquerystr.Split(',');
foreach (string pm in param1)
{
var rp = new Parameter();
var kd = pm.Split('=');
if (kd[0].Substring(0, 2) == "rp")
{
rp.ParameterName = kd[0].Replace("rp", "");
if (kd.Length > 1) rp.Value = kd[1];
ReportDataObj.ReportParameters.Add(rp);
}
else if (kd[0].Substring(0, 2) == "dp")
{
rp.ParameterName = kd[0].Replace("dp", "");
if (kd.Length > 1) rp.Value = kd[1];
ReportDataObj.DataParameters.Add(rp);
}
}
}
}
}
Add ScriptManager to the ReportView.aspx page. Now Take a Report Viewer to the page. In report viewer set the property AsyncRendering="false". The code is given below.
<rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
Width="1271px" Height="1000px" >
</rsweb:ReportViewer>
Add two NameSpace in ReportView.aspx.cs
using Microsoft.Reporting.WebForms;
using System.IO;
Change the System.Web.UI.Page to ReportBasePage. Just replace your code using the following.
public partial class ReportView : ReportBasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RenderReportModels(this.ReportDataObj);
}
}
private void RenderReportModels(ReportData reportData)
{
RASolarERPData dal = new RASolarERPData();
List<ClosingInventoryValuation> objClosingInventory = new List<ClosingInventoryValuation>();
// Reset report properties.
ReportViewerRSFReports.Height = Unit.Parse("100%");
ReportViewerRSFReports.Width = Unit.Parse("100%");
ReportViewerRSFReports.CssClass = "table";
// Clear out any previous datasources.
this.ReportViewerRSFReports.LocalReport.DataSources.Clear();
// Set report mode for local processing.
ReportViewerRSFReports.ProcessingMode = ProcessingMode.Local;
// Validate report source.
var rptPath = Server.MapPath(#"./Report/" + reportData.ReportName +".rdlc");
//#"E:\RSFERP_SourceCode\RASolarERP\RASolarERP\Reports\Report\" + reportData.ReportName + ".rdlc";
//Server.MapPath(#"./Report/ClosingInventory.rdlc");
if (!File.Exists(rptPath))
return;
// Set report path.
this.ReportViewerRSFReports.LocalReport.ReportPath = rptPath;
// Set report parameters.
var rpPms = ReportViewerRSFReports.LocalReport.GetParameters();
foreach (var rpm in rpPms)
{
var p = reportData.ReportParameters.SingleOrDefault(o => o.ParameterName.ToLower() == rpm.Name.ToLower());
if (p != null)
{
ReportParameter rp = new ReportParameter(rpm.Name, p.Value);
ReportViewerRSFReports.LocalReport.SetParameters(rp);
}
}
//Set data paramater for report SP execution
objClosingInventory = dal.ClosingInventoryReport(this.ReportDataObj.DataParameters[0].Value);
// Load the dataSource.
var dsmems = ReportViewerRSFReports.LocalReport.GetDataSourceNames();
ReportViewerRSFReports.LocalReport.DataSources.Add(new ReportDataSource(dsmems[0], objClosingInventory));
// Refresh the ReportViewer.
ReportViewerRSFReports.LocalReport.Refresh();
}
}
Add a Folder to the Reports Folder and named it Report. Now add a RDLC report to the Reports/Report folder and named it ClosingInventory.rdlc.
Now add a Controller and Named it ReportController. In to the controller add the following action method.
public ActionResult ReportViewer()
{
ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
return View();
}
Add a view page click on the ReportViewer Controller. Named the view page ReportViewer.cshtml. Add the following code to the view page.
#using (Html.BeginForm("Login"))
{
#Html.DropDownList("ddlYearMonthFormat", new SelectList(ViewBag.YearMonthFormat, "YearMonthValue", "YearMonthName"), new { #class = "DropDown" })
Stock In Transit: #Html.TextBox("txtStockInTransit", "", new { #class = "LogInTextBox" })
<input type="submit" onclick="return ReportValidationCheck();" name="ShowReport"
value="Show Report" />
}
Add an Iframe. Set the property of the Iframe as follows
frameborder="0" width="1000"; height="1000"; style="overflow:hidden;" scrolling="no"
Add Following JavaScript to the viewer.
function ReportValidationCheck() {
var url = $('#hdUrl').val();
var yearmonth = $('#ddlYearMonthFormat').val();
var stockInTransit = $('#txtStockInTransit').val()
if (stockInTransit == "") {
stockInTransit = 0;
}
if (yearmonth == "0") {
alert("Please Select Month Correctly.");
}
else {
//url = url + "dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
url = "../Reports/ReportView.aspx?rptmode=local&reportname=ClosingInventory&parameters=dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
var myframe = document.getElementById("ifrmReportViewer");
if (myframe !== null) {
if (myframe.src) {
myframe.src = url;
}
else if (myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
myframe.contentWindow.location = url;
}
else { myframe.setAttribute('src', url); }
}
}
return false;
}
In Web.config file add the following key to the appSettings section add
key="UnobtrusiveJavaScriptEnabled" value="true"
In system.web handlers Section add the following key
add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
Change your data source as your own. This solution is very simple and I think every one enjoy it.
You can use the ReportViewer object to render an RDLC to PDF or HTML. For my case (below) I wanted a PDF document and I returned it as a FileContentResult ActionResult. If you want it to return as a download use the File ActionResult (I've commented that out for your use).
public ActionResult GetPackingSlipPDF(int shipmentId)
{
var shipment = _inboundShipmentService.GetInboundShipmentById(shipmentId);
Warning[] warnings;
string mimeType;
string[] streamids;
string encoding;
string filenameExtension;
var viewer = new ReportViewer();
viewer.LocalReport.ReportPath = #"Labels\PackingSlip.rdlc";
var shipLabel = new ShippingLabel { ShipmentId = shipment.FBAShipmentId, Barcode = GetBarcode(shipment.FBAShipmentId) };
viewer.LocalReport.DataSources.Add(new ReportDataSource("ShippingLabel", new List<ShippingLabel> { shipLabel }));
viewer.LocalReport.Refresh();
var bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return new FileContentResult(bytes, mimeType);
//return File(bytes, mimeType, shipment.FBAShipmentId + "_PackingSlip.pdf");
}

WebPart-Button Click

I have a table called Links.
two stored Procedures called sp_InsertLinks, sp_GetLinks.
I have simple webpart which takes two parameters and adds it the SQL Table call Links.
In The first Interface it displays the list of values from the database and a Button to ADD List.
When I click on the Link it displays next interface, where I can add txtbox for Link Name and Txtbox for Link URL.
And When I submit this The page is loading in the sequence of events of normal sharepoint lifecycle.
And I am unable to add the new links into the page because the button click method never gets fired.
Could any one have a look at this please?
The Code is :
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Text ;
using System.Data ;
using System.Data.SqlClient;
using System.Drawing;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace ContextMenuOptionsUsingJQuery
{
[Guid("7a3a52d4-9ad6-44b2-b96f-852da1a95371")]
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart
{
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
string Con_string = string.Empty;
Button btnAddLink;
Button btnAddNewLink;
StringBuilder outputDisplay;
TextBox txtLink;
TextBox txtLinkUrl;
Label lblDisplay = new Label();
public ContextMenuOptionsUsingJQuery()
{
}
protected override void CreateChildControls()
{
try
{
// Getting the Connection
ConnectionMethod();
// Calling the Appropraite Method or stored Procedures
RefreshData();
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
//New item
Controls.Add(btnAddLink);
}
catch (Exception e)
{
Label l = new Label();
l.Text = e.StackTrace;
Controls.Add(l);
}
}
// Button Add Link
private void btn_AddLink(Object sender, EventArgs e)
{
Controls.Clear();
btnAddNewLink = new Button();
txtLink = new TextBox();
txtLinkUrl = new TextBox();
Controls.Add(txtLink);
Controls.Add(txtLinkUrl);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
Controls.Add(btnAddNewLink);
}
private void btnAddNewLink_Click(Object sender, EventArgs e)
{
int i;
try
{
ConnectionMethod();
cmd.CommandText = "sp_InsertLinks";
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramLinkName = new SqlParameter("#LinkName", SqlDbType.VarChar, 50);
SqlParameter paramLinkUrl = new SqlParameter("#LinkUrl", SqlDbType.VarChar, 50);
paramLinkName.Direction = ParameterDirection.Input;
paramLinkUrl.Direction = ParameterDirection.Input;
paramLinkName.Value = txtLink.Text.ToString();
paramLinkUrl.Value = txtLinkUrl.Text.ToString();
cmd.Parameters.Add(paramLinkUrl);
cmd.Parameters.Add(paramLinkName);
i = cmd.ExecuteNonQuery();
con.Close();
ConnectionMethod();
RefreshData();
}
catch (Exception exp)
{
Label l = new Label();
l.Text = exp.StackTrace;
Controls.Add(l);
}
finally
{
con.Close();
}
}
private void RefreshData()
{
cmd.CommandText = "sp_GetLinks";
cmd.CommandType = CommandType.StoredProcedure;
dr = cmd.ExecuteReader();
outputDisplay = new System.Text.StringBuilder();
outputDisplay.AppendLine("<br/>");
// Fetching the Data from the Datareader object
while (dr.Read())
{
outputDisplay.AppendLine("" + dr[1] + "" + "<br/><br/>");
}
con.Close();
outputDisplay.AppendLine("<br/> <br/>");
lblDisplay.Text = outputDisplay.ToString();
Controls.Add(lblDisplay);
}
// Method to get the Connection
public void ConnectionMethod()
{
con = new SqlConnection();
cmd = new SqlCommand();
Con_string = "Data Source=servername;Initial Catalog=HariVMTest;Integrated Security=True";
con.ConnectionString = Con_string;
con.Open();
cmd.Connection = con;
}
}
}
Thank you
Hari
I would nearly always recommend creating all your controls in CreateChildControls()
Then you should use the Visible property to show and hide the controls as needed.
The code would then look something like this:
public class ContextMenuOptionsUsingJQuery : System.Web.UI.WebControls.WebParts.WebPart {
Button btnAddLink;
Button btnAddNewLink;
protected override void CreateChildControls() {
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
Controls.Add(btnAddLink);
btnAddNewLink.Text = "ADD NEW Link";
btnAddNewLink.Click += new EventHandler(btnAddNewLink_Click);
btnAddNewLink.Visible = false;
Controls.Add(btnAddNewLink);
}
private void btn_AddLink(Object sender, EventArgs e) {
btnAddLink.Visible = false;
}
private void btnAddNewLink_Click(Object sender, EventArgs e) {
}
}
If you do it this way, your events will more often than not, fire correctly.
i think you need to just add :
// Adding a New Link though the button
btnAddLink = new Button();
btnAddLink.Text = "Add Link";
btnAddLink.Click += new EventHandler(btn_AddLink);
before connectionmethod in createchildcontrol()
hope this works.

Resources