Alert on gridview edit based on permission - c#

I have a gridview with edit option at the start of the row. Also I maintain a seperate table called Permission where I maintain user permissions. I have three different types of permissions like Admin, Leads, Programmers. These all three will have access to the gridview. Except admin if anyone tries to edit the gridview on clicking the edit option, I need to give an alert like This row has important validation and make sure you make proper changes.
When I edit, the action with happen on table called Application. The table has a column called Comments. Also the alert should happen only when they try to edit rows where the Comments column have these values in them.
ManLog datas
Funding Approved
Exported Applications
My try so far.
public bool IsApplicationUser(string userName)
{
return CheckUser(userName);
}
public static bool CheckUser(string userName)
{
string CS = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
DataTable dt = new DataTable();
using (SqlConnection connection = new SqlConnection(CS))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select * from Permissions where AppCode='Nest' and UserID = '" + userName + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
if (dt.Rows.Count >= 1)
return true;
else
return true;
}
protected void Details_RowCommand(object sender, GridViewCommandEventArgs e)
{
string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name;
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string[] words = currentUser.Split('\\');
currentUser = words[1];
bool appuser = IsApplicationUser(currentUser);
if (appuser)
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
if (e.CommandName.Equals("Edit") && ds.Tables[0].Rows[0]["Role_Cd"].ToString().Trim() != "ADMIN")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gvCurrentGrid = (GridView)sender;
GridViewRow row = gvCurrentGrid.Rows[index];
string strID = ((Label)row.FindControl("lblID")).Text;
string strAppName = ((Label)row.FindControl("lblAppName")).Text;
Response.Redirect("AddApplication.aspx?ID=" + strID + "&AppName=" + strAppName + "&Edit=True");
}
}
}
Kindly let me know if I need to add something. Thanks for any suggestions.

public static bool CheckUserAdminOrNot(your arguments)
{
string currentUser = HttpContext.Current.Request.LogonUserIdentity.Name;
string str = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string[] words = currentUser.Split('\\');
currentUser = words[1];
bool appuser = IsApplicationUser(currentUser);
if (appuser)
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(str))
{
SqlCommand command = new SqlCommand();
command.Connection = connection;
string strquery = "select Role_Cd from User_Role where AppCode='PM' and UserID = '" + currentUser + "'";
SqlCommand cmd = new SqlCommand(strquery, connection);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
}
if(user is not Admin)
return string that you want....
}
}
}
After that you get response in ajax use this response and redirect page and pass value in url that you want...

Related

NullReferenceException when using SQL Queries WPF C#

