Error when trying count page views ASP.NET C# - asp.net

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!

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.

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.

Related

How can I have variable accessible in whole project in ASP.NET

Hi to all I'm beginner in asp.net.
I have Uploader.aspx page.
Whenever called this page execute some code like saving file.
Now I need a varible that count number of uploading the problem is that when I define counter variable, every time that I call the page defined variable again and lost the value.
How can I solve this problem?
Add this to your global.asax:
protected void Application_Start()
{
Application["Counter"] = 0;
}
Then you would increment it in your code like this:
Application["Counter"] = ((int)Application["Counter"]) + 1;
Note the counter will be reset when the application is restarted, if that's an issue you will need to persist the value in a file or database.

asp.net async thread with pooling

I have a long running task that I need to implement on a webpage. What I would like to do is run the task on a separate thread, but have a progress bar on the webpage.
I am struggling to find an easy way of doing this. Here is a very simplified example that I want to do this on. Basically, I want the ResetAll() in a thread, and pool the variable y to update the webpage UI.
Can someone help me?
Protected Sub btnReset_Click(sender As Object, e As System.EventArgs) Handles btnResetLowConductor.Click
ResetAll()
End Sub
Private Sub ResetAll()
Dim y As Integer = 0
While y < x
y += 1
Reset()
lblProgress.Text = y & "/" & x
End While
End Sub
Private Sub Reset()
Threading.Thread.Sleep(200)
End Sub
your lblProgress will not update as long as thread is alive. You will get only final value of y & x i.e when thread is dead. You can store the values of Y & X inside a session variable.
Private Sub ResetAll()
Dim y As Integer = 0
While y < x
y += 1
Reset()
Session("CurrentStatus") = y & "/" & x
End While
End Sub
From Your UI you will fire an asynchronous event using PageMethod i.e
function GetCurrentThreadStatus()
{
PageMethods.GetThreadStatus(function(status){
// success
$("span[id*='lblProgress']").text(status);
});
}
Code Behind : C#
[WebMethod]
public static string GetThreadStatus()
{
return (string)Session["CurrentStatus"];
}
As this is a website, you will probably need to use some sort of ajax method to call back to the server periodically. Here is the basic flow of your program as far as I can see it:
User makes initial call
Spin up new thread to run process and return with a 0% status
Periodically, make a call to the web server via ajax (A GetStatus call that will return the percentage of completion)
If the call is complete, update/refresh the page appropriately
If the call is not complete, then use the returned status
Now, I am not as sure about the details given that this is a web page, but you could try to store the status in the session variable (which may or may not be possible once you have already returned) periodically, and then the GetStatus will just read the most current status. If session does not work, then you will need to persist the status another way (db, file, etc).
Just be careful on how often you store the status. Too often and you slow your process down, and too little and you do not give an accurate representation of the status.
Last, if you can upgrade to .NET 4.0, then this becomes even more trivial using the TPL (Task Parallel Library)
You are confused about how web pages work.
Once the thread is fired and you write the response to the client, you won't be able to continue updating the page as the Thread progresses.
One way to do this sort of thing is using Ajax. Ulhas already showed you a way top do this; all you need to do is have that javascript function he wrote call itself until you get a 100% completion. You can do that using a timer.
Okay, with the help of various websites, I managed to do this.
Here is a sample project. Please let me know if there are any problems with this. I'm no expert, so I would like some feedback!
http://www.mediafire.com/?7vn16vp78rave6a

Asp.Net / Ajax updating update panel automatically how to?

