visual studio 2010 c# traverse between web pages on aspx.cs - c#

As title state after my solution on aspx.cs I want to switch to another web page to remove cookies and avoid resending the same email.

Do the PRG pattern
After you done with your transaction, Redirect to another page (showing "It is done successfully" or some other message). Now Refresh can not beat you
To Redirect, You can use Response.Redirect method
Response.Redirect("welcome.aspx")

You could add a Session which prevents the email being sent again (if this is a once per session email (ie. Newsletter sign up etc)).
Then check whether this Session exists before sending the email:
if (Session["emailsent"]==null){
//Send email code here
Session["emailsent"] = true;
}

you have to test
in your page_load event
if(!IsPostBack)
{
//send mail...
}
else
{
//do nothing
}

Related

How to persist a value in asp.net label after response.redirect to same URL

I have an application which is used by another application by passing credentials in querystring to my application.I will take the querystring and do the LDAP authentication .If it is failed , i will move to my application login page to enter credentials after clearing querystrings(Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""), false);) from URL.But here i have to show a message to user like invalid NT credentials.I assigned the message to Session variable and then assigned to a asp.net label,but it is not working ie no warningmessage coming.
This is the code i did
if (AutheticateLDAP("LDAP://dc01-opsoft.corp.ae", txtUserName.Value, txtPassword.Value))
{
}
else
{
Session["val"] = "Invalid credentials,Use NT UserId and Password";
if (!string.IsNullOrEmpty(Request.Url.Query))
{
txtUserName.Attributes.Remove("readonly");
txtPassword.Attributes.Remove("readonly");
Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""), false);
}
lblMsg.Text = Session["val"].ToString();
return;
}
Here when i debug i can see that values are properly assigned to lblMsg.Text,but finally it disappears in UI
As i understand you have to remain on the same page and show a error message.
The problem below is that you do a response redirect. What happens after is that you do a redirect which results in a complete page reload.
if (!string.IsNullOrEmpty(Request.Url.Query))
{
Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""), false);
}
With triggering the page reload assigning the lblMsg.text in the response before is already lost. Meaning in the new page load you have to assing the value of the label again. Unles you call the exact same method again to get to the point where the lblMsg.Text is being set to makethis work.
The reason you see the lblMsg.text being set is because of doing a Response.Redirect(Request.RawUrl.Replace(Request.Url.Query, ""), false);. The false means do not end the response so it finishes to execute the code in the method and after does a redirect.
The cleaner way would be to not response.redirect but just show the label with the error. if you are concerned about the querystring and wanna clean it then keep doing a redirect and use this example how to show a message after redirect. Instead of the javascript alert you can set the 'lblMsg.text`

Is this possible to clear the session whenever browser closed in asp.net?

In my asp.net application, i want to clear the session whenever my browser closed or my tab (if my browser containing multiple tabs)closed.
Please guide me to get out of this issue...
Short version, No.
There's no solid way of a server detecting if the client has closed their browser. It's just the nature of web development's asynchronous pattern.
Long version, if it's really, really important to you;
Put a bit of javascript in the page that sends a regular post to your website in the background and set up a serverside agent or service that disposes of the sessions if it doesnt receive these regular "heartbeat" signals.
You can put a javascript postback onto the page's unload() event but dont rely on it, it doesnt always fire.
This happens by default whenever you close your browser, and that's not just for ASP.NET. It's for most server-side programming languages that have a session state. Basically, any cookie that is added that doesn't specify an expiration date, will be deleted when the browser is closed.
Where this doesn't apply, is when you close a tab, which is something you will not have any control over because the tab close event will not get sent back to the Web server.
You can try to do that with javascript. Check it at:
http://www.codeproject.com/Tips/154801/How-to-end-user-session-when-browser-closed
Alternatively you can check you previous session state on every new browser opening and can Session.clear() or Session.abandon() the previous session.
this will make sure that every time you start application you will get new session.
use BasePage in your .net application.
Check the session.sessionid on basepage load.
More Inforamtion how to detect new session in basepage. BasePage.Session.Link
Hope this helps
regards
Shaz
public class BasePage : Page
{
protected string mySessionId;
private CurrentUser _currentUser;
public CurrentUser _CurrentUser
{
get { return ((CurrentUser)HttpContext.Current.Session["myCurrentUser"]); }
set { _currentUser = value; }
}
protected override void OnLoad(EventArgs e)
{
if (Session["myCurrentUser"] != null)
{
if (_CurrentUser.ProUser)
{
mySessionId = Session.SessionID; // it means New Session
}
if (!mySessionId.IsNullOrDefault() && mySessionId != Session.SessionID)
{
Session.Abandon(); //Abandon current session and start new one
}
}
}
}
I think cookies can better meet your requirement here for session management.
it means that session data should not be stored on the server and
should be with your call, so that you don't have to worry about
clearing the data on server.
Yes.First of all Browser automatically clear session when browser is closed. you can try to capture browser close or tab close event in browser using javascript function like on before unload and on unload. Mostly onbefore unload event captures browser close event in chrome, Firefox, IE 11.
You can use Session_End event of Global.aspx
//For Specific Session
Session.Remove("SessionName");
//All the Session
Session.Abandon();

