Replace/overwrite local SQLite database file [WP8] - sqlite

I' ve got a local pre-populated SQLite database file in my main project folder from which I get the needed data in my application. I establish a connection using:
SQLiteAsyncConnection conn = new SQLiteAsyncConnection("mydb.sqlite");
This file gets somehow updated (not locally & not by me or the user) so, after checking for new versions in my application, I have to overwrite my .sqlite file with the new one I download for that purpose.
(Also, there is a property called 'Build Action' which needs to be changed after adding a new db file.)
Is that possible? If so, have you got any suggestions?
edit:
I've managed to store the downloaded file in LocalStorage and then tried to copy and replace my database using this code:
StorageFile originalFile = await
ApplicationData.Current.LocalFolder.GetFileAsync("mydb.sqlite");
StorageFile downloadedFile = await ApplicationData.Current.LocalFolder.GetFileAsync("mydb2.sqlite");
await downloadedFile.CopyAndReplace(originalFile);
Now I'm getting this error:
'Windows.Storage.StorageFile' does not contain a definition for 'CopyAndReplace' and no extension method 'CopyAndReplace' accepting a first argument of type 'Windows.Storage.StorageFile' could be found
It's strange because it works fine in a new project I created. Could that be a conflict in the assembly references?

Related

Unable to open SQLite database file from local data store of UWP app

I'm using this section of this official MSDN tutorial: Use a SQLite database in a UWP app but I'm getting the following error:
REMARK: There are many online posts related (or similar) to this issue but none seems to have a solution. Most of these posts are a few years old so I thought this issue would have been resolved by now. Moreover, the above mentioned tutorial is using .NET Standard Class library project, as well. And the online posts regarding the issue do not have .NET Standard involved. So, I was wondering if the issue is caused by the use of .NET Standard library. Regardless, a solution will be greatly appreciated.
SQLite Error 14: 'unable to open database file'
Error occurs at line db.Open() of this code:
public static void InitializeDatabase()
{
using (SqliteConnection db =
new SqliteConnection("Filename=sqliteSample.db"))
{
db.Open();
String tableCommand = "CREATE TABLE IF NOT " +
"EXISTS MyTable (Primary_Key INTEGER PRIMARY KEY, " +
"Text_Entry NVARCHAR(2048) NULL)";
SqliteCommand createTable = new SqliteCommand(tableCommand, db);
createTable.ExecuteReader();
}
}
NOTES:
The line just below the above code reads: This code creates the SQLite database and stores it in the application's local data store. That means the app should have access to that local data store.
I'm using latest version 16.3.5 of VS2019 on Windows 10. The target version on the project is selected as Windows 10 1903 and min version as Windows 10 1903
UPDATE
This similar official 3 years old sample works fine. So, the problem seems to be related to newer versions of .NET Core. But I need to use latest version of .NET Core for other features my app is using that are not available in the older versions.
I also tried this similar old tutorial, but it did not on new version of .NET Core work either - giving exact same error.
The old problem reported in 2016 here to Microsoft seems to have resurfaced again with the new version of .NET Core.
This is a misunderstanding, SqliteConnection db = new SqliteConnection("Filename=sqliteSample.db") can not create a Sqlite file, but access the existing Sqlite database file through the path.
So you need to create a valid sqliteSample.db file and place it in the root directory of the UWP project. Select the content in the Properties -> Build operation to ensure it will be loaded into the application directory.
Update
Please create the sqliteSample.db file in LocalFolder first.
await ApplicationData.Current.LocalFolder.CreateFileAsync("sqliteSample.db", CreationCollisionOption.OpenIfExists);
Then use the path to access the database file
string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "sqliteSample.db");
using (SqliteConnection db =
new SqliteConnection($"Filename={path}"))
{
// ...
}
Best regards.

Cant find sql lite file on android

I created a SQL Lite database and embbed in my app as a android asset the question is where the heck is the file stored on the device I used the following code to access the database
public Database()
{
var path = Path.Combine(System.Environment.
GetFolderPath(System.Environment.
SpecialFolder.Personal), "StockApp.db");
Console.Write("OPening Database dbPath" + path);
database = new SQLiteAsyncConnection(path);
}
When I search for the file i cannot find it but when I use the internal debugger it puts the file at the following location.
It finds it fine and it does place a row in the table
path "/data/user/0/com.companyname.StockApp/files/StockApp.db" string
But where is the actual file I have a STK7 DEVICE for testing so Do any ideas?

How can I install a database in a titanium alloy project?

