C# Project in Visual Studio 2010 for Windows Phone Notefunction - c#

Im trying to get my notefunction to post the current city you are in by using your gps coordinates when saving a note. Right now it's only showing "unknown location". Im kinda lost right now and i have worked so long with this code to try and get it to work so please could anyone tell me what i have done wrong?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Device.Location;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using Secret.myTerraService;
namespace Secret
{
public partial class AddNotePage : PhoneApplicationPage
{
private IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
private string location = "";
#region Hämtar din geografiska position
public AddNotePage()
{
InitializeComponent();
GeoCoordinateWatcher watcher;
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default)
{
MovementThreshold = 20
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
// location is unsupported on this device
break;
case GeoPositionStatus.NoData:
// data unavailable
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
var epl = e.Position.Location;
// Access the position information thusly:
epl.Latitude.ToString("0.000");
epl.Longitude.ToString("0.000");
epl.Altitude.ToString();
epl.HorizontalAccuracy.ToString();
epl.VerticalAccuracy.ToString();
epl.Course.ToString();
epl.Speed.ToString();
e.Position.Timestamp.LocalDateTime.ToString();
}
void client_ConvertLonLatPtToNearestPlaceCompleted(object sender, myTerraService.ConvertLonLatPtToNearestPlaceCompletedEventArgs e)
{
location = e.Result;
//throw new NotImplementedException();
}
#endregion
#region Knappfunktioner
private void AppBar_Cancel_Click(object sender, EventArgs e)
{
navigateBack();
}
private void AppBar_Save_Click(object sender, EventArgs e)
{ // spara en ny anteckning
if (location.Trim().Length == 0)
{
location = "Okänd Plats";
}
// skapa namnet på filen
StringBuilder sb = new StringBuilder();
sb.Append(DateTime.Now.Year);
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Month));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Day));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Hour));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Minute));
sb.Append("_");
sb.Append(String.Format("{0:00}", DateTime.Now.Second));
sb.Append("_");
location = location.Replace(" ", "-");
location = location.Replace(", ", "_");
sb.Append(location);
sb.Append(".txt");
//spara filen i Isolated Storage
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
try
{
using (var fileStream = appStorage.OpenFile(sb.ToString(), System.IO.FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
sw.WriteLine(editTextBox.Text);
}
}
}
catch
{
// åtgärda vid senare tillfälle..
}
//Klart Navigera tillbaka till NoteMainPage
navigateBack();
}