PhotobucketNet photo upload

I have a problem with PhotobucketNet user login(I need user to login so I can upload a picture from HDD to his Photobucket account).
Photobucket photobucket = new Photobucket("myapikey", "myapisecret");
photobucket.LaunchUserLogin();
// the problem happens here
photobucket.RequestUserToken();
If I call RequestUserToken() it will happen immediately, so I'll get a crash cause user didn't logged in, and there is no event that's been raised after user logs in. Is there some variable(bool or something else) that I can check to see if user logged in - maybe to put it in a loop with timer?
Also is their a way to know if user canceled logging in?
I know that timer isn't a good solution, so if anyone has anything better as an idea, I'm open for any suggestions...
I've encountered the same problem today and i found your post while i was searching for solutions. Here is how i managed to solve the problem:
Firstly, i got the "user login url" and passed it to a form with a web browser control, called "Login".
Service=new Photobucket ("mykey", "mysecret");
string u=Service.GenerateUserLoginUrl ();
Login l=new Login (u);
l.Show ();
Next, I got the url from this page,
which is the page after the login. If the web browser's url is that page, i asked the photobucket class (in my case Program.Service), to request the token.
The code from the Login form is something like this:
public Login (string url)
{
InitializeComponent ();
webBrowser1.Navigate (url);
webBrowser1.DocumentCompleted+=delegate
{
if (webBrowser1.Url.ToString ()=="http://photobucket.com/apilogin/done")
{
PhotobucketNet.UserToken t=Program.Service.RequestUserToken ();
//save the token
}
}
}
Now you just save the token and use it.

How to force the user to change his password after first login?

