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

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...

Related

Execute or compile runtime c# code on textbox after changes event - "PlatformNotSupportedException"

I am wondering to provide an option in my application to users to be able to customize buttons in ASP.NET CORE with Blazor.
I mean, C# code can be stored in database, and compiled/executed in runtime.
How can I "provide" an object from razor to be manipulated in this "code stored in the database" and after that, make those changes in runtime, after code been executed?
Please share your ideas.
I already tried some things, like this:
using Blazored.Toast.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.CSharp;using Newtonsoft.Json;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Projeto.Web.Pages.Components {
public class McwEditModel : CustomComponentBase
{
[Inject]
public IToastService ToastService { get; set; }
#region Parameters
[Parameter]
public string nome { get; set; }
#endregion
public void OnTextChanged(string newValue)
{
string source =
#"public class SomeClass {
public int OnTextChanged (string newValue) {
if (!string.IsNullOrEmpty(newValue)) {
ToastService.ShowWarning(newValue);
}
}
} ";
var compParms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, source);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("OnTextChanged");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { newValue });
InvokeAsync(StateHasChanged);
}
}}
The problem is that does not work, particularly I am getting the error "System.PlatformNotSupportedException: 'Operation is not supported on this platform.'" on line
" CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms, source); "
I am using Blazor .NET Core.
Is there any chance or way to achieve what I want?
I solved it using using Microsoft.CodeAnalysis package.
I needed to create a
public class Globals
{
[Inject]
public IToastService ToastService { get; set; }
public string newValue { get; set; }
public dynamic objeto { get; set; }
}
and inside my method I did:
public void OnTextChanged(string newValue){
Aql aql = new Aql { EaqcCodigo = "1", EaqcDescricao = "AQL" };
var globals = new Globals { ToastService = ToastService, newValue = newValue, objeto= aql };
CSharpScript.RunAsync("ToastService.ShowWarning(newValue + \"- desc:\" + objeto.EaqcDescricao + \"- cod:\" + objeto.EaqcCodigo);", ScriptOptions.Default.WithReferences("Microsoft.CSharp"), globals).Wait();
}
with this, now I can pass a dynamic object and also make any codes in a string field on database and retrieve this wherever I want, to customize a lot of things, ie: change of fields (in a custom generic and dynamic component)

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

Debug Mode - LINQ NullReferenceException on Collection Constructor

I think I've found a bug in Visual Studio when you drag-and-drop the break-point to a different branch and you're using a certain type of LINQ query. If you place a breakpoint on the "if (x)" below and drag the executing line to the else branch, the code will fail on the initialisation/constructor for the "test2" collection.
I've used this "double from" syntax in LINQ before to do joins and I assume it's a accepted practice - not sure if there's a term for it.
Anyway can anyone else confirm this strange debug behaviour?
public class TestEntity
{
public int TestID { get; set; }
public string Test { get; set; }
}
public class Test2Entity
{
public int Test2ID { get; set; }
public string Test2 { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
bool x = Calc();
if (x) //breakpoint here
{
int y = 1;
}
else
{
System.Collections.ObjectModel.Collection<TestEntity> test = new System.Collections.ObjectModel.Collection<TestEntity>();
System.Collections.ObjectModel.Collection<Test2Entity> test2 = new System.Collections.ObjectModel.Collection<Test2Entity>(); // fails here
var z = from t in test
from t2 in test2
select t.TestID;
}
}
private bool Calc()
{
return true;
}

Local Database Samples in 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
}

Resources