When testing this, I can see a few points where your code could break. You should debug with breakpoints to actually confirm that your app is getting GPS location data. If not, use the Windows Phone emulator and run a GPS simulation (and then confirm again).
Next, once you know that your GPS data is coming in and formatted correctly for your Terra Web Service, confirm that the data is actually being sent to the Terra Web Service and that data is being returned from the web service call. If your Terra Web Service is returning "Unknown Location" still, try again but this time plot the GPS location near a major city to increase the odds of the web service knowing what city you are close to. If you are still returning "Unknown Location" then you can be fairly certain that the issue resides with the web service provider.
In my experience with the Windows Phone location services (I've only used dev phones with WiFi access (i.e. no sim)), location data sometimes takes a few seconds or minutes to pickup. If you're testing this on a physical dev phone in a basement or an area with limited access for the GPS to find you, odds are the data isn't being generated. Also, because the Windows Phone location data isn't necessarily instant, you can't always call it on the fly and expect it to have location data ready. In my experience I have had the user opt in to location services (per the Windows Phone Marketplace submission requirements) and then have a background agent pull location data while the user is using the app. That way location data is likely to be ready by the time user would need it (like your example when the user saves the note).
Here's a working example I made for you in C# that will work for your Windows Phone app. The sample is a console app for the sake of simplicity and time. If you can't figure it out still, I'll code it up for Windows Phone. With this though you really have everything you need to make it work, just plug in the lat and long variables. Download Working Source Code (Visual Studio 2010)
C# Source code snippet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TerraServiceExample.com.msrmaps; // add the service using statement
// http://msrmaps.com/terraservice2.asmx
namespace TerraServiceExample
{
class Program
{
/// <summary> The main entry point for the application. </summary>
static void Main(string[] args)
{
// Create the GPS point from your location services data
LonLatPt location = new LonLatPt();
// Modify Lat and Lon based on your needs
// This example uses the GPS Coordinates for "Eau Claire, Wisconsin, United States"
location.Lat = 44.811349;
location.Lon = -91.498494;
// Create a new TerraService object
TerraService ts = new TerraService();
// Output the nearest location from the TerraService
Console.WriteLine(ts.ConvertLonLatPtToNearestPlace(location));
// For console app to stay open/close easily
Console.WriteLine("Press any key to close window...");
Console.ReadKey();
// Lastly, appreciate the Microsoft folks that made this available for free
// They are all interesting individuals but you should read about Jim Gray via Wikipedia to
// understand some history behind this cool web service.
}
}
}

Related

Creating running and installing windows services - How to appropriately send a control request to the SCM

I've been struggling with this windows service now for almost two weeks, I have scoured the internet for a resolution and in the process I have learned a lot except that I have not been able to resolve my issue.
I can't seem to find the right way to compose and run a service. There are some articles and opinions on this question even on SO but most of the questions on SO don't even have an acceptable answer, I'm hoping my question will be better accepted by the community so we can settle this windows service issue once and for all.
First of all I have set my configuration mode to debug on x86 (Internal reason for this). I have an installer class as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace Practique
{
[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
public Installer1()
{
InitializeComponent();
ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();
ServiceInstaller serviceInstaller = new ServiceInstaller();
//# Service Account Information
serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
serviceProcessInstaller.Username = null;
serviceProcessInstaller.Password = null;
//# Service Information
serviceInstaller.DisplayName = "Practique";
serviceInstaller.StartType = ServiceStartMode.Manual;
//# This must be identical to the WindowsService.ServiceBase name
//# set in the constructor of WindowsService.cs
serviceInstaller.ServiceName = "Practique";
//S.Nsibande - Add service description.
serviceInstaller.Description = "Practique - application is for testing how I should send control messages to the SCM in best practice manner so as not to get stupid errors on start and stop control requests to the Microsoft OS.";
this.Installers.Add(serviceProcessInstaller);
this.Installers.Add(serviceInstaller);
}
}
}
My entry point into my service application is as follows:
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Practique
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]{ new Service1() };
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
And then the logic performed by my service is as follows:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace Practique
{
//Service class inheriting from the ServiceBase class
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
//Two required overides... OnStart() and OnStop()
protected override void OnStart(string[] args)
{
EventLog log = new System.Diagnostics.EventLog();
log.Source = "Application";
try
{
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt");
System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "Log.txt");
}
catch (Exception ex)
{
log.WriteEntry(ex.Message + ".Stack trace - " + ex.StackTrace);
if(ex.InnerException != null)
{
log.WriteEntry(ex.InnerException.Message);
}
}
}
protected override void OnStop()
{
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + "OnStart.txt");
}
private void ServiceStatus()
{
// Toggle the Practique service -
// If it is started (running, paused, etc), stop the service.
// If it is stopped, start the service.
ServiceController sc = new ServiceController("Practique");
string path = AppDomain.CurrentDomain.BaseDirectory + "Log.txt";
// Open the stream and write to it.
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("The Ptractique service status is currently set to " + sc.Status.ToString() + ".");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) || (sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
// Start the service if the current status is stopped.
// Open the stream and write to it.
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("Starting the Practique service...");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
sc.Start();
}
else
{
// Stop the service if its status is not set to "Stopped".
// Open the stream and write to it.
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("Stopping the Practique service...");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
sc.Stop();
}
// Refresh and display the current service status.
sc.Refresh();
// Open the stream and write to it.
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("The Practique service status is now set to " + sc.Status.ToString() + ".");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
}
}
I might have made some very stupid basic mistake, but that is all the code on my application. And on debug, it runs just fine, it does what it is expected to do. But once installed successfully using a batch file with the following instructions:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe
"C:\Programming\Test\Practique.exe"
Pause
My question which I hope will be answered by someone that has been creating and using windows services successfully for a long time, is why does my service keep causing the following error:
This is the information from event viewer after a successful install:
A service was installed in the system.
Service Name: Practique Service File Name:
"C:\Programming\Test\Practique.exe" Service Type: user mode
service Service Start Type: demand start Service Account:
LocalSystem
Then when I attempt to start the service, I get the following error in event viewer:
A timeout was reached (30000 milliseconds) while waiting for the
Practique service to connect.
And...
The Practique service failed to start due to the following error: The
service did not respond to the start or control request in a timely
fashion.
Then I also get this popup when trying to start the service:
Please tell me if my approach is wrong, have I missed a basic principle here, what have I done wrong or have I done too much. Any assistance is greatly appreciated.
(Edit) - I am compiling in Debug mode, although I have tried release mode just in case there might be a difference, but this did not help.
With the code you have you must compile in RELEASE mode to install your service: the SCM requires a response from your service that it has started before the service starts doing any work: when your service is compiled in DEBUG mode it starts working straight away, so never reports back to the SCM, thus resulting in the error.

