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:
Related
I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}
I have list in class
public List<Igrac> Igraci { get; set; } = new List<Igrac>();
The class:
class Igrac
{
public string Ime { get; set; }
public string Prezime { get; set; }
public string Pozicija { get; set; }
public int Godine { get; set; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
Added new list elements:
noviklb.DodavanjeIgraca(new Igrac("Petar", "Petrovic", "Krilo", 1992));
noviklb.DodavanjeIgraca(new Igrac("Badr", "Hari", "Napad", 1993));
The method for adding is working OK. The problem is that when I use Console.WriteLine I get an error like this:
System.Collections.Generic.List`1[zadatak.Program+Igrac]
I Googled and foreach is solution but I cant do it right. Do I need to write foreach as method?
class Igrac
{
public string Ime { get; }
public string Prezime { get; }
public string Pozicija { get; }
public int Godine { get; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
public override string ToString()
{
return $"{Ime} {Prezime} {Pozicija} {Godine}";
}
Now you can use.
string myStringDate = new Igrac("Petar", "Petrovic", "Krilo", 1992).ToString();
ALSO NOTE: It would be good to make you properties get only.
Working link:
https://dotnetfiddle.net/zMNiln
use this code:
public void showList(List<Igrac> noviklb)
{
foreach (var item in noviklb)
{
Console.WriteLine("Ime : " + item.Ime);
Console.WriteLine("Prezime : " + item.Prezime);
Console.WriteLine("Pozicija : " + item.Pozicija);
Console.WriteLine("Godine : " + item.Godine);
Console.WriteLine("Get New Record****************** ");
}
}
I created a new table "TravauxDBs" using Visual Studio, but when i call PullAsync it returns count = 0, so i guess it's empty. Then i get an error "not found".
Everything works fine using basic table ToDoItems, and i use the same code for this new table.
My item mobile side :
public class TravauxDB
{
public string Id { get; set; }
[JsonProperty(PropertyName = "nomtravail")]
public string NomTravail { get; set; }
[JsonProperty(PropertyName = "voie")]
public string Voie { get; set; }
[JsonProperty(PropertyName = "pk")]
public string PK { get; set; }
[JsonProperty(PropertyName = "quantity")]
public string Quantity { get; set; }
[JsonProperty(PropertyName = "unite")]
public string Unite { get; set; }
[JsonProperty(PropertyName = "observation")]
public string Observation { get; set; }
[JsonProperty(PropertyName = "idchantier")]
public string IdChantier { get; set; }
}
Service side :
public class TravauxDB : EntityData
{
public string NomTravail { get; set; }
public string Voie { get; set; }
public string PK { get; set; }
public string Quantity { get; set; }
public string Unite { get; set; }
public string Observation { get; set; }
public string IdChantier { get; set; }
}
Activity :
public class Travaux : ActionBarActivity
{
private Android.Support.V7.Widget.SearchView _searchView3;
private ListView _listView3;
private ArrayAdapter _adapter3;
private MobileServiceClient client;
private IMobileServiceSyncTable<TravauxDB> TravauxTable;
const string applicationURL = #"myurl";
const string applicationKey = #"mykey";
const string localDbFilename = "localstore.db";
public List<string> travaux { get; private set; }
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Layout_travaux);
CurrentPlatform.Init();
client = new MobileServiceClient(applicationURL, applicationKey);
await InitLocalStoreAsync();
TravauxTable = client.GetSyncTable<TravauxDB>();
await SyncAsync();
List<string> travaux = await ItemsOnly();
_listView3 = FindViewById<ListView>(Resource.Id.listView3);
_adapter3 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, travaux);
_listView3.Adapter = _adapter3;
_listView3.ItemClick += _listView3_ItemClick;
}
void _listView3_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
int pos = e.Position;
Intent b = new Intent(this, typeof(Travail));
Bundle bundle = new Bundle();
bundle.PutInt("Ntravail", pos);
b.PutExtras(bundle);
StartActivity(b);
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.main, menu);
var item = menu.FindItem(Resource.Id.action_search);
var searchItem = MenuItemCompat.GetActionView(item);
_searchView3 = searchItem.JavaCast<Android.Support.V7.Widget.SearchView>();
_searchView3.QueryTextChange += (s, e) => _adapter3.Filter.InvokeFilter(e.NewText);
_searchView3.QueryTextSubmit += (s, e) =>
{
Toast.MakeText(this, "Searched for: " + e.Query, ToastLength.Short).Show();
e.Handled = true;
};
return true;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
private async Task InitLocalStoreAsync()
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<TravauxDB>();
await client.SyncContext.InitializeAsync(store);
}
private async Task SyncAsync()
{
try
{
await client.SyncContext.PushAsync();
await TravauxTable.PullAsync("alltravaux", TravauxTable.CreateQuery()); // query ID is used for incremental sync
}
catch (Java.Net.MalformedURLException)
{
CreateAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
catch (Exception e)
{
CreateAndShowDialog(e, "Error");
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
public async Task<List<string>> ItemsOnly()
{
try
{
List<string> travaux = await TravauxTable
.Select(tr => tr.NomTravail).ToListAsync();
return travaux;
}
catch (MobileServiceInvalidOperationException e)
{
Console.Error.WriteLine(#"ERROR {0}", e.Message);
return null;
}
}
I also added a new controller for this, just replaced ToDoItem by TravauxDB :
public class TravauxController : TableController<TravauxDB>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ChantierContext context = new ChantierContext();
DomainManager = new EntityDomainManager<TravauxDB>(context, Request, Services);
}
// GET tables/TodoItem
public IQueryable<TravauxDB> GetAllTravauxDB()
{
return Query();
}
// GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<TravauxDB> GetTravauxDB(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<TravauxDB> PatchTravauxDB(string id, Delta<TravauxDB> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTravauxDB(TravauxDB item)
{
TravauxDB current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteTravauxDB(string id)
{
return DeleteAsync(id);
}
}
If something is missing or you need more details let me know.
Thank you by advance.
The client class name needs to match the server controller name. So, your class should be called Travaux instead of TravauxDB. Alternatively, you can use the attribute [TableName] on the class.
I have this:
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
public List<???prpClass???> Whatever(string prpClass)
where string prpClass can be "Blah" or "Doh".
I would like the List type to be class Blah or Doh based on what the string prpClass holds.
How can I achieve this?
EDIT:
public List<prpClass??> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result;
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result;
}
return null
}
}
you have to have a common supertype:
public interface IHaveAnId
{
int id { get;set; }
}
public class Blah : IHaveAnId
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh : IHaveAnId
{
public int id {get;set;}
public string dohh { get; set; }
public string mahh { get; set; }
}
then you can do:
public List<IHaveAnId> TheList = new List<IHaveAnId>();
and in some method:
TheList.Add(new Blah{id=1,blahh = "someValue"});
TheList.Add(new Doh{id =2, dohh = "someValue", mahh = "someotherValue"});
to iterate through the list:
foreach(IHaveAnId item in TheList)
{
Console.WriteLine("TheList contains an item with id {0}", item.id);
//item.id is allowed since you access the property of the class over the interface
}
or to iterate through all Blahs:
foreach(Blah item in TheList.OfType<Blah>())
{
Console.WriteLine("TheList contains a Blah with id {0} and blahh ='{1}'", item.id, item.blahh);
}
Edit:
the 2 methods and a int field holding the autovalue:
private int autoValue = 0;
public void AddBlah(string blahh)
{
TheList.Add(new Blah{id = autovalue++, blahh = blahh});
}
public void AddDoh(string dohh, string mahh)
{
TheList.Add(new Doh{id = autovalue++, dohh = dohh, mahh = mahh});
}
Another Edit
public List<object> Whatever(string prpClass)
{
using (var ctx = new ApplicationDbContext())
{
if (prpClass == "Blah")
{
string queryBlah = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Blah>(queryBlah).ToList();
return result.Cast<object>().ToList();
}
if (prpClass == "Doh")
{
string queryDoh = #"SELECT ... ";
var result = ctx.Database.SqlQuery<Doh>(queryDoh).ToList();
return result.Cast<object>.ToList();
}
return null;
}
}
in the view you then have to decide what type it is. In asp.net MVC you can use a display template and use reflection to get a good design. But then i still don't know what technology you are using.
Yet another Edit
TestClass:
public class SomeClass
{
public string Property { get; set; }
}
Repository:
public static class Repository
{
public static List<object> Whatever(string prpClass)
{
switch (prpClass)
{
case "SomeClass":
return new List<SomeClass>()
{
new SomeClass{Property = "somestring"},
new SomeClass{Property = "someOtherString"}
}.Cast<object>().ToList();
default:
return null;
}
}
}
And a controller action in mvc:
public JsonResult Test(string className)
{
return Json(Repository.Whatever("SomeClass"),JsonRequestBehavior.AllowGet);
}
then i called it with: http://localhost:56619/Home/Test?className=SomeClass
And got the result:
[{"Property":"somestring"},{"Property":"someOtherString"}]
Is this what you are trying to do?
public class Blah
{
public int id { get; set; }
public string blahh { get; set; }
}
public class Doh
{
public int id { get; set; }
public string dohh { get; set; }
public string mahh { get; set; }
}
class Program
{
public static List<T> Whatever<T>(int count) where T: new()
{
return Enumerable.Range(0, count).Select((i) => new T()).ToList();
}
static void Main(string[] args)
{
var list=Whatever<Doh>(100);
// list containts 100 of "Doh"
}
}
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;
}
}
}