This is an existing class in the dll to verify that the database exists
public class CheckDataBaseExists
{
public void CheckDataBase(string Server, string Database_name)
{
SqlConnection con = new SqlConnection(#"Data Source=" + Server + ";Initial Catalog=master;Integrated Security=True");
con.Open();
con.InfoMessage += connection_InfoMessage;
SqlCommand comm = new SqlCommand(#"if DB_ID('" + Database_name + "') is null print '" + Database_name + " is not exist !\r\nCreate new database ?'", con);
SqlDataAdapter adp = new SqlDataAdapter(comm);
DataTable set = new DataTable();
adp.Fill(set);
con.Close();
}
public static void connection_InfoMessage( object sender, SqlInfoMessageEventArgs e)
{
if( MessageBox.Show(e.Message, e.Source, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes)
{
try
{
The form of entering the name of the server and the database if the database did not exist
#region create form
Label creating = new Label();
creating = new System.Windows.Forms.Label();
creating.SuspendLayout();
//
// creating
//
creating.AutoSize = true;
creating.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
creating.Font = new System.Drawing.Font("Tahoma", 12F);
creating.Location = new System.Drawing.Point(25, 3);
creating.Name = "creating";
creating.Size = new System.Drawing.Size(150, 19);
creating.TabIndex = 0;
creating.Text = "Creating database...";
Form create_db = new Form();
create_db.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
create_db.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
create_db.BackColor = System.Drawing.Color.White;
create_db.ClientSize = new System.Drawing.Size(200, 25);
create_db.ControlBox = false;
create_db.TopMost = true;
create_db.Controls.Add(creating);
create_db.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
create_db.MaximizeBox = false;
create_db.MinimizeBox = false;
create_db.Name = "Create";
create_db.ShowIcon = false;
create_db.ShowInTaskbar = false;
create_db.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
create_db.Text = "Creating Databse...";
create_db.ResumeLayout(false);
create_db.PerformLayout();
create_db.Controls.Add(creating);
create_db.ShowDialog();
#endregion
Read the file that contains the database name and the server
string[] read_file = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + #"\" + "ConReq.HP");
string db_src = read_file[2],
db_nm = read_file[0].Substring(7, read_file[0].Length - 7),
db_server = read_file[1].Substring(7, read_file[1].Length - 7),
location = read_file[3];
The SQL file contains commands to create the database with the name of the database to be created
string read_DBsql = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + #"\Required\DB\DB.sql");
read_DBsql = read_DBsql.Replace("DataBaseName", db_nm);
Create a connection and execute the command
SqlConnection con = new SqlConnection("Data Source=" + db_server + ";Initial Catalog=master;Integrated Security=True;MultipleActiveResultSets=True");
con.Open();
SqlCommand comm = con.CreateCommand();
comm.CommandType = CommandType.Text;
comm.CommandText = read_DBsql;
comm.ExecuteNonQuery();
con.Close();
}
catch (Exception db_e)
{
MessageBox.Show(db_e.Message, db_e.Source, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
But what happens is that when a message appears make sure there is no database and question is do you want to create one.
when I want to create a new one, appears the Form created then nothing happens and remains visible. As in the pictures
Why you are using Info_Message event for such simplest thing ( checking database)
Just check the result is below query:
String query = "select count(*) from sys.databases where name = 'dbname'"
Execute above query as:
var count = cmd.ExecuteScalar();
Also can you please show full code written in Info_Message
Related
I am developing a Windows Forms application in C#. I have always encryption columns in SQL Server.
My goal is to pull data from the datagridview in the form and display data.
I want to pull the data with the where operator and display it in the datagridview, but I am getting the following error.
Is there any way to do this?
I would be glad if you help!!
Error
System.Data.SqlClient.SqlException: 'Must declare the scalar variable "#SSN".
Code:
private void btnSearch_Click(object sender, EventArgs e)
{
con = new SqlConnection("Data Source = " + IP + "; Initial Catalog = " + db + "; Persist Security Info = False; User ID = " + username + "; Password = " + password + ";Column Encryption Setting = Enabled;");
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE TEST_TYPE = #SSN";
SqlParameter paramSSN = cmd.CreateParameter();
paramSSN.ParameterName = #"#SSN";
//paramSSN.ParameterName = "#SSN";
paramSSN.DbType = DbType.AnsiStringFixedLength;
paramSSN.Direction = ParameterDirection.Input;
paramSSN.Value = "'INITIAL_TEST'";
paramSSN.Size = 18;
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}
}
When I changed my code like this, the error went away.I found the solution.
ConnectionString();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = #"SELECT* FROM AE WHERE "+comboBox1.Text+" =
#SSN";
SqlParameter paramSSN = cmd.CreateParameter();
DataSet data_set = new DataSet(cmd.CommandText);
dataAdapter = new SqlDataAdapter(cmd.CommandText,con);
dataAdapter.SelectCommand.Parameters.Add("#SSN",
SqlDbType.VarChar,18).Value = textBox2.Text;
SqlCommandBuilder commandbuild = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(data_set);
dataGridView1.DataSource = data_set.Tables[0].DefaultView;
int rowCount = data_set.Tables[0].Rows.Count;
label6.Text = rowCount.ToString();//Total record
con.Close();
}
I am creating an app whose first window is a database configuration window. From this window, a user inputs server details and selects the database they want to use upon which the database connection details and carried over to the login window and the window is opened.
The login and subsequent windows use the database details for their sql connection string.
My question here is this: how can I save these connection details from the configuration window such that the user bypasses this screen if they have already established a previous connection? I have the idea to store these details to a file and set a boolean condition in App.xaml.cs, but I do not know how to go about doing it.
Here is my code:
For the Database Settings Window
DatabaseSettings.xaml.cs
private void btnTest_Click(object sender, RoutedEventArgs e)
{
try
{
connectionString = "Data Source = " + txtServer.Text + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
conn.Open();
string message = "Connection Successful Please Select a Database to Proceed";
string caption = "Success!";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Information;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
txtServer.IsEnabled = false;
txtUserID.IsEnabled = false;
txtPassword.IsEnabled = false;
btnTest.IsEnabled = false;
cmbdatabase.IsEnabled = true;
btnConfigure.IsEnabled = true;
btnConfigure.IsDefault = true;
sql = "EXEC sp_databases";
command = new SqlCommand(sql, conn);
reader = command.ExecuteReader();
cmbdatabase.Items.Clear();
while (reader.Read())
{
cmbdatabase.Items.Add(reader[0].ToString());
}
conn.Close();
}
catch(Exception ex)
{
System.Windows.MessageBox.Show("Error: " + ex);
}
}
static string Encrypt_Password(string value)
{
using (SHA256Managed sha2 = new SHA256Managed())
{
UTF8Encoding uTF8 = new UTF8Encoding();
byte[] data = sha2.ComputeHash(uTF8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
private void btnConfigure_Click(object sender, RoutedEventArgs e)
{
try
{
string selected = cmbdatabase.Text;
txtSelectedDBItem.Text = cmbdatabase.Text;
string EncryptedPassword = Encrypt_Password(txtPassword.Password);
connectionString = "Data Source = " + txtServer.Text + "; Initial Catalog = " + selected + "; User Id = " + txtUserID.Text + "; Password = " + txtPassword.Password + "";
conn = new SqlConnection(connectionString);
sql = "INSERT INTO Proc_Activity_Log ([UserName], [Password], [AccessTime], [MachineSerial]) values(#userId, #password, #accessTime, #machineserial)";
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#userID", txtUserID.Text);
cmd.Parameters.AddWithValue("#password", EncryptedPassword);
cmd.Parameters.AddWithValue("#accessTime", dateTime.Text);
cmd.Parameters.AddWithValue("#machineserial", txtMachineSerialNo.Text);
cmd.ExecuteNonQuery();
}
UserInterface.frmLogin loginScreen = new UserInterface.frmLogin(txtUserID.Text, txtPassword.Password, txtServer.Text, txtSelectedDBItem.Text);
spashScreen.Show();
this.Close();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Error Here:" + ex.Message);
}
}
For the login screen
frmLogin.xaml.cs
public frmLogin(string uname, string pwd, string server, string db)
{
InitializeComponent();
txtServerUser.Text = uname;
txtServerPwd.Password = pwd;
txtServer.Text = server;
txtSelectedDBItem.Text = db;
}
private void btnOk_Click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(#"Data Source=" + txtServer.Text + "; Initial Catalog=" + txtSelectedDBItem.Text + "; Integrated Security=True;");
try
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
String query = "SELECT COUNT(1) FROM dbo.users WHERE name=#Username and password=#Password";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.AddWithValue("#Username", txtLogin.Text);
sqlCmd.Parameters.AddWithValue("#Password", txtPwd.Password);
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
frmMDI yourDesktop = new frmMDI(txtLogin.Text, txtServerUser.Text, txtServerPwd.Password, txtServer.Text, txtSelectedDBItem.Text);
yourDesktop.Show();
this.Close();
}
else
{
txtLogin.Text = "admin";
txtPwd.Password = "admin";
txtLogin.Focus();
}
}
catch (Exception ex)
{
string message = "The Following Error Occurred: " + ex.Message;
string caption = "Invalid Action";
MessageBoxButton buttons = MessageBoxButton.OK;
MessageBoxImage icon = MessageBoxImage.Error;
System.Windows.MessageBox.Show(message, caption, buttons, icon);
}
finally
{
sqlCon.Close();
}
}
From the screenshots I have included below one can infer which buttons represent the click events in the code above
Database Settings Window - Testing Connection
Database Settings Window - Testing Connection
Database Settings Window - Configuring Database
Database Settings Window - Configuring Database
And finally the login window
login window
I want to connect different access database (they have same tables, same columns) to my system to make a report and this database has a password. I use a openfileDialog to take this database from my files and I want to connect both .mdb, .accdb but but when I use Microsoft.jet.oledb.12.0, I get an error
The microsoft.jet.olebd.12.0 provider is not registered on local machine
This is my code:
private void tileBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open file Dialog";
fdlg.InitialDirectory = #"C:\Desktop";
fdlg.Filter = "(*.mdb)|*.mdb|(*.accdb)|*accdb";
//fdlg.Filter = "All Files (*.*)|*.mdb|*.accdb" + "MS-Access Database Files (*.accdb)|*.accdb, (*.mdb)|*.mdb";
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = fdlg.FileName;
}
}
private void txtRead_Click(object sender, EventArgs e)
{
//connection string
String strDSN = "Provider=Microsoft.Jet.OLEDB.12.0;" + "Data Source=" + txtFilePath.Text;
try
{
//Create a connection and open it
OleDbConnection conn = new OleDbConnection(strDSN);
conn.Open();
String strSQl = "SELECT * FROM Student;";
//create data adapter
OleDbDataAdapter myCmd = new OleDbDataAdapter(strSQl, conn);
// Create and fill dataset
DataSet dtSet = new DataSet();
myCmd.Fill(dtSet);
DataTable dt = dtSet.Tables[0];
dataGridView1.DataSource = dtSet.Tables[0];
//add items to the list box
listBox1.Items.Add("ID,F_Name,S_Name," + "Age");
listBox1.Items.Add("=====================================");
foreach (DataColumn dc in dt.Columns)
{
listBox1.Items.Add(dc.ColumnName + "," + dc.DataType + "," + dc.Unique + "," + dc.AutoIncrement + "," + dc.AllowDBNull);
}
OleDbCommand cmd = new OleDbCommand("SELECT student.ID, student.F_name, student.S_name, student.Age, Teachers_Info.Teachers_ID, Teachers_Info.Firstname, Teachers_Info.Surname, Teachers_Info.Teachers_Subject, Teachers_Info.Teachers_code FROM student, Teachers_Info ORDER BY student.ID;", conn);
OleDbDataReader Reader = cmd.ExecuteReader();
//if (Reader.HasRows)
if (Reader.HasRows)
{
Reader.Read();
txtID.Text = (Reader["ID"].ToString());
txtF_name.Text = (Reader["F_name"].ToString());
txtS_name.Text = (Reader["S_name"].ToString());
txtAge.Text = (Reader["Age"].ToString());
txtTeachers_ID.Text = (Reader["Teachers_ID"].ToString());
txtFirstname.Text = (Reader["Firstname"].ToString());
txtSurname.Text = (Reader["Surname"].ToString());
txtTeachers_Subject.Text = (Reader["Teachers_Subject"].ToString());
txtTeachers_code.Text = (Reader["Teachers_code"].ToString());
}
//close connection
conn.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message.ToString());
}
}
While trying to covert Mssql code to MySQL, specifically during a MysqlCommand request I have created CS1026, CS1002 and a CS1513 error codes,
here is the Mssql code:
try
{
sqlConnect = new System.Data.SqlClient.SqlConnection("server=" + SQLServerAddress + "," + SQLServerPort + "; initial catalog=" + DatabaseName + "; Integrated Security=SSPI");
sqlConnect.Open();
System.Data.SqlClient.SqlCommand sqlCmd = new System.Data.SqlClient.SqlCommand("SELECT ImageFileName, FacePositionXc, FacePositionYc, FacePositionW, FacePositionAngle, Eye1X, Eye1Y, Eye2X, Eye2Y, Template, Image, FaceImage FROM FaceList", sqlConnect);
System.Data.SqlClient.SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
I tried to translate this to MySQL as:
string conn = "server=localhost; uid=user;" +
"pwd=password; database=database;";
MySqlConnection connection = new MySqlConnection(conn);
connection.Open();
try
{
MySqlCommand cmd = connection.CreateCommand();
cmd.Connection = connection;
cmd.CommandText = ("SELECT ImageFileName, FacePositionXc, FacePositionYc, FacePositionW, FacePositionAngle, Eye1X, Eye1Y, Eye2X, Eye2Y, Template, Image, FaceImage FROM faces", connection);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
TFaceRecord fr = new TFaceRecord();
fr.ImageFileName = reader.GetString(4);
fr.FacePosition = new FSDK.TFacePosition();
fr.FacePosition.xc = reader.GetInt32(5);
fr.FacePosition.yc = reader.GetInt32(6);
fr.FacePosition.w = reader.GetInt32(7);
fr.FacePosition.angle = reader.GetFloat(8);
fr.FacialFeatures = new FSDK.TPoint[2];
fr.FacialFeatures[0] = new FSDK.TPoint();
fr.FacialFeatures[0].x = reader.GetInt32(9);
fr.FacialFeatures[0].y = reader.GetInt32(10);
fr.FacialFeatures[1] = new FSDK.TPoint();
fr.FacialFeatures[1].x = reader.GetInt32(11);
fr.FacialFeatures[1].y = reader.GetInt32(12);
fr.Template = new byte[FSDK.TemplateSize];
reader.GetBytes(9, 0, fr.Template, 0, FSDK.TemplateSize);
Image img = Image.FromStream(new System.IO.MemoryStream(reader.GetInt32(14)));
Image img_face = Image.FromStream(new System.IO.MemoryStream(reader.GetInt32(15)));
fr.image = new FSDK.CImage(img);
fr.faceImage = new FSDK.CImage(img_face);
FaceList.Add(fr);
imageList1.Images.Add(fr.faceImage.ToCLRImage());
string fn = fr.ImageFileName;
listView1.Items.Add((imageList1.Images.Count - 1).ToString(), fn.Split('\\')[fn.Split('\\').Length - 1], imageList1.Images.Count - 1);
textBox1.Text += "File '" + fn + "' read from database\r\n";
img.Dispose();
img_face.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception on loading database");
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
// LoadData();
}
}
}
The error is generated at the end of the command text ' ", connection ) '
Removing the ', connection' creates a 'Unable to cast object of type ‘symbol.Byte[] to type ‘System.Convertable’' on the error exception.
Could anyone please advise on the correct syntax to use or where my mistake is thank you.
I wanted to update my database that contains two text and one filename that is needed for image.
The problem is that the image and filename updates but the two other text values title and body wont be affected and don't change the previous values. Also visual studio don't get any problem and the message for executing command shows that it's executed the command but nothing except the image changes.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["user"] == null)
Response.Redirect("~/default.aspx");
if (Request .QueryString ["action"]=="edit")
{
Panel1.Visible = true;
}
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString =GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString () + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text=myReader ["Title"].ToString ();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
protected void btn_addpost_Click(object sender, EventArgs e)
{
string title= title_txt .Text ;
string body=bodytxt .Text ;
if (Request.QueryString["edit"] != null)
{
string message;
string filename = thumb_uploader.FileName;
string path = HttpContext.Current.Server.MapPath("~") + "\\Thumb";
string exup = System.IO.Path.GetExtension(thumb_uploader.FileName);
string[] ext = { ".jpg", ".png", ".jpeg" };
if (Array.IndexOf(ext, exup) < 0)
{
message = "not correct.";
}
if (thumb_uploader.FileBytes.Length / 1024 > 400)
{
message = "not currect.";
}
while (System.IO.File.Exists(path + "\\" + filename + exup))
{
filename += "1";
}
savepath = path + "\\" + filename;
if (thumb_uploader.HasFile)
{
thumb_uploader.SaveAs(savepath);
thumb = thumb_uploader.FileName;
SqlCommand command;
SqlDataAdapter da;
SqlConnection con3 = new SqlConnection();
con3.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
command = new SqlCommand();
command.Connection = con3;
da = new SqlDataAdapter();
da.SelectCommand = command;
command.CommandText = "UPDATE tbl_post SET Title=#title ,Body=#body ,Thumb=#thu Where Postid=" + Request.QueryString["edit"].ToString();
con3.Open();
command.Parameters.AddWithValue("#title", title );
command.Parameters.AddWithValue("#body", body );
command.Parameters.AddWithValue("#thu", thumb_uploader .FileName);
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
else
{
using (SqlConnection con3 = new SqlConnection(GNews.Properties.Settings.Default.connectionstring))
{
string sql = "update tbl_post SET Title=#title ,Body=#body Where Postid=#postid" ;
using (SqlCommand command = new SqlCommand(sql, con3))
{
con3.Open();
command.Parameters.AddWithValue("#title", title);
command.Parameters.AddWithValue("#body", body);
command.Parameters.AddWithValue("#postid", Request.QueryString["edit"].ToString());
command.ExecuteNonQuery();
con3.Close();
message = "its ok.";
lbl_result.Text = message;
}
}
}
}
I've found the answer I needed this code to include my pageload reading database so it wouldn't do it when I click on the update button.I mean the problem was all about the post back thing.
if (!Page.IsPostBack)
{
if (Request.QueryString["edit"] != null)
{
Panel1.Visible = true;
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = GNews.Properties.Settings.Default.connectionstring;
DataTable dt3 = new DataTable();
con2.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from loadpost_view where Postid=" + Request.QueryString["edit"].ToString() + "", con2);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
title_txt.Text = myReader["Title"].ToString();
bodytxt.Text = myReader["Body"].ToString();
}
con2.Close();
}
}