I want to force the user to change his password after his first login. Now, where should I put the redirection code to ChangePassword page ?
If I put it in the Page_Load of Default page, user can move to any page because he is Authenticated.
If I put it in the Page_Load of Master page, the ChangePassword page uses the same master page, and it'll enter in an infinit loop of redirections.
I though of ignoring the redirection if the Page is the ChagePassword page from the Master page, and I found this answer which says:
This sounds like a bad idea to start with. The idea of the master is that it shouldn't care what page is there as this is all common code for each page.
Any suggestion!
Here you are, a fully tested solution ;)
protected void LoginButton_Click(object sender, EventArgs e)
{
/****note: UserName and Password are textbox fields****/
if (Membership.ValidateUser(UserName.Text, Password.Text))
{
MembershipUser user = Membership.GetUser(UserName.Text);
if (user == null)
{
FailureText.Text = "Invalid username. Please try again.";
return;
}
if (user.IsLockedOut)
user.UnlockUser();
/* this is the interesting part for you */
if (user.LastPasswordChangedDate == user.CreationDate) //if true, that means user never changed their password before
{
//TODO: add your change password logic here
}
}
}
You can do it in GLobal.asax file.
Check if user in logged in and request url is not ChangePassword then redirect to change password page.
/// <summary>
/// this event occurs just after user is authenticated
/// </summary>
void Application_AuthorizeRequest(object sender, EventArgs e)
{
// check if user is authenticated
if (User.Identity.IsAuthenticated)
{
// checking page extension
switch (System.IO.Path.GetExtension(Context.Request.Url.AbsoluteUri.ToLower()))
{
case ".bmp":
case ".gif":
case ".jpg":
case ".jpe":
case ".jpeg":
case ".png":
case ".css":
case ".js":
case ".txt":
case ".swf":
// don't redirect, these requests may required in many cases
break;
default:
// checking if request is not for ChangePassword.aspx page
if (!Context.Request.Url.AbsoluteUri.ToLower().Contains("/changepassword.aspx"))
{
Context.Response.Redirect("~/ChangePassword.aspx");
}
break;
}
}
}
We had an app with similar requirements. We extended the base ASP.NET membership provider to allow for a check on the LastPasswordChangedDate and compared it to the CreateDate. If equal, that means the user has never changed their password, and was redirected to the login page.
I see you would like to have some kind of check to keep bugging them even after the login. I think you can accomplish this in the AuthorizationRequest of the Global.asax. That might be expensive though.
You may handle the following events of the Login control,
•LoggedIn
•LoggingIn
Good luck, I hope this helps.
as i understand you should put the validation code in "Page_PreRender"
protected void Page_PreRender(object sender, EventArgs e)
{
//Validation Code
}
this event will fire the code before the page renders anything
Which object are you putting into the section in order to evaluate if the user is authenticated? I would just set a boolean property named "ChangePasswordOnNextLoggin", then if its true I redirect to "ChangePassword.aspx", you may put it wherever you want (even in the master page, as you only redirect if this property is true, avoiding the infinite loop).
But personally I would make a wrapper for the PAGE object, that every .aspx code behind class should inherit, then I would inherit this wrapper instead, on the wrapper ctor I would add an Authenticate method to the Load event in such a way it would be the first method to be called when any page is loaded. If I do it, i'm able to avoid putting validation code on MasterPage and the code behind, making the code cleaner. Do you get it?
In the place of your code where the user is authenticated.
Since you want the user to change his password on the very first login, after registration, you just create one more field in your database's login table which will have a status value whether the initial pasword change process has been done. So when a user logs in the first time, that value is checked and, if it is something like "unchanged," redirect the user from the login page to the change password page. Upon successful password change, update the field.
In SQL Server 2005(plus VS2008), Apart from all the "add one more field" approaches, I think it's much easier to execute asp.net security database's built in stored procedure aspnet_Membership_FindUsersByName. It returns a dataset with all the info you'll ever need incl last activity date, last password change date, last login date etc with time values.

ASP.NET MVC 2 caching problem

I'm writing an app and have come across caching problem which I cannot work out.
I have a default Home controller for the site which checks whether the user is authenticated or not.
If is not then LogOn View is displayed otherwise the client is redirected to another page.
Along with the LogOn view, also a Check cookie is being sent to user to check on response if his browser supports cookies or not.
When I delete the cookie before sending the form with credentials, Home (Post method) in Home controller displays message that cookies must be enabled with a button which
should refresh the page with Logon boxes(http://localhost:1234/)
This button is linked to js refresh function:
var sURL = unescape("/");
function refresh()
{
window.location.href = sURL;
}
I have implemented CacheFilter which is set on the base controller.
public class NoCache : ActionFilterAttribute, IActionFilter
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}
}
and the problem is that if I Immediately click the button to refresh LogOn page, browser read it using its cache. But when I do it after a few seconds then the query is sent to the server.
This is wrong, because LogOn page should also create again a Check cookie.
It seems to me that the cache policy is set to 1-2 seconds, and after this time pages are reloaded from the server.
What is wrong? Thanks for help.
I have seen some similar behaviour, related to the javascript in IE7. The browser 'helpfully' realizes that you've recently requested that URL and therefore serves up the cached version. If this is the case, the solution is to make sure the URL is unique every time by adding a pseudo random number. I use something like:
function refresh()
{
window.location.href = sURL + "?rnd="+ Math.random();
}
Am I right in saying you're testing this by running this in Visual Studio?
As far as I know you can't enable things like caching in the Visual Studio Development Server. This is something you will enable on your webserver, which I guess will be IIS in your case.

Categories