How can i scan and list all connected devices to my network wireless, i'm getting exception?

My pc is connected to the router of the network i want to scan but the not wireless the pc is connected with a cable to the router.
But my android device is connected to the network wireless.
So in logic in this case the results in the list should be my pc and my android device.
This is what i'm using now managed wifi api:
managed wifi api
This 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.Windows.Forms;
using NativeWifi;
namespace ScanWifi
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
WlanClient client = new WlanClient();
try
{
foreach (WlanClient.WlanInterface wlanIface in client.Interfaces)
{
Wlan.WlanBssEntry[] wlanBssEntries = wlanIface.GetNetworkBssList();
foreach (Wlan.WlanBssEntry network in wlanBssEntries)
{
int rss = network.rssi;
byte[] macAddr = network.dot11Bssid;
string tMac = "";
for (int i = 0; i < macAddr.Length; i++)
{
tMac += macAddr[i].ToString("x2").PadLeft(2, '0').ToUpper();
}
listView1.Items.Add("Found network with SSID {0}." + System.Text.ASCIIEncoding.ASCII.GetString(network.dot11Ssid.SSID).ToString());
listView1.Items.Add("Signal: {0}%."+ network.linkQuality);
listView1.Items.Add("BSS Type: {0}."+ network.dot11BssType);
listView1.Items.Add("MAC: {0}.", tMac);
listView1.Items.Add("RSSID:{0}", rss.ToString());
}
Console.ReadLine();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
When running the program i'm exception on WlanApi.cs on the line:
Wlan.ThrowIfError(
Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle));
System.ComponentModel.Win32Exception' occurred in ManagedWifi.dll
The service has not been started
For Windows 10, the service "WLAN AutoConfig" must be started for WlanClient to work. This service should be started automatically on a computer which has a WiFi adapter present. On a computer such as a desktop which does not have a WiFi adapter, the service startup type is probably Manual and not started; you can start it anyway and WlanClient should no longer throw any exceptions, but without a WiFi adapter, it won't see any interfaces, so you won't be able to get a list of networks.
According to the documentation of the [WlanOpenHandle ][1] function, the problem is that the Wireless Zero Configuration (WZC) service is not started on your machine:
WlanOpenHandle will return an error message if the Wireless Zero Configuration (WZC) service has not been started or if the WZC service is not responsive.
However, depending on your platform, it might also might be the case that you are simply passing the wrong parameters to the WlanOpenHandle function. Have you tried passing Wlan.WLAN_CLIENT_VERSION_LONGHORN as the first parameter?

Set HTML Signature on Lotus Notes with no user interaction

I have a small VS C# program that modifies some data from an email signature on HTML format that will be used later in Lotus Notes 8.5.3
Each user is able to generate his own .html file filled with his personal data from the common template.
My problem is that now I would like the software to save the .html file on Lotus Notes Data directory and then configure the client to use that specific signature without the user having to go through the menues "More-->Preferences-->Signature" himself.
Here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FirmaCorreo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void Generar_Click(object sender, RoutedEventArgs e)
{
string suSaludo;
suSaludo = Texto1.Text;
string suNombre;
suNombre = Texto2.Text;
string suCargo;
suCargo = Texto3.Text;
string suCargo2;
suCargo2 = Texto4.Text;
string suMovil;
suMovil = Texto5.Text;
string suDirecto;
suDirecto = Texto6.Text;
string suDelegacion;
if (DelegacionVillajoyosa.IsChecked == true)
{
suDelegacion = "Villajoyosa";
}
else if (DelegacionCanarias.IsChecked == true)
{
suDelegacion = "Canarias";
}
else if (DelegacionVigo.IsChecked == true)
{
suDelegacion = "Vigo";
}
else
{
suDelegacion = "Francia";
}
var contents = System.IO.File.ReadAllText(#"C:\Users\Public\Documents\IS-IT\FirmaCorreo\Plantilla\Plantillacorreo.html", Encoding.GetEncoding(28591));
contents = contents.Replace("<!--Saludo-->", suSaludo);
contents = contents.Replace("<!--NombreDelEmpleado-->", suNombre);
contents = contents.Replace("<!--CargoDelEmpleado-->", suCargo);
contents = contents.Replace("<!--CargoDelEmpleado2-->", "<br />"+suCargo2);
contents = contents.Replace("<!--TelefonoMovil-->", "Mobile.- "+suMovil);
contents = contents.Replace("<!--TelefonoDirecto-->", "<br />Direct.- "+suDirecto);
contents = contents.Replace("<!--Delegacion"+suDelegacion, "<!-- -->");
System.IO.File.WriteAllText(#"C:\Users\Public\Documents\IS-IT\FirmaCorreo\Plantilla\PlantillacorreoModificada.html", contents, Encoding.GetEncoding(28591));
}
}
}
On my Lotus Notes 8.5.3 installation I see a notes.ini file which seems to have the signature configuration:
...
$SigSet=1
$SigState=1
$SigSetValue=1
....
$tmpStrFilter=HTML File
$tmpSigPath=C:\Lotus\Notes\Data\FirmaCorreo\FirmaPedro.html
...
Notes allows three different options for mail signatures:
I thought maybe I just had to edit notes.ini on each client to set up the resulting HTML file from my program.
The problem is notes.ini doesn't change when I change the type of signature on my client.
Is there any way to get the resulting HTML file to be the default signature on Lotus Notes without asking each user to go to the Preferences menu and select the right settings?
Can I have my C# program do that for them?
The html file path is stored in a profile document in the Mail database called $CalendarProfile and the field Signature2
You might be able hook into Notes using Microsoft COM objects(windows) and read the document, but then the code need to run on the client machine using the users password.
Another approach can be to create a lotusscript that updates the profile when user open the mailfile for the first time, this can be done once by changing the mail template and pushing it out to all users.
Keep in mind that a signature referenced to local disk will not work in webmail

Xamarin/Android - Issue reading locally stored photo from camera - no read access

I'm trying to create a simple test app to take photos in Android, using Xamarin. When I get this app working (or so I hope), i'll use the code in a real app that I'm working on. I'm using the following recipe from Xamarin as my basis:
http://docs.xamarin.com/recipes/android/other_ux/camera_intent/take_a_picture_and_save_using_camera_app/
The major difference is that I need to store images locally, and not on the SD card. I'm able to successfully take a picture (with the Android simulator). I can see the file in the file structure using ADB and can successfully copy and open the file on my PC. However, I'm unsuccessfull in accessing the file in the app, probably due to user rights.
Please note that I was successfull in creating my own .txt files, and reading them back using either System.IO and Java.IO.
Please review the following code. My app crashes when using "System.IO.File.ReadAllText" and gives me "Access to the path "/data/data/CameraAppDemo.CameraAppDemo/files/photo.jpg" is denied.". And whatever I try (absolute, relative paths, uri's), objBitmap is always null.
ADB says that "photo.jpg" has -rwxrwx--- rights, and though I'm not entirely sure, I think that should be more than sufficient
On the other hand, maybe the intent still has a lock on "photo.jpg"? Or something else is going on...
And one final note, I'm using System.IO.File.ReadAllText just for testing purposes. I experimented with stream readers as well, but with the same result. Also, though I believe this step is unnecessary, I enabled "WriteExternalStore" in the Manifest
namespace CameraAppDemo
{
using System;
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.OS;
using Android.Provider;
using Android.Widget;
using Java.IO;
using Environment = Android.OS.Environment;
using Uri = Android.Net.Uri;
[Activity(Label = "Camera App Demo", MainLauncher = true)]
public class MainActivity : Activity
{
private File _file;
private string _basePath;
private ImageView _imageView;
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
var objBitmap = BitmapFactory.DecodeFile(_file.AbsolutePath) ;
Console.WriteLine ("objBitmap = null : " + (objBitmap == null).ToString ());
var strOutput = System.IO.File.ReadAllText (FileManager.BasePath + "/photo.jpg");
Console.WriteLine (strOutput);
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
FileManager.SetupFolderStructure();
if (IsThereAnAppToTakePictures())
{
Button button = FindViewById<Button>(Resource.Id.myButton);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
button.Click += TakeAPicture;
}
}
private bool IsThereAnAppToTakePictures()
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
IList<ResolveInfo> availableActivities = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
return availableActivities != null && availableActivities.Count > 0;
}
private void TakeAPicture(object sender, EventArgs eventArgs)
{
System.IO.Directory.Delete (FileManager.BasePath, true);
_basePath = FileManager.BasePath;
_file = new Java.IO.File (_basePath, "photo.jpg");
Intent intent = new Intent(MediaStore.ActionImageCapture);
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(_file));
StartActivityForResult(intent, 0);
}
}
}
//Part of the FileManager class:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Android.Graphics;
namespace CameraAppDemo
{
public class FileManager
{
public static string BasePath {
get {
var libraryPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
if (Directory.Exists (libraryPath) == false) {
Directory.CreateDirectory (libraryPath);
}
return libraryPath;
}
}
}
}
==== Edit ====
It seems that I'm simply not able to read the file. As an ex-webdeveloper, I'm fairly new to programming for mobile, let alone the combo of C# and Java and I'm still learning a lot.
Anyway, I added the following lines:
Console.WriteLine("Setting file :" + _file.SetReadable (true));
Console.WriteLine("Can read :" + _file.CanRead());
Both cases return False. I can't read the file, and I am unable to give read access.
So, any ideas? Is this by design? Can I tell the Intent for taking images to give me read access, or is there another workaround?
If everything fails, I'm hoping to workaround the problem by saving to the SD card first and then copying the file to the local filesystem. But that's something I rather would not do; I can't guarantee that the end users have an SD card, and the pictures should not be deleted by accident.

