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
Related
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?
I'm attempting to grab a device handle on the Synaptics Touchpad using the Synaptics SDK, specifically using methods in the SYNCTRLLib.
However, the SYNCTRL method failed to find it, returning -1.
Syn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Syn
{
SynAPICtrl SynTP_API = new SynAPICtrl();
SynDeviceCtrl SynTP_Dev = new SynDeviceCtrl();
SynPacketCtrl SynTP_Pack = new SynPacketCtrl();
int DeviceHandle;
//Constructor
public Syn ()
{
SynTP_API.Initialize();
SynTP_API.Activate();
//DeviceHandle == -1 ? Can't find device?
DeviceHandle = SynTP_API.FindDevice(new SynConnectionType(), new SynDeviceType(), 0);
//Below line causing Unhandled Exception
SynTP_Dev.Select(DeviceHandle);
SynTP_Dev.Activate();
SynTP_Dev.OnPacket += SynTP_Dev_OnPacket;
}
public void SynTP_Dev_OnPacket()
{
Console.WriteLine(SynTP_Pack.FingerState);
Console.WriteLine(SynTP_Pack.X);
Console.WriteLine(SynTP_Pack.Y);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Program
{
static void Main(string[] args)
{
Syn mySyn = new Syn();
mySyn.SynTP_Dev_OnPacket();
}
}
}
I see that you are using the C# wrappers for Synaptics SDK. Even though CPP code might be not trivial to you, you might want to take a look at the file Samples/ComTest.cpp. It contains some example logic in order to find devices, more specifically at lines 66-76:
// Find a device, preferentially a TouchPad or Styk.
ISynDevice *pDevice = 0;
long lHandle = -1;
if ((pAPI->FindDevice(SE_ConnectionAny, SE_DeviceTouchPad, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceStyk, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceAny, &lHandle)) ||
pAPI->CreateDevice(lHandle, &pDevice))
{
printf("Unable to find a Synaptics Device.\n");
exit(-1);
}
Also, make sure you have registered the dlls. According to the ReadSynSDK.txt file:
For certain purposes it may be necessary to register the dlls
that are provided with the SDK. This can be done with the windows regsvr32
utility.
I'm a beginner in c#, currently attempting a windows form project. I've designed a form titled drugform. I use the dataset method to connect to the database. Here is my code:
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.Data.SqlClient;
using System.Windows.Forms;
using drugstoreform.BaseInfoTableAdapters;
namespace drugstoreform
{
public partial class DrugForm : Form
{
int Row = -1;
public DrugForm()
{
InitializeComponent();
}
private void Register_click(object sender, EventArgs e)
{
try
{
dbm_Medecine db = new dbm_Medecine();
db.Insert(Convert.ToInt32(DrugCode.Text.Trim()), DrugName.Text.Trim(), Convert.ToString(HowUse.Text.Trim()), Convert.ToDecimal(price.Text.Trim()));
}
catch(SqlException ex)
{
}
When I click on the register button, I get this error: input string was not in a correct format.
You get the error inConvert.ToInt32 and/or Convert.ToDecimal because the input was invalid. You can use int.TryParse and decimal.TryParse to validate it:
int drugCode;
decimal price;
if (int.TryParse(DrugCode.Text.Trim(), out drugCode) && decimal.TryParse(price.Text.Trim(), out price))
{
db.Insert(drugCode, DrugName.Text.Trim(), HowUse.Text.Trim(), price);
}
In the if drugCode and price are initialized with the correct value. Otherwise you should provide an error message that the user should provide correct input.
Possible reasons: perhaps the user enters 2.6 but the computer uses , as decimal separator. Or DrugCode.Text or price.Text are simply empty.
I am working in project in which I have used vlc plugin v2. the path for my video is
axVLC.playlist.add(#"D:\My Project\Science\Resources\myvideo.mp4");
axVLC.playlist.play();
now the problem is when I build the project and give it to someone and he/she install it on his/her computer , it show exception that video path is wrong. I am sure that path is not suitable as my the video path in my project is D:... and he/she installed it on C.
So my question is that is there any way to give it common path by which user don`t face such kind of error
Import IO
Using System.IO;
then declare a string that will reference to your video folder
string AbsoluteRef;
use this code in your form load
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
Now declare a string for your video or which ever file like
string vlcvideo;
now add the two together
vlcvideo = AbsoluteRef & "myvideo.mp4";
Finnally add all this into your vlc plugin
axVLC.playlist.add(vlcvideo);
Complete Code looks like so.
using Microsoft.VisualBasic;
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 System.Windows.Input;
using yournamespace.Forms;
using System.IO;
namespace yourNameSpace
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
string AbsoluteRef = null;
private void frmMain_Load(object sender, EventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
AbsoluteRef = Path.GetFullPath(Application.StartupPath + "\\..\\..\\Resources\\");
}
else
{
AbsoluteRef = Application.StartupPath + "\\Resources\\";
}
string vlcVideo = AbsoluteRef + "myvideo.mp4";
axVLC.playlist.add(vlcvideo);
}
I'm new to C# and I'm new to Speech.Recognition.
I searched very long for tutorials but didn't find that much, I'm even not quiet sure whether I included everything correctly.
I downloaded:
SDK
Runtime
Languages
I'm programming local, I have Windows XP, .net framework 3.5.
Now I just want to get started with some simple lines of code, like to say "hello world" or say one or two words as input.
I tried following, and of course it doesn't work :>
error:
"The Typ- or Namespacename "SpeechSynthesizer" couldn't be found (Is a Using-Direktive or a Assemblyverweis missing?)"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Recognition;
using System.Speech.Synthesis;
namespace System.Speech.Recognition { }
namespace System.Speech.AudioFormat {}
namespace System.Speech.Recognition.SrgsGrammar{}
namespace System.Speech.Synthesis { }
namespace System.Speech.Synthesis.TtsEngine { }
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SpeechSynthesizer foo = new SpeechSynthesizer();
foo.Speak("Test");
}
}
}
edit:
hello,
i tried you code,but
using SpeechLib;
couldn't be found :>
well now i wrote:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.SpeechLib;
namespace System.SpeechLib { }
namespace System.Speech.Recognition { }
namespace System.Speech.AudioFormat {}
namespace System.Speech.Recognition.SrgsGrammar{}
namespace System.Speech.Synthesis { }
namespace System.Speech.Synthesis.TtsEngine { }
but I get an error with:
numericUpDown1,SpVoice,SpeechVoiceSpeakFlags,textBox1 and Timeout
Project + Add Reference, .NET tab, select "System.Speech".
A project template pre-selects several .NET assemblies. But only common ones, like System.dll, System.Core.dll, etcetera. You have to add the 'unusual' ones yourself.
you can try this:
get Interop.SpeechLib.dll
using SpeechLib;
private void ReadText(string readText)
{
int iCounter = 0;
while (Convert.ToInt32(numericUpDown1.Value) > iCounter)
{
SpVoice spVoice = new SpVoice();
spVoice.Speak(textBox1.Text, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
spVoice.WaitUntilDone(Timeout.Infinite);
iCounter = iCounter + 1;
}
}