I am currently writing an addition to a website that I made for work. It generates a PDF from an HTML template and then serves it to the browser so that it can be printed off.
I created a small test that works perfectly. The problem I am running into is when I coded a more complete test, nothing happens when I click the generate button. In the first page when the page loads the PDF is created and shows in the browser. On the second page I get nothing, and no error message which makes troubleshooting this difficult. The code is almost identical between the two pages, so I am really confused as to what is happening.
I will post both versions of my code. Hopefully you guys can figure out what is happening.
Working Page
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Server.MapPath("/test.pdf");
string html = "<h1>Hello World</h1>";
PdfSharp.Pdf.PdfDocument my_pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.Letter);
my_pdf.Save(filePath);
byte[] docStream = System.IO.File.ReadAllBytes(filePath);
Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=test.pdf");
Response.AddHeader("Content-Length", docStream.GetLength(0).ToString());
Response.BinaryWrite(docStream);
Response.End();
System.IO.File.Delete(filePath);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Non Working Page
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
frmMain.Style.Add(HtmlTextWriterStyle.Width, "900px");
frmMain.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
frmMain.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
tblForm.Style.Add(HtmlTextWriterStyle.MarginRight, "auto");
tblForm.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto");
}
protected void generate_pdf(object sender, EventArgs e)
{
string html_page = System.IO.File.ReadAllText(Server.MapPath("/nice_letter.html"));
string filePath = Server.MapPath($"/{RandomString(10, true)}.pdf");
html_page = html_page.Replace("{{letter_date}}", txtLetterDate.Text);
html_page = html_page.Replace("{{recipient_name}}", txtRecipientName.Text);
html_page = html_page.Replace("{{patient_name}}", txtPatientName.Text);
html_page = html_page.Replace("{{appointment_date}}", txtAppointmentDate.Text);
PdfSharp.Pdf.PdfDocument my_pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html_page, PdfSharp.PageSize.Letter);
my_pdf.Save(filePath);
byte[] docStream = System.IO.File.ReadAllBytes(filePath);
Response.ClearContent();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline; filename=letter.pdf");
Response.AddHeader("Content-Length", docStream.GetLength(0).ToString());
Response.BinaryWrite(docStream);
Response.End();
System.IO.File.Delete(filePath);
}
public string RandomString(int size, bool lowerCase = false)
{
Random _random = new Random();
var builder = new StringBuilder(size);
char offset = lowerCase ? 'a' : 'A';
const int lettersOffset = 26;
for (var i = 0; i < size; i++)
{
var #char = (char)_random.Next(offset, offset + lettersOffset);
builder.Append(#char);
}
return lowerCase ? builder.ToString().ToLower() : builder.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="frmMain" runat="server">
<center><h1>Nice Letter</h1></center>
<asp:ScriptManager ID="smMain" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upMain" runat="server">
<ContentTemplate>
<table id="tblForm" runat="server">
<tr>
<td><asp:Label ID="lblLetterDate" Text="Letter Date: " runat="server"></asp:Label></td>
<td><asp:TextBox ID="txtLetterDate" Width="150" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblRecipientName" Text="Recipient: " runat="server"></asp:Label></td>
<td><asp:TextBox ID="txtRecipientName" Width="300" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblPatientName" Text="Patient Name: " runat="server"></asp:Label></td>
<td><asp:TextBox ID="txtPatientName" Width="300" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="lblAppointmentDate" Text="Appointment Date: " runat="server"></asp:Label></td>
<td><asp:TextBox ID="txtAppointmentDate" Width="150" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="cmdCreatePDF" runat="server" Text="Create PDF" OnClick="generate_pdf" /></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
I figured out the problem. Apparently it was because I was doing an ajax request via the update panels. It works fine without the ajax.
Related
I appreciate this is a common occurrence, however I've tried some of the solutions and none of worked thus far. My project is a 'Web Site' within Visual Studio, thus I don't have the option to 'Right Click and Crete new application'.
The labelID names from my aspx file cannot be read in the corresponding .cs file - flags up with syntax errors.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtCity" runat="server" Text="" />
<asp:Button Text="Get Weather Forecast" runat="server" OnClick="GetWeatherInfo" Width="207px" />
<hr />
<asp:Repeater ID="Repeater_weatherReports" runat="server">
<ItemTemplate>
<table id="tblWeather" runat="server" border="0" visible="false">
<tr>
<th>
Weather Info
</th>
</tr>
<tr>
<td>
<asp:Label runat="server" ID="lblCity_Country" Text='<%# Eval("city.name") %>' />
humidity:<asp:Label runat="server" ID="Label_humidity" Text='<%# Eval("main.humidity") %>' />
</td>
</tr>
<tr>
<td>
min:<asp:Label runat="server" ID="Label_min" Text='<%# Eval("main.temp_min") %>' />
max:<asp:Label runat="server" ID="Label_max" Text='<%# Eval("main.temp_max") %>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
A strange thing is, I can't even see the labelIDs if I click on the 'Design' view. See screenshot. Am I supposed to see the labelIDs here?
Any help will be much appreciated, Thanks
Edit - heres my c# code. Must I loop over RepeatItems somehow?
WeatherInfo weatherinfo = serializer.Deserialize<WeatherInfo>(json);
Repeater_weatherReports.DataSource = weatherinfo.list;
Repeater_weatherReports.DataBind();
int i = 0;
foreach (List list in weatherinfo.list)
{
lblCity_Country = weatherinfo.city.name;
//lblDescription.Text = weatherinfo.list[0].weather[0].description;
Label_min = string.Format("{0}", Math.Round(weatherinfo.list[i].main.temp_min, 1));
Label_max = string.Format("{0}", Math.Round(weatherinfo.list[i].main.temp_max, 1));
Label_humidity = weatherinfo.list[i].main.humidity.ToString();
tblWeather.Visible = true;
i++;
}
You can not access direct to label that is inside of repeater or gridview or other data binding controls. You can use events of repeater to access them. e.x:
<asp:repeater onitemcreated="methodnameToCall1" onitemdatabind="methodnameToCall2" >
and find labels by findcontrol method in c#:
void methodnameToCall1(object s,typeofitemcreatedEventsArgs e){
if(e.itemtype == dataitemtype){
var lbl = e.item.findcontrol("lblId") as Label;
}
}
It is semi code, because wrote in stack android app!
Excuseme!
For starters, you can mark table visible="true". Then, you will be able to see the repeater atleast in design view.
protected void Repeater_weatherReports_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
Label lblmin = (Label)item.FindControl("Label_min");
Label lblmax = (Label)item.FindControl("Label_max");
//.........and you can set of get values here.
}
}
In your aspx page, in the line where asp:Repeater is defined, you can add
OnItemDataBound="Repeater_weatherReports_ItemDataBound", it will start working.
My html code is this
<asp:Image ID="Img_CreateUser" runat="server"/>
<asp:FileUpload ID="Upload_CreateUser" runat="server" />
My C# code is this
byte[] ImgArr = null;
if(Upload_CreateUser.PostedFile != null)
{
HttpPostedFile File = (HttpPostedFile)Upload_CreateUser.PostedFile;
string Filename = Path.GetFileName(Upload_CreateUser.FileName);
Upload_CreateUser.SaveAs(Server.MapPath("~/") + Filename);
//byte[] filebytes = Upload_CreateUser.FileBytes;
using(FileStream filestream = new FileStream(Filename, FileMode.Open, FileAccess.Read))
{
ImgArr = new byte[filestream.Length];
int ImgReadArr = filestream.Read(ImgArr, 0, (int)filestream.Length);
if(ImgArr != null && ImgArr.Length > 0)
{
string ImgType = File.ContentType;
string base64string = Convert.ToBase64String(ImgArr, 0, ImgArr.Length);
Img_CreateUser.ImageUrl = "data:" +ImgType+ ";base64," + base64string;
}
`
I dont want to save my image into database. I just want to preview it.
Thanks
Use following code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Preview Image While Upload</title>
<script src="jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowPreview(input) {
if (input.files && input.files[0]) {
var ImageDir = new FileReader();
ImageDir.onload = function(e) {
$('#impPrev').attr('src', e.target.result);
}
ImageDir.readAsDataURL(input.files[0]);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table cellpadding="10" cellspacing="4" width="70%" align="center" style="border: Solid 10px Green;
font-weight: bold; font-size: 16pt; background-color: Skyblue; color: Blue;">
<tr>
<td align="center">
Upload Images
</td>
</tr>
<tr>
<td>
Select Your File To Upload #:
<input type="file" name="ImageUpload" id="ImageUpload" onchange="ShowPreview(this)" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
</td>
</tr>
<tr>
<td>
<asp:Image ID="impPrev" runat="server" Height="200px" />
</td>
</tr>
</table>
</form>
</body>
</html>
For more details Go through the link it will help you
Preview Image Before Uploading
<script type="text/javascript">
function previewFile() {
var preview = document.querySelector('#<%=ImgPropertyGroupImageAdd.ClientID %>');
var file = document.querySelector('#<%=InputPropertyGroupImageAdd.ClientID %>').files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
</script>
<asp:Image ID="ImgPropertyGroupImageAdd" runat="server" Width="200px" Height="200px" ImageUrl="~/Images/Open.png" />
<asp:FileUpload ID="InputPropertyGroupImageAdd" type="file" onchange="previewFile()" runat="server" />
I am trying to access an asp label field properties from c# code, and it keeps giving me the error:
The name 'lblTest' does not exist in the current context.
This is happening on my login.aspx page when calling the 'ValidateEmail' method.
There are no associated .cs files, just a login.master page.
I have a business request requiring me to modify someone elses code for enhancement, and I am guessing this has something to do with the existing content structure of .
I have tried placing this in master file, outside of the structure, etc. Still no joy.
Here is the login.aspx code:
<%# Page Language="C#" MasterPageFile="~/Masters/Login.master" AutoEventWireup="true" Culture="auto" UICulture="auto" EnableEventValidation="false" %>
<%# Import Namespace="Internal.Platform.Diagnostics" %>
<%# Import Namespace="Internal.Web" %>
<%# Import Namespace="Internal.Trial" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Web.Controls" Namespace="Internal.Web.Controls.ScriptResourceProvider" TagPrefix="Internal" %>
<%# Register Assembly="Internal.Trial" Namespace="Internal.Trial" TagPrefix="InternalTrial" %>
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="ContentPlaceHolderArea">
<script type="text/javascript">
</script>
<asp:Label ID="lblTest" runat="server"></asp:Label>
<asp:Login ID="intLogin" runat="server" DestinationPageUrl="Default.aspx"
OnPreRender="PreRender" Font-Names="Arial,Verdana,Sans-sarif" Font-Size="0.8em"
ForeColor="#000000">
<LayoutTemplate>
<div id="logoContainer">
<div class="logo"><img src="images/icons/logo.png" width="680" height="100"></div>
</div>
<div id="logonContainer">
<div>
<div class="LoginBtn1" onclick="lgnUser('pam')">Admin - Pam</div>
<div class="User1"><img src="images/icons/user1.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('lee')">Sales - Lee</div>
<div class="User2"><img src="images/icons/user2.png" width="80" height="80"></div>
</div>
<div>
<div class="LoginBtn1" onclick="lgnUser('samantha')">Support - Samantha</div>
<div class="User1"><img src="images/icons/user3.png" width="80" height="80"></div>
<div class="LoginBtn2" onclick="lgnUser('larry')">Marketing - Larry</div>
<div class="User2"><img src="images/icons/user4.png" width="80" height="80"></div>
</div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1"
OnServerValidate="ValidateEmail" ValidationGroup="ValidateGp"
ErrorMessage="This is a custom error validator" runat="server"/>
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/>
<%-- These are hidden controls used for the login process --%>
<asp:TextBox ID="UserName" runat="server" style="display: none;"></asp:TextBox>
<asp:CustomValidator ID="UserNameRequired" ValidateEmptyText="True" OnServerValidate="ValidateUserName"
ClientValidationFunction="" runat="server" ControlToValidate="UserName" ErrorMessage="<%$ resources: UserNameRequired %>"
ToolTip="<%$ resources: UserNameRequired %>" ValidationGroup="intLogin" Text="<%$ resources: asterisk %>"></asp:CustomValidator>
<asp:TextBox ID="Password" runat="server" TextMode="Password" style="display: none;"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" CommandName="Login" style="display: none;" ValidationGroup="intLogin" />
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</LayoutTemplate>
</asp:Login>
</asp:Content>
<script type="text/C#" runat="server">
private const string AuthError = "AuthError";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
EnsureChildControls();
}
protected new void PreRender(object sender, EventArgs e)
{
object msg = Internal.Platform.Application.ApplicationContext.Current.State[AuthError];
if (msg == null)
{
var pageId = Internal.Platform.Application.ApplicationContext.Current.State["CurrentPageID"];
var key = pageId + ":" + AuthError;
msg = Internal.Platform.Application.ApplicationContext.Current.State[key];
}
if (msg != null)
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
Literal FailureText = (Literal)intLogin.FindControl("FailureText");
FailureText.Text = msg.ToString();
}
}
private static void SetAuthError(string errorMsg)
{
if (!string.IsNullOrEmpty(errorMsg))
{
Internal.Platform.Application.ApplicationContext.Current.State[AuthError] = errorMsg;
}
else
{
Internal.Platform.Application.ApplicationContext.Current.State.Remove(AuthError);
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs args)
{
var oValidator = (CustomValidator)source;
if (oValidator == null)
{
args.IsValid = false;
SetAuthError(GetLocalResourceObject("InvalidUserNameValidation").ToString());
return;
}
char cBadChar;
BusinessRuleHelper.InvalidUserNameReason reason;
if (BusinessRuleHelper.IsValidUserNameValue(args.Value, out reason, out cBadChar))
{
args.IsValid = true;
SetAuthError(null);
}
else
{
args.IsValid = false;
switch (reason)
{
case BusinessRuleHelper.InvalidUserNameReason.NullOrEmpty:
case BusinessRuleHelper.InvalidUserNameReason.WhiteSpace:
oValidator.ErrorMessage = GetLocalResourceObject("UserNameRequired").ToString();
break;
default:
oValidator.ErrorMessage = GetLocalResourceObject("intLoginResource1.FailureText").ToString();
break;
}
SetAuthError(oValidator.ErrorMessage);
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
if (Internal.Trial.TrialLogin.VerifyEmail(args.Value.ToString()))
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
args.IsValid = true;
}
}
protected void Page_Error(Object sender, EventArgs e)
{
var userName = (TextBox)intLogin.Controls[0].FindControl("UserName");
string usrnm = userName.Text;
Exception err = Server.GetLastError();
if (err is Internal.Platform.Application.ValidationException)
{
string errMsg = err.Message;
}
}
</script>
Here is the login.master code:
<%# Master Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<script runat="server">
public void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
Internal.Platform.TimeZones tzs = new Internal.Platform.TimeZones();
Internal.Platform.TimeZone tz = tzs.CurrentTimeZone;
if (Request.Params["tz_info"] != null)
{
string[] tzinfo = Request.Params["tz_info"].Split(',');
if (tzinfo.Length == 11)
{
tz = tzs.FindTimeZone(tzinfo[0], tzinfo[1], tzinfo[2], tzinfo[3], tzinfo[4], tzinfo[5], tzinfo[6], tzinfo[7], tzinfo[8], tzinfo[9], tzinfo[10]);
}
}
else
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
log.Warn("TimeZone: Unable to get timezone from client, using server timezone.");
}
Internal.Platform.Application.IContextService context = Internal.Platform.Application.ApplicationContext.Current.Services.Get<Internal.Platform.Application.IContextService>(true);
context.SetContext("TimeZone", tz);
}
Page.Title = GetLocalResourceObject("LoginPageTitle").ToString();
}
</script>
<script type="text/javascript">
function internalCleanUrl(strUrl) {
if(window.location.href.indexOf("internalclient") > -1) {
strUrl = strUrl;
} else {
strUrl = "internalClient" + "/" + strUrl;
}
return strUrl;
};
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head2" runat="server">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Saleslogix</title>
<link type="text/css" href="../css/internalBase.css" rel="stylesheet" />
<link type="text/css" href="../css/BDLogin.css" rel="stylesheet" />
<style type="text/css">
body {
background-color : #f1f1f1;
background-image: none;
}
</style>
<script pin="pin" type="text/javascript">
var dojoConfig = {
parseOnLoad: true,
async: true,
isDebug: false,
locale: '<%= Global.Locale %>',
paths: { 'Internal.: '../../../jscript/Internal. },
deferredOnError: function (e) {
if (dojo.config.isDebug) {
}
}
};
</script>
<script pin="pin" type="text/javascript" src="javascript:internalCleanUrl("Libraries/dojo/dojo/dojo.js">)"</script>
</head>
<body>
<script pin="pin" src="Libraries/jQuery/jquery.js" type="text/javascript"></script>
<script pin="pin" src="jscript/BDLogin.js" type="text/javascript"></script>
<script pin="pin" src="jscript/timezone.js" type="text/javascript"></script>
<script pin="pin" src="jscript/Internal.platform/gears_init.js" type="text/javascript"></script>
<form id="Form1" runat="server" method="post" >
<div class="LoginArea" id="LoginContainer">
<asp:ContentPlaceHolder ID="ContentPlaceHolderArea" runat="server"></asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
If you have a login.designer.cs file try to regenerate it (delete and then click on project and chose 'convert to web application').
Try this:
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Import Namespace="System" %>
<%# Import Namespace="System.Web" %>
<%# Import Namespace="System.Web.UI" %>
<%# Import Namespace="System.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/C#" runat="server">
protected void btnTest_Click(object sender, EventArgs e)
{
System.Web.UI.WebControls.Label lblTest = FindControl("lblTest") as System.Web.UI.WebControls.Label;
lblTest.Text = "Test";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lblTest"></asp:Label>
<asp:Button runat="server" ID="btnTest" OnClick="btnTest_Click" Text="test" />
</div>
</form>
</body>
</html>
I am working with a project in which I need to compare the byte representation of the file being uploaded to go ahead and check it against an accepted file size.
However, when the compiler executes byte[ ] filebyte = fileUpload.FileBytes the StreamReader stops functioning correctly.
Why is this behavior being caused, and is there a better way to accomplish what I am trying to do?
Below is a sample mockup of the issue.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="TestASP.FileUpload" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajax:ToolkitScriptManager>
<ajax:AsyncFileUpload runat="server" ID="fileUpload" Width="300px" UploaderStyle="Modern"
BackColor="LightCoral" UploadingBackColor="#CCFFFF" ThrobberID="fileLoader" />
<asp:Button ID="btUpload" runat="server" Text="Upload" OnClick="btUpload_Clicked" />
<br />
<asp:Label ID="lblMessage" runat="server" ForeColor="Green"></asp:Label>
<br />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btUpload_Clicked(object sender, EventArgs e)
{
if(fileUpload.HasFile)
{
byte[] fileByte = fileUpload.FileBytes;
StreamReader sr = new StreamReader(fileUpload.FileContent);
TextReader tr = sr;
String fileContent = tr.ReadToEnd();
String fileName = Path.GetFileName(fileUpload.FileName);
this.lblMessage.Text = (fileContent);
}
else
{
this.lblError.Text = "File Not Uploaded";
}
}
You should decide for one way or the other, either use FileBytes or open the Stream using the FileContent property. I assume that FileBytes also reads the content of the Stream, so the StreamReader will start reading at the end - hence the empty output.
If you only want to check the size, you can do this using the PostedFile.ContentLength property:
if(fileUpload.HasFile)
{
var sizeLimit = 1024 * 1024; // Limit to a megabyte
if (fileUpload.PostedFile.ContentLength > sizeLimit)
lblError.Tet = "File is too large";
else
{
using(StreamReader sr = new StreamReader(fileUpload.FileContent))
{
String fileContent = sr.ReadToEnd();
String fileName = Path.GetFileName(fileUpload.FileName);
this.lblMessage.Text = (fileContent);
}
}
}
I have an application where a PDF file is opened inside the web form as shown in the below code
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
<div id="divPDF" runat="server">
<object data="<%=pdfPath%>" type="application/pdf" style="height:500px; width: "500px" >
</object>
</div>
</div>
</form>
</body>
</html>
protected string pdfPath;
protected void Page_Load(object sender, EventArgs e)
{
divPDF.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.FileName != "")
{
FileUpload1.SaveAs(Server.MapPath(FileUpload1.FileName));
pdfPath = FileUpload1.FileName;
divPDF.Visible = true;
}
}
It is working fine and I can view and read the pdf. Now what I need is when I scroll through the pages the current pagenumber should appear in a text box.