I have been trying to install a tiny simple database into my titanium project with the code from the documentation and trying different tweaks as suggested by a variety of sources. But I cannot get it to work, I get errors like "no such table" or resultset is null. Currenty my code looks like this:
var db = Ti.Database.install('../assets/exercises.db', 'exercisesDB');
Ti.API.info('installed '+ db.getName() );
db.close();
Ti.API.info('closed db' );
db = Ti.Database.open('exercisesDB');
Ti.API.info('reopened db' );
//Ti.API.info(db.getName() );
var exercisesDBRS = db.execute('SELECT id,name FROM exercise');
I have tried putting the database file exercises.db in the assets folder and in the Resources folder but I'm getting no where. I created the db file with "DB Browser for SQLite" ver 3.9.1 on OSX Sierra - is it compatible with appcelerator alloy projects? My current code produces the error "no such table" on the execute call. I assure you the db file has an exercise table.
PS, full code in new projects index.js file is as follow:
var db = Ti.Database.install('exercises.sqlite', 'exercisesDB');
Ti.API.debug('installed '+ db.getName() );
db.close();
Ti.API.debug('closed db' );
db = Ti.Database.open('exercisesDB');
Ti.API.debug('reopened db' );
var exercisesDBRS = db.execute('SELECT id, name FROM exercise');
Ti.API.debug('executed select');
Ti.API.debug(' rowcount== '+ exercisesDBRS.rowCount);
while (exercisesDBRS.isValidRow()) {
var exId = exercisesDBRS.fieldByName('id');
var exName = exercisesDBRS.fieldByName('name');
Ti.API.debug("Exercise: "+exId + ' ' + exName );
exercisesDBRS.next();
}
exercisesDBRS.close();
db.close();
function doClick(e) {
alert($.label.text);
}
$.index.open();
New project but same code and a copy of the same database file in the app/lib folder. Same error - no such table on the execute line when tested in android, works fine in iOS sim.
As per the docs, your external database should be located at the same place where you are running the below code:
var db = Ti.Database.install('../assets/exercises.db', 'exercisesDB');
There's no need to use ../assets/. You can simply refer the database without it because everything you put in assets folder is moved to respective Resources->iphone/android folder.
You can always use Ti.Database.install method for external database because after installing a database once, it will behave like Ti.Database.open('exercisesDB') method.
Coming to your primary concern, you can always safely put your database file in app -> lib folder (create lib folder if it's not present and put db file in there then).
After putting the db file there, you can always use below code:
var db = Ti.Database.install('exercises.db', 'exercisesDB');
Though, I have never used .db extension, instead I have always used .sqlite format (since docs also says SQLite database) and it has worked 100% correct every time.
So you can try this process by changing the database format to .sqlite and put it in app->lib folder. It will definitely work and after verifying you can use same code on using a .db file and see if it's supported or not.
On Android: Follow these steps:
1- In your PC, go to the project's root directory, delete build and Resources folders.
2- On device, clear app data from Settings and then delete the app.
3- Now install the app again with the same code and flow as I mentioned here.
If it's working fine for iOS sim, then it should also work for Android (only some cleaning issues are there or your previous database is still there).

Entity Framework migration: access sql file within ASP.NET

I have a ASP.NET Web API project. I'm using Entity Framework Migrations. Currently, I have a custom script that is to be executed during a migration. I'm using the SqlFile method for this:
SqlFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Migrations/Scripts/MyCustomScript.sql"));
This works fine in the integration tests, IF I set the "Copy to Output Directory" of the script to "Copy always".
However, when running the website, the script is copied to <websiteroot>\bin\Migrations\MyCustomScript.sql, while AppDomain.CurrentDomain.BaseDirectory points to the websiteroot. Therefore, an error is thrown stating that the script cannot be found: it resides in the bin folder, not in the root.
How can I load the script so that things work both in the tests and in the actual website?
I would include the script in you dll and than load the script from the dll directly. Than you do not need any if statements and you always know you have the correct scripts included. Set the build action to Embedded resource. Then you can get the script like:
Assembly assembly = Assembly.LoadFile(dll);
using (Stream stream = assembly.GetManifestResourceStream(resourcepath))
using (StreamReader reader = new StreamReader(stream))
{
string script = reader.ReadToEnd();
I would fix it this way (it's not the best way, but it's a way)
string sqlfilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Migrations/Scripts/MyCustomScript.sql");
if (!File.Exists(sqlfilepath))
sqlfilepath = "your other path where it might exist";

How to use pre-designed SQLite in UWP project?

I have a SQLite database from another project and I want to use it in a UWP application. But I don't know how to import this database to the project and!
I can create a new Database and use it but I don't know how to copy database file from project. I use from SQLite.Net-PCL nuget package.
For how to access an exist file, there are two locations that all apps can access. Details please reference the file-access-permissions.
One is Application install directory. As #Henk Holterman said, you can import your existed database file into your project by right-click one folder and select Add->Existing item to add your database file to the project. Pay attention the file's Build action property need to be set to content. Details please see the following picture.
Suppose you already had a database file Sun.db added to the Assets folder, and now you can connect to it by the following code( use the SQLite.Net-PCL Nuget Package).
path = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, #"Assets\Sun.db");
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
}
But this folder is read only. Another location is Application data locations which can read/write. You can copy the database file from install directory to the application data directory for using. The following code example is for connecting a database file that in the local folder.
StorageFile file;
try
{
file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Sun.db");
}
catch
{
StorageFile Importedfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Sun.db"));
file = await Importedfile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
}
path = file.Path;
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
{
conn.CreateTable<User>();
}

Resources