xamarin sqlite SQLiteException: near ")": syntax error add - sqlite

I am trying to learn xaml and C# used in Xamarin Forms, and now I want to implement SQLite functionality.
I am simply trying to add a value into a SQL table but get the following error:
Unhandled Exception:
SQLite.SQLiteException: near ")": syntax error occurred
My Database connection interface is as follows:
using SQLite;
namespace TestSQLite
{
public interface IDatabaseConnection
{
SQLiteAsyncConnection GetConnection();
}
}
My Android specific Database Connection (iOS is identical) is as follows:
using SQLite;
using System.IO;
using TestSQLite;
using Xamarin.Forms;
[assembly: Dependency(typeof(DatabaseConnection))]
namespace TestSQLite
{
public class DatabaseConnection : IDatabaseConnection
{
public SQLiteAsyncConnection GetConnection()
{
var dbName = "TestDb.db3";
var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dbName);
return new SQLiteAsyncConnection(path);
}
}
}
My MainPage (testpage) is as follows:
using SQLite;
using Xamarin.Forms;
namespace TestSQLite
{
public class ControlledDrugs
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Drug { get; set; }
public double Volume { get; set; }
}
public class Users
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
public partial class MainPage : ContentPage
{
private SQLiteAsyncConnection _connection;
public MainPage()
{
InitializeComponent();
_connection = DependencyService.Get<IDatabaseConnection>().GetConnection();
}
protected override async void OnAppearing()
{
await _connection.CreateTableAsync<ControlledDrugs>();
await _connection.CreateTableAsync<Users>();
var drugs = await _connection.Table<ControlledDrugs>().ToListAsync();
Drugslistview.ItemsSource = drugs;
var user = await _connection.Table<Users>().ToListAsync();
Userlistview.ItemsSource = user;
base.OnAppearing();
}
async void OnAdd(object sender, System.EventArgs e)
{
var user = UserInput.Text;
//The next step generates the error
await _connection.InsertAsync(user);
}
void OnUpdate(object sender, System.EventArgs e)
{
}
void OnDelete(object sender, System.EventArgs e)
{
}
}
}
As you can see, I have yet to progress to update or delete. Learning by Youtube and Stackoverflow snippets is painfully slow. But this error got me stumped.
Also, have NuGet package sqlite-net-pcl v1.5.166-beta installed Xamarin Visual Studio.

you are attempting to insert a string into the User table instead of a User object
var user = UserInput.Text;
// user is just a string
await _connection.InsertAsync(user);
instead you need to create a User object
var user = new Users { Name = UserInput.Text };
await _connection.InsertAsync(user);

Related

How start migrations EF Core

I have several project in a solution. There is a dbContext in the Infrastructure project and I want to migrate, but I get an error. Please tell me what I'm doing wrong and how can I fix it.
using Infrastructure.Models;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<EventModel> Event { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql(GetConnectionString());
}
private static string GetConnectionString()
{
const string databaseName = "myDb";
const string databaseUser = "postgres";
const string databasePass = "root";
return $"Server=localhost;" +
$"database={databaseName};" +
$"uid={databaseUser};" +
$"pwd={databasePass};" +
$"pooling=true;";
}
}
}
You have to add constructor without parameters to class ApplicationDbContext.
It is clearly described in link on error image: https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli#using-a-constructor-with-no-parameters

How can I stop items being duplicated in SQLite database?

