C# UWP Geolocation, access denied - c#

everybody.
I am trying to get current user's location in C# UWP application.
var geoLocator = new Geolocator();
geoLocator.DesiredAccuracy = PositionAccuracy.High;
var accessStatus = await Geolocator.RequestAccessAsync();
var pos = await geoLocator.GetGeopositionAsync();
var latitude = pos.Coordinate.Point.Position.Latitude;
var longitude = pos.Coordinate.Point.Position.Longitude;
But I get the error:
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll but was not handled in user code
WinRT information: Your App does not have permission to access location data. Make sure you have defined ID_CAP_LOCATION in the application manifest and that on your phone, you have turned on location by checking Settings > Location.
Additional information: Access is denied.
In Package.appxmanifest I have these items checked:
Internet (Client & Server) - checked,
Internet (Client) - checked,
Location - checked.
How can I set permission in local machine?

I solved this issue. In Windows 10, in Location privacy settings my Location services wasn't on. So I turned it on, and now it is working.

You need to check either you are allowed to access location services or not ?
You can handle this using RequestAccessAsync() method of GeoLocater Class in UWP.
Geolocator geoLocator = new Geolocator();
GeolocationAccessStatus accessStatus = await Geolocator.RequestAccessAsync();
if ( accessStatus == GeolocationAccessStatus.Allowed)
{
// Put all your Code here to access location services
Geoposition geoposition = await geoLocator.GetGeopositionAsync();
var position = geoposition.Coordinate.Point.Position;
var latlong = string.Format("lat:{0}, long:{1}", position.Latitude, position.Longitude);
}
else if (accessStatus == GeolocationAccessStatus.Denied)
{
// No Accesss
}
else
{
}

Related

C# LDAP authentication strange issue

