How to prevent Sqlite Database is locked? - c#

i got one thread reading on the database. When i click on the menustrip it shows an error "Database is locked." and it only happen sometimes. Any way to prevent the database lock? I have try WAL but its not working.
Reading:
private void checkPort(string ipIN, char[] input, string output)
{
try
{
bool building = false;
Thread beep = new Thread(Beep);
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string query = "select * from ALL_IO(nolock)";
using (SQLiteCommand cmd = new SQLiteCommand(query, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
int Contact;
while (dr.Read())
{
string _IP = dr.GetString(0);
string _IO_I = dr.GetString(1);
string _BuildingName = dr.GetString(4);
int IO_I = Convert.ToInt32(dr.GetString(1).Replace("DI ", ""));
if (dr.GetString(3) == "NC")
{
Contact = 1;
}
else
{
Contact = 0;
}
_tableName = dr.GetString(8);
string _name = dr.GetString(5);
var _active = dr.GetString(6);
var _status = dr.GetString(7);
if (_active == "Yes" && _status == "Enable")
{
//Some condition check here
}
}
catch { }
}
Writing:
void contexMenuuu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
data = "";
ToolStripItem item = e.ClickedItem;
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
c.Open();
string sql = "select * from " + Properties.Settings.Default.TableName + "(nolock) where Name= '" + Properties.Settings.Default.LabelName.Replace(" DO", "") + "' ";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
_controllerIP = dr.GetString(0);
_IO = dr.GetString(1);
_IO_O = dr.GetString(2).Replace("DO ", "");
_Name = dr.GetString(4);
_Interval = Convert.ToInt32(dr.GetString(9));
}
}
}
}
if (item.Text == "Bypass Enable")
{
using (SQLiteConnection c = new SQLiteConnection(dbconnection))
{
//c.DefaultTimeout = 2000;
c.Open();
string sql = "update ALL_IO SET Active='Yes', Status='Bypass' where ControllerIP='" + _controllerIP + "' and DI='" + _IO + "';";
using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
{
lock (lockobj)
{
//SQLiteConnection.ClearAllPools();
cmd.ExecuteNonQuery(); //Error occur here
}
}
}
}

Once the functionality is finished you must close the Database connect for avoid database lock issue. For executing the query you opened the database connection after that you didn't close it. so you need to close.

Related

How to Display Username in the homepage using ASP MVC

How to Display the User Id in my Homepage in ASP MVC. I don't know what is the problem. May I know what are the cause the userId
This is the part of Dashboard
protected void Page_Load(object sender, EventArgs e)
{
string sUserInfo = System.Environment.UserName;
string constr = "Data Source=MyDatabase;Database=test;User Id=username;Password=add3" ;
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("Select SystemName from tbl_SYS_Users where UserId='" + sUserInfo + "'");
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
string tempa = "";
while (sdr.Read())
{
tempa += sdr["SystemName"].ToString();
}
lblUserID.Text = Utilities.GetUserInfo(tempa);
}
This is for the Utilities in AppData Folder
public static string GetUserInfo(string sSystem)
{
sSystem = sSystem.ToUpper();
string sUserInfo = System.Environment.UserName;
if (SetConfigs()) //Check config file first
{
//Get userinfo from db server
if (sSystem != "HOME")
{
string sQry = "Select * from tbl_SYS_Users where SystemName = '" + sSystem + "' AND UserId='" + sUserInfo + "'";
using (DataTable dsTable = SQL_Query(Globals.sSQLCS_FNS, sQry, true, false))
{
if (dsTable == null)
{
sUserInfo += " - Unknown User!a";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
if (dsTable.Rows.Count == 0) //ID not found!
{
sUserInfo += " - Unknown User!";
Globals.UserID = null;
Globals.UserAccess = "";
Globals.UserName = null;
}
else
{
sUserInfo += " - " + dsTable.Rows[0]["Username"];
Globals.UserID = dsTable.Rows[0]["UserId"].ToString().Trim();
Globals.UserName = dsTable.Rows[0]["Username"].ToString().Trim();
}
}
}
}
}
else if (sSystem != "HOME")
sUserInfo += " - Unknown User!s";
return sUserInfo; // return to lblUserID.Text in the homepage
}
This image is the homepage
This is the database
I Want to display the Username in my Homepage
inject usermanager in to the view and add this
#UserManager.GetUserAsync(User).Result.UserName
What is the scope of Globals class? It seems when page loads class object initialized and all becomes empty. Declare Globals class as static (If not).

WPF disable rows duplicate in Datagrid using foreach loop

