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; }
}
}
Related
Good day Stackoverflow,
I want to write some text at a specific point of a line in a txt-file.
So I want to write something between two ; in the line.
The Line of the textfile is: 20180912_0149;KIV\vischer;12.09.2018;01:49;; .
I want to write it if I click the "Geht" Button. I tried different things with streamreader and writer but I don't get to a solution.
Here is my code of the aspx.cs and my helper class:
Aspx.cs:
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_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(), ";");
}
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
Helperclass for splitting and array:
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 can't quite Point out what are you trying to do from your code, but from the question you asked:
I would look into every line if you are looking for a specific line
string Data = "";
using(StreamReader Sr = new StreamReader(Path))
{
while(!Sr.EndOfStream())
{
string UseMe = Sr.ReadLine();
Data += UseMe;
}
}
Now you could just validate each line. With the Data-string I gave you a possibility to build each line into one string
I hope I could help you, otherwise contact me directly (I also speak german I guess this is easier for you)
If your file isn't big, I propose you to write to new files with new data.
This is the idea
string[] lines = File.ReadAllLines(sPath);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].IndexOf(";;") != -1)
{
lines[i] = lines[i].Insert(line.IndexOf(";;"), "xxx");
}
}
File.WriteAllLines(sPathTemp, lines);
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 want to write my items by JSON format, but My files empty. Here is my two class:
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString(string jsonData)
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part = new DocPart
{
Title = "chapter1",
"chapter2",
Checked = checkBox1.Checked,
checkbox2.Checked
};
config.Parts.Add(part);
var configString = config.SaveToString();
File.WriteAllText(#"C:\link to my file", configString);
var configString = File.ReadAllText(#"C:\link to my file");
var config = DocConfig.LoadFromString(configString);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
chekbox1.Checked = part.Checked;
if (part.Title == "chapter2")
checkbox2.Checked = part.Checked;
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
return config;
}
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
So I run my program, everything looks okey, but my file is still empty without any JSON format data. Maybe you could help me?
Thanks.
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString()
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part1 = new DocPart
{
Title = "chapter1",
Checked = checkBox1.Checked
};
config.Parts.Add(part1);
var part2 = new DocPart
{
Title = "chapter2",
Checked = checkBox2.Checked
};
config.Parts.Add(part2);
var configString = config.SaveToString();
File.WriteAllText(#"d:\temp\test.json", configString);
configString = File.ReadAllText(#"d:\temp\test.json");
var ms = new MemoryStream(Encoding.UTF8.GetBytes(configString));
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
config = (DocConfig)serializer.ReadObject(ms);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
{
chekbox1.Checked = part.Checked;
Debug.WriteLine("chapter1" + part.Checked);
}
if (part.Title == "chapter2")
{
checkbox2.Checked = part.Checked;
Debug.WriteLine("chapter2" + part.Checked);
}
}
return config;
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
Here's a really simple example I mocked up for you...
void Main()
{
const string filePath = #"C:\FilePath\json.txt";
const string testJson = #"{""glossary"": {""title"": ""example glossary"", ""GlossDiv"": {""title"": ""S"", ""GlossList"": {""GlossEntry"": {""ID"": ""SGML"", ""SortAs"": ""SGML"", ""GlossTerm"": ""Standard Generalized Markup Language"", ""Acronym"": ""SGML"", ""Abbrev"": ""ISO 8879:1986"", ""GlossDef"": {""para"": ""A meta-markup language, used to create markup languages such as DocBook."", ""GlossSeeAlso"": [""GML"", ""XML""]}, ""GlossSee"": ""markup""}}}}}";
// Now we have our Json Object...
SampleJson sample = JsonConvert.DeserializeObject<SampleJson>(testJson);
// We convert it back into a string with indentation...
string jsonString = JsonConvert.SerializeObject(sample, Newtonsoft.Json.Formatting.Indented);
// Now simply save to file...
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(jsonString);
}
Process.Start(filePath);
}
// The following classes are what the `testJson` string is deserialized into.
public class GlossDef
{
[JsonProperty("para")]
public string Para { get; set; }
[JsonProperty("GlossSeeAlso")]
public string[] GlossSeeAlso { get; set; }
}
public class GlossEntry
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("SortAs")]
public string SortAs { get; set; }
[JsonProperty("GlossTerm")]
public string GlossTerm { get; set; }
[JsonProperty("Acronym")]
public string Acronym { get; set; }
[JsonProperty("Abbrev")]
public string Abbrev { get; set; }
[JsonProperty("GlossDef")]
public GlossDef GlossDef { get; set; }
[JsonProperty("GlossSee")]
public string GlossSee { get; set; }
}
public class GlossList
{
[JsonProperty("GlossEntry")]
public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossList")]
public GlossList GlossList { get; set; }
}
public class Glossary
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossDiv")]
public GlossDiv GlossDiv { get; set; }
}
public class SampleJson
{
[JsonProperty("glossary")]
public Glossary Glossary { get; set; }
}
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;
}
}
}
I have one list that is written to this class:
public class keyfrs
{
public keyfrs() { }
public long regID { get; set; }
public long ID { get; set; }
public string county { get; set; }
public string state { get; set; }
}
List<keyfrs> k = {1,2,3,4}] regID
{A,B,C,D} ID
I have another list class like this:
public class states
{
public states() { }
public long regID { get; set; }
public string state { get; set; }
public string county { get; set; }
}
List<states> s = {1,2,3,4}regID
{MA,NY,CT}state
{Suffolk,NY,Hampden}county
Want to write the county and state to the keyfrs list that matches with the regID from the lists.
What my program does so far is parse in two files and write each one to the different class list it corresponds to. As you can see both classes have a regID column. What I need to do is match the two lists together on regID and write the county and state to the keyfrs list class to then output that list to a new file with these added column in it.
static void Main(string[] args)
{
PARSEkeYfrs();
parsestateFile();
matchValues();
outputFile();
}
private static void outputFile()
{
string filename = #"c:\keyswCounty.csv";
using(StreamWriter write = new StreamWriter(filename))
{
write.WriteLine("RegIF"+","+"ID"+","+"County"+","+"State");
foreach(keyfrs k in keysandID)
{
write.WriteLine(k.regID +"," +k.ID+","+k.county+","+k.state);
}
}
}
private static void matchValues()
{
foreach(keyfrs k in keysandID)
{
}
}
private static void parsestateFile()
{
int a = 0;
string filename = #"c:\ALLStates.txt";
using (StreamReader read = new StreamReader(filename))
{
read.ReadLine();
while (!read.EndOfStream)
{
a++;
try{
string line = read.ReadLine();
string[] splitline = line.Split(',');
if(splitline[1]!="")
{
states s = new states();
s.regID = Convert.ToInt64(splitline[0]);
s.county = Convert.ToString(splitline[1]);
s.state = Convert.ToString(splitline[2]);
stateFile.Add(s);
}
}
catch(Exception ex)
{
string.Format("error:{0}" + ex.Message.ToString());
}
}
}
}
private static void PARSEkeYfrs()
{ int a = 0;
string filename = #"c:\key_frs.csv";
using (StreamReader read = new StreamReader(filename))
{
read.ReadLine();
while (!read.EndOfStream)
{
try{
a++;
string line = read.ReadLine();
string[] splitline = line.Split(',');
if(splitline[1]!="")
{
keyfrs k = new keyfrs();
k.regID = Convert.ToInt64(splitline[0]);
k.ID = Convert.ToInt64(splitline[1]);
k.county = "";
k.state = "";
keysandID.Add(k);
}
}
catch(Exception ex)
{
string.Format("error:{0}"+ex.Message.ToString());
}
}
}
}
switched the state list to a dictionary and matched the values by the key value pair by using the TryGetValue method.