I have a VMWare machine with Windows Server 2012 and Active Directory installed. The domain name is "cpx.local" and I have created a new user "testad".
I have a C# Winform application so I can test the connection to the LDAP server and then get all the users or groups in the Active Directory.
This is the code that works fine:
string server = "192.168.238.129";
string port = "389";
System.DirectoryServices.Protocols.LdapConnection ldapConnection =
new System.DirectoryServices.Protocols.LdapConnection(new LdapDirectoryIdentifier(server + ":" + port));
TimeSpan mytimeout = new TimeSpan(0, 0, 0, 1);
try
{
ldapConnection.AuthType = AuthType.Anonymous;
ldapConnection.AutoBind = false;
ldapConnection.Timeout = mytimeout;
ldapConnection.Bind();
Console.WriteLine(("Successfully authenticated to ldap server "));
ldapConnection.Dispose();
}
catch (LdapException ex)
{
Console.WriteLine(("Error with ldap server "));
Console.WriteLine((ex.GetType().ToString() + (":" + ex.Message)));
}
The problem is that if I want to authenticate with the new user "testad" it doesn't work.
I change the AuthType to be Basic and set the credentials.
ldapConnection.AuthType = AuthType.Basic;
ldapConnection.Credential = new NetworkCredential(#"cpx\testad", "test#D12345", "cpx.local");
ldapConnection.AutoBind = false;
ldapConnection.Timeout = mytimeout;
ldapConnection.Bind();
I get the following error:
I have tried to Login the Windows Server 2012 with this user and I can login perfect.
The interesting thing is that the following code is working fine:
var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", "192.168.238.129:389", "DC=cpx,DC=local"), "testad", "test#D12345");
var searcher = new DirectorySearcher(dirEntry)
{
Filter = "(&(&(objectClass=user)(objectClass=person)))"
};
var resultCollection = searcher.FindAll();
Am I doing something wrong with the NetworkCredentials?
maybe doubleccheck credentials.in NetworkCredential support username without 'cpx/' in front. as domain is provided
ldapConnection.Credential = new NetworkCredential(#"testad", "test#D12345", "cpx.local");
If you set the AuthType to Negotiate, does it work ?
AuthType details here
change:
ldapConnection.AuthType = AuthType.Basic;
to:
ldapConnection.AuthType = AuthType.Negotiate;
Regarding the domain name - cpx vs cpx.local - you can take a look at this article about some recommended practices
http://www.mdmarra.com/2012/11/why-you-shouldnt-use-local-in-your.html
The correct way to name an Active Directory domain is to create a subdomain that is the delegation of a parent domain that you have registered and have control over. As an example, if I ever started a consulting business and used the Internet-facing website mdmarra.com as my company's site, I should name my Active Directory domain ad.mdmarra.com or internal.mdmarra.com, or something similar. You want to avoid making up a TLD like .local and you also want to avoid the headache of using mdmarra.com for the Internet-facing zone and the internal zone.
Change: ldapConnection.AutoBind= false;
to: ldapConnection.AuthType = true;

Hide share option from Google doc

I am uploading / creating file on Google Drive using .NET SDK for google drive api. Everything works fine and I can give permission to user as per my business logic like writer,reader,commenter or owner. But I want to hide the Share button from everybody except Owner as my business logic should decide which file should be shared with whom and when.
Here is the code for sharing the document:
try
{
Google.Apis.Drive.v2.Data.Permission permission = new Google.Apis.Drive.v2.Data.Permission();
switch (role)
{
case GoogleRoles.WRITER:
case GoogleRoles.READER:
case GoogleRoles.OWNER:
{
permission.Role = role;
permission.Value = userEmail;
permission.Type = "user";
break;
}
case GoogleRoles.COMMENTER:
{
permission.Role = GoogleRoles.READER; //Need to assign role before we assign the additional role of commenter.
List<String> additionalRoles = new List<string>();
additionalRoles.Add(GoogleRoles.COMMENTER);
permission.AdditionalRoles = additionalRoles;
permission.Type = "user";
permission.Value = userEmail;
break;
}
}
PermissionsResource.InsertRequest insertRequest = DriveService.Permissions.Insert(permission, fileId);
insertRequest.SendNotificationEmails = true;
insertRequest.Execute();
Where DriveService is an instance of service account. Any pointer would be a great help.
Unfortunately the Drive API doesn't yet support the feature of disabling sharing or disabling downloading. Please file a feature request here: https://code.google.com/a/google.com/p/apps-api-issues/issues/entry?template=Feature%20request&labels=Type-Enhancement,API-Drive
I had raised this as an enhancement, and got the response too. So in Google drive API its not part of permission but these are properties of file itself, so we need to set he properties instead of permissions like:
File.LabelsData labels = new File.LabelsData();
labels.Restricted = true;
File body = new File();
body.Labels = labels;
body.WritersCanShare = false;
It has solved the issue of Share but download issue is not solved it by above changes. More details about this can be found at https://developers.google.com/drive/v2/reference/files

Trying to update livetile from backgroundaudiotask in Windows Phone 8.1: "The application identifier provided is invalid"

I have a music player and would like to update the livetile with the albumart of the playing track. So each time the track changes I call a method in a seperate Windows Runtine Component. The method looks like this:
public async void CreateLivetile(string albumart, string artist, string trackname)
{
try
{
// constants
string textElementName = "text";
string imageElementName = "image";
// Create a tile update manager
var updater = TileUpdateManager.CreateTileUpdaterForApplication();
updater.EnableNotificationQueue(true);
updater.Clear();
// wide 310x150
var tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150PeekImage03);
tileXml.GetElementsByTagName(textElementName).LastOrDefault().InnerText = string.Format(artist + " - " + trackname);
var image = tileXml.GetElementsByTagName(imageElementName).FirstOrDefault();
if (image != null)
{
var src = tileXml.CreateAttribute("src");
src.Value = albumart;
image.Attributes.SetNamedItem(src);
}
// square 150x150
var squaredTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150PeekImageAndText01);
squaredTileXml.GetElementsByTagName(textElementName).FirstOrDefault().InnerText = string.Format(artist + " - " + trackname);
image = squaredTileXml.GetElementsByTagName(imageElementName).LastOrDefault();
if (image != null)
{
var src = squaredTileXml.CreateAttribute("src");
src.Value = albumart;
image.Attributes.SetNamedItem(src);
}
updater.Update(new TileNotification(tileXml));
updater.Update(new TileNotification(squaredTileXml));
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
// Inform the system that the task is finished.
//_deferral.Complete();
}
}
When the method reaches this line:
var updater = TileUpdateManager.CreateTileUpdaterForApplication();
I get this error:
The application identifier provided is invalid.
This method does work fine in the app (front-end)...
There is solution:
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/83498107-fe0d-4a8b-93f3-02d484983953/tileupdatemanager-throws-exception?forum=wpdevelop
Just provide ID directly:
TileUpdateManager.CreateTileUpdaterForApplication("App")
You've found a common bug in the simulator.
From one of Microsoft's blogs:
We’ve found two scenarios that cause this failure. The first is during
app development when running the app in the simulator in Visual
Studio. This error may be thrown when updating tiles. The
recommendation is to run the app under the Local Machine setting
[...].
Secondly, this failure can occur when the underlying notification
platform is not available on the user’s machine. If the notification
platform has encountered an issue that caused it to terminate, it
causes tile notification and updating to fail as well. The call to
TileUpdateManager.CreateTileUpdaterForApplication normally retrieves
the package full name, creates a notification endpoint, and performs
package and app name validation for the notification subsystem.
Problems with either of the last two steps can cause “The application
identifier provided is invalid” to be returned, generating this
exception.
See also:
updating tiles in Win 8 Metro app
Why is identifier for secondary tile invalid?
"cant-update-secondary-tile"

Access Denied Exception while writing email Windows 8.1 C#

private async Task<StorageFile> GetCsvFile()
{
var localFolder = KnownFolders.DocumentsLibrary;
var file = await localFolder.CreateFileAsync("NRBcatalogue.csv", Windows.Storage.CreationCollisionOption.ReplaceExisting);
String rk = "";
for (int i = 0; i < k1.Count; i++)
{
rk += k1[i] + "\n";
}
await Windows.Storage.FileIO.WriteTextAsync(file, rk);
return file;
}
private async void AppBarButton_Click_1(object sender, RoutedEventArgs e)
{
EmailMessage email = new EmailMessage();
email.To.Add(new EmailRecipient("brk27.007#gmail.com"));
email.Subject = "NRB Catalogue";
var file = await GetCsvFile(); //Error occured here
email.Attachments.Add(new EmailAttachment(file.Name, file));
await EmailManager.ShowComposeNewEmailAsync(email);
}
The Error Details are:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll.
An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.ni.dll but was not handled in user code.
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
you are trying to access a location that you don't have permission var localFolder = KnownFolders.DocumentsLibrary;
This is valid exception because you can't access DocumentsLibrary location from you windows phone app. This location is only available for Windows store app. You can use other location but before using make sure that you have added this location as capability in the app’s manifest. For reference check This Link.
So have to chose other location that your app can access. e.g LocalFolder , IsolatedStorage etc. For Localfolder just change your accessing folder code by below code.
var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Hope it solve your problem. cheers :)

