Access Denied Exception while writing email Windows 8.1 C# - 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 :)

Related

How to launch PDF file in associated app in HoloLens UWP?

I'm trying to open a PDF file, packaged inside app folder ("Assets"), in HoloLens (C#) app.
string imageFile = #"Assets\test.jpg";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
Debug.WriteLine("Opening file in path :" + file.Path);
if (file != null)
{
Debug.WriteLine("File found\nLaunching file...");
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
Debug.WriteLine("File launched successfully");
// File launched
}
else
{
Debug.WriteLine("File launch failed");
// File launch failed
}
}
else
{
Debug.WriteLine("Could not find file");
// Could not find file
}
Getting Access is Denied error.
Exception thrown: 'System.UnauthorizedAccessException' in mscorlib.ni.dll
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at SchneiderDemoLibrary.HoloHelper.<DefaultLaunch>d__3.MoveNext() Exception caught.
Can someone help me to solve this issue? I simply want to open some file with the corresponding app associated with the file type.
Verify that the file is included in your project, and that the Build Action is set to "Content".
Switch to retrieving the IStorageFile reference via the StorageFile.GetFileFromApplicationUriAsync call.
The following code is working for me in a regular UWP application:
private async void OpenPdfButton_Click(object sender, RoutedEventArgs e)
{
var file = await StorageFile.GetFileFromApplicationUriAsync
(
new Uri("ms-appx:///Content/output.pdf")
);
await Launcher.LaunchFileAsync(file);
}

C# UWP Geolocation, access denied

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
{
}

Closed Captions resolving error System.UnauthorizedAccessException

So, I'm trying to implement closed captions support to my UWP video player (using MediaElement), I've followed this example to do so.
I'm getting an error when resolving it called "Error resolving track due to error NetworkError System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I do it like this: I open a file using filepicker and then get the SRT of the video that was picked. After that I show it. Unfortunately, nothing appears.
Here is my OpenButton function:
private async void BtnOpenMedia_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.Thumbnail;
filePicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
filePicker.FileTypeFilter.Add(".mp4");
filePicker.FileTypeFilter.Add(".wmv");
filePicker.FileTypeFilter.Add(".mpg");
filePicker.FileTypeFilter.Add(".mpeg");
filePicker.FileTypeFilter.Add("*");
StorageFile storageFile = await filePicker.PickSingleFileAsync();
if (storageFile != null && mElement != null)
{
string strSource = Path.GetDirectoryName(storageFile.Path) + #"\" + storageFile.DisplayName + ".srt";
var mediaSource = MediaSource.CreateFromStorageFile(storageFile);
var ttsStream = TimedTextSource.CreateFromUri(new Uri(strSource));
ttsStream.Resolved += TtsStream_Resolved;
mediaSource.ExternalTimedTextSources.Add(ttsStream);
var mediaPlayback = new MediaPlaybackItem(mediaSource);
mElement.SetPlaybackSource(mediaPlayback);
}
}
Here is my resolve function:
private void TtsStream_Resolved(TimedTextSource sender, TimedTextSourceResolveResultEventArgs args)
{
if (args.Error != null)
{
var ignoreAwaitWarning = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
var msg = new MessageDialog("Error resolving track " + " due to error " + args.Error.ErrorCode + " " + args.Error.ExtendedError);
await msg.ShowAsync();
});
return;
}
}
P.S: Also, I don't know if this is duplicated or not, that's why I'm adding it in this but I've done my research and found nothing. How to preview frames of MediaElement ? For example like YouTube you can preview thumbnails in the slider, I don't know how to achieve that, thanks!
You used a FileOpenPicker to select the Video file, but use a Path to access the .srt file. The .srt file is also in the Video file's folder. I reproduced your problem here:
The error message is clear, you have no access to this file, this file indicates the .srt file, so the problem is where did you store this .srt file. Just have a test, seems TimedTextSource.CreateFromUri(Uri) | createFromUri(Uri) method does not support to access the files in the local machine, but you can use TimedTextSource.CreateFromStream(IRandomAccessStream) | createFromStream(IRandomAccessStream) method for example like this:
if (storageFile != null && mElement != null)
{
//string strSource = Path.GetDirectoryName(storageFile.Path) + #"\" + storageFile.DisplayName + ".srt";
var fileSource = await KnownFolders.VideosLibrary.GetFileAsync(storageFile.DisplayName + ".srt");
IRandomAccessStream strSource = await fileSource.OpenReadAsync();
var mediaSource = MediaSource.CreateFromStorageFile(storageFile);
//var ttsStream = TimedTextSource.CreateFromUri(new Uri(strSource));
var ttsStream = TimedTextSource.CreateFromStream(strSource);
ttsStream.Resolved += TtsStream_Resolved;
mediaSource.ExternalTimedTextSources.Add(ttsStream);
var mediaPlayback = new MediaPlaybackItem(mediaSource);
mediaPlayback.TimedMetadataTracksChanged += (sender1, args) =>
{
mediaPlayback.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
};
mElement.SetPlaybackSource(mediaPlayback);
}
When using this code, the .srt file and video file should in the Video lib and the capability "Videos Library" should be enabled in the manifest.
In an UWP app, you can only access the files in known folder like picture lib, music lib and video lib and doc lib or local folder of your app, if your video is not in these folders, you should also handle the exception when access is denied in this scenario.
How to preview frames of MediaElement ? For example like YouTube you can preview thumbnails in the slider.
For this question, I can't find any ready-made sample for you, but I think the scenario 4 of official Media editing sample can be a direction, it shows a overlay layer on MediaElement, maybe you can set the "baseVideoFile" and the "overlayVideoFile" with the same source. The problem is when and where to show this overlay layer, it's related to the transport control of MediaElement. This is for now just a mind, you can have a try.

