System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))' - c#

Hello I am working on VPN in C# this is my code
VpnManagementAgent vpnManagementAgent = new VpnManagementAgent();
VpnManagementAgent mgr = vpnManagementAgent;
VpnNativeProfile profile = new VpnNativeProfile()
{
AlwaysOn = false,
NativeProtocolType = VpnNativeProtocolType.IpsecIkev2,
ProfileName = "MyConnection",
RememberCredentials = true,
RequireVpnClientAppUI = true,
RoutingPolicyType = VpnRoutingPolicyType.SplitRouting,
TunnelAuthenticationMethod = VpnAuthenticationMethod.Certificate,
UserAuthenticationMethod = VpnAuthenticationMethod.Mschapv2,
};
profile.Servers.Add("serveAddress");
VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
PasswordCredential credentials = new PasswordCredential
{
UserName = "username",
Password = "Abc",
};
VpnManagementErrorStatus connectStatus = await mgr.ConnectProfileWithPasswordCredentialAsync(profile, credentials);
i add all this code on button action. now when i start VPN connection this line throw exception
VpnManagementErrorStatus profileStatus = await mgr.AddProfileFromObjectAsync(profile);
Exception is
System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'
StackTrace:
at Windows.Networking.Vpn.VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile profile)
at App1.MainPage.<Button_Click>d__2.MoveNext() in C:\Users\HP\source\repos\StarkVPnTesting\App1\MainPage.xaml.cs:line 62

I believe you need to add the App Capability "networkingVpnProvider" as per the below:
This link describes the significance and how to apply App Capabilities MSDN App Capability. Ultimately you will need to add the below to your app package manifest source file (Package.appxmanifest).
<?xml version="1.0" encoding="utf-8"?>
<Package
...
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="... rescap">
...
<Capabilities>
<rescap:Capability Name="networkingVpnProvider"/>
</Capabilities>
</Package>
Note that this is a Windows 10 requirement as per the documentation for the method: VpnManagementAgent.AddProfileFromObjectAsync(IVpnProfile) Method

Related

StimulReport Error with MVC (Access Denied or Null Value)

I have a stimulus report that runs locally without any problems, but I get the following error in IIS
Access to the path 'Stimulsoft' is denied.
System.UnauthorizedAccessException: Access to the path 'Stimulsoft' is denied.
Source Error : Line 6
Line 4: }
Line 5:
Line 6: #Html.Stimulsoft().StiMvcViewer(options: new StiMvcViewerOptions()
Line 7: {
Line 8: Actions =
Code in Controller :
public ActionResult report()
{
var report = new StiReport();
report.Load(Server.MapPath("~/Content/SalaryReport.mrt"));
report.Compile();
Code in View :
#using Stimulsoft.Report.Mvc;
#{
ViewBag.Title = "Print";
}
#Html.Stimulsoft().StiMvcViewer(options: new StiMvcViewerOptions()
{
Actions =
{
GetReport = "report",
ViewerEvent = "viewerEvent"
}
})
unfortunately no one answered my question and I finally found the solution myself, the reason for this error is in the version of the reporting software that needs to be changed.
add this code to web config :
<appSettings>
<add key="PageInspector:ServerCodeMappingSupport" value="Disabled" />
</appSettings>
Use StimulSoft Report 2015 or higher, version 2014 does not work properly

UWP application unable to access USB drive even though permissions are set

