why my local:CustomMap Error
sorry i'm beginner in english,
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/map-pin
my project name PTSSRU
xaml code
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="PTSSRU.Views.MapPage"
xmlns:local="clr-namespace:PTSSRU;assembly=PTSSRU"
<local:CustomMap x:Name="customMap"
MapType="Street" />
</ContentPage>
cs code
using PTSSRU.Custom;
using System.Collections.Generic;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
namespace PTSSRU.Views
{
public partial class MapPage : ContentPage
{
public MapPage()
{
InitializeComponent();
CustomPin pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(37.79752, -122.40183),
Label = "Xamarin San Francisco Office",
Address = "394 Pacific Ave, San Francisco CA",
Name = "Xamarin",
Url = "http://xamarin.com/about/"
};
customMap.CustomPins = new List<CustomPin> { pin };
customMap.Pins.Add(pin);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183),
Distance.FromMiles(1.0)));
}
}
}
I have finished the map
But I want to change the pin icon.
Error Name cannot begin with the '<' character, hexadecimal value 0x3C. Line 7, position 5. PTSSRU C:\Users\MrC4\source\repos\PTSSRU\PTSSRU\PTSSRU\Views\MapPage.xaml 7
incode
<local:CustomMap x:Name="customMap"
MapType="Street" />
im not sure xmlns:local="clr-namespace:PTSSRU;assembly=PTSSRU" it Correct.
my git hub
https://github.com/s58122519013/Xamarin.Map.git
Related
I need to add a bunch of pins on a MapsUI map control that uses OpenStreetMap tiles.
The problem is I cant find anything mentioning pins in their documentation so my question is:
Are there any pins available but have different names or i have to draw pins myself (using Geometry and Points as in some examples i found) and if so how do i keep them the same size when zooming the map ?
Maybe someone can point out where should i look in their documentation in case I'm blind and missed it.
Thanks!
Your Mapsui Map View Mapsui.UI.Forms.MapView has property Pins. You can add pins there.
You can access MapView View from code-behind *xaml.cs of your MapView.
For that, first, name your Map View in XAML Page:
<ContentPage
xmlns:mapsui="clr-namespace:Mapsui.UI.Forms;assembly=Mapsui.UI.Forms"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="YourProject.Pages.YourMap">
<ContentPage.Content>
<mapsui:MapView
x:Name="selectMapControl"/>
</ContentPage.Content>
</ContentPage>
Then access it from C# code-behind of that Page:
using Mapsui.UI.Forms;
protected override async void OnAppearing()
{
selectMapControl.Pins.Add(new Pin(new MapView())
{
Position = new Position(0, 0),
Type = PinType.Pin,
Label = "Zero point",
Address = "Zero point",
});
}
Hope this simplest example will help.
The idea is that you use your own bitmaps to draw as 'pins'.
Mapsui has features. A feature has a geometry which can be a point, linestring and polygon (and some others). A feature is drawn with some kind of style. What you need to do is create features with point geometry and use a symbolstyle with a bitmap as symbol. You need to register your bitmap and use the bitmapId in the symbol. See the sample here:
https://github.com/Mapsui/Mapsui/blob/master/Samples/Mapsui.Samples.Common/Maps/PointsSample.cs
You can use Xamarin.Forms.GoogleMaps as they give you the feature to add multiple pins of your choice.
Here is the sample code :
var position = new Position(Latitude, Longitude);
var pin = new Pin
{
Type = PinType.Place,
Position = position,
Icon = BitmapDescriptorFactory.FromBundle("pin.png"),
Label = "custom pin",
Address = "custom detail info",
};
MyMap.Pins.Add(pin);
The following works on version 3.02. I've not checked it on any other version of MapSui.
First make sure your pin Bitmap is an embedded resource. You can then get the Bitmap ID like this:
var assembly = typeof(YourClass).GetTypeInfo().Assembly;
var image = assembly.GetManifestResourceStream("YourSolution.YourProject.AFolder.image.png");
If var image returns null, then the image was not found and it's likely not an embedded resource or you got the address/name wrong.
var ID = BitmapRegistry.Instance.Register(image);
The BitmapRegistry method also registers the BitMap for MapSui to use later. I think if it's your first image registered it will be 0.
Then you can create a memory layer as follows:
MemoryLayer PointLayer = new MemoryLayer
{
Name = "Points",
IsMapInfoLayer=true,
DataSource = new MemoryProvider(GetListOfPoints()),
Style = new SymbolStyle { BitmapId = ID, SymbolScale = 0.50, SymbolOffset = new Offset(0, bitmapHeight * 0.5) };
};
The DataSource can be generated as follows (I'm just adding one feature, but you can add as many as you like):
private IEnumerable<IFeature> GetListOfPoints()
{
List<IFeature> list = new List<IFeature>();
var feature = new Feature();
feature.Geometry = new Point(-226787, 7155483);
feature["name"] = "MyPoint";
list.Add(feature);
IEnumerable<IFeature> points = list as IEnumerable<IFeature>;
return points;
}
Then add the new MemoryLayer to your Map as follows:
MapControl.Map?.Layers.Add(PointLayer);
I am setting the source property of ResourceDictionary programatically and not from xaml in a Xamarin forms project.
During run time I always get System.invalidOperation exception with the message "Source can only be set from Xaml.
Resources = Resources ?? new ResourceDictionary();
if(Resources.Source == null)
{
Resources.Source = new Uri("/Styles/ActiveTrackerStyle.xaml", UriKind.Relative);
}
Wondering if I am doing anything wrong while setting the Source. Source property has both getter and setter. Any pointers of what is wrong here.
With the help of a colleague, I got it working:
First: Browsing through the Xamarin.Forms' ResourceDictionary class (here, I saw the following property:
public Uri Source {
get { return _source; }
set {
if (_source == value)
return;
throw new InvalidOperationException("Source can only be set from XAML."); //through the RDSourceTypeConverter
}
It seems that you cannot change the source if the private variable "_source" has been set already;
However, the class also have another method "SetAndLoadSource" and in this method the _source variable is set without any checks. Thus, I got it working by doing the following:
var source = new Uri("/Styles/LightResourceDictionary.xaml", UriKind.RelativeOrAbsolute);
var resourceDictionary = new ResourceDictionary();
resourceDictionary.SetAndLoadSource(source, "Styles/LightResourceDictionary.xaml", this.GetType().GetTypeInfo().Assembly, null);
ThemeDictionary.MergedDictionaries.Add(resourceDictionary);
ThemeDictionary.MergedDictionaries.ElementAt(0).Source = source;
Note that "ThemeDictionary" is the x:Name of my MergedDictionary:
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary x:Name="ThemeDictionary">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles/DarkResourceDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Has anyone used Sage Pay with asp.net Webpages??
I have downloaded the integration kit from Sage Pay but this is made in webforms and i am having trouble converting it the WebPages format.
Sage Pay are no help so i'm hoping someone out there has done this. Or can point me in the right direction.
I have managed to do this using the class from the SagePay template you can download.
Put these files in your bin folder:-
SagePay.IntegrationKit.DotNet.dll
SagePay.IntegrationKit.DotNet.pdb
Put these files in your App_Code folder:-
SagePayConfiguration.cs
SagePayAPIIntegration.cs
SagePayFormIntegration.cs
You also need to add some stuff to your web.config file
<SagePayConfiguration>
<!--Mandatory
Set to TEST for the Test Server and LIVE for the live environment-->
<add key="sagepay.api.env" value="TEST" />
<!--Transaction Settings -->
<add key="sagepay.api.protocolVersion" value="3.00" />
<add key="sagepay.kit.vendorName" value="your Name" />
<add key="sagepay.kit.fullUrl" value="your url" />
<add key="sagepay.kit.currency" value="GBP" />
<!--Optional setting. It's recommended to set the siteFqdn value to the Fully
Qualified Domain Name of your server.
This should start http:// or https:// and should be the name by which our servers can call back to yours
i.e. it MUST be resolvable externally, and have access granted to the Sage Pay servers
examples would be https://yoursite or http://212.111.32.22/
NOTE: Do not include any URI path.
If you leave this value blank the kit will use the current host name-->
<add key="sagepay.kit.siteFqdn.LIVE" value="http://your web address" />
<add key="sagepay.kit.siteFqdn.TEST" value="http://your web address" />
<!--Mandatory. Usually PAYMENT. This can be DEFERRED or AUTHENTICATE if your Sage Pay
account supports those payment types
NB Ideally all DEFERRED transaction should be released within 6 days (according to card scheme rules).
DEFERRED transactions can be ABORTed before a RELEASE if necessary-->
<add key="sagepay.kit.defaultTransactionType" value="PAYMENT" />
<!--0 = If AVS/CV2 enabled then check them. If rules apply, use rules (default).
1 = Force AVS/CV2 checks even if not enabled for the account. If rules apply, use rules.
2 = Force NO AVS/CV2 checks even if enabled on account.
3 = Force AVS/CV2 checks even if not enabled for the account but DON'T apply any rules.-->
<add key="sagepay.kit.applyAvsCv2" value="0" />
<!--0 = If 3D-Secure checks are possible and rules allow, perform the checks and apply the authorisation rules. (default)
1 = Force 3D-Secure checks for this transaction if possible and apply rules for authorisation.
2 = Do not perform 3D-Secure checks for this transaction and always authorise.
3 = Force 3D-Secure checks for this transaction if possible but ALWAYS obtain an auth code, irrespective of rule base.-->
<add key="sagepay.kit.apply3dSecure" value="0" />
<!--FORM Protocol Only Settings
Set this value to the Encryption password assigned to you by Sage Pay -->
<add key="sagepay.kit.form.encryptionPassword.TEST" value="Your password" />
<add key="sagepay.kit.form.encryptionPassword.LIVE" value="Your password" />
<!--The Sage Pay server URLs to which customers will be sent for payment for each environment-->
<add key="sagepay.api.formPaymentUrl.LIVE" value="https://live.sagepay.com/gateway/service/vspform-register.vsp" />
<add key="sagepay.api.formPaymentUrl.TEST" value="https://test.sagepay.com/gateway/service/vspform-register.vsp" />
</SagePayConfiguration>
To make this easier to manage i have but this web.config file in the checkout folder so it is easy to keep updated.
I also created the following class to encrypt and dencrypt the data:-
you can call it what ever you want but it needs to be saved in the App_Code folder.
using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.IO;
public static class EncryptionHelper
{
private static byte[] keyAndIvBytes;
static EncryptionHelper()
{
// You'll need a more secure way of storing this, I this isn't
// a real key
keyAndIvBytes = UTF8Encoding.UTF8.GetBytes("123123123123123b");
}
public static string ByteArrayToHexString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public static string DecodeAndDecrypt(string cipherText)
{
string DecodeAndDecrypt = AesDecrypt(StringToByteArray(cipherText));
return (DecodeAndDecrypt);
}
public static string EncryptAndEncode(string plaintext)
{
return ByteArrayToHexString(AesEncrypt(plaintext));
}
public static string AesDecrypt(Byte[] inputBytes)
{
Byte[] outputBytes = inputBytes;
string plaintext = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(outputBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(cryptoStream))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
public static byte[] AesEncrypt(string inputText)
{
byte[] inputBytes = UTF8Encoding.UTF8.GetBytes(inputText);//AbHLlc5uLone0D1q
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateEncryptor(keyAndIvBytes, keyAndIvBytes), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
private static RijndaelManaged GetCryptoAlgorithm()
{
RijndaelManaged algorithm = new RijndaelManaged();
//set the mode, padding and block size
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 128;
algorithm.BlockSize = 128;
return algorithm;
}
}
I call the the class like so:-
string crypt = "blahblahblah";
string EncryptAndEncode = EncryptionHelper.EncryptAndEncode(crypt);
string DecodeAndDecrypt = EncryptionHelper.DecodeAndDecrypt(EncryptAndEncode);
When the transaction is complete i get the crypt with this code:-
IFormPaymentResult PaymentStatusResult = new DataObject();
if (Request.QueryString["crypt"] != null && !string.IsNullOrEmpty(Request.QueryString["crypt"]))
{
SagePayFormIntegration sagePayFormIntegration = new SagePayFormIntegration();
PaymentStatusResult = sagePayFormIntegration.ProcessResult(Request.QueryString["crypt"]);
}
you can then call the needed information from the calss like so
if (PaymentStatusResult.Status == ResponseStatus.NOTAUTHED)
{reason = "You payment was declined by the bank. This could be due to insufficient funds, or incorrect card details.";}
You can see all the fields in the Result.aspx of the SagePay template.
Can any one let me know how to get a bool result, verifying a value exists in a web.config's key.
Scenario is,
I have this tag in my website...
<add key="isEnabled" value="False"/> for a website,
On this key value I keep my site 'on' and 'off' using
public static bool isEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings["isEnabled "]);
if(isEnabled)
{
//
}
now the requirement is got 3-4 websites now, want to change the above line to something like
<add key="SitesEnabled" value="1,4,5"/>
because i want to enable only 1st, 4th, 5th site
1 - is the static value for my 1st website, 2 - 2nd.....
But now how do I do on and off...my websites something like
public static bool OneSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="1"]); // true
public static bool TwoSiteEnabled = Convert.ToBoolean(WebConfigurationManager.AppSettings[SitesEnabled="2"]); //false
Please let me know ...Thanks
I would do it something like this:
using System.Linq;
var sitesEnabled =
ConfigurationManager.AppSettings["SitesEnabled"] != null
? ConfigurationManager.AppSettings["SitesEnabled"].Split(',')
: new string[0];
var oneSiteEnabled = sitesEnabled.Contains("1");
var twoSiteEnabled = sitesEnabled.Contains("2");
I'm using this for my code, it outputs to the xml file perfectly, but it adds an ' = ' sign after the element name even though only one of my elements has an attribute.
I suppose I could do something like
if(reader.Getattribute != "")
// I made that up on the spot, I'm not sure if that would really work
{
Console.WriteLine("<{0} = {1}>", reader.Name, reader.GetAttribute("name"));
}
else
{
Console.WriteLine("<{0}>", reader.Name);
}
but is there a cleaner way to code that?
My code (without workaround)
using System;
using System.Xml;
using System.IO;
using System.Text;
public class MainClass
{
private static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter w = XmlWriter.Create(#"Path\test.xml", settings);
w.WriteStartDocument();
w.WriteStartElement("classes");
w.WriteStartElement("class");
w.WriteAttributeString("name", "EE 999");
w.WriteElementString("Class_Name", "Programming");
w.WriteElementString("Teacher", "James");
w.WriteElementString("Room_Number", "333");
w.WriteElementString("ID", "2324324");
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
w.Close();
XmlReader reader = XmlReader.Create(#"Path\test.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Console.WriteLine("<{0} = {1}>", reader.Name, reader.GetAttribute("name"));
break;
case XmlNodeType.Text:
Console.WriteLine(reader.Value);
break;
case XmlNodeType.CDATA:
Console.WriteLine("<[CDATA[{0}]>", reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
Console.WriteLine("<?{0} {1}?>", reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
Console.WriteLine("<!--{0}-->", reader.Value);
break;
case XmlNodeType.XmlDeclaration:
Console.WriteLine("<?xml version='1.0'?>");
break;
case XmlNodeType.Document:
break;
case XmlNodeType.DocumentType:
Console.WriteLine("<!DOCTYPE {0} [{1}]", reader.Name, reader.Value);
break;
case XmlNodeType.EntityReference:
Console.WriteLine(reader.Name);
break;
case XmlNodeType.EndElement:
Console.WriteLine("</{0}>", reader.Name);
break;
}
}
}
}
Output
<?xml version='1.0'?>
<classes = >
<class = EE 999>
<Class_Name = >
Programming
</Class_Name>
<Teacher = >
James
</Teacher>
<Room_Number = >
333
</Room_Number>
<ID = >
2324324
</ID>
</class>
</classes>
Because this line
case XmlNodeType.Element:
Console.WriteLine("<{0} = {1}>", reader.Name, reader.GetAttribute("name"));
break;
Always writes the '=' without checking.
A rough fix :
case XmlNodeType.Element:
Console.WriteLine("<{0}", reader.Name);
if (reader.HasAttributes)
// Write out attributes
Console.WriteLine(">");
break;
But why are you using the XmlReader at all? It is cumbersome and only useful when dealing with huge Xml streams.
If your datasets are not >> 10 MB then take a look at XDocument or XmlDocument
The XmlWriter in your Example can be replaced by (rough approx):
// using System.Xml.Linq;
var root = new XElement("classes",
new XElement("class", new XAttribute("name", "EE 999"),
new XElement("Class_Name", "Programming"),
new XElement("Teacher", "James")
));
root.Save(#"Path\test.xml");
var doc = XDocument.Load(#"Path\test.xml");
// doc is now an in-memory tree of XElement objects
// that you can navigate and query
And here is an intro
I don't know exactly what you're trying to accomplish but personally I would create a .NET class representing your class element with properties identifying the sub elements then use System.Xml.Serialization.XmlSerializer to write or read it from a file.
Here is an example:
using System.Xml.Serialization;
public class MyClasses : List<MyClass>{}
public class MyClass{
public String Teacher{ get; set; }
}
void main(){
MyClasses classList = new MyClasses();
MyClass c = new MyClass();
c.Teacher = "James";
classList.Add(c);
XmlSerializer serializer = new XmlSerializer(classList.GetType());
serializer.Serialize(/*Put your stream here*/);
}
And, after leaving setting up your stream as an exercise to the reader, blamo, you're done outputing an XML representation of your object to some stream. The stream could be a file, string, whatever. Sorry for nasty C# (if its nasty) I use VB.NET everyday so the syntax and keywords may be a little off.
Update
I added some code to show how to serialize a collection of the classes. If nodes aren't coming out named correctly there are attributes you can add to your class properties, just do a quick google for them.
Update again
Sorry, its hard to explain when we're using the same word to mean two different things. Lets say you're trying to represent a bucket of bricks. You would write a C# class called Brick and a C# class called Bucket that inherited from List<Brick> your Brick would have a property called Color. You would then make all your bricks with different colors and fill the bucket with your bricks. Then you would pass your bucket to the serializer and it would give you something like:
<Bucket>
<Brick>
<Color>
blue
</Color>
</Brick>
</Bucket>
The serializer builds the XML for you from the definitions of your classes so you don't have to worry about the details. You can read more about it here and here