This is the code behind of button named "Create". How can i add automatically "membershipCreateStatus" through the condition if. I try to add it manualy and i get an erroe message: "The name 'membershipCreateStatus' does not exist in the current context"
protected void btnAddUser_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
membershipCreateStatus
}
}
}
}
you need to add
using System.Web.Security;
protected void btnAddUser_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MembershipCreateStatus createStatus;
MembershipUser newUser = Membership.CreateUser(Username.Text, Password.Text, Email.Text, passwordQuestion, SecurityAnswer.Text, true, out createStatus);
}
}
Related
In my asp.net project I have an event in global.asax as session end which fires when the session is timeout and in this event, I am calling one stored procedure that updates logout time and flag in the table. But when the user is log in and after some work user close browser and on next day when he tries to log in at first attempt message shows that user is already login but when he tried to log in again he is able to log in.
please help its production issue.
<%# Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
}
void Application_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
objUserRole.SchemaName =
(string)CBase.TripleDESDecode(Application["SchemaName"].ToString(),
CBase.EncryptionKey);
if (Session["UserId"] != null)
objUserRole.UserId = (string)Session["UserId"];
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
}
void Application_Error(object sender, EventArgs e)
{
Exception ex = this.Server.GetLastError().GetBaseException();
}
public HttpSessionState GetSession()
{
if (HttpContext.Current != null)
{
return HttpContext.Current.Session;
}
else
{
return this.Session;
}
}
void Session_Start(object sender, EventArgs e)
{
}
void Session_End(object sender, EventArgs e)
{
Admin.User_Role objUserRole = new Admin.User_Role();
string userid = Convert.ToString(GetSession()["UserId"]);
objUserRole.UserId = (string)CBase.TripleDESDecode(userid,
CBase.EncryptionKey);
objUserRole.ModifiedDate = Convert.ToDateTime(CBase.GetServerDateTime());
// objUserRole.funcUpdateLoggedIn();
try
{
objUserRole.funcUpdateLoggedIn();
}
catch (Exception ex)
{
//Response.Redirect(HttpUtility.UrlEncode("Logout.aspx"), false);
}
finally
{
Session.Abandon();
Session.Clear();
}
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
if (!IsPostBack)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
}
the user loged in and he is authenticated, but when I check for his name I get ""
I try to get the user name using a jquery ajax, and I return the data to the ajax
update:
a look at my immediate window (while in a break point) when a user named moria is logedin
**User.Identity**
{System.Web.Security.FormsIdentity}
[System.Web.Security.FormsIdentity]: {System.Web.Security.FormsIdentity}
AuthenticationType: "Forms"
**IsAuthenticated: true**
**Name: ""**
**Membership.GetUser()**
**null**
**Membership.GetUser("moria")**
{moria}
Comment: null
CreationDate: {23/02/2016 01:10:08}
Email: "orders.gca#gmail.com"
IsApproved: true
IsLockedOut: false
IsOnline: false
LastActivityDate: {24/02/2016 03:21:08}
LastLockoutDate: {01/01/1754 02:00:00}
LastLoginDate: {24/02/2016 03:21:08}
LastPasswordChangedDate: {23/02/2016 01:10:08}
PasswordQuestion: "1"
ProviderName: "MySqlMembershipProvider"
ProviderUserKey: {ff589472-e852-4049-8803-6d22740414ee}
UserName: "moria"
Taking from ADreNaLiNe-DJ's answer and adding in the ability to redirect back to the calling page, you would add this to the Global.asax file:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var loginUrl = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Login", "Account") ?? "";
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains(loginUrl))
{
Response.Redirect(loginUrl + "?ReturnUrl=" + Request.Url.AbsoluteUri);
}
}
Hope that helps.
First of all, you should check authentication earlier in the pipeline.
Add this code in your Global.asax.cs:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains("login.aspx"))
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
}
You check authentication for all pages/requests in 1 unique place.
So when you are in the Page_Load, you are sure to be logged in and authenticated.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
I have some validation code in my WebForm page. When a user clicks on a button and does a postback.
Page_Load event gets processed then the Button1_Click event gets processed.
I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.
Is a trick to do this?
Thanks
4 variations shown below.
public partial class _Default : System.Web.UI.Page
{
private bool MyPageIsValid { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bool valid = false; /* some routine here */
MyPageIsValid = valid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.MyPageIsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!this.MyPageIsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
I think it should be better to check validation conditions exactly in the Button1_Click method like this:
if (!this.IsValid()) { return; }
Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:
if (!this.isValid) { return; }
I want to get the username after login but it doesn't work.
public partial class Login : System.Web.UI.Page
{
string strUser;
protected void Login1_LoggedIn(object sender, EventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
}
This is my error:
Membership.GetUser().UserName is null, because the new principal object is not attached to the current HttpContext object yet.
So you need to explicitly retrieve that recently logged-in user using username from Login control.
Update: Credit to jadarnel27
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
// Get the username from login control and retrieves the user info explicitly
Membership user = Membership.GetUser(Login1.Username);
...
}
You need to check and make sure the user's login was successful. It looks like you're just using standard ASP.NET membership, so this should work:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if(e.Authenticated)
{
strUser = Membership.GetUser().UserName;
Response.Redirect("Home");
}
else
{
strUser = "Login Failed!";
}
}
It's been a while since I worked with these controls, but you might need to determine the value of e.Authenticated yourself first and set it. If so, you need to put this before the if-block I wrote above:
bool authenticated = Membership.ValidateUser(Login1.UserName, Login1.Password);
e.Authenticated = authenticated;
I think vanilla ASP.NET membership handles that part for you; if you were using a custom authentication scheme, you would definitely need to do that step.
Using a GridView on the default page and want to show details of the row selected on another page. The code for capturing and sending the datakey is -
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
Response.Redirect("InvoicePage.aspx? EntityID= " + GridView1.DataKeys[index].Value.ToString());
}
And the code for retrieving the value is -
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["EntityID"];
}
My problem is that the id variable is a null on the receiving page. What am I missing?
Your URL should look something like this: InvoicePage.aspx?EntityID=", No space before or after EntityID
By The way Remove the white space : aspx?<>*EntityID<>*=
protected void SelectedIndexChanged(object sender, EventArgs e)
{
int index = GridView1.SelectedIndex;
string id = GridView1.DataKeys[index].Value.ToString();
Response.Redirect("InvoicePage.aspx?EntityID="+id);
}
Try to add :
private string _EntityId;
//To check if value pass on query string
//but this is not really required if you want
public string EntityId
{
get
{
if (Request.QueryString["EntityID"] != null)
{
try
{
_EntityId = Convert.ToString(Request.QueryString["EntityID"].ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
else
{
_EntityId="0";
}
return _EntityId;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Request.QueryString["EntityID"].ToString();
string id = EntityId;
}
Regads