ASP.Net ElasticSearch - c#

Hello so I am trying to code a simple web view, with asp.net and NEST library, that will take my ElasticSearch database, and show it in textview on button click.
This is the code that I input when my button is clicked,
would you please look at it and tell me am I on a good path or something is not good.
using Elasticsearch.Net;
using Nest;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
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 workОfShakespeare = GetElasticClient();
ISearchResponse<shekspir> result = null;
result = workОfShakespeare.Search<shekspir>(x => x
.Index("shekspir")
.Query(q => q
.MatchAll())
.Size(100)
);
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>";
}
}
}
}

List<shekspir> list = new List<shekspir>();
foreach (var r in result.Hits)
{
shekspir a = r.Source;
list.Add(a);
}
If you just want the returned documents above can be replaced by
var list= result.Documents

Related

Specified cast is not valid - Xamarin Forms

So I am trying to navigate to a content page that is supposed to have all the movie details from the movie the user selects in the collection view but every time I select a movie in my collection view the error "Specified cast is not valid", which occurs at the Navigation.PushAsync(new MovieDetails((MovieData)e.CurrentSelection)); line, pops up.
I'm very new to C# and using Xamarin forms so I'm not sure if this is the right way to be doing things.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using Listly.Models;
using Xamarin.Forms;
namespace Listly
{
public partial class SearchPage : ContentPage
{
public ObservableCollection<MovieData> allMovies = new ObservableCollection<MovieData>();
public int NumClicked { get; set; }
public bool BtnClicked = false;
public string Poster_Path_End { get; set; }
public MovieList newList = new MovieList();
public SearchPage()
{
InitializeComponent();
contentPage.BackgroundColor = Color.FromHex("1D1D1D");
searchBtn.BackgroundColor = Color.FromHex("28D7B5");
searchBtn.TextColor = Color.FromHex("1D1D1D");
searchBar.PlaceholderColor = Color.FromHex("A0A0A0");
searchBar.TextColor = Color.Black;
collectionView.SelectionMode = SelectionMode.Single;
collectionView.ItemsSource = allMovies;
collectionView.SelectionChanged += CollectionView_SelectionChanged;
searchBtn.Clicked += SearchBtn_Clicked;
}
private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.CurrentSelection != null)
{
Navigation.PushAsync(new MovieDetails((MovieData)e.CurrentSelection));
}
}
private async void SearchBtn_Clicked(object sender, EventArgs e)
{
if (BtnClicked == false)
{
BtnClicked = true;
NumClicked += 1;
DataManager dataManager = new DataManager(searchBar.Text);
dataManager.GetMovie(searchBar.Text);
newList = await dataManager.GetMovie(searchBar.Text);
foreach (var movie in newList.searchList)
{
if (movie.Title == null)
{
bool answer = await DisplayAlert("Movie Not Found", "The movie searched was not found. Please try again.", "Okay", "Cancel");
searchBar.Text = "";
searchBar.Placeholder = "Enter Movie Name";
break;
}
allMovies.Add(movie);
}
}
else if (BtnClicked == true)
{
if (NumClicked == 1 || NumClicked > 1)
{
allMovies.Clear();
DataManager dataManager = new DataManager(searchBar.Text);
newList = await dataManager.GetMovie(searchBar.Text);
foreach (var movie in newList.searchList)
{
if (movie.Title == null)
{
bool answer = await DisplayAlert("Movie Not Found", "The movie searched was not found. Please try again.", "Okay", "Cancel");
break;
}
allMovies.Add(movie);
}
}
}
collectionView.ItemsSource = allMovies;
}
protected override void OnAppearing()
{
base.OnAppearing();
collectionView.ItemsSource = allMovies;
}
}
}
Here's the MovieDetails page
using System;
using System.Collections.Generic;
using Listly.Models;
using Xamarin.Forms;
namespace Listly
{
public partial class MovieDetails : ContentPage
{
public MovieData details = new MovieData();
public MovieData selectedMovie = new MovieData();
public string Poster_Path_End { get; set; }
public MovieDetails(MovieData selectedMovie)
{
InitializeComponent();
details = selectedMovie;
details.Title = selectedMovie.Title;
details.Overview = selectedMovie.Overview;
}
}
}
As Jason said,
CurrentSelection – the list of items that are selected, after the
selection change.
So you could set SelectionMode to Single,then use SelectedItem.
or do like this:
MovieData movie = e.CurrentSelection.FirstOrDefault() as MovieData ;
Navigation.PushAsync(new MovieDetails(movie);
the more you could look at CollectionView Selection.

How to fix .Exception: 'Custom pin not found for specific pins

Please help me with this issue.
I was making a custom renderer in xamarin using this article:
Xamarin Form Custom Renderer
Everything worked fine until I made the pin information into a JSON file.
So basically now the LAT, LNG, label, name and URL were stored in a JSON file instead of a C# file.
For testing, I had made 3 temporary pins. But only 1 of them shows the custom rendered window. When I click the other 2 pins an exception occurs as custom pin not found. But the custom pin is found for the last pin but not the 1st and 2nd pin which confuses me.
My code:
JSON file:
[
{"Label" :"Country1",
"Address":"A multine paragraph",
"Lat":"-12",
"Lng":"14",
"Name":"Xamarin",
"Url": "http://xamarin.com/about/"
},
{ "Label" :"Country2",
"Address":"Multiline paragraph",
"Lat":"-25",
"Lng":"45",
"Name":"Xamarin",
"Url": "http://xamarin.com/about/"
},
{ "Label" :"Country3",
"Address":"Multiline paragraph",
"Lat":"-5",
"Lng":"45",
"Name":"Xamarin",
"Url": "http://xamarin.com/about/"
}
]
MapPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Newtonsoft.Json;
using System.IO;
using Xamarin.Forms.Xaml;
using System.Reflection;
namespace Orbage
{
public partial class MapPage : ContentPage
{
public MapPage()
{
CustomMap customMap = new CustomMap
{
MapType = MapType.Hybrid
};
Content = customMap;
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MapPage)).Assembly;
Stream stream = assembly.GetManifestResourceStream("Orbage.Mydata.json");
string json = "";
using (var reader = new System.IO.StreamReader(stream))
{
json = reader.ReadToEnd();
}
var places = JsonConvert.DeserializeObject<List<Mydata>>(json);
List<CustomPin> custompinList = new List<CustomPin>();
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
Label = place.Label,
Address = place.Address,
Name = place.Name,
Url = place.Url
};
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
customMap.CustomPins = custompinList;
}
}
}
public class Mydata
{
public string Label { get; set; }
public string Address { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
public string Name { get; set; }
public string Url { get; set; }
}
}
CustomPin:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms.Maps;
namespace Orbage
{
public class CustomPin : Pin
{
public string Name { get; set; }
public string Url { get; set; }
public string Adress { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
}
}
CustomMap:
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms.Maps;
namespace Orbage
{
public class CustomMap : Map
{
public List<CustomPin> CustomPins { get; set; }
}
}
CustomMapRenderer.cs:
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using ----;
using ----.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace ----.Droid
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<CustomPin> customPins;
public CustomMapRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
return marker;
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Name.Equals("Xamarin"))
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Position == position)
{
return pin;
}
}
return null;
}
}
}
Thanks for seeing this and I hope this get's answered and someone with the same error gets it fixed.
:)
I tried debugging and here is a image of what somewhat might help:
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
Label = place.Label,
Address = place.Address,
Name = place.Name,
Url = place.Url
};
customMap.CustomPins = new List<CustomPin> { pin }; //this will cause your customMap.CustomPins always has only the last custompin.
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
The issue is here,you add the customMap.CustomPins inside the loop,so it always has only the third CustomPin.
Try to move it out of the foreach:
List<CustomPin> custompinList = new List<CustomPin>();
foreach (var place in places)
{
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(Double.Parse(place.Lat), Double.Parse(place.Lng)),
Label = place.Label,
Address = place.Address,
Name = place.Name,
Url = place.Url
};
custompinList.Add(pin);
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
customMap.CustomPins = custompinList;
Update the effect like below:

