my sqlite3 DB doesn't show column values in device but it does in simulator - ios

My DB is not getting copied over to my device, but it does to the simulator.
Here is what I am doing:
Create a new sqllite3 db from terminal:
sqlite> create table myTable (id integer primary key, name text);
sqlite> insert into myTable (name) values ('john');
sqlite> select * from myTable;
1|john
This creates a db in this path: users/John/iosApp.db
Then I close the terminal and copy that db to my xamarin project and set its buildAction to 'content'.
Here is my model:
[Table("myTable")]
public class MyTable
{
[PrimaryKey, AutoIncrementAttribute, Column("id")]
public int ID {get; set;}
[Column("name")]
public string Name { get; set; }
}
And I do this to copy the db to the Document folder:
string pathToDatabase = "iosApp.db";
userPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), pathToDatabase);
File.Delete (userPath); // delete first and copy next
File.Copy (pathToDatabase, userPath);
var myDB = new SQLiteConnection (userPath);
MyTable myTable = myDB.Get<MyTable> (1);
then I run the app and I set a breaking point after the last line in the code above and I hover over the myTable:
if I am using the simulator, I see the schema and value of 1 for ID and 'john' for Name.
if I am using the device, I see the schema but 0 value for ID and null for Name!
Looking at the path when I am using the device, points to this:
"/private/var/mobile/Applications/277749D4-C5CC-4BF4-8EF0-23B23833FCB1/Documents/iosApp.db"
I loaded the files in using iFunBox and the db file is there with the exact size
I have tried all the following:
Clean All in the project
Rebuild All
removed the 'debug' folder from the project
restarted Xamarin
and even restart the machine
But still the same behavior, what else should I try to be able to see the values of ID and Name?
my sdk version is attached
UPDATE:
After a lot of changes and cleaning up, I managed to display the value of all columns except the identity column displayed as 0. Puzzled, I went back to the xamarin sample project: http://developer.xamarin.com/recipes/ios/data/sqlite/create_a_database_with_sqlitenet/
it displayed the value of the identity correctly.
Trying to bring in similar code to my project, but no success.
To role out the possibility of version issue, I went and downloaded the latest sqlite from this link:
http://components.xamarin.com/gettingstarted/sqlite-net/true
The same behavior... I created a whole new page in my project, used the references the sample used and only has the code to create a sample table. Same behavior, the identity value is displayed in the other project but not mine. This leads me to conclude that there is something completely is wacky in my project. Now I am considering creating a whole new project and move my files to the new one after making sure first that the piece of being able to see the value of my id in my model shown up. Stay toned, I will make sure to update this thread.
If you have any pointers, please share them

I couldn't find a solution to my problem, but I found an alternate method to create the DB that turns out to be even nicer than the original one.
One important thing to note is that in the original problem (details above), the DB code was working for months since I started developing the application. I don't know when it started behaving badly, but I suspect it was due to the download of the new Xamarin 3.0. I can't think of any other reason.
So, to solve my issue, There are two main things I did:
I followed this link on how to create DB and tables and do CRUD operations: http://components.xamarin.com/gettingstarted/sqlite-net/true
This method seems to be the newest way to create DB. It was: published on
June 24, 2014. It has an SQLite.dll, whereas my previous solution was using a SQLite.cs file. So, now I am creating my DB now at runtime.
Something didn't work still with the new method. It was giving me an object null exception error. I didn't spend much time investigating about it. When I provided values for my primary key and identity values, the error went away. Actually, this could have been the solution to my previous problem. I would have tried providing the identity values against the old code, if I am not already happier with the new method.
I hope this helps someone.

Related

Model field value always null - EF5

I have an integer that is set in my DB but it is always null when running, whether in a view or controller.
Here is my code:
#if(Model.DefaultTerrain == null)
{
//do something
}
else
{
//do other thing
}
The app reads the correct database.
DefaultTerrain is a nullable integer in the Project table, it shows in the edmx file.
Other fields are OK.
This is not a coding issue, rather a configuration issue I believe (this code works in production; I checked out the project from a repo and am now testing on my local machine for improvements).
EF5, IIS 8
Thanks
In VS using the edmx file, I refreshed the Project table from the database then re-published the app and that fixed it.

property mapping not being associated correctly. Why?

