Reputation: 878
I have the following C# code:
Application["CountTrackViews"] = int.Parse(Application["CountTrackViews"].ToString()) + 1;
The problem here is that there is no start value for this application object, and I really don't know which start value should I give, and how can I do it (this application object should count time of views)
Wish for help, thanks!
Upvotes: 0
Views: 302
Reputation: 218837
If you can add a Global.asax
and use the Application_Start
event, then you can initialize the value there. Something like this:
protected void Application_Start()
{
Application["CountTrackViews"] = 0;
}
Failing that, you could check for the existence of the value before using it. Something like this:
var viewCount = 0;
int.TryParse(Application["CountTrackViews"], out viewCount);
Application["CountTrackViews"] = viewCount + 1;
This is untested code, you might need to tweak it a little. But the idea is simple enough. Start with a default value, try to parse the current value, if the parsing fails then default to the default value. Wrap all of this in some kind of global (static) helper method so you don't have to repeat these lines in multiple places.
Keep in mind, however, as stated in the comments above that this counter will reset any time the application resets.
Upvotes: 2
Reputation: 3289
This is a bad way of logging page views over any time period longer than 20 minutes. By default in IIS, the application will be recycled after 20 minutes of inactivity. Then your counter will be lost and reset the next time a user loads it.
As David suggested, look to storing this in a database or even text file.
Upvotes: 1