Using Linq to sql for windows phone - c#

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

Related

How to fix DbUpdateConcurrencyException when removing multiple entries?

I receive this error when trying to remove entries from the table with EFC
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 30 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
This is my code:
https://paste.mod.gg/xlynuworjmmf/0
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MySql.EntityFrameworkCore;
namespace Flanium_Agent
{
public class AgentContext : DbContext
{
public DbSet<Agent> agent { get; set; }
public DbSet<AgentRequest> agentRequest { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("Server=localhost;User ID=root;Database=orchestration_db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
modelBuilder.Entity<Agent>().ToTable("agents");
modelBuilder.Entity<AgentRequest>().HasKey(a => a.Station);
modelBuilder.Entity<AgentRequest>().ToTable("agent_requests");
}
}
public class Agent
{
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
}
public class AgentRequest
{
public string Station { get; set; }
public string Request { get; set; }
}
public class Agency : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private bool ProcessRunning = false;
private List<string> RequestList = new List<string>();
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
public string Request { get; set; }
private Grid DisplayGrid { get; set; }
private Window appWindow { get; set; }
public Grid GetDisplayGrid()
{
return DisplayGrid;
}
public Agency InsertAgentToGrid(Window mainWindow)
{
DisplayGrid = new Grid();
var headerRowDefinition = new RowDefinition();
headerRowDefinition.Height = new GridLength(50);
DisplayGrid.RowDefinitions.Add(headerRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var property = GetType().GetProperties()[index];
var header = new TextBlock();
var column = new ColumnDefinition();
header.Text = property.Name;
header.HorizontalAlignment = HorizontalAlignment.Center;
header.VerticalAlignment = VerticalAlignment.Center;
header.FontSize = 16;
header.FontWeight = FontWeights.Medium;
Grid.SetRow(header, 0);
Grid.SetColumn(header, index);
DisplayGrid.ColumnDefinitions.Add(column);
DisplayGrid.Children.Add(header);
}
var contentRowDefinition = new RowDefinition();
contentRowDefinition.Height = GridLength.Auto;
DisplayGrid.RowDefinitions.Add(contentRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var propertyValue = GetType().GetProperties()[index];
var content = new TextBlock();
content.HorizontalAlignment = HorizontalAlignment.Center;
content.VerticalAlignment = VerticalAlignment.Center;
content.FontSize = 12;
content.TextWrapping = TextWrapping.Wrap;
Grid.SetRow(content, 1);
Grid.SetColumn(content, index);
DisplayGrid.Children.Add(content);
var myBinding = new Binding(propertyValue.Name)
{
Source = this,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
content.SetBinding(TextBlock.TextProperty, myBinding);
}
DisplayGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
DisplayGrid.VerticalAlignment = VerticalAlignment.Top;
DisplayGrid.Margin = new Thickness(0, 25, 0, 0);
(mainWindow.Content as Grid).Children.Add(DisplayGrid);
appWindow = mainWindow;
return this;
}
private string[] GetPackages()
{
var packagesArray = new List<string>();
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathString = Path.Combine(desktopPath, "Flanium Agent Data");
var packageFolders = Directory.GetDirectories(pathString);
foreach (var packFolder in packageFolders)
{
var versions = Directory.GetDirectories(packFolder);
if (versions.Length != 0)
{
packagesArray.AddRange(versions.Select(version => version.Split('\\').Last())
.Select(versionName => packFolder.Split('\\').Last() + "\\" + versionName));
packagesArray = packagesArray.Select(x => x = pathString + "\\" + x).ToList();
}
}
return packagesArray.ToArray();
}
public Agency(string station, string process, string actions, string started, string finished, string status)
{
try
{
using (var context = new AgentContext())
{
context.agent.Add(new Agent
{Station = station, Process = process, Actions = actions, Started = started, Finished = finished, Status = status});
// Saves changes
context.SaveChanges();
}
Station = station;
Process = process;
Actions = actions;
Started = started;
Finished = finished;
Status = status;
}
catch (Exception e)
{
}
}
public void RemoveAgent()
{
using (var context = new AgentContext())
{
context.agent.Where(x=> x.Station == Station).ToList().ForEach(x=> context.agent.Remove(x));
// Saves changes
context.SaveChanges();
}
}
}
}
I followed a tutorial on the internet on how to use EFC by the teeth and for some euclidean reason, as always, the code works for others and the same code does not work when I try it out.
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
So you have an entity Agent, about which you tell Entity Framework that it has a primary key column named "station".
You have a database with at least 30 records in it, and at least 30 of those records have the same value for the station column.
So despite you telling EF that station is the primary key, it isn't. So EF generates the query:
DELETE FROM agent WHERE station=#station
And the database engine happily removes all 30 records for which the station equals the station of the first record it encounters, and reports this, then EF throws, because it expected one record to be deleted, not 30.
The solution: configure the actual primary key as key, or if there isn't any, create one.

Unable to cast object of type 'System.Collections.Generic.List`1 to type System.Windows.Forms.BindingSource' [duplicate]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using project2;
namespace project
{
public enum TankData
{
Name = 0,
Cannon =1,
Weight =2,
TopSpeed =3,
Armor =4,
YearProduced =5,
Production =6,
CruisingSpeed =7,
TurretTurn =8,
Classifaction= 9,
Crew =10,
NATOorNonNATO =11,
Period =12,
Era = 13,
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable table = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
}
#region Event Handlers
private void button1_Click(object sender, EventArgs e)
{
LoadData();
}
#endregion
#region Class Helpers
protected void LoadData()
{
List<TankClass> tanks = new List<TankClass>();
string[] lines = File.ReadAllLines(#"C:\Users\bluehalo\Documents\tank chart 2.txt");
for (int i = 0; i < lines.Length; i++)
{
TankClass tank = new TankClass(lines[i].ToString());
tanks.Add(tank);
}
dataGridView1.DataSource = tanks;
}
#endregion
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
So I've been trying to filter my datagridview using a text box and I have tried using:
"(DataGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '{0}%' OR Name LIKE '% {0}%'", TextBox.Text);"
but it kept returning a null error. Is there a way to fix this?
Edit: here's the TankClass class, sorry I forgot to put this in earlier.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using project;
namespace project2
{
class TankClass
{
protected bool _isLoaded = false;
#region Class Property
public string Tankname { get; set; }
public int Caliber { get; set; }
public double Weight { get; set; }
public double TopSpeed { get; set; }
public int Armor { get; set; }
public int Year { get; set; }
public int Production { get; set; }
public int CruisingSpeed { get; set; }
public int TurretTurn { get; set; }
public string Classification { get; set; }
public string Era { get; set; }
public int Crew { get; set; }
public string Country { get; set; }
public string Faction { get; set; }
#endregion
#region Constructor(s)
public TankClass()
{
}
public TankClass(string concatProps)
{
string[] values = concatProps.Split(new char[] { ',' });
Tankname = values[(int)TankData.Name];
Caliber = Convert.ToInt32(values[(int)TankData.Cannon]);
Weight = Convert.ToDouble(values[(int)TankData.Weight]);
TopSpeed = Convert.ToDouble(values[(int)TankData.TopSpeed]);
Armor = Convert.ToInt32(values[(int)TankData.Armor]);
Year = Convert.ToInt32(values[(int)TankData.YearProduced]);
Production = Convert.ToInt32(values[(int)TankData.Production]);
CruisingSpeed = Convert.ToInt32(values[(int)TankData.CruisingSpeed]);
TurretTurn = Convert.ToInt32(values[(int)TankData.TurretTurn]);
Classification = values [(int)TankData.Classifaction];
Crew = Convert.ToInt32(values[(int)TankData.Crew]);
Era = values[(int)TankData.Era];
Country = values[(int)TankData.NATOorNonNATO];
Faction = values[(int)TankData.Period];
_isLoaded = true;
}
public TankClass(string tankname, int caliber, float weight, float topSpeed, int armor, int year, int numbers, int cruisingSpeed, int turretTurn, string classification, int crew, string country, string nATOorNotNATO, string timePeriod)
{
Tankname = tankname;
Caliber = caliber;
Weight = weight;
TopSpeed = topSpeed;
Armor = armor;
Year = year;
Production = numbers;
CruisingSpeed = cruisingSpeed;
TurretTurn = turretTurn;
Classification = classification;
Crew = crew;
Era = country;
Country = nATOorNotNATO;
Faction = timePeriod;
_isLoaded = true;
}
#endregion
}
}
If you want to be able to filter and sort, then you can use the SortableList<T> as above.
If you really just want to filter, though, it's as simple as this: store the tanks list, and assign the datasource as a subset of tanks when the filter changes:
// 'tanks' is stored as a field when loaded from disk
private List<TankClass> tanks;
protected void LoadData()
{
tanks = new List<TankClass>();
string[] lines = File.ReadAllLines(#"C:\Users\bluehalo\Documents\tank chart 2.txt");
for (int i = 0; i < lines.Length; i++)
{
TankClass tank = new TankClass(lines[i].ToString());
tanks.Add(tank);
}
dataGridView1.DataSource = tanks;
}
And when you want to filter:
private void textBox1_TextChanged(object sender, EventArgs e)
{
// name contains text
dataGridView1.DataSource = tanks.Where(t => t.Name.IndexOf(textBox1.Text, StringComparison.OrdinalIgnoreCase) > -1).ToList()
}

Class with hierarchy to DataGridview

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.

System.IO.IOException: file used by another process when try to write to file

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

Drawing polyline with JSON data on Windows Phone Map application

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

Categories

Resources