I am doing a little project and I got stuck at a certain point (I am new to C# WPF). What I want to do is I have some data tables called item, issue_note & items_in_Issue_Note. I want to get all the issue note details into a datagrid & after selecting a row and click view button, I want to display the items in that issue note. I can get the data using
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
but when I am going to use
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
the code throws a NullReferenceException (I want to use the SQL query, because I want to search issue notes by no and date).
I will add my code for reference.
Thank you!
public PnlISNDetails_SK()
{
InitializeComponent();
dgISNDetails.ItemsSource = db.Database.SqlQuery<Issue_Note>("select Issue_No,Created_Date,R_Name,R_Dep,R_Desig,Issued_Date,UpdatedAt from Issue_Note").ToList();
dgISNDetails.ItemsSource = db.Issue_Note.ToList();
datagrid = dgISNDetails;
}
private void btnSearch_Click(object sender, RoutedEventArgs e)
{
dt = new DataTable();
addIssueNoteLogic = new AddIssueNoteLogic();
if(cmbSearchBy.Text== "ISSUE NOTE NO")
{
addIssueNoteLogic.ViewISNFromISNNo(txtSearchBox.Text).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "CREATED DATE")
{
addIssueNoteLogic.ViewISNFromCreatedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
else if (cmbSearchBy.Text == "ISSUED DATE")
{
addIssueNoteLogic.ViewISNFromIssuedDate(Convert.ToDateTime(dpSearchDatePicker.Text)).Fill(dt);
dgISNDetails.ItemsSource = dt.DefaultView;
datagrid = dgISNDetails;
}
}
Class code for search issue notes:
public SqlDataAdapter ViewISNFromISNNo(string searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issue_No like '%" + searchText + "%'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromCreatedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where created_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNFromIssuedDate(DateTime searchText)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select * from Issue_Note where Issued_date = '" + searchText + "'";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
public SqlDataAdapter ViewISNDetails(string isnNo)
{
con.Open();
cmd = new SqlCommand();
cmd.CommandText = "select Item.ItemCode,Item.itemName,Item.Unit,Items_In_Issue_Note.Issued_Qty,Issue_Note.Issue_No from ((Item inner join Items_In_Issue_Note on Item.ItemCode= " +
"Items_In_Issue_Note.ItemCode) inner join Issue_Note on Issue_Note.Issue_No = Items_In_Issue_Note.Issue_No)where Issue_Note.Issue_No = '"+isnNo+"'; ";
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Close();
return da;
}
This is the code for displaying items in issue note:
public void LoadGrid()
{
dt = new DataTable();
string isnNo = (PnlISNDetails_SK.datagrid.SelectedItem as Issue_Note).Issue_No; //Exception is thrown in here
addIssueNoteLogic = new AddIssueNoteLogic();
addIssueNoteLogic.ViewISNDetails(isnNo).Fill(dt);
dgItemsInISN.ItemsSource = dt.DefaultView;
}
Debug and verify that the connection to the database in your datacontext is not null or closed. specifically this part
db.Database

C# get sql table column value and put it in a variable

I have a user login menu. I want to redirect the user based on their Level. The Level data is in the SQL table. I want to get the Level data from the table based on their username and assign it to a variable.
protected void btnDefault_Click(object sender, EventArgs e)
{
//filter entered text
string strUserName = Tools.checkSQLInjection(txtUserName.Text).Trim();
string strPassword = Tools.checkSQLInjection(txtPassword.Text);
string strError = "";
//Get Dealer Level Value
SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email='" + strUserName + "'");
string strDealerLvl = "dealerLvl".ToString();
int intDealerLvl;
bool isParsable = Int32.TryParse(strDealerLvl, out intDealerLvl);
if (strDealerLvl == "1")
{ Response.Redirect("/dealers/dashboard"); }
else if (strDealerLvl == "2")
{ Response.Redirect("/dealers/dashboard-2"); }
You don't seem to be checking the password, but perhaps that supposed to come later.
A working code stub to do this would look like say this:
DataTable MyTable = new DataTable();
int intDealerLvl = 0;
using (SqlCommand cmdSQL = new SqlCommand("SELECT dealerLv1 FROM Users where email = #meail",
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
}
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
switch (intDealerLvl)
{
case 1:
{
Response.Redirect("/dealers/dashboard");
break;
}
case 2:
{
Response.Redirect("/dealers/dashboard-2");
break;
}
default:
{
// no level found - where to go??
break;
}
}
However, it not clear if you supposed to be checking the password, and if so then of course we use this:
DataTable MyTable = new DataTable();
string strSQL;
strSQL = "SELECT dealerLv1 FROM Users where email = #Email and Password = #Pass";
using (SqlCommand cmdSQL = new SqlCommand(strSQL,
new SqlConnection(My.Settings.test3ConnectionString)))
{
cmdSQL.Parameters.Add("#email", SqlDbType.NVarChar).Value = strUserName;
cmdSQL.Parameters.Add("#Pass", SqlDbType.NVarChar).Value = strPassword;
cmdSQL.Connection.Open();
MyTable.Load(cmdSQL.ExecuteReader);
if (MyTable.Rows.Count > 0)
intDealerLvl = MyTable.Rows(0)(0);
using(SqlCommand command = new SqlCommand("SELECT dealerLvl FROM Users where email= #strUserName", connection))
{
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#strUserName", strUserName);
DataSet ds = new DataSet();
using(SqlDataAdapter da = new SqlDataAdapter(command))
da.Fill(ds);
//Get the result of the first row
DataRow dr = ds.Tables[0].Rows[0];
//Get the value of the column in the first row
string strDealerLvl = dr["dealerLvl"].ToString();
}

how can I store all of the database records from a username(from registration) but it is based on the user input?

Here is my log in page code. What I want to do is when the user inputs his/her username, it will then get all of the database records "based on that username input" of the customer and store it in a single session.
protected void btn_Login_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(scm.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkPassword = "select Password from UserData where Username ='" + txtUser.Text + "'";
SqlCommand passCom = new SqlCommand(checkPassword, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ", "");
if (password == txtPassword.Text)
{
Session["Username"] = txtUser.Text;
Response.Write("<script>alert('Record saved successfully')</script>");
Response.Redirect("OrderNow.aspx");
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
else
{
lblcrederror.Text = ("Credentials dont match");
}
}
I have set the Session["Username"] to the user input(txtUser.text), but what I want to do is to get all of the database records on that username that the customer will enter.
Afterwards, I am planning to call on that specific database record and bind it to the order .aspx page. I have tried this code below but its only showing me the Session["Username"], since I have called it on the login page.
txtCustomerName.Text = Session["Username"].ToString();
txtCustomerPhoneNo.Text = Session["Contact"].ToString();
txtCustomerEmailID.Text = Session["Email"].ToString();
txtCustomerAddress.Text = Session["DeliveryAddress"].ToString();
You can create a data structure to store the information you need.
public class Person
{
public string Username { get; set; }
public string Contact { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
using (SqlCommand command = new SqlCommand(
"SELECT * FROM databaseTablename where username = " + txtUser.Text, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
Person person = new Person();
person.Username = reader.GetString(reader.GetOrdinal("username"));
person.Contact = reader.GetString(reader.GetOrdinal("contact"));
person.Email = reader.GetString(reader.GetOrdinal("email"));
person.Password = reader.GetString(reader.GetOrdinal("password"));
}
}
}
}
You can then store this object in a session like so:
Session["username"] = person;
Later on, if you want to access the contents of the session, say in the Order.aspx page, you can do like so:
Person person = (Person)Session["username"];
get the records from the database. Store it in a comma separated string.
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
conn.Open();
string checkuser = "select count(*) from UserData where Username = '" + txtUser.Text + "'";
SqlCommand scm = new SqlCommand(checkuser, conn);
SqlDataAdapter da=new SqlDataAdapter(scm);
DataSet ds=new DataSet();
da.Fill(ds);
conn.Close();
string userdata="";
foreach (DataRow row in ds.Tables[0].Rows)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
userdata+=","+row[i].ToString();
}
}
userdata=userdata.TrimStart(',');
Session["username"]= userdata;
for getting all the records just get this string from session and split it
If(Session["username"]!=null)
String user=Session["username"].ToString();
string[] udat=user.Split(',');
you can get all data in this string array.
Im kind of new to programming so please excuse any error.
This is for storing your all values in single session
DataBaseConnection db = new DataBaseConnection();
DataTable dt = new DataTable();
dt = db.executeNonQuery("Your Query that retrieves all user's data goes here");
if(dt.Rows.Count > 0)
{
List<string> lst = new List<string>();
foreach(DataRow dr in dt.Rows)
{
lst.Add(dr["Cloumn_1"].ToString());
lst.Add(dr["Column_2"].ToString());
.
.
Session["YourSessionName"] = lst;
}
}
here DataBaseConnection is class that returns connection string of database, so now you know what to do.
i hope this helps. Let me know

How to get list of all database from sql server in a combobox using c#.net

I am entering the source name userid and password through the textbox and want the database list should be listed on the combo box so that all the four options sourcename, userid, password and databasename can be selected by the user to perform the connectivity
The databases are to be retrieve from other system as per the user. User will enter the IP, userid and password and they should get the database list in the combo box so that they can select the required database and perform the connectivity
private void frmConfig_Load(object sender, EventArgs e)
{
try
{
string Conn = "server=servername;User Id=userid;" + "pwd=******;";
con = new SqlConnection(Conn);
con.Open();
da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cbSrc.Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am trying to do this but it is not generating any data
sys.databases
SELECT name
FROM sys.databases;
Edit:
I recommend using IDataReader, returning a List and caching the results. You can simply bind your drop down to the results and retrieve the same list from cache when needed.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
// Open connection to the database
string conString = "server=xeon;uid=sa;pwd=manager; database=northwind";
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
// Set up a command with the given query and associate
// this with the current connection.
using (SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
First add following assemblies:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.Smo.dll
from
C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\
and then use below code:
var server = new Microsoft.SqlServer.Management.Smo.Server("Server name");
foreach (Database db in server.Databases) {
cboDBs.Items.Add(db.Name);
}
you can use on of the following queries:
EXEC sp_databases
SELECT * FROM sys.databases
Serge
Simply using GetSchema method:
using (SqlConnection connection = GetConnection())
{
connection.Open();
DataTable dtDatabases = connection.GetSchema("databases");
//Get database name using dtDatabases["database_name"]
}
using (var connection = new System.Data.SqlClient.SqlConnection("ConnectionString"))
{
connection.Open();
var command = new System.Data.SqlClient.SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "SELECT name FROM master.sys.databases";
var adapter = new System.Data.SqlClient.SqlDataAdapter(command);
var dataset = new DataSet();
adapter.Fill(dataset);
DataTable dtDatabases = dataset.Tables[0];
}
How to get list of all database from sql server in a combobox using c# asp.net windows application
try
{
string Conn = "server=.;User Id=sa;" + "pwd=passs;";
SqlConnection con = new SqlConnection(Conn);
con.Open();
SqlCommand cmd = new SqlCommand();
// da = new SqlDataAdapter("SELECT * FROM sys.database", con);
cmd = new SqlCommand("SELECT name FROM sys.databases", con);
// comboBox1.Items.Add(cmd);
SqlDataReader dr;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
//comboBox2.Items.Add(dr[0]);
comboBox1.Items.Add(dr[0]);
}
}
// .Items.Add(da);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Try this:
SqlConnection con = new SqlConnection(YourConnectionString);
SqlCommand cmd = new SqlCommand("SELECT name from sys.databases", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cbSrc.Items.Add(dr[0].ToString());
}
con.Close();
or this:
DataSet ds = new DataSet();
SqlDataAdapter sqlda = new SqlDataAdapter("SELECT name from sys.databases", YourConnectionString);
sqlda.Fill(ds);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
cbSrc.Items.Add(ds.Tables[0].Rows[i][0].ToString());
}
public static List<string> GetAllDatabaseNamesByServerName(string ServerName, [Optional] string UserID, [Optional] string Password)
{
List<string> lstDatabaseNames = null;
try
{
lstDatabaseNames = new List<string>();
//string servername = System.Environment.MachineName;
string newConnString = string.Format("Data Source={0};", ServerName);
if (UserID == null)
{
newConnString += "Integrated Security = True;";
}
else
{
newConnString += string.Format("User Id ={0}; Password={1};", UserID, Password);
}
SqlConnection con = new SqlConnection(newConnString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT name FROM master.sys.databases", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
lstDatabaseNames.Add(row[0].ToString());
}
con.Close();
return lstDatabaseNames;
}
finally
{
}
}

How to extract individual column data from C# MySQL query?

How can I extract the column data from my user row? EX: This gets called on my WCF server when the client logs in. It works up to var xx = ds.Tables[0].Rows[1]; where it throws an error on the clients side. Basically I am trying to have the user/pass verified in the database. Then return to the Client a DateTime of when his subscription expires.
public bool Authenticate(string userId, string password, out string token)
{
token = "";
string MyConnectionString = "Server=localhost;Database=testdb;Uid=root;Pwd=admin;";
MySqlConnection sqlCon = new MySqlConnection(MyConnectionString);
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = '"+userId+"' AND password = '"+password+"'";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
adap.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0];
CustomDataSource.AddUserData(token, userId);
return true;
}
return false;
}
Well I suppose that your query returns only one row (if it finds the user with the correct password)
In that case you get the date from the first row returned (index zero).
Also I assume that your date is stored in the fifth column (index four), if not you should adjust the second index to point to the correct column. (The base array index is always zero)
if (ds.Tables[0].Rows.Count > 0)
{
token = Guid.NewGuid().ToString();
var xx = ds.Tables[0].Rows[0][4];
CustomDataSource.AddUserData(token, userId);
return true;
}
Said that, let me point to a big problem of this code.
This code could be easily used for a Sql Injection Attack because it concatenates strings, probably typed by your user, to form a Sql Text passed to the database engine. Instead you should use parameters to avoid the Sql Injection problem and the quoting of user text (password with an apostrophe?)
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
sqlCon.Open();
MySqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = "SELECT * FROM table1 WHERE username = ?user AND password = ?pwd";
cmd.Parameters.AddWithValue("?user", userId);
cmd.Parameters.AddWithValue("?pwd", password);
using(MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
}
var xx = ds.Tables[0].Rows[0].ItemArray[5];
Is how.
try using foreach loop
foreach (DataRow row in ds.Tables[0].Rows)
{
var xx = row[1];
var x = row[5];
// other codes
return true;
}
one more thing, parameterized your query to avoid SQL injection
using(MySqlConnection sqlCon = new MySqlConnection(MyConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = sqlCon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table1 WHERE username = #user AND password = #pass";
cmd.Parameters.AddWithValue("#user", userId);
cmd.Parameters.AddWithValue("#pass", password);
using (MySqlDataAdapter adap = new MySqlDataAdapter(cmd))
{
try
{
DataSet ds = new DataSet();
adap.Fill(ds);
}
catch (MySqlException e)
{
// do something with the exception
// don't hide it!
}
}
}
}

Categories