I'm trying to capture the value of my password to Label.
4 digit letter and 1 lower case letter
This is my method to add both digit and num
public void SaveTransactionID()
{
string password = lblStart.Text + lblStop.Text;
lblPassword.Text = password;
}
The generators:
private void GenRandomNumber()
{
Random generator = new Random();
String r = generator.Next(0, 10000).ToString("D4");
lblStart.Text = r;
}
//Generate Random Letter
static class RandomLetter
{
static Random _random = new Random();
public static char GetLetter()
{
// This method returns a random lowercase letter.
// ... Between 'a' and 'z' inclusize.
int num = _random.Next(0, 26); // Zero to 25
char let = (char)('a' + num);
return let;
}
}
My page load
protected void Page_Load(object sender, EventArgs e)
{
char lowerCase;
lowerCase = Convert.ToChar(RandomLetter.GetLetter());
lblStop.Text = lowerCase.ToString();
GenRandomNumber();
}
I know that my password will change every page load. That is why I tried to save it on my Label so I could capture the password in case the page loads again. But the things is my SaveTransactonId() also change during page load. How could I store the value of my password even with page load?
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
char lowerCase;
lowerCase = Convert.ToChar(RandomLetter.GetLetter());
lblStop.Text = lowerCase.ToString();
GenRandomNumber();
}
}
This will solve your problem.
EDIT:
Here's a short explanation of what conditions occur when IsPostBack = true or false. For a single computer for developing and debugging code, the "Client" is your browser and the "Server" is your computer. (In the linked article, the question is not "What is IsPostBack?" The correct question is "What is PostBack?" There is a better, more intricate diagram; I cannot find it, but this'll do.)
PostBack is the name given to the process of submitting an ASP.NET page to the server for processing. PostBack is done if (for example) certain credentials of the page are to be checked against some sources (such as verification of username and password for a database). This is something the client is not able to accomplish on its own and thus these details have to be 'posted back' to the server via user interaction.
A postback is round trip from the client (Browser) to the server and then back to the client. This enables your page to go through the asp engine on the server and any dynamic content to be updated.
For a more detailed answer to the PostBack question, see here.
Here is a description of the ASP.NET (web-) page life cycle overview, some of which involve PostBack.
write your code inside if(!Page.IsPostBack){// put your logic here.}
and You can save your value in Session["sessionKey"] = value;
and you can retrieve it by checking session is not null
if(Session["sessionKey"] !=null);
lblPassword.Text = Session["sessionKey"];
You can store the value in a Session variable; you can also control what runs in Page_Load on initial page load vs. subsequent page reloads (per session) via Page.IsPostBack property.
Related
I am creating a web browser using c# winform. I am using webbrowser control for this. I am using this code. This is running good so far
// Declared Variables
private string[] SiteMemoryArray = new string[100];
private int count = 0;
// Page Load
private void Form1_Load(object sender, EventArgs e)
{
webBrowser.Navigate("http://www.google.com/"); // Goes To A Preset Site At Run Time
SiteMemoryArray[count] = urlTextBox.Text; // Saves URL To Memory
}
// Code For The ToolStrip
// URL TextBox
private void urlTextBox_Click(object sender, EventArgs e)
{
urlTextBox.SelectAll(); // Selects All The Text In The urlTexBox
}
// GO Button
private void goButton_Click(object sender, EventArgs e)
{
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
}
// Back Button
private void backButton_Click(object sender, EventArgs e)
{
if (count > 0) // Checks To Make Sure The Count Variable Is More Then 0
{
count = count - 1; // Subtracts 1 From Count Variable
urlTextBox.Text = SiteMemoryArray[count]; // Replace The Text In The urlTextBox With The Last URl
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
forwardButton.Enabled = true; // Enables The forwarButton
}
}
// Forward Button
private void forwardButton_Click(object sender, EventArgs e)
{
if (count < 100) // Checks To Make Sure The Count Variable Is Less Then 100
{
count = count + 1; // Adds 1 To Count Variable
urlTextBox.Text = SiteMemoryArray[count]; // Replace The Text In The urlTextBox With The Next URl
webBrowser.Navigate(urlTextBox.Text); // Navigates To The Site Typed In The urlTextBox
backButton.Enabled = true; // Enables The backButton
count = count + 1; // Adds 1 To Count Variable
if (SiteMemoryArray[count] == null) // Checks To See If The Next Variable In The SiteMemoryArray Is Null
{
forwardButton.Enabled = false; // Disables The forwarButton
}
count = count - 1; // Subtracts 1 From Count Variable
}
}
But after create this small application my friend who is php developer ask me to check browser name . For this he create a php script n give me url then i run this url on my this browser its show me the browser name Internet Explorer
Now I want my browser name whatever I give name Please tell me is it possible with this control. Is there any property by using i can change it ?
The web browser control is IE. If you want to create your own browser, it is a lot more work than this. You need to write code that is able to do following and more:
Understand and handle HTTP protocol.
Understand, parse and render HTML. Most browsers ignore certain HTML errors and still render pages accurately. Not sure if you want that kind of features.
Your application should be able apply CSS settings on the pages.
Your application should be able to apply JS, flash, video, audio and other items that may well be embedded on a page.
You would also need to provide features that are available standard browsers.
The question is: What is the purpose of this application? Are you trying to write your own browser?
I need to implement a back button for my asp application.
In my web application I got 3 module
task1.aspx ->task1-1.aspx ->task1-2.aspx
task2.aspx-> task2-1.aspx->task3-1.aspx
task3.aspx->task3-1.aspx->task2.1aspx
In the above example.3 module also can navigate to other pages . So now I got problem, is it possible to implement a back button based on which previous page that I come from.
For example, I click
task3.aspx -> task3-1.aspx -> task2.1aspx
then when I click back button, will be
task2.1aspx -> task3-1.aspx -> task3.aspx.
On the other hand, when I click task2.aspx -> task2-1.aspx.
the back button will navigate me to task2-1.aspx ->task2.apx
Is it possible done in server side?
I would use use a Stack for this, and keep it in the Session. On each page load, push the current URL to the stack.
void Page_Init()
{
Stack<string> history = Session["history"];
if (history == null) history = new Stack<string>();
history.Push(Request.Url.AbsoluteUri);
Session["history"] = history;
}
Then of course in the click handler:
void Back_Click()
{
Stack<string> history = Session["history"];
if (history != null)
{
string url = history.Pop();
Session["history"] = history;
Response.Redirect(url);
}
}
You can do this way:
static string prevPage = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( !IsPostBack )
{
prevPage = Request.UrlReferrer.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect(prevPage);
}
For Multi-source cross page posting, it is suggested to use
<%# PreviousPageType TypeName
instead of
<%# PreviousPageType VirtualPath
I'm doing it in a somewhat similar way than dbaseman explains.
Basically, I append a BackUrl query string parameter to each URL I'm redirecting the client to and to each link that a user potentially may click. This BackUrl parameter contains the full URL of the current page (including all parameters).
So you end up of a string getting longer and longer on each subsequent redirect or link being clicked by the user. Some time, the URL get's way too long.
My solution is to not store the actual URL to go back in the BackUrl query string parameter but just a hash code. Server-side, I have a string dictionary (in the user's session) to remember the hash codes and the actual URLs.
On the clicking of any "back" button in my website, I do a lookup inside this dictionary and then redirect to the matching URL found in the dictionary for the given hash.
The drawback of this aproach could be that the dictionary may grow over time and never shrinks. In all of my real-world projects that was never an issue, though. Plus, it gets released if the session is discared.
So an example would be:
In task1.aspx, do not redirect user to task1-1.aspx, but to task1-1.aspx?BackUrl=24378.
Store a server-side dictionary entry, mapping 24378 to task1-1.aspx.
In task1-1.aspx?BackUrl=24378, do not redirect user to task1-2.aspx, but to task1-2.aspx?BackUrl=93748.
Store a server-side dictionary entry, mapping 93748 to task1-1.aspx?BackUrl=24378.
etc.
Then you can have a back button on your page.
If the user clicks that back button, it calls to your void BackButton_Click function.
In that function, use Request["BackUrl"] to get the hash code (e.g. 24378).
Use the hash code to look into the dictionary and get the actual URL.
Response.Redirect to that URL.
That's basically the idea.
Pseudo code:
Some pseudo code to make it more clear.
For the dictionary, I would write me a helper property inside a Page-derived base class, like e.g.
protected Dictionary<string, string> BackUrls
{
get
{
var dic = Session["backdic"] as Dictionary<string, string>;
if ( dic == null )
{
dic = new Dictionary<string, string>();
}
return dic;
}
}
You then can access the dictionary by writing to it or reading from it.
E.g. writing to dictionary:
private void goForwardToNextTask()
{
var hash = Math.Abs(Guid.NewGuid().GetHashCode());
// Store current page's full URL.
BackUrls[hash] = Request.RawUrl;
Response.Redirect( "task1-2.aspx?BackUrl=" + hash );
}
And reading from dictionary:
private void goBackward()
{
var hash = Request["BackUrl"];
// Backward translation.
Response.Redirect( BackUrls[hash] );
}
(All examples omit error and sanity checking).
I have a Button_click event. While refreshing the page the previous Postback event is triggering again. How do I identify the page refresh event to prevent the Postback action?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
This article could be of help to you
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this
http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
This worked fine for me..
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
Simple Solution
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1 without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loaded parameter of the query string.
Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState (assuming SessionState is enabled) and the value of the loaded QueryString parameter
the window.onbeforeunload event listener
keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
cookies
If someone does come up with a solution, I'd love to hear it.
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}
i am developing a web for my final project,and im new to ASP.NET and this forum.
thx to all who help me.
the question is...
example i have 2 pages.
page1.aspx.cs (this page for receive variable from mikrokontroler via network module)
example mikrokontroler send a variable "status" = 1
protected void Page_Load(object sender, EventArgs e)
{
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
}
page2.aspx
(in page 2 there is button and textbox)
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
}
You have a lot of options to store the variable value:
session state: Session["status"]= A
application state: Application["status"] = A
asp net cache: using Cache.Add()
database: here i would store also the timestamps, to trace the historic status of the controller.
local XML file.
It all depends on the scope of the stored data: session data is local to the current user/session and will expire after a predefined timeout(def: 20mins), application will be global to all your users/sessions and will expire when you will restart the application (by iis, iisreset, recompiling...), cache is global and will expire based on the parameters of invocation, the database and xml are global and will maintain state.
In your case i would use database or application store, because the microcontroller and user live in different sessions and the app cache is not a suitable messaging mechanism while Xml introduces some problems on his own (eg: filesystem permissions, data replication...).
write:
Application["status"] = A;
read:
int A = 0;
bool result = int.TryParse(Application["status"],out A);
BTW: to parse the integer you can skip the try/catch part doing this:
int A = 0;
bool result = int.TryParse(POST["status"],out A);
in this case if unable to parse A will be equal to 0;
You can use Session
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
Session["Avalie"] = A;
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
and then on page 2
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
if(!String.IsNullOrEmpty( Session["Avalie"] ))
int Aval = int.Parse(Session["Avalie"]);
}
Use crosspagepostback to pass values from one page to another (introduced in asp.net 2.0)
One option is to assign the value to a static variable in the first page.
Refer to Static Classes and Static Class Members (C# Programming Guide)
Another option is to use state variables as session state variables or application variables.
Refer to ASP.NET Session State Overview and ASP.NET Application State Overview
i have a webform that generates a file, but when i click the button that produces the postback to generate the file Once it finish if i press Refresh (F5) the page resubmit the postback and regenerates the file, there's any way to validate it and show a message to the user or simply DO NOTHING!
thanks :)
The simpler way will be to use Post Rediret Get pattern.
http://en.wikipedia.org/wiki/Post/Redirect/Get
Make sure to check out External Links on that Wikipedia article.
the browser should warn them if they hit refresh on a page that has been postbacked. how i handle it though is in the session track what i have done so i don't repeat certain actions. a simple flag should suffice.
Check for the existence of the file in question in your postback logic and only create the file if the file doesn't already exist:
if (false == System.IO.File.Exists(filename))
{
// create the file
}
else
{
// do whatever you do when the file already exists
}
i wrote a solution for this problem and here it is if anyone needs it.
protected void Page_Load(object sender, System.EventArgs e)
{
/*******/
//Validate if the user Refresh the webform.
//U will need::
//A global private variable called ""private bool isRefresh = false;""
//a global publica variable called ""public int refreshValue = 0;""
//a html control before </form> tag: ""<input type="hidden" name="ValidateRefresh" value="<%= refreshValue %>">""
int postRefreshValue = 0;
refreshValue = SII.Utils.convert.ToInt(Request.Form["ValidateRefresh"]); //u can use a int.parse()
if (refreshValue == 0)
Session["ValidateRefresh"] = 0;
postRefreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
if (refreshValue < postRefreshValue)
isRefresh = true;
Session["ValidateRefresh"] = postRefreshValue + 1;
refreshValue = SII.Utils.convert.ToInt(Session["ValidateRefresh"]); //can use a int.parse()
/********/
if (!IsPostBack)
{
//your code
}
}
you just have to evaluate:
if (!isRefresh)
PostFile();
else
{
//Error msg you are refreshing
}