Hello my main issue is how to use MKAnnotationView to set a custom pin image for all my coordinate points.
For reference, I've went ahead and hardcoded values that I will normally be calling down from a json webservice call.
Heres an example of a hardcoded trails:
CLLocationCoordinate2D[] trail1 = new CLLocationCoordinate2D[]{
new CLLocationCoordinate2D(10.74812, -97.330277),
new CLLocationCoordinate2D(10.74501, -97.350277),
new CLLocationCoordinate2D(10.74912, -97.340277),
};
CLLocationCoordinate2D[] trail2 = new CLLocationCoordinate2D[]{
new CLLocationCoordinate2D(10.84812, -97.331277),
new CLLocationCoordinate2D(10.94501, -97.352277),
new CLLocationCoordinate2D(10.14912, -97.343277),
new CLLocationCoordinate2D(10.12912, -97.313277),
};
mapview.AddAnnotation (new SampleMapAnnotation (trail1));
Right now I am using MKAnnotation but realized I need to use the MKAnnotationView for custom image pins.
public class SampleMapAnnotation : MKAnnotation
{
string _title;
public SampleMapAnnotation (CLLocationCoordinate2D coordinate)
{
Coordinate = coordinate;
_title = "Sample";
}
public override CLLocationCoordinate2D Coordinate { get; set; }
public override string Title
{
get {
return _title;
}
}
}
Have a look at the MapCallout sample from Xamarin. This is a C# port from the Objective-C sample by Apple. It will show you how to create image-based annotations and show them on a map.
Related
I have C# class which I need to convert to Json file, and I tried looking for some online tools to do that but could not find
Can someone know if we can change it to Json string online or not?
Sample c# class:
public enum Culture
{
GB,
US,
IT,
FR,
CA,
DE,
SE,
NL,
NZ,
AU,
AE,
CN,
JP,
IE,
IN,
ES
}
public class FullName
{
public string First;
public string Last;
public FullName(string first, string last)
{
this.First = first;
this.Last = last;
}
}
public class StringResourcesX
{
public static string HTMLAttribute_QA { get; set; }
public static string DOB { get; set; }
public static Dictionary<Culture, FullName> CulturalNames = new Dictionary<Culture, FullName>
{
{Culture.GB, new FullName(GB_Name, GB_LastName)},{Culture.US, new FullName(US_Name , US_LastName)},
{Culture.IT, new FullName(IT_Name, IT_LastName)},{Culture.ES, new FullName(ES_Name, ES_LastName)},
{Culture.FR, new FullName(FR_Name, FR_LastName)},{Culture.AE, new FullName(AE_Name, AE_LastName)},
{Culture.DE, new FullName(DE_Name, DE_LastName)},{Culture.NL, new FullName(NL_Name, NL_LastName)},
{Culture.JP, new FullName(JP_Name, JP_LastName)},{Culture.SE, new FullName(SE_Name, SE_LastName)},
{Culture.IE, new FullName(IE_Name, IE_LastName)},{Culture.AU, new FullName(AU_Name, AU_LastName)},
{Culture.CA, new FullName(CA_Name, CA_LastName)},{Culture.NZ, new FullName(NZ_Name, NZ_LastName)},
{Culture.IN, new FullName(IN_Name, IN_LastName)},{Culture.CN, new FullName(CN_Name, CN_LastName)}
};
}
I have really long file which I need to convert to Json string, so wanted to know rather doing it manually, if we have any online tool where we can use?
You may consider using NewtonSoft's JsonConvert.SerializeObject method:
https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm
For example:
var instance = new FullName {
First="Bob",
Last="DaBuilda"
};
string json = JsonConvert.SerializeObject(instance, Formatting.Indented);
you can try out this link : https://csharp2json.io/
and before you try to convert JSON assign the value of all class member.
this example is already given by on this web
im completly new to programing,
im trying to create something like a manga organizing tool in windows forms, but im getting stuck in populating a listbox with data from a deserialized json string, it currently is only displaying boolean values correctly all other values are "0" even strings.
i have a button to do this:
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Json Files|*.json", ValidateNames = true, Multiselect = false })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var fileStream = openFileDialog.OpenFile();
using (StreamReader sr = new StreamReader(fileStream))
{
string fileContent = sr.ReadToEnd();
ComicList comics = JsonConvert.DeserializeObject<ComicList>(fileContent);
Manga_listBox.DataSource = DisplayComic.FullList;
//ignore this little bit it's just so i can see what's happening
label1.Text = Convert.ToString(comics.Comics.Count);
label1.Text = Convert.ToString(DisplayComic.FullList);
}
}
}
and i have the following classes like so:
public class Comic
{
private string Manga;
private int Chapters;
private bool isFinished;
private int LastReadCH;
public string Manga1 { get => Manga; set => Manga = value; }
public int Chapters1 { get => Chapters; set => Chapters = value; }
public bool IsFinished { get => isFinished; set => isFinished = value; }
public int LastReadCH1 { get => LastReadCH; set => LastReadCH = value; }
public Comic(Comic asd)
{
this.Manga = Manga1;
this.Chapters = Chapters1;
this.IsFinished = IsFinished;
this.LastReadCH = LastReadCH1;
}
public override string ToString()
{
return string.Format("{0}, {1}, {2}, {3}",
this.Manga, this.Chapters, this.IsFinished, this.LastReadCH);
}
}
and
public class ComicList
{
private List<Comic> comics;
public List<Comic> Comics { get => comics; set => comics = value; }
}
and
public class DisplayComic
{
static DisplayComic()
{
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Json Files|*.json", ValidateNames = true, Multiselect = false })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
var fileStream = openFileDialog.OpenFile();
using (StreamReader sr = new StreamReader(fileStream))
{
string fileContent = sr.ReadToEnd();
ComicList comics = JsonConvert.DeserializeObject<ComicList>(fileContent);
FullList = comics.Comics;
}
}
}
}
private static List<Comic> fullList;
public static List<Comic> FullList { get => fullList; set => fullList = value; }
public static List<Comic> GetComcis()
{
return FullList;
}
}
code is probably quite messy, then again I'm completely new and have been following all kind of information online, also for some reason, the open dialog windows is opening twice I don't understand why.
here is the json file I'm using:
{
"Comics": [
{
"Manga": "MangaNumber1",
"Chapters": 85,
"isFinished": true,
"LastReadCH": 85
},
{
"Manga": "MangaNumber2",
"Chapters": 112,
"isFinished": true,
"LastReadCH": 112
},
{
"Manga": "MangaNumber3",
"Chapters": 117,
"isFinished": true,
"LastReadCH": 117
},
{
"Manga": "MangaNumber4",
"Chapters": 74,
"isFinished": true,
"LastReadCH": 74
}
]
}
I've tried pretty much anyone with my "expertise" could, changing all kind of variable names and so on, would really appreciate some help.
here's a screenshot of the problem:
as you can see only the boolean values are actually correct, otherwise they'd be false, all other values though...
EDIT:
the result im hopping for is to populate the listbox with the manga names, (thank you #beeker for that property thing) and once i select said manga then i want to create some other objects such as labels and text boxes to view and edit the values of the chapters etc, also i would like to be able to see what is being parsed by the json file how ever when i do this:
label1.Text = Convert.ToString(comics);
i get the label with the text "Manga_Organizer_2.ComicList"
By the way when i say im new, i mean i only ever did stuff with console apps using only "if" functions this whole parsing json, openfiledialog, and even classes usage is completly new. I also have no background in programing with any other language c# is the first and im loving it even though having terrible difficulties :)
Answer/Update:
All is good now :)
all i had to do was set
DisplayComic.FullList = comics.Comics;
in the openfiledialog right before setting the datasource for the listbox.
In the end it looks like this:
string fileContent = sr.ReadToEnd();
ComicList comics = JsonConvert.DeserializeObject<ComicList>(fileContent);
DisplayComic.FullList = comics.Comics;
Manga_listBox.DataSource = DisplayComic.FullList;
Manga_listBox.DisplayMember = "manga";
also removed the encapsulations alltogether in the comic class, in the end it looks like this:
public class Comic
{
public string Manga { get; set; }
public double Chapters { get; set; }
public bool IsFinished { get; set; }
public double LastReadCH { get; set; }
public string StartedOn { get; set; }
public string FinishedOn { get; set; }
}
and also the displaycomic class looks like this:
public class DisplayComic
{
public static List<Comic> FullList { get; set; }
public static List<Comic> GetComcis()
{
return FullList;
}
}
Also, after all this trouble came even more, i could deserialize the json, parse it to a string and then to a list, load, save and edit it and i also managed to serialize it back together, and with a savefiledialog create a file for it, however when i did, i would be unable to re-deserialize it once again, something about the json had changed (from object to array or vice versa), aside from that i also had problems with datetime stuff, couldn't load it correctly from a string and so on, anyway after a bunch of mishaps, and litteraly 17hours of looking at code with a puzzled face i finnaly finished my app :D!
It does all i want it to, load a json, save and edit it, put it back together, add and remove from it, and i learned a bunch from all this trouble, thank you all for helping, thanks to you guys learned how to set stuff to display on listboxes, and also very importantly "somewhat" learned how to debug code.
Thanks.
Try setting the listbox "DisplayMember" property so that the control knows which property of the class you want to see. Something like this...
Manga_listBox.DataSource = DisplayComic.FullList;
Manga_listBox.DisplayMember = "Manga";
Ref:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listcontrol.displaymember?view=netframework-4.8
Answer:
i removed that whole openfiledialog in the display comic class, renamed the encapsulations in the Comic class and done :D, now the openfiledialog only opens once and the values from the json are being correctly parsed to the comics list, thus enabling me to use them however i want, thank you, you pushed me in the right direction with the idea to learn debug stuff :D.
Now all that's left is learn how to create objects by selecting the different lines from the listbox, another challenge awaits this newcomer.
I am trying to solve uri address converting to image issue. Main idea , what I am doing I want to pick image from a gallery, bind it and save it to database. Everything is working, I can save string image path to class property, but unfortunately I can't convert that address to my imageSource where I will displaying my image, because now I see empty image circle.
This is where I am selecting image from gallery and trying to convert into image:
IGalleryImageService galleryService = Xamarin.Forms.DependencyService.Get<IGalleryImageService>();
galleryService.ImageSelected += (o, imageSourceEventArgs) =>
{
Uri uri = new Uri(imageSourceEventArgs.ImageSource);
(ActivePage.Page as PageTemplate).CarImage.Source = ImageSource.FromFile(uri.ToString());
ActivePage.CarImageBindable = (ActivePage.Page as PageTemplate).CarImage.Source.GetValue(StreamImageSource.StreamProperty).ToString(); // here I am trying to convert from path address to image
};
galleryService.SelectImage();
Here is my PageTemplate
public partial class PageTemplate: ContentPage
{
public CircleImage CarImage
{
get
{
return Car;
}
set
{
Car = value;
}
}
}
and PageTemplate.xaml where I am displaying images.
<controls:CircleImage x:Name="Car" AbsoluteLayout.LayoutBounds=".5,0,-1,-1" AbsoluteLayout.LayoutFlags="PositionProportional" Aspect="AspectFill">
</controls:CircleImage>
This is my bindable property from Unit2 class:
public string CarImageBindable
{
get
{
return base.CarImage;
}
set
{
base.CarImage = value;
OnPropertyChanged(nameof(CarImageBindable));
}
}
And another property from Core project Unit class:
public int Id { get; set; }
public DateTime StartDate { get; set; }
public string CarImage { get; set; }
That's why I decided to make all properties as string data type, because I want to save image path. And yes, then convert again from database to physical image.
Thank you for answers or suggestions.
Well, I solved issue like this:
IGalleryImageService galleryService = Xamarin.Forms.DependencyService.Get<IGalleryImageService>();
galleryService.ImageSelected += (o, imageSourceEventArgs) =>
{
ActiveParking.CarImageBindable = imageSourceEventArgs.ImageSource.ToString();
(ActiveParking.Page as PageTemplate).CarImage.Source = galleryService.GetImage(imageSourceEventArgs.ImageSource.ToString());
};
galleryService.SelectImage();
I am fairly new to arrays in C# and am used to storing a mass of data in a string and in INI files and then breaking it down into basic arrays using delimiters...so yeh, my knowledge is almost none existent.
My main form class begin this definition:
public CAirportData[] _AirportData; //size not known
This is the method I am using to create the array:
...string[] airports = possibleAirports.Split(','); //size is known
foreach (string airport in airports)
{
string[] rwys = inif.Read(airport, "rwys").Split(':'); //size is known (2)
_AirportData = new CAirportData[] { new CAirportData() { icao=airport, depRwy=rwys[0], arrRwy=rwys[1] } };
}
I know this just boils down to my limited knowledge of objects and arrays. But I can't seem to find anything on the internet that uses this sort of thing. I have tried to combine other peoples code with little success.
I need the _AirportData array to be available outside of the form hence public and declared outside of any methods. I supose the main problem is that I am overwriting array and foreach airport I am creating a new array hence loosing the previous. I had tried moving the ..= new CAirportData[] to all sorts of places but Visual Studio doesn't like it.
Below is the class definition for CAirportData:
public class CAirportData
{
public string icao { get; set; }
public string depRwy { get; set; }
public string arrRwy { get; set; }
public override string ToString()
{
string result = string.Format("ICAO: {0}, Dep: {1}, Arr: {2}", this.icao, this.depRwy, this.arrRwy);
return result;
}
}
public class CMRunways
{
public string icao { get; set; }
public string depRwy { get; set; }
public string arrRwy { get; set; }
}
Many thanks in advance for any help!
What you're looking for is generic List. Change the definition to:
public List<CAirportData> _AirportData = new List<CAirportData>();
Then the code in the loop to:
_AirportData.Add(new CAirportData { icao=airport, depRwy=rwys[0], arrRwy=rwys[1] });
This is what I would do...Create a static class, with a static property (airports) and add a static constructor to load the airports from file at the begining.
public static class Session
{
public static CAirportData[] _AirportData;
static Session()
{
string airports = possibleAirports.Split(",");
foreach (string airport in airports)
{
string[] rwys = inif.Read(airport, "rwys").Split(':'); //size is known (2)
_AirportData = new CAirportData[] { new CAirportData() { icao=airport, depRwy=rwys[0], arrRwy=rwys[1] } };
}
}
}
Now you can access the array anywhere in the project like
MessageBox.Show(Session.CAirportData[0].depRwy);
Im struggling with Observable collections and using it to add pushpins onto a silverlight bing map. Im trying to build up a collection here using Linq. But im getting the error under every "PushPinItems" instance in my code saying:
'observable_collection_test.Map.PushPinItems' is a 'field' but is used like a 'type' c:\users\dan\documents\visual studio 2010\Projects\observable collection test\observable collection test\Map.xaml.cs 26 38 observable collection test
Not sure whats going on here, am I declaring/constructing it wrong or something?
Im new to Observable collections (and most of c#!) so any help/advice welcome. Many thanks.
UPDATE:
This seems to be ok now, the above issue, but now its not binding my items to pushpins.
I have looked at the "PushPins = pushPinCollection;" method and all 143 items are in there with lat, long and location propertiess with the correct data- as per this breakpoint:
Maybe there is an issue with my XAML binding?
Here is the updated code:
namespace observable_collection_test
{
public partial class Map : PhoneApplicationPage
{
private ObservableCollection<SItem2> _PushPins;
public event PropertyChangedEventHandler PropertyChanged;
public Map()
{
InitializeComponent();
getItems();
}
public ObservableCollection<SItem2> PushPins
{
get
{
return _PushPins;
}
private set
{
_PushPins = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("PushPins"));
}
}
}
private GeoCoordinate _location;
public GeoCoordinate Location
{
get { return _location; }
set
{
if (_location != value)
{
_location = value;
}
}
}
private string _pinSource;
public string PinSource
{
get { return _pinSource; }
set
{
if (_pinSource != value)
{
_pinSource = value;
}
}
}
public void getItems()
{
var document = XDocument.Load("ListSmall.xml");
if (document.Root == null)
return;
var xmlns = XNamespace.Get("http://www.blahblah.co.uk/blah");
var events = from ev in document.Descendants("item")
select new
{
Latitude = Convert.ToDouble(ev.Element(xmlns + "Point").Element(xmlns + "lat").Value),
Longitude = Convert.ToDouble(ev.Element(xmlns + "Point").Element(xmlns + "long").Value),
};
ObservableCollection<SItem2> pushPinCollection = new ObservableCollection<SItem2>();
foreach (var ev in events)
{
SItem2 PushPin = new SItem2
( ev.Latitude, ev.Longitude)
{
};
pushPinCollection.Add(PushPin);
}
PushPins = pushPinCollection;
}
other class:
namespace observable_collection_test
{
public class SItem2
{
//public DateTimeOffset Date { get; set; }
//public string Title
//{ get; set; }
public double Latitude
{ get; set; }
public double Longitude
{ get; set; }
public GeoCoordinate Location
{ get; set; }
//public Uri Link { get; set; }
public SItem2(//string Title,
double Latitude, double Longitude)
{
//this.Date = Date;
//this.Title = Title;
this.Latitude = Latitude;
this.Longitude = Longitude;
//this.Location = Location;
//this.Link = Link;
}
}
Bit of XAML concerning adding pins to map:
<my:Map ZoomBarVisibility="Visible" ZoomLevel="10" CredentialsProvider="AhqTWqHxryix_GnWER5WYH44tFuutXNEPvFm5H_CvsZHQ_U7-drCdRDvcWSNz6aT" Height="508" HorizontalAlignment="Left" Margin="0,22,0,0" Name="map1" VerticalAlignment="Top" Width="456">
<my:MapItemsControl ItemsSource="{Binding PushPins}" >
<my:MapItemsControl.ItemTemplate>
<DataTemplate>
<my:Pushpin Background="Aqua" Location="{Binding Location}" ManipulationCompleted="pin_click">
</my:Pushpin>
</DataTemplate>
</my:MapItemsControl.ItemTemplate>
</my:MapItemsControl>
</my:Map>
It would also be good to know if I am approaching the pushpin binding to the maps in the right way.
It looks as if this is because you have used x:Name="PushPinItems" in your XAML which is the same name as one of your types, so when you think you are referencing your PushPinItems type in your codebehind, you are actually referencing the field that VS has generated for you from your XAML that represents that Pushpin instance. You could use a different x:Name in your XAML.
Update
Ok, I see the issue :) I haven't worked with the Bing maps control before, but looking at http://forums.silverlight.net/forums/t/197631.aspx (second post down), you need to set the map controls MapItemsControl property. The ItemsSource property here should be bound to your ObservableCollection of a custom type which contains properties such as Name and Location. You can then populate this collection with instances of this custom type (in the post they have used MapData as the type name).
You can also get more examples and source code at http://www.microsoft.com/maps/isdk/silverlight/