In my asp.net project I have an event in global.asax as session end which fires when the session is timeout and in this event, I am calling one stored procedure that updates logout time and flag in the table. But when the user is log in and after some work user close browser and on next day when he tries to log in at first attempt message shows that user is already login but when he tried to log in again he is able to log in.
please help its production issue.
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
objUserRole.SchemaName =
(string)CBase.TripleDESDecode(Application["SchemaName"].ToString(),
CBase.EncryptionKey);
if (Session["UserId"] != null)
objUserRole.UserId = (string)Session["UserId"];
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
}
void Application_Error(object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError().GetBaseException();
}
public HttpSessionState GetSession()
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Session;
}
else
{
return this.Session;
}
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
string userid = Convert.ToString(GetSession()["UserId"]);
objUserRole.UserId = (string)CBase.TripleDESDecode(userid,
CBase.EncryptionKey);
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
// objUserRole.funcUpdateLoggedIn();
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
finally
{
Session.Abandon();
Session.Clear();
}
}
</script>
Related
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
if (!IsPostBack)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
}
the user loged in and he is authenticated, but when I check for his name I get ""
I try to get the user name using a jquery ajax, and I return the data to the ajax
update:
a look at my immediate window (while in a break point) when a user named moria is logedin
**User.Identity**
{System.Web.Security.FormsIdentity}
[System.Web.Security.FormsIdentity]: {System.Web.Security.FormsIdentity}
AuthenticationType: "Forms"
**IsAuthenticated: true**
**Name: ""**
**Membership.GetUser()**
**null**
**Membership.GetUser("moria")**
{moria}
Comment: null
CreationDate: {23/02/2016 01:10:08}
Email: "orders.gca#gmail.com"
IsApproved: true
IsLockedOut: false
IsOnline: false
LastActivityDate: {24/02/2016 03:21:08}
LastLockoutDate: {01/01/1754 02:00:00}
LastLoginDate: {24/02/2016 03:21:08}
LastPasswordChangedDate: {23/02/2016 01:10:08}
PasswordQuestion: "1"
ProviderName: "MySqlMembershipProvider"
ProviderUserKey: {ff589472-e852-4049-8803-6d22740414ee}
UserName: "moria"
Taking from ADreNaLiNe-DJ's answer and adding in the ability to redirect back to the calling page, you would add this to the Global.asax file:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var loginUrl = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Login", "Account") ?? "";
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains(loginUrl))
{
Response.Redirect(loginUrl + "?ReturnUrl=" + Request.Url.AbsoluteUri);
}
}
Hope that helps.
First of all, you should check authentication earlier in the pipeline.
Add this code in your Global.asax.cs:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains("login.aspx"))
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
}
You check authentication for all pages/requests in 1 unique place.
So when you are in the Page_Load, you are sure to be logged in and authenticated.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}
I have some validation code in my WebForm page. When a user clicks on a button and does a postback.
Page_Load event gets processed then the Button1_Click event gets processed.
I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.
Is a trick to do this?
Thanks
4 variations shown below.
public partial class _Default : System.Web.UI.Page
{
private bool MyPageIsValid { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bool valid = false; /* some routine here */
MyPageIsValid = valid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.MyPageIsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!this.MyPageIsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
I think it should be better to check validation conditions exactly in the Button1_Click method like this:
if (!this.IsValid()) { return; }
Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:
if (!this.isValid) { return; }
I am trying to send the data to serial port in ASP.net. After connecting to serial port Before postback data is being sent. But after postback i get exception while sending data.
'System.InvalidOperationException: The port is closed.'
I tried everything by connecting to port on pageload: ispostback, and disconnecting and connecting again. Still it shows same exception. Is there any way to retain the state of serial port..
here's my code. Please Help me Out...
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
openPort("COM10");
disconnect();
connect();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//disconnect();
openPort("COM10");
connect();
check(TextBox1.Text); //Data Sending Successful but after postback even it doesnt work too.
}
public void connect()
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void disconnect()
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
public void openPort(string p)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
indata = sp.ReadExisting();
Debug.WriteLine(" Data Received:");
Debug.Write(" " + indata);
}
protected void Button4_Click(object sender, EventArgs e)
{
check("" + (char)26); //Exception in sending
}
protected void Button3_Click(object sender, EventArgs e)
{
check("\r\n"); //exception in sending
}
protected void Button2_Click(object sender, EventArgs e)
{
check(TextBox1.Text); // exception in sending
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
sp.Write(ss);
else
{
disconnect(); openPort("COM10"); connect();
sp.Write(ss);
}
}
}
I would simplify your code, so the port is configured on page load and the one handler deals with resetting your port. The disconnect, connect, I see is complicating it. Here I have given an example of using the button click event.
Please note the missing brace below.
public partial class _Default : System.Web.UI.Page
{
string indata;
public SerialPort sp = new SerialPort();
protected void Page_Load(object sender, EventArgs e)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
if (!Page.IsPostBack)
{
sp.BaudRate = 9600;
sp.Parity = Parity.None;
sp.StopBits = StopBits.One;
sp.DataBits = 8;
sp.Handshake = Handshake.None;
sp.PortName = p;
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
// sp.ReadTimeout = 200;
// sp.WriteTimeout = 200;
}
protected void Button1_Click(object sender, EventArgs e)
if sp.IsOpen = False then
{
try { sp.Open(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
else
{
try { sp.Close(); }
catch (Exception e1) { MessageBox.Show(e1.ToString()); }
}
void check(string ss)
{
//sp.Dispose();
//openPort("COM10"); connect();
if (sp.IsOpen)
{//missing brace
sp.Write(ss);
}//missing brace
else
{
sp.Open();
sp.Write(ss);
}
}
}
Edit 2:
As I mentioned in the comments the code will only run once.
The following examples are provided from the link below.
Have you tried writing some codes under the !IsPostBack code block to
check if the codes hits there when it postbacks? try this below for
testing
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("First load");
}
else
{
Response.Write("Postback occurs");
}
}
OR
I will refer the code you want to run as One Time Code. For what you
are attempting to achieve, following should work. Please note that
sessions also expire. So after about 20 minutes (default value) of
inactivity, if the user comes back to the site/hits refresh, the One
Time Code will run again. If you want something more persistent than
20 minutes you can try using cookies, but if user clears their cookies
your One Time Code with run again.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["firsttimeuser"] == null)
{
//put code here for One Time Code;
Session["firsttimeuser"] = true;
}
}
Please see this link:
There is lengthy discussion about this.
http://forums.asp.net/t/1314918.aspx/1
You should be able to create a solution from this, please advise.
Edit 1
Please see MSDN for Get Port Names:
Use the GetPortNames method to query the current computer for a list
of valid serial port names. For example, you can use this method to
determine whether COM1 and COM2 are valid serial ports for the current
computer.
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx
And SerialPort.Open
_serialPort.PortName = SetPortName(_serialPort.PortName)
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.open.aspx
Edit 3
Try:
if (!IsPostBack) or
if(!Page.IsPostBack)
Please see:
Implementation of IsPostBack in page load
What is a postback?
and:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
I want to have a method which gets executed when session expires or user logs out or user closes the web application. How can i catch these events in asp.net and execute a method ?
I'm building a web app in vs 2008/asp.net/c#.
Please help me.
Thanks in anticipation
use Global.asax file
Refer the link to use Global.asax file http://www.dotnetcurry.com/ShowArticle.aspx?ID=126
Right click on The solution and the Add new item the Add Global.asax in the solution Then after
which have the following Event
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
//Utils.LoadExtensions();
}
void Application_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
void Application_Error(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
Exception ex = context.Server.GetLastError();
if (ex == null || !(ex is HttpException) || (ex as HttpException).GetHttpCode() == 404)
{
return;
}
StringBuilder sb = new StringBuilder();
try
{
sb.AppendLine("Url : " + context.Request.Url);
sb.AppendLine("Raw Url : " + context.Request.RawUrl);
while (ex != null)
{
sb.AppendLine("Message : " + ex.Message);
sb.AppendLine("Source : " + ex.Source);
sb.AppendLine("StackTrace : " + ex.StackTrace);
sb.AppendLine("TargetSite : " + ex.TargetSite);
ex = ex.InnerException;
}
}
catch (Exception ex2)
{
sb.AppendLine("Error logging error : " + ex2.Message);
}
if (BlogSettings.Instance.EnableErrorLogging)
{
Utils.Log(sb.ToString());
}
context.Items["LastErrorDetails"] = sb.ToString();
context.Response.StatusCode = 500;
//// Custom errors section defined in the Web.config, will rewrite (not redirect)
//// this 500 error request to error.aspx.
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
ClsCollege ObjClsColledge = new ClsCollege();
ObjClsColledge.TruncateAllUserDetails(Session["UserSessionId"].ToString());
ObjClsColledge.TruncateAllUserDetailsPrefrance(Session["UserSessionId"].ToString());
}
</script>
The Event Session_start(),Session_End() and Application_End() you will able to track the
Event.