i using a single master page in asp.net for log-In and Log-Out functionality...
but in master page session name takes null value.
Here is my code ,please help me...
MasterPage.master.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["name"] == null)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
else if (Session["name"] != null)
{
Panel1.Visible = false;
Panel2.Visible = true;
Label2.Text = "WELCOME | Mr." + Session["name"].ToString();
}
}
}
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
}
my homepage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string st="select Label4,Label3 FROM Register1_master WHERE Label4='" + TextBox1.Text + "' and Label3='" + TextBox2.Text + "'";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
string result= null;
Object value=cmd.ExecuteScalar ();
if ( value != null)
{
result = value.ToString ();
Session["name"] = TextBox1.Text;
Response.Redirect("Main.aspx");
}
else
{
Label3.Text="Invalid username or password";
}
cmd.Connection.Close();
}
after the login from homepage i'll be go on Main.aspx page
my Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperLink link = (HyperLink)Master.FindControl("HyperLink1");
link.Visible = false;
HyperLink link1 = (HyperLink)Master.FindControl("HyperLink2");
link1.Visible = true;
Label masterlbl = (Label)Master.FindControl("Label2");
string login = Convert.ToString(Session["name"]);
Session["name"] = login;
}
}
Have you try like this :
int result= null;
result= = Convert.ToInt32(cmd.ExecuteScalar());
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
Please refer MSDN
Related
I have saved the dropdown value in db and in the viewstate, but on page load it is not getting loaded.
Can someone please tell me where am I going wrong
protected void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ddSelectedValue"] != "0")
{
dd_RuleFor.SelectedValue = Convert.ToInt32(ViewState["ddSelectedValue"]).ToString();
}
}
protected void btn_Save_Click(object sender, System.EventArgs e)
{
if(chkRuleApprover.Checked == true && dd_RuleFor.SelectedValue != "0")
{
strSQL = "update UserFile set Rule_Approval_Selection=" + dd_RuleFor.SelectedItem.Value + " where UID=" + intUserID;
objCmd = new System.Data.SqlClient.SqlCommand(strSQL, oconn);
objCmd.ExecuteNonQuery();
ViewState["ddSelectedValue"] = dd_RuleFor.SelectedValue.ToString();
}
}
Make sure you are filling the dropdown with the values first on pageload and after than use below condition:
if(!Page.Ispostback())
{
if (ViewState["ddSelectedValue"] != "0")
{
dd_RuleFor.SelectedValue = Convert.ToInt32(ViewState["ddSelectedValue"]).ToString();
}
}
the code here is using ASP.NET with C#. The issue is that when user click logout button a user can return back to previous page.
Logoin code
protected void Page_Load(object sender, EventArgs e)
{
Session["email"] = txtemail.Text;
}
protected void btlogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT [email], [password] FROM [customer] WHERE [email]=#email AND [password]=#password";
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = txtemail.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = txtpassword.Text;
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
Response.Redirect("~/Booking.aspx");
reader.Close();
conn.Close();
}
else
{
lb.Text="Email or Password incorrect";
}
}
}
logout code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["email"] == null)
{
Response.Redirect("Default.aspx");
}
}
protected void btlogout_Click(object sender, EventArgs e)
{
Session["email"] = null;
Response.Redirect("Default.aspx");
}
How to stop user from accessing the previous pages once he/she logs out
There are several ways
Clear Your Session using Session.Abandon and use Response.Redirect("~/LoginPage.aspx");
Then you can use Following Methods to Clear Cache or clear history
Using Codebehind
// Code disables caching by browser.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
Using JavaScript
<SCRIPT LANGUAGE="javascript">
function ClearHistory()
{
var backlen = history.length;
history.go(-backlen);
window.location.href = loggedOutPageUrl
}
</SCRIPT>
with asp.net
without update panel
Page.ClientScript.RegisterStartupScript(this.GetType(),
Guid.NewGuid().ToString(),"ClearHistory();",true);
with update panel
ScriptManager.RegisterStartupScript(this,this.GetType(),
Guid.NewGuid().ToString(),"ClearHistory();",true);
I am working on designing a payroll system using access database as back end.
Currently, I am facing problems implementing a 'clock out' functionality.
The 'clock in' button inserts the time in the database. However, when the 'clock out' button is clicked, it inserts the data into a new row. Is there any there any way to avoid this and to update the existing last row considering the Employee name. I have tried to approach this using different methods and so far I have not been able to solve it.
Is there any way to rectify this?
I think I would have to implement a loop somewhere to check emp name, clock in and locate null values in clock out field. Not sure though.
Please advise.
My code are as follows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class timecards : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
{
if (Session["ID"] != null && Session["ID"].ToString() != "")
{
PanelUsersInfo.Visible = true;
}
else
{
PanelUsersInfo.Visible = false;
}
empLabel.Visible = false;
mainPagebutton.Visible = false;
logoutButton.Visible = false;
if (Session["Title"] == null || Session["Names"] == null)
{
clockPanel.Visible = false;
return;
}
else
{
mainPagebutton.Visible = true;
logoutButton.Visible = true;
empLabel.Visible = true;
empLabel.Text = "<b>Hi, " + Session["Names"].ToString() + "</b>";
nameLabel.Text = Session["Names"].ToString();
clockinLabel.Text = DateTime.Now.ToString("HH:mm");
Label1.Text = clockinLabel.Text;
}
}
}
protected void mainPage_Click(object sender, EventArgs e)
{
Response.Redirect("employeeLoggedin.aspx");
}
protected void logout_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("default.aspx");
}
protected void clockinButton_Click(object sender, EventArgs e)
{
informLabel.Text = "Clocked in at " + Label1.Text + "";
Label1.Visible = false;
Label2.Visible = false;
clockinButton.Enabled = false;
clockoutButton.Enabled = true;
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + Page.Server.MapPath("App_Data\\database.mdb");
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);
System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand();
cmd.Parameters.Add("Employee", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Employee"].Value = nameLabel.Text;
cmd.Parameters.Add("Clockin", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Clockin"].Value = clockinLabel.Text;
cmd.CommandText = "INSERT INTO [timecard] ([Employee], [Clockin]) VALUES (#Employee, #Clockin)";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
protected void clockoutButton_Click(object sender, EventArgs e)
{
clockoutLabel.Visible = true;
clockoutLabel.Text = "You have now been clocked out.";
informLabel.Visible = false;
Label1.Visible = false;
clockoutButton.Enabled = false;
infoLabel.Visible = true;
infoLabel.Text = "If you want to clock in again, please select timecard option from the main employee page.";
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + Page.Server.MapPath("App_Data\\database.mdb");
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);
System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand();
cmd.Parameters.Add("Employee", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Employee"].Value = this.nameLabel.Text;
//String x = DateTime.Now.ToString("HH:mm");
cmd.Parameters.Add("Clockout", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Clockout"].Value = this.clockinLabel.Text;
cmd.CommandText = "UPDATE [timecard] SET [Employee]=#Employee, [Clockout]=#Clockout";
conn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
conn.Close();
}
}
If both buttons are INSERTing records then both buttons are running the same code. Check your .aspx page to see if both buttons happen to have the same onClick= attribute.
Thank you all who helped and provided suggestions to overcome the difficulty I was encountering.
Apparently, I found a solution. It's is better to store the values as string and then use WHERE clause to update it. For some reason, it will not directly take values from the textfields.
I'm working with c#, in vs 2008, framework 3.5, I need to save the username and when
the user log in, it shows he/her first and last name, at this point can save it, and
that is what I want but need to show to the user not his/her username just the first and
last name. here is my code, thanks in advance.
//code in the login
ClPersona login = new ClPersona();
bool isAuthenticated = login.sqlLogin1((txtUsuario.Text), (txtPassword.Text));
if (isAuthenticated)
{
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
//code in the form where shows the username but I want the first and last name
public partial class menu2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
if (!IsPostBack)
//ClPersona class
public Boolean sqlLogin1(string nombreUsuario, string password)
{
string stSql = "select * from usuarios where usuario='" + nombreUsuario + "' and
pass='" + password + "'and id_rol='1'";
Bd miBd = new Bd();
DataTable dt = miBd.sqlSelect(stSql);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//return ds;
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
Modify two sections
First
if (isAuthenticated)
{
Session["YouObject"] = login;//<--
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
Second
protected void Page_Load(object sender, EventArgs e)
{
if(Session["YouObject"] != null)
{
ClPersona obj = (ClPersona )Session["YouObject"];
lblNombreUsuario.Text = string.Format("{0}-{1}", obj.FirstName, obj.LastName )
}
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
....
}
I have a problem regarding with add an image URL within a database.I'm using fileupload method within formview in ASP.Net.And I have a table called duyurular
which can be record a image URL.BTW,I'm using SQL Server Database.
My question is;I'm doing the process update,delete and to make an announcement in the FormView.I can upload those images within folder called "img" with FileUpload.
However,I want to record it within database as well.when to add within database another those infos,there are no the image URL.
Finally,I can't add the image URL within database.
Here is my code;
public partial class panel_yoneticipaneli : System.Web.UI.Page
{
FileUpload dosya, dosya1;
//TextBox t1, t2, t3;
//Button btn;
SqlConnection con;
static string str = "Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True";
string yol = "";
protected void Page_Load(object sender, EventArgs e)
{
dosya = (FileUpload)FormView2.FindControl("FileUpload1");
dosya1 = (FileUpload)FormView2.FindControl("FileUpload2");
// btn = (Button)FormView2.FindControl("ResimKaydetButonu");
//t1 = (TextBox)FormView2.FindControl("DuyuruBaslikTextBox");
//t2 = (TextBox)FormView2.FindControl("DuyuruIcerikTextBox");
//t3 = (TextBox)FormView2.FindControl("DuyuruTarihiTextBox");
Label1.Visible = false;
if (Session["KullaniciID"]!=null)
{
con = new SqlConnection(str);
SqlCommand sorgu = new SqlCommand("SELECT * FROM Kullanici WHERE KullaniciAdi=#KullaniciAdi", con);
sorgu.Parameters.Add("#KullaniciAdi", SqlDbType.VarChar).Value = Session["KullaniciAdi"];
con.Open();
SqlDataReader oku = sorgu.ExecuteReader(CommandBehavior.CloseConnection);
Label1.Visible = true;
while (oku.Read())
{
Label1.Text = oku["KullaniciAdi"].ToString();
}
}
else {
Response.Redirect("error.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
Response.Redirect("giris.aspx");
}
protected void btn_Click(object sender,EventArgs e) {
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
System.Drawing.Image resim = System.Drawing.Image.FromFile(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
resim.Dispose();
DbUpload();
}
}
catch (Exception ex)
{
}
}
public void DbUpload() {
try {
SqlConnection sc = new SqlConnection("Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True");
SqlCommand scom = new SqlCommand("insert into Duyuru(DuyuruResmi) values(#DuyuruResmi)", sc);
scom.Parameters.AddWithValue("#DuyuruResmi", dosya.FileName);
scom.ExecuteNonQuery();
sc.Close();
}catch(Exception p){
p.Message.ToString();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
Response.Write("Fileupload çalışıyor...");
DbUpload();
}
}
catch (Exception ex)
{
}
}
thanks in advance for all comments you can share.
I suggest that you just upload the image name without specifying the full URL, and you can save the image base path in the web.config like '<add key="ImagesBasePath" value="/img" />' so you can change the path were you have your images and you can control the view of this image by concatenating the Image name to ConfigurationManager.AppSettings["ImagesBasePath"] so this will be better.
You have to use Formview ItemInserting Event, where you can pass in the built URL.
protected void frmAsset_ItemInserting(object sender, FormViewInsertEventArgs e)
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
e.NewValues["URL"] = "img/" + dosya.FileName;
}
}