Saving data in a Database C# WPF [duplicate] - c#

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.

It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.

Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
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
Answer Source
Here is a link to some further discussion and how to documentation.

Related

Data missing from Access database after added using textboxes [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
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
Answer Source
Here is a link to some further discussion and how to documentation.

Ado.net firebird commit insert new lines to table

I'm adding new lines to a database for our company's "order list" for each order created, using the firebird ado.net client. The code i've written works fine for listing items, but inserting new ones doesn't appear elsewhere (e.g. in flamerobin). What I think is happening is that the transaction isn't being committed, seeing as it's recognised within my code (can't add duplicate values).
Code:
using (FbConnection fbCon = new FbConnection)
{
fbCon.Open();
***command w/ parameterised command string***
using (FbTransaction fbTrans = fbCon.BeginTransaction())
using FbCommand orderCommand = new FbCommand(cmdString, fbCon, fbTrans)
{
***Adding parameters and values***
try
{
int recordsAffected = orderCommand.ExecuteNonQuery();
fbTrans.Commit();
}
catch (FbException E)
{
fbTrans.Rollback();
fbCon.Close();
throw E
}
}
recordsAffected returns 1 but I am not able to see the updated values in flamerobin or the db management program. Am i missing something?
If anyone else runs into this problem, it's in Visual Studio's debugging settings. https://visualstudiomagazine.com/blogs/tool-tracker/2012/05/dealing-with-local-databases-or-why-your-updates-dont-stick.aspx explains pretty clearly, but basically VS makes a copy of your database in bin/Debug of your project (Ostensibly to not mess with your data) but if you actually need to use/view the data externally, either link your external application to the debug database (e.g. flamerobin). You may also need to set your project database settings to Copy if Newer if you want your updates to stay, as the default setting copies the database into the folder each time you run your c# app.

How to describe details of an automatic migration

In Entity Framework Code-First you can enable automatic migrations based on code changes in the model.
By calling Update-Database, these changes are:
Registered in a [timestamp]_AutomaticMigration
Generate SQL scripts and migrate database
Store the migration in the table __MigrationHistory
In the __MigrationHistory table, the migration is described in the Model column as a large hex value. eg:
0x1F8B0800000000000400CD57CD6EDB3810BE2FB0EF20F0B40512313F976D20B5C8CAC9C2D83A09AAB4775A1ADBC492944A5281FD6C3DF491FA0A1D...
In the Package Manager Console within Visual Studio, you can retrieve a list of automatic migrations with Get-Migrations.
However, there doesn't seem to be a way to retrieve the details of a particular automatic migration -- whether that's SQL script, or which model & fields are being affected.
Is there a way that I'm unaware of to retrieve details of a particular automatic migration?
Yes, there is.
This value in table __MigrationHistory, is a GZiped Xml, that contains the EDMX schema.
I made this following code to retrieve the EDMX model (this code uses C# 6)
You can access this code on my gist also, with this link: https://gist.github.com/AlbertoMonteiro/45198dc80641ce1896e6
In this gist there is a C# 5 version, that you can paste in a console application.
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Data.dll"
#r "C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\System.Xml.Linq.dll"
using System.Xml.Linq;
using System.IO.Compression;
public void DecompressDatabaseMigration(string migrationName, string databaseName)
{
var connectionString = $#"Data source=.\sqlexpress;Initial catalog={databaseName};Integrated security=true";
var sqlToExecute = String.Format("select model from __MigrationHistory where migrationId like '%{0}'", migrationName);
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var command = new SqlCommand(sqlToExecute, connection);
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
throw new Exception("Now Rows to display. Probably migration name is incorrect");
}
while (reader.Read())
{
var model = (byte[])reader["model"];
var decompressed = Decompress(model);
File.WriteAllText(#"C:\temp\edmx.xml", decompressed.ToString());
}
}
}
public XDocument Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
return XDocument.Load(gzipStream);
}
}
}
DecompressDatabaseMigration(Args[1], Args[0]);
As you can see, there is some syntax that is allowed in the new C# REPL that arrived with Visual Studio Update 1.
So I save this file with .csx extention and then I execute, in my case DecompileMigration.csx
csi DecompileMigration.csx
Then the script will put in my C:\temp folder the file emdx.xml and then I see the model in this particular migration.
To use the REPL of VS 2015 update 1, you can
Load the customized CMD called Developer Command Prompt for VS2015
Press Windows and then search for this name Developer Command Prompt for VS2015
Option 1
Open this in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\Visual Studio Tools
Option 2
Open a cmd session, and then execute this following command
call "%vs140comntools%vsdevcmd.bat"
Option 3
Open it in Visual Studio 2015 U1 in the menu VIEW > Other Windows > C# Interactive
If you use this option, the Args member in the script will not work, so you must replace the Args[0] for your database name, and Args[0] for your database name.
This question came from a misunderstanding between automatic migrations vs. explicit migrations.
I considered an explicit migration would require you to write all up/down changes.
Add-Migration with migration changes that would otherwise be picked up by an automatic migration are placed automatically into the explicit migration file.
Calling Update-Database after the explicit migration will migrate the changes, but now with a code file detailing the changes.

