I'm trying to catch user identity but not able to catch it.
I turned windows features on or off and update Windows authentication,
but still not able to catch the login ID.
Any idea would be appreciated.
c# code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string uid = "";
try { uid = Session["uid"].ToString(); }
catch { uid = ""; }
if (uid == "" || uid == null)
{
uid = Page.User.Identity.Name;
if (uid.Length > 0)
{
uid = uid.Substring(10);
}
}
}
}
Related
currently i am working a one project and i got this type of error.
i excuted the procedure and in debugging mode prcedure pass the data to entity file but when i go back to aspx page so that time i got this null exception.
how can i resolve.
any one help me?.
UserDAL file
this is a prcedure
public UserENT PR_IP_User_LoginUser(SqlInt32 UserID)
{
using (SqlConnection objconn = new SqlConnection(ConnectionString))
{
objconn.Open();
using (SqlCommand objcmd = objconn.CreateCommand())
{
try
{
#region Prepaed Command
objcmd.CommandType = CommandType.StoredProcedure;
objcmd.CommandText = "PR_IP_User_LoginUser";
objcmd.Parameters.AddWithValue("#UserID", UserID);
#endregion
UserENT entuser = new UserENT();
#region Read and set controls
using (SqlDataReader objSDR = objcmd.ExecuteReader())
{
while (objSDR.Read())
{
if (!objSDR["User_Name"].Equals(DBNull.Value))
{
entuser.User_Name = Convert.ToString(objSDR["User_Name"].ToString().Trim());
}
if (!objSDR["Password"].Equals(DBNull.Value))
{
entuser.Password = Convert.ToString(objSDR["Password"].ToString().Trim());
}
if (!objSDR["User_ID"].Equals(DBNull.Value))
{
entuser.User_ID = Convert.ToInt32(objSDR["User_ID"]);
}
if (!objSDR["ContactNo"].Equals(DBNull.Value))
{
entuser.ContactNo = Convert.ToString(objSDR["ContactNo"]);
}
if (!objSDR["Email_ID"].Equals(DBNull.Value))
{
entuser.Email_ID = Convert.ToString(objSDR["Email_ID"]);
}
if (!objSDR["Is_Admin"].Equals(DBNull.Value))
{
entuser.Is_Admin = Convert.ToBoolean(objSDR["Is_Admin"]);
}
}
return entuser;
}
#endregion
}
catch (Exception e)
{
Message = e.InnerException.Message;
return null;
}
finally
{
objconn.Close();
}
}
}
}
#endregion
on client side or can say aspx page
on button click event
protected void btnLogin_Click(object sender, EventArgs e)
{
#region Server Side Validation
String strerr = "";
if (txtusername.Text.Trim() == "")
{
strerr += "Enter UserName";
}
if (txtpassword.Text.Trim() == "")
{
strerr += "Enter Password";
}
if (strerr != "")
{
lblMessage.EnableViewState = true;
lblMessage.Text = strerr;
}
#endregion
#region Gather Data
SqlString Username, userpass;
if (txtusername.Text.Trim() != "")
{
Username = txtusername.Text.Trim();
}
if (txtpassword.Text.Trim() != "")
{
userpass = txtusername.Text.Trim();
}
#endregion
UserBAL baluser = new UserBAL();
UserENT entuser = new UserENT();
SqlInt32 UserID_Res;
SqlString User_name_res, User_Password_res;
SqlInt32 userid = Convert.ToInt32(txtuserid.Text.Trim());
if (Request.QueryString["User_ID"] == null)
{
if (baluser.Login(userid) != null)
{
User_name_res = entuser.User_Name.Value.ToString().Trim();
UserID_Res = Convert.ToInt32(entuser.User_ID.Value);
User_Password_res = entuser.Password.Value.ToString().Trim();
if (User_name_res == txtusername.Text.Trim() || User_Password_res == txtpassword.Text.Trim())
{
Response.Redirect("AddSubject.aspx");
}
else
{
Response.Redirect("AddTopic.aspx");
}
}
}
#endregion
The C# code associated with a ".aspx" page (or code behind) is executed on the server side.
I assume that UserBAL.Login() function returns the user's data once logged in. It may be necessary to get the returned object.
On button click event :
protected void btnLogin_Click(object sender, EventArgs e)
{
...
UserENT entuser = baluser.Login(userid);
if (entuser != null)
{
...
Thanks every one who help to solve my error. now i resolve my error.
i Just pass the data to procure and check the data in procedure and return
Boolean value.
Thanks Again :)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
{
txtUserName.Text = Request.Cookies["UserName"].Value;
txtPass.Attributes.Add("value", Convert.ToString(Request.Cookies["Password"].Value));
CheckBox1.Checked = true;
}
}
}
protected void btnLogIn_Click(object sender, EventArgs e)
{
if (dt.Rows.Count != 0)
{ }
else
{
lblMsg.Visible = true;
lblMsg.Text = "Login In Failed";
}
ClearField();
}
}
protected void ClearField()
{
txtUserName.Text = string.Empty;
txtPass.Text = string.Empty;
}
When my else condition execute. it not empty my txtPass Textbox instead if i write wrong password it display correct password in textbox.
i think something wrong with Cookie but idk how to solve it.
I want before or after each login to each user Give a new Session ID. I use Asp.net and IIS 8.0 and windows 2012 server.
I used this method
protected void Page_Load(object sender, EventArgs e)
{
Session["userid"] = txt_user_name.Text;
if (Session["userid"] != null && Session["AuthToken"] != null && Request.Cookies["AuthToken"] != null)
{
if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
{
lbl_message.Text = "NOT LOGIN";
}
}
if (txtInput.Text == "")
{
CreateSesstion_Click(sender, e); // This method Generate new Session Id
}
if (!IsPostBack)
{
Captcha();
}
}
protected void CreateSesstion_Click(object sender, EventArgs e)
{
SessionIDManager manager = new SessionIDManager();
string newID = manager.CreateSessionID(Context);
bool redirected = false;
bool isAdded = false;
manager.SaveSessionID(Context, newID, out redirected, out isAdded);
HttpContext.Current.Session["x"] = 123;
}
This method works fine before publishing it, but after publishing when the site runs with HTTPS, it fails and does not recognize the new Session ID. And makes a mistake.
If it's open without SSL, it works fine
Please help me
Thankful
Im having a problem handing an exception in ASP.net WebForms(i'm a beginner)
i want to display the error in the webform using CustomValidator but with no luck, below is my code.
protected void dvEmployeeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
int empID;
empID = int.TryParse(dvEmployeeList.DataKeys[rowindex].Value.ToString(), out empID) ? empID : 0;
oEmployeeBLL.DeleteEmployee(empID);
dvEmployeeList.DataSource = oEmployeeBLL.GetEmployeeList();
dvEmployeeList.DataBind();
}
catch (Exception ex)
{
var delConstrainsVal = new CustomValidator();
delConstrainsVal.IsValid = false;
delConstrainsVal.ErrorMessage = "Update failed: " + ex.Message;
delConstrainsVal.Text = delConstrainsVal.ErrorMessage;
Page.Validators.Add(delConstrainsVal);
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User cancel!')", true);
}
}
it catch the exception but didnt display the message on the on the form.
Please guide me, thanks!
Validators are meant to validate user input, not to display server errors. You should consider using a simple <asp:Label>.
The reason why the error doesn't appear is probably because validation happens before the control is added.
I have a menu and label in my master page which i want to update depending on the type of user logged in.
Firstly am removing few MenuItems from the menu that is working fine but its not showing up in the master page. Instead the old menu is only seen with all the menu items for limited user also. When i debug the label text shows what i have set but when page loads its not updating too.
Am using the following code.
Label lbWelcomeMessage = new Label();
protected void Page_Load(object sender, EventArgs e)
{
Master.FindControl("CAMenu").Visible = false;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
Common common = new Common();
DataTable tab = new DataTable();
tab= common.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID=string.Empty;
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (userPassword == password)
{
if (RoleID != "1")
{
Menu CAMenu = new Menu();
CAMenu = (Menu)Master.FindControl("CAMenu");
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
lbWelcomeMessage = (Label)Master.FindControl("lbLoginMessage");
lbWelcomeMessage.Text = lbWelcomeMessage.Text+" "+firstName ;
Response.Redirect("NewTemplate.aspx");
}
}
}
I assume you have written this code in your login.aspx. When login button is clicked then it takes you to another page and all the life cycle of page is run again. and master page contents are reset.
The solution to this problem could be. Move this logic to your master page code like
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Session.Count == 0 || Session["Username"] == null)
Response.Redirect("~/Login.aspx", true);
CheckRole();
}
public void CheckRole()
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
tab= common.GetUserDetails(Session["Username"]);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][2].ToString();
userPassword = tab.Rows[0][4].ToString();
RoleID = tab.Rows[0][5].ToString();
}
if (RoleID != "1")
{
Menu CAMenu = new Menu();
int count = CAMenu.Items.Count;
for (int i = 3; i > 0; i--)
{
string text = CAMenu.Items[i - 1].Text;
CAMenu.Items.RemoveAt(i - 1);
}
//your label logic
lbWelcomeMessage.Text = "Welcome"+" "+ firstName;
((SiteMaster)Page.Master).MyText = lbWelcomeMessage.Text;
Response.Redirect("AdHocSMS.aspx");
}
else
{
//Logic
Response.Redirect("NewTemplate.aspx");
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
You have to put a UserId or Username in Session this is the one disadvantage but for every page you dont have to worry about anything.
for life cycle read this article http://msdn.microsoft.com/en-us/library/ms178472.aspx
let me know if it solves or not.
What i did is something like this
In Site.Mater:-
public void CheckRole()
{
try
{
if (System.Web.HttpContext.Current.Session.Count > 0)
{
string firstName = string.Empty;
// string userPassword = string.Empty;
string RoleID = string.Empty;
Common common = new Common();
DataTable tab = new DataTable();
string userName = (string)Session["UserName"];
User user = new User(userName);
tab = user.GetUserDetails(userName);
if (tab.Rows.Count == 1)
{
firstName = tab.Rows[0][1].ToString();
RoleID = tab.Rows[0][3].ToString();
}
if (RoleID != "1")
{
int count = CAMenu.Items.Count;
if (count == 5)
{
for (int menuCount = 3; menuCount > 0; menuCount--)
{
string text = CAMenu.Items[menuCount - 1].Text;
CAMenu.Items.RemoveAt(menuCount - 1);
}
}
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
else
{
lbLoginMessage.Text = "Welcome," + " " + firstName;
loginStatus.Visible = true;
}
}
else
{
Session.Abandon();
Response.Redirect("~/Login.aspx", true);
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.SiteMaster.CheckRole()", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
In Login.Apsx:-
protected void Page_Load(object sender, EventArgs e)
{
try
{
Master.FindControl("CAMenu").Visible = false;
Master.FindControl("loginStatus").Visible = false;
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void LoadMessageBox(string MessageID)
{
try
{
messages = new GUIMessages();
popupExtend = new ModalPopupExtender();
lbMessage = (Label)Master.FindControl("label5");
lbMessage.Text = messages.GetGUIMessage(GUIModule.Login, MessageID);
popupExtend = (ModalPopupExtender)Master.FindControl("popupExtender");
popupExtend.Show();
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.LoadMessageBox(string MessageID)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
try
{
string userName = txtUsername.Text;
string password = txtPassword.Text;
if (userName == string.Empty && password == string.Empty)
{
LoadMessageBox("5");
txtUsername.Focus();
return;
}
if (userName == string.Empty)
{
LoadMessageBox("1");
txtUsername.Focus();
return;
}
else if (password == string.Empty)
{
LoadMessageBox("3");
txtPassword.Focus();
return;
}
User user = new User(userName);
DataTable tab = new DataTable();
tab = user.GetUserDetails(userName);
string firstName = string.Empty;
string userPassword = string.Empty;
string RoleID = string.Empty;
string userID = string.Empty;
Session["UserName"] = userName;
if (tab.Rows.Count == 0)
{
LoadMessageBox("6");
txtPassword.Text = string.Empty;
txtUsername.Text = string.Empty;
txtUsername.Focus();
return;
}
if (tab.Rows.Count == 1)
{
userID = tab.Rows[0][0].ToString();
firstName = tab.Rows[0][1].ToString();
userPassword = tab.Rows[0][2].ToString();
RoleID = tab.Rows[0][3].ToString();
Session["UserID"] = userID;
}
//if (firstName != userName)
//{
// LoadMessageBox("2");
// txtUsername.Focus();
// return;
//}
//else
{
if (userPassword == password)
{
Response.Redirect("~/Default.aspx");
}
else
{
LoadMessageBox("4");
txtPassword.Focus();
return;
}
}
}
catch (Exception ex)
{
new Logger().Log("ShortCom.Login.btnLogin_Click(object sender, EventArgs e)", ex.Message);
Response.Redirect("~/Error.aspx");
}
}