elastic search in .net with NEST - asp.net

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.

Related

How to safe a ObservableCollection within a ObservableCollection in xamarin.forms with Sqlite.net

Last 3 days i tried to save my collection in my database.
I tried it in all sorts of ways... without success.
The last one i tried is to serialize my collection and save it to a byte[] everytime the collection changes.
And on appstart i tried to derserialize it in my collection.
I'm just trying to show the most important thing's.
I can save and reload this class without problems from my database.
[Serializable]
public class MainElement : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public static int count = 0;
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
public byte[] _elements;
private ObservableCollection<SecondElement> elements;
[OneToMany]
public ObservableCollection<SecondElement> Elements
{
get
{
return elements;
}
set
{
elements = value;
this.SerializeElementsFromMainElement();
//_elements = ExtensionAndDb.SerializeElementsFromMainElement(elements);
OnPropertyChanged();
}
}
public MainElement()
{
Id = count++;
Elements = new ObservableCollection<SecondElement>();
this.DeSerializeElementsFromMainElement();
//Elements = ExtensionAndDb.DeSerializeElementsFromMainElement(_elements);
}
public void OnPropertyChanged([CallerMemberName] string propertyname = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
}
public void DeSerializeElementsFromMainElement()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream(_elements);
using (stream)
{
Elements = bf.Deserialize(stream) as ObservableCollection<SecondElement>;
}
}
public void SerializeElementsFromMainElement()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
using (stream)
{
bf.Serialize(stream, Elements);
_elements = stream.ToArray();
}
}
}
Every MainElement is stored in the MainList (ObservableCollection).
Everything is fine.
But i cant save or reload the public byte[] _elements; from/to the collection.
I know my code is not good, but if anyone has an idea or can show me how to save the public ObservableCollection<SecondElement> Elements with my class together in Sqlite, i would be really grateful.
I've been trying for 3 days
if you need more code, let me know.
Thank's in advance.
According to your description, you want to serialize and deserialie ObservableCollection, I suggest you ca use Newtonsoft.Json to do this.
Installing Newtonsoft.Json by Nuget package firstly.
For example, I do one esample:
public class person
{
public string username { get; set; }
public int age { get; set; }
}
public ObservableCollection<person> persons { get; set; }
private string list;
public Page13()
{
InitializeComponent();
persons = new ObservableCollection<person>()
{
new person(){username="cherry",age=12},
new person(){username="barry",age=14}
};
}
Btn1.clicked is to serialize data, Btn2.clicked is to deserialize data.
private void Btn1_Clicked(object sender, EventArgs e)
{
list = Newtonsoft.Json.JsonConvert.SerializeObject(persons);
}
private void Btn2_Clicked(object sender, EventArgs e)
{
var myValue = Newtonsoft.Json.JsonConvert.DeserializeObject<ObservableCollection<person>>(list) ;
}
If the Observablecollection changed, you can query this data by Id or other, then update this data.
Here is the article about Update, insert and save data in sqlite, you can take a look:
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms

Xamarin, how can i access a specific column property in sqlite so i can add the values?

