I am using the following code to get a user's full name, then
I am attempting to use the user's full name to then find out their ID, department and job title. Is there a way to use the DirectoryEntry to also acquire the EmplID from active directory?
public void Connect()
{
//method to connect to database and autofill user information
string n = GetFullName();
string[] names = n.Split(',');
FullName.Text = n;
fn = names[1];
ln = names[0];
try
{
var connection = ConfigurationManager.ConnectionStrings["PSHRDataConnection"];
SqlConnection ds = new SqlConnection(connection.ConnectionString);
ds.Open();
SqlCommand com = new SqlCommand("Select EmpID, psd.Descr, JobCode from PSHRData ps Inner Join PSDept psd on psd.DeptID=ps.DeptID where ps.LastName =#lname and ps.FirstName=#fname", ds);
com.Parameters.AddWithValue("#fname", fn);
com.Parameters.AddWithValue("#lname", ln);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
EmID.Text = reader["EmpID"].ToString();
dept.Text = reader["Descr"].ToString();
jobtitle.Text = reader["JobCode"].ToString();
}
ds.Close();
}
catch (SqlException)
{
}
}
This works properly when I replace the 2 parameters with my actual first and last name, but does not seem to want to accept the parameters for what ever reason (no error is thrown, just doesn't populate the information that it is supposed to)
Related
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}
I want to retrieve multiples values from database and display on one label.
My database design currently is:
courseid scholarshipid course
--------------------------------
1 1 maths
2 1 english
3 1 science
scholarshipid schName
-----------------------
1 moon
2 start
3 light
I would like to retrieve this information into one single label such as
Maths, English, Science
However, now I manage to retrieve one of it which is just maths.
This is my code in code behind:
protected void btnShowDetails_Click(object sender, EventArgs e)
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
int selectedIdtoPass = Convert.ToInt32(Selectedid);
courseBLL getRecord = new courseBLL();
addcourse courseRetrieve = new addcourse();
courseRetrieve = getRecord.getCourseDetail(selectedIdtoPass);
lbCourse.Text = courseRetrieve.course1 + "," + courseRetrieve.course1;
}
in my courseBLL
public addcourse getCourseDetail(int idcourse)
{
addcourse userObj = new addcourse();
courseDAL objtoPass = new courseDAL();
userObj = objtoPass.displayCourseInfo(idcourse);
return userObj;
}
in my DAL
public addcourse displayCourseInfo(int idcourse)
{
string strCommandText = "Select course from course where schokarshipid = #schokarshipid";
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", idcourse);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
addcourse userObj = new addcourse();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseID"].ToString());
string course = myReader["course"].ToString();
userObj = new addcourse(sID, course);
}
myReader.Close();
return userObj;
}
Edited:
public addcourse displayCourseInfo(int idcourse)
{
var courses = new List<addcourse>();
string strCommandText = "Select statement here"
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", idcourse);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["scholarshipid"].ToString());
string course = myReader["course"].ToString();
courses.Add(new addcourse(sID,course));
}
myReader.Close();
return courses;
}
I have removed some fields for this purpose so that I will not confuse you
You should return a List<addcourse> from getCourseDetail() and from displayCourseInfo and then you can do this if your addCourse has Course property:
lbCourse.Text = string.Join(", ", courses.Select(x => x.Course));
If the property name is different then change x.Course to that.
So in your reader you will do this
var courses = new List<addcourse>();
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseID"].ToString());
string course = myReader["course"].ToString();
courses.Add( new addcourse(sID, course)) ;
}
return courses;
Your query is also wrong:
Select course, from course ss inner join where courseID =#courseID
So you should fix that and make sure you get the columns you need because right now it is only getting course column and it has syntax errors. Run your query directly against the db using management studio. Once your query works the copy paste it and replace where part with a parameter the way you have it right now.
EDIT
It seems you are still stuck with this so I will give you a more detailed answer; however, you should really study up on some fundamental programming concepts. Anyhow, here it is:
Your code behind:
protected void btnShowDetails_Click(object sender, EventArgs e)
{
string Selectedid = GVFBAcc.SelectedRow.Cells[1].Text;//get user id
// Make sure this is the scholarshipid or the whole thing will
// not work.
int selectedIdtoPass = Convert.ToInt32(Selectedid);
courseBLL courseRetriever = new courseBLL();
// Remember you will get a list here
List<addcourse> courses = courseRetriever.getCourseDetail(selectedIdtoPass);
// This will take the list and separate the course property with a comma and space
var courseNames = string.Join(", ", courses);
// Now assign it to the text property
lbCourse.Text = courseNames;
}
Your BLL:
// See here you are retuning a list
// But you need to pass the scholarshipid so you can get the courses for that scholarshipid
public List<addcourse> GerCourses(int scholarshipId)
{
courseDAL courseRetriever = new courseDAL();
// Get the list
List<addcourse> courses = courseRetriever.GetCourses(scholarshipId);
return courses;
}
Your DAL:
// See here you are retuning a list
// But you need to pass the scholarshipid so you can get the courses for that scholarshipid
public List<addcourse> GetCourses(int scholarshipId)
{
// Make sure your query is correct, see you have spelling mistakes
// it should be scholarshipid not schokarshipid. it has to match the column in your database
// Make sure your table is called course and it has 3 columns: 1. courseid 2. course
// 3. scholarshipid or this query will not work
string strCommandText = "Select courseid, course from course where scholarshipid = #scholarshipId";
SqlCommand cmd = new SqlCommand(strCommandText, conn);
cmd.Parameters.AddWithValue("#scholarshipid", scholarshipId);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader();
// create a list so we can hold all the courses
List<addcourse> userObjs = new List<addcourse>();
// This will read one row at a time so keep reading until there are no more records
while (myReader.Read())
{
int sID = Convert.ToInt32(myReader["courseid"].ToString());
string course = myReader["course"].ToString();
addcourse userObj = new addcourse(sID, course);
// add it to the list
userObjs.Add(userObj);
}
myReader.Close();
// return the list
return userObjs;
}
A few more tips:
Give your methods more meaningful names. See the names I gave them GetCourses, now it reads like English and it is easy to follow.
Your class addcourse should be called Course. addcourse sounds like an action "add course", that could be a good name for a method if you were adding courses. Also use Pascal notation for class names and method names. Use Camel casing for arguments, parameters and local variables.
Learn how to use the Visual Studio debugger. Go watch some YouTube videos on Visual Studio Debugger.
Create a for loop then add it on the variable you are using
I'm trying to populate a text box with a forename and surname using the code below:
using (OleDbConnection connName = new OleDbConnection(strCon))
{
String sqlName = "SELECT forename, Surname FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand commandname = new OleDbCommand(sqlName, connName);
connName.Open();
// Create a reader containing the results
using (OleDbDataReader readerName = commandname.ExecuteReader())
{
readerName.Read(); // Advance to the first row.
txtName.Text = readerName[0].ToString();
}
connName.Close();
}
However I'm getting the error: OleDbException was unhandled.
"no required values for one of more required parameters"
at the ExecuteReader and I'm not sure how to go about fixing this.
EDIT: this code below is nearly the exact same bar for the information in the query but this exception is not coming up for it.
string strCon = Properties.Settings.Default.PID2dbConnectionString;
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
conn.Open();
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn);
// Create a reader containing the results
using (OleDbDataReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
conn.Close();
}
The usual reason for this is a null or empty string i.e. txtCustomerID.Text has no value so the query being sent to the server is:
SELECT forename, Surname FROM customer WHERE [customerID]=
You can avoid errors like this and SQL Injection, use strongly typed parameters and avoid data truncation using parameterised queries (I have assumed customer ID is an int field)
using (OleDbConnection connName = new OleDbConnection(strCon))
{
String sqlName = "SELECT forename, Surname FROM customer WHERE customerID = #CustomerID";
// Create a command to use to call the database.
using (OleDbCommand commandname = new OleDbCommand(sqlName, connName))
{
//Check the input is valid
int customerID = 0;
if (!int.TryParse(txtCustomerID.Text, out customerID))
{
txtName.Text = "Customer ID Text box is not an integer";
return;
}
connName.Open();
// Add the parameter to the command
commandname.Parameters.Add("#CustomerID", OleDbType.Integer).Value = customerID;
// Create a reader containing the results
using (OleDbDataReader readerName = commandname.ExecuteReader())
{
readerName.Read(); // Advance to the first row.
txtName.Text = readerName[0].ToString();
}
connName.Close();
}
}
You have to encode parameters used in string queries.
String sqlName = String.Format("SELECT forname, Surname FROM customer WHERE customerID={0}",txtCustomerID.Text);
But I advice you against using SQL queries hard-coded in strings. Its easy way for SQL Injection attack. You should use parammeters instead.
I am using System.Data.SQLite for my database, and my select statements are very slow. It takes around 3-5 minutes to query around 5000 rows of data. Here is the code I am using:
string connectionString;
connectionString = string.Format(#"Data Source={0}", documentsFolder + ";Version=3;New=False;Compress=True;");
//Open a new SQLite Connection
SQLiteConnection conn = new SQLiteConnection(connectionString);
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * From urls";
//Assign the data from urls to dr
SQLiteDataReader dr = cmd.ExecuteReader();
SQLiteCommand com = new SQLiteCommand();
com.CommandText = "Select * From visits";
SQLiteDataReader visit = com.ExecuteReader();
List<int> dbID2 = new List<int>();
while (visit.Read())
{
dbID2.Add(int.Parse(visit[1].ToString()));
}
//Read from dr
while (dr.Read())
{
string url = dr[1].ToString();
string title = dr[2].ToString();
long visitlong = Int64.Parse(dr[5].ToString());
string browser = "Chrome";
int dbID = int.Parse(dr[0].ToString());
bool exists = dbID2.Any(item => item == dbID);
int frequency = int.Parse(dr["visit_count"].ToString());
bool containsBoth = url.Contains("file:///");
if (exists)
{
if (containsBoth == false)
{
var form = Form.ActiveForm as TestURLGUI2.Form1;
URLs.Add(new URL(url, title, browser, visited, frequency));
Console.WriteLine(String.Format("{0} {1}", title, browser));
}
}
}
//Close the connection
conn.Close();
And here is another example that takes long:
IEnumerable<URL> ExtractUserHistory(string folder, bool display)
{
// Get User history info
DataTable historyDT = ExtractFromTable("moz_places", folder);
// Get visit Time/Data info
DataTable visitsDT = ExtractFromTable("moz_historyvisits",
folder);
// Loop each history entry
foreach (DataRow row in historyDT.Rows)
{
// Select entry Date from visits
var entryDate = (from dates in visitsDT.AsEnumerable()
where dates["place_id"].ToString() == row["id"].ToString()
select dates).LastOrDefault();
// If history entry has date
if (entryDate != null)
{
// Obtain URL and Title strings
string url = row["Url"].ToString();
string title = row["title"].ToString();
int frequency = int.Parse(row["visit_count"].ToString());
string visit_type;
//Add a URL to list URLs
URLs.Add(new URL(url, title, browser, visited, frequency));
// Add entry to list
// URLs.Add(u);
if (title != "")
{
Console.WriteLine(String.Format("{0} {1}", title, browser));
}
}
}
return URLs;
}
DataTable ExtractFromTable(string table, string folder)
{
SQLiteConnection sql_con;
SQLiteCommand sql_cmd;
SQLiteDataAdapter DB;
DataTable DT = new DataTable();
// FireFox database file
string dbPath = folder + "\\places.sqlite";
// If file exists
if (File.Exists(dbPath))
{
// Data connection
sql_con = new SQLiteConnection("Data Source=" + dbPath +
";Version=3;New=False;Compress=True;");
// Open the Connection
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
// Select Query
string CommandText = "select * from " + table;
// Populate Data Table
DB = new SQLiteDataAdapter(CommandText, sql_con);
DB.Fill(DT);
// Clean up
sql_con.Close();
}
return DT;
}
Now, how can I optimize these so that they are faster?
In addition to moving more of the data aggregation to SQL as joins, you might also consider getting your SQLiteDataReader to provide the data types instead of always parsing the values.
For example, you have the line:
long visitlong = Int64.Parse(dr[5].ToString());
dr[5] is a Sqlite value which you are first converting to a string, then parsing it to a long. These parse operations take time. Why not instead do:
long visitlong = dr.GetInt64(5);
Or:
long visitlong = dr.GetInt64(dr.GetOrdinal("columnName"));
Check out the various methods that SqliteDataReader offers and utilize them whenever possible instead of parsing values.
Edit:
Note that this requires the data be stored as the correct type. If everything in the database is stored as a string, some parsing will be unavoidable.
Make sure that you've recently run the SQL command "ANALYZE {db|table|index};".
I recently ran into a situation where queries were running fast (<1 sec) in my ER software (Navicat), ie: not debugging, but they were very slow (>1 min) debugging in Visual Studio. It turned out that because I did my database design in Navicat (SQLite v3.7), the statistics were not the same as those used by System.Data.SQLite in Visual Studio (v3.8). Running "ANALYZE;" on the entire database file from Visual Studio updated the [sqlite_statX] tables used by v3.8. Both places were the same speed after that.
I'm trying to implement a method which will take a given connection string and return an ArrayList containing the contents of a SQL view.
I've verified the validity of the connection string and the view itself. However I don't see what the problem is in the code below. In debug, when it runs the ExecuteReader method and then try to enter the while loop to iterate through the records in the view, it immediately bails because for some reason sqlReader.Read() doesn't.
public ArrayList GetEligibles(string sConnectionString)
{
string sSQLCommand = "SELECT field1, field2 FROM ViewEligible";
ArrayList alEligible = new ArrayList();
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
// Open connection.
sConn.Open();
// Define the command.
SqlCommand sCmd = new SqlCommand(sSQLCommand, sConn);
// Execute the reader.
SqlDataReader sqlReader = sCmd.ExecuteReader(CommandBehavior.CloseConnection);
// Loop through data reader to add items to the array.
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader["field1"].ToString();
Person.field2 = sqlReader["field2"].ToString();
alEligible.Add(Person);
}
// Call Close when done reading.
sqlReader.Close();
}
return alEligible;
}
Note, EligibleClass is just a class object representing one row of the view's results.
A couple of things I would check:
Is the connection string ok
Does the user in your connection string have access to the database/view
Can you access that database from the pc your at
Does the ViewEligable view exist
Does the view contain a field1 and field2 column.
Here one way you could possibly clean up that code somewhat (assuming you have .net 2.0)
public List<EligibleClass> GetEligibles(string sConnectionString)
{
List<EligibleClass> alEligible = null;
try
{
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
sConn.Open();
using (SqlCommand sCmd = new SqlCommand())
{
sCmd.Connection = sConn;
sCmd.CommandText = "SELECT field1, field2 FROM ViewEligible";
using (SqlDataReader sqlReader = sCmd.ExecuteReader())
{
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader.GetString(0);
Person.field2 = sqlReader.GetString(1);
if (alEligible == null) alEligible = new List<EligibleClass>();
alEligible.Add(Person);
}
}
}
}
}
catch (Exception ex)
{
// do something.
}
return alEligible;
}