MySQL error in C# structure - c#

I'm having some problem with MySQL on a program. I'm not professional with it.
Error message:
"MySql.Data.MySqlClient.MySqlException: There is already an open DataReader associated with this Connection which must be closed first.
at System.Void MySql.Data.MySqlClient.MySqlCommand.CheckState()
at MySqlDataReader MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(System.Data.CommandBehavior behavior)
at MySqlDataReader MySql.Data.MySqlClient.MySqlCommand.ExecuteReader()"
The code is below:
public static class MySQL
{
private static string strConnection;
static void dbConnection_StateChange(object sender, StateChangeEventArgs ev)
{
if (ev.CurrentState == ConnectionState.Broken)
{
System.Threading.Thread.Sleep(1000);
dbConnection.Close();
}
if (ev.CurrentState == ConnectionState.Closed)
{
System.Threading.Thread.Sleep(1000);
dbConnection = new MySqlConnection(strConnection);
dbConnection.StateChange += new System.Data.StateChangeEventHandler(dbConnection_StateChange);
System.Threading.Thread.Sleep(1000);
dbConnection.Open();
}
}
private static MySqlConnection dbConnection;
public static bool openConnection(string dbHost, int dbPort, string dbName, string dbUsername, string dbPassword)
{
try
{
strConnection = "server=" + dbHost + ";" + "database=" + dbName + ";" + "uid=" + dbUsername + ";" + "password=" + dbPassword;
dbConnection = new MySqlConnection(strConnection);
dbConnection.StateChange += new System.Data.StateChangeEventHandler(dbConnection_StateChange);
dbConnection.Open();
Console.WriteLine(" Connected to MySQL.");
return true;
}
catch (Exception ex)
{
Console.WriteLine(" Couldn't connect to MySQL! The error:");
Console.WriteLine(ex.Message);
return false;
}
}
public static void closeConnection()
{
try
{
dbConnection.Close();
}
catch
{
Console.WriteLine("tasdsdaa fodaa");
}
}
public static void checkConnection()
{
try
{
if (dbConnection.State != ConnectionState.Open)
{
closeConnection();
openConnection(Config.dbHost, Config.dbPort, Config.dbName, Config.dbUsername, Config.dbPassword);
}
}
catch {
Console.WriteLine("ta fodaa");
}
}
public static void runQuery(string Query)
{
checkConnection();
try { new MySqlCommand(Query, dbConnection).ExecuteScalar(); }
catch { }
}
public static int insertGetLast(string Query)
{
checkConnection();
return int.Parse((new MySqlCommand(Query + "; SELECT LAST_INSERT_ID();", dbConnection).ExecuteScalar()).ToString());
}
public static string runRead(string Query)
{
checkConnection();
try { return new MySqlCommand(Query + " LIMIT 1", dbConnection).ExecuteScalar().ToString(); }
catch
{
return "";
}
}
public static int runRead(string Query, object Tick)
{
checkConnection();
try { return Convert.ToInt32(new MySqlCommand(Query + " LIMIT 1", dbConnection).ExecuteScalar()); }
catch
{
return 0;
}
}
public static string[] runReadColumn(string Query, int maxResults)
{
checkConnection();
MySqlCommand Command = null;
MySqlDataReader Reader = null;
if (maxResults > 0)
Query += " LIMIT " + maxResults;
try
{
Command = dbConnection.CreateCommand();
Command.CommandText = Query;
Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
ArrayList columnBuilder = new ArrayList();
while (Reader.Read())
{
try { columnBuilder.Add(Reader[0].ToString()); }
catch { columnBuilder.Add(""); }
}
return (string[])columnBuilder.ToArray(typeof(string));
}
else
{
return new string[0];
}
}
catch(MySqlException Ex)
{
if (Command != null)
{
Console.WriteLine("[MySQL] Error!\n\r" + Command.CommandText, Ex);
}
else
{
Console.WriteLine("[MySQL] Error!", Ex);
}
}
finally
{
// Close the reader/command if they are active.
if (Reader != null)
{
Reader.Close();
Reader.Dispose();
}
if (Command != null)
{
Command.Dispose();
}
}
return new string[0];
}
public static int[] runReadColumn(string Query, int maxResults, object Tick)
{
checkConnection();
MySqlCommand Command = null;
MySqlDataReader Reader = null;
if (maxResults > 0)
Query += " LIMIT " + maxResults;
try
{
Command = dbConnection.CreateCommand();
Command.CommandText = Query;
Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
ArrayList columnBuilder = new ArrayList();
while (Reader.Read())
{
try { columnBuilder.Add(Reader.GetInt32(0)); }
catch { columnBuilder.Add(0); }
}
return (int[])columnBuilder.ToArray(typeof(int));
}
else
{
return new int[0];
}
}
catch (MySqlException Ex)
{
if (Command != null)
{
Console.WriteLine("[MySQL] Error!\n\r" + Command.CommandText, Ex);
}
else
{
Console.WriteLine("[MySQL] Error!", Ex);
}
}
finally
{
// Close the reader/command if they are active.
if (Reader != null)
{
Reader.Close();
Reader.Dispose();
}
if (Command != null)
{
Command.Dispose();
}
}
return new int[0];
}
public static string[] runReadRow(string Query)
{
checkConnection();
MySqlCommand Command = null;
MySqlDataReader Reader = null;
try
{
Command = dbConnection.CreateCommand();
Command.CommandText = Query + " LIMIT 1";
Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
ArrayList rowBuilder = new ArrayList();
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
{
try { rowBuilder.Add(Reader[i].ToString()); }
catch { rowBuilder.Add(""); }
}
}
return (string[])rowBuilder.ToArray(typeof(string));
}
else
{
return new string[0];
}
}
catch (MySqlException Ex)
{
if (Command != null)
{
Console.WriteLine("[MySQL] Error!\n\r" + Command.CommandText, Ex);
}
else
{
Console.WriteLine("[MySQL] Error!", Ex);
}
}
finally
{
// Close the reader/command if they are active.
if (Reader != null)
{
Reader.Close();
Reader.Dispose();
}
if (Command != null)
{
Command.Dispose();
}
}
return new string[0];
}
public static int[] runReadRow(string Query, object Tick)
{
checkConnection();
MySqlCommand Command = null;
MySqlDataReader Reader = null;
try
{
Command = dbConnection.CreateCommand();
Command.CommandText = Query + " LIMIT 1";
Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
ArrayList rowBuilder = new ArrayList();
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
{
try { rowBuilder.Add(Reader.GetInt32(i)); }
catch { rowBuilder.Add(0); }
}
}
return (int[])rowBuilder.ToArray(typeof(int));
}
else
{
return new int[0];
}
}
catch (MySqlException Ex)
{
if (Command != null)
{
Console.WriteLine("[MySQL] Error!\n\r" + Command.CommandText, Ex);
}
else
{
Console.WriteLine("[MySQL] Error!", Ex);
}
}
finally
{
// Close the reader/command if they are active.
if (Reader != null)
{
Reader.Close();
Reader.Dispose();
}
if (Command != null)
{
Command.Dispose();
}
}
return new int[0];
}
public static bool checkExists(string Query)
{
checkConnection();
try { return new MySqlCommand(Query + " LIMIT 1", dbConnection).ExecuteReader().HasRows; }
catch
{
return false;
}
}
public static List<List<string>> readArray(string Query)
{
MySqlCommand Command = null;
MySqlDataReader Reader = null;
try
{
// Create the command.
Command = MySQL.dbConnection.CreateCommand();
Command.CommandText = Query;
// Read the result.
Reader = Command.ExecuteReader();
// Store the incomming fields.
List<List<string>> fieldValues = new List<List<string>>();
// Read all the data.
while (Reader.Read())
{
// Create a new field values to hold the data.
List<string> Buffer = new List<string>();
// Add the field values.
for (int i = 0; i < Reader.FieldCount; i++)
{
Buffer.Add(Reader[i].ToString());
}
// Add it too our overall data.
fieldValues.Add(Buffer);
}
return fieldValues;
}
catch (MySqlException Ex)
{
if (Command != null)
{
Console.WriteLine("[MySQL] Error!\n\r" + Command.CommandText, Ex);
}
else
{
Console.WriteLine("[MySQL] Error!", Ex);
}
return null;
}
finally
{
// Close the reader/command if they are active.
if (Reader != null)
{
Reader.Close();
Reader.Dispose();
}
if (Command != null)
{
Command.Dispose();
}
}
}
public static string Stripslash(string Query)
{
try { return Query.Replace(#"\", "\\").Replace("'", #"\'"); }
catch { return ""; }
}
}

You need to call Close on your Reader objects to release the underline resources, something like this:
try
{
Command = dbConnection.CreateCommand();
Command.CommandText = Query;
using (Reader = Command.ExecuteReader()) // 'using' forces a call to `Dispose`/`Close` at the end of the block
{
if (Reader.HasRows)
{
ArrayList columnBuilder = new ArrayList();
while (Reader.Read())
{
try { columnBuilder.Add(Reader.GetInt32(0)); }
catch { columnBuilder.Add(0); }
}
return (int[])columnBuilder.ToArray(typeof(int));
}
else
{
return new int[0];
}
}
}

an obvious issue to me is here:
public static bool checkExists(string Query)
{
checkConnection();
try { return new MySqlCommand(Query + " LIMIT 1", dbConnection).ExecuteReader().HasRows; }
catch
{
return false;
}
}
You aren't closing the reader here, LEAK.

Related

How to load in data from database to listbox

My program can load in the listbox headers, but not the actually data from the whole table.
(how I am connecting to the database):
const string connectionString = "Data Source=test;Initial Catalog=dbi391731;User ID=test;Password=test";
SqlConnection conn = new SqlConnection(connectionString);
I'm using a class to load in the data:
public List<ScoreMdw> GetScoreMdwList()
{
List<ScoreMdw> scoremdwList = new List<ScoreMdw>();
conn.Open();
string query = ("Select employeeid, questionid, score from contentment");
SqlCommand cmd = new SqlCommand(query, conn);
try
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch (Exception ex)
{
Exception error = new Exception("error", ex);
throw error;
}
finally
{
conn.Close();
}
return scoremdwList;
}
In the while loop I'm using an other class:
class ScoreMdw
{
private int employeeid;
private int questionid;
private char score;
public ScoreMdw(int nr, int id, char s)
{
this.employeeid= nr;
this.questionid= id;
this.score = s;
}
public int EmployeeId
{
get { return employeeid; }
}
public int QuestionId
{
get { return questionid; }
}
public char Score
{
get { return score; }
}
public override string ToString()
{
string s = string.Format("{0} \t{1} \t{2}", this.employeeid, this.questionid, this.score);
return s;
}
}
In my main window I'm doing this:
private void btnLoadScores_Click(object sender, RoutedEventArgs e)
{
scoremdwList = new List<ScoreMdw>();
try
{
conn.Open();
List<string> headers = so.GetContentmentHeaders();
foreach (string header in headers)
txtHeader.Text += header + "\t";
scoremdwList = so.GetScoreMdwList();
lbScores.ItemsSource = scoremdwList;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
}
I get the error that I made in the class ("error"). I don't know what I'm doing wrong? Maybe something with the connection? Am I opening and closing it the wrong way?
May i ask you, to show us the ex.Message? So we know what the possible error could be.
try
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
while(dr.read())
{
ScoreMdw sm = new ScoreMdw((int)dr["employeeid"], (int)dr["questionid"], (char)dr["score"]);
scoremdwList.Add(sm);
}
}
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message); // <= here you will get you errormessage that is important to fix your error.
Exception error = new Exception("error", ex);
throw error;
}

