MapsUI 1.4.0 Xamarin differemce versions Newtonsoft.Json - c#

I am writing a app where you can show your location on the screen. Everything works fine but the map is just one pixel line high. Is there a solution for this?
<Grid x:Name="MapGrid"
HorizontalOptions="CenterAndExpand"/>
<Grid>
This is the main cs code of my project, i dont get breaking errors just warnings about packages. My app will start just fine just showing just one pixel line of the map.
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Essentials;
using Mapsui.Utilities;
using Mapsui.Projection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
private MapsuiView mapControl;
public MainPage()
{
InitializeComponent();
mapControl = new MapsuiView();
mapControl.NativeMap.Layers.Add(OpenStreetMap.CreateTileLayer());
MapGrid.Children.Add(mapControl);
Device.StartTimer(TimeSpan.FromSeconds(2), () =>
{
GoToLocation();
return true;
});
async void GoToLocation()
{
Location location = await getLocation();
if (location != null)
{
var sphericalMercatorCoordinate = SphericalMercator.FromLonLat(location.Longitude, location.Latitude);
mapControl.NativeMap.NavigateTo(sphericalMercatorCoordinate);
mapControl.NativeMap.NavigateTo(mapControl.NativeMap.Resolutions[15]);
}
}
async Task<Location> getLocation()
{
Location location = null;
try
{
var request = new GeolocationRequest(GeolocationAccuracy.Best);
location = await Geolocation.GetLocationAsync(request);
if(location != null)
{
Console.WriteLine($"Latitude: {location.Latitude}, " +
$"Longitude: {location.Longitude}, " +
$"Altitude: {location.Altitude}, " +
$"Accuracy: {location.Accuracy}");
}
}
catch (FeatureNotSupportedException fnsEx)
{
Console.WriteLine(fnsEx.ToString());
}
catch (FeatureNotEnabledException fneEx)
{
Console.WriteLine(fneEx.ToString());
}
catch (PermissionException pEx)
{
Console.WriteLine(pEx.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Overige fout: " + ex.ToString());
}
return location;
}
}
}
}
This is a class which i added because it wouldn't work otherwise.
using System;
using System.Collections.Generic;
using System.Text;
namespace mobile_83504_3
{
public class MapsuiView : Xamarin.Forms.View
{
public Mapsui.Map NativeMap { get; }
protected internal MapsuiView()
{
NativeMap = new Mapsui.Map();
}
}
}
I'm using MapsUI 1.4.0 and it's trying to connect to a Newtonsoft.Json 9.0.0 that coudn't be found. so it takes 9.0.1, i don't know if that is the error but that is one of the few warnings that i get. alongside with a .NET framework that might not be fully compatible.

Everything works fine but the map is just one pixel line high. Is there a solution for this?
To use the Mapsui, it's not necessary to create a custom mapsui view. Add the declare line code to the xaml file, the view will be available.
Check the code:
<ContentPage
...
xmlns:mapsui="clr-namespace:Mapsui.UI.Forms;assembly=Mapsui.UI.Forms">
<StackLayout>
<mapsui:MapView x:Name="mapView"
VerticalOptions="FillAndExpand"
HorizontalOptions="Fill"
BackgroundColor="Gray" />
</StackLayout>
</ContentPage>
How to use Mapsui 2.0.1 with Xamarin.Forms?

Related

ArmDeploymentCollection Not in Azure.ResourceManager.Resources Namespace

