System.UnauthorizedAccessException C# Windows 10 Phone Emulator - c#

I know there is a bunch of threads on seemingly the same issue but I cannot for the life of me figure this out after 3 hours so I really need some help.
I understand that I am getting this error because the system does not have access to the file. I have tried setting permissions to full and a few other code snippets to solve my issue but none have worked.
This is a windows 10 app using Xaramin,
I am trying to populate a listbox with contact from an XML file. I have the list box itemsSource set to "Data Context" and path "myList". The XML build action is set to "Content" and the Copy to Output Directory Set to "Copy Always".
I have attempted to follow the tutorial from my course from the beginner 3 times and always get the same error.
Here is the error I am getting
Below is the entire code on the page.
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 Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using System.Xml;
using System.Xml.Linq;
using Windows.Storage;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace ContactsApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
string TEMPFILEPATH = "";
string TARGETFILEPATH = "";
private ObservableCollection<string> lstd = new ObservableCollection<string>();
public ObservableCollection<string> myList { get { return lstd; } }
public MainPage()
{
this.InitializeComponent();
}
private void Grid_Loading(FrameworkElement sender, object args)
{
Windows.ApplicationModel.Package package = Windows.ApplicationModel.Package.Current;
StorageFolder installedLocation = package.InstalledLocation;
StorageFolder targetLocation = ApplicationData.Current.LocalFolder;
TEMPFILEPATH = installedLocation.Path.ToString() + "\\Contacts.xml";
TARGETFILEPATH = targetLocation.Path.ToString() + "\\Contacts.xml";
File.Move(TEMPFILEPATH, TARGETFILEPATH);
loadContacts();
}
private void loadContacts()
{
XmlReader xmlReader = XmlReader.Create(TARGETFILEPATH);
while (xmlReader.Read())
{
if (xmlReader.Name.Equals("ID") && (xmlReader.NodeType == XmlNodeType.Element))
{
lstd.Add(xmlReader.ReadElementContentAsString());
}
}
DataContext = this;
xmlReader.Dispose();
}
}
}
I will be eternally grateful for any help regarding the matter. :)

You should not try to access restricted paths in constrained environments (like Windows Phone).
Instead, if you really need to embed this file with your application, change the build action to Embedded Resource and to Do not copy for your xml file, and then retrieve the resource inside your code as an Embedded Resource:
public void LoadContacts()
{
const string fileName = "Contacts.xml";
var assembly = typeof(MainPage).GetTypeInfo().Assembly;
var path = assembly.GetManifestResourceNames()
.FirstOrDefault(n => n.EndsWith(fileName, StringComparison.OrdinalIgnoreCase));
if(path == null)
throw new Exception("File not found");
using (var stream = assembly.GetManifestResourceStream(path))
using (var reader = XmlReader.Create(stream))
{
while (reader.Read())
{
if (reader.Name.Equals("ID") && (reader.NodeType == XmlNodeType.Element))
{
lstd.Add(reader.ReadElementContentAsString());
}
}
}
DataContext = this; // better to move this inside the constructor
}

Related

Trouble Enumerating BLE devices in Win32 Desktop Application Using UWP APIs

I am trying to add BLE functionality into a classic (WinForms?) C# desktop application, and have added references (Windows.winmd and System.Runtime.WindowsRuntime) to allow me to access the new BLE API recently introduced by Microsoft for Windows 10 UWP applications. I need to create a classic desktop application, as I need to use an older driver device wrapper (teVirtualMIDI) and want to create a .exe, not an app package.
I am referencing the aformentioned libraries from the following locations...
C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.WinMD
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.UI.Xaml.dll
At this point, I simply want to be able to view connected services and characteristics in the debug output window, as is done in this blog post...
https://blogs.msdn.microsoft.com/cdndevs/2017/04/28/uwp-working-with-bluetooth-devices-part-1/
It seems that I am getting errors because the BLE API needs to perform async operations, but I am honestly at a loss. The code I have written so far is included below. Essentially, I am receiving errors when trying to call the "GetGattServicesAsync()" method, as Visual Studio says that class "BluetoothLEDevice" does not contain such a definition. That method is included in the online documentation though, and I am wondering why I am not able to access it.
I hope I have given sufficient information, and any help in solving this problem will be more than appreciated. Thank you all for all the helpful advice you give!
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using Windows.Devices.Bluetooth;
using Windows.Devices.Midi;
using Windows.Devices.Bluetooth.Advertisement;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace BDBMidiClient
{
public class BLEHandlingDiscovery : Page
{
//private ObservableCollection<BluetoothLEAttributeDisplay> ServiceCollection = new ObservableCollection<BluetoothLEAttributeDisplay>();
//private ObservableCollection<BluetoothLEAttributeDisplay> CharacteristicCollection = new ObservableCollection<BluetoothLEAttributeDisplay>();
public ObservableCollection<BluetoothLEDeviceDisplay> KnownDevices = new ObservableCollection<BluetoothLEDeviceDisplay>();
//private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();
//private DeviceWatcher deviceWatcher;
//private BluetoothLEDevice bluetoothLeDevice = null;
//private GattCharacteristic selectedCharacteristic;
private void StartBLEDeviceWatcher()
{
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
/*
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
"System.ItemNameDisplay:~~\"BDB\"",
requestedProperties,
DeviceInformationKind.AssociationEndpoint);*/
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.Start();
//Debug.WriteLine(requestedProperties);
}
private async void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
Guid gattService = new Guid();
var device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
var services=await device.GetGattServicesAsync();
foreach (var service in services.Services)
{
Debug.WriteLine($"Service: {service.Uuid}");
var characteristics = await service.GetCharacteristicsAsync();
foreach (var character in characteristics.Characteristics)
{
Debug.WriteLine($"Characteristic: {character.Uuid}");
}
}
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfoUpdate)
{
}
async void ConnectToBLEDevice(DeviceInformation deviceInformation)
{
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync("BDB");
}
private BluetoothLEDeviceDisplay FindBluetoothLEDeviceDisplay(string id)
{
foreach (BluetoothLEDeviceDisplay bleDeviceDisplay in KnownDevices)
{
if (bleDeviceDisplay.Id == id)
{
return bleDeviceDisplay;
}
}
return null;
}
}
The doc says the API belongs to "Windows 10 Creators Update (introduced v10.0.15063.0)". So please try to add the one from "C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.15063.0\Windows.winmd"
Here is the result from my project
You can see my code works well.

