How to Display Username in the homepage using ASP MVC - c#

How to Display the User Id in my Homepage in ASP MVC. I don't know what is the problem. May I know what are the cause the userId
This is the part of Dashboard
protected void Page_Load(object sender, EventArgs e)
{
string sUserInfo = System.Environment.UserName;
string constr = "Data Source=MyDatabase;Database=test;User Id=username;Password=add3" ;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select SystemName from tbl_SYS_Users where UserId='" + sUserInfo + "'");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
string tempa = "";
while (sdr.Read())
{
tempa += sdr["SystemName"].ToString();
}
lblUserID.Text = Utilities.GetUserInfo(tempa);
}
This is for the Utilities in AppData Folder
public static string GetUserInfo(string sSystem)
{
sSystem = sSystem.ToUpper();
string sUserInfo = System.Environment.UserName;
if (SetConfigs()) //Check config file first
{
//Get userinfo from db server
if (sSystem != "HOME")
{
string sQry = "Select * from tbl_SYS_Users where SystemName = '" + sSystem + "' AND UserId='" + sUserInfo + "'";
using (DataTable dsTable = SQL_Query(Globals.sSQLCS_FNS, sQry, true, false))
{
if (dsTable == null)
{
sUserInfo += " - Unknown User!a";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
if (dsTable.Rows.Count == 0) //ID not found!
{
sUserInfo += " - Unknown User!";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
sUserInfo += " - " + dsTable.Rows[0]["Username"];
Globals.UserID = dsTable.Rows[0]["UserId"].ToString().Trim();
Globals.UserName = dsTable.Rows[0]["Username"].ToString().Trim();
}
}
}
}
}
else if (sSystem != "HOME")
sUserInfo += " - Unknown User!s";
return sUserInfo; // return to lblUserID.Text in the homepage
}
This image is the homepage
This is the database
I Want to display the Username in my Homepage

inject usermanager in to the view and add this
#UserManager.GetUserAsync(User).Result.UserName

What is the scope of Globals class? It seems when page loads class object initialized and all becomes empty. Declare Globals class as static (If not).

Related

Display SQL information of user based on username in WPF App

I'm creating a WPF application were-in a user creates an account and can log-in with their username and password. When the user successfully logs in their Username and other details that they entered whiles signing up should be displayed on the next page. So far when I do it the only thing that shows up is the info of the first registered user no matter what Username or Password is used but it should be based on who's logged in.
Better explained, There's User A and User B, when User A logs in his info is displayed, when User B logs in, User A's info is still displayed no matter what, I want the info of User B(and all subsequent Users) to show when his specific Username is entered.
C# for Sign Up Command
private void SubmitBtn_Click(object sender, RoutedEventArgs e)
{
if (tbStudentName.Text == "" || pbPassword.Password == "" || tbSchoolName.Text == "" || tbHouseName.Text == ""
|| tbProg.Text == "" || tbPhoneNumber.Text == "" || tbAddress.Text == "")
{
var dim = new Dim();
dim.Show();
this.Effect = new BlurEffect();
var cmb = new Custom_MessageBoxes.CustomMsgBox2();
cmb.ShowDialog();
this.Effect = null;
dim.Close();
}
else
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
string InsertUser = "INSERT INTO tblSignUp values ('"+tbStudentName.Text+ "', '" + tbSchoolName.Text + "', '" + tbHouseName.Text + "', '" + tbProg.Text + "', '" + tbPhoneNumber.Text + "', '" + tbAddress.Text + "', '" + pbPassword.Password + "')";
obj.cmd.Connection = obj.conn;
obj.cmd.CommandText = InsertUser;
obj.cmd.ExecuteNonQuery();
obj.conn.Close();
var dim = new Dim();
dim.Show();
this.Effect = new BlurEffect();
var cmb = new Custom_MessageBoxes.RegistrationComplete();
cmb.ShowDialog();
this.Effect = null;
dim.Close();
Clear();
}
}
C# for Sign In Command
//Sign In button click event
private void UserSignInBtn_Click(object sender, RoutedEventArgs e)
{
SqlConnection sqlCon = new SqlConnection(connectionString);
try
{
Connect obj = new Connect();
obj.conn.ConnectionString = obj.locate;
obj.conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT COUNT (*) FROM tblSignUp WHERE StudentName = '"+tbID.Text+"' AND Password = '"+PB.Password+"'", obj.conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
// Custom Message Box and Dim Effect
var jim = new Dim();
jim.Show();
this.Effect = new BlurEffect();
var lsmb = new Custom_MessageBoxes.LoginSuccessfulMsgBox();
lsmb.ShowDialog();
this.Effect = null;
jim.Close();
var User_Homepage = new User_Homepage();
NavigationService.Navigate(User_Homepage);
}
else
{
// Custom Message Box and Dim Effect 2
var him = new Dim();
him.Show();
this.Effect = new BlurEffect();
var rmdlgb = new ReturnMessageDialogueBox();
rmdlgb.ShowDialog();
this.Effect = null;
him.Close();
}
obj.conn.Close();
}
catch(Exception ex)
{
using (EventLog eventlog = new EventLog("Application"))
{
eventlog.Source = "SQL Error: From My Application";
eventlog.WriteEntry(ex.StackTrace, EventLogEntryType.Error, 101, 1);
}
}
finally
{
sqlCon.Close();
}
}
Page where I want user info
string connectionString = #"Data Source=HP;Initial Catalog=User_SignUpDB;Integrated Security=True;";
public UHP()
{
InitializeComponent();
Page1 p1 = new Page1();
var pls = p1.tbID.Text;
SqlConnection sqlCon = new SqlConnection(connectionString);
sqlCon.Open();
string query = "SELECT * FROM tblSignUP WHERE StudentName = StudentName and HouseName = HouseName";
SqlCommand createCommand = new SqlCommand(query, sqlCon);
SqlDataReader dr = createCommand.ExecuteReader();
if (dr.Read())
{
nameTxt.Text = (dr["StudentName"].ToString());
hseTxt.Text = (dr["HouseName"].ToString());
progTxt.Text = (dr["Prog"].ToString());
}
sqlCon.Close();
}
Your query:
SELECT *
FROM tblSignUP
WHERE
StudentName = StudentName
AND HouseName = HouseName
There are no parameters being passed into this; it is just a hardcoded statement.
You're comparing equivalent fields in your WHERE clause, which makes it redundant, i.e. you're really just doing a SELECT * from the table. What you're reading into your application is therefore always just the first row returned.
What you need is something like:
string query = "SELECT * FROM tblSignUP WHERE StudentName = #StudentName and HouseName = #HouseName";
SqlCommand createCommand = new SqlCommand(query, sqlCon);
createCommand.Parameters.Add(new SqlParameter("#StudentName", StudentName));
createCommand.Parameters.Add(new SqlParameter("#HouseName", HouseName));
The variables for StudentName and HouseName that are passed into the SqlParameter constructor (second argument), I'm assuming are already defined in your code somewhere.