Changes do not get saved permanently into SQL Server Compact edition

I am having a weird problem. I am using vs2012 to connect to SQL Server CE and executing some insert queries.
public void EstablishConnection()
{
connection = new SqlCeConnection("Data Source=DataDump.sdf;Persist Security Info=False;");
try
{
connection.Open();
Console.WriteLine("Connection Successful");
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
public void AddRecord(string link,string content)
{
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) VALUES('"+link+"','"+content+"');",connection);
num = command.ExecuteNonQuery();
Console.WriteLine("Command Successful rows affected"+num);
var cmd2 = new SqlCeCommand("SELECT * FROM Webpages",connection);
SqlCeDataReader reader = cmd2.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
Console.WriteLine(reader[1]);
}
}
However I am having the problem that once VS is closed and when later I open it to display the data, the data is gone as it was never saved
How is that possible when it is clear then it executed the query?
It is a common scenario.
You have your database file listed between your project items.
Its property Copy to Output directory is set to Copy Always.
Now, you run your debug session with VS. The compile is succesfull and VS copies your sdf file from the project folder to the current output directory (BIN\DEBUG).
Your code runs smoothly and inserts the data in your database file (on the output directory).
You stop and restart the debug session to fix something, but, at restart, the VS recopies the empty file from the project folder to the output directory.
To break this circle, set Copy to Output Directory to Copy Never (or Copy if Newer)
EDIT Another source of confusion is due to the use of SERVER EXPLORER to view the contents of your database file. If the server explorer use a connection string that points to the database file in the project folder you never see the changes made to the database file in the Output Directory.
You should create two connections in Server Explorer, one named DEBUG DataDump that points to PROJECTFOLDER\BIN\DEBUG. You could use this connection to check the data inserted during debug or for other debugging tasks. Another one, called DISTRIBUTION DataDump, points to the file in the project folder and you make here your schema changes needed for the distribution of your app.
Said that, keep in mind that your code has a BIG problem. It is called Sql Injection
A parameterized query will avoid quotations problems and remove the Sql Injection
int num = 0;
var command = new SqlCeCommand("INSERT INTO Webpages(Link,Data) " +
"VALUES(#lnk, #cnt)",connection);
command.Parameters.AddWithValue("#lnk", link);
command.Parameters.AddWithValue("#cnt", content);
num = command.ExecuteNonQuery();
set Copy to Output Directory property as Copy if newer for your sdf file
it seems now you have set it as copy always which result :
The database file is copied from the project directory to the bin
directory every time that you build your application. Any changes made
to the data file in the output folder are overwritten the next time
that you run the application.

Mono can't open sqlite database

I'm attempting to do a very basic connection to a sqlite v3 database and I'm using monodevelop 3.0 and Mono 2.10 and am unable to get connected to the database. I can make the app create the database, but then it immediately fails attempting to connect to it. Any suggestions? I had started with a different database, but then decided to have my app attempt to create a database empty and then connect to it. This still seems to fail.
SqliteConnection.CreateFile("db\\DataWorksProg.s3db");
SqliteConnection conn = new SqliteConnection("Data Source=file:db\\DataWorksProg.s3db");
conn.Open();
This small piece of code fails with an error about not being able to open the database file.
Mono.Data.Sqlite.SqliteException: Unable to open the database file
Permissions look OK and I have the Sqlite3.dll in the project, and it seems to be working OK. Have I missed anything obvious? I'm pretty good on the Visual Studio side, but still fairly fresh working in a Mono/Monodevelop environment.
What platform?
I don't believe you need to create a file. If it's not found, iirc, it'll make the database file.
Fwiw, on a Mac, I'm doing (note URI to a pretty standard path; I haven't used Data Source)...
using System;
using System.Data;
using Mono.Data.Sqlite;
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
IDbConnection conTemp = null;
IDbCommand cmdTemp = null;
conTemp = (IDbConnection)new SqliteConnection ("URI=file:/Users/userName/mnmh.db");
conTemp.Open ();
cmdTemp = conTemp.CreateCommand ();
cmdTemp.CommandText = "SELECT * FROM employee";
IDataReader drTemp = cmdTemp.ExecuteReader ();
while (drTemp.Read()) {
Console.WriteLine (drTemp.GetString (0));
}
}
}
}
etc etc
Check the obvious -- you've referenced all the stuff you're using, etc.
Figured out my problem here. Apparently instead of using
"Data Source=file:db\\DataWorksProg.s3db"
I should have been using
"URI=file:db\\DataWorksProg.s3db"
Switched to the URI and it works as expected. I had thought from reading the docs that under the 2.0 profile, the DataSource part was needed instead of the URI, but I got the results I'm looking for.

Categories

Resources