Can't create sqlite db on production machine - database

I have a program that works correctly on my computer in Debug mode.
When my program start he create a Sqlite data base file if not exists.
This is ok on my computer.
I create a setup version for production version. The program setup is ok.
But when I start the program (.exe) my db file is not created.
This is the connection string I used :
static string dbDirectopry = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
static string dbName = "MySqliteDb.db";
static string Connexion = Path.Combine(dbDirectopry, #"MySociety\MyApplication\" + dbName);

Hi thanks for your help,
this is the code that create db.
public static void CreateDb(string path)
{
SqLiteHelper sqlite = new SqLiteHelper(path);
try
{
User.CreateTable();
}
catch (Exception e)
{
throw e;
}
}
Normaly if the file doesn't exists he is automaticaly created.
If I try my application in Debug mode with Visual Studio my db is created and I can write into.
But when I deploy my application it doesn't work anymore.
My problem is is there any special directory (for windows) to create de db file?

Related

ODI 12c Smart Import into Exec Repository with SDK behave like importing into Dev Repository

I try to smart import an XML file generated from an Exec Repository via ODI client to another Exec Repository with the SDK. I am using ODI 12.2.1.4.
I already had a java program that was working fine in 11g (11.1.1.9) but since I upgraded to 12, I have errors (I made some changes to the code due to the new version).
Smart importing the xml file to the Exec Repository with ODI studio is working fine so the file seems okay.
The error given by the program is :
oracle.odi.impexp.smartie.OdiSmartImportException: com.sunopsis.dwg.SQLWorkReposException: ORA-00942: Table ou vue inexistante
Caused by: Error : 942, Position : 14, Sql = SELECT 1 FROM SNP_VAR WHERE I_PROJECT IS NULL AND VAR_NAME = 'CONN_DEC_USER', OriginalSql = SELECT 1 FROM SNP_VAR WHERE I_PROJECT IS NULL AND VAR_NAME = 'CONN_DEC_USER', Error Msg = ORA-00942: Table ou vue inexistante
According to the Oracle support, it is totally normal that my Exec repository doesn't have the table SNP_VAR, it is only in Dev repository.
What is strange is that the smart Import makes this request on it. It seems to me that the smartImport is acting like working with a Dev Repository (just guessing)
My code :
private String TargetUrl = "jdbc:oracle:thin:#";
private String TargetDriver="oracle.jdbc.OracleDriver";
private String TargetMaster_User;
private String TargetMaster_Pass;
private String WorkRep_Execution="WORK1";
private String TargetOdi_User="USER";
private String TargetOdi_Pass="PASS";
private String ExportFile;
private MasterRepositoryDbInfo targetmasterInfo;
private WorkRepositoryDbInfo workInfo_exec;
private OdiInstance odiInstance_exec;
private Authentication auth_exec;
private SmartImportServiceImpl smartImport;
private ITransactionManager Tm;
ITransactionStatus TStatus;
SmartImport(String Url, String File, String targetMasterUser, String targetMasterPwd) throws IOException{
TargetUrl = TargetUrl+Url;
ExportFile = File;
TargetMaster_User = targetMasterUser;
TargetMaster_Pass = targetMasterPwd;
targetmasterInfo = new MasterRepositoryDbInfo(TargetUrl, TargetDriver, TargetMaster_User,TargetMaster_Pass.toCharArray(), new PoolingAttributes());
workInfo_exec = new WorkRepositoryDbInfo(WorkRep_Execution, new PoolingAttributes());
odiInstance_exec=OdiInstance.createInstance(new OdiInstanceConfig(targetmasterInfo,workInfo_exec));
auth_exec = odiInstance_exec.getSecurityManager().createAuthentication(TargetOdi_User,TargetOdi_Pass.toCharArray());
odiInstance_exec.getSecurityManager().setCurrentThreadAuthentication(auth_exec);
smartImport = new SmartImportServiceImpl(odiInstance_exec);
Tm = odiInstance_exec.getTransactionManager();
TStatus = odiInstance_exec.getTransactionManager().getTransaction( new DefaultTransactionDefinition());
}
smartImport.importObjectsFromXml(ExportFile, "MyPassword".toCharArray(), false);
The master repository I am working on has only one work repository (called "WORK1") which is an execution repository.
Any clue on what is wrong ?
Thanks
PEB
Thanks to JeromeFR suggestion, I found a workaround for my issue using Deployment Archives instead of Smart Export/Import.
It works fine exporting my archive from my dev repository (through ODI client) and importing to my Exec repositories via java skd (I have several exec environments)
The code for importing the archive in replacement for the smartImport :
DeploymentService.applyFullDeploymentArchive(odiInstance_exec, "EXEC_Init.zip", true, "Password".toCharArray(), true);
Thx
PEB

Windows Forms save to dataset but not table [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.

Create persistent Sqlite db in Windows phone 8

I am trying my hands on Windows phone 8 applications and I am stuck into a weird situation here. I am using sqlite in order to create sqlite db and add values into the database. I am able to create the database and add the values in the database successfully but I am having a weird situation here.
Everytime I close the emulator and start the project again the database gets created again which should not be happening because I created the db the very first time I run the application.
Does anybody know why, and how I can prevent it from recreating the database each time?
public string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "aa.sqlite"));
private SQLiteConnection dtCon;
public MainPage()
{
InitializeComponent();
CreateDatabase();
dtCon = new SQLiteConnection(DB_PATH);
var tp = dtCon.Query<Contacts>("select * from contacts").ToList();
}
private async void CreateDatabase()
{
bool isDatabaseExisting = false;
//Checking if database already exists
try
{
Windows.Storage.StorageFile storagefile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("aa.sqlite");
isDatabaseExisting = true;
}
catch
{
isDatabaseExisting = false;
}
//if not exists then creating database
if (!isDatabaseExisting)
{
String str = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "sqlite.db");
AddDataToDB(DB_PATH);
}
}
private void AddDataToDB(string str)
{
// Create the database connection.
dtCon = new SQLiteConnection(str);
// Create the table Task, if it doesn't exist.
dtCon.CreateTable<Contacts>();
Contacts oContacts = new Contacts();
oContacts.Name = "dfgdf";
oContacts.Detail = "asdfsf";
dtCon.Insert(oContacts);
}
I'm pretty sure when you close your emulator and restart, you're basically just uninstalling the application. Which is why your files or not there anymore -- as it looks like you're storing your data in isolated storage. I do not know if there is anyway around this.
You can buy a very cheap Windows 8/8.1 Phone and the files will persist until you manually uninstall the test application.
As #Chubosaurus says, closing and re-opening the emulator will remove all the apps. You can generally keep it running as long as you want and keep re-deploying your app to the emulator (although obviously rebooting the host PC will kill it).
You can save and restore the data from your emulator image via the ISETool command. See more here
Try adding Console.WriteLine("True"); and Console.WriteLine("False"); into the expected places after checking isDatabaseExisting to see/understand what the code path really is.