Make a dynamic sqlite table creating and inserting function

I have around 8-9 functions for filling tables from SQL to Sqlite and I am trying to make a dynamic function on which I will just pass some params and it will create the sqlite table (if it doesn't exist), create multiple instances in a loop of the type I want to insert in the specific table, set the properties for it and then insert it. Here are example functions:
private bool ReloadItemsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillItem_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Item>();
while (reader.Read())
{
{
var newItem = new Item();
newItem.ItemID = reader.GetInt32(0);
newItem.ItemBaseID = reader.GetInt32(1);
newItem.BrandID = reader.GetInt32(2);
newItem.Issue = reader.GetInt32(3);
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
and here's another one:
private bool ReloadContragentsFromServer()
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand("rsp_FillContragent_MobileDevice;", GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable<Contragent>();
while (reader.Read())
{
{
var newContragent = new Contragent();
newContragent.ContragentID = reader.GetInt32(0);
newContragent.ContragentTypeID = reader.GetInt32(1);
newContragent.ContragentGroupID = reader.GetInt32(2);
newContragent.FullName = reader.GetString(3);
newContragent.BULSTAT = reader.GetString(4);
newContragent.ItemPriceGroupID = reader.GetInt32(5);
newContragent.ItemDiscountGroupID = reader.GetInt32(6);
sqliteConn.Insert(newContragent);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForContragentFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
You can see what's different. How can I make it so I just call one method and give it some params so i dont have 8-9 blocks of code which are somewhat repeating?
I currently have this as a dynamic function (unfinished):
private bool LoadDataFromServer(string procedure, Type passedType)
{
try
{
using (GS.cnn)
{
SqlCommand command = new SqlCommand(procedure, GS.cnn);
command.CommandType = System.Data.CommandType.StoredProcedure;
GS.cnn.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
string dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DataBase.PremierAndroid");
using (var sqliteConn = new SQLiteConnection(dbPath))
{
sqliteConn.CreateTable(passedType);
while (reader.Read()) //to do > i++ bla bla
{
{
var newItem = Activator.CreateInstance(passedType);
//newItem - loop through properties and set = reader.get(int/string)(i)
sqliteConn.Insert(newItem);
}
}
}
}
else
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(Resources.GetString(Resource.String.NoRowsForItemFound));
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
reader.Close();
}
return true;
}
catch (Exception ex)
{
_dlgAlert = new AlertDialog.Builder(this).Create();
_dlgAlert.SetMessage(ex.Message);
_dlgAlert.SetTitle(Resources.GetString(Resource.String.Error));
_dlgAlert.SetButton("OK", delegate { });
_dlgAlert.Show();
return false;
}
finally
{
if (GS.cnn.State != ConnectionState.Closed)
{
GS.cnn.Close();
}
}
}
Thank you
let reflection and inherit help like this:
class Caller{
// see how it sends objects to method 'processAllClasses' with different classes
void main(){
ItemClass1 i1 = new ItemClass1();
i1.setItemsB(1,2);
processAllClasses(i1);
ItemClass2 i2 = new ItemClass2();
i2.setItemsB(10, 20);
processAllClasses(i2);
}
//using reflection and inherit to process different classes, obj is what need to be processed on.
//alternative way:
//get members from the type, then assign values to them one by one
void processAllClasses(ParentClass myobjvalue)
{
Type realtype = myobjvalue.GetType();
ParentClass myobj = new ParentClass();
MethodInfo mi = realtype.GetMethod("setItemsA");
object obj = Activator.CreateInstance(realtype);
Object[] parameter = new Object[] { myobjvalue };
mi.Invoke(obj, parameter);
}
}
class ParentClass {
}
class ItemClass1: ParentClass
{
int ItemID;
int ItemBaseID;
public void setItemsA(ItemClass1 itemclass1)
{
this.ItemID = itemclass1.ItemID;
this.ItemBaseID = itemclass1.ItemBaseID;
}
public void setItemsB(int ItemID, int ItemBaseID)
{
this.ItemID = ItemID;
this.ItemBaseID = ItemBaseID;
}
}
class ItemClass2 : ParentClass
{
int ContragentID;
int ContragentTypeID;
public void setItemsA(ItemClass2 itemclass2)
{
this.ContragentID = itemclass2.ContragentID;
this.ContragentTypeID = itemclass2.ContragentTypeID;
}
public void setItemsB(int ContragentID, int ContragentTypeID)
{
this.ContragentID = ContragentID;
this.ContragentTypeID = ContragentTypeID;
}
}

Select items in row on a created list

I am currently creating a list in the class ExpandWindow using a method in the class JobComponent. How would I access the JobDateTime in JobList from jobDetail and assign the value to DateTimeTextBlock?
Code below:
ExpandWindow.cs
public ExpandWindow(int jobId)
{
InitializeComponent();
List<JobComponent.JobList> jobDetail = JobComponent.SelectJobBooking(jobId);
}
JobComponent.cs
public static List<JobList> SelectJobBooking(int jobId)
{
const string query = "SELECT t1.datetime FROM booking t1 " +
"WHERE t1.id=#id";
var jobList = new List<JobList>();
using (var cmd = new MySqlCommand(query, DbObject.Connection))
{
if (DbObject.Connection.State != ConnectionState.Open)
{
DbObject.OpenConnection();
}
cmd.Parameters.AddWithValue(("#id"), jobId);
try
{
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
var item = new JobList
{
JobDateTime = dataReader["datetime"] + ""
};
jobList.Add(item);
}
dataReader.Close();
DbObject.CloseConnection();
return jobList;
}
}
catch (Exception ex)
{
ErrorHandlingComponent.LogError(ex.ToString());
throw;
}
}
}
Not exactly sure what you trying here, but think you will get idea how to get the JobDateTime.
public ExpandWindow(int jobId)
{
InitializeComponent();
List<JobComponent.JobList> jobDetail = JobComponent.SelectJobBooking(jobId);
if(jobDetail == null) return;
var item = jobDetail.FirstOrDefault();
if(item == null) return;
yourDatetimeControl.Value = item.JobDateTime;
}

Error adding usercontrol to winform

I am trying to add a usercontrol to my winform. When I try to do this I get an error:
I have tried to recreate both the form and usercontrol, but the error keeps showing up.
Really bothered with this because I can not continue my project this way..
How can I fix this?
Edit: I have used various different names for both the usercontrol and form. Also restarting Visual Studio did not help.
Edit2:
UcLeed Contains the following code:
public partial class ucLeed : UserControl
{
ErrorProvider error = new ErrorProvider();
DBLid DBlid = new DBLid();
public ucLeed()
{
InitializeComponent();
error.BlinkStyle = ErrorBlinkStyle.NeverBlink;
}
string lidID;
public string LidID
{
get { return lidID; }
set { lidID = value; }
}
public string Achternaam
{
get { return tbAchternaam.Text; }
set { tbAchternaam.Text = value; }
}
public string Adres
{
get { return tbStraat.Text; }
set { tbStraat.Text = value; }
}
public string Email
{
get { return tbEmail.Text; }
set { tbEmail.Text = value; }
}
public string Geboortedatum
{
get { return tbGeboortedatum.Text; }
set { tbGeboortedatum.Text = value; }
}
public string Gebruikersnaam
{
get { return tbGebruikersnaam.Text; }
set { tbGebruikersnaam.Text = value; }
}
public string Voornaam
{
get { return tbVoornaam.Text; }
set { tbVoornaam.Text = value; }
}
public string Wachtwoord
{
get { return tbPassword.Text; }
set { tbPassword.Text = value; }
}
public string BevWachtwoord
{
get { return tbPassBev.Text; }
set { tbPassBev.Text = value; }
}
public string Woonplaats
{
get { return tbWoonplaats.Text; }
set { tbWoonplaats.Text = value; }
}
public string Postcode
{
get { return tbPostcode.Text; }
set { tbPostcode.Text = value; }
}
private void CheckInput(CancelEventArgs e, TextBox tb)
{
if (string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, "*");
e.Cancel = true;
}
if (!string.IsNullOrEmpty(tb.Text))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
}
private void CheckIntInput(CancelEventArgs e, TextBox tb)
{
int integer;
if (int.TryParse(tb.Text, out integer))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
else
{
MessageBox.Show("Je moet een getal invullen!");
tb.Focus();
error.SetError(tb, "*");
}
}
private void CheckDateInput(CancelEventArgs e, TextBox tb)
{
string date = tb.Text;
DateTime fromDateValue;
var formats = new[] { "dd/MM/yyyy", "dd-MM-yyyy" };
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
error.SetError(tb, String.Empty);
error.Clear();
error.Dispose();
}
else
{
MessageBox.Show("Je moet wel een datum invullen!");
tb.Focus();
error.SetError(tb, "*");
}
}
private void ComparePasswords(CancelEventArgs e, MaskedTextBox tb, MaskedTextBox tb2)
{
if (tb.Text != tb2.Text)
{
MessageBox.Show("Je hebt niet het juiste wachtwoord bevestigd!");
error.SetError(tb2, "*");
}
else
{
error.SetError(tb2, String.Empty);
error.Clear();
error.Dispose();
}
}
private void tbVoornaam_Validating(object sender, CancelEventArgs e)
{
CheckInput(e, (TextBox)sender);
}
private void tbPassBev_Validating(object sender, CancelEventArgs e)
{
ComparePasswords(e, (MaskedTextBox)tbPassword, (MaskedTextBox)sender);
}
private void tbEmail_Validating(object sender, CancelEventArgs e)
{
try
{
var email = new MailAddress(tbEmail.Text);
error.SetError(tbEmail, String.Empty);
error.Clear();
error.Dispose();
}
catch
{
MessageBox.Show("Verkeerde formaat email adres!");
error.SetError(tbEmail, "*");
}
}
private void tbGeboortedatum_Validating(object sender, CancelEventArgs e)
{
CheckDateInput(e, (TextBox)sender);
}
private void tbGebruikersnaam_Validating(object sender, CancelEventArgs e)
{
if (DBlid.CheckLid(tbGebruikersnaam.Text))
{
MessageBox.Show("Gebruikersnaam al in gebruik!");
this.Focus();
error.SetError(tbGebruikersnaam, "*");
}
}
}
Edit3: The code of class DBLid.
class DBLid
{
DBChecks DBChecks = new DBChecks();
bool querystatus = false;
public bool Querystatus
{
get { return querystatus; }
set { querystatus = value; }
}
string connectionString = ConfigurationManager.ConnectionStrings["Insomnia.Properties.Settings.dbInsomniaConnectionString"].ConnectionString;
public DataTable GetLeden()
{
DataTable DT = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.CommandText = "SELECT Lid.Id, Lid.Achternaam, Lid.Voornaam, Lid.Email, Lid.Adres, Lid.Woonplaats, Lid.Postcode, convert(varchar, Lid.Geboortedatum, 101) AS 'Geboorte Datum', Lid.GebruikersNaam AS Gebruikersnaam FROM Lid";
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(DT);
return DT;
}
public bool CheckLid(string gebruikersnaam)
{
bool inUse = false;
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("gebruikersnaam", gebruikersnaam);
cmd.CommandText = "SELECT COUNT(Lid.ID) FROM Lid WHERE GebruikersNaam = #gebruikersnaam";
try
{
conn.Open();
if ((int)cmd.ExecuteScalar() == 1)
{
inUse = true;
}
else
{
inUse = false;
}
}
catch
{
}
finally
{
conn.Close();
}
return inUse;
}
public void AddLid(string achternaam, string adres, string email, string geboortedatum, string gebruikersnaam, string voornaam, string wachtwoord, string woonplaats, string postcode)
{
// Encrypt password
string encryptedPassword = DBChecks.encryptPassword(wachtwoord);
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection(connectionString);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("achternaam", achternaam);
cmd.Parameters.AddWithValue("adres", adres);
cmd.Parameters.AddWithValue("email", email);
cmd.Parameters.AddWithValue("geboortedatum", geboortedatum);
cmd.Parameters.AddWithValue("gebruikersnaam", gebruikersnaam);
cmd.Parameters.AddWithValue("voornaam", voornaam);
cmd.Parameters.AddWithValue("woonplaats", woonplaats);
cmd.Parameters.AddWithValue("postcode", postcode);
cmd.Parameters.AddWithValue("wachtwoord", encryptedPassword);
cmd.CommandText = "INSERT INTO Lid (Achternaam, Adres, Email, GeboorteDatum, GebruikersNaam, Voornaam, Wachtwoord, Woonplaats, Postcode) VALUES (#achternaam, #adres, #email, #geboortedatum, #gebruikersnaam, #voornaam, #wachtwoord, #woonplaats, #postcode); SELECT CONVERT(int, SCOPE_IDENTITY());";
try
{
conn.Open();
int lidID = (int)cmd.ExecuteScalar();
MessageBox.Show("Het lid is toegevoegd met LidID: " + lidID);
querystatus = true;
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
querystatus = false;
}
finally {
conn.Close();
}
}
}
Edit4: Added DBChecks for Reference.
class DBChecks
{
bool reserveerStatus;
public bool ReserveerStatus
{
get { return reserveerStatus; }
set { reserveerStatus = value; }
}
bool querystatus = false;
public bool QueryStatus
{
get { return querystatus; }
set { querystatus = value; }
}
int gameID;
public int GameID
{
get { return gameID; }
set { gameID = value; }
}
int boekID;
public int BoekID
{
get { return boekID; }
set { boekID = value; }
}
private int itemsoort;
public int Itemsoort
{
get { return itemsoort; }
set { itemsoort = value; }
}
string connectionString = ConfigurationManager.ConnectionStrings["Insomnia.Properties.Settings.dbInsomniaConnectionString"].ConnectionString;
public string encryptPassword(string uncryptedPassword)
{
HashAlgorithm hash = new SHA256Managed();
string salt = "UserName";
// compute hash of the password prefixing password with the salt
byte[] plainTextBytes = Encoding.UTF8.GetBytes(salt + uncryptedPassword);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string hashValue = Convert.ToBase64String(hashBytes);
return hashValue;
}
public bool ReserveringStatus(int itemID)
{
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
cmd.Connection = conn;
cmd.CommandText = "SELECT ReserveerStatus FROM Item WHERE Id = #itemID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
reserveerStatus = (bool)sdr["ReserveerStatus"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return reserveerStatus;
}
public int CheckLid(int lidID)
{
int aantal = 0;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("lidID", lidID);
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) AS Aantal FROM Lid WHERE Id = #lidID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
aantal = (int)sdr["Aantal"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return aantal;
}
public int CheckPas(int pasID)
{
int aantal = 0;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("pasID", pasID);
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT(*) AS Aantal FROM Pas WHERE Id = #pasID";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
aantal = (int)sdr["Aantal"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return aantal;
}
public void CheckSoort(int itemID)
{
// Variable declaration
string soort = "";
List<Boek> boek = new List<Boek>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
// Check if ItemID is boek or game
cmd.Parameters.AddWithValue("itemID", itemID);
cmd.Connection = conn;
cmd.CommandText = "SELECT Soort FROM Item WHERE ID = #itemID;";
// Retrieve data
// Try-catch-final to catch wrong itemID error
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
soort = sdr["Soort"].ToString();
}
if (soort == "Boek")
{
itemsoort = 1;
}
if (soort == "Game")
{
itemsoort = 2;
}
if (soort == "")
{
itemsoort = 3;
MessageBox.Show("Dit ID bestaat niet!");
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
}
public bool CheckStatus(int itemID)
{
// Variables
bool itemStatus = true;
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Method
cmd.Connection = conn;
cmd.CommandText = "SELECT Status FROM Item WHERE Item.Id = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
itemStatus = (bool)sdr["Status"];
}
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return itemStatus;
}
public List<Game> ShowGame(int itemID)
{
// Variable declaration
List<Game> gameList = new List<Game>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Retrieve data
cmd.Connection = conn;
cmd.CommandText = "SELECT Game.*, Item.*, convert(varchar, Item.DvU, 101) AS DatumVUitgave, Platform.Soort as Platform, Media.soort as Media, GameGenre.Genre AS Genre FROM Game LEFT JOIN ITEM ON Item.ID = Game.itemID LEFT JOIN Media ON Game.MediaID = Media.Id LEFT JOIN Platform ON Game.PlatformID = Platform.Id LEFT JOIN GameGenre ON Game.GameGenreID = GameGenre.Id WHERE Game.itemID = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
gameList.Add(new Game() { Titel = sdr["Titel"].ToString(), Dvu = sdr["DatumVUitgave"].ToString(), Genre = sdr["Genre"].ToString(), Media = sdr["Media"].ToString(), Pegi = sdr["PEGI"].ToString(), Platform = sdr["Platform"].ToString(), EAN = sdr["EAN"].ToString(), Uitgever = sdr["Uitgever"].ToString() });
}
}
catch (FormatException e)
{
MessageBox.Show(e.Message);
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return gameList;
}
public List<Boek> ShowBoek(int itemID)
{
// Variable declaration
List<Boek> boekList = new List<Boek>();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("itemID", itemID);
// Retrieve data
cmd.Connection = conn;
cmd.CommandText = "SELECT Boek.*, Item.*, convert(varchar, Item.DvU, 101) AS DatumVUitgave, Auteur.Auteur AS Auteur, BoekGenre.Genre AS Genre, Bindwijze.Soort as Bindwijze, Taal.Taal AS Taal FROM Boek LEFT JOIN Item ON Boek.ItemID = Item.Id LEFT JOIN Bindwijze ON Boek.BindwijzeID = Bindwijze.ID LEFT JOIN BoekGenre ON Boek.BoekGenreID = BoekGenre.Id LEFT JOIN Auteur on Boek.AuteurID = Auteur.Id LEFT JOIN Taal ON Boek.TaalID = Taal.Id WHERE Boek.ItemID = #itemID;";
try
{
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
// Fill boek with retrieved item(s)
boekList.Add(new Boek() { Auteur = sdr["Auteur"].ToString(), Genre = sdr["Genre"].ToString(), Dvu = sdr["DatumVUitgave"].ToString(), ISBN101 = sdr["ISBN10"].ToString(), ISBN131 = sdr["ISBN13"].ToString(), Paginas = sdr["AantalPagina"].ToString(), Taal = sdr["Taal"].ToString(), Titel = sdr["Titel"].ToString(), Bindwijze = sdr["Bindwijze"].ToString(), Uitgever = sdr["Uitgever"].ToString() });
}
}
catch (FormatException e)
{
MessageBox.Show(e.Message);
}
catch
{
MessageBox.Show("Oeps! Er ging iets mis!");
}
finally
{
conn.Close();
}
return boekList;
}
}
Try changing string lidID; to string lidID = ""; and probably bool reserveerStatus; to bool reserveerStatus = false;
Ok, I still do not know how or why; but if I remove the code from ucLeed, I can drag and drop the control onto my form.
Not sure how or why, but that is something I will try to figure out!

