Local Database Samples in Windows Phone 7? - windows-phone-7

Any Samples on Local Database in windows Phone 7?i haven't work on it till now.So,
Please give some idea on that.How to save data in windows phone 7.

There are some good examples on the internet:
Simple WP7.1 local databases
WP7 Mango Local Database Support

The official documentation is quite rich in this area (apologies for the link dump):
How to: Create a Basic Local Database Application for Windows Phone
How to: Create a Local Database Application with MVVM for Windows Phone
How to: Deploy a Reference Database with a Windows Phone Application
Walkthrough: Updating a Local Database Application for Windows Phone
There are also good overview documentation:
Local Database Overview for Windows Phone
Local Database Best Practices for Windows Phone
Local Database Migration Overview for Windows Phone

First we have to create local database table.
namespace DatabaseSample.Db
{
[Table]
public class tblStudentDetails
{
[Column(CanBeNull = false)]
public string name
{
get;
set;
}
[Column(CanBeNull = false)]
public string std
{
get;
set;
}
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int id
{
get;
set;
}
}
}
After that we can create a database context
namespace DatabaseSample.Db
{
public class dbDataContext : DataContext
{
public dbDataContext(string connectionString)
: base(connectionString)
{
}
public Table<tblStudentDetails> studentDetails
{
get
{
return this.GetTable<tblStudentDetails>();
}
}
}
}
After that we can connect to the database and can insert value to the table
public class ConnectTable
{
private const string Con_String = #"isostore:/Db.sdf";
public ConnectTable()
{
using (Db.dbDataContext context = new Db.dbDataContext(Con_String))
{
if (!context.DatabaseExists())
{
// create database if it does not exist
context.CreateDatabase();
}
}
}
#region StudentDetails
public void AddToTableSDetails(string name,string standard)
{
using (Db.dbDataContext context = new Db.dbDataContext(Con_String))
{
Db.tblStudentDetails sd = new Db.tblStudentDetails();
sd.name = name;
sd.std = standard;
context.studentDetails.InsertOnSubmit(sd);
context.SubmitChanges();
}
}
public IList<Db.tblStudentDetails> GetSDetails()
{
IList<Db.tblStudentDetails> sList = null;
using (Db.dbDataContext context = new Db.dbDataContext(Con_String))
{
IQueryable<Db.tblStudentDetails> stQuery = from c in context.studentDetails select c;
sList = stQuery.ToList();
}
return sList;
}
/* public void DeleteSDetails()
{
using (Db.dbDataContext context = new Db.dbDataContext(Con_String))
{
IQueryable<Db.tblStudentDetails> stQuery = from c in context.studentDetails select c;
foreach (var value in stQuery)
{
context.studentDetails.DeleteOnSubmit(value);
}
context.SubmitChanges();
}
}*/
#endregion
}

Related

Dynamo DB .Net Object Persistence Model Not working When Hosted to AWS Lambda

I am using the .Net object persistence model to store item into Dynamo DB. It is working fine on my machine, but when I publish the project to AWS lambda service nothing is storing into database.
Please help.
I fix the issue by setting "IgnoreValue" to true in DynamoDBContextConfig. Remove the context.SaveAsync(model) from the code. below is the working code sample.
[DynamoDBTable("User")]
public class UserModel
{
[DynamoDBHashKey]
public int ID { get; set; }
[DynamoDBRangeKey]
public string Class { get; set; }
[DynamoDBProperty]
public string Name { get; set; }
}
After initializing above model below is code to insert item into DynamoDB.
public async Task InsertRecord(UserModel model)
{
try
{
using( var context = new DynamoDBContext(client, new DynamoDBContextConfig { ConsistentRead = true, SkipVersionCheck = true,IgnoreNullValues=true }))
{
var dataContext = context.CreateBatchWrite<UserModel>();
dataContext.AddPutItem(model);
await dataContext.ExecuteAsync();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException.StackTrace.ToString());
}
}