Create a SQLite database with Monotouch - permission denied

I am trying to create a Sqlite database using Monotouch 3.0.3.4. Everything works fine on the iPhone simulator, but I get the following error on the test iPhone:
DataLayer.CreateDatabase Exception: System.UnauthorizedAccessException: Access to the path "/private/var/mobile/Applications/4B4944BB-EC37-4B0C-980C-1A9B60DACB44/TestApp.app/myDatabase.db3" is denied.
Here is the code I am using:
// creates database and tables if they do not exist.
public void CreateDatabase ()
{
string sql = string.Empty;
string dbFileName = "myDatabase.db3";
try {
if (!File.Exists (dbFileName)) {
// create database
SqliteConnection.CreateFile (dbFileName); //This is where the error occurs
Console.WriteLine ("CreateDatabase: Database created.");
...
}
catch (Exception ex) {
Console.WriteLine ("CreateDatabase Exception: " + ex.ToString ());
}
...
I have also tried specifing the personal folder, but that has no effect. What do I need to do to make sure permissions are correct?
Thanks!
Monotouch 3.0.3.4
That's likely MonoDevelop 3.0.3.4. See About MonoDevelop to get the MonoTouch version.
"/private/var/mobile/Applications/4B4944BB-EC37-4B0C-980C-1A9B60DACB44/TestApp.app/myDatabase.db3"
On devices the applications are signed, so their content can't change (without breaking the signature). As such you're not allowed to change things in the .app directory.
You should create (or copy) the database in the Documents directory and then open the database as read-write.
See the linked article for more details.

deploying winform application with embedded sqlite

I'm deploying a winform application built with vs 2008 0n XP sp3.
I created a database with empty schema which i dropped in the root folder of the project and in properties i choosed Build Action: Embedded Resources and Copy to Output directory : Copy always. Now instead of having connectionstring in the app.config connectionString section, i put an entry in appSetting: key="database";value="mydb.db;Version=3".
So to create my connectionString i used :
SQLiteConnection con = new SQLiteConnection("Data Source=" + Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["database"]));
Everything works fine and i packaged the app with a setup project.Now after i installed the app the database could not be found and i was obliged to copy the database to the Application Folder in the setup project for it to work.
what i thought is that db is supposed to be in the app dll because of copy always .but i can't access it.So what exactly did i do wrong?
i'm suspecting i should have just connected to the root db meaning not using Application.StartupPath
But i'm here asking for the best practices cause what i did is working but still looking like workaround so please can anyone share his experience with me?
thanks for reading
Embedded Resource means the database gets embedded in your dll. The Copy to output directory setting doesn't apply in this case, that's used for Build Action: Content.
With the database embedded, you basically have to un-embed it on first use. To do this read it out of the Assembly and store it to a file.
class EmbeddedResourceTest
{
public static void Test()
{
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Test.db");
using(var resourceStream = typeof(EmbeddedResourceTest).Assembly.GetManifestResourceStream("Test.db"))
{
using(var fileStream = File.OpenWrite(path))
{
CopyStream(resourceStream, fileStream);
}
}
// now access database using 'path'
}
public static void CopyStream(Stream inputStream, Stream outputStream)
{
CopyStream(inputStream, outputStream, 4096);
}
public static void CopyStream(Stream inputStream, Stream outputStream, int bufferLength)
{
var buffer = new byte[bufferLength];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, bufferLength)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
}
}

Resources