specified method is not supported - c#

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?

Related

C# bool array index was outside the bounds of the array on declaration and initialization

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]

If the SELECT SQL Server value is null, the query takes 5 minutes C #

I have a very silly problem. I am doing a select, and I want that when the value comes null, return an empty string. When there is value in sql query, the query occurs all ok, but if there is nothing in the query, I have to give a sqlCommand.CommandTimeout greater than 300, and yet sometimes gives timeout. Have a solution for this?
public string TesteMetodo(string codPess)
{
var vp = new Classe.validaPessoa();
string _connection = vp.conString();
string query = String.Format("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = {0}", codPess);
try
{
using (var conn = new SqlConnection(_connection))
{
conn.Open();
using (var cmd = new SqlCommand(query, conn))
{
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRows)
return "";
return codPess;
}
}
}
You should probably validate in the UI and pass an integer.
You can combine the usings to a single block. A bit easier to read with fewer indents.
Always use parameters to make the query easier to write and avoid Sql Injection. I had to guess at the SqlDbType so, check your database for the actual type.
Don't open the connection until directly before the .Execute. Since you are only retrieving a single value you can use .ExecuteScalar. .ExecuteScalar returns an Object so must be converted to int.
public string TesteMetodo(string codPess)
{
int codPessNum = 0;
if (!Int32.TryParse(codPess, out codPessNum))
return "codPess is not a number";
var vp = new Classe.validaPessoa();
try
{
using (var conn = new SqlConnection(vp.conString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM teste cliente WHERE cod_pess = #cod_pess", conn))
{
cmd.Parameters.Add("#cod_pess", SqlDbType.Int).Value = codPessNum;
conn.Open();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
return "";
return codPess;
}
}
catch (Exception ex)
{
return ex.Message;
}
}

Why is this code throwing 'System.ArgumentOutOfRangeException' (SQlite)?

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;
}
}

C# How to Update/Change the specific letter/number of a string in database

I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID

ADO.NET ExecuteReader Returns No Results

I'm updating some old legacy code and I ran into a problem with the
SqlCommand.ExecuteReader() method. The problem is that it's not returning any
results. However, using SqlDataAdapter.Fill(), I get results back from the
database. What am I doing wrong? How can I get results back using the data
reader?
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
using (var sqlConnection = new SqlConnection(connectionString))
{
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.Text;
sqlCommand.CommandText = "SELECT * FROM MyTable WHERE ID = 1";
sqlConnection.Open();
// This code works.
//var dataTable = new DataTable();
//using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
//{
// sqlDataAdapter.Fill(dataTable);
//}
// This code is not working.
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
// This fails because the data reader has no results.
var id = sqlDataReader.GetInt32(0);
}
}
}
}
Could it be that there is no Int32 in your results ?
var id = sqlDataReader.GetInt32(0); // <-- this might not be an Int32
Either try:
var id = sqlDataReader.GetValue(0);
Or cast to the correct type (BIGINT for example is Int64), not sure without seeing your data.
Try this..
var id = 0;
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
id = sqlDataReader.GetInt32(sqlDataReader.GetOrdinal("ColName"));
}
}
I have moved the variable outside of the reader code or the variable will only be accessible inside that scope. I would avoid specifying the ordinal in the code, in case someone altered the columns in the DB.
Also, specify the columns in the SQL statement... SELECT ColName FROM ... and use params in the query
If you got to that line then it has results
Does not mean the value is not null
And you should not use a SELECT *
If may have a problem with an implicit cast
Try Int32
try
{
if(sqlDataReader.IsDBNull(0))
{
// deal with null
}
else
{
Int32 id = sqlDataReader.GetInt32(0);
}
}
catch (SQLexception Ex)
{
Debug.WriteLine(Ex.message);
}
var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();
using (var sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
string sql = "SELECT * FROM MyTable WHERE ID = 1";
using (var sqlCommand = new SqlCommand(sql, sqlConnection))
{
using (var sqlDataReader = sqlCommand.ExecuteReader())
{
while (sqlDataReader.Read())
{
// This fails because the data reader has no results.
var id = sqlDataReader.GetInt32(0);
}
}
}
}

Categories