Basically a web app that we distribute to clients, one of whom will be trialling it so I need to be able to switch it off at a certain point. Don't want to put the end date in the web.config in case they work out they can change it, I was thinking of putting something in the global.asax with a hard coded date, but then I'm not sure how I can 'turn off' the app. I was thinking of checking the date in the Authenticate Request part and simply redirecting to a page that says your trial is finished (or something similar), but is there a better way?
You can do that on global.asax as:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if(DateTime.UtcNow > cTheTimeLimitDate)
{
HttpContext.Current.Response.TrySkipIisCustomErrors = true;
HttpContext.Current.Response.Write("...message to show...");
HttpContext.Current.Response.StatusCode = 403;
HttpContext.Current.Response.End();
return ;
}
}
this is safer than place it on web.config, but nothing is safe enough. Its even better there to redirect them to a page, or not show them a message, or what ever you think.
For make redirect to a page you also need to check if the call if for a page, and the code will be as:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
{
// and here is the time limit.
if(DateTime.UtcNow > cTheTimeLimitDate)
{
// make here the redirect
HttpContext.Current.Response.End();
return ;
}
}
}
To makes it even harder, you can make a custom BasePage that all page come from it (and not from System.Web.UI.Page) and you place there the limit on the render of the page - or show a message on top of every page render, that the time is ends.
public abstract class BasePage : System.Web.UI.Page
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
if(DateTime.UtcNow > cTheTimeLimitDate)
{
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// render page inside the buffer
base.Render(htmlWriter);
string html = stringWriter.ToString();
writer.Write("<h1>This evaluation is expired</h1><br><br>" + html);
}
else
{
base.Render(writer);
}
}
}
Just add the app_offline.htm and you can even create a nice message for your users. Also it's very easy to put the site back online, just remove or rename the app_offline.htm.
http://weblogs.asp.net/dotnetstories/archive/2011/09/24/take-an-asp-net-application-offline.aspx
Related
I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
I have a .aspx web page, with a html form within it, this also has two input boxes.
Whats the best way to take the input box data and pass it to a new .aspx page where it is dealt with by the request method.
Assuming that the data is not sensitive then the best method to pass it to your new page using Response.Redirect and the querystring using:
protected void MyFormSubmitButton_Click(Object sender, EventArgs e)
{
string value1 = txtValue1.Text;
string value2 = txtValue2.Text;
// create a querystring
string queryString = "x=" + value1 + "&y=" + value2;
// redirect to the encoded querystring
Response.Redirect("NewPage.aspx?" + Server.URLEncode(queryString));
}
This web page has a lot of information which you can use for passing the values from page to page.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx#Y1100
Try Server.Transfer:
Terminates execution of the current
page and starts execution of a new
page by using the specified URL path
of the page. Specifies whether to
clear the QueryString and Form
collections.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
Your main page:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// ThreadAbortException occurs here.
// See http://support.microsoft.com/kb/312629 for more details.
Server.Transfer("AnotherPage.aspx", true);
}
}
"AnotherPage.aspx":
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
// Accessing previous page's controls
}
}
i'm trying to set my website's culture programmatically, so when a user clicks a button they can change the text on the page from english to spanish. here's my code:
protected void btnChangeLanguage(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("es");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es);
}
<asp:Label ID="lblDisplay" runat="server" meta:ResourceKey="lblDisplay" />
<asp:Button ID="btnChangeLanguage" runat="server" Text="Change Language"
OnClick="btnChangeLanguage_Click" />
i have a Default.aspx.resx file with a key/value of: lblDisplay.text/English
and a Default.aspx.es.resx file with a key/value of: lblDisplay.text/Espanol
i can't get my Label's text to change from "English" to "Spanish". anyone see what i'm doing wrong?
ASP.Net threads are used for the lifetime of one request, not a user's entire session. Worse, sometimes the framework will recycle the same thread to handle additional requests rather than return it to the pool and get a new one (it's not that big a deal because the next request will initialize the culture again, but still).
Instead, you need to override the InitializeCulture() method for your page. See this link for more detail:
http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
Create Session variable called "CurrentUI". and change it on link buttons event
eg:
Here i have two link buttons for each language
protected void EnglishLinkButton_Click(object sender, EventArgs e) {
Session["CurrentUI"] = "en-US";
Response.Redirect(Request.Url.OriginalString);
}
protected void SinhalaLinkButton_Click(object sender, EventArgs e) {
// සිංහල (ශ්රී ලංකා)
Session["CurrentUI"] = "si-LK";
Response.Redirect(Request.Url.OriginalString);
}
Now you need to override the InitializeCulture() in the base class of page
protected override void InitializeCulture() {
if (Session["CurrentUI"] != null) {
String selectedLanguage = (string)Session["CurrentUI"];
UICulture = selectedLanguage;
Culture = selectedLanguage;
Thread.CurrentThread.CurrentCulture =
CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentUICulture = new
CultureInfo(selectedLanguage);
}
base.InitializeCulture();
}
Note that I used
//Response.Redirect(Request.Url.OriginalString);
after assigning culture key into the session in order to create a second post back to the page.
Because InitializeCulture() happens before the event and change will be applicable in the next request only.
Duplicate of Asp.Net Button Event on refresh fires again??? GUID?
hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again.
any one know some method to prevent page refresh with out redirect the page to the same page again ?
something like if (page.isRefresh) or something... or if exist any javascript solution is better.
this seen to works.... but when i refresh it does not postback but show the before value in the textbox
http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx
private Boolean IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
TextBox1.Text = "Hi";
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) // check that page is not refreshed by browser.
{
TextBox2.Text = TextBox1.Text + "#";
}
}
Thanks for comments and sorry for my mistake,
I found this code in:
http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx
And this time tested ;)
private bool _refreshState;
private bool _isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
_refreshState = bool.Parse(AllStates[1].ToString());
_isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
}
protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] AllStates = new object[2];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(_refreshState);
return AllStates;
}
protected void btn_Click(object sender, EventArgs e)
{
if (!_isRefresh)
Response.Write(DateTime.Now.Millisecond.ToString());
}
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: w3schools on IsPostBack
Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place.
If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history.
Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem.
First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution.
All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information.
I haven't seen any solution to this I'm afraid, as it is pretty complex.
bool IsPageRefresh ;
if (Page.IsPostBack)
{
if (ViewState["postid"].ToString() != Session["postid"].ToString())
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postid"] = Session["postid"];
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like...
I put that on my custom basepage to reuse it like an Property
public bool IsPageRefresh = false;
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var rForm = Request.Form;
var vw = rForm["__EVENTVALIDATION"].ToString();
var svw = Session["__EVENTVALIDATION"] ?? "";
if (vw.Equals(svw)) IsPageRefresh = true;
Session["__EVENTVALIDATION"] = vw;
}
}
I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen?
The page is a custom page in Community Server. Here is the basic code:
void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// Code removed for testing.
Response.Clear();
Response.Redirect("ApproveResidents.aspx", true);
Response.End();
}
A Response.Redirect will trigger an HTTP GET from the browser. As no data is posted, IsPostBack is false. You have something else going on.
I'd suggest firing up Fiddler and looking at the sequence of requests. It should look something like:
Client: HTTP POST (button click)
Server: HTTP 302 (Redirect)
Client: HTTP GET
Server: HTTP 200 (Writes page)
I suggest this as a better solution to your problem than attempting to redirect from the browser.
protected void Page_Load( object sender, EventArgs e )
{
if (!IsPosBack) {
BuildData();
}
}
void btnApprove_Command(object sender, CommandEventArgs e)
{
// do your stuff and clear any some controls, maybe
BuildData();
}
private void BuildData()
{
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr);
DataTable tbl = new DataTable();
da.Fill(tbl);
da.Dispose();
rptNonResidents.DataSource = tbl;
rptNonResidents.DataBind();
}
Sorry, it was an id-10-t error. My event handler wasn't getting called at all. The page had EnableViewState="false". Once I changed that to true it worked.
I also took tvanfosson suggestion. This allows me to display a confirmation message. I can easily check to see if the action has already been taken and safely ignore it. Since I'm likely the only one to ever see this screen, I'm not too concerned with usability.
Response.Redirect(url,true);
this worked for me.
The page is posted back , that is why you're getting it as true. make sure it is false.