"File.Exists" does not exist

I created this class "XML_Toolbox" that could be used by any of my forms to perform any of the key XML actions that i am going to be using repeatedly. So with that being said, here is that class' code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace Personal_Finance_Manager
{
class XML_toolbox
{
public static void createFile (string filename, string filePath)
{
string createPath = filePath + #"\" + filename + ".txt";
if (file.exists(createPath))
{
StreamWriter outfile = new StreamWriter(createPath, true);
}
else
{
MessageBox.Show("This file already exists!!! Please choose another name!");
}
}
}
}
all the individual parts were working when called from another form up until i added the:
if (file.exists(createPath)) {}
IF statement.
Now i am getting the
The name "file" does not exist in the current context
error. I have the
using System.IO;
what else am i missing?
Thanks!
Class name is File not file, method name is Exists. C# is case-sensitive.
It's called File, not file.
File.Exists()

COMException C# Microsoft.Office.Interop.Excel

I am trying to solve an issue I am having with a COMException. This is my code:
The error occurs at Workbook Original = new Workbook(result[0]);
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;
using MahApps.Metro.Controls;
using MahApps.Metro;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Data;
using Microsoft.Office.Interop.Excel;
namespace KPI_Generator_v3
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
string [] result;
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
public MainWindow()
{
InitializeComponent();
}
private void exit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void browse_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
instructionslbl.Visibility = Visibility.Hidden;
dlg.Multiselect = true;
dlg.ShowDialog();
result = dlg.FileNames;
dlg.DefaultExt = ".xls";
dlg.Filter = "XLS Files (*.xls)|*.xls";
foreach (string fileName in result)
{
displayFilesBox.Text += fileName + System.Environment.NewLine;
}
SelectedFileslbl.Visibility = Visibility.Visible;
displayFilesBox.Visibility = Visibility.Visible;
generateBtn.Visibility = Visibility.Visible;
}
private void generate_Click(object sender, RoutedEventArgs e)
{
Workbook Original = new Workbook(result[0]);
for (int i = 1; i <= result.Length; i++)
{
Workbook next = new Workbook(result[i]);
Worksheet newOGsheet = Original.Worksheets.Add();
Worksheet nextSheet = next.Worksheets[0];
nextSheet.Copy(newOGsheet);
}
}
}
}
Now.. Although the above code will probably not work I am getting an error that states
'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll
with additional information saying
HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
After googling for quite some time I have downloaded dependency walker and have the following output:
I have no idea what I am doing and some help would be much appreciated! Thank you
EDIT: REGEDIT picture of HKEY CLASSES_ROOT (if needed)
EDIT2: Picture of error
This error is a COM interop flaw unfortunately. Otherwise, you would be getting a compile error, since Workbook is an interface and doesn't have a constructor. This interface isn't meant to be instantiated, which is why you are getting this exception. (Not sure why you're passing in the filename here as well...)
To fix this, use Microsoft.Office.Interop.Excel.Application:
using Microsoft.Office.Interop.Excel;
Application excelApp = new Application();
excelApp.Workbooks.Open(result[0]);
Other notes:
You should call dlg.ShowDialog() last - that way, your filters will take effect.
For your filter, I suggest adding an option for .xlsx files, to support newer Excel files
Add result.Length > 0 before using it, just to make sure the user actually opened something.
Change your for loop condition to i < result.Length; otherwise, you'll get an IndexOutOfRangeException
Also, just to add more information: you may be asking: "but wait, ryrich, Application is an interface too! How come I can instantiate it but not Workbook??"
I wondered this too. Apparently this works because it is decorated with a CoClassAttribute (and some other attributes). For more detailed information about this, see this stack overflow post.

How to give Common path to video

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);
}

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