I am working on an app that is responsible for formatting a USB drive and prepare it for further use on an embedded system.
I am formatting the drive using the following method that I found on stack overflow (unfortunately I did not save the link. I'll post it there if I find it again)
public static bool FormatUSB(string driveLetter, string fileSystem = "FAT32", bool quickFormat = true,
int clusterSize = 4096, string label = "USB_0000", bool enableCompression = false)
{
//add logic to format Usb drive
//verify conditions for the letter format: driveLetter[0] must be letter. driveLetter[1] must be ":" and all the characters mustn't be more than 2
if (driveLetter.Length != 2 || driveLetter[1] != ':' || !char.IsLetter(driveLetter[0]))
return false;
//query and format given drive
//best option is to use ManagementObjectSearcher
var files = Directory.GetFiles(driveLetter);
var directories = Directory.GetDirectories(driveLetter);
foreach (var item in files)
{
try
{
File.Delete(item);
}
catch (UnauthorizedAccessException) { }
catch (IOException) { }
}
foreach (var item in directories)
{
try
{
Directory.Delete(item);
}
catch (UnauthorizedAccessException) { }
catch (IOException) { }
}
ManagementObjectSearcher searcher = new ManagementObjectSearcher(#"select * from Win32_Volume WHERE DriveLetter = '" + driveLetter + "'");
foreach (ManagementObject vi in searcher.Get())
{
try
{
var completed = false;
var watcher = new ManagementOperationObserver();
watcher.Completed += (sender, args) =>
{
Console.WriteLine("USB format completed " + args.Status);
completed = true;
};
watcher.Progress += (sender, args) =>
{
Console.WriteLine("USB format in progress " + args.Current);
};
vi.InvokeMethod(watcher, "Format", new object[] { fileSystem, quickFormat, clusterSize, label, enableCompression });
while (!completed) { System.Threading.Thread.Sleep(1000); }
}
catch
{
}
}
return true;
}
I also added all the capabilities that should be required (I think) in order to access a removable drive in my manifest:
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
IgnorableNamespaces="uap mp rescap iot">
<Identity
Name="7b9becad-6afd-4872-bcb7-7f414c098edf"
Publisher="CN=vitto"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="7b9becad-6afd-4872-bcb7-7f414c098edf" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>DiskMakerApp</DisplayName>
<PublisherDisplayName>vitto</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="DiskMakerApp.App">
<uap:VisualElements
DisplayName="DiskMakerApp"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="DiskMakerApp"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
<rescap:Capability Name="appCaptureSettings" />
<Capability Name="internetClient" />
<uap:Capability Name="removableStorage" />
<iot:Capability Name="systemManagement"/>
<DeviceCapability Name="usb"/>
</Capabilities>
</Package>
And also allowed access to the file system in Window's settings page:
But I am still getting:
I am wondering if I am missing anything. Is there a way I could run the app as an administrator^ Would that solve the issue? (In any case, only admins would be able to run that app in a real life scenario)
UWP application unable to access USB drive even though permissions are set
Directory.GetFiles can't not use to access file with path in UWP platform. And you can only use Windows Storage API to access file with path (enable broadFileSystemAccess ), by the way, System.Management Namespace is not work for UWP platform, and if you want to format USB device within UWP app, please use desktop extension to process. for more please refer stefan' blog UWP with Desktop Extension

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) when trying to read battery of Airpod pro

I am trying to read my air pods pro battery life using UWP app and I get an exception error when socket.ConnectAsync is called Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) without any more info. Below you can find the source:
private async Task ConnectToAirpods()
{
DeviceInformationCollection connectedDevices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected));
foreach (DeviceInformation connectedDevice in connectedDevices)
{
if (connectedDevice.Name != "AirPods Pro")
continue;
BluetoothDevice bluetoothDevice = await BluetoothDevice.FromIdAsync(connectedDevice.Id);
RfcommDeviceServicesResult rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(
RfcommServiceId.FromUuid(new Guid("0000111e-0000-1000-8000-00805f9b34fb")), BluetoothCacheMode.Uncached);
if (rfcommServices.Services.Count > 0)
{
var service = rfcommServices.Services[0];
try
{
var socket = new StreamSocket();
await socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
}
catch (Exception ex)
{
}
}
}
}
Update #1
Package.appxmanifest
<Capabilities>
<Capability Name="internetClient"/>
<Capability Name="internetClientServer"/>
<Capability Name="privateNetworkClientServer"/>
<DeviceCapability Name="bluetooth"/>
<DeviceCapability Name="bluetooth.rfcomm">
<Device Id="any">
<Function Type="name:serialPort"/>
</Device>
</DeviceCapability>
</Capabilities>
Update #2
<DeviceCapability Name="bluetooth.rfcomm">
<Device Id="any">
<Function Type="serviceId:0000111e-0000-1000-8000-00805f9b34fb" />
</Device>
</DeviceCapability>
I tested this. The problem may appear in this line of code:
RfcommDeviceServicesResult rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(new Guid("0000111e-0000-1000-8000-00805f9b34fb")), BluetoothCacheMode.Uncached);
It is recommended to replace the Guid with:
RfcommDeviceServicesResult rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(
RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached);
I used a similar wireless headset device for testing. Before the replacement, I got an access denied error. After that, the connection can proceed normally.
Thanks.