EDIT 1
While I understand that for this particular scenario (and other alike) I could use the mapping editor alone to migrate my store correctly so that the values in the persistent store don't jump around, but that's not a solution to my current problem but only avoids addressing the root of the problem. I am keen on sticking with my custom migration policy as this will give me a lot of control through the migration process, especially for future scenarious where setting up a custom migration policy will work for me. This is for a long term solution and not just for this scenario.
I urge you to try and help me solve the current situation at hand rather than diverting me to lightweight migration or advising me to avoid using a migration policy. Thank you.
I really do look forward to sorting this out and your valuable input/ideas on what I could do to fix this problem.
What I have done:
I have a migration policy set up so that the source data can be copied into the destination data from version 1 of the core model to version 2.
This is the migration policy:
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError **)error {
// Create the product managed object
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:[mapping destinationEntityName]
inManagedObjectContext:[manager destinationContext]];
NSString *productCode = [sInstance valueForKey:#"productCode"];
NSNumber *productPrice = [sInstance valueForKey:#"productPrice"];
[newObject setValue:productCode forKey:#"productCode"];
[newObject setValue:productPrice forKey:#"productPrice"];
//This is the field where the name has changed as well as the type.
[newObject setValue:[NSNumber numberWithBool:YES] forKey:#"productPriceNeedsUpdating"];
// Set up the association between the old source product and the new destination Product for the migration manager
[manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
/*
A test statement to make sure the destination object contains the correct
values int he right properties:
Product description: <NSManagedObject: 0xb983780> (entity: Product; id: 0xb9837b0 <x-coredata:///Product/t97685A9D-09B4-475F-BDE3-BC9176454AEF6> ; data: {
productCode = 9999;
productPrice = "2.09";
productPriceNeedsUpdating = 1;
})
*/
// Set up the association between the old source product and the new destination Product for the migration manager
return YES;
}
So even though the tested properties show the correct values in runtime, the resultant values saved in the data model store is incorrect as seen in the snapshots.
Here is a comparison from version 1 to version 2 of the data store.
Version 1: Correct
to Version 2: Which is now storing the values incorrectly.
The expected output should have the Product price inserted into the productPrice field and not in the ProductPriceNeedsUpdating field which should actually only have boolean values.
Can anyone help me understand what I am doing wrong, or explain whats happening here?
UPDATE 1 - Here are my entity mappings:
Update 2 - 20/aug/2014 01:02 GMT
When I remove the attribute ProductPriceLastUpdated of type date from version 1, and remove the attribute ProductPriceNeedsUpdate of type boolean in version 2, leaving only the two attributes that both match in version 1 and 2, then everything works. Even though I can leave it here and move on, I cant ignore the users that are currently using version 1 of the database which does have that pointless ProductPriceLastUpdated attribute which I need the type converted to boolean and also have the name changed to ProductPriceNeedsUpdate. Thats when things start going weird, and the price values are shown in the ProductPriceNeedsUpdate field instead of the productPrice field.
I hope someone can address the original problem and tell me why it is that the entityMapping, or more so, property mapping is not being saved properly?
Update 3 - EntityMapping and properties:
Version 1
Version 2
Any ideas?
First, if you want to just use a lightweight migration (which you really should in this case) you can get rid of your custom migration policy. In this instance, it's not needed. And, as a matter of fact, you can get rid of your custom mapping model as well. All you need to do is in your Version 2 model, select the productPriceNeedsUpdating boolean flag, and in the Attribute Detail inspector on the right, set the default value to YES. This will achieve the goal you're try to get to with your custom migration policy.
However, if you really need to write this in code with your custom migration policy, I would still not use custom code. You can achieve this migration with only a mapping model. Simply select the ProductToProduct mapping, and in the value expression for productNeedsUpdating, enter YES, or 1.
EDIT
So, after a rather lengthy screen share, it was determined that the migration was using code from Marcus Zarra's Core Data book describing progressively migrating stores. When this was written, WAL mode was not the default mode with Core Data. When WAL mode is enabled, progressively migrating stores don't function well since there are two more files to deal with, the Write Ahead Log, and the Shared Memory file. When simply replacing the old store with a new one, without first removing those files, odd things happen, such as described in this post. The solution ultimately ended up being to disable WAL mode for the progressively migrating scenario so the extra files are not generated in the first place.

Entity Framework 4 SaveChanges Method not saving to database

I'm trying to use Entity Framework 4 for a small database application I'm writing to keep record of downloaded files. When running the application I set a break point after the tableName.Add() method, before the .SaveChanges() method and I can see the data saved into the entity; then I have another break point after calling the .SaveChanges() method, and look into the database to find there is no record saved to it. I have found a lot of similar questions, but I have not found the solution to my particular problem. Here is the code:
public void StartNewDownload(string FileID)
{
DateTime startTime = DateTime.Now;
FilesDBEntities db = new FilesDBEntities();
int startedID = (from dr in db.tblDownloadResults
where dr.Value.Equals("Started")
select dr.ResultID).First();
tblDownloads myDownload = new tblDownloads { FileID = FileID, StartDateTime = startTime, ResultID = startedID };
db.tblDownloads.Add(myDownload);
db.SaveChanges();
}
Any help is appreciated.
Thanks!
Pawel, you guided me in the right direction. The entity had the data, but the database I was looking into did not. But after reading your comment I ran the program from Visual Studio and used Process Monitor to monitor any operations to *.sdf files. This helped finding out that upon building the solution, it would create another database file to the bin\Debug folder. I forgot the database Build Action property was set as "Content".
Thanks!!
You can use SQL Server Profiler to see if the entity framework has really called the database.
(The tool is not included in SQL Server Express)

Flex Mobile 4.6 App wont create Database on IOS?

I have been creating Mobile Application in Flex for over a year now and have done many complicated things, however recently something simple that i am trying to do is not working for a new mobile app I am creating.
I simply want to be able to create a sqlite db on the device so i can read and write data to it, to create the database I have used the code below:
sqlConnection = new SQLConnection();
sqlConnection.open(File.documentsDirectory.resolvePath("New.db"));
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = "CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR(90))";
stmt.execute();
Then when I test the App in debug from within Flashbuilder all looks ok for both android and IOS. However when I run the app on the device for some reason the database is not created :-S
This is very odd to me as I am sure I have used the right code as I have used the following code below in another app which is exactly the same as you can see and when i run that app on IOS it creates the database fine :-S :-S
sqlConnection = new SQLConnection();
sqlConnection.open(File.documentsDirectory.resolvePath("Bikes.db"));
var stmt:SQLStatement = new SQLStatement();
stmt.sqlConnection = sqlConnection;
stmt.text = "CREATE TABLE IF NOT EXISTS makes (id INTEGER PRIMARY KEY AUTOINCREMENT, name INTEGER)";
stmt.execute();
stmt.text = "CREATE TABLE IF NOT EXISTS models (id INTEGER PRIMARY KEY AUTOINCREMENT, name INTEGER)";
stmt.execute();
I don't understand why the old app that I have created would work and the new one wouldn't?? Does anyone know if there are any other elements that need to be in place in order to allow me to write this database file to IOS? just to note I have added all permissions to the manifest, i appreciate the help :-)
I'm pretty sure the documentsDirectory is write protected on iOS.
For application specific files, use the File.applicationStorageDirectory instead. You have both read and write access to that directory out of the box, no altering of permissions required.

Mygeneration autonumber field bug with MS Access database

I am using Mygeneration tools to create the abstract classes responsible for dealing with database to perform CRUD operation as well as some other dooDad operations. Problem is I cant retrieve the auto number field (it is also Primary Key) of table using the code
Employees newObj = new Employees();
newObj.ConnectionString = connectionString;
newObj.AddNew();
// Your Properties will be different here
newObj.FirstName = "Joe";
newObj.LastName = "Plank Plank";
newObj.Save();
int staffid=newObj.StaffID;
The same thing is working fine in MS SQL server or other databases. Looks like auto number is not generated instantly which can be accessed once I added the entry. But, later, when I am checking the database, I found that auto number is generated there. Not sure, why this is happening. Anybody having expertise with dooDads, please help with info.
Edited:
The main problem is I cant access the autonumber field instantly after I create the fresh row entry. Looks like MS Access autonumber takes some time to show up and even in VS, you can see this phenomenon. How to fix this problem?
I have built many applications using Doodads , using MS Access , you have only to make the filed as autonumber .. and generate the stored procedures and other classes.
i.e your code should work ..
also I made modification to Dodads to return list of Objects
How to get list of objects from BusinessEntity using myGeneration?

Resources