C# using DataDirectory in connection string with variable filename - c#

I am new to C# and have been working on a program for work. A simple ticketing program as a backup when the primary goes down. I don't have a server to run a database on so I have been using sqlite. This works great since I don't need to install anything. I would like to set it up to save the database file for each users program to save to a network location with a unique name for the database file. I have figured out how to set the save location of the database but not give the file a name. I would like to use the name of the current logged in user which is already unique and displays when the program runs, it is also added to the database when a new ticket is saved. The program checks the file location and if the database does not exist creates it.
public partial class Ticket_Contingency : Form
{
SQLiteConnection con;
SQLiteDataAdapter da;
SQLiteCommand cmd;
DataSet ds;
DataTable dt;
int id;
string userName = Environment.UserName;
}
public Ticket()
{
InitializeComponent();
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal));
private void Form1_Load(object sender, EventArgs e)
{
//loads the saved username from App.config
usernametextBox.Text = userName;
AppDomain.CurrentDomain.SetData("DataDirectory", Properties.Settings.Default.folderdb);
dblabel.Text = Properties.Settings.Default.folderdb;
//Diables Autovalidation
this.AutoValidate = AutoValidate.Disable;
if (!File.Exists("|DataDirectory|incidentdb.sqlite"))
try
{
con = new SQLiteConnection(#"Data Source=|DataDirectory|incidentdb.sqlite;Version=3;New=True;Compress=True;");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "CREATE TABLE 'contacts' ('Id' INTEGER PRIMARY KEY NOT NULL DEFAULT (0) ,'firstname' VARCHAR,'lastname' VARCHAR,'mi' CHAR,'email' VARCHAR,'phone' VARCHAR,'ext' CHAR,'visn' CHAR,'site' VARCHAR,'department' VARCHAR,'desklocation' VARCHAR,'notes' VARCHAR,'template' VARCHAR,'priority' CHAR,'summary' VARCHAR, 'status' CHAR, 'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, 'username' VARCHAR)";
cmd.ExecuteNonQuery();
con.Close();
Form1_Load(this, null);
}
catch (SQLiteException ex)
{
// Log the exception
{
}
//Tries to connect to the local Database. Returns error message on failure
try
{
con = new SQLiteConnection(#"Data Source=|DataDirectory|incidentdb.sqlite;Version=3;");
con.Open();
da = new SQLiteDataAdapter("Select ID, firstname as 'firstname', lastname as 'lastname', summary as 'summary', timestamp as 'timestamp' from contacts ORDER by ID ASC", con);
ds = new System.Data.DataSet();
da.Fill(ds, "Person_Details");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
Clear_Form(this, null);
}
catch (SqlException)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
}
What I would like to do is replace
if (!File.Exists("|DataDirectory|incidentdb.sqlite"))
with something like
if (!File.Exists("|DataDirectory|" + userName + ".sqlite"))
I know that doesn't work but I really have no idea how to go about this. I have searched everywhere but can only come up with results that look like the original code
if (!File.Exists("|DataDirectory|incidentdb.sqlite")
I would really appreciate some help. Like I said I am new to this. Most of my other issues were solved with research but this is beyond me. Thanks!

Related

File Not Found Exception was unhandled in the line of adapter.Fill(table)

Im trying to connect to the database MySql but this error was appeared
FileNotFoundException was unhandled
in the line of adapter.Fill.
FileNotFoundException was unhandled Could not load file or assembly 'Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106' or one of its dependencies. The system cannot find the file specified
class CONNECT
{
private MySqlConnection connection = new MySqlConnection("Datasource=localhost;Port=3306;Username=root;Password=;Database=Csharp_Hotel_DB");
//create a function to return our connection
public MySqlConnection getConnection()
{
return connection;
}
//create a function to open the connection
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
//create a function to close the connection
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
private void buttonLogin_Click(object sender, EventArgs e)
{
CONNECT conn = new CONNECT();
DataTable table = new DataTable();
MySqlDataAdapter adapter = new MySqlDataAdapter();
MySqlCommand command = new MySqlCommand();
String query = "SELECT * FROM `users` WHERE `username`=#usn AND `password`=#pass";
command.CommandText = query;
command.Connection = conn.getConnection();
command.Parameters.Add("#usn", MySqlDbType.VarChar).Value = textBoxUsername.Text;
command.Parameters.Add("#pass", MySqlDbType.VarChar).Value = textBoxPassword.Text;
adapter.SelectCommand = command;
adapter.Fill(table); //this line is the FileNotFoundException was unhandled
// if the username and the password exists
if (table.Rows.Count > 0)
{
this.Hide();
MessageBox.Show("YES");
Main_Form mform = new Main_Form();
mform.Show();
}
else
{
if (textBoxUsername.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Username to Login", "Empty Username", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBoxPassword.Text.Trim().Equals(""))
{
MessageBox.Show("Enter Your Password to Login", "Empty Password", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Username and Password Doesn't Exists", "Wrong Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
It's now working c.
Using the MySQL-connector-net-6.3.5 can fix this error or problem because I'm using .net 4
Thank you for your help.
it seems that you do not handle the exceptions adapter.fill could through.
use:
try{
adapter.Fill(table);
} catch(FileNotFoundException e) {
do stuff with e or your code
}
alternatively check the pathes if they exist before using them.
You are creating a data table without passing a name into the constructor. This means that the table is nameless and so when you try to call Fill on a nameless table you get your file not found exception.
You should pass in the table name
DataTable table = new DataTable("users");
This is a bug in MySQL Connector/NET, bug 96614. It will be fixed in Connector/NET 8.0.18.
Fixed as of the upcoming MySQL Connector/NET 8.0.18 release, and here's the changelog entry:
The Renci.SshNet.dll deployment was problematic for Connector/NET 8.0.17
MSI installations. Some applications, such as Microsoft Excel, were unable
to read MySQL data as a result. This fix removes unnecessary dependencies
on the DLL and also ensures that the MSI installation deploys the correct
Renci.SshNet.dll to the GAC.
A workaround you can use today is switching to MySqlConnector, an alternative OSS ADO.NET library for MySQL, which doesn't have this bug.

DataBase not updating in C# when using service-based database

I'm trying to write a program for my exam. I have to use and work with database, i've written some code and encountered a problem. Database is not updating. When I execute my application everything works perfectly, I add some info and it appears in my dataGridView, but when I go to the table in database that i've been updating and select "Show table data", it's empty.
This is function that inserts data into my database.
static public void Insert(string _imonesPav, string _imonesKodas, string _sutartiesPradzia, string _sutartiesPabaiga)
{
try
{
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO Tiekejai VALUES (#ImonesPav, #ImonesKodas, #SutartiesPradzia, #SutartiesPabaiga)", connection);
command.Parameters.AddWithValue("#ImonesPav", _imonesPav);
command.Parameters.AddWithValue("#ImonesKodas", _imonesKodas);
command.Parameters.AddWithValue("#SutartiesPradzia", _sutartiesPradzia);
command.Parameters.AddWithValue("#SutartiesPabaiga", _sutartiesPabaiga);
command.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
And this is how i use it.
private void updateDatabase_Click(object sender, EventArgs e)
{
SQLFunkcijos.Insert(imonesVardas.Text, imonesKodas.Text, sutartPradzia.Text, sutartPabaiga.Text);
SQLFunkcijos.Refresh(this.dataGridView1);
}
Refresh function is used to update data in dataGridView in real time.
So the question would be, what am i doing wrnog? Why table in database is not updating.
P.S. I've tried all Copy to Output options, it works only with Copy if newer.
EDIT1: Refersh function.
static public void Refresh(DataGridView _dataGridView)
{
try
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * FROM Tiekejai", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
_dataGridView.DataSource = dataTable;
}
catch(SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
EDIT2: Problem solved! I was just using bad connection string. Thanks for everyones help.

validation of data with sql and c#

i've been struggling to understand how to validate data i entered in an input in an .aspx webform,
say username and password, i've tried many things, tried reading about it and looking for solutions but all of them are really messy with a lot of things i don't really need.
It is for a school project in my school and i already set up a working database, and i already made a register page, that works and it submits it to the database.
Our teachers supplied us with a DalAccess file, that is stored in the App_Data folder in my project.
This is the code inside of it:
public class DalAccess
{
private OleDbConnection conn;
private OleDbCommand command;
private OleDbDataAdapter adapter;
public DalAccess(string strQuery)
{
string ConnectionString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database.accdb");
conn = new OleDbConnection(ConnectionString);
command = new OleDbCommand(strQuery, conn);
adapter = new OleDbDataAdapter(command);
}
public DataSet GetDataSet(string strSql)
{
DataSet ds = new DataSet();
command.CommandText = strSql;
adapter.SelectCommand = command;
adapter.Fill(ds);
return ds;
}
public int InsertUpdateDelete(string strSql)
{
int rowsAffected;
this.conn.Open();
OleDbCommand cmd = new OleDbCommand(strSql, conn);
rowsAffected = cmd.ExecuteNonQuery();
conn.Close();
return rowsAffected;
}
}
Note: i am a complete beginner and have no idea what does anything in that code means.
So, i wrote these lines of code in the aspx.cs page behind
{
public DataSet ds ;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
string loginid = Request.Form["loginid"];
string loginpw = Request.Form["loginpw"];
string sqlS = "Select IDD,Pass from UserInfo where IDD = '"+ loginid + "'";
DalAccess dal = new DalAccess(sqlS);
ds = dal.GetDataSet(sqlS);
}
}
}
And if i wrote it correctly i selected the two tabs of the row that the value of IDD(ID of the user) in the table is loginid.
Problem is, i can't figure out how to take that data i selected and compare it to the things entered into the inputs and to check if they match.
I'd greatly appreciate if someone were to go as far as explain to me what everything does, since my teacher hasn't got a lot of time to give to all the students, but an example and a simple explanation will work for me too.
Important note!: I know if i make it parameterized it is safe against sql injection, which i did not do, but this part of the project is not for the purpose of security, which we will have a part for it too, and we will learn.
Thanks in advance.
when water rises above the level of the noses, only those will survive, who know how to swim, isn’t it?
Technically we will go for stored procedure to validate the login[as best practices].In the link the its very clear that you can do it with minimal coding.
How to validate login and pass userID
Updated:
ok, if we want to do it in your way.
In the code behind inside the method
private void ValidateLogin()
{
string uname = "Hsakarp";//I have hard-coded the value to make it simple
string pwd = "12345";
string sqlS = "Select UserName,Password from Login where UserName = '" + uname + "' and Password = " + pwd;
DalAccess dal = new DalAccess();
DataSet ds = dal.GetDataSet(sqlS); //GetDataset is gonna return the ds
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["UserName"].ToString().Trim() == uname && ds.Tables[0].Rows[i]["Password"].ToString().Trim() == pwd)
//Check whether the username and password exists.
Label1.Text = "Login Successfull";
else
Label1.Text = "Login failed";
}
}

Data Corruption: select into to create a duplicate table as alternative for alter table for excel using ado.net

I have tried to use Alter table on an excel spreadsheet to add a new column to existing spreadsheet but found out that I cannot use alter table on excel.
From browsing the net I found that I can use select into to create a duplicate worksheet with new column in it. Here is the code for this.
static private bool CopyAndCreateNewSheet()
{
try
{
DataTable dataTable = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConfigHelper.ConnectionStringReadWriteWorkBook))
{
conn.Open();
//string selectQuery = "SELECT 0 As IsProcessed, * INTO [Copy] FROM [" + ConfigHelper.WorkSheetName + "$]";
string selectQuery = "SELECT 0 As IsProcessed, * INTO [Excel 12.0;HDR= Yes;DATABASE=c:\\data\\Apr12.xlsx].[copyd] FROM [" + ConfigHelper.WorkSheetName + "$]";
OleDbCommand cmd = new OleDbCommand(selectQuery, conn);
int count = cmd.ExecuteNonQuery();
MessageBox.Show(count.ToString());
conn.Close();
}
}
catch (OleDbException e)
{
MessageBox.Show(e.Message.ToString());
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return true;
}
My config for connectionstring is as follows.
<add name="ReadWriteWorkBook" connectionString='Provider = Microsoft.ACE.OLEDB.12.0; Data Source="c:\data\Apr12.xlsx"; Extended Properties="Excel 12.0;HDR=Yes;READONLY=FALSE"'/>
I have tried with both commented query and uncommented query to run select into but with no luck...
When I open my workbook after above method call I am getting the following error. "Excel found unreadable connect in the file. do you want to recover the contents of this workbook? If you trust the source of this workbook, click yes."
When I click yes, my new tab is there and also new headers are there but no data as excel has removed data from it.
Any help much appreciated.
Thanks in advance.
G'day,
I was able to replicate this and have it work perfectly. The code I used looks like this:
public static void Main(string[] Arguments)
{
try
{
string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Test.xlsx\";Extended Properties=\"Excel 12.0;HDR=Yes;READONLY=FALSE\"";
DataTable dataTable = new DataTable();
using (OleDbConnection conn = new OleDbConnection(sConnectionString))
{
conn.Open();
string selectQuery = "SELECT 0 As IsProcessed, * INTO [Excel 12.0;HDR= Yes;DATABASE=Test.xlsx].[copyd] FROM [TestWorkSheet1$]";
OleDbCommand cmd = new OleDbCommand(selectQuery, conn);
int count = cmd.ExecuteNonQuery();
Console.WriteLine(count.ToString());
conn.Close();
}
}
catch (OleDbException e)
{
Console.WriteLine(e.Message.ToString());
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Note that this code was modified slightly to run inside a console application. This doesn't really help you out at all however. Excel can be a real pain to work with sometimes, have you considered investigating the following:
Permissions
Does the original file open in Excel without issues (i.e., is that file readable by Excel in the first place?)
Has Excel somehow TSR'd and is interfering with your project in some fashion? I've seen this happen before, usually when Excel isn't closed properly
Good luck.
Cheers!

CombBox is not populating the ValueMember Properly from MySQL in C#

I have two combobox in my form, using a mysql connection to a remote server. The first combobox populated nicely. However, I need the indexid since that is a foreign key to populate a second combobox. Based on the selection, it will change the data in the second combo (for the xample, i the first combo is for car makes, then the models of each make gets filled, so if I choose Nissan, the models will then have Altima, Maxima, Sentra, ... but if I chose Toyota, the combo will then show Corolla, Camry, Prius, ...)
My foreign key is always -1 for some reason. I am using the selectindex change method, but it keeps crashing/ bc the value is always -1.
I am very new to MySQL in C# and eager to learn. Any help is appreciated. The code is below.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboMake.SelectedIndex >= 0)
cboModel.Enabled = true;
else
cboModel.Enabled = false;
// get the foreign key value of the model id to get the make for each brand to populate here
// MessageBox.Show(cboModel.ValueMember);
// right now selectindex always shows -1. why?
// if it changes, you need to then enable the right cbo, else, disable.
// but also, you need the mid, fk, so you can then do a new sql statement with the where clause to populate it.
int fk = cboModel.SelectedIndex;
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid='fk'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "model";
cboMake.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
private void frmMain_Load(object sender, EventArgs e)
{
string connStr = "server=123.456.7.8;user=root;database=car;port=3306; password=nowayjose";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_make";
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboMake.DataSource = dt;
cboMake.DisplayMember = "make";
cboMake.ValueMember = "mid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}
Correct me if I'm wrong, but considering code provided, just a guess :
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int fk = cboModel.SelectedIndex; // ?????
.....
}
You access here cboModel, which is not that one whom item was actually selected. At least lookin on event name cboMake_SelectedIndexChanged, seems to me that you should look on cboMake selected index.
Hope this helps.
private void cboMake_SelectedIndexChanged(object sender, EventArgs e)
{
int foreignKey = (int)cboMake.SelectedIndex +1; // i forgot to cast the int from string since the database was tinyint, it still returns string in c#
string fk = foreignKey.ToString(); // since i need the string for the query, back it goes, but i needed to do arithmetic
string connStr = "server=10.18.30.1;user=notroot;database=car;port=3306;password=password";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
string sql = "SELECT * FROM cs_model WHERE mid=" + fk; // forgot to escape out of the string (used to php $var style within double quotes)
MySqlCommand cmd = new MySqlCommand(sql, conn);
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
cboModel.DataSource = dt; // i had cboModel by a silly mistake
cboModel.DisplayMember = "model";
cboModel.ValueMember = "mmid";
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "MySQL Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
conn.Close();
}

Categories