Upload a file in Onedrive exception

I would upload a file to onedrive, I created a method for signing , i insert wl.skydrive_update scope,the problem is in the upload method generates me an exception, I call the method with a button this is the code:
private async void upload_Click(object sender, RoutedEventArgs e)
{
if(defaultDb != null)
{
try
{
// Upload to OneDrive.
LiveUploadOperation uploadOperation = await connectClient.CreateBackgroundUploadAsync(folderId, "file.db", defaultDb, OverwriteOption.Rename);
LiveOperationResult uploadResult = await uploadOperation.StartAsync();
}
catch (LiveAuthException ex)
{
// Handle errors.
}
catch (LiveConnectException ex)
{
// Handle errors.
}
}
}
defaultDb is a StorageFile of the files I want to load.
folderId is the ID of the folder in OneDrive.
this is the exception:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.ni.dll
thank you.
EDIT:
the problem is in the file to be uploaded, because if I select another file with the filepicker this is successful, instead, selecting my file that is in the folder localstate of application, is not working. it is possible that the reason why I can not upload it just because it is in the folder Localstate?

Access to the path is denied in Windows Store application

I create Windows Store application. In MainPage.xaml.cs I want to get data from xml file, but I get error message on line:
XDocument document = XDocument.Load(filename).
UnauthorizedAccessException was unhandled by user code
Access to the path 'C:\Events Project\events.xml' is denied.
Any advice is appreciated.
MainPage.xaml.cs
private EventMan man = new EventMan();
public MainPage()
{
this.InitializeComponent();
this.LoadEvents();
}
private void LoadEvents()
{
this.Events = man.GetAllEvents(#"C:\Events Project\events.xml");
}
EventMan.cs
public List<Event> GetAllEvents(string filename)
{
if (filename == null)
{
throw new ArgumentNullException("filename");
}
XDocument document = XDocument.Load(filename);
...
}
You can only access certain locations with Windows Store apps by default, as explained here:
File access and permissions in Windows Store apps
You can put the file in your app's AppData folder. Then you can use the ApplicationData class to freely access the file from there...
var file = await ApplictionData.Current.LocalFolder.GetFileAsync("events.xml");

Categories