I am having trouble understanding why I am getting this exception thrown !
This is the code :
public static List<Employee> LoadEmployees()
{
List<Employee> emp = new List<Employee>();
try
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
string query = "select * from Employee;";
SQLiteCommand cmd = new SQLiteCommand(query, cnn);
using (var reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
emp[i].Id = reader.GetString(0);
emp[i].Name = reader.GetString(1);
emp[i].Gender = reader.GetString(2);
emp[i].Department = reader.GetString(3);
emp[i].Doj = reader.GetString(4);
emp[i].Email = reader.GetString(5);
emp[i].Phone = reader.GetString(6);
i++;
}
}
return emp;
}
}
catch (Exception ex)
{
emp = null;
return emp;
}
}
I tried debugging and found that -
id = 'emp[i].Id' threw an exception of type 'System.ArgumentOutOfRangeException'
Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll
I am not understanding why it throwing it because i have initialized i = 0;
List<Employee> emp = new List<Employee>();
At this point, emp is empty, but you try accessing items by using emp[i] when it's still empty.
You should use emp.Add(new Employee()); at some point if you don't want the list to be empty anymore.
public static List<Employee> LoadEmployees()
{
List<Employee> emp = new List<Employee>(); // basically you have created new List<Employee> which is at the moment is empty. so if you try to do emp[0].Name, you will get exception
try
{
using (SQLiteConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Open();
string query = "select * from Employee;"; // fetching employees from database
SQLiteCommand cmd = new SQLiteCommand(query, cnn);
using (var reader = cmd.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
Employee e = new Employee(); // create new instance of employee object and initialize it's members and then add it in emp object.
e.Id = reader.GetString(0);
e.Name = reader.GetString(1);
e.Gender = reader.GetString(2);
e.Department = reader.GetString(3);
e.Doj = reader.GetString(4);
e.Email = reader.GetString(5);
e.Phone = reader.GetString(6);
emp.Add(e);
}
}
return emp;
}
}
catch (Exception ex)
{
emp = null;
return emp;
}
}
Related
I have this function, which updates some info in my database. It works properly until bool[] days = new bool[7]; and it throws exception message - 'index is outside the bounds of the array'. I cannot understand how it is out of bounds, when I just declared and initialized it.
public static void UpdateDepartment(Department department, string oldName)
{
if (department!=null)
{
try
{
using (MySqlConnection conn = new MySqlConnection(ConnectionString))
{
string query = "select * from people where department = #oldName";
List<User> results = new List<User>();
MySqlCommand cmd_refactor = new MySqlCommand(query, conn);
cmd_refactor.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
MySqlDataReader dataReader = cmd_refactor.ExecuteReader();
while (dataReader.Read())
{
int id = int.Parse(dataReader[0].ToString());
string username = dataReader[1].ToString();
string firstName = dataReader[2].ToString();
string lastName = dataReader[3].ToString();
string email = dataReader[4].ToString();
string phoneNumber = dataReader[5].ToString();
PersonPosition position =
(PersonPosition)Enum.Parse(typeof(PersonPosition), dataReader[6].ToString(), true);
double salary = Double.Parse(dataReader[7].ToString());
Department departmentResult = new Department(dataReader[8].ToString());
ShiftType shiftType =
(ShiftType)Enum.Parse(typeof(ShiftType), dataReader[11].ToString(), true);
bool[] days = new bool[7];
for (int i = 0; i < 7; i++)
{
days[i] = bool.Parse(dataReader[i + 12].ToString());
}
User user = new User(username, firstName, lastName, email, position, salary, shiftType,
days, departmentResult, id, phoneNumber);
results.Add(user);
}
conn.Close();
foreach (var item in results)
{
conn.Open();
item.UserDepartment = department;
UpdateUser(item);
conn.Close();
}
query = "update departments set departmentName = #name where departmentName = #oldName";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#name", department.Name);
cmd.Parameters.AddWithValue("#oldName", oldName);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw new NoConnectionException();
}
}
}
days[i] can't be out of range. It must be the other array in this line which throws this error: dataReader[i + 12]
I'm retrieving some information from an MSSQL via SQLDataReader, but while debugging it I notice in some cases the reader clears the result view with the error "Enumeration yielded no results" see the screenshot Before Running passing Read(),
After passing read()
this is my code,the error happens on getActiveUsers() method.
getDatabases() works just fine. could someone help me? cheers
public partial class automation : System.Web.UI.Page
{
SqlConnection con;
static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
protected void Page_Load(object sender, EventArgs e)
{
ASPxGridView1.DataSource = activeUsers.ToList();
}
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
con = new System.Data.SqlClient.SqlConnection(sqlconn);
var cmd = new SqlCommand(SqlQuery, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<ActiveUsers> results = new List<ActiveUsers>();
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
con.Close();
return results;
}
public void getActiveUsers()
{
activeUsers.Clear();
List<ActiveUsers> Databases= getDatabases();
SqlConnection conn = new SqlConnection();
string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1 inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";
for (int i = 0;i < Databases.Count;i++)
{
conn.ConnectionString =
"Data Source=MAXSQLCLUS01;" +
"Initial Catalog=" + Databases[i].ToString()+";"+
"User id=sa;" +
"Password=Max1m1zer;";
var cmd = new SqlCommand(SqlQuery, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int NumberOfUsersCounter = 0 ;
//TODO Select Enabled users
if (reader.Read())
{
while (reader.Read())
{
string user = String.Format("{0}", reader["User_Id"]);
//logic to remove system users
if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
{
NumberOfUsersCounter++;
}
}
ActiveUsers newEntry = new ActiveUsers();
newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
newEntry.ClientName = Databases[i].ClientName.ToString();
activeUsers.Add(newEntry);
}
conn.Close();
//Add to ActiveUsers list
}
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = activeUsers.ToList();
ASPxGridView1.DataBind();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
getActiveUsers();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ASPxGridView1.DataBind();
ASPxGridViewExporter1.Landscape = true;
ASPxGridViewExporter1.FileName = "User Count Report";
ASPxGridViewExporter1.WriteXlsToResponse();
}
}
}
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
use this
if (reader.HasRows)
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
your if Condition is wrong
if(reader.Read()) ==> is Wrong
Read() is not return boolean Value
use HasRows to check rows in SQLDataReader
You are skipping the first result. if (reader.Read()) { while(reader.Read()) {.... Remove the enclosing if, all it does is see if there is a row and retrieve it but then you do not read it, instead you do it again in the if so the first result is always discarded.
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
using(var cmd = new SqlCommand(SqlQuery, con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
List<ActiveUsers> results = new List<ActiveUsers>();
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = reader.GetString(0);
company.ClientName = reader.GetString(1);
results.Add(company);
}
}
}
return results;
}
Side notes:
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]) would be better written as company.DatabaseName = reader.GetString(0). The same goes for the next line. No need to use string.Format and you are specifying the columns and order in the query so use the ordinal index so get the native value.
I would recommend you wrap the SqlConnection and SqlDataReader in using blocks to ensure they are closed/disposed after use even in the event of an exception.
I have a StoredProcedure that I created like this;
CREATE DEFINER=`mysqladmin`#`%` PROCEDURE `Alerts_GetAlerts`(IN managerID INT)
BEGIN
SELECT ID, Type, EmpID, ManagerID, HolID
FROM Alerts
WHERE ManagerID = managerID;
END$$
I then try to call this from my C# code like so;
using (var con = new MySqlConnection(MySQLConStr))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("Alerts_GetAlerts", con))
{
cmd.Parameters.AddWithValue("#managerID", managerID);
using (var dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var alert = new AlertsModel
{
ID = Convert.ToInt32(dataReader[0]),
Type = Convert.ToInt32(dataReader[1]),
ManagerID = Convert.ToInt32(dataReader[2]),
EmployeeID = Convert.ToInt32(dataReader[3]),
HolidayID = Convert.ToInt32(dataReader[4]),
};
AllAlerts.Add(alert);
}
}
}
return AllAlerts;
}
However I constantly get, Incorrect number of arguments for PROCEDURE sdcdatabase.Alerts_GetAlerts; expected 1, got 0 even though to me it appears I am passing the managerID argument through;
cmd.Parameters.AddWithValue("#managerID", managerID);
Where am I going wrong?
try this code
using (var con = new MySqlConnection(MySQLConStr))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand("Alerts_GetAlerts(#managerID)", con))
{
cmd.Parameters.AddWithValue("#managerID", managerID);
using (var dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var alert = new AlertsModel
{
ID = Convert.ToInt32(dataReader[0]),
Type = Convert.ToInt32(dataReader[1]),
ManagerID = Convert.ToInt32(dataReader[2]),
EmployeeID = Convert.ToInt32(dataReader[3]),
HolidayID = Convert.ToInt32(dataReader[4]),
};
AllAlerts.Add(alert);
}
}
}
return AllAlerts;
}
Trying to retrieve a single value from an oracle database table, with the code below
public int _getProductPrice(string product_id)
{
Int16 price = 0;
string query = string.Format(#"select sum(price) price from sales where product_id = '{0}'", product_id);
string connectionString = String.Format("SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1}))(CONNECT_DATA=(SERVICE_NAME={2})));uid={3};pwd={4};", AppConfig.OraDBHOST, AppConfig.OraDBPORT, AppConfig.OraDBNAME, AppConfig.OraDBUSER, AppConfig.OraDBPWD);
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand cm = new OracleCommand(query);
try
{
cm.Connection = connection;
connection.Open();
OracleDataReader reader = cm.ExecuteReader();
reader.Read();
price = reader.GetInt16(0);
}
catch(Exception e) {
throw new Exception(e.Message);
}
}
return price;
}
However the exception returns the "specified method is not supported", not sure which method.
What am i getting wrong?
I've developed a simple system in C# MVC pattern, in model controller I have a list of employees. When the form loads, I want to add the list of employees to the textbox and user can filter the employee details by entering code and name of the employee. Now I don't know how to add employee list value to textbox auto complete customer source, please help..
Model controller
public List<Employee> Findlist()
{
List<Employee> emp = new List<Employee>();
string query = "select RTRIM(code) as [Code],RTRIM(name) as [Name] from m_Employee";
SqlCommand cmd = new SqlCommand(query);
cmd.Connection = con;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Employee e = new Employee();
e.code = dr["code"].ToString();
e.name = dr["name"].ToString();
emp.Add(e);
}
dr.Close();
return emp;
}
Controller
public List<Employee> SearchEmp()
{
EmployeeModel md = new EmployeeModel();
return md.Findlist();
}
View
private void FrmEmployeeSearchBar_Load(object sender, EventArgs e)
{
try
{
LoginControll lc = new LoginControll();
List<Employee> emp = new List<Employee>();
emp = lc.SearchEmp();
AutoCompleteStringCollection collection = new AutoCompleteStringCollection();
textBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
for (int i = 0; i < emp.Count; i++)
{
string result = Convert.ToString(emp[i].name);
//collection.Add(emp[i].code);
collection.Add(result);
}
textBox1.AutoCompleteCustomSource = collection;
//txtAutocompletesearcbar.au
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
}
}
Add the following lines
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
before
textBox1.AutoCompleteCustomSource = collection;