How retrieve date and time from database according to login user using C#

I want to retrieve date and time according to login user in my ASP.NET web application using C#. The code I'm using is just returning the 1st row details.
I want date and time of current login user and bind it to with a label.
I have a table called Userdatatext with 3 columns:
UserName, UserText, LastEditTime
Sorry for my bad English.
Thanks in advance :)
My C# code
protected void Page_Load(object sender,EventArgs e)
{
if (Session["userName"] != null && Session["userName"] != "")
{
LblUser.Text = "Welcome " + Session["userName"].ToString() + "";
}
else
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
try
{
string Connectionstring = ConfigurationManager.ConnectionStrings["DbLogns"].ToString();
SqlConnection objConection = new SqlConnection(Connectionstring);
objConection.Open();
SqlCommand objCommand = new SqlCommand("select LastEditTime from Userdatatext where UserName='" + Session["userName"] + "'", objConection);
DataSet objDataset = new DataSet();
SqlDataAdapter objAdapter = new SqlDataAdapter(objCommand);
objAdapter.Fill(objDataset);
string lastdatetime = objDataset.Tables[0].Rows[0][0].ToString();
Lbllastedit.Text = "Last edit on :-" + lastdatetime;
Lbllastedit.Font.Size = 15;
objConection.Close();
}
catch(IndexOutOfRangeException n)
{
Lbllastedit.Text = "Last edit :- no data found !";
Lbllastedit.Font.Size = 13;
}
}
Try this code with a SqlDataReader:
try
{
string lastdatetime = null;
string Connectionstring = ConfigurationManager.ConnectionStrings["DbLogns"].ToString();
SqlConnection objConection = new SqlConnection(Connectionstring);
objConection.Open();
SqlCommand objCommand = new SqlCommand("select LastEditTime from Userdatatext where UserName='" + Session["userName"] + "'", objConection);
SqlDataReader dr = objCommand.ExecuteReader();
if (dr.Read())
{
lastdatetime = dr["LastEditTime"].ToString();
}
dr.Close();
Lbllastedit.Text = "Last edit on :-" + lastdatetime;
Lbllastedit.Font.Size = 15;
objConection.Close();
}

Insert and Update Function work on single button click in c#

I am trying to insert and update data using same button. I have created method(uniqueEmail()) to check the email address exist in table or not. Using this method I am trying to insert data if email is not preset.
here is my code please correct me where I am going wrong.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
You need to check for the count of the particular emailId, not the total count.
Modify the code as below:
public static bool uniqueEmail(string email)
{
string stremail;
string querye = "select count(email) as email from register where
email = '" + email + "'";
//Remaining Code
}
public static void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail(TextBox1.Text)) == true)
//Remaining Code
}
#nirmala you should replace method
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Two Things need to be done
Pass the Email Id while calling
if (uniqueEmail()==true)
To
if (uniqueEmail(TextBox1.Text)==true)
And in uniqueEmail method chenage the query ()include where condition as below
public bool uniqueEmail(email)
{
string stremail;
string querye = "select count(email) as email from registeruser where email='" + email + "'";
//your remaining code
}
Hi Nirmala your code is correct only you need to put where clause to find the email id already exist in the Database.
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser where email = '" +TextBox1.Text+ "'";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}