Getting location in Windows 8 desktop apps

I am a total beginner at C#, but I have used Java a lot. I am trying to use the following code in my app to get location data. I am making a Windows 8 desktop app to use the GPS sensor in my device:
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 Windows.Devices.Sensors;
using Windows.Devices.Geolocation;
using Windows.Devices.Geolocation.Geoposition;
using Windows.Foundation;
namespace Hello_Location
{
public partial class Form1 :
{
public Form1()
{
InitializeComponent();
}
async private void Form1_Load(object sender, EventArgs e)
{
Geolocator loc = new Geolocator();
try
{
loc.DesiredAccuracy = PositionAccuracy.High;
Geoposition pos = await loc.GetGeopositionAsync();
var lat = pos.Coordinate.Latitude;
var lang = pos.Coordinate.Longitude;
Console.WriteLine(lat+ " " +lang);
}
catch (System.UnauthorizedAccessException)
{
// handle error
}
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
I get this error:
'await' requires that the type
'Windows.Foundation.IAsyncOperation'
have a suitable GetAwaiter method. Are you missing a using directive
for 'System'? C:\Users\clidy\documents\visual studio
2012\Projects\Hello-Location\Hello-Location\Form1.cs
How can I fix this?
Also it will be very useful if you can point me to some resources for C# location and the sensor API for windows desktop apps. Upon googling, I am only getting Windows RT APIs.
To fix your error you have to reference to the link that Bart gave in one of the question's comments.
You might need to add a reference to System.Runtime.WindowsRuntime.dll
as well if you are using mapped types like Windows Runtime event
handlers:
...
That assembly resides in C:\Program Files (x86)\Reference
Assemblies\Microsoft\Framework.NETCore\v4.5
I recently found a "solution" for a similar question: C# desktop application doesn't share my physical location. Maybe you might be interested by my approach: https://stackoverflow.com/a/14645837/674700.
It's more like a workaround and it's not targeting Windows 8, but it works in the end.
alex's solution works!
add that reference and geolocation api starts working like a charm! so do async methods for other sensors!
here is a function i just got working using it.
async public void UseGeoLocation()
{
Geolocator _GeoLocator = new Geolocator();
Geoposition _GeoPosition =
await _GeoLocator.GetGeopositionAsync();
Clipboard.Clear();
Clipboard.SetText("latitude," +
_GeoPosition.Coordinate.Latitude.ToString() +
"," + "longitude," + _GeoPosition.Coordinate.Longitude.ToString() +
"," + "heading," + _GeoPosition.Coordinate.Heading.ToString() +
"," + "speed," + _GeoPosition.Coordinate.Speed.ToString());
Application.Exit();
}

Categories

Resources