I had login Page and it worked well but remember me check box didn't work well and I couldn't know where the error please anyone help me this is my code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt,Passwordtxt;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["Mycookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("Mycookie");
Usertxt.Text=Cookie.Values["UserName"];
Passwordtxt.Text=Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
Literal LBL;
LBL = (Literal)Login1.FindControl("FailureText");
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}
Thank you more I got the answer and this the right code
public partial class _Default : System.Web.UI.Page
{
public TextBox Usertxt, Passwordtxt;
public Literal LBL;
public CheckBox CHB;
protected void Page_Load(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
if (!IsPostBack)
{
if (Request.Cookies["MyCookie"] != null)
{
HttpCookie Cookie = Request.Cookies.Get("MyCookie");
Usertxt.Text = Cookie.Values["UserName"];
Passwordtxt.Text = Cookie.Values["Password"];
}
}
}
protected void LoginButton_Click(object sender, EventArgs e)
{
Usertxt = (TextBox)Login1.FindControl("UserName");
Passwordtxt = (TextBox)Login1.FindControl("Password");
CHB = (CheckBox)Login1.FindControl("RememberMe");
LBL = (Literal)Login1.FindControl("FailureText");
HttpCookie MyCookie = new HttpCookie("MyCookie");
bool IsRememberme = CHB.Checked;
if (IsRememberme)
{
MyCookie.Values.Add("UserName", Usertxt.Text);
MyCookie.Values.Add("Password", Passwordtxt.Text);
MyCookie.Expires = DateTime.Now.AddDays(15);
}
else
{
MyCookie.Values.Add("UserName", string.Empty);
MyCookie.Values.Add("Password", string.Empty);
MyCookie.Expires = DateTime.Now.AddDays(5);
}
Response.Cookies.Add(MyCookie);
if (FormsAuthentication.Authenticate(Usertxt.Text, Passwordtxt.Text))
{
Response.Redirect("");
}
else
{
Login1.FindControl("FailureText");
LBL.Text = "error ocurred";
}
}
}
Related
I am using the below code to try to bind a c# class that has been registered but do not see "dwgData" anywhere under Scope when debugging the webpage. What would dwgData be bound to?
private void ChromiumBrowserForm_Load(object sender, EventArgs e)
{
CefSettings settings = new CefSettings();
ChromiumWebBrowser browser = new ChromiumWebBrowser("http://localhost:3000");
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
browser.JavascriptObjectRepository.Register("dwgData", new DwgData(), true, null);
browser.IsBrowserInitializedChanged += Browser_IsBrowserInitializedChanged;
browser.LoadingStateChanged += Browser_LoadingStateChanged;
}
private async void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (e.IsLoading == false)
{
await Task.Run(() => browser.ExecuteScriptAsync("CefSharp.BindObjectAsync(\"dwgData\");"));
}
}
private void Browser_IsBrowserInitializedChanged(object sender, EventArgs e)
{
ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
if (browser.IsBrowserInitialized)
{
browser.ShowDevTools();
}
}
public class DwgData
{
public void showMessage()
{
MessageBox.Show("HELLO FROM JS");
}
}
I have logged in as a user and it works fine , but when i try to open the login in a different tab in same browser it still goes to the login.aspx without the actual member page
Please help !
Aboutus.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
string Username = Session["Username"].ToString();
Label1.Text = Username;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
}
Login.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM [dbo].[Reg] WHERE Username='" + Login1.UserName + "' and Password=#pass");
cmd.Connection = con;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
////create an array of bytes we will use to store the encrypted password
Byte[] hashedBytes;
////Create a UTF8Encoding object we will use to convert our password string to a byte array
UTF8Encoding encoder = new UTF8Encoding();
////encrypt the password and store it in the hashedBytes byte array
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Login1.Password));
cmd.Parameters.AddWithValue("#pass", hashedBytes);
var username = Login1.UserName;
int OBJ = Convert.ToInt32(cmd.ExecuteScalar());
if (OBJ > 0)
{
if (username == "admin")
{
Session["Username"] = Login1.UserName;
Response.Redirect("AdminPanel.aspx");
}
else
{
Session["Username"] = Login1.UserName;
Response.Redirect("About.aspx");
}
}
else
{
Label1.Text = "Invalid username or password";
this.Label1.ForeColor = Color.Red;
}
}
}
}
In Page_Load of Login.aspx do this:
if(Session["Username"] != null)
{
string username = Convert.ToString(Session["Username"]);
if (username == "admin")
{
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Redirect("About.aspx");
}
}
Your page laod method on Loginpage must be like this
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
}
else
{
Response.Redirect("index.aspx",false);
}
}
I hope this helps
I want to check if btnTest_Click is clicked in another Button6_Click event.Below is my code.....Please help
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if()
}
as per Kevin's answer but instead of:
protected bool testPassed;
Have this:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
By accessing the value of this property via view state the value will persist between requests.
I would declare a class level boolean called testPassed.
Set it to false in the onload event if it is not a Postback.
Set it to true in the btnTest_Click event handler
Edit to add an example:
protected bool testPassed
{
get { return (bool)ViewState["testpassed"]; }
set { ViewState["testpassed"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
testPassed=false;
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
Session["Counter1"] = newValue;
Session["Counter"] = newValue;
if (Session["Markici"] != null || Session["Markici"] != null)
{
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
/*decimal*/ old = dtCurrentTable.Rows[clickedIndex].Field<decimal>("Kolicina");
decimal oldIznos = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkIznos");
decimal VkDanok = dtCurrentTable.Rows[clickedIndex].Field<decimal>("VkDanok");
string Cena1 = dtCurrentTable.Rows[clickedIndex].Field<string>("Cena1");
int TarifaID = dtCurrentTable.Rows[clickedIndex].Field<Int16>("TarifaID");
testPassed=true;
}
protected void Button6_Click(object sender, EventArgs e)
{
// how to check here if btnTest_Click is clickied
if(testPassed)
}
i have a listview and a button out of this list view, on button click i want to add a "insert" row defined in InsertItemTemplate. The problem is when i click the button, this row is added(i know this because when a do any postback aftewards this row really shows), but isnt shown/rendered. So the question is: why this change doesn´t apply on the first postback - button click? here is my code:
EDIT:
Whole Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem ByName = new ListItem("By name", "Name");
ListItem ByPhone = new ListItem("By phone", "Phone");
ListItem ByEmail = new ListItem("By email", "Email");
FilterTypeDDL.Items.Add(ByName);
FilterTypeDDL.Items.Add(ByPhone);
FilterTypeDDL.Items.Add(ByEmail);
FilterTypeDDL.DataBind();
}
}
//protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
//{
//switch (e.CommandName)
//{
//case "EditItem":
// break;
//case "InsertItem":
// if (Page.IsValid)
// {
// string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
// string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
// string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
// DAORestaurant.InsertRestaurant(NameTxt, PhoneTxt, EmailTxt);
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
// }
// break;
//case "CancelCreation":
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
//case "Articles":
// Session["Restaurant"] = e.CommandArgument.ToString();
// Control ArticlesCtrl = LoadControl("~/Controls/Article.ascx");
// ListViewItem Item = (ListViewItem)e.Item;
// Item.FindControl("CtrlPlaceHolder").Controls.Add(ArticlesCtrl);
//}
//}
protected void closeButton_Click(object sender, EventArgs e)
{
}
protected void newArticleButton_Click(object sender, EventArgs e)
{
}
protected void NewRestaurantBtn_Click(object sender, EventArgs e)
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
//SetDataSource();
//ListView.DataBind();
}
protected void ValidateName(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = (NameTxt.Length > 2 && NameTxt.Length < 51);
}
protected void ValidateUniqueness(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = DAORestaurant.IsUnique(NameTxt);
}
protected void ValidatePhone(object source, ServerValidateEventArgs args)
{
string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
Regex regex = new Regex(#"^\d{3}\s\d{3}\s\d{3}$");
args.IsValid = regex.IsMatch(PhoneTxt);
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
args.IsValid = regex.IsMatch(EmailTxt);
}
protected void ShowAllBtn_Click(object sender, EventArgs e)
{
Session["ALL"] = true;
ListView.DataSource = DAORestaurant.GetRestaurants();
ListView.DataBind();
}
protected void FilterBtn_Click(object sender, EventArgs e)
{
string filterType = FilterTypeDDL.SelectedValue;
string substring = StringTB.Text.Trim().ToUpper();
Session["ALL"] = false;
Session["FilterType"] = filterType;
Session["Substring"] = substring;
ListView.DataSource = DAORestaurant.GetRestaurants(substring, filterType);
ListView.DataBind();
}
protected void ListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView.EditIndex = e.NewEditIndex;
//SetDataSource();
//ListView.DataBind();
}
protected void ListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
ListView.InsertItemPosition = InsertItemPosition.None;
}
else
{
ListView.EditIndex = -1;
}
//SetDataSource();
//ListView.DataBind();
}
private void SetDataSource()
{
if ((bool)Session["ALL"])
{
ListView.DataSource = DAORestaurant.GetRestaurants();
}
else
{
ListView.DataSource = DAORestaurant.GetRestaurants((string)Session["Substring"], (string)Session["FilterType"]);
}
}
The code commented out is what i used before, i´ve switched to what you can see now, but the problem still persists. Only when i uncomment those 2 commented lines in each event, the changes apply instantly, but i know i cannot use such a method that many times, and it should not even be there.
Because of the order of execution. Try setting it in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack &&
!string.IsNullOrEmpty(Request.Form[NewRestaurantBtn.ClientID]))
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
}
}
I have a problem while writting event for ImageUpload User control.
I want to add a event that fire on imagebutton click in this case that green ok button. I write some code for event but it get raised on pageload() and on postback, so it causes a problem --> Image path which is provided for image upload is get clear after image upload but on a page refresh a same image is upload again and again on every page refresh.
User Control Code
public partial class Gallery_Controls_ImgUpload : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
public string TxtDesc
{
get {return txtimgdesc.Text;}
set { txtimgdesc.Text = value; }
}
public string TxtImgName
{
get { return txtimgname.Text; }
set { txtimgname.Text = value; }
}
public FileUpload ImgUpld
{
get { return ImgUpload; }
//set { ImgUpload = value; }
}
public string ImgAttr
{
get { return ImgUpload.Attributes["onchange"]; }
set { ImgUpload.Attributes["onchange"] = value; }
}
public event EventHandler ImgBtnUpClick;
protected void imgbtnok_Click(object sender,EventArgs e)
{
ImgBtnUpClick(ImgUpload, e);
}
Code for Adding control in page and upload a file
public partial class Gallery_iupload : System.Web.UI.Page
{
ASP.gallery_controls_imgupload_ascx upctrl;
protected void Page_Load(object sender, EventArgs e)
{
upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
protected void Upload(object sender, EventArgs e)
{
TextBox txtbximgname = (TextBox)upctrl.FindControl("txtimgname");
TextBox txtbxdesc = (TextBox)upctrl.FindControl("txtimgdesc");
FileUpload Imgload = (FileUpload)sender;
if (Imgload.HasFile)
try{
Imgload.SaveAs("C:\\Uploads\\" + txtbximgname.Text + ".jpg");
Label1.Text = "File name: " + Imgload.PostedFile.FileName + "<br>" +
Imgload.PostedFile.ContentLength + " kb<br>" +"Content type: " +
Imgload.PostedFile.ContentType;
}
catch (Exception ex)
{
Label1.Text = "ERROR: " + ex.Message.ToString();
}
else
{
Label1.Text = "You have not specified a file.";
}
}
}
you have to put a IsPostBack check in your page_load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{ upctrl = (ASP.gallery_controls_imgupload_ascx)LoadControl ("Controls/ImgUpload.ascx");
upctrl.ImgBtnUpClick += new EventHandler(Upload);
upctrl.ImgAttr = "checkFileExtension(this); return false;";
PlaceHolderupctrl.Controls.Add(upctrl);
}
}