How can I have variable accessible in whole project in ASP.NET - 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.

Related

C# code to increment by 1 an item in Application state

How to write the C# code to increment by 1 an item in Application state named “total” in ASP.net?
In order to modify any Application variables, you need to lock them before modifying it to ensure no inadvertent changes between parallel requests happen.
An example
Application.Lock();
var userCount = Convert.ToInt32(Application["OnlineUserCount"]);
Application["OnlineUserCount"] = ++userCount;
Application.UnLock();
Application.Lock ensures that only one thread or request has access to the variables and other requests wait in queue. You modify the values as per the need and Application.Unlock to release your lock so other requests can work on Application variables.
Please note that there may be a performance hit, if you depend on this!!
Note: A page does not need to lock the application object to edit the
application collection. If one page tries to edit the application
collection without locking and a second page also tries to edit the
collection, no error is sent by IIS and the Application object ends up
in an inconsistent state.
Better use a
static variable
and
Interlocked.Increment
like this:
private static int total= 0;
public static void Increment()
{
Interlocked.Increment(ref total);
}

How to prevent calling of function on every postback request

I have bind complete menu on postback now every post back request function
call and bind menu again i want to call it only first time please suggest
here below is my code
if (!Page.IsPostBack)
{
objCommon = new Common();
Common.UpdateLoginSession();
if (hiddenMenuFlag.Value == "S")//used hidden field but not working as is
//does not retain value on post back please suggest
{
BindMenu("0");//here is function for binding menu
hiddenMenuFlag.Value="";
}
}
use
if (!IsPostBack)
{
--------------------------;
--------------------------;
}
All functions or code inside this condition will run only for the first time, when page is requested. It won't execute on reload.
If you want to run a code only once; when the user request the page then you can use some session as suggested above.
If you want to run a code only for the first time when application runs, then you can use Application state to control your code
You could create a session variable and then check that variable to ensure your code will execute only once.
You create session variable like this:
Session["myVar"] = "myText";
And then you could check it value like below:
((string)Session["myVar"]) == "myText"

Error when trying count page views ASP.NET C#

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.

Asp.net Wizard Control with Dynamic Steps gets stuck

I have a wizard control which must use dynamic steps in. I have the following code which loads the dynamic steps (this all works fine). I have 7 static steps.
protected override LoadViewState(object savedState)
{
base.LoadViewState(savedState);
int offset = 4;
foreach(string stepName in this.ViewState["Steps"])
{
WizardStep step = new WizardStep();
step.Title = stepName;
this.Wizard1.WizardSteps.AddAt(step, offset); // LINE 1
this.Wizard1.WizardSteps.Add(step); // LINE 2
offset++;
}
}
I have two issues, when I execute the code and use Line 1. When I get to a dynamic step it won't let you procede to the next one (using the Next button). This seems to be because this.IsValid is false (but I have no validation controls on the page). It just seems to get stuck on that current page.
When I run using Line 2, it adds the steps again fine. When I am on the first dynamic step and click Next I get the error. ActiveViewIndex is being set '7'. It must be smaller than the current view controls '7'. For dynamically added views, make sire they are added before or in Page_PreInit event.
The issue with the second error is I can't add the dynamic steps in Page_PreInit because I need access to the viewstate to know how many steps to draw.
I found the issue. Its since the steps must be added in the Page_PreInit event. Which does mean I can't use the Viewstate but I am using the Session instead now.

ASP.NET variable scope

im really new to ASP.Net and still havnt got my head round most of the concepts, im really having problems with variable, when creating a desktop application, any variable created in code for example
int n = 10;
this variable will be there until the program is running right. but in asp iv created variables which are supposed to last until the user gets of that page, so for example say i have a page which takes the users value ( call this variable n say the user type in 10) and every time the user presses the next button the code add 10 to this value. so the first time the user presses the next button
n= n + 10;
what i have found is no matter how many times i press the next button n will always equal 20, because the previous value is not saved !!
these values are populated the first time the user enters that page, once the user clicks the next button the content of these values disappear! how can stop this from happening ??
hope this makes sense !!
thanks
Every time you refresh page (click also refreshes page) new instance of Page class is created. This means that all your fields become empty.
You can try to use ViewState to persist data between refreshes. But you should be care as this will increase page size. So best practice is to minimaze data in view state.
Another options is SessionState, but in this case you will keep data even between pages.
Hope this helps.
Each time the user requests the page, it receives the request, is initialized, processed, and then rendered (read about the Asp.Net Page Life Cycle here.). So, on each page request, your variables are being created, initialized, and then assigned your values - each page load is a new life cycle. If you want values to persist betwen page life cycles, then you need to use one of the available methods (ViewState, Session, QueryString, Post, ....) to pass the values to the "next" request.
Variables don't automatically maintain state across page calls in ASP.NET. Asp.Net Page has a life cycle and being stateless, the information is lost at the end of this cycle, after a request has been served on the client side. There are several solution for this.
session
hidden fields
querystrings
Here is hidden field example.
In HTML, you simply create:
<input type="hidden" id="myHiddenVar">
To set it's value in javascript:
document.getElementById("myHiddenVar").value = "myValue"
In ASP.NET code-behind, you use the Request object to retrieve the value.
string myHiddenVar = (string)Request.Params["myHiddenVar"];
Variables in ASP.NET work exactly the way that variables in Windows Forms work:
public class MyPage : System.Web.UI.Page
{
private int n = 0;
public void Button_Click(object sender, EventArgs e)
{
n = n + 1;
}
}
public class MyForm : System.Windows.Forms.Form
{
private int n = 0;
public void Button_Click(object sender, EventArgs e)
{
n = n + 1;
}
}
So, why is it with the page, that the old value of "n" is gone the next time you hit the page?
Because HTTP is a request/response protocol. Each request creates a new instance of your MyPage class, each with its own copy of "n". In a Windows Forms application, you're probably not creating a new instance of your form on every button click!

Resources