I know how to read or show all data inserted in the database but I don't know how to query a specific data. In the my database is in Post.cs it will store date/time and get 2 datas from user.
so like this: enter image description here
Column1(ID), Column2(Date), (column3(rain1), column4(rain2).
1 12/13/2019 21 22
2 12/16/2019 21 22
3 12/16/2019 11 12
I want to do: if (rain1 && rain2) have the same date. I would like to add 2data from rain1 which is 21+11 and save the total to rain1total=32 then rain2total would be 34. I don't know where to start
here is Post.cs
namespace listtoPDF.Model
{
//Post table, user posting drainvolume
//this is the source of Binding
public class Post: INotifyPropertyChanged
{
private double? rain1Vol;
private double? rain2Vol;
//from settingspage to show up in history
string rain1lbl = Settings.Drain1LocationSettings;
string rain2lbl = Settings.Drain2LocationSettings;
//ID primary key that we will autoincrement
//These are columns ID, drain1 to 8 so 9 columns
//These are binding source for Historypage
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public static bool showLabel { get; set; } //public class model
public string rain1Lbl
{
get => rain1lbl;
set => rain1lbl= Settings.Drain1LocationSettings;
}
public string rain2Lbl
{
get => rain2lbl;
set => rain2lbl= Settings.Drain2LocationSettings;
}
public string CDateTime { get; set; }
[MaxLength(3)]
public double? rain1vol
{
get { return rain1Vol; }
set
{
rain1Vol = value;
RaisePropertyChanged("rain1vol");
}
}
[MaxLength(3)]
public double? rain2vol
{
get { return rain2Vol; }
set
{
rain2Vol = value;
RaisePropertyChanged("rain2vol");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
here is the main that will list data entered with date
namespace listtoPDF
{
public partial class MainPage : ContentPage
{
List<Post> posts;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
postListView.ItemsSource = posts;
conn.Close();
//right click quickwatch
}
void addbuttonHandle_Clicked(object sender, EventArgs args)
{
Navigation.PushModalAsync(new AddRainsPage());
}
private void GetValues()
{
//Initiate SQLite connection
//Create table with class
//Get the values in table
//close the line
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
conn.Close();
}
}
Here is the page where i need query the add a certain column so i can add the data associated to it. So far it's connecting to the sqlite.
namespace listtoPDF
{
public partial class selecteddataPage : ContentPage
{
List<Post> posts;
public selecteddataPage()
{
InitializeComponent();
}
private void GetValues()
{
//Initiate SQLite connection
//Create table with class
//Get the values in table
//close the line
SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation);
conn.CreateTable<Post>();
posts = conn.Table<Post>().ToList();
**if (Post.rain1 values have the same date )
{
totalrain1= then add data that have same date
}
if (Post.rain2 values have the same date )
{
totalrain1= then add data that have same date
}**
conn.Close();
}
}
}

How to store unique class instances in SQLite?

I'm trying to store some information as a class instance in a SQLite table. The instances need to be unique in their DateTime property. I'm completely new to database programming, and I don't really understand how use SQLite in Xamarin. As new instances are created they need to update the existing instances in the table if they match in their DateTime property.
SQLiteAsyncConnection connection = new SQLiteAsyncConnection(App.FilePath);
await connection.CreateTableAsync<ModulInformationData>();
ModulInformationData data = new ModulInformationData();
data.InitModulInformation(modul);
int rows = 0;
try
{
rows = await connection.UpdateAsync(data);
}catch(Exception e)
{
Console.WriteLine("SQL Update failed " + e.Message);
}
Console.WriteLine("rows updated: " + rows);
if (rows == 0)
{
Console.WriteLine("before insert");
try
{
int key1 = await connection.InsertAsync(data);
Console.WriteLine("after insert: " + key1);
}catch (Exception e)
{
Console.WriteLine("SQL insert failed " + e.Message);
}
}
The ModulInformationData class
public class ModulInformationData
{
[PrimaryKey,AutoIncrement]
public int Id { get; set; }
[Unique]
public DateTime tidspunkt { get; set; }
other properties...
At the moment, I'm catching an error when inserting, but the message only says 'Constraint'. What can I do to make this work?
Do you want to achieve the result like this GIF。
First of all, you can create a class for the database CRUD.
public class NoteDatabase
{
readonly SQLiteAsyncConnection _database;
public NoteDatabase(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<Note>().Wait();
}
public Task<List<Note>> GetNotesAsync()
{
return _database.Table<Note>().ToListAsync();
}
public Task<Note> GetNoteAsync(int id)
{
return _database.Table<Note>()
.Where(i => i.ID == id)
.FirstOrDefaultAsync();
}
public Task<int> SaveNoteAsync(Note note)
{
if (note.ID != 0)
{
return _database.UpdateAsync(note);
}
else
{
return _database.InsertAsync(note);
}
}
public Task<int> DeleteNoteAsync(Note note)
{
return _database.DeleteAsync(note);
}
}
Then there is model class.
public class Note
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string Text { get; set; }
[Unique]
public DateTime Date { get; set; }
public string Gender { get; set; }
}
If we want to add or update the data to the database, firstly, we should update the data to the instance, then we could just save this instance to the database like following save click event.
async void OnSaveButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
note.Date = DateTime.UtcNow;
note.Gender = (string)myPicker.SelectedItem;
await App.Database.SaveNoteAsync(note);
await Navigation.PopAsync();
}
Here is my demo. you can download it and refer to it.
https://github.com/851265601/databaseDemo

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

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);

error Missing client_id parameter by asp.net?

I had this error when getting Facebook user details .
{
"error": {
"message": "Missing client_id parameter.",
"type": "OAuthException",
"code": 101 }
}
I will use this solution when user click on Facebook tab. I tried to solve this issue more but I cannot .
public partial class DefaultPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
FaceBookConnect.Authorize("user_photos,email",
Request.Url.AbsoluteUri.Split('?')[0]);
FaceBookConnect.API_Key = "111111111111111";
FaceBookConnect.API_Secret = "xxxxxxxxxxxxxxxxxx";
if (Request.QueryString["error"] == "access_denied")
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User has denied access.')", true);
return;
}
string code = Request.QueryString["code"];
if (!string.IsNullOrEmpty(code))
{
string data = FaceBookConnect.Fetch(code, "me");
FaceBookUser faceBookUser = new JavaScriptSerializer().Deserialize<FaceBookUser>(data);
faceBookUser.PictureUrl = string.Format("https://graph.facebook.com/{0}/picture", faceBookUser.Id);
pnlFaceBookUser.Visible = true;
//lblId.Text = faceBookUser.Id;
//lblUserName.Text = faceBookUser.UserName;
lblName.Text = faceBookUser.Name;
//lblEmail.Text = faceBookUser.Email;
ProfileImage.ImageUrl = faceBookUser.PictureUrl;
//btnLogin.Enabled = false;
}
}
}
public class FaceBookUser
{
public string Id { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string PictureUrl { get; set; }
public string Email { get; set; }
}
Thanks!
I suspect it will be because you're setting the API Key and secret after you are actually calling the authorize method. Try swapping it round like this:
FaceBookConnect.API_Key = "111111111111111";
FaceBookConnect.API_Secret = "xxxxxxxxxxxxxxxxxx";
FaceBookConnect.Authorize("user_photos,email",
Request.Url.AbsoluteUri.Split('?')[0]);
If this doesn't fix it, where are you getting the FaceBookConnect reference from?

Resources