I am following the new Azure.ResourceManager SDK examples here.
I'm not seeing classes I'd expect to see in Azure.ResourceManager.Resources. Specifically, ArmDeploymentCollection and ResourceGroupResource doesn't have a GetArmDeployments() method.
Azure.ResourceManager installed is Azure.ResourceManager.1.0.0. I'm targeting .NET framework 4.8.
I've tried uninstalling/re-installing Azure.ResourceManager several times, but doesn't change anything.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.KeyVault;
using System.Threading;
using Azure;
using Azure.Identity;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
public static void Initialize()
{
try
{
// Authenticate
var credentials = new DefaultAzureCredential();
await RunSample(credentials);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
public static async Task RunSample(TokenCredential credential)
{
try
{
var deploymentName = "bradDeployment";
var rgName = "rg-percipience-test-002";
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var templateJson = Utilities.GetArmTemplate("ArmTemplate.json");
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
ResourceGroupCollection rgCollection = subscription.GetResourceGroups();
// With the collection, we can create a new resource group with an specific name
AzureLocation location = AzureLocation.EastUS;
ArmOperation<ResourceGroupResource> lro = await rgCollection.CreateOrUpdateAsync(WaitUntil.Completed, rgName, new ResourceGroupData(location));
ResourceGroupResource resourceGroup = lro.Value;
Utilities.Log("Created a resource group with name: " + rgName);
// Create a deployment for an Azure App Service via an ARM
// template.
Utilities.Log("Starting a deployment for an Azure App Service: " + deploymentName);
// First we need to get the deployment collection from the resource group
ArmDeploymentCollection armDeploymentCollection = resourceGroup.GetArmDeployments();
// Use the same location as the resource group
// Passing string to template and parameters
var input = new ArmDeploymentContent(new ArmDeploymentProperties(ArmDeploymentMode.Incremental)
{
Template = BinaryData.FromString(File.ReadAllText("storage-template.json")),
Parameters = BinaryData.FromString(File.ReadAllText("storage-parameters.json"))
});
ArmOperation<ArmDeploymentResource> lro2 = await ArmDeploymentCollection.CreateOrUpdateAsync(WaitUntil.Completed, deploymentName, input);
ArmDeploymentResource deployment = lro2.Value;
Utilities.Log("Completed the deployment: " + deploymentName);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
await (await resourceGroups.StartDeleteAsync(rgName)).WaitForCompletionAsync();
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
I resolved the issue by adding a reference to Azure.ResourceManager.Resources.dll. Not sure why this reference isn't added when the nuget package is installed.

Getting Error Only after using Build in Visual Studio?

Using DJI Mavic Air
https://developer.dji.com/windows-sdk/documentation/tutorials/index.html
Using this guide i am Integrating DJIVideoParsel, at the end,Build is successful but output is a failure because of an issue shows up.
i have Added the Error Text and The Code, if i need to add something else please do tell. Also the code shows no error until i build it.
Error Text:
$exception {"The specified module could not be found. (Exception from HRESULT: 0x8007007E)":null} System.IO.FileNotFoundException
this {DJIWSDKDemo.MainPage} DJIWSDKDemo.MainPage
type {DJI.WindowsSDK.ResultValue<DJI.WindowsSDK.CameraTypeMsg?>} DJI.WindowsSDK.ResultValue<DJI.WindowsSDK.CameraTypeMsg?>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using DJI.WindowsSDK;
using DJIVideoParser;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace DJIWSDKDemo
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
//use videoParser to decode raw data.
private DJIVideoParser.Parser videoParser;
//raw data
void OnVideoPush(VideoFeed sender, byte[] bytes)
{
videoParser.PushVideoData(0, 0, bytes, bytes.Length);
}
//Decode data. Do nothing here. This function would return a bytes array with image data in RGBA format.
async void ReceiveDecodedData(byte[] data, int width, int height)
{
}
//We need to set the camera type of the aircraft to the DJIVideoParser. After setting camera type, DJIVideoParser would correct the distortion of the video automatically.
private void OnCameraTypeChanged(object sender, CameraTypeMsg? value)
{
if (value != null)
{
switch (value.Value.value)
{
case CameraType.MAVIC_2_ZOOM:
this.videoParser.SetCameraSensor(AircraftCameraType.Mavic2Zoom);
break;
case CameraType.MAVIC_2_PRO:
this.videoParser.SetCameraSensor(AircraftCameraType.Mavic2Pro);
break;
default:
this.videoParser.SetCameraSensor(AircraftCameraType.Others);
break;
}
}
}
public MainPage()
{
this.InitializeComponent();
DJISDKManager.Instance.SDKRegistrationStateChanged += Instance_SDKRegistrationEvent;
//Replace with your registered App Key. Make sure your App Key matched your application's package name on DJI developer center.
DJISDKManager.Instance.RegisterApp("bb291a0f01c8567c7c7200fb");
}
//Callback of SDKRegistrationEvent
private async void Instance_SDKRegistrationEvent(SDKRegistrationState state, SDKError resultCode)
{
if (resultCode == SDKError.NO_ERROR)
{
System.Diagnostics.Debug.WriteLine("Register app successfully.");
//Must in UI Thread
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Raw data and decoded data listener
if (videoParser == null)
{
videoParser = new DJIVideoParser.Parser();
videoParser.Initialize(delegate (byte[] data)
{
//Note: This function must be called because we need DJI Windows SDK to help us to parse frame data.
return DJISDKManager.Instance.VideoFeeder.ParseAssitantDecodingInfo(0, data);
});
//Set the swapChainPanel to display and set the decoded data callback.
videoParser.SetSurfaceAndVideoCallback(0, 0, swapChainPanel, ReceiveDecodedData);
DJISDKManager.Instance.VideoFeeder.GetPrimaryVideoFeed(0).VideoDataUpdated += OnVideoPush;
}
//get the camera type and observe the CameraTypeChanged event.
DJISDKManager.Instance.ComponentManager.GetCameraHandler(0, 0).CameraTypeChanged += OnCameraTypeChanged;
var type = await DJISDKManager.Instance.ComponentManager.GetCameraHandler(0, 0).GetCameraTypeAsync();
OnCameraTypeChanged(this, type.value);
});
}
else
{
System.Diagnostics.Debug.WriteLine("SDK register failed, the error is: ");
System.Diagnostics.Debug.WriteLine(resultCode.ToString());
}
}
}
}

