Install database script in C # - c#

We created a C # program with entity framework
Now I'm having trouble making the setup, because if this program is installed on another system it will be difficult to miss the database.
This program automatically installs sql server engine. Now my problem is the installation of the database.
I would like a code to check when installing whether or not there is a database on the engine, if not, install a script file that our database is installed on.

Sounds like you want a Database Initialization Stategy and I'd recommend this one to meet your requirements:
CreateDatabaseIfNotExists: This is default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, then it will throw an exception.
The page I linked also includes an example of how to implement the strategy:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}

If you are using code first migrations, you could generate the requiered sql-scripts. I believe you already have the scripts to run, so that won't be a problem.
If Initializers won't do the trick, You could take a look at custom actions.
You can then run a program with the permissions of the system/user running the setup to check of if the database (or server) exists. And if not create it.
Assuming you are creating a msi setup take a look here.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa368066(v=vs.85).aspx

I used sp_attach_db for attach database.
But he tells me that Attach the database successfully
But something is not attached to SQL Server
When I run two runs, the program says that The database is available
or
(Database 'TellDB' already exists. Choose a different database name.
Changed database context to 'master'.)
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;";
con.Open();
string str = "USE master;" +
"EXEC sp_attach_db #dbname = N'TellDB' , " +
" #filename1 = N'" + System.Environment.CurrentDirectory + "\\Data\\TellDB.mdf'," +
"#filename2 = N'" + System.Environment.CurrentDirectory + "\\Data\\TellDB_log.ldf'";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Attach the database successfully");
}
catch (Exception x)
{
if (x.Message.IndexOf("already exists") >= 0)
MessageBox.Show("The database is available");
else
MessageBox.Show(x.Message);
}

Related

Why is my math not working on my SQL Server database?

