How to prevent reset of session timeout timer when using handler (ashx)? - c#

I'm using a handler to poll certain information out my application. I've got some questions about using the handler in combination with session timeout:
Does a call to the handler reset the session timeout timer?
If so, are there ways to prevent a reset of this timer?
Due to security reasons I would not like my handler to be the cause that my user is logged on indefinitely.

Yes
Run the handler in a different web app

The only solution I can think of is to do some kind of manual session timeout handling. Something like this:
void Application_BeginRequest(object sender, EventArgs e)
{
if(Session["LastAccessTime"] != null && (DateTime)Session["LastAccessTime"] < DateTime.Now.AddMinutes(-20))
Session.Abandon();
if(Request.RawUrl != "/MyHandler.ashx")
Session["LastAccessTime"] = DateTime.Now;
}

Related

How to implement and async email verification logic?

I need to implement the following: I have a page on which user enters an email. Every time text changes, I have to check whether the user exists in a DB and based on that information, I should set the text of the button to either "Sign up" or "Sign in". The problem is, that this DB request may take a couple of seconds (the reason is irrelevant) and the API is async, so event handler will be decorated with async, and since mail entry may change several times, this handler will be called several times before any one will end. So I'll have concurrent API requests and then, potentially, concurrent attempts to change the button text and that may not end well. I thought of something like this:
private async void OnTextChanged(object sender, TextChangedEventArgs e)
{
mailEntry.TextChanged -= OnTextChanged;
...
submitButton.Text = (await api.AccountExistAsync(mailEntry.Text)).IsRegistered
? "Sign in"
: "Sign up";
...
mailEntry.TextChanged += OnTextChanged;
}
But a problem with this design, is that, say, a valid email was entered between -= OnTextChanged and += OnTextChanged, in which case it'll never be checked.
My question is, what is the right way to implement what I'm trying to achieve? Thanks in advance.
Here is one solution:
private long requestNumber;
private async void OnTextChanged(object sender, TextChangedEventArgs e)
{
var text = mailEntry.Text;
long myRequestNumber = ++requestNumber;
await Task.Delay(200);
if (requestNumber != myRequestNumber)
return;
var result = (await api.AccountExistAsync(text)).IsRegistered;
if (requestNumber != myRequestNumber)
return;
submitButton.Text = result ? "Sign in" : "Sign up";
}
It maintains a requestNumber variable to hold the last request number which is incremented each time you change the text.
If after the AccountExistAsync operation completes the code discovers that the variable was changed, it will conclude that a new request has been issued, and will not update the UI.
Please note that the solution also waits 200 milliseconds before attempting to send a validation request. Although this will delay the validation operation 200 milliseconds, it will prevent too many requests to be sent, especially as the user is typing quickly. This is optional of course.
Edit:
I removed the use of synchronization when reading/updating requestNumber because such code runs in the UI thread only.

Will Duplex Channel's State in NetTcpBinding automatically transition accordingly to client's?

On client side, I handle the proxy state so that when its State==CommunicationState.Faulted, it will automatically call Abort() and gracefully transition to CommunicationState.Closed.
On server side, I have 2 events hooked up to callback channel
OperationContext.Current.Channel.Faulted += Channel_Faulted;
OperationContext.Current.Channel.Closed += Channel_Closed;
Here are my events code
private void Channel_Closed(object sender, EventArgs e)
{
var callback = sender as IPtiCommunicationCallback;
PtiClient client;
lock (syncObj)
{
client = clientsList.FirstOrDefault(x => x.Value == callback).Key;
}
if (client != null)
{
//Code to remove client from the list
Disconnect(client);
}
}
private void Channel_Faulted(object sender, EventArgs e)
{
(sender as ICommunicationObject).Abort();
}
Now the question: Will the duplex channel's (the callback channel) state automatically transition accordingly to client's or I have to handle the Faulted State as I did? I'm using NetTcpBinding by the way.
The Callback channel's state will generally mimic the client's state, but this is not guaranteed. For example, if the client is trying to reach the server to close the connection, its state might be Closing while the state on the server side could be Opened. You are handling it correctly in assuming that each side must handle Closed and Faulted states individually.
I have done bit research about what kind of binding should we use and finally decided to go ahead with nettcp binding. See my blog for detail explanation.
http://maheshde.blogspot.com.au/2013/06/duplex-communication-over-internet.html
I have no idea why those events not fired. But triggering WCF call from client every 10 minutes our problem solved.

Using Watin, how can I refresh the browser when the request times out

