I am trying to draw a polyline using the "PATH" from the JSON data after clicking on the "Draw Polyline" button. However I met with this error,
"An exception of type 'System.ArgumentException' occurred in ESRI.ArcGIS.Client.DLL but was not handled in user code
Additional information: Invalid geometry."
Am I missing any codes?
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Symbols;
using ESRI.ArcGIS.Client.Tasks;
using ESRI.ArcGIS.Client.Toolkit.DataSources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;
using Test.Resources;
namespace Test
{
public partial class MainPage : PhoneApplicationPage
{
private String finalPath;
GraphicsLayer _myFromJsonGraphicsLayer;
Draw _myDrawObject;
// Constructor
public MainPage()
{
InitializeComponent();
_myFromJsonGraphicsLayer = MyMap.Layers["MyFromJsonGraphicsLayer"] as GraphicsLayer;
_myDrawObject = new Draw(MyMap)
{
LineSymbol = LayoutRoot.Resources["DrawLineSymbol"] as LineSymbol,
FillSymbol = LayoutRoot.Resources["DrawFillSymbol"] as FillSymbol
};
_myDrawObject.DrawComplete += MyDrawObject_DrawComplete;
}
private void MyDrawObject_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs args)
{
Graphic graphic = new Graphic()
{
Geometry = args.Geometry,
Symbol = LayoutRoot.Resources["RedFillSymbol"] as FillSymbol
};
GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
graphicsLayer.Graphics.Add(graphic);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//base.OnNavigatedTo(e);
setUpLayers();
// Create webclient.
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
//client.DownloadStringAsync(new Uri("http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl="+startX+","+startY+"&el="+endX+","+endY+"&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback="));
client.DownloadStringAsync(new Uri("http://www.onemap.sg/publictransportation/service1.svc/routesolns?token=qo/s2TnSUmfLz+32CvLC4RMVkzEFYjxqyti1KhByvEacEdMWBpCuSSQ+IFRT84QjGPBCuz/cBom8PfSm3GjEsGc8PkdEEOEr&sl=39167.4524,35518.8625&el=28987.5163,33530.5653&startstop=&endstop=&walkdist=300&mode=bus&routeopt=cheapest&retgeo=true&maxsolns=1&callback="));
}
private void setUpLayers()
{
ArcGISTiledMapServiceLayer baseMapLayer = new ArcGISTiledMapServiceLayer();
baseMapLayer.ID = "BaseMap";
baseMapLayer.Url = "http://e1.onemap.sg/arcgis/rest/services/SM128/MapServer";
//baseMapLayer.Url = "http://onemap.sg/arcgis/rest/services/Basemap/MapServer";
MyMap.Layers.Add(baseMapLayer);
}
public class STEP
{
//public string STEP { get; set; }
public string type { get; set; }
public string ServiceType { get; set; }
public string ServiceID { get; set; }
public string NumberOfStop { get; set; }
public string BoardId { get; set; }
public string BoardDesc { get; set; }
public string BoardDist { get; set; }
public string AlightId { get; set; }
public string AlightDesc { get; set; }
public string AlightDist { get; set; }
}
public class BusRoute
{
public string Solution { get; set; }
public string Duration { get; set; }
public string TotalCard { get; set; }
public string TotalCash { get; set; }
public string TotalDistance { get; set; }
public List<STEP> STEPS { get; set; }
public string TotalStops { get; set; }
public List<List<string>> PATH { get; set; }
}
public class RootObject
{
public List<BusRoute> BusRoute { get; set; }
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
// var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
JObject rawData = JObject.Parse(e.Result);
String path = rawData["BusRoute"][0]["PATH"].ToString();
String[] collectionOfPoints = path.Split(';');
//JObject path = JObject.Parse(rawData["BusRoute"].ToString());
finalPath = "";
for (int i = 0; i < collectionOfPoints.Length; i++)
{
if (i == 0)
{
finalPath = #"{""paths"":[" + collectionOfPoints[i] + "]";
finalPath = finalPath + ",";
}
else if (i == collectionOfPoints.Length - 1)
{
finalPath = finalPath + "[" + collectionOfPoints[i] + "],\"spatialReference\":{\"wkid\":4326}}";
}
else
{
finalPath = finalPath + "[" + collectionOfPoints[i] + "]";
finalPath = finalPath + ",";
}
}
tb_test.Text = finalPath;
}
private void DrawGeometryButton_Click(object sender, RoutedEventArgs e)
{
ESRI.ArcGIS.Client.Geometry.Geometry geometry = ESRI.ArcGIS.Client.Geometry.Geometry.FromJson(tb_test.Text);
Graphic graphic = new Graphic();
_myDrawObject.DrawMode = DrawMode.Polyline;
tb_test.Text = finalPath;
}
}
}
Related
Good morning Stackoverflow,
I'm developing a time tracking web application with ASP.Net / C#.
There is a "coming" button that writes in a line of a textfile this: ID;Username;Date;Time.
At the other side, there is the "leaving" button. It should replace the line with the same content but add the time of leaving. So it should be looking like this: ID;Username;Date;TimeOfComing;TimeOfLeaving.
That's the problem. How do I replace the line? Every thing (ID, user etc.) is stored in variables of a helper class named "cZeile". So, how do I replace the line by pushing the "leaving" button aka btn_geht?
Code:
namespace Zieterfassung_0._0._2pre_alpha
{
public partial class Zeiten : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung`\obj\Debug\Zeiten.txt";`
tb_User.Text = WindowsIdentity.GetCurrent().Name.ToString();
tb_Datum.Text = DateTime.Now.ToString("dd.MM.yyyy");
tb_Zeit.Text = DateTime.Now.ToString("hh:mm");
cZeile KommtDatumZeit = new cZeile();
if (File.Exists(sPath))
{
using (StreamReader sr = new StreamReader(sPath))
{
while (!sr.EndOfStream)
{
KommtDatumZeit = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
}
}
tb_Kommt.Text = KommtDatumZeit.dtKommt.ToString();
}
protected void btn_Kommt_Click(object sender, EventArgs e)
{
string ID = DateTime.Now.ToString("yyyyMMdd_hhmm");
string sAusgabeKommt = string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};;", ID, tb_User.Text, tb_Datum.Text, tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
if (!fi.Exists)
{
fi.Create().Dispose();
}
using (StreamWriter sw = File.AppendText(sPath))
{
sw.Write(sAusgabeKommt);
}
}
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sAusgabeGeht = string.Format("{0:hh:mm}", tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
Geht.Geht = DateTime.Now.ToString("hh:mm");
Geht.dtGeht = DateTime.Now;
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
}
Helper Class:
namespace Prog
{
public static class cZeiterfassung
{
public static cZeile GetZeileObjectFromZeileString(string Zeile, string Trenner)
{
cZeile ZeileReturn = new cZeile();
string[] separators = { Trenner };
string[] arZeile = Zeile.Split(separators, StringSplitOptions.None);
ZeileReturn.ID = arZeile[0];
if (arZeile[1].IndexOf("\\") != -1)
{
ZeileReturn.Domain = arZeile[1].Substring(0, arZeile[1].IndexOf("\\"));
if (arZeile[1].Length >= arZeile[1].IndexOf("\\"))
ZeileReturn.User = arZeile[1].Substring(arZeile[1].IndexOf("\\") + 1);
}
else
ZeileReturn.User = arZeile[1];
ZeileReturn.Datum = arZeile[2];
ZeileReturn.Kommt = arZeile[3];
ZeileReturn.Geht = arZeile[4];
if(!string.IsNullOrEmpty(arZeile[2]))
ZeileReturn.dtDatum = Convert.ToDateTime(arZeile[2]);
if(!string.IsNullOrEmpty(arZeile[3]))
ZeileReturn.dtKommt = Convert.ToDateTime(arZeile[3]);
if (!string.IsNullOrEmpty(arZeile[4]))
ZeileReturn.dtGeht = Convert.ToDateTime(arZeile[4]);
return ZeileReturn;
}
}//cZeiterfassung
public class cZeile
{
public string ID { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Datum { get; set; }
public string Kommt { get; set; }
public string Geht { get; set; }
public DateTime dtDatum { get; set; }
public DateTime dtKommt { get; set; }
public DateTime dtGeht { get; set; }
public string Dauer { get; set; }
}
}
I got the code of detecting poor grammar from here - Detecting Poor grammar
I am new to C# and Xamarin. I want to merge this code into my speech to text conversion app.
I tried to do it, but I am not getting the desired results.
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
namespace SpeechToText
{
[Activity(Label = "SpeechToText", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, IRecognitionListener
{
public const string Tag = "VoiceRec";
SpeechRecognizer Recognizer { get; set; }
Intent SpeechIntent { get; set; }
TextView Label { get; set; }
TextView Label1 { get; set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
Recognizer.SetRecognitionListener(this);
SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
var button = FindViewById<Button>(Resource.Id.btn);
button.Click += ButtonClick;
var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
Grammarbutton.Click += new EventHandler(ButtonClick2);
Label = FindViewById<TextView>(Resource.Id.tv);
Label1 = FindViewById<TextView>(Resource.Id.tv1);
}
private void ButtonClick(object sender, EventArgs e)
{
Recognizer.StartListening(SpeechIntent);
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches != null && matches.Count > 0)
{
Label.Text = matches[0];
}
}
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
for (; ; )
{
Console.Write("Text to check: ");
var text = Label.Text;
if (string.IsNullOrEmpty(text)) break;
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
public void OnReadyForSpeech(Bundle #params)
{
Log.Debug(Tag, "OnReadyForSpeech");
}
public void OnBeginningOfSpeech()
{
Log.Debug(Tag, "OnBeginningOfSpeech");
}
public void OnEndOfSpeech()
{
Log.Debug(Tag, "OnEndOfSpeech");
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Log.Debug("OnError", error.ToString());
}
public void OnBufferReceived(byte[] buffer) { }
public void OnEvent(int eventType, Bundle #params) { }
public void OnPartialResults(Bundle partialResults) { }
public void OnRmsChanged(float rmsdB) { }
}
}
class GingerItApi
{
public CheckResult Check(string text)
{
var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
WebResponse response = null;
try
{
response = request.GetResponse();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string data = reader.ReadToEnd();
var first = data.IndexOf('{');
var last = data.LastIndexOf('}');
var json = data.Substring(first, last - first + 1);
return JsonConvert.DeserializeObject<CheckResult>(json);
}
}
}
catch (Exception)
{
throw;
}
return null;
}
}
public class LrnFrgOrigIndx
{
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Mistake
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("CanAddToDict")]
public bool CanAddToDict { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Suggestion
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("LrnCatId")]
public int LrnCatId { get; set; }
[JsonProperty("Text")]
public string Text { get; set; }
}
public class Correction
{
[JsonProperty("Confidence")]
public int Confidence { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("LrnFrg")]
public string LrnFrg { get; set; }
[JsonProperty("LrnFrgOrigIndxs")]
public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }
[JsonProperty("Mistakes")]
public IList<Mistake> Mistakes { get; set; }
[JsonProperty("ShouldReplace")]
public bool ShouldReplace { get; set; }
[JsonProperty("Suggestions")]
public IList<Suggestion> Suggestions { get; set; }
[JsonProperty("To")]
public int To { get; set; }
[JsonProperty("TopLrnCatId")]
public int TopLrnCatId { get; set; }
[JsonProperty("Type")]
public int Type { get; set; }
[JsonProperty("UXFrgFrom")]
public int UXFrgFrom { get; set; }
[JsonProperty("UXFrgTo")]
public int UXFrgTo { get; set; }
}
public class Sentence
{
[JsonProperty("FromIndex")]
public int FromIndex { get; set; }
[JsonProperty("IsEnglish")]
public bool IsEnglish { get; set; }
[JsonProperty("ToIndex")]
public int ToIndex { get; set; }
}
public class CheckResult
{
[JsonProperty("Corrections")]
public IList<Correction> Corrections { get; set; }
[JsonProperty("Sentences")]
public IList<Sentence> Sentences { get; set; }
}
I want to get the recognized speech, send it to grammar corrector, and display the output.
Please help me to solve this, or at least help me to further research the problem.
Thank you.
You have put an infinite loop in your code. Please remove it.
For example:
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
Console.Write("Text to check: ");
var text = Label.Text;
if (!string.IsNullOrEmpty(text))
{
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Label1.Text = "Looks okay.\n";
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
And the result is:
I have the following class, which has Fixture as the parent class -> FixtureSensors etc are child classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FixtureData
{
class Fixture
{
public int Id { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public List<FixtureSensors> Sensors = new List<FixtureSensors>();
public List<FixturePneumaticValves> Valves { get; set; }
}
class FixturePneumaticValves
{
public int Id { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
public string Type { get; set; }
public List<FixturePneumaticUnits> Units { get; set; }
}
class FixtureSensors
{
public string Fixture { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
public string Unit { get; set; }
}
class FixturePneumaticUnits
{
public string Fixture { get; set; }
public string Hardware { get; set; }
public string Connection { get; set; }
}
}
I would like to display information from the different classes on a datagridview which is editable. I managed to display this information, however to make the datagridview editable I had to include a class after the linq select new statement:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FixtureData;
namespace GridViewObjects_DB
{
public partial class Form1 : Form
{
private BindingSource source = new BindingSource();
static List<Fixture> Fixtures = new List<Fixture>()
{
new Fixture() { Id = 0, Name = "S7K010LFX1", Type = "GEO WELDING",Sensors = new List<FixtureSensors>()
{
new FixtureSensors(){Connection = "0.0", Hardware = "S7K010LFX1VS1",Unit = "102L-C1"},
new FixtureSensors(){Connection = "0.1", Hardware = "S7K010LFX1VS1",Unit = "103L-C1"},
new FixtureSensors(){Connection = "0.2", Hardware = "S7K010LFX1VS1",Unit = "103L-C1"},
new FixtureSensors(){Connection = "0.3", Hardware = "S7K010LFX1VS1",Unit = "104L-C1"},
new FixtureSensors(){Connection = "0.4", Hardware = "S7K010LFX1VS1",Unit = "105L-C1"}
},Valves = new List<FixturePneumaticValves>()
{
new FixturePneumaticValves(){Id=0,Connection = "0.0",Hardware = "S7K010LFX1VS1",Type = "Clp",Units = new List<FixturePneumaticUnits>()
{
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "0.6"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.0"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.2"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.4"},
new FixturePneumaticUnits(){Hardware = "S7K010LFX1VS1",Connection = "1.6"}
}
}
}
}
};
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
source.DataSource =(from fixture in Fixtures
from sensors in fixture.Sensors
select new Fixture() {Name = sensors.Fixture}
);
dataGridView1.DataSource = source;
dataGridView1.ReadOnly = false;
dataGridView1.Enabled = true;
}
}
}
This limits me to only display properties of the Fixture class and I would like to know of a way around this.
I searched over the internet and saw many questions about it, i tried many suggestion solutions, but nothing seems to work for me (maybe i am not implementing something right)
Here is my aspx.cs code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
public partial class Default : Page
{
static List<Member> memberList = new List<Member>();
static string fileName = #"C:\Users\Nir - PC\Desktop\public\gradesClient.json";
protected void Page_Load(object sender, EventArgs e)
{
if (File.Exists(fileName))
{
using (StreamReader re = new StreamReader(fileName))
{
JsonTextReader reader = new JsonTextReader(re);
JsonSerializer se = new JsonSerializer();
object parsedData = se.Deserialize(reader);
string json = JsonConvert.SerializeObject(parsedData);
Console.Write(json);
}
}
}
protected void addBtn_Click(object sender, EventArgs e)
{
memberList = JsonConvert.DeserializeObject<List<Member>>(File.ReadAllText(fileName));
Member member = new Member();
member.id = 4;
member.name = name.Value;
member.email = email.Value;
member.Date = date.Value;
member.Address = address.Value;
member.Country = country.Value;
member.Zip = zip.Value;
member.Grade = Int32.Parse(grade.Value);
member.Course = course.Value;
memberList.Add(member);
string json = JsonConvert.SerializeObject(memberList.ToArray());
File.WriteAllText(fileName, json);
}
}
public class Member
{
public int id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string Date { get; set; }
public string Address { get; set; }
public string Country { get; set; }
public string Zip { get; set; }
public int Grade { get; set; }
public string Course { get; set; }
public Member()
{
}
}
the error happens when it reach to line File.WriteAllText(fileName, json);
Please help me to fix the problem,
Please provide example code.
Thanks
I am trying to show out History for my windows 8 application which includes date, time , Floor ,Zone , Longitutde and latitude. I tried the code below but there was no output in it above.
THe image you can see on the link down below that I want to show on my application.But I can see nothing when I run my program.
I have three classes for using linq to sql to retrieve database and show information through it.The main class is History.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO.IsolatedStorage;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Text;
using System.Data.Linq;
namespace SmartParking
{
public partial class History : PhoneApplicationPage
{
private readonly HistoryDataContext historylog;
public History()
{
InitializeComponent();
// createDB();
}
public HistoryDataContext Log
{
get { return historylog; }
}
public void createDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
if (historylog.DatabaseExists() == false)
{
historylog.CreateDatabase();
addDataDB();
}
}
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
// Date = DateTime.Today,
// Time = DateTime.Now.TimeOfDay,
Zone = Checkin.Zone_st,
Floor = Checkin.Floor_st,
location_latitude = Checkin.Latitud_do,
location_longtitud = Checkin.Longtitude_do
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
public IList<HistoryDB> GetHistoryLog()
{
IList<HistoryDB> HistoryList = null;
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
IQueryable<HistoryDB> query = from histoy in historylog.history select histoy;
HistoryList = query.ToList();
}
return HistoryList ;
}
}
}
The next class is HistoryDB.cs with the tables and columns
[Table]
public class HistoryDB
{
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public TimeSpan Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
The next class is HistoryDataContext.cs.
public class HistoryDataContext:DataContext
{
public static string DBConnectionString = "Data Source=isostore:/History.sdf";
public HistoryDataContext(string DBConnectionString)
: base(DBConnectionString)
{
}
public Table<HistoryDB> history
{
get
{
return this.GetTable<HistoryDB>();
}
}
}
What I am trying is to get information from the NFC tag and store it in the local database and then retrieve it in the history page. The code below is to read from nfc tag but I dunno how again to save in the local databse from there and retrive it back in the history page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Networking.Proximity;
using NdefLibrary.Ndef;
using NdefLibraryWp.Ndef;
using Windows.Networking.Sockets; // needed for DataReader, DataWriter
using Windows.UI.Popups;
using Microsoft.Phone.UserData;
using System.Text;
using Windows.Phone.PersonalInformation;
using SmartParking.Resources;
using System.Diagnostics;
namespace SmartParking
{
public partial class Checkin : PhoneApplicationPage
{
private ProximityDevice _device;
private long _subscriptionIdNdef;
public static double Latitud_do { get; set; }
public static double Longtitude_do { get; set; }
public static string Floor_st { get; set; }
public static string Zone_st { get; set; }
History store = new History();
public Checkin()
{
InitializeProximityDevice();
InitializeComponent();
}
private void SetLogStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (LogStatus != null) LogStatus.Text = newStatus; });
}
private void SetFloorStatus(string newStatus)
{
Dispatcher.BeginInvoke(() => { if (FloorStatus != null) FloorStatus.Text = newStatus; });
}
private void ApplicationBarIconButton_Click(object sender, System.EventArgs e)
{
MessageBox.Show(" ");
}
private void InitializeProximityDevice()
{
_device = Windows.Networking.Proximity.ProximityDevice.GetDefault();
if (_device != null)
{
_subscriptionIdNdef = _device.SubscribeForMessage("NDEF", MessageReceivedHandler);
}
}
private void MessageReceivedHandler(ProximityDevice sender, ProximityMessage message)
{
var rawMsg = message.Data.ToArray();
var ndefMessage = NdefMessage.FromByteArray(rawMsg);
////// Loop over all records contained in the NDEF message
foreach (NdefRecord record in ndefMessage)
{
if (NdefTextRecord.IsRecordType(record))
{
// Convert and extract URI info
var textRecord = new NdefTextRecord(record);
//var str = textRecord.Text;
string[] str = textRecord.Text.Split('|');
var latitude = str[2];
Latitud_do = double.Parse(latitude);
var longtitude = str[3];
Longtitude_do = double.Parse(longtitude);
var Floor_st = str[0];
var Zone_st = str[1];
SetLogStatus("Floor: " + Floor_st + " Zone: " + Zone_st );
SetFloorStatus("Longitude: " + latitude + " Longitude: " + longtitude);
store.addDataDB();
}
}
}
}
}
The Image of the table is in the link below
https://www.dropbox.com/s/g87yta6hegjstge/Untitled.png?dl=0
try this:
In Database There Should be a Primary key otherwise it would Throw an Exception and the Datatype that is TimeSpan not supported so you need to take DateTime or String as Done Below :
[Table]
public class HistoryDB
{
[Column(IsPrimaryKey = true)]
public int Id { get; set; }
[Column(CanBeNull = false)]
public DateTime Date
{ get; set; }
[Column(CanBeNull = false)]
public DateTime Time
{ get; set; }
[Column(CanBeNull = false)]
public String Zone
{ get; set; }
[Column(CanBeNull = false)]
public String Floor
{ get; set; }
[Column(CanBeNull = false)]
public double location_latitude
{ get; set; }
[Column(CanBeNull = false)]
public double location_longtitud
{ get; set; }
}
public void addDataDB()
{
using (HistoryDataContext historylog = new HistoryDataContext(HistoryDataContext.DBConnectionString))
{
HistoryDB hdb = new HistoryDB
{
Id = 0,
Date = DateTime.Today,
Time = DateTime.Now,
Zone = "Zone",
Floor = "Floore",
location_latitude = 00.00,
location_longtitud = 00.00
};
historylog.history.InsertOnSubmit(hdb);
historylog.SubmitChanges();
GetHistoryLog();
}
}
I have implemented above thing and its working Properly