I am developing an asp.net web application and I am trying to add a user xp system to it. I have a SQL Server database connected to it and I am trying to make a function that will give 5 experience points to the user.
I queried to the user that is logged in, accessed the user_xp column, and I am trying to add +5 to the old session variable for xp, then send that back into the database to be stored. Here is my code, I am not sure what is wrong with it.
void generateXp()
{
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("UPDATE member_master_tbl SET user_xp = #user_xp WHERE " +
"user_name = '" + Session["username"].ToString().Trim() + "'", con);
int xp = 5;
int current_xp = Convert.ToInt32(Session["user_xp"]);
int new_xp = xp + current_xp;
string new_xp2 = Convert.ToString(new_xp);
cmd.Parameters.AddWithValue("user_xp", new_xp2);
}
catch (Exception ex)
{
}
}
Try renaming the SQL parameter to #user_xp.
cmd.Parameters.AddWithValue("#user_xp", new_xp2);
I don't have an accessible database to test. Also, you need to add the command to execute the query at the end.
cmd.ExecuteNonQuery()
That being said, it's a good practice to learn to separate DB queries to stored procedures or functions.
As others noted, you simply forgot to do a execute non query to run the command that you setup.
However, you can write things this way. You don't mention or note what the data type the experience points column is - I assumed "int".
So, your code block can be written this way:
using (SqlCommand cmd = new SqlCommand("UPDATE member_master_tbl SET user_xp = #user_xp WHERE user_name = #user",
new SqlConnection(strcon)))
{
cmd.Parameters.Add("#user_xp", SqlDbType.Int).Value = 5 + Session("user_xp");
cmd.Parameters.Add("#user", SqlDbType.NVarChar).Value = Session("username");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
note how the command object has a connection object (so we don't need a separate one).
And while several people here "lamented" the string concentration to build the sql and warned about sql injection?
Actually, the introduction of # parameters for both values cleans up the code. So you get nice parameters - nice type checking, and you don't have to remember to add/use/have things like quotes around teh string, but not for numbers.
And I let .net cast the number expression from session() - this also likely is ok.
Also the "using block" also correctly cleans up the command object and also the connection object - so the using block is a good idea here.

C# SQLite FTS5 Table and Triger creation

I am creating a virtual table with sqlite fts5 and I am having the following error message: SQL Logic error no such module: FTS5. Below is my code:
Using Package manager in VS 2017 I have already download SQLite and SQLite FTS5.
private static void CreateReport()
{
try
{
using (SQLiteConnection sqliteConnection = new SQLiteConnection(DataSources.LocalConnectionString()))
{
sqliteConnection.Open();
sqliteConnection.EnableExtensions(true);
string commandText = "CREATE TABLE IF NOT EXISTS JReport(JRId INTEGER PRIMARY KEY, IDId INTEGER, CaseId INTEGER, BoxName TEXT, JRText TEXT, JRFormatted TEXT)";
string commandText1 = "CREATE VIRTUAL TABLE IF NOT EXISTS DReport USING FTS5(JRId, CaseId, BoxName, CONTENT = 'JReport', CONTENT_ROWID = 'JRId')";
string commandText2 = "CREATE TRIGGER DocRepo AFTER INSERT ON JReport BEGIN INSERT INTO DReport(RowId, JRId, CaseId, BoxName) VALUES(NEW.JRId, NEW.CaseId, NEW.BoxName) END";
using (SQLiteCommand sqliteCommand = new SQLiteCommand(commandText, sqliteConnection))
{
sqliteCommand.ExecuteNonQuery();
sqliteCommand.Dispose();
}
using (SQLiteCommand sqliteCommand = new SQLiteCommand(commandText1, sqliteConnection))
{
sqliteCommand.ExecuteNonQuery();
sqliteCommand.Dispose();
}
using (SQLiteCommand sqliteCommand = new SQLiteCommand(commandText2, sqliteConnection))
{
sqliteCommand.ExecuteNonQuery();
sqliteCommand.Dispose();
}
sqliteConnection.Close();
}
}
catch (Exception ex)
{
MessageBoxEx.Show("An error has occurred while creating the Report table, the original error is: " +
ex.Message, "Report", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
SQL Logic error no such module: FTS5.
Just like the error message says, your sqlite3 library doesn't have the FTS5 module. It probably wasn't configured to include it as a built in one when the library was built, as it's not enabled by default. It might have been made available as a dynamically loadable module by whoever did configure and build the library you're using. Or not.
Personally, I just always include a copy of sqlite3.c in any program I'm using that uses it to avoid relying on an external dependency and so you can make sure you're always using a version with all the features you want to use present. Dunno what you'd have to do in C# to use your own local instance, but I'm sure there's a way.
Instructions for building FTS5 into sqlite3 or as a loadable module.

SQL CE Not updating database values from windows forms

I am building a inventory based application that can be directly run from any pc without any installation and so i am using SQL CE.. On Start, I am checking if database is present. If Not i am creating new database as :
try
{
string conString = "Data Source='ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;";
SqlCeEngine engine = new SqlCeEngine(conString);
engine.CreateDatabase();
return true;
}
catch (Exception e)
{
//MessageBox.Show("Database Already Present");
}
The database is created properly and i can access the database to create tables as well.. The Problem i am facing is - I am inserting and updating records in windows form on button click with code :
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
String Name = NameTxt.Text.ToString();
String Phone = PhoneTxt.Text.ToString();
double balance = Double.Parse(BalanceTxt.Text.ToString());
String City = CityTxt.Text.ToString();
string sqlquery = "INSERT INTO Customers (Name,Phone,Balance,City)" + "Values(#name,#phone, #bal, #city)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#bal", balance);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
connection.Close();
}
and Updation Code is
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
int idtoedit = select_id_edit;
String Name = NameEditTxt.Text.ToString();
String Phone = metroTextBox1.Text.ToString();
String City = CityEditTxt.Text.ToString();
string sqlquery = "Update Customers Set Name = #name, Phone = #phone,City = #city where Id = #id";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#id", idtoedit);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Updated");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
loadIntoGrid();
connection.Close();
}
Whenever i execute code for inserting and updating records - Records are reflected in datagrid filled with adapter from database table. But once i restart the application, values do not appear in database. Once in a million, values are reflected in database. I cannot understand the reason behind this issue.
I have reffered to these articles :
C# - ExecuteNonQuery() isn't working with SQL Server CE
Insert, Update, Delete are not applied on SQL Server CE database file for Windows Mobile
But since i am creating database programmatically - It is getting created directly to bin/debug directory and i cannot see it in solution explorer in visual studio for changing copy options
You probably rewrite your database file with a blank copy from your project.
See this answer. You should not store your database in a bin folder, rather you should find a place in user's or public profile in AppData or another folder, depending on your needs.
The connection string would look like this:
<connectionStrings>
<add name="ITMContext" connectionString="data source=|DataDirectory|\ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;" providerName="System.Data.SqlServerCe.4.0">
You shuld deploy your db file with your custom code run at app's starup to a chosen location, see this ErikEJ blog: http://erikej.blogspot.cz/2013/11/entity-framework-6-sql-server-compact-4_25.html
private const string dbFileName = "Chinook.sdf";
private static void CreateIfNotExists(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Set the data directory to the users %AppData% folder
// So the database file will be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// Enure that the database file is present
if (!System.IO.File.Exists(System.IO.Path.Combine(path, fileName)))
{
//Get path to our .exe, which also has a copy of the database file
var exePath = System.IO.Path.GetDirectoryName(
new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
//Copy the file from the .exe location to the %AppData% folder
System.IO.File.Copy(
System.IO.Path.Combine(exePath, fileName),
System.IO.Path.Combine(path, fileName));
}
}
Check also this post.
You have several options to change this behavior. If your sdf file is
part of the content of your project, this will affect how data is
persisted. Remember that when you debug, all output of your project
(including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
The database file in your project can be different when debugging or not. Check also this answer. You might be writting your records to another copy of the database file.

Create database without wizard c#

Today i'm working on a project where I will create a relational database through source code and not through the built-in wizard.I have been looking for tutorials which explain to me the processes of doing this but seem to not be able to do so. Most have tutorials on how to use the build-in wizard and add content to tables, my main goal is to actually have a utility that users could use which includes a self-building database. if you have examples of this, I would greatly appreciate it or if you know of any good tutorials that will be helpful too
Thanks!
class Program
{
static string strcon = #"user id = sde ; password = passrd;
server =dfgserver;database =valrollclients";
static SqlCommand cmdinserted = new SqlCommand();
static SqlConnection con; //declaring a connection object
static void Main(string[] args)
{
cmdinserted.CommandText = "[dbo].[prcinsert_client]";
cmdinserted.CommandTimeout = 0;
cmdinserted.CommandType = CommandType.StoredProcedure;
cmdinserted.Connection = con;
cmdinserted.Parameters.Add("#client_name",
SqlDbType.VarChar, 12).Value = "me";
cmdinserted.Parameters.Add("#client_lastname",
SqlDbType.VarChar, 15).Value = "abutair";
cmdinserted.Parameters.Add("#client_age ",
SqlDbType.Int, 4).Value = 4;
try
{
con.Open(); //open connection
cmdinserted.ExecuteNonQuery(); //execute the stored procedure
con.Close();//close connection
}
catch (SqlException) //catch an error
{
throw; //throw it back to the calling method
}
This is the code you have to run on the server:
USE master;
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL \DATA\saledat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\salelog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;
GO
You can add it into a SqlCommand. You will need an SqlConnection which I see you have.
Hope it helps.
It seems like this is being made way more complicated than it needs to be if you're planning to use SQL server.
Your application offers the user a way to enter a SQL server instance location and user with admin rights.
You then have a class with various methods which create your database, create your tables etc.
So you would do:
1) If not exists create database X.
2) IF not exists create tables A B C etc
3) alter the tables to setup the relations
4) If not exists create stored proc spA spB etc etc
and just build up the database that way.
Each step above would be a separate method which executes some inline SQL.
If you write the SQL to always check if the thing you're going to create exists it can be used to upgrade as well as create.

Create an SQL Express 2008 database in C# code, but login fails when trying to connect with a sysadmin

I have a piece of code that creates an SQL Server Express 2008 in runtime, and then tries to connect to it to execute a database initialization script in Transact-SQL. The code that creates the database is the following:
private void CreateDatabase()
{
using (var connection = new SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master;" +
"Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
"CREATE DATABASE " + m_databaseFilename +
" ON PRIMARY (NAME=" + m_databaseFilename +
", FILENAME='" + this.m_basePath + m_databaseFilename + ".mdf')";
command.ExecuteNonQuery();
}
}
}
The database is created successfully. After that, I try to connect to the database to run the initialization script, by using the following code:
private void ExecuteQueryFromFile(string filename)
{
string queryContent = File.ReadAllText(m_filePath + filename);
this.m_connectionString = string.Format(
#"Server=.\SQLExpress; Integrated Security=true;Initial Catalog={0};", m_databaseFilename);
using (var connection = new SqlConnection(m_connectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = queryContent;
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
}
However, the connection.Open() statement fails, throwing the following exception:
Cannot open database "TestData"
requested by the login. The login
failed. Login failed for user
'MYDOMAIN\myusername'.
I am completely puzzled by this error because the account I am trying to connect with has sysadmin privileges, which should allow me to connect any database (notice that I use a connection to the master database to create the database in the first place).
Is there a reason you specify User Instance=True when you create it but not when you try to connect to it?
When you create it after connecting with User Instance, it will create the database files but does not attach it to your actual instance. You'll either have to not specify User Instance=True in the first connection string or add it to the second and specify the database file to use.
Is the user you are logging with have rights to the database 'TestData'?
If not grant the user the privileges required.
I am not sure if this means anything, but in your first create you are connecting to server
.\\sqlexpress
The second one is
.\SQLExpress
You'll need to issue a CREATE USER command (see: http://msdn.microsoft.com/en-us/library/ms173463.aspx) after creating the database but before trying to open a connction to that database.
For example:
CREATE USER 'MYDOMAIN\myusername' FOR LOGIN 'MYDOMAIN\myusername'

Categories