Reputation: 13280
I am working on an confirmation system, that sends a number back to the user after the process has been complete. What I need is a incrementing counter, that send back the new number. This is what I have so far.
int i = 100;
int Counter = i++;
w.Write(Count);
I want the counter to start at 100, and when the first user uses the system their count number printed to the screen will be 101. The second user will be 102... and so on.
I can get it to increment but the only that displays is 101, it doesn't save 101 and increment it to 102. Any thoughts?
Upvotes: 0
Views: 2796
Reputation: 33880
I would store it in the asp Application object or in a database. Each request is inherently stateless so you can't keep a variable in scope without sessions or databases.
var number = Application["NameOfObject"] as int ?? 100;
number ++;
Application["NameOfObject"] = number;
w.write(number);
Upvotes: 0
Reputation: 5247
Web apps are stateless so all data is lost on a page reload. Session state will save the data in memory :
Session("counter") = i++;
But note that a Session state is per user (so each user will have different counts).
To have sitewide data persist over different sessions and long term the only real solution is to store hits in the database since Application data is cleared on a reload of the app (which will happen if there are no users or if there is a change to web.config)
Upvotes: -2
Reputation: 100248
Save counter into Application vault:
// read data
// if no such one is present, set counter to the default value (100, etc)
int count = Application["counter"] as int? ?? 100;
// increment
count++;
// save back
Application["counter"] = count;
// do stuff you want to measure
But this data will be lost if application dies by timeout, or another reason why the appropriate app pool becomes recycled.
Thus consider to use a database. Install local SQL Express is quite simple task.
Also there is another thing to consider: if work fails, do you want to count it in?
try
{
DoWork();
Count(); // count only if success
}
finally
{
Count(); // count it anyway
}
Upvotes: 4