I want to check each row in unbound datagrid if cell value equal textbox value then dont add the row
using foreach loop
the problem now is that iam using unbound datagrid and cannot use the ItemSource in the foreach loop
and if i run the code below i got error :
System.InvalidCastException: 'Unable to cast object of type 'MyMasrof' to type 'System.Data.DataRow'.'
here is my code :
private void AddMaterial_btn_Click(object sender, RoutedEventArgs e)
{
if (Materials_Lookup.Text == null)
{
MessageBox.Show("Choose Item First");
}
else
{
if (Masrof_Grid.Items.Count > 0)
{
foreach (System.Data.DataRow dr in Masrof_Grid.Items)
{
if (dr["Masrof_Material_Name"].ToString() == StoreName_txt.Text)
{
MessageBox.Show("Item Already Exist");
}
else
{
MySqlConnection conn2 = new MySqlConnection("DataSource='" + DoSomething.Server_Param + "';UserID='" + DoSomething.Uid_Param + "';Password='" + DoSomething.Password_Param + "';Database='" + DoSomething.Database_Param + "';PORT=3306;CHARSET=utf8");
conn2.Open();
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader rd;
DataSet ds = new DataSet();
ds.Clear();
cmd.Connection = conn2;
cmd.CommandText = "SELECT id FROM Items where Item_Arabic_Name ='" + Materials_Lookup.Text + "'";
rd = cmd.ExecuteReader();
if (rd.Read())
{
Masrof_Grid.Items.Add(new MyMasrof()
{
Masrof_Material_Code = (rd["id"].ToString()),
Masrof_Material_Name = Materials_Lookup.Text,
Masrof_MAterial_QTY = QTY_txt.Text,
Masrof_Material_Store = StoreName_txt.Text,
MAterial_Curr_Balance = CurrBalance_txt.Text
});
}
else
{
MessageBox.Show("Cannot be found");
}
conn2.Close();
}
}
}
else
{
MySqlConnection conn2 = new MySqlConnection("DataSource='" + DoSomething.Server_Param + "';UserID='" + DoSomething.Uid_Param + "';Password='" + DoSomething.Password_Param + "';Database='" + DoSomething.Database_Param + "';PORT=3306;CHARSET=utf8");
conn2.Open();
MySqlCommand cmd = new MySqlCommand();
MySqlDataReader rd;
DataSet ds = new DataSet();
ds.Clear();
cmd.Connection = conn2;
cmd.CommandText = "SELECT id FROM Items where Item_Arabic_Name ='" + Materials_Lookup.Text + "'";
rd = cmd.ExecuteReader();
if (rd.Read())
{
Masrof_Grid.Items.Add(new MyMasrof()
{
Masrof_Material_Code = (rd["id"].ToString()),
Masrof_Material_Name = Materials_Lookup.Text,
Masrof_MAterial_QTY = QTY_txt.Text,
Masrof_Material_Store = StoreName_txt.Text,
MAterial_Curr_Balance = CurrBalance_txt.Text
});
// decimal sum = 0m;
// for (int i = 0; i < Masrof_Grid.Items.Count; i++)
// {
// sum += (decimal.Parse((Masrof_Grid.Columns[7].GetCellContent(Masrof_Grid.Items[i]) as TextBlock).Text));
// }
//// txtSumReal.Text = sum.ToString();
}
else
{
MessageBox.Show("cannot be found");
}
conn2.Close();
}
}
}

Login form with SQLite in C#