Here is my code where I add items to SQLite database
public partial class BirdPages : ContentPage
{
private SQLiteAsyncConnection _connection;
public BirdPages(string BirdNames, Button BirdSelect)
{
InitializeComponent();
_connection = DependencyService.Get<ISQLiteDb>().GetConnection();
BirdNameCall.Text = BirdNames;
AddToList = BirdSelect;
}
async private void AddToList_Clicked(object sender, EventArgs e)
{
await _connection.CreateTableAsync<Bmodel>();
string BirdNames = BirdNameCall.Text;
var voel = new Bmodel { Bname = BirdNames};
await _connection.InsertAsync(voel);
await DisplayAlert(BirdNames, "added to list", "Ok");
}
And here is where I get from database to a listview
public class Bmodel
{
[PrimaryKey, AutoIncrement]
public int Id { get; set;}
[MaxLength(255)]
public string Bname { get; set; }
}
public partial class myBirdList : ContentPage
{
private SQLiteAsyncConnection _connection;
private ObservableCollection<Bmodel> _birds;
public myBirdList()
{
InitializeComponent();
_connection = DependencyService.Get<ISQLiteDb>().GetConnection();
}
protected override async void OnAppearing()
{
await _connection.CreateTableAsync<Bmodel>();
var blists = await _connection.Table<Bmodel>().OrderBy(x => x.Bname).ToListAsync();
_birds = new ObservableCollection<Bmodel>(blists);
birdlistview.ItemsSource = _birds;
base.OnAppearing();
}
void MenuItem_Clicked(object sender, System.EventArgs e)
{
var blists = (sender as MenuItem).CommandParameter as Bmodel;
_connection.DeleteAsync(blists);
_birds.Remove(blists);
}
When an item is added twice or more to the database it display's in the listview. I would appreciate help on how to not display the duplicate items or even how to display alert when it is already in the database. I think it has something to do with the PrimaryKey if I am not mistaken. Any help would be great Thanks.
So all I changed was to keep my Public int Id as the Primary Key and change the Bname to [Unique] and where I used InsertAsync I changed it to InsertOrReplaceAsync

elastic search in .net with NEST

I am trying to get ElasticSearch data with NEST in ASP.NET. With a Button that when its clicked my data will be shown in a TextBox.
Do I need to put my database in the project or something? , when I click the button no data is shown.
I am using Visual Studio 2015, .NET Framework 4.6.1
I am a beginner so I can't handle this error that occurred.
I will provide my code.
Error:
NuGet Packages:
namespace ElasticsearchWeb{
public class shekspir
{
public string type { get; set; }
public int line_id { get; set; }
public string play_name { get; set; }
public int speech_number { get; set; }
public float line_number { get; set; }
public string speaker { get; set; }
public string text_entry { get; set; }
}
public partial class Default : System.Web.UI.Page
{
public static Uri GetElasticHost()
{
var host = "http://localhost:9200";
return new Uri(host);
}
public static ElasticClient GetElasticClient(ConnectionSettings settings = null)
{
if (settings == null)
{
var node = GetElasticHost();
var pool = new SingleNodeConnectionPool(node);
settings = new ConnectionSettings(pool);
}
settings.DisableDirectStreaming(true);
var client = new ElasticClient(settings);
return client;
}
public static List<shekspir> GetAllShekspir(int ID)
{
var client = GetElasticClient();
ISearchResponse<shekspir> result = null;
result = client.Search<shekspir>(x => x
.Index("shekspir")
.Query(q => q
.MatchAll())
);
List<shekspir> list = new List<shekspir>();
foreach (var r in result.Hits)
{
shekspir a = r.Source;
list.Add(a);
}
return list;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
List<shekspir> list = GetAllShekspir(1);
foreach (shekspir u in list)
{
litInfo.Text += u.play_name + ": " + u.text_entry + "<br>";
}
}
}}
What version of .Net runtime is your application running? The elastic search Nest API version that you have used is expecting the .Net Standard Version 2.0, which it cannot find.

Xamarin.Forms SQLite exception - don't know about PartsManagement.Models.Part[] (<- a custom class)

I am sorry for this re-post of a question, but the original was never answered in a way that I could understand and leverage. I was not certain if I should try to revive that question or spawn a new one.
I am attempting to add a Part object to my Part table within the database I created. I get the following error during execution
System.AggregateException
Message=One or more errors occurred. (Don't know about PartsManagement.Models.Part[])
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2027
at System.Threading.Tasks.Task.Wait (System.Int32 millisecondsTimeout, System.Threading.CancellationToken cancellationToken) [0x00043] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2759
at System.Threading.Tasks.Task.Wait () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/external/corert/src/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs:2625
at PartsManagement.Database..ctor (System.String dbPath) [0x00027] in C:\Users\5w3rv0\source\repos\PartsManagement\PartsManagement\PartsManagement\Database.cs:18
at PartsManagement.App.get_Database () [0x0000e] in C:\Users\5w3rv0\source\repos\PartsManagement\PartsManagement\PartsManagement\App.xaml.cs:20
at PartsManagement.Views.NewPartPage.Save_Clicked (System.Object sender, System.EventArgs e) [0x00057] in C:\Users\5w3rv0\source\repos\PartsManagement\PartsManagement\PartsManagement\Views\NewPartPage.xaml.cs:25
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_0 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1021
at Android.App.SyncContext+<>c__DisplayClass2_0.<Post>b__0 () [0x00000] in <4ccdb3137d974856b786e1aeebbfbab6>:0
at Java.Lang.Thread+RunnableImplementor.Run () [0x00008] in <4ccdb3137d974856b786e1aeebbfbab6>:0
at Java.Lang.IRunnableInvoker.n_Run (System.IntPtr jnienv, System.IntPtr native__this) [0x00009] in <4ccdb3137d974856b786e1aeebbfbab6>:0
at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.71(intptr,intptr)
From the error message I have determined that the error appears to occur durring the execution of line 25
await App.Database.SavePartAsync(new Part
{
Name = partName.Text,
Description = partDescription.Text
});
in the NewPartsPage.xaml.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using PartsManagement.Models;
namespace PartsManagement.Views
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class NewPartPage : ContentPage
{
public NewPartPage()
{
InitializeComponent();
}
async void Save_Clicked(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(partName.Text) && !string.IsNullOrWhiteSpace(partDescription.Text))
{
await App.Database.SavePartAsync(new Part
{
Name = partName.Text,
Description = partDescription.Text
});
}
await Navigation.PopModalAsync();
}
async void Cancel_Clicked(object sender, EventArgs e)
{
await Navigation.PopModalAsync();
}
}
}
Here is the Part class:
using SQLite;
namespace PartsManagement.Models
{
public class Part
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
and the database file:
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;
using PartsManagement.Models;
namespace PartsManagement
{
public class Database
{
readonly SQLiteAsyncConnection _database;
public Database(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Part>().Wait();
_database.CreateTableAsync<Product>().Wait();
}
public Task<List<Part>> GetPartsAsync()
{
return _database.Table<Part>().ToListAsync();
}
public Task<int> SavePartAsync(Part aPart)
{
return _database.InsertAsync(aPart);
}
public Task<List<Product>> GetProductsAsync()
{
return _database.Table<Product>().ToListAsync();
}
public Task<int> SaveProductAsync(Part aProduct)
{
return _database.InsertAsync(aProduct);
}
}
}
The error seems to further indicate that the NewPartsPage cannot find the Part object, but I have referenced it with the proper using statement of using PartsManagement.Model;. I am not sure if the square brackets in the error are significant. Is it attempting to find a specific instantiation of the Parts object as an array? I have reviewed the sqlite key words, but Part does not seem to be included in it. Is my folder structure having an impact on the functionality I am looking for? I have performed this functionality in the local database tutorial, but this example is different in that I attempted to use a different folder structure. Not sure how this would impact, but just in case I am bringing it up.
This examples folder structure
static Database database;
public static Database Database
{
get
{
if (database == null)
{
database = new Database(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Inventory.db3"));
}
return database;
}
}
Including the product class as it is key to the root cause of this issue.
using SQLite;
namespace PartsManagement.Models
{
public class Product
{
[PrimaryKey, AutoIncrement]
public string ID { get; set; }
public string Name { get; set; }
public int Cost { get; set; }
public int OnHand { get; set; }
public int UsedIn { get; set; }
public double AveragePerProduct { get; set; }
public int NumberSold { get; set; }
public double Price { get; set; }
public Part[] PartsIn { get; set; }
}
}
it is failing when creating the Product table because sqlite does not understand how to create an Part array. If you want to have tables with FK relations you need to add the SQLite Extensions package

Pass generic list in console app from asp.net

I have a solution that i need to call a console app from asp.net and need to pass variables. one variable is a generic list of a certain class.
I have tried passing it but I got error that i cannot convert a generic list to a string which is correct.
I am not sure if there is another way to pass this.
I know webservice can solve this issue. But it there any other options?
Is this possible to do or only string are possible to pass
Here is the generic list sample.
List<person> personList = new List<person>();
person p = new person();
p.name = "test";
p.age = 12;
p.birthdate = 01/01/2014
personList.add(p)
Thanks.
Ok, Console application accepts only strings. This is defined in the Main method as
static void Main(string[] args)
Since you have a complex object list it'll be bit hard to pass this information to the console application (but not impossible). There are several options for you.
Pass your values as comma separated values as a string as long as this string is not too long.
Web Services or a Web API as you suggested.
Serialize your object to an XML file and then deserialize in your console application.
Write and read from a persistent data store
UPDATE
Sample Code for Option 3 (Write to an XML file)
I wrote this sample code out of curiosity. Hope this helps to solve your issue.
ASP.Net Website
I have a button in my web page (Default.aspx) and in it's click event it writes the Person collection/ List to an XML file. Here's the code behind.
using System;
using System.IO;
using System.Xml.Serialization;
namespace WriteToConsole
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnWriteToConsole_Click(object sender, EventArgs e)
{
PersonCollection personList = new PersonCollection();
// Person 1
Person p = new Person();
p.Name = "test 1";
p.Age = 12;
p.BirthDate = DateTime.Parse("01/01/2014");
personList.Add(p);
// Person 2
Person p2 = new Person();
p2.Name = "test 2";
p2.Age = 25;
p2.BirthDate = DateTime.Parse("01/01/2014");
personList.Add(p2);
XmlSerializer serializer = new XmlSerializer(personList.GetType());
StreamWriter file = new StreamWriter(#"D:\temp\PersonCollection.xml");
serializer.Serialize(file, personList);
file.Close();
}
}
}
And, the Person.cs looks like this.
using System;
using System.Collections.Generic;
namespace WriteToConsole
{
[Serializable]
[System.Xml.Serialization.XmlRoot("PersonCollection")]
public class PersonCollection : List<Person> {
}
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }
public Person()
{
this.Name = string.Empty;
this.Age = 0;
this.BirthDate = DateTime.MinValue;
}
}
}
Console Application
Then read the XML file in your console application and display the data in personList on the console.
using System;
using System.IO;
using System.Xml.Serialization;
namespace ReadInConsole
{
class Program
{
static void Main(string[] args)
{
XmlSerializer deserializer = new XmlSerializer(typeof(PersonCollection));
TextReader textReader = new StreamReader(#"D:\temp\PersonCollection.xml");
PersonCollection personList = new PersonCollection();
personList = (PersonCollection)deserializer.Deserialize(textReader);
textReader.Close();
if (personList != null && personList.Count > 0)
{
foreach (Person p in personList)
{
Console.WriteLine("Person name: {0}, Age: {1} and DOB: {2}", p.Name, p.Age, p.BirthDate.ToShortDateString());
}
Console.ReadLine();
}
}
}
}
In your console application you should have the same Person class as a modal (This is same as the Person class in your Web Application. Only the namespace is different).
using System;
using System.Collections.Generic;
namespace ReadInConsole
{
[Serializable]
[System.Xml.Serialization.XmlRoot("PersonCollection")]
public class PersonCollection : List<Person>
{
}
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime BirthDate { get; set; }
public Person()
{
this.Name = string.Empty;
this.Age = 0;
this.BirthDate = DateTime.MinValue;
}
}
}
Hope you understand the code.

Resources