I have an Asp.net page which requires certain sections to be partially updated automatically at an interval of 5 seconds.
I was planning to use the good old Timer control with the AJAX Update Panel for this purpose, but after a bit of reading on this control i found out that it may have some problems especially if,
1) The time difference between the async event performed ( 4 seconds ) by the update panel and the Timer's tick interval ( which is 5 seconds ) are quite small, the update panel will be held up in the async operation all the time.
2) Also, the fact that timer control doesn't work very well with Firefox.
I just wanted to get your opinion as to whether if i should go ahead with the timer and update panel approach, write some custom javascript that does the partial page update or some other strategy altogether.
Personally, I tend to think that the DIY approach is better -- easier to debug and easier to write.
You can use a javascript setInterval for a timer, and every time the function is called, you can initiate an ajax request to your asp.net code-behind to fetch whatever data needs to be updated.
For example, let's say you simply need to, every 5 seconds, update the current time on a page. Let's assume you have a span of ID currentTime on your page, something like:
<asp:Label id="CurrentTime" runat="server" CSSClass="currentTimeLabel" />
In your initial PageLoad event, you set the time:
protected void PageLoad(...)
{
CurrentTime.Text = DateTime.Now.ToString();
}
Now you need to define some javascript on your page that will, every 5 seconds, call the code-behind and get the new date/time value.
Doing this with something like jQuery is very simple:
$(document).ready(function() {
setInterval(5000, updateTime);
});
function updateTime() {
url: "myPage.aspx/SomePageMethod",
success: function(data) {
$(".currentTimeLabel").text(data);
});
}
In ASP.NET, getting the PageMethod to work is the trickiest part (for me, anyway). You need to create a public function in your code-behind with a 'WebMethod' attribute. Something like this:
[WebMethod]
public static string GetCurrentTime()
{
return DateTime.Now.ToSTring();
}
I didn't test any of this code, but the basic premise is sound and should work fine.
Now, this may seem more complicated than using an UpdatePanel, but I find it easier when I know what code is actually running on my page.
If you need to update a series of controls instead of just one control, you can use a more complicated web method that returns xml or json data, and then parse that using javascript.

Will my shared variables loose value? (asp.net vb)

I have a class includes.vb that holds some variables (sharing them with other pages) like:
Public Shared pageid As Integer = 0
I then have a function that does some work with these variables returning them with values;
Return pageid
When I step through the code, the variables have values (while stepping through the function), but when they are returned to the page, they come back null.
Do they loose value everytime a page is loaded?
Can you suggest an alternative method?
Thanks a lot.
You should use probably Session variables.
Session("PageID") = 0
and access it every time you need.
Not a best practice but if you want to be even stricter, you can use specific application variable for every session so that if the user returns after a day to the website, it still not lost (as long as you haven't done an iisreset).
To overcome iisreset will be an even bigger overkill, you can save the value to a file/DB and retrieve it everytime you want. (Please don't do that!!)
Maybe this can explain further:
http://codeforeternity.com/blogs/technology/archive/2007/12/19/handling-asp-net-session-variables-efficiently.aspx
It is not a very good idea to use shared variables in web projects: first off, every time you do an "iisreset" or recycle your application pool, these variables are reset. Next thing, these variables are not per-user, but per-process, and (I believe) are not guaranteed to be thread safe, so one thread may change the value of a variable and then another one reset the value to something different.
Judging from the variable name "PageID", I think you are trying to track the last page user has visited. If this is the case, then session variable scope is a better solution for you. See tutorial here: http://msdn.microsoft.com/en-us/library/ms178581.aspx

how to display something one time every hour in asp.net?

how to display something one time every hour in asp.net ?
example for show messeage in Begining hour one time only?
i use for asp.net ajax timer control?
protected void Timer1_Tick(object sender, EventArgs e)
{
MessageBoxShow(Session["playsound"].ToString());
Session["playsound"] = 1;
}
but alway null?
---------------------------
Message from webpage
---------------------------
Object reference not set to an instance of an object.
---------------------------
OK
---------------------------
Sounds like your session might have timed out. If, between AJAX calls, your session expires on the server, then the ToString invocation may be operating on a null reference:
MessageBoxShow(Session["playsound"].ToString());
This would appear to coincide with what the AJAX client script is attempting to tell you.
This could also be the result of Session["playsound"]; being uninitialised.
The default session expiry duration for ASP.NET is 20 minutes, which you should be mindful of if you're executing an hour long timer.
You can use the
window.setInterval
method
It calls a function repeatedly, with a fixed time delay between each call to that function.
intervalID = window.setInterval(func, delay[, param1, param2, ...]);
Read more info
window.setInterval
On the client?
The only way I know to do this is via a javascript timer.
One way of doing this could be to have an session variable with NextTime to show the item on the page. If its null one could display the item now (or get the NextTime scheduled). On every page refresh, if the current time is after the Next Time, show the item and reset the NextTime session variable to the next Hour.
This would only work if the user is navigating the site and the page is being refreshed.
You can use the javascript variable window.name which keeps its value between page refreshes.
You could store a 'last checked time' in there and compare it with the current time.
If the user navigates to another site and that site clears this variable then your back to square one.
An easy answer would be to use a small cookie to store the original time and then query it every so often (~5 min?) this way the session won't run out and you're not SOL if the user leaves the page (if that's what you want).
DISCLAIMER: I haven't really dipped my toes into AJAX yet even though I've been programming ASP.net all summer, so excuse me if this isn't possible.

Resources