Windows Store App, ... cannot be used on the current platform. ERROR

I have Windows Store app which is actually a game and I'm trying to implement posting result on Facebook.
I'm using Facebook SDK for .Net from facebooksdk.net
Here's my code
FacebookSession session = await App.FacebookSessionClient.LoginAsync("publish_stream");
if (session == null)
{
MessageDialog dialog = new MessageDialog("Error while getting publishing permissions. Please try again.");
await dialog.ShowAsync();
return;
}
// refresh your access token to contain the publish permissions
App.AccessToken = session.AccessToken;
FacebookClient fb = new FacebookClient(App.AccessToken);
string message = "Your score is: " + points;
dynamic proba = message;
try
{
//The next line throws exception
dynamic fbPostTaskResult = await fb.PostTaskAsync("/me/feed?message='{0}", proba);
var result = (IDictionary<string, object>)fbPostTaskResult;
var successMessageDialog = new Windows.UI.Popups.MessageDialog("Posted Open Graph Action, id: " + (string)result["id"]);
await successMessageDialog.ShowAsync();
}
catch (Exception ex)
{
MessageDialog exceptionMessageDialog = new MessageDialog("Exception during post: " + ex.Message);
exceptionMessageDialog.ShowAsync();
}
And the Exception Message that I recieve is:
The API 'System.String.Get_FirstChar()' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information
I tried diffrent ways to send arguments to "PostTaskAsync()" method but I always got the same Exception. Searching Google and Stackoverflow wasn't much helpful.
I'm much grateful for any sort of help.
Cheers

Categories