I have an asp.net page, and a static value totalBalance that sums the values in a column in a gridview.
I found, when I refresh the page, the totalBalance get accumulated instead of keep the original value.
Is there any code I could insert so that it can refresh the values, and each time I refresh the page, it is re-calculating the column values instead of accumulating numbers?
I currently have this RemoveCache
protected void RemoveCache()
{
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;
}
Can I insert some code in this or the aspx to reset the value after running please?
Thanks.
Never mind, I set totalBalance=0 when loading the page....
A static variable is a variable that has one copy of it (which means shared throughout the application) and its lifetime is the same as the application, once instantiated. Regardless of refresh, the variable is the same one from the first time it was created and you are re-using and re-totaling a running value. I would say stop using static variables in your web applications unless you really understand the implications and the problem should go away.
Related
Im trying working on a web app project and trying to figure out how to display my answer on the second web page.
I have put a a text box on my first webpage and have corrected the coding of my application as I have received the correct answers in the textbox after I have debugged it.
Ideally I want to remove this textbox and want my answers which I managed to display on my textbox displayed on a label in the next webpage. Here is the calculation part of my code;
var cost = ((int)duration.TotalMinutes) * 0.35m;
txtCost.Text = cost.ToString("c");
I'd like to make my answer appear in my second webpage and not have it displayed in the first. I have tried using Session["Cost"] = cost; on the button click event handler of the first webpage double cost = (double)(Session["Cost"]);
lblDisplay.Text = cost.ToString("c");
and this on the second webpage but every time I Debug it and run I always get $0.00 displayed on my label. Can someone help me fix this?
Sharing value between two views in MVC application, try following
// To save into the Cache
System.Web.HttpContext.Current.Cache["CostKey"] = cost;
// To retrieve Cache Value
var cachedValue = System.Web.HttpContext.Current.Cache["CostKey"] as double;
For Session State, have a look at this link
In ASP.NET WebForms application, you can pass data around in various ways:
Cache
See the Learning Curve answer for examples.
However, the object put in the cache is not guaranteed to be found again if the server experiences memory shortage or alike. The ASP.NET manages the cache and evicts objects on its own to maintain memory availability. This is in contrast with ApplicationState and SessionState where the objects are kept until they are removed manually, or the Application ends or Session expires.
Session and Application states
You can put any object in the SessionState object and retrieve it elsewhere in your code. However, you need to cast it appropriately as the SessionState accepts object-s. E.g. if you store a number, when you retrieving it, you must do the casting yourself, just as you already did it.
The reason it doesn't work, is perhaps you're trying to retrieve it from within another user's SessionState. Yes, the SessionState is a per-user structure. If you need to add the value as from one device and use it on another, use ApplicationState:
Application["cost"] = cost;
Redirecting Response
Using this technique, you could force the browser to request another page from the server and specify the full query string, including the variables you need. E.g. :
var destination = Server.UrlEncode("/someOtherPage.aspx?cost=34.65");
Response.Redirect(destination);
As an alternative, you can use Server.Transfer("someOtherPage.aspx") to save the roundtrip. However, in that case, the browser doesn't change the address in the address bar so the user is misled that she browses one page, but in fact, it is the someOtherPage.aspx.
This question already has answers here:
Scope of static Variable in multi-user ASP.NET web application
(4 answers)
Closed 7 years ago.
I have a problem with a static variable in ASP.NET using C#. I'm declaring the variable in a webform.
public partial class Logueado_Movimientos : System.Web.UI.Page
{
static List<ExchangeItems> theList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostback) return;
theList = GetListValues();
}
}
So far, so good. We tested the site, no problems were found, deployed it... but in production environment something weird has happened. This site is used daily all day long and just twice, a situation has happened.
ExchangeItems has an ID property, which returns the id from the database for each item to be exchanged. The GetListValues() method is called only once when the page loads. After that, the user can select items to be exchanged by clicking on a checkbox in the GridView, make further validations and after all that, there's a "Print and Save" button, which prints to a PDF using iTextSharp and sends the status back to the database.
After all the validations, the item has been changed twice in production. For example, item 180 is the one that is being exchanged, but when the document is printed and saved, it turns out that item 103 is the one processed. All previous validations have the ID as 180. Item 103 was not even in the list to begin with.
Now, checking the database (SQL Server) we found that item 103 was saved 10 minutes after item 180. We use the GetDate() function to store the date and time. Furthermore, they were assigned to different customers by two different users.
It is possible that the user takes those 10 minutes to process the request, sometimes they are on the phone with the customer. That means that user1 is working with item 180 and user2 is working with item 103, both using the same module/webform. Since the variable is static, is it possible that both users are affecting each other's information? I'm declaring it now as "private static", just out of paranoia, but is there anything else I'm missing?
Note: the variable is static because the postback losses it's value if not declared so. It is not in the Session variable, because it is only used in that module/webform, nowhere else.
Since the variable is static, is it possible that both users are affecting each other's information?
Yes - static variables are shared across sessions. Making it private does not change that. One option may be to use a session variable instead
Session["theList"] = GetListValues();
It is not in the Session variable, because it is only used in that module/webform, nowhere else.
So? There's nothing wrong with having session data that's not used by the whole app.
I have a page which has a text box at the top. When the page is loaded, the code runs for the value of text box i.e Textbox.text= something. The logic of that code is:
bring the last value of the specific column of specific table from database (Integer always)
add 1 to it
show in text box.
It works perfectly fine. But I want to know that if two users are accessing the same page how should I handle this scenario when page is loaded.
Example the last value in DB column was 8 when the page loaded it incremented it and showed 9 in text box.
But what if two users loaded the page same time on different browsers it will cause problem because I don't want duplicate in my columns.
What you can do here is before you insert into db first get the last value from the colum and then +1 the value and then insert it into db.
but there is one catch which is if your User1 and User2 are seeing 8 value in textbox and User1 clicks on button 9 will get stored in db column and then User2 clicks on button 10 value will get stored.
Your best bet would be to load the database value into memory (e.g. a static variable) and have a method that uses a lock before incrementing and returning the result to the respective users. e.g.
private static object _syncRoot = new object();
private static int? dbValue;
public static int GetNewDbValue()
{
if (dbValue == null)
{
// load db value from database
}
// lock ensures only one user can increment at a time
lock (_syncRoot)
{
dbValue++;
return dbValue;
}
}
This will work as long as you are not running a web farm or load balancing. If you want to stay away from static, by all means you can, just make sure the object you use instead is centrally accessible.
I'm looking to create a simple web form, and I would like to "discourage" users from filling a form out multiple times. The metrics of the form are used for statistical analysis, and each time a user fills out and resubmits the form, the result set usually changes, and hence analysis.
While we don't want to BLOCK re-trys (knowing that a re-try was done is also valuable information), we do want to warn users: "Hey, it looks like you filled this out recently. Are you sure you want to fill it out again?"
The caveat here is that we want to minimize the amount of personably identifiable information collected.
Is storing a cookie with the clients IP the best/simpliest way to do this? Or is there a simple method for caching an IP server-side for xx amount of time so we can run a comparison to says "hey, I think this guy tried to access me earlier today. I should present a warning".
Cookie with constant value should be enough, not even IP. If user did not cleared cookies you'd know that the user already filled out the form.
On easy solution I've used before is to put an invisible timestamp in the HTML form the user fills out. If you get submitted the same timestamp twice, you know its a re-submittion.
If you're worried about tampering, you can always mix up/encrypt the timestamp.
This could also just be a random unique identifier, I chose a timestamp in order to know how long a user took filling out a form (roughly).
This is basically like a session cookie, but might be considered more "private" as theres nothing for a client's computer to remember so it can't be used as like some tracking cookies ad sites.
The downside is that this method requires that a client/proxy not cache the form as it "changes" every request.
There are two issues here the user clicking the submit button multiple times, and the user filling in the form at another point in time.
For the second I can see two quite simple solutions would recommend a session cookie, just cookie the users machine and don't let them see the form again, or ask for a piece of information like email address and then check in the DB if its been used before, if so disregard the new form details.
For the multiple form submit you can use this code, which will disable the button onclick.
//
// Disable button with no secondary JavaScript function call.
//
public static void DisableButtonOnClick(Button ButtonControl)
{
DisableButtonOnClick(ButtonControl, string.Empty);
}
// Disable button with a JavaScript function call.
//
public static void DisableButtonOnClick(Button ButtonControl, string ClientFunction)
{
var sb = new StringBuilder(128);
// If the page has ASP.NET validators on it, this code ensures the
// page validates before continuing.
sb.Append("if ( typeof( Page_ClientValidate ) == 'function' ) { ");
sb.Append("if ( ! Page_ClientValidate() ) { return false; } } ");
// Disable this button.
sb.Append("this.disabled = true;");
// If a secondary JavaScript function has been provided, and if it can be found,
// call it. Note the name of the JavaScript function to call should be passed without
// parens.
if (!String.IsNullOrEmpty(ClientFunction))
{
sb.AppendFormat("if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction);
}
// GetPostBackEventReference() obtains a reference to a client-side script function
// that causes the server to post back to the page (ie this causes the server-side part
// of the "click" to be performed).
sb.Append(ButtonControl.Page.GetPostBackEventReference(ButtonControl) + ";");
// Add the JavaScript created a code to be executed when the button is clicked.
ButtonControl.Attributes.Add("onclick", sb.ToString());
}
How do I go about when page is reloaded that I make sure the variables I have declared at the top o my class do not get reset. IE I have a counter that is originally set at 0 if I use a postback control it resets that variable how do i go about not having this happen in C#?
Are you looking for a value specific to the client or to the server?
If you want something specific to the client use a cookie or session value.
If you are looking something specific to the server use a static class, application or cache value.
Use ASP.Net Session or Cookies. Or you can store their values in hidden fields. You can read about theese and outher option in following article.
Put the value you want to save in a cookie.
if you´re using a postback, not a link, you should save your data into viewstate.
vb
Public Property MyValue() As String
Get
Dim _mv As Object = ViewState("MyValue")
If Not _mv Is Nothing Then
Return _mv.ToString
End If
Return String.Empty
End Get
Set(ByVal value As String)
ViewState("MyValue") = value
End Set
End Property
C#
public string MyValue {
get {
object _mv = ViewState("MyValue");
if ((_mv != null)) {
return _mv.ToString();
}
return string.Empty;
}
set { ViewState("MyValue") = value; }
}
ViewState is saved along PostBacks, if you stay on the current page. For Example if you are on page.aspx and using a <asp:button> that is clicked each time, you can use Viewstate as a place for saving some of your data, it looks in the page source code like this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4Mzg3MjEyMzdkZNNlI9zvMeIGeUB4MZbJA2gmsHns9IsmAy/c4dQMybXD" />
the viewstate is generated automatically
That data is not persisted on HTTP Requests; you need to persist it in a cookie, hidden control, or manually store it in view state.
If you're manually doing a page counter, consider storing it in session state.