I'm developing a windows form application that has different features, one of these features is that the user has the ability to generate a receipt file in a pdf format.
The Problem I'm facing now is that when I run the application from visual studio this feature works perfectly, but when I publish and run the application in my pc and in other pcs the following error pops-up:
System.IO.DirectoryNotFoundException: C:\Users\USERNAME\AppData\Local\Apps\2.0\B8GVHPQK.4RG\XND3YQM7.9AB\hsar..tion_5a44077fdab68dde_0002.0000_e0623e33977d687d\TempReceipts
at System.Security.AccessControl.NativeObjectSecurity.CreateInternal(ResourceType resourceType, Boolean isContainer, String name, SafeHandle handle, AccessControlSections includeSections, Boolean createByName, ExceptionFromErrorCode exceptionFromErrorCode, Object exceptionContext)
at System.Security.AccessControl.FileSystemSecurity..ctor(Boolean isContainer, String name, AccessControlSections includeSections, Boolean isDirectory)
at System.Security.AccessControl.DirectorySecurity..ctor(String name, AccessControlSections includeSections)
at System.IO.DirectoryInfo.GetAccessControl()
The error tells that the directory, where the receipts are stored, is can't be found, while in visual studio the there is no such error.
I've read a little about and some said that this is occurred because of permissions restrictions, I've tried to use the following code to grant the WRITE permissions in the targeted directory, but still facing the same error:
AddDirectorySecurity("TempReceipts", #"Resources\\TempReceipts", FileSystemRights.WriteData, AccessControlType.Allow);
Here is the method:
public static void AddDirectorySecurity(string FileName, string Account, FileSystemRights Rights, AccessControlType ControlType)
{
// Create a new DirectoryInfo object.
DirectoryInfo dInfo = new DirectoryInfo(FileName);
// Get a DirectorySecurity object that represents the
// current security settings.
DirectorySecurity dSecurity = dInfo.GetAccessControl();
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, Rights, ControlType));
// Set the new access settings.
dInfo.SetAccessControl(dSecurity);
}
so could anyone please suggest a solution for this problem?
Related
OS: Mac M1
Framework: .Net 6.0
IDE: Rider
NuGet packages:
Microsoft.ClearScript (v7.2.1)
Microsoft.ClearScript.V8 (v7.2.1)
My simple JavaScript REPL:
using Microsoft.ClearScript.V8;
using myConsole = System.Console;
var v8 = new V8ScriptEngine();
v8.AddHostType("myConsole", typeof(Console));
// JavaScript REPL
while (true)
{
myConsole.WriteLine("> ");
var expression = myConsole.ReadLine();
if(string.IsNullOrEmpty(expression)) continue;
if(expression.Equals("exit", StringComparison.InvariantCultureIgnoreCase)) Environment.Exit(0);
try
{
_ = v8.Evaluate(expression);
}
catch (Exception ex)
{
myConsole.WriteLine(ex.Message);
}
}
I can build it without any problems. But if I run my code I get the error. I see it can't find file ClearScriptV8.osx-arm64.dylib:
/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/ConsoleApp1
Unhandled exception. System.TypeLoadException: Cannot load ClearScript V8 library. Load failure information for ClearScriptV8.osx-arm64.dylib:
/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/runtimes/osx-arm64/native/ClearScriptV8.osx-arm64.dylib: Unable to load shared library '/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/runtimes/osx-arm64/native/ClearScriptV8.osx-arm64.dylib' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/runtimes/osx-arm64/native/ClearScriptV8.osx-arm64.dylib, 0x0001): tried: '/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/runtimes/osx-arm64/native/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/local/lib/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/lib/ClearScriptV8.osx-arm64.dylib' (no such file)
/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/ClearScriptV8.osx-arm64.dylib: Unable to load shared library '/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/ClearScriptV8.osx-arm64.dylib' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/ClearScriptV8.osx-arm64.dylib, 0x0001): tried: '/Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/bin/Debug/net6.0/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/local/lib/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/lib/ClearScriptV8.osx-arm64.dylib' (no such file)
/System/ClearScriptV8.osx-arm64.dylib: Unable to load shared library '/System/ClearScriptV8.osx-arm64.dylib' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(/System/ClearScriptV8.osx-arm64.dylib, 0x0001): tried: '/System/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/local/lib/ClearScriptV8.osx-arm64.dylib' (no such file), '/usr/lib/ClearScriptV8.osx-arm64.dylib' (no such file)
at Microsoft.ClearScript.V8.V8Proxy.LoadNativeLibrary(String baseName, String platform, String architecture, String extension)
at Microsoft.ClearScript.V8.V8Proxy.LoadNativeAssembly()
at Microsoft.ClearScript.V8.V8Proxy.OnEntityHolderCreated()
at Microsoft.ClearScript.V8.SplitProxy.V8EntityHolder..ctor(String name, Func`1 acquireHandle)
at Microsoft.ClearScript.V8.SplitProxy.V8IsolateProxyImpl..ctor(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8IsolateProxy.Create(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8Runtime..ctor(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8Runtime..ctor(String name, V8RuntimeConstraints constraints, V8RuntimeFlags flags)
at Microsoft.ClearScript.V8.V8Runtime..ctor(String name, V8RuntimeConstraints constraints)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(V8Runtime runtime, String name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(String name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, Int32 debugPort)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(String name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor(String name, V8RuntimeConstraints constraints)
at Microsoft.ClearScript.V8.V8ScriptEngine..ctor()
at Program.<Main>$(String[] args) in /Users/andrey/RiderProjects/ConsoleApp1/ConsoleApp1/Program.cs:line 4
Process finished with exit code 134.
Is it possible to use ClearScript on Mac M1? If "yes" then how can I fix the problem?
The problem solved. A solution was provided in the following GitHub issue: here.
The solution is to use the Microsoft.ClearScript.osx-arm64 package.
I have an application that creates new event sources in an event log on a 2016 Windows Server v1607. It is not known which names the sources will have. To archive this the account needs read access to all the event sources to assure the source name does not already exist (why double source names in different logs are not allowed is another interesting question). By default a local account is blocked from reading the Security event log, so the creation of a new source ends up with an error that there is no read access to the Security log.
The most promising approach seemed to be the answer to this question: https://stackoverflow.com/a/3138269/2091030
I followed the steps 1-5 changing the registry permissions of HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security by adding read permissions for the local account. I checked all the sub-keys in the Security folder and they all show proper read access for the account. Nevertheless I get another error now when using a simple C# program to add an event with a new source:
using System;
using System.Diagnostics;
namespace EventlogTest {
public class Test {
public static void Main() {
var log = new EventLog("SomeLog", ".", "SomeNewSource");
log.WriteEntry("Test 123", EventLogEntryType.Information);
}
}
}
System.Security.SecurityException: Der angeforderte Registrierungszugriff ist unzulässig.
bei System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
bei Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
bei System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData)
bei System.Diagnostics.EventLogInternal.VerifyAndCreateSource(String sourceName, String currentMachineName)
bei System.Diagnostics.EventLogInternal.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData)
bei System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type)
bei EventlogTest.Test.Main()
Did I miss something?
The following settings for the local account allowed me to add new sources in my event-log "MyLog":
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog:
Add your local account with the following rights: Query Value, Set Value, Create Subkey, Enumerate Subkey
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security:
This folder does not inherit rights from it's parent. Add the local account with normal read access.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\MyLog:
Deactivate inheritance and copy values, then add your local account with full access
In my .NET client application I use the default settings provider with Scope=User and Roaming=True. This works fine in most environments, no matter if client or Terminal Server, except for a customer with a Citrix Terminal Server farm. Whenever Properties. Settings.Default.Save() is called, the following exception is thrown:
System.UnauthorizedAccessException: Attempted to perform an unauthorized operation.
at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.FileSystemSecurity.Persist(String fullPath)
at System.Configuration.Internal.WriteFileContext.DuplicateTemplateAttributes (String source, String destination)
at System.Configuration.Internal.WriteFileContext.DuplicateFileAttributes(String source, String destination)
at System.Configuration.Internal.WriteFileContext.Complete(String filename, Boolean success)
at System.Configuration.Internal.InternalConfigHost.StaticWriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
at System.Configuration.Internal.DelegatingConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
at System.Configuration.ClientSettingsStore.ClientSettingsConfigurationHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
at System.Configuration.UpdateConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)
at System.Configuration.ClientSettingsStore.WriteSettings(String sectionName, Boolean isRoaming, IDictionary newSettings)
at System.Configuration.LocalFileSettingsProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values)
at System.Configuration.SettingsBase.SaveCore()
at System.Configuration.SettingsBase.Save()
The reason for this exception:
System.Configuration.Internal.WriteFileContext writes a new copy (...newcfg) of the user settings in the user's roaming profile. Then, DuplicateTemplateAttributes tries to modify the ACLs of this file and explicitly set the ownership to the current user.
In the case of this customer this fails because the roaming profile is stored on a file share and the users have only Read and Change permissions, but not Full Control. They probably have Full Control in NTFS (because by default you are "Owner" of all files you create, and as the owner, you can do anything with the file no matter if you have "Full Control" explicitly set), but it seems like its blocked on the SMB share level.
This behavior doesn't make any sense to me: Given that the LocalFileSystemProvider always uses a private profile folder of the current user (local or roaming), we can safely assume that the user is the owner anyway.
Since WriteFileContext catches the exception, deletes the temporary .newcfg file and then rethrows, there is no way to simply catch the exception in my code and rename the file or somehow grab its content since it is already deleted when the exception is thrown.
I couldn't find any simple way to work around this issue except for implementing my own settings provider. For this, it seems like I even would have to rebuild things like the serialization part since all the System.Configuration stuff used for this is internal. And of course I don't want to break the currently used settings, so it looks like a ridiculous amount of code just to rebuild everything as it is with just "one line commented out" (setting the owner of the file).
Any ideas what else I could try?
There is no way the customer changes anything in its file share permissions...
I have experienced a similar issue on Citrix - AppData is redirected to a "Change & Read" network share (not "Full Control" - it works on "Full Control"). On first run, our application will create the user.config on the first Save() call but throws UnauthorizedAccessException on any subsequent Save() calls.
The answer appears to be to delete the user.config file if it exists before calling Save().
We are currently testing this with our client - I will update my answer when I have concrete results.
Update: You need to "touch" each setting in Settings.Default before calling Save() as the temp file is actually merged with existing user.config. By calling the following method before calling Save(), the user.config is correctly recreated each time (no UnauthorizedAccessException thrown).
public static void ClearUserConfigFile()
{
//Touch each setting
foreach (SettingsProperty property in Settings.Default.Properties)
{
if (property.DefaultValue != Settings.Default[property.Name])
Settings.Default[property.Name] = Settings.Default[property.Name];
}
//Delete the user.config file
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
var userConfigPath = config.FilePath;
try
{
if (File.Exists(userConfigPath) == true)
File.Delete(userConfigPath);
}
catch (Exception ex)
{
_log.ErrorFormat("Exception thrown while deleting user.config : {0}", ex.ToString());
}
}
I'm using the code below to change the owner of a file. This code runs in a Windows Service written in C#, version 4.0. It's running on a local server, running Windows Server 2008 R2 Standard, Service Pack 1.
I need to change the owner of a file that is received via FTP to a domain account. I can log into the box and do it manually using Explorer, but when I try and run this via code, I get an InvalidOperation exception. I can change the owner to the Local System account, but not a network account. Any help on this would be greatly appreciated.
I'm working with some bizarre Microsoft Dynamics AX code that handles EDI files. The process requires the owner of the file be a valid DAX user, in this case a Domain User. We have Vendors that send us EDI data via FTP. Our DAX application checks the FTP directory every 10 minutes and processes the files. The process currently fails, because the owner is invalid. So, I've written a service to change the owner of the file when it arrives. However, the code below fails with the exception show below the code example.
var ediFileOwner = new NTAccount("MyDomain", _ediEndpointUserAccount);
var fileSecurity = File.GetAccessControl(fileName);
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
fileSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, AccessControlType.Allow));
fileSecurity.AddAccessRule(new FileSystemAccessRule(ediFileOwner, FileSystemRights.TakeOwnership, AccessControlType.Allow));
fileSecurity.SetOwner(ediFileOwner); //Change our owner from to our desired User
File.SetAccessControl(fileName, fileSecurity);
Here is the full Exception:
System.InvalidOperationException: The security identifier is not allowed to be the owner of this object.
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections)
at System.Security.AccessControl.FileSystemSecurity.Persist(String fullPath)
at System.IO.File.SetAccessControl(String path, FileSecurity fileSecurity)
UPDATE
If I change the account the service run under to the account I'm trying to change to owner to, I get a different exception.
Unexpected Exception: System.UnauthorizedAccessException: Attempted to
perform an unauthorized operation. at
System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type,
String name, SafeHandle handle, SecurityInfos securityInformation,
SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl,
GenericAcl dacl)
I ended up using some code I found here, http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User
I had to jump through a few hoops in order to get everything done, but it worked. In order to avoid the errors I was getting, I had to use the Impersonate stuff I found in addition to switching between users throughout.
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
// ...
//Copy the file. This allows our service account to take ownership of the copied file
var tempFileName = Path.Combine(Path.GetDirectoryName(file.FileName), "TEMP_" + file.FileNameOnly);
File.Copy(file.FileName, tempFileName);
var windowID = WindowsIdentity.GetCurrent();
var currUserName = windowID.User.Translate(typeof(NTAccount)).Value;
var splitChar = new[] { '\\' };
//var name = currUserName.Split(splitChar)[1];
//var domain = currUserName.Split(splitChar)[0];
var ediFileOwner = new NTAccount("TricorBraun", _radleyEDIEndpointUserAccount);
//We have to give Access to the service account to delete the original file
var fileSecurity = File.GetAccessControl(file.FileName);
var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
fileSecurity.AddAccessRule(new FileSystemAccessRule(everyone, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(file.FileName, fileSecurity);
File.Delete(file.FileName);
//We rename our file to get our original file name back
File.Move(tempFileName, file.FileName);
//The following give our desired user permissions to take Ownership of the file.
//We have to do this while running under the service account.
fileSecurity = File.GetAccessControl(file.FileName);
var aosSID = (SecurityIdentifier) ediFileOwner.Translate(typeof(SecurityIdentifier));
fileSecurity.AddAccessRule(new FileSystemAccessRule(aosSID, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(file.FileName, fileSecurity);
//Now we user the Impersonator (http://www.codeproject.com/Articles/10090/A-small-C-Class-for-impersonating-a-User)
//This allows us to manage the file as the Account we wish to change ownership to.
//It makes itself the owner.
using (new Impersonator(_radleyEDIEndpointUserAccount, "MyDomain", "password")) {
_logger.Debug(string.Format("Attempting changing owner to Tricorbraun\\{0}", _radleyEDIEndpointUserAccount));
fileSecurity = File.GetAccessControl(file.FileName);
fileSecurity.SetOwner(ediFileOwner); //Change our owner from LocalAdmin to our chosen DAX User
_logger.Debug(string.Format("Setting owner to Tricorbraun - {0}", _radleyEDIEndpointUserAccount));
File.SetAccessControl(file.FileName, fileSecurity);
}
I need to impersonate the my code to run with a different windows user id, right now i am using some code which i got from web which is calling some native libraries.
the purpose of the code is to change the permissions on a file server user directories permissions.
I can change my folder permissions, but i have the credentials of the other user to go and change the permissions on his folder. But i am running the code on my machine by impersonating him.
But, i am getting un authorized exception.
the code i am using is:
[DllImport("advapi32.dll", SetLastError = true)]
private static extern int LogonUser(
string lpszUserName,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
I am not sure this is working in Windows 7 or not. Is there any one who faced any issue like this..?
Exception i am getting:
Messagee:"{"Attempted to perform an unauthorized operation."}"
stack trace:
at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections)
at System.Security.AccessControl.FileSystemSecurity.Persist(String fullPath)
at System.IO.Directory.SetAccessControl(String path, DirectorySecurity directorySecurity)
at FolderAccessManager.Program.Main(String[] args) in
Could you please share some solutions..?
Have a look at WindowsIdentity.Impersonate. There you'll see an example of how to go about.
Are you using a domain joined machine with ASP.NET?
I got the exact same message tring this code in a asp.net application when running with the default apppool identity. Changing the apppool user to a domain user with 'domain admin' permissions solved this problem (also Windows 7).