In the name the owner of a procedure must be specified - sql

I wrote C# code which returns a DataTable. All parameters i.e. Connection, sQuery have proper values.
Still I am getting an error:
In the name the owner of a procedure must be specified, this improves performance
I googled it but found nothing.
This is my code:
public static DataTable getATM(ref SqlConnection Connection)
{
DataTable dtReturn;
string sQuery = "";
try
{
sQuery = "Select ATM From ATM Where Bank=1";
using (SqlStoredProcedure sspObj = new SqlStoredProcedure(sQuery, Connection, CommandType.Text))
{
dtReturn = sspObj.ExecuteDataTable();
sspObj.Dispose();
}
}
catch (Exception xObj)
{
dtReturn = new DataTable();
}
return dtReturn;
}
SqlStoredProcedure.cs:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Diagnostics;
namespace ReflectionIT.Common.Data.SqlClient {
public class SqlStoredProcedure : IDisposable {
public static readonly TraceSource TraceSource = new TraceSource("SqlStoredProcedure");
private static int _eventId = 0;
private const string _returnValue = "ReturnValue";
private SqlCommand _command;
private bool _connectionOpened = false;
public SqlStoredProcedure(string name, SqlConnection connection, CommandType comtype)
: this(name, connection, null, comtype) {
}
public SqlStoredProcedure(string name, SqlConnection connection, SqlTransaction transaction, CommandType comtype) {
if (name.IndexOf('.') == -1) {
throw new ArithmeticException("In the name the owner of a procedure must be specified, this improves performance");
}
_command = new SqlCommand(name, connection, transaction);
_command.CommandTimeout = 0;
_command.CommandType = comtype;
AddReturnValue();
}
public void Dispose() {
if (_command != null) {
_command.Dispose();
_command = null;
}
}
virtual public string Name {
get { return _command.CommandText; }
set { _command.CommandText = value; }
}
virtual public int Timeout {
get { return _command.CommandTimeout; }
set { _command.CommandTimeout = value; }
}
virtual public SqlCommand Command {
get { return _command; }
}
virtual public SqlConnection Connection {
get { return _command.Connection; }
set { _command.Connection = value; }
}
virtual public SqlTransaction Transaction {
get { return _command.Transaction; }
set { _command.Transaction = value; }
}
virtual public SqlParameterCollection Parameters {
get { return _command.Parameters; }
}
virtual public int ReturnValue {
get { return (int)_command.Parameters[_returnValue].Value; }
}
virtual public SqlParameter AddParameter(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction) {
SqlParameter p;
if (size > 0) {
p = new SqlParameter(parameterName, dbType, size);
} else {
// size is automacally detected using dbType
p = new SqlParameter(parameterName, dbType);
}
p.Direction = direction;
Parameters.Add(p);
return p;
}
virtual public SqlParameter AddParameterWithValue(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction,
object value) {
SqlParameter p = this.AddParameter(parameterName, dbType, size, direction);
if (value == null) {
value = DBNull.Value;
}
p.Value = value;
return p;
}
virtual public SqlParameter AddParameterWithStringValue(string parameterName,
SqlDbType dbType,
int size,
ParameterDirection direction,
string value,
bool emptyIsDBNull) {
SqlParameter p = this.AddParameter(parameterName, dbType, size, direction);
if (value == null) {
p.Value = DBNull.Value;
} else {
value = value.TrimEnd(' ');
if (emptyIsDBNull && value.Length == 0) {
p.Value = DBNull.Value;
} else {
p.Value = value;
}
}
return p;
}
virtual protected SqlParameter AddReturnValue() {
SqlParameter p = Parameters.Add(
new SqlParameter(_returnValue,
SqlDbType.Int,
/* int size */ 4,
ParameterDirection.ReturnValue,
/* bool isNullable */ false,
/* byte precision */ 0,
/* byte scale */ 0,
/* string srcColumn */ string.Empty,
DataRowVersion.Default,
/* value */ null));
return p;
}
virtual public int ExecuteNonQuery() {
int rowsAffected = -1;
try {
Prepare("ExecuteNonQuery");
rowsAffected = _command.ExecuteNonQuery();
TraceResult("RowsAffected = " + rowsAffected.ToString());
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return rowsAffected;
}
virtual public SqlDataReader ExecuteReader() {
SqlDataReader reader;
try {
Prepare("ExecuteReader");
reader = _command.ExecuteReader();
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public SqlDataReader ExecuteReader(CommandBehavior behavior) {
SqlDataReader reader;
try {
Prepare("ExecuteReader");
reader = _command.ExecuteReader(behavior);
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public object ExecuteScalar() {
object val = null;
try {
Prepare("ExecuteScalar");
val = _command.ExecuteScalar();
TraceResult("Scalar Value = " + Convert.ToString(val));
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return val;
}
virtual public XmlReader ExecuteXmlReader() {
XmlReader reader;
try {
Prepare("ExecuteXmlReader");
reader = _command.ExecuteXmlReader();
TraceResult(null);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return reader;
}
virtual public DataSet ExecuteDataSet() {
DataSet dataset = new DataSet();
this.ExecuteDataSet(dataset);
return dataset;
}
virtual public DataSet ExecuteDataSet(DataSet dataSet) {
try {
Prepare("ExecuteDataSet");
SqlDataAdapter a = new SqlDataAdapter(this.Command);
a.Fill(dataSet);
TraceResult("# Tables in DataSet = " + dataSet.Tables.Count);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return dataSet;
}
virtual public DataTable ExecuteDataTable() {
DataTable dt = null;
try {
Prepare("ExecuteDataTable");
SqlDataAdapter a = new SqlDataAdapter(this.Command);
dt = new DataTable();
a.Fill(dt);
TraceResult("# Rows in DataTable = " + dt.Rows.Count);
} catch (SqlException e) {
throw TranslateException(e);
} finally {
CloseOpenedConnection();
}
return dt;
}
protected Exception TranslateException(SqlException ex) {
Exception dalException = null;
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Error, _eventId, "{0} throwed exception: {1}", this.Name, ex.ToString());
foreach (SqlError error in ex.Errors) {
if (error.Number >= 50000) {
dalException = new DalException(error.Message, ex);
}
}
if (dalException == null) {
switch (ex.Number) {
case 17:
case 4060:
case 18456:
dalException = new DalLoginException(ex.Message, ex);
break;
case 547:
dalException = new DalForeignKeyException(ex.Message, ex);
break;
case 1205:
dalException = new DalDeadLockException(ex.Message, ex);
break;
case 2627:
case 2601:
dalException = new DalUniqueConstraintException(ex.Message, ex);
break;
default:
dalException = new DalException(ex.Message, ex);
break;
}
}
return dalException;
}
protected void Prepare(string executeType) {
_eventId++;
if (_eventId > ushort.MaxValue) {
_eventId = 0;
}
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Information, _eventId, "{0}: {1}", executeType, this.Name);
TraceParameters(true);
if (_command.Connection.State != ConnectionState.Open) {
_command.Connection.Open();
_connectionOpened = true;
}
}
private void TraceParameters(bool input) {
if (SqlStoredProcedure.TraceSource.Switch.ShouldTrace(TraceEventType.Verbose) && this.Parameters.Count > 0) {
foreach (SqlParameter p in this.Parameters) {
bool isInput = p.Direction != ParameterDirection.ReturnValue && p.Direction != ParameterDirection.Output;
bool isOutput = p.Direction != ParameterDirection.Input;
if ((input && isInput) || (!input && isOutput)) {
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Verbose, _eventId, "SqlParamter: Name = {0}, Value = '{1}', Type = {2}, Size = {3}", p.ParameterName, p.Value, p.DbType, p.Size);
}
}
}
}
protected void CloseOpenedConnection() {
if ((_command.Connection.State == ConnectionState.Open) & _connectionOpened)
_command.Connection.Close();
}
protected void TraceResult(string result) {
if (result != null) {
SqlStoredProcedure.TraceSource.TraceEvent(TraceEventType.Verbose, _eventId, "Result: {0}", result);
}
TraceParameters(false);
}
}
}
SqlStoredProcedure() is checking that there is a dot in your stored procedure name and if there isn't throwing that exception, so prefix your stored procedure name with "dbo." or whatever it is e.g.:
dbo.myProcedureName
It improves performance in the sense that SQL doesn't have to search all the users to find the proc first.

Categories