Opening Location Settings Page or Prompting user to Enable Location

i've been hacking my brain and googling away in vain. i am trying to find a way to prompt the user to switch location on either by going directly to the settings page or just tapping yes on the screen.
all code i've seen doesn't seem to work. does any one have something that works. a detailed example will be much appreciated. thank you.
I'm really new to Xamarin development
i would prefer a way to do it on xamarin forms, but starting with something that will prompt android user, because for iOS i have no simulator
.
so after going through several tutorials and answers all over the internet i finally was able to find to accomplish what i wanted to achieve,
i used a dependency service as one of the answers indicated here How to open setting from our application in xamarin
there are few things that were not mentioned like registering the interface in order to use it in platform specific projects.
here is the code for anyone who needs it
the Interface :
I called my Interface ILocSettings.cs
using System;
using System.Collections.Generic;
using System.Text;
[assembly: Xamarin.Forms.Dependency(typeof(DE2.ILocSettings))]
namespace DE2
{
public interface ILocSettings
{
void OpenSettings();
}
the form that has a button I called it DataEntryForm
DataEntryForm.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DE2.DataEntryForm"
>
<ContentPage.Content>
<StackLayout>
<Button x:Name="TurnLocationOn"
Text="Turn On Location"
Clicked="TurnLocationOn_OnClicked"/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
then the DataEntryForm.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Plugin.pbXSettings;
using Plugin.Geolocator;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using Plugin.DeviceInfo;
using Plugin.DeviceInfo.Abstractions;
[assembly: Xamarin.Forms.Dependency(typeof(DE2.ILocSettings))]
namespace DE2
{
using Xamarin.Forms.PlatformConfiguration;
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class DataEntryForm : ContentPage
{
public DataEntryForm ()
{
InitializeComponent ();
}
private async void TurnLocationOn_OnClicked(object sender, global::System.EventArgs e)
{
var myAction = await DisplayAlert("Location", "Please Turn On Location", "OK","CANCEL");
if (myAction)
{
if (Device.RuntimePlatform == global::Xamarin.Forms.Device.Android)
{
//DependencyService.Get<ISettingsService>().OpenSettings();
global::Xamarin.Forms.DependencyService.Get<global::DE2.ILocSettings>().OpenSettings();
}
else
{
DisplayAlert("Device", "You are using some other shit", "YEP");
}
}
else
{
DisplayAlert("Alert","User Denied Permission","OK");
}
//
}
}
}
Then I have this Class Placed on the Android Specific Platform LocationZ.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Locations;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Xamarin.Android;
using Xamarin.Forms;
using DE2;
using DE2.Droid;
//[assembly: Xamarin.Forms.Dependency(typeof(ILocSettings))]
//Notice the use of LocationZ in registering below instead of ILocSettings
[assembly: Xamarin.Forms.Dependency(typeof(LocationZ))]
namespace DE2.Droid
{
using System.Runtime.Remoting.Messaging;
using Android.Support.V4.View;
using Android.Support.V7.App;
using Xamarin.Forms;
using DE2;
public class LocationZ : ILocSettings
{
public void OpenSettings()
{
LocationManager LM = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
if (LM.IsProviderEnabled(LocationManager.GpsProvider)==false)
{
Context ctx = Forms.Context;
ctx.StartActivity(new Intent(Android.Provider.Settings.ActionLocationSourceSettings));
}
else
{
//this is handled in the PCL
}
}
}
}
`
If you are talking about getting the user to grant location permission, the easiest way to do it is to use the permissions plugin. This allows you to both request and check on a particular permission.
The permission plugin and full documentation can he found here
You will then be able to do the following:
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
if(await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
{
await DisplayAlert("Need location", "Gunna need that location", "OK");
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
//Best practice to always check that the key exists
if(results.ContainsKey(Permission.Location))
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
var results = await CrossGeolocator.Current.GetPositionAsync(10000);
LabelGeolocation.Text = "Lat: " + results.Latitude + " Long: " + results.Longitude;
}
else if(status != PermissionStatus.Unknown)
{
await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
}
}
catch (Exception ex)
{
LabelGeolocation.Text = "Error: " + ex;
}
the Images show the screens up to the Settings page

Wrong path to SQLiteDB (or copy) on WinPhone. Xamarin.Forms PCL

Have installed NUGet packages for Xamarin.Forms for PCL. I have 4 projects for Droid, iOS, Win 8.1 and WinPhone 8.1. Tried to connect my database, but encountered trouble: my Win and WinPhone projects don`t see it or return me the wrong path. Followed official Xamarin.Forms forum.
Interface:
public interface ISQLite
{
string GetDatabasePath(string filename);
}
WInPhone Class:
using System.IO;
using Windows.Storage;
using Baumizer.WinPhone;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_WinPhone))]
namespace Baumizer.WinPhone
{
public class SQLite_WinPhone:ISQLite
{
public SQLite_WinPhone() { }
public string GetDatabasePath(string filename)
{
return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
}
}}
This class for selecting info:
public class DataBase
{
SQLiteConnection connection;
public DataBase()
{
connection= new SQLiteConnection(DependencyService.Get<ISQLite>().GetDatabasePath("Database.db"));
}
public IEnumerable<Group> GetGroups()
{
return connection.Query<Group>("SELECT * FROM [Scedule] WHERE [facultyName] =" + "'" + Data.CurrentFaculty + "'");
}
}
It works well on Android. On WinPhone I get exception of SQLite - no such table: Scedule. I open the local directory for emulator where db was - 0Kb.
I put db to Assets and set BuildInAction to Content. What`s wrong? Need help
On forum find this code, putted to OnLaunched(...) in WinPhone App.cs:
if(await ApplicationData.Current.LocalFolder.GetItemAsync(Data.DataBaseName) == null)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync($"Assets\\{Data.DataBaseName}");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
It copies DB if it's not exist, but it is. May be I need to delete DB 0Kb, but I don't know how to do this.
It's work, OnLaunched():
try
{
await ApplicationData.Current.LocalFolder.GetItemAsync("Scedule.db");
}
catch (System.IO.FileNotFoundException)
{
StorageFile databaseFile =
await Package.Current.InstalledLocation.GetFileAsync($"Assets\\{"Scedule.db"}");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
DB was uncorrectly copied. May be there are any another ways.

Server unable to execute EWS autodiscover

On our testing server, EWS autodiscover does not work. To eliminate an ill-set IIS option from the list of causes, I C&P'ed together a WindowsForms Application (code below) and put it, together with the Microsoft.Exchange.Webservice.dll, into a folder on which I have write permission.
Unfortunately, neither xml nor text file are created. Instead, I get an Unhandled Exception error.
System.NullReferenceException
at System.Windows.Forms.TextBoxBase.AppendText(String text)
This does not happen on my development machine, which is in the same AD domain and on which the test app always returns that autodiscover was successful.
Question: How come no Trace output is generated?
So now, my app code:
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
namespace ADDebugWin
{
public partial class Form1 : Form
{
public static string traceData;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ExchangeService ews = new ExchangeService(ExchangeVersion.Exchange2010);
ews.TraceListener = new TraceListener();
// Optional flags to indicate the requests and responses to trace.
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
ews.TraceEnabled = true;
ews.UseDefaultCredentials = true;
try {
ews.AutodiscoverUrl("email#mydomain.com");
textBox1.AppendText("AutoDiscover erfolgreich.");
} catch (Exception ex) {
textBox1.AppendText(traceData);
textBox1.AppendText(ex.Message + "\r\n" + ex.StackTrace);
}
}
}
}
TraceListener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ADDebugMvc.Controllers;
using Microsoft.Exchange.WebServices.Data;
using System.Xml;
namespace ADDebugMvc.Models
{
class TraceListener : ITraceListener
{
public void Trace(string traceType, string traceMessage)
{
CreateXMLTextFile(traceType, traceMessage.ToString());
HomeController.traceData += traceType + " " + traceMessage.ToString() + "\r\n";
}
private void CreateXMLTextFile(string fileName, string traceContent)
{
// Create a new XML file for the trace information.
try
{
// If the trace data is valid XML, create an XmlDocument object and save.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(traceContent);
xmlDoc.Save(fileName + ".xml");
}
catch
{
// If the trace data is not valid XML, save it as a text document.
System.IO.File.WriteAllText(fileName + ".txt", traceContent);
}
}
}
}
One should note that
ews.TraceFlags = TraceFlags.EwsRequest | TraceFlags.EwsResponse;
is not returning any Traces during AutoDiscover.
(ews.TraceFlags = TraceFlags.All; does.)
So no string is appended to traceData, which is why traceData==null -> Exception when appending it to a TextBox.

Categories