Error while accessing AvailableFreeSpace/TotalSize in DriveInfo in UWP

I am able to list the local disks using DriveInfo.GetDrives() method. also, I access/get the Drive name using Name property. But I get error as "System. UnauthorizedAccess Exception: 'Access to the path 'X:\' is denied." while accessing any properties like AvailableFreeSpace. Code below.
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Debug.WriteLine("Drive: " + d.Name); //This line executes w/o error!
Debug.WriteLine("Drive: " + d.AvailableFreeSpace);
Debug.WriteLine("Drive: " + d.TotalSize);
}
NB: I have placed the following lines xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" in Package Tag Block and < rescap:Capability Name="broadFileSystemAccess"/ > inside the Capabilities Tag Block, in Package.appxmanifest file in my Project.
I am able to get total and available disk space for some of my drives using this code:
const String k_freeSpace = "System.FreeSpace";
const String k_totalSpace = "System.Capacity";
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
try
{
Debug.WriteLine("Drive: " + d.Name);
Debug.WriteLine("RootDir: " + d.RootDirectory.FullName);
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(d.RootDirectory.FullName);
var props = await folder.Properties.RetrievePropertiesAsync(new string[] { k_freeSpace, k_totalSpace });
Debug.WriteLine("FreeSpace: " + (UInt64)props[k_freeSpace]);
Debug.WriteLine("Capacity: " + (UInt64)props[k_totalSpace]);
}
catch (Exception ex)
{
Debug.WriteLine(String.Format("Couldn't get info for drive {0}. Does it have media in it?", d.Name));
}
}
I am targeting Windows 10, version 1803 (10.0: Build 17134) for both my "Min version" and "Target version".
Here are a couple of excerpts from my Package.appxmanifest
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
IgnorableNamespaces="uap mp iot rescap">
...
<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
</Package>

Add a firewall rule for Distributed Transaction Coordinator (msdtc.exe)

I tried to use firewallAPI.dll to add a rule. It works fine for calc.exe (or some other files) as described bellow but fails for msdtc.exe with the following exception:
System.IO.FileNotFoundException: 'The system cannot find the file
specified. (Exception from HRESULT: 0x80070002)'
Example:
static void Main(string[] args)
{
var manager = GetFirewallManager();
if (manager.LocalPolicy.CurrentProfile.FirewallEnabled)
{
var path = #"C:\Windows\System32\calc.exe";
//var path = #"C:\Windows\System32\msdtc.exe"; // System.IO.FileNotFoundException: 'The system cannot find the file specified.
AuthorizeApplication("Test", path, NET_FW_SCOPE_.NET_FW_SCOPE_ALL, NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY);
}
}
private const string CLSID_FIREWALL_MANAGER =
"{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private static NetFwTypeLib.INetFwMgr GetFirewallManager()
{
Type objectType = Type.GetTypeFromCLSID(
new Guid(CLSID_FIREWALL_MANAGER));
return Activator.CreateInstance(objectType)
as NetFwTypeLib.INetFwMgr;
}
private const string PROGID_AUTHORIZED_APPLICATION =
"HNetCfg.FwAuthorizedApplication";
public static bool AuthorizeApplication(string title, string applicationPath,
NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
{
// Create the type from prog id
Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);
INetFwAuthorizedApplication auth = Activator.CreateInstance(type)
as INetFwAuthorizedApplication;
auth.Name = title;
auth.ProcessImageFileName = applicationPath;
auth.Scope = scope;
auth.IpVersion = ipVersion;
auth.Enabled = true;
INetFwMgr manager = GetFirewallManager();
manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
return true;
}
Note: I checked the folder and see the file is located properly...
Could anybody help to add firewall rule for Distributed Transaction Coordinator? Maybe I should try to add another file to firewall (not msdtc.exe)?
Project > Properties > Build tab, untick the "Prefer 32-bit" checkbox. You don't prefer it, there is no 32-bit version of msdtc.exe.
Why the file system redirector caused the FileNotFoundException is explained well in this MSDN article.

Categories

Resources