I'm having a problem making a loginform with sqlite in C#. this is the code
SQLiteConnection connectionstring;
connectionstring = " Data Source = C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db; Version = 3 ";
public void LoadData()
{
try
{
SQLiteCommand SelectCommand = new SQLiteCommand("SELECT `Username`, `Password` FROM `LoginData` WHERE `Username` = '" + flatTextBox1.Text + "' AND `Password` = '" + flatTextBox2.Text + "'", connectionstring);
SQLiteDataReader myReader;
connectionstring.Open();
myReader = SelectCommand.ExecuteReader();
int count = 0;
while (myReader.Read())
{
count = count + 1;
}
if (count == 1)
{
Base bs = new Base();
bs.Show();
this.Hide();
connectionstring.Close();
}
else if (count == 0)
{
flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
flatAlertBox1.Text = "data not right";
connectionstring.Close();
}
else
{
}
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
connectionstring.Close();
}
}
it is showing error in this line of code
connectionstring = " Data Source = C:\\Crystal Management\\Crystal Management\bin\\Debug\\Konaku.db; Version = 3 ";
message error is : Cannot implicitly convert type 'string' to 'Finisar.SQLite.SQLiteConnection'
what can I do with this?
This is the proper way to query SQL. Always use "using" for disposable class like SQLiteConnection, SQLiteCommand, and SQLiteDataReader. Use parameterized queries to avoid sql injection.
public void LoadData()
{
try
{
using (var conn = new SQLiteConnection(#"Data Source=C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db;Version=3"))
{
conn.Open();
using (var cmd = new SQLiteCommand("SELECT Username,Password FROM LoginData WHERE Username='#username' AND Password = '#password'", conn))
{
cmd.Parameters.AddWithValue("#username", flatTextBox1.Text);
cmd.Parameters.AddWithValue("#password", flatTextBox2.Text);
using (var reader = cmd.ExecuteReader())
{
var count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
Base bs = new Base();
bs.Show();
Hide();
}
else if (count == 0)
{
flatAlertBox1.kind = FlatUI.FlatAlertBox._Kind.Error;
flatAlertBox1.Text = "data not right";
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It should be like this
sql_con = new SQLiteConnection
("Data Source=C:\Crystal Management\Crystal Management\bin\Debug\Konaku.db;Version=3;New=False;Compress=True;");

Nothing happens on query execution

I have this simple code C# and SQL Server database:
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
// here like cursor stop
cm2.ExecuteNonQuery();
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
I have run it but nothing happens on query execution I used MessageBox like that to identify the line that has the problem
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
SqlCommand cm2 = new SqlCommand();
cm2.Connection = cn;
MessageBox.Show("1");
cm2.CommandText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
MessageBox.Show("2");
cm2.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
MessageBox.Show("3");
// here cursor stops
cm2.ExecuteNonQuery();
// that messagebox isn't shown
MessageBox.Show("4");
lastpage = "x";
File.Delete(Directory.GetCurrentDirectory() + #"\myimage.jpg");
Any help will be appreciated
You haven't opened your Connection. See below.
You should also use the using syntax to make use of IDisposable
int refcodenum = getOrderNum();
string refcode = "E" + refcodenum;
byte[] personalpic = getBarcode(refcodenum);
var sqlCmdText = "Update Clients set ReferenceNumber='" + refcode + "',ReferenceBarcode=#photo where NetNumber='"+id+"'";
try
{
using (var sqlConnection = new SqlConnection([YOUR CONNECTION STRING HERE]))
{
using (var sqlCommand = new SqlCommand(sqlCmdText, sqlConnection))
{
sqlCommand.CommandType = CommandType.Text;
sqlCommand.Parameters.Add("#photo", SqlDbType.Image, personalpic.Length).Value = personalpic;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new DataException(ex.Message);
}

"Variable names must be unique within a query batch or stored procedure." error c# asp.net

this is my code,when the textbox content changes the datas required have to retrieved from the databse and displayed in the labels specified.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
try
{
DropDownList1.Focus();
string dpt = (string)Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlConnection con1 = new SqlConnection(con);
con1.Open();
// string val1 = dpt;
try
{
String str = "SELECT * from student where sid=#val";
SqlCommand cmd = new SqlCommand(str, con1);
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
SqlCommand cmd2 = new SqlCommand(str2, con1);
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
con1.Close();
}
catch(Exception ex)
{
TextBox1.Text=ex.ToString();
}
}
catch (Exception ex)
{
TextBox1.Text = ex.ToString();
}
} else
{
formatlabel.Visible = true;
}
}
but,when i run the code,i get an error "The variable name '#sid' has already been declared. Variable names must be unique within a query batch or stored procedure.",I googled, generally this error occurs when there is a for loop or any loops,but i do not have any loops in my code.so im unable to find the cause
Try using two separate connection and command objects, like this:
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Match match = Regex.Match(TextBox1.Text, #"^\d{4}[A-Z]{5}\d{3}$");
if (match.Success)
{
DropDownList1.Focus();
string dpt = (string) Session["deptmnt"];
idd = TextBox1.Text;
Label33.Text = idd;
string val = idd;
string con = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con1 = new SqlConnection(con))
{
String str = "SELECT * from student where sid=#val";
con1.Open();
using (SqlCommand cmd = new SqlCommand(str, con1))
{
cmd.CommandType = CommandType.Text;
SqlParameter sql;
cmd.Parameters.Clear();
sql = cmd.Parameters.Add("#val", SqlDbType.VarChar, 20);
sql.Value = val;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows == false)
{
Label35.Visible = true;
TextBox1.Text = "";
}
else
{
Panel3.Visible = true;
DropDownList1.Focus();
while (reader.Read()) // if can read row from database
{
Panel3.Visible = true;
Label3.Text = reader["sname"].ToString();
Label5.Text = reader["dept"].ToString();
Label25.Text = reader["yr"].ToString();
}
cmd.Parameters.Clear();
}
}
}
using (SqlConnection con2 = new SqlConnection(con))
{
string val1 = idd;
string str2 = "SELECT bid from studentissuebook where sid=#val1 AND status='" + "lost" + "'";
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(str2, con2))
{
cmd2.CommandType = CommandType.Text;
cmd2.Parameters.Clear();
SqlParameter sql2;
sql2 = cmd2.Parameters.Add("#val1", SqlDbType.VarChar, 20);
sql2.Value = val1;
SqlDataReader reader1 = cmd2.ExecuteReader();
if (reader1.HasRows == false)
{
TextBox1.Text = "";
Label39.Visible = true;
Panel3.Visible = false;
}
else
{
DropDownList1.Focus();
while (reader1.Read()) // if can read row from database
{
DropDownList1.Items.Add(reader1[0].ToString());
}
DropDownList1.Focus();
}
}
}
}
else
{
formatlabel.Visible = true;
}
}
Note: I have removed your try-catch blocks to make the code simpler to interpret, once it is working, then please re-apply your try-catch logic where you feel appropriate. Also, I added using blocks for the SqlConnection and SqlCommand objects, this will clean up the connection even if an exception happens.

Categories