Table Row (//tr) HtmlNodes seem to have issue with rows being skipped

I'm currently trying to scrape a cannabis strain database as it is no longer being maintained. I seem to be running into an issue where table rows are skipped in my logic but it really doesn't make sense, it's like a break is being called when I'm iterating through the //tr elements of the table that is storing the chemical reports.
Is it something like the δ α symbols in the next row. I've tried regex replacing them out to now luck. Any help would be appreciated all code is in a single class console app.
Issue is in the table.ChildNodes not iterating all the way through. Located in the ParseChemical() method.
Sample Page: http://ocpdb.pythonanywhere.com/ocpdb/420/
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.Design;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Reflection.Emit;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.VisualBasic.CompilerServices;
namespace CScrape
{
class Program
{
private static readonly HttpClient Client = new HttpClient();
private static readonly string BaseUri = "http://ocpdb.pythonanywhere.com/ocpdb/";
private static int _startId = 420;
private static int _endId = 1519;
private static List<Lab> _labs = new List<Lab>();
private static List<ChemicalItem> _chemicalItems = new List<ChemicalItem>();
private static List<UnitOfMeasure> _uoms = new List<UnitOfMeasure>();
private static List<Strain> _strains = new List<Strain>();
static void Main(string[] args)
{
Client.DefaultRequestHeaders.Accept.Clear();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13;
_uoms.AddRange(GetUoms());
for (var i = _startId; i <= _endId; i++)
{
var result = GetUri($"{BaseUri}{i}").Result;
_strains.Add(ParseChemical(result));
}
}
private static long AddChemicalItem(ChemicalItem item)
{
if (ChemicalExists(item.Symbol))
return _chemicalItems.FirstOrDefault(ci => ci.Symbol == item.Symbol)?.Id ?? -1;
item.Id = _chemicalItems.Count + 1;
_chemicalItems.Add(item);
return item.Id;
}
private static void UpdateChemicalItem(ChemicalItem item)
{
if (!ChemicalExists(item.Symbol)) return;
var index = _chemicalItems.IndexOf(item);
if (!(index >= 0)) return;
_chemicalItems.RemoveAt(index);
AddChemicalItem(item);
}
private static long AddLab(Lab lab)
{
if (LabExists(lab.Name))
return _labs.FirstOrDefault(l => l.Name == lab.Name)?.Id ?? -1;
lab.Id = _labs.Count + 1;
_labs.Add(lab);
return lab.Id;
}
private static async Task<string> GetUri(string uri)
{
var response = await Client.GetByteArrayAsync(uri);
return Encoding.UTF8.GetString(response, 0, response.Length - 1);
}
private static Strain ParseChemical(string html)
{
html = Regex.Replace(html, #"Δ", "Delta");
HtmlDocument htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var strain = new Strain();
strain.Reports ??= new List<ChemicalReport>();
try
{
strain.Name = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[1]/h3/b").InnerText;
}
catch (Exception e)
{
// TODO: DOcument Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.Name)) return null;
try
{
var ocpId = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/b/text()[1]");
strain.OcpId = SanitizeHtml(ocpId.InnerText).Split(':')[1];
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
if (string.IsNullOrWhiteSpace(strain.OcpId)) return null;
try
{
var date = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[1]/div[2]/p/text()");
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
var chemReport = new ChemicalReport();
chemReport.Items ??= new List<ReportItem>();
try
{
var table = htmlDoc.DocumentNode.SelectSingleNode("/html/body/div/div[2]/div[1]/table/tbody");
var children = table.ChildNodes.ToList();
// On the sample page there are 200 children here
// However it only interates through the first few and then just breaks out of the loop
foreach (var child in children)
{
var name = child.Name;
if (child.Name == "tr")
{
var infos = child.SelectNodes("th|td");
foreach (var info in infos)
{
if(string.IsNullOrWhiteSpace(info.InnerText)) continue;
if (info.InnerText.Contains("Report")) continue;
if (double.TryParse(info.InnerText, out var isNumber))
{
var last = chemReport.Items.LastOrDefault();
if (last == null) continue;
if (last.Value <= 0.0000) last.Value = isNumber;
else
{
var further = chemReport.Items.ToArray()[chemReport.Items.Count - 2];
if (further.Value <= 0.0000)
further.Value = isNumber;
}
continue;
}
var _ = new ChemicalItem
{
Name = info.InnerText,
Symbol = info.InnerText
};
_.Id = AddChemicalItem(_);
var report = new ReportItem
{
Chemical = _,
ChemicalItemId = _.Id,
UnitOfMeasureId = 1,
UoM = GetUoms()[0]
};
chemReport.Items.Add(report);
}
}
}
strain.Reports.Add(chemReport);
}
catch (Exception e)
{
// TODO: Document exception
Console.Write(e.Message);
}
return strain;
}
private static List<UnitOfMeasure> GetUoms()
{
return new List<UnitOfMeasure>
{
new UnitOfMeasure {Name = "Milligrams per Gram", Symbol = "mg/g"},
new UnitOfMeasure {Name = "Percent", Symbol = "%"}
};
}
private static string SanitizeHtml(string text, string replacement = "")
{
return Regex.Replace(text, #"<[^>]+>| |α|\n|\t", replacement);
}
private static string GetLabName(string[] split)
{
var strip = split[0].Split(':')[1];
for(var i = 1; i < split.Length - 2; i ++)
{
if (string.IsNullOrWhiteSpace(split[i])) break;
strip += $" {split[i]}";
}
return strip;
}
private static string GetSampleId(string[] split)
{
var found = false;
foreach (var item in split)
{
if (found)
return item.Split(':')[1];
if (item == "Sample") found = true;
}
return "NA";
}
private static bool LabExists(string name)
{
return _labs.Any(lab => lab.Name == name);
}
private static bool ChemicalExists(string name)
{
return _chemicalItems.Any(ci => ci.Symbol == name);
}
private static ReportItem GetReportItem(string text)
{
if (string.IsNullOrWhiteSpace(text)) return null;
ReportItem ri = null;
try
{
var clean = SanitizeHtml(text);
var check = 0;
var split = clean.Split(':');
var label = split[0];
if (string.IsNullOrWhiteSpace(label)) return null;
if (double.TryParse(label, out var invalidType)) return null;
var val = string.Empty;
if (split.Length == 1)
{
if (split[0].Contains("Total"))
{
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(split[0]);
label = result.Groups[1].Value;
val = result.Groups[2].Value;
}
}
if(split.Length > 1)
val = split[1];
if (!ChemicalExists(label)) AddChemicalItem(new ChemicalItem {Id = _chemicalItems.Count + 1,Symbol = label});
ri = new ReportItem();
ri.Chemical = _chemicalItems.FirstOrDefault(ci => ci.Symbol == label);
ri.UoM = val.Contains("%")
? _uoms.FirstOrDefault(uom => uom.Symbol == "%")
: _uoms.FirstOrDefault(uom => uom.Symbol == "mg/g");
if (string.IsNullOrWhiteSpace(val)) return ri;
var value = val.Contains("%") ? split[1].Substring(0, val.Length - 1) : val;
ri.Value = Convert.ToDouble(value);
}
catch (Exception e)
{
// TODO: Document Exception
Console.WriteLine(e.Message);
}
return ri;
}
//private static ChemicalItem GetChemicalItem(string text)
//{
//}
public class Strain
{
public long Id { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public string OcpId { get; set; }
public bool IsHidden { get; set; } = false;
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class Lab
{
public long Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ChemicalReport> Reports { get; set; }
}
public class ChemicalReport
{
public long Id { get; set; }
[ForeignKey("Lab")]
public long LabId { get; set; }
public virtual Lab Lab { get; set; }
public string SampleId { get; set; }
public DateTime Created { get; set; }
public virtual ICollection<ReportItem> Items { get; set; }
[ForeignKey("Strain")]
public long StrainId { get; set; }
public virtual Strain Strain { get; set; }
}
public class ChemicalItem
{
public long Id { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
}
public class ReportItem
{
public long Id { get; set; }
[ForeignKey("Chemical")]
public long ChemicalItemId { get; set; }
public virtual ChemicalItem Chemical { get; set; }
public double Value { get; set; }
[ForeignKey("UoM")]
public long UnitOfMeasureId { get; set; }
public virtual UnitOfMeasure UoM { get; set; }
}
public class UnitOfMeasure
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Symbol { get; set; }
}
}
}

how to read items from file into a list of items and set the properties to the value in the file?

Hello I am trying to create a stock log system in c# winforms and i am a bit stuck for ideas on how to read the items back into a list and storing the data into the properties.
I will be reading in from a csv file where each line is 1 item and each property is separated by a comma.
the main Class
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using System.IO;
//using Microsoft.VisualBasic;
namespace stock_list
{
public partial class Form1 : Form
{
private List<item> itemlist = new List<item>((1));
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
saveitem(Convert.ToInt64(txtStallNumber.Text), Convert.ToInt64(txtStockNumber.Text), txtDescription.Text, Convert.ToDecimal(txtPaidprice.Text), Convert.ToDecimal(txtSoldPrice.Text));
}
private void btnItems_Click(object sender, EventArgs e)
{
readfromfile();
}
private void readfromfile()
{
var reader = new System.IO.StreamReader(#"file.csv", Encoding.UTF8, false);
while (!reader.EndOfStream)
{
//what todo here??
}
}
private void saveitem(long stallnumberpar, long stocknumberpar, string itemdiscriptionpar, decimal boughtpricepar, decimal soldpricepar, decimal profitorlosspar = 0)
{
itemlist.Add(new item { stallnumber = stallnumberpar, stocknumber = stocknumberpar, itemdescription = itemdiscriptionpar, boughtprice = boughtpricepar, soldprice = soldpricepar, profitorloss = soldpricepar - boughtpricepar});
txtDescription.Clear();
txtPaidprice.Clear();
txtSoldPrice.Clear();
txtStallNumber.Text = "";
txtStockNumber.Clear();
txtStallNumber.Focus();
MessageBox.Show("Item Saved");
}
private void btnQuery_Click(object sender, EventArgs e)
{
RunQueryDescription(Microsoft.VisualBasic.Interaction.InputBox("Enter Search Criteria", "Enter Search Criteria", "Default",0,0));
}
private void RunQueryDescription(string description)
{
//List<item> products = new List<item>((1));
var writer = new System.IO.StreamWriter(#"file.csv", true, Encoding.UTF8);
item[] productsarr = new item[itemlist.Count];
int index = 0;
foreach (item product in itemlist)
{
if (product.itemdescription.Contains(description))
{
productsarr[index] = product;
index++;
}
else
{
index++;
continue;
}
}
for (int i = 0; i < productsarr.Length; i++)
{
MessageBox.Show(productsarr[i].stallnumber.ToString() +
productsarr[i].stocknumber.ToString() +
productsarr[i].itemdescription.ToString() +
productsarr[i].boughtprice.ToString() +
productsarr[i].soldprice.ToString() +
productsarr[i].profitorloss.ToString());
writer.Write(productsarr[i].stallnumber.ToString() + "," +
productsarr[i].stocknumber.ToString() + "," +
productsarr[i].itemdescription.ToString() + "," +
productsarr[i].boughtprice.ToString() + "," +
productsarr[i].soldprice.ToString() + "," +
productsarr[i].profitorloss.ToString());
writer.Close();
writer.Dispose();
}
}
}
}
The items class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
namespace stock_list
{
class item
{
public long stallnumber { get; set; }
public long stocknumber { get; set; }
public string itemdescription { get; set; }
public decimal boughtprice { get; set; }
public decimal soldprice { get; set; }
public decimal profitorloss { get; set; }
}
}
EDIT:
Example File
1,1,Vase,1.00,2.00,1.00
Any help will be valued
Thanks in Advance!
You can use the File.ReadAllLines to read the file
private List<item> itemlist = new List<item>();
private void readfromfile()
{
var lines = System.IO.File.ReadAllLines("path");
foreach (string item in lines)
{
var values = item.Split(',');
itemlist.Add(new item()
{
stallnumber = long.Parse(values[0]),
stocknumber = long.Parse(values[1]),
itemdescription = values[2],
//and so on
});
}
}
Try splitting each line on the delimiter (most likely a comma), and then parse out the line and add a new instance of item to your list. Something like this should work inside your loop (untested):
var line = reader.ReadLine();
var values = line.Split(',');
itemlist.Add(new item { stallnumber = Convert.ToInt32(values[0]), ... });

read column names from sqlite table windows 8 app

I am using SQLite for a data entry windows 8 app I am working on. I can create the db, insert data, retrieve a column count, and read data, but cannot get the column names.
The underlying framework is from this post.
I read about the PRAGMA table_info(table_name); command but I cannot seem to send and read back this query properly. I have been googling for 3 days!
MainPage.xaml.cs:
using SQLite;
using SqlLiteTest.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace SqlLiteTest
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
txtPath.Text = ApplicationData.Current.LocalFolder.Path;
}
private async void createDB(object sender, RoutedEventArgs e)
{
// access local folder
var qvLocalFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
//Create a blank carrier file
StorageFile qvLocalFileCarrier = await qvLocalFolder.CreateFileAsync("qvdbLocal.db", CreationCollisionOption.FailIfExists);
//Write the blank carrier file
await FileIO.WriteTextAsync(qvLocalFileCarrier, "");
}
catch { }
// connect
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
// create table
await db.CreateTableAsync<qvdb>();
// insert data
var insertRecords = new List<qvdb>()
{
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
new qvdb
{
qvdbRecord = 1,
qvdbNotes = "Notes1",
qvdb001 = "Variable 1.1",
qvdb002 = "Variable 2.1"
},
};
await db.InsertAllAsync(insertRecords);
// read count
var allUsers = await db.QueryAsync<qvdb>("SELECT * FROM qvdb");
var count = allUsers.Any() ? allUsers.Count : 0;
Debug.WriteLine(count);
}
private async void updateDB(object sender, RoutedEventArgs e)
{
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
var tempCell = db.QueryAsync<qvdb>("UPDATE qvdb SET qvdbNotes ='!##$%$%^^&*()+)(*&^%$##!{:L<>?' WHERE qvdbRecord = 10");
await db.UpdateAsync(tempCell);
}
private async void readDB(object sender, RoutedEventArgs e)
{
var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + #"\qvdbLocal.db";
var db = new SQLiteAsyncConnection(path);
var query = db.Table<qvdb>();
var result = await query.ToListAsync();
foreach (var item in result)
{
MessageDialog dialog = new MessageDialog(string.Format("{0} {1} {2}", item.qvdbRecord, item.qvdbNotes, item.qvdb001));
await dialog.ShowAsync();
}
}
private void readColNames(object sender, RoutedEventArgs e)
{
}
}
}
qvdb.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
namespace SqlLiteTest.Model
{
public class qvdb
{
[PrimaryKey, AutoIncrement]
public int qvdbRecord { get; set; }
[MaxLength(3000)]
public string qvdbNotes { get; set; }
[MaxLength(1000)]
public string qvdb001 { get; set; }
[MaxLength(1000)]
public string qvdb002 { get; set; }
}
}
Thanks CL for the info. I added the class but still do not know how to access them. Some more code...
// this works
// read record count
var allRecords = await db.QueryAsync<qvdb>("SELECT * FROM qvdb");
var countRecords = allRecords.Any() ? allRecords.Count : 0;
this.textboxLog.Text = this.textboxLog.Text + Environment.NewLine + "There are " + countRecords + " records.";
// ??
// read column names
var allColumns = await db.QueryAsync<qvdb>("PRAGMA table_info(qvdb)");
foreach (var item in allColumns) {
//read name
this.textboxLog.Text = this.textboxLog.Text + Environment.NewLine + "columbn names";
}
The records returned by PRAGMA table_info look like this:
public class table_info_record
{
public int cid { get; set; }
public string name { get; set; }
public string type { get; set; }
public int notnull { get; set; }
public string dflt_value { get; set; }
public int pk { get; set; }
}
Use it like this:
db.QueryAsync<table_info_record>("PRAGMA table_info(...)");
o end the loop on CL's advice, this code successfully reads the column names:
// read column names
var query = await db.QueryAsync<table_info_record>("PRAGMA table_info(MY_TABLE_NAME_HERE)");
foreach (var item in query)
{
Debug.WriteLine(string.Format("{0}", item.name) + " is a column.");
}

Categories