I have this code:
var ie = new IE();
ie.GoTo("http://www.google.com");
I want IE auto refresh when the result is: "Time out"
And if IE have to load for a long time but still cannot access to http://www.google.com, Can you tell me the way to set a time out for my browser???
Do you have to use Watin? Using the .NET webbrowser you can use the onNavigate event to start a stopwatch for your timeout time and stop in the documentComplete event handler. If the stopwatch time is longer than your timeout you can do webBrowser1.Refresh(). That would be much simpler than embedding Javascript but I don't know if you can change browsers at this point.
you can create a background JavaScript process in the browser that sends regular heartbeats to the server. Regenerate a new cookie with timed expiration, say, every 5 or 10 minutes.
1st of all session timeout is desided and fixed by the website developer/producer.
So that we can not amend/alter the session timeout.
Session timeout is moniter by the IIS (internet information server)
Now there is only way to handle it that is regularly interacting with the server, and for this you may have two ways
1 sending hartbeets to the server by using java script
2 refresh the web page before session expires, for this you have to know about when the session going to expire.
The 2nd one is quite easy.
Consider you have a form containing webbrowser control, on its load event (form_load) event you can write as following.
private void FrmMain_Load(object sender, EventArgs e)
{
string url = "http://www.google.com";
webBrowser1.Navigate(url);
timer1.Interval = 1000-10; // "1000" Time in millisecond that will be your maximum Session expires Time span
// and -10 is value that you want to refresh the page before expire
}
private void timer1_Tick(object sender, EventArgs e)
{
webBrowser1.Refresh();
}

Session variable value not always available in Global.asax Session_end

When a user logs into the website, I am creating 5 session variables with some user related values (like userid,roleid etc..). Based on one of the values stored in a session variable, I have to update a record in the database. To do this I am writing the following code in the Session_End() event of Global.asax
if (Session["UserHistoryID"] != null)
SessionUtility.UpdateDatabase(Convert.ToInt32(Session["UserHistoryID"]));
The problem here with this is when the Session times out and Session_End fires the Session variable Session["UserHistoryID"] is NULL some-time and the above condition fails and the record in the database is not updated. When this is tested in my local system it works fine but when I test this in production server some of the records are not getting updated
Why is this happening?
Some one please explain how the Session_End works exactly.
I have searched everywhere but can't find a solution to this.
I think that the earliest possible time you could obtain the Session value is under Application_AcquireRequestState as mentioned hereSessions and Global.asax so you could write something like this in your Global.asax
void Application_AcquireRequestState(object sender, EventArgs e)
{
if (System.Web.HttpContext.Current.Session != null)
{
if (Session["language"] != null)
{
Response.Write(Session["language"].ToString());
}
}
}
hopefully that would help !!
If I declare a variable for each session value I want to access in the Session_End event and store the value of the session in this variable and use the declared variable in the my functionality it is working fine
void Session_End(object sender, EventArgs e)
{
int var=0;
if (Session["value"] != null)
{
var = Convert.ToInt32(Session["value"]);
UpdateToDatabase(var);
}
}

check for condition every period of time

i have a specific state(business case),i want to check it every period of time,to execute an action..they tell me to write a patch to handle this situation ..
the application i works in is a web application (asp.net)..
i don't know how to write the patch ,, and i don't know if the patch is the ideal solution in this state or not..
please any suggestions ,, any details explanation for this issue..
thanks in advance.
Firstly, it is quite simple to setup a timer to do this check. Initialise a timer,
int _State;
System.Timers.Timer stateCheckTimer = new System.Timers.Timer();
stateCheckTimer.Interval = 1000; // TODO - set to desired interval (in ms)
stateCheckTimer.AutoReset = true;
stateCheckTimer.Elapsed += stateCheckTimer_Elapsed;
Then just check your state in the stateCheckTimer_Elapsed function,
void stateCheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
The most difficult thing will be accessing the _State, so you'll probably have to put the timer in the same location as it (or have it passed, whatever works). I would suggest an event driven solution though. Make a public event handler on your class that handles the state,
public EventHandler OnStateChanged;
Then, encapsulate the access to your state variable (in this example, _State) so that you control the setting of it. When it is set, fire off this event. I do this through a property,
public int State
{
get { return _State; }
set
{
_State = value;
if (OnStateChanged != null)
{
OnStateChanged(this, null);
}
}
}
Then, you just need to wire up an event handle to execute your desired action,
OnStateChanged += StateChangeAction;
And in that function execute your desired action,
void StateChangeAction(object sender, EventArgs args)
{
// Check for the desired state
if (_State == 1)
{
// Do something
}
}
(you will have to pass the state in through the EventArgs args but that is pretty simple to do). This way, whenever the state changes you will immediately be able to act upon it (send an email, do whatever it is) rather than having to poll the state every x seconds or minutes. It will use less resources, be more reactive (quicker), and ultimately be neater code! If you are able to do it this way, I would highly recommend it.
this checking is done from the browser or on the server side application ?
if it is done from the client( Browser ) than you can do it with JavaScript See this Post
If you want to do it from the Server Side code than , you can do it with a thread, make thread sleep for some time and when it's wake up than check the state of your object
Is the action to be executed a database one, e.g. update some row in the database? If yes you can create a database job that handles this situation.
What about writing a small simple service that works in the background 24/7. I think its the simplest solution.

Categories