Why does getting FileByte of uploaded file break StreamReader? - c#

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);
}
}
}

Related

Generate PDF with PDFSharp from HTML template and send to browser

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.

Saving Clipboard PrintScreen to Image File in C#

I am trying to use Visual Studio C# to printscreen, then save the screen capture to a file.
Currently, I am having problems reading from the clipboard.
I have tried using both of the following lines to save a screen capture to the clipboard:
SendKeys.SendWait("+{PRTSC}");
SendKeys.SendWait("{PRTSC}");
However, when I try to save the image using the following lines, I get a Null Reference Exception.
How to do resolve this?
My code below
markup code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Welcome to ASP.NET!
</h2>
1. Copy image data into clipboard or press Print Screen
<br />
2. Press Ctrl+V (page/iframe must be focused):
<br />
<br />
<canvas style="border: 1px solid grey;" id="cc" width="200" height="200">
<script type="text/javascript">
var canvas = document.getElementById("cc");
var ctx = canvas.getContext("2d");
//=== Clipboard ===============================
window.addEventListener("paste", pasteHandler); //chrome
//handler
function pasteHandler(e) {
if (e.clipboardData == false) return false; //empty
var items = e.clipboardData.items;
if (items == undefined) return false;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") == -1) continue; //not image
var blob = items[i].getAsFile();
var URLObj = window.URL || window.webkitURL;
var source = URLObj.createObjectURL(blob);
paste_createImage(source);
}
}
//draw pasted object
function paste_createImage(source) {
var pastedImage = new Image();
pastedImage.onload = function () {
ctx.drawImage(pastedImage, 0, 0);
}
pastedImage.src = source;
}
</script>
</canvas>
<br />
</div>
<div>
<asp:Button ID="btn" runat="server" OnClick="btn_Click" Text="Go" />
</div>
</form>
</body>
</html>
code-behind
protected void btn_Click(object sender, EventArgs e)
{
var path = new[] { #"C:\Users\A\source\repos\CopyPaste\public",
#"C:\Users\A\source\repos\CopyPaste\public" }.First(p => Directory.Exists(p));
var prefix = "css-social-media-icon-list";
var fileName = Enumerable.Range(1, 100)
.Select(n => Path.Combine(path, $"{prefix}-{n}.png"))
.First(p => !File.Exists(p));
Clipboard.GetImage().Save(fileName, ImageFormat.Png);
Clipboard.SetText($"![image](/public/{Path.GetFileName(fileName)})");
}
I hope this helping... following this example

Write to a file C# ASP.net on button click

I can't get this asp.net page do write to a file. I was following this guide. I am not sure what i am doing wrong because i can use this button to change label text, but not to print "Hello World" into a text file in the same directory.
<%# Page Language="C#" %>
<script runat="server">
void Button1_Click(Object sender, EventArgs e)
{
using (StreamWriter w = new StreamWriter(Server.MapPath("~/Saved Layouts.txt"), true))
{
w.WriteLine("Hello World"); // Write the text
}
}
</script>
<html>
<head>
<title>Single-File Page Model</title>
</head>
<body>
<form runat="server">
<div>
<asp:Label id="Label1"
runat="server" Text="Label">
</asp:Label>
<br />
<asp:Button id="Button1"
runat="server"
onclick="Button1_Click"
Text="Button">
</asp:Button>
</div>
</form>
</body>
</html>
The problem is probably this error "The type or namespace name 'StreamWriter' could not be found". That's because there is no using System.IO present. To fix this write out the complete NameSpace of the StreamWriter.
using (System.IO.StreamWriter w = new System.IO.StreamWriter(Server.MapPath("~/Saved Layouts.txt"), true))
{
w.WriteLine("Hello World"); // Write the text
}
Or add it to the single page
<%# Import Namespace="System.IO" %>

Cant access asp labels properties using c# in aspx page

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>

Session variable lost when click sign in

In first visit, Page_Load is running and session store correctly. When I click on Sign In button, Page_Load is call again, and then call btnSignIn_Click function, but Session is empty!
public partial class LoginPage : System.Web.UI.Page
{
UserItem userItem = null;
protected void Page_Load(object sender, EventArgs e)
{
//Initialize and validate post
RequestObj post = new RequestObj(Context);
if (post.isValid)
{
Session["post"] = post;
}
}
protected void btnSignIn_Click(object sender, EventArgs e)
{
if (Session["post"] != null)
{
RequestObj post = Session["post"] as RequestObj;
userItem = Functions.LogIn(post);
}
Response.Redirect("LogIn.aspx");
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<%# Page Language="C#" AutoEventWireup="true" CodeBehind=" LoginPage.aspx.cs"
Inherits="myNameSpace.LoginPage " %>
<!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">
<meta name="viewport" content="width=320"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="width:100%; text-align:center;">
<%if (userItem == null)
{%>
Username:
<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="txtPass" runat="server" TextMode="Password">
</asp:TextBox>
<br />
<asp:Button ID="btnSignIn" runat="server" Text="Sign In"
onclick="btnSignIn_Click" />
<%}else{%>
<%=userItem.LoginName%>
<br />
<%=userItem.LoginTime.ToString()%>
<br />
<asp:Button ID="btnSignOut" runat="server" Text="Sign Out"
onclick="btnSignOut_Click" />
<%}%>
</div>
</form>
</body>
</html>
Did you mean to only set session when the page renderes initially?
Try wrapping the assignment like this
if(!IsPostBack)
{
RequestObj post = new RequestObj(Context);
if (post.isValid)
{
Session["post"] = post;
}
}
This will prevent this from being reset during a postback
Otherwise I would check the value of post in a debugger

Categories