SQLite-net-pcl not working properly on Android 7.0 (Xamarin)

SQLite-net-pcl seem's to work on all platforms except Android 7.0.
So far on Android 7.0 from a fresh install the application will crash due to an SQLException with the issue that it can't create a PK. If I uninstall the applications storage I.e. wipe the app from application settings, the app then works perfectly.
All other platforms seem to install instantly. See for youself https://play.google.com/store/apps/details?id=com.purewowstudio.fivestartips
I cannot seem to fix this. Worst of all, my iOS which shares a DB PCL doesn't load at all.
Does anyone know how to fix this?
Code example:-
Object
using System;
namespace App.LocalObjects
{
[Preserve(AllMembers = true)]
public class LocalArticle
{
[SQLite.PrimaryKey, SQLite.Column("articleObjectId")]
public string objectId { get; set; }
public DateTime createdAt { get; set; }
public DateTime updatedAt { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public int Status { get; set; }
public LocalArticle()
{
this.objectId = " ";
this.Title = " ";
this.Description = " ";
this.Url = " ";
}
}
}
Database
using System;
using System.Linq;
using System.Collections.Generic;
using SQLite;
using App.LocalObjects;
namespace App.DataLayer
{
public class Database
{
static object locker = new object();
public SQLiteConnection database;
public string path;
public Database(SQLiteConnection conn)
{
database = conn;
database.CreateTable<LocalArticle>();
}
public int SaveLocalArticleItem(LocalArticle item)
{
lock (locker)
{
LocalArticle article = database.Table<LocalArticle>().FirstOrDefault(x => x.objectId == item.objectId);
if (article != null && article.objectId.Equals(item.objectId) && !article.updatedAt.Equals(item.updatedAt))
{
database.Update(item);
return item.ID;
} else {
return database.Insert(item);
}
}
}
Code to initialize DB:
using System;
using System.IO;
using Android.App;
using App.BusinessLayer.Managers;
using App.BusinessLayer.ParseObjects;
using App.Utils;
using Android.Content;
using Com.Nostra13.Universalimageloader.Core;
using Com.Nostra13.Universalimageloader.Core.Assist;
using Android.Graphics;
using Com.Nostra13.Universalimageloader.Cache.Memory.Impl;
using Com.OneSignal;
using Parse;
using SQLite;
namespace App.Droid
{
[Application(LargeHeap = true)]
public class App : Application
{
public static App Current { get; private set; }
public ModelManager modelManager { get; set; }
private SQLiteConnection conn;
private ImageLoader imageLoader;
public App(IntPtr handle, global::Android.Runtime.JniHandleOwnership transfer)
: base(handle, transfer)
{
Current = this;
}
public override void OnCreate()
{
base.OnCreate();
SetupParse();
SetupDB();
}
private void SetupParse()
{
ParseObject.RegisterSubclass<ParseArticle>();
ParseClient.Initialize(new ParseClient.Configuration
{
ApplicationId = Constants.ParseApplicationID,
Server = Constants.ParseServer
});
}
private void SetupDB()
{
var sqliteFilename = Constants.DBName;
string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = System.IO.Path.Combine(libraryPath, sqliteFilename);
conn = new SQLiteConnection(path);
modelManager = new ModelManager(conn);
}
Here's what my project is currently referencing:-
Android N began actually enforcing rules around accessing the SQLite libraries that come with Android. Therefore any app (or app library) that was previously directly accessing SQLite without going through the special Java wrapper was already breaking the rules technically, the reason it was not a problem was because Android never really enforced those rules. Read more about that here
Now that Android N does enforce those rules, it causes the crash to occur. I am guessing that you are using the SQLite.Net-PCL library for accessing your SQLite DB. If you look here there is an open issue for that exact problem that the library creators never fixed.
We ran into the same issue and have since switched to the SQLite-Net-PCL library (notice the dash instead of the period) which works the exact same way and has an almost identical API. A link for that library can be found here.
i have same issue. i install this package for sqlite and set targeted version to android 8(oreo) my application works again

SQLite.Net Update generating error "it has no PK"

I'm using Lync syntax in a PCL using Xamarin.
public class settings
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string user_name { get; set; }
public string password { get; set; }
public string server { get; set; }
}
void CreateTables()
{
database.CreateTable<settings>();
}
void Insert()
{
settings s = new settings();
s.server = "<none>"
s.user_name = "";
s.password = "";
database.Insert(s)
}
void Update()
{
settings s = database.Table<settings>().FirstOrDefault();
s.server = server_address.Text;
s.user_name = user_name.Text;
s.password = pass.Text;
database.Update(s)
}
I get "Cannot update settings: it has no PK" when updating, but inserting works fine. I'm using Xamarin in a PCL referencing SQLite.net. I'm new to SQlite and Xamarin, so please be verbose when asking for more detail.
UPDATE - RESOLVED
The class is in the same namespace as the place I create an instance of the database object. Simply adding the "Sqlite" to my attribute fixed the issue which is really strange.
[SQLite.PrimaryKey, SQLite.AutoIncrement]
I have been stocked for a week now on this problem and even the above solution is not working for me...
I think that the Id does not increments automatically, that's why it says :cannot update ...
What actually works for me is incrementing the PK (Id) manually...as follows.
persons.Id++;
At the moment of verifying and inserting data into the database, I just added the above code and it updated successfully.
private async void Register_Student(object sender, EventArgs e){... ...
if(!string.Equals(newPassword.Text, rePassword.Text)){
warningLabel.Text = "Enter same pwd"; ...
}
else{
persons.Id++; //solution that worked for me at insertion level
persons.UserName = newUsername.Text; //Text entered by the user
}...
}
Thanks...

MvvmCross plugin for setting up Alarms

I want to write a cross mobile platform app that sets up the alarm by specifying the required parameters like Date and Time. I just want to set up only one time and not repeatedly.
I was unable to find any readily available plugin in mvvmcross or in Xamarin ?
Please help
Since there is no existing plugin within MVVMCross, you may want to write your own plugin. You can find the documentation here:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins
Because you'd like to specify a few parameters, you'd want to see the following section:
https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#writing-a-configurable-plugin
Overall this is what you might do:
General Interface
public interface IAlarm
{
void SetupAlarm();
}
public class PluginLoader
: IMvxPluginLoader
{
public static readonly PluginLoader Instance = new PluginLoader();
public void EnsureLoaded()
{
var manager = Mvx.Resolve<IMvxPluginManager>();
manager.EnsurePlatformAdaptionLoaded<PluginLoader>();
}
}
Android Implementation
public class DroidAlarmConfiguration
: IMvxPluginConfiguration
{
public AlarmLength { get; set;}
}
public class DroidAlarm : IAlarm
{
public TimeSpan AlarmLength { get; set; }
public void SetupAlarm()
{
//ALARM IMPLEMENTATION HERE. NOTE THIS IS SOME JAVA SYNTAX!!!!
var globals = Mvx.Resolve<Cirrious.CrossCore.Droid.IMvxAndroidGlobals>();
var alarm = globals.ApplicationContext
.GetSystemService(Context.ALARM_SERVICE)
as AlarmManager;
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
alarmLength, alarmIntent);
}
}
public class Plugin
: IMvxPlugin
{
private _alarmLength = **Your Value Here**;
public void Configure(IMvxPluginConfiguration configuration)
{
if (configuration == null)
return;
var droidConfiguration = (DroidAlarmConfiguration)configuration;
_alarmLength = droidConfiguration.AlarmLength;
}
public void Load()
{
var instance = new DroidAlarm();
instance.AlarmLength = _AlarmLength;
Mvx.RegisterSingleton<IAlarm>(instance);
}
}
Setup.cs - To set the values in one core place for all android/ios/windows
protected override IMvxPluginConfiguration GetPluginConfiguration(Type plugin)
{
if (plugin == typeof(Yours.Alarm.Droid.Plugin))
{
return new Yours.Alarm.Droid.DroidAlarmConfiguration()
{
AlarmLength = **YOUR VALUE HERE**
};
}
return null;
}
You would then follow the same Droid step for iOS and Windows Phone. I hope this helps!

Insertion operation in SqlCe in windows phone

I am trying to insert some data into mydatabase but getting error like "Can't perform Create, Update, or Delete operations on 'Table(Dic)' because it has no primary key."
My database name is "condrokotha_new.sdf" and it has a table named "dic" which have 2 columns named "english" and "bangla". I made this database in another C# project in vs 2010. Then i used this database into my windowsphone project. I can show data from database but when i try to insert data i am getting error.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
condrokotha_newContext db = null;
// Constructor
public MainPage()
{
InitializeComponent();
db = new condrokotha_newContext(condrokotha_newContext.ConnectionString);
db.CreateIfNotExists();
db.LogDebug = true;
}
private void fav_Click(object sender, RoutedEventArgs e)
{
add_new_words("cintakhela","ami");
}
private void add_new_words(string e_word,string b_word)
{
using (condrokotha_newContext context = new condrokotha_newContext(condrokotha_newContext.ConnectionString))
{
Dic d = new Dic();
d.English = e_word;
d.Bangla = b_word;
context.Dics.InsertOnSubmit(d);
context.SubmitChanges();
}
}
}
My data context code like these :
public static string ConnectionString = "Data Source=isostore:/condrokotha_new.sdf";
public static string ConnectionStringReadOnly = "Data Source=appdata:/condrokotha_new.sdf;File Mode=Read Only;";
public static string FileName = "condrokotha_new.sdf";
public condrokotha_newContext(string connectionString) : base(connectionString)
{
OnCreated();
}
#region Extensibility Method Definitions
partial void OnCreated();
#endregion
public System.Data.Linq.Table<Dic> Dics
{
get
{
return this.GetTable<Dic>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dic")]
public partial class Dic
{
private string _English;
private string _Bangla;
public Dic()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="english", Storage="_English", DbType="NVarChar(1000)")]
public string English
{
get
{
return this._English;
}
set
{
if ((this._English != value))
{
this._English = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="bangla", Storage="_Bangla", DbType="NText", UpdateCheck=UpdateCheck.Never)]
public string Bangla
{
get
{
return this._Bangla;
}
set
{
if ((this._Bangla != value))
{
this._Bangla = value;
}
}
}
}
`
How can i insert my data into my database??
Is there anyone who can help in this??
For example you have this
SampleDataContextDataContext db = new SampleDataContextDataContext();
Employee emp = new Employee() {
FirstName = "Experts",
Lastname = "Comment",
Address = "rs.emenu#gmail.com"
}
db.Employees.InsertOnSubmit(emp);
db.SubmitChanges();
The above code will give you same error when u try to insert a new row. The reason is that LINQ does not provide the facility to insert data into a table without a primary key. At this point you have two options.
1.Create a store procedure and call it from LINQ.
SampleDataContextDataContext db = new SampleDataContextDataContext();
db.InsertEmployeeData("Experts","Comment", "rs.emenu#gmail.com");
Here InsertEmployeeData is a a stored procedure, and called it from the code.
2.Create an insert statement and execute using LINQ.
SampleDataContextDataContext db = new SampleDataContextDataContext();
string insertStatement = "Insert into Employee values('Experts', 'Comment','rs.emenu#gmail.com')";
db.ExecuteQuery<Employee>(insertStatement);
Here insert query is normal sql query and executed using the the LINQ ExecuteQuery method.

Resources