How to prevent Sqlite Database is locked?

i got one thread reading on the database. When i click on the menustrip it shows an error "Database is locked." and it only happen sometimes. Any way to prevent the database lock? I have try WAL but its not working.
Reading:
private void checkPort(string ipIN, char[] input, string output)
{
try
{
bool building = false;
Thread beep = new Thread(Beep);
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string query = "select * from ALL_IO(nolock)";
using (SQLiteCommand cmd = new SQLiteCommand(query, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
int Contact;
while (dr.Read())
{
string _IP = dr.GetString(0);
string _IO_I = dr.GetString(1);
string _BuildingName = dr.GetString(4);
int IO_I = Convert.ToInt32(dr.GetString(1).Replace("DI ", ""));
if (dr.GetString(3) == "NC")
{
Contact = 1;
}
else
{
Contact = 0;
}
_tableName = dr.GetString(8);
string _name = dr.GetString(5);
var _active = dr.GetString(6);
var _status = dr.GetString(7);
if (_active == "Yes" && _status == "Enable")
{
//Some condition check here
}
}
catch { }
}
Writing:
void contexMenuuu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
data = "";
ToolStripItem item = e.ClickedItem;
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string sql = "select * from " + Properties.Settings.Default.TableName + "(nolock) where Name= '" + Properties.Settings.Default.LabelName.Replace(" DO", "") + "' ";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
_controllerIP = dr.GetString(0);
_IO = dr.GetString(1);
_IO_O = dr.GetString(2).Replace("DO ", "");
_Name = dr.GetString(4);
_Interval = Convert.ToInt32(dr.GetString(9));
}
}
}
}
if (item.Text == "Bypass Enable")
{
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
//c.DefaultTimeout = 2000;
c.Open();
string sql = "update ALL_IO SET Active='Yes', Status='Bypass' where ControllerIP='" + _controllerIP + "' and DI='" + _IO + "';";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
lock (lockobj)
{
//SQLiteConnection.ClearAllPools();
cmd.ExecuteNonQuery(); //Error occur here
}
}
}
}
Once the functionality is finished you must close the Database connect for avoid database lock issue. For executing the query you opened the database connection after that you didn't close it. so you need to close.

How to get next data row by hiting on Next button

I want to get next record from table to show as Question. With below code I am not able to get next Question from table.
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Quiz_Load();
}
}
private void Quiz_Load()
{
try
{
if (Session["UserQuizID"] != null)
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("select top 0.1 percent QuestionID, Title, Answer1,Answer2,Answer3,Answer4,UserAnswer from [Table_UserAnswer] WHERE UserQuizID = '" + UserQuiz_ID.ToString() + "' AND UserName = '" + mayank.ToString() + "' order by newid()", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Session["QuestionID"] = dr[0].ToString();
Lbl_QuestionTitle.Text = dr[1].ToString();
RadBut_Answer.Items.Add(dr[2].ToString());
RadBut_Answer.Items.Add(dr[3].ToString());
RadBut_Answer.Items.Add(dr[4].ToString());
RadBut_Answer.Items.Add(dr[5].ToString());
Session["UserAnswer"] = dr[6].ToString();
}
else
{
}
con.Close();
}
else
{
Response.Redirect("Start.aspx");
}
}
catch
{
}
}
protected void RadBut_Answer_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int getvalue;
getvalue = Convert.ToInt32(RadBut_Answer.SelectedIndex + 1);
Lbl_SelectedAnsMsg.Text = MessageFormatter.GetFormattedAlertsMessage("Your Selected Answer is : " + getvalue.ToString());
Session["UserAnswer"] = getvalue.ToString();
}
catch
{
}
}
protected void But_Next_Click(object sender, EventArgs e)
{
UpdateUserAns();
if (Session["UserAnswer"] == null)
{
Response.Redirect("Result.aspx");
}
else
{
}
}
private void UpdateUserAns()
{
try
{
string mayank = "mm.bhagat";
string UserQuiz_ID = Session["UserQuizID"].ToString();
string Question_ID = Session["QuestionID"].ToString();
string User_Answer = Session["UserAnswer"].ToString();
SqlConnection con = new SqlConnection(c);
SqlCommand cmd = new SqlCommand("UPDATE Table_UserAnswer SET UserAnswer='" + User_Answer.ToString() + "' WHERE UserQuizID = '"+ UserQuiz_ID.ToString() +"' AND QuestionID = '"+Question_ID.ToString()+"' AND UserName = '"+mayank.ToString()+"'", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
cmd.Cancel();
}
catch
{
}
}
hi check this post client here
here you can find solution of your question

Categories