I'm going to copy a file to this path(C:\Windows\Win32) in windows 7 using C# programming(the "Win32" Folder created by me) but I can't.Because the operation system don't allow me.so I need to full access . I write this code for solving the problem , but I see this error in the program running : " Attempted to perform an unauthorized operation."
. please help me !!! .thanks
using System.IO;
using System.Security.AccessControl;
using System.Management;
using System.Management.Instrumentation;
1. private void Sample2_Click(object sender, EventArgs e)
2. {
3. System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(#"C:\Windows\Win32");
4. FileSystemAccessRule fsar = new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow);
5. DirectorySecurity ds = null;
6. if (!di.Exists)
7. {
8. System.IO.Directory.CreateDirectory(#"C:\Windows\Win32");
9. }
10. ds = di.GetAccessControl();
11. ds.AddAccessRule(fsar);
12. di.SetAccessControl(ds);
13. File.Copy(#"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg", #"C:\Windows\Win32\Desert.jpg");
14. MessageBox.Show("successfully copy!!!!");
15. }
You will need to trigger UAC when starting your application.
Either embed this XML in your manifest-file
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges>
<requestedExecutionLevel
level="asInvoker"
uiAccess="false"/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
or you can make use of this sample code from MSDN or look here or even on SO. There is plenty of stuff.
Related
We are having problems with partial views after migrating to .net 5. The main page will optionally render a custom partial view to allow per-customer customizations. After migrating we are unable to render these partial views. the error message is:
InvalidOperationException: The partial view ~/Resources/Customer/Views/File.cshtml was not found. The following locations were searched: ~/Resources/Customer/Views/File.cshtml
We know the path is valid because if we rename the file the page renders (without customizations). If we debug in visual studio the page renders as expected but in a deployed IIS server it fails. We suspect there is a permissions issue but we have been unable to find it. So far we haven't been able to find anything in google searches or SO
Here is a snippet where we handle the custom file:
// load file path from config
string url = configuration.OrderPageSetting["OrderInfoViewRenderFile"];
bool exists = false;
// determine the path
if (!string.IsNullOrWhiteSpace(url))
{
string _url = url;
if (_url.StartsWith("~/")) _url = _url.Substring(2);
else if (_url.StartsWith("/")) _url = _url.Substring(1);
exists = System.IO.File.Exists(System.IO.Path.Combine(Resource.SystemDirectory, _url));
}
// test for and render custom view
if (exists)
{
var data = new ViewDataDictionary<object>(new EmptyModelMetadataProvider(), new ModelStateDictionary());
data.Add("Order", order);
data.Add("Config", configuration);
await Html.RenderPartialAsync(url, data);
}
else
{
... default rendering ...
}
The application is hosted in a virtual directory with a dedicated application pool. This problem occurs without a web.config at the site level. On the same server, the prior .net framework version of the application works correctly.
here is the applications web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\myapp.dll" stdoutLogEnabled="false" hostingModel="InProcess" stdoutLogFile=".\logs\stdout">
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
A co-worker found the solution the problem, the clue was in https://weblog.west-wind.com/posts/2019/Sep/30/Serving-ASPNET-Core-Web-Content-from-External-Folders
There were 2 changes required:
Add package: Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
called extension to support runtime complication on the controllers/views:
services.AddControllersWithViews().AddRazorRuntimeCompilation(opt =>
{
opt.FileProviders.Add(
new PhysicalFileProvider(System.IO.Path.Combine(Environment.ContentRootPath, ""))
);
})
if you want to change where the dynamic compilation is supported, simply change the "" to the path where it is permitted.
The following code is defined in the test class. But i want to use DataSource("DataSourceSettingName") and app.config define.
<DeploymentItem("DataSets\\TestUserMainInput.csv")>
<DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\DataSets\\TestUserMainInput.csv", "TestUserMainInput#csv", DataAccessMethod.Sequential)>
Environment:
Visual Studio 2017
Microsoft.VisualStudio.TestTools.UnitTesting
.NET Framework 4.6.1
I already tried the following code. It failed.
<configSections>
<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<connectionStrings>
<add name="MyExcelConn" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DataSets\TestUserMainInput.csv;Extended Properties='text;HDR=Yes;FMT=Delimited'" providerName="System.Data.OleDb" />
</connectionStrings>
<microsoft.visualstudio.testtools>
<dataSources>
<add name="MainDataSource" connectionString="MyExcelConn" dataTableName="TestUserMainInput#csv" dataAccessMethod="Sequential"/>
</dataSources>
</microsoft.visualstudio.testtools>
Output --> Tests
Error Message
An exception occurred while calling the 'executor: // mstestadapter / v2' player: 'Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.MSTestSettings, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter, Version = 14.0.0.0, Culture = neutral, PublicKeyToken The species could not be resolved for = b03f5f7f11d50a3a '.
Could anyone help me solve this?
There is no need to change the app.config
Just Create a new test project and add a class like this one.
The test iterates for all the csv rows. You need to place the csv in your solution and change it to copy local always.
[TestClass]
public class UnitTest1
{
public TestContext TestContext { get; set; }
private static TestContext _testContext;
[ClassInitialize]
public static void SetupTests(TestContext testContext)
{
_testContext = testContext;
}
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\DataSource\\teste.csv", "teste#csv", DataAccessMethod.Sequential), DeploymentItem("DataSource\\teste.csv"), TestMethod]
public void Testing()
{
Assert.AreEqual(TestContext.DataRow["user"], "myusername");
}
}
I found the answer in following thread:
https://dondeetan.com/2017/07/03/referencing-mstest-and-mstestv2-unit-testing-framework-through-namespace-aliasing/
MSTest (Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll) and MSTestV2 (Microsoft.VisualStudio.TestPlatform.TestFramework.dll) those assemblies have the exact same namespace.
The Issue: Reference both MSTest and MSTestV2 in the same test project using the C# but that there's no VB way of doing this.
I want to access files (images, text files etc.) from an USB stick on my Raspberry Pi 2 using Windows 10 IoT Core.
So I've added the to the appxmanifest file.
When using this code in my IBackgroundTask I get an access denied error in the second line:
public sealed class StartupTask : IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
//...
Windows.Storage.StorageFolder sf = Windows.Storage.KnownFolders.RemovableDevices;
//get list of drives
IReadOnlyList<Windows.Storage.StorageFolder> list = await sf.GetFoldersAsync();
...
}
}
I found that I should add the fileTypeAssociation with the file types I'd like to access in Package.appxmanifest so I did that:
<?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:iot="http://schemas.microsoft.com/appx/manifest/iot/windows10" IgnorableNamespaces="uap mp iot">
<Identity Name="test-uwp" Publisher="CN=user" Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="8f31dff8-3a2b-4df1-90bb-2c5267f32980" PhonePublisherId="00000000-0000-0000-0000-000000000000" />
<Properties>
<DisplayName>test</DisplayName>
<PublisherDisplayName>user</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">
<uap:VisualElements DisplayName="test" Square150x150Logo="Assets\Square150x150Logo.png" Square44x44Logo="Assets\Square44x44Logo.png" Description="test" BackgroundColor="transparent" AppListEntry="none">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png">
</uap:DefaultTile>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="test.StartupTask">
<BackgroundTasks>
<iot:Task Type="startup" />
</BackgroundTasks>
</Extension>
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name="myimages">
<uap:SupportedFileTypes>
<uap:FileType ContentType="image/jpeg">.jpg</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
<uap:Capability Name="removableStorage" />
</Capabilities>
</Package>
If I want to deploy that, I get the following error:
Severity Code Description Project File Line Suppression State
Error Error : DEP0700 : Registration of the app failed.
AppxManifest.xml(37,10): error 0x80070490: Cannot register the
test-uwp_1.0.0.0_arm__yzekw4x8qxe1g package because the following
error was encountered while parsing the windows.fileTypeAssociation
Extension element: Element not found. . Try again and contact the
package publisher if the problem persists. (0x80073cf6)
As soon as I remove the uap:Extension element, the error goes away (but the access denied is still there).
Did I miss anything? Is it not possible to access files from an USB stick using a background service (I want to run that headless with no user interaction)?
At the moment you can't register a headless app that uses filetypeAssociation.
There is a workaround - see here: https://github.com/ms-iot/ntvsiot/issues/62
Simply add a headed app (project) to your solution (no need for any special code there).
Add a reference to this project in your headless app.
Now change the manifest of the headless (file asso..) and add Executable: YourHeadedApp.exe and EntryPoint: YourHeadedApp.App now with the next deploy the EXE will be included in deployment - so it can be found when the manifest is checked.
I have a small set of ServiceStack REST services that is using NLog 2.1 (from NuGet) for logging.
My test server is running:
Windows 7
IIS 7.5
.NET 4.5
NLog config:
<nlog throwExceptions="true" internalLogToConsole="true" internalLogLevel="Debug" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="c" xsi:type="Console" />
<target name="f1" xsi:type="File" fileName="C:\logs\test.log" />
</targets>
<rules>
<logger name="*" writeTo="c,f1" />
</rules>
</nlog>
My NLog config is exceedingly simple... just trying to get it working...
and in this configuration, everything works fine. NLog creates the log files correctly.
On my DEVELOPMENT machine, I am using:
Windows 7
Xamarin Studio / XSP4
Mono 3.2.3
Here is my Application_Start...
protected void Application_Start() {
LogManager.LogFactory = new NLogFactory();
ILog log = LogManager.GetLogger(typeof(Global));
log.Info("Application_Start called");
try {
new AppHost().Init();
} catch (Exception e) {
log.Error("Exception caught initializing AppHost");
}
}
In this configuration, my service's AppHost().Init() throws an exception as ServiceStack is registering my services in ServiceController.cs. I believe that part is irrelevant except that it is the first time something is logged outside of Application_Start (because both of the calls in Application_Start work... the log.info before the exception and the log.error after the exception).
Here is the exception that is shown:
The most relevant bit is that there was a System.NotImplementedException thrown at NLog.Internal.FileAppenders.BaseFileAppender.WindowsCreateFile (System.String fileName, Boolean allowConcurrentWrite).
I have found a workaround (in the accepted answer below). Hopefully anyone else who runs into this will quickly come upon this solution.
Some digging around on Google led me to this NLog pull request:
Avoid Win32-specific file functions in Mono where parts not implemented.
It appears that this change tries to use the preprocessor to NOT call WindowsCreateFile at all. However, for some reason, this still executes.
So I then went to check the newest version of BaseFileAppender.cs in the NLog GitHub repository to make sure someone didn't at some later point break this again.
#if !NET_CF && !SILVERLIGHT && !MONO
try
{
if (!this.CreateFileParameters.ForceManaged && PlatformDetector.IsDesktopWin32)
{
return this.WindowsCreateFile(this.FileName, allowConcurrentWrite);
}
}
catch (SecurityException)
{
InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream");
}
#endif
Hmmm... it's still there. What gives? Why doesn't MONO seem to be defined by the preprocessor, thus allowing this block to execute? I'm not sure. Before I started down that path of investigation, I noticed another change...
if (!this.CreateFileParameters.ForceManaged && ...
So after following that tracing that ForceManaged boolean back to it's origin, it appeared that I could set forceManaged="true" on my FileTarget declaration in my NLog config. Could it really be that simple?!
<nlog throwExceptions="true" internalLogToConsole="true" internalLogLevel="Debug" xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="c" xsi:type="Console" />
<target name="f1" xsi:type="File" forceManaged="true" fileName="C:\logs\test.log" />
</targets>
<rules>
<logger name="*" writeTo="c,f1" />
</rules>
</nlog>
Once that change was made, everything worked... the call to WindowsCreateFile that was throwing the exception was skipped & a managed filestream was used instead, which works great. Hallelujah!
Lastly, I could not find that forceManaged flag in the NLog documentation anywhere. Would likely have found this solution sooner if it was.
I'm trying to use Entity Framework Tracing Provider to log the SQL staments generated.
I changed my context class to something like this:
public partial class MyDBContext: DbContext
{
public MyDBContext(string nameOrConnectionString)
: base(EFTracingProviderUtils.CreateTracedEntityConnection(nameOrConnectionString), true)
{
// enable sql tracing
((IObjectContextAdapter) this).ObjectContext.EnableTracing();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
//DbSets definition....
}
But this doesn't log the SQL statements on the Output window...
Should I had something more in the class or in web.config file? (I'm working on a ASP.NET MVC 4 project)
I using the solution in the following post:Entity Framework 4.1 - EFTracingProvider
but I made some changes that I don't know if they are important:
The class is partial instead of abstract, and the constructor is public instead of protected...
What am I missing?
After modifying your code, you need to enable tracing in your web.config like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.diagnostics>
<sources>
<source name="EntityFramework.NorthwindEntities" switchValue="All" />
</sources>
</system.diagnostics>
</configuration>
The name of your TraceSource should be your context name prefixed with 'EntityFramework'.
Make sure that you disable tracing when you deploy your application to production by setting the switchValue to Off.