Accessviolationexception attempted to read or write protected memory - c#

I create one Windows Form App on my friends machine. It works fine on his machine. But when I tried to run same App on my own machine then from _dialog.ShowDialog() line an exception thrown like "accessviolationexception attempted to read or write protected memory. this is often an indication that other memory is corrupt...". I check for this error on net and I found following solutions:
1) Tools menu ->Options -> Debugging -> General -> Uncheck this option "Suppress JIT optimization on module load" link : http://social.msdn.microsoft.com/Forums/en-US/8789ea67-fbc5-4a7b-a4eb-d4a8a050d5c1/attempt-to-read-or-write-protected-memory-this-is-often-an-indicating-that-other-memory-is-corrupt. Done on my machine but wasnt work.
2) Attempted to read or write protected memory, Install http://support.microsoft.com/kb/971030 for framework 2.0,..3.5, but I dont find any of download product from mention link.
My machine configuration: VS 2010(SP1), Framework used 4.0, DB used MS-Access.
Block of code:
private void SetAttachmentInfo()
{
Dictionary<string, object> _fileInfo = new Dictionary<string, object>();
OpenFileDialog _dialog = new OpenFileDialog();
var _fileName = (object)(null);
var _fileData = (object)(null);
var _fileDataLength = (object)(null);
_dialog.Multiselect = false;
_dialog.Filter = "Office Files (*.doc;*.xls;*.ppt;*pdf;*txt) |*.doc;*xlsx;*.xls*.ppt;*pdf;*.txt;|Image Files (*.jpeg;*.png;*.jpg;*.gif) |*.jpeg;*.png;*.jpg;*.gif |All File|*.*";
if (_dialog.ShowDialog() != DialogResult.Cancel)
{
_fileInfo = GetAttachmentFileInformation(_dialog.FileName);
_fileInfo.TryGetValue("FileName", out _fileName);
_fileInfo.TryGetValue("FileData", out _fileData);
_fileInfo.TryGetValue("Lenght", out _fileDataLength);
FileName = Convert.ToString(_fileName);
FileData = (_fileData != null && (_fileDataLength as int?) > 0) ? (byte[])_fileData : (byte[])null;
AttachmentLength = _fileDataLength as int?;
}
}
Any useful help?

Turning off the DEP settings may solve your problem. Turn off DEP via an elevated Command Prompt by clicking the Windows (Start) > All Programs > Accessories and right-click Command Prompt, then ‘Run as Administrator’. Type bcdedit.exe /set {current} nx AlwaysOff (note the four spaces) and press Enter. To turn it back on, change AlwaysOff to AlwaysOn. You need to restart the system after the changes have been made.

Related

UWP application use "CustomDevice.FromIdAsync" access KMDF driver is denied

I found a similar question, but it probably didn't help me much.
I'm learning to access drive devices via UWP, in the first two days, the program was working fine, but today, UWP error close when open device, the error message is "Access is denied. Exception from HRESULT: 0x80070005"
I don't know if something was modified during the update process that caused this problem. I only have a snapshot of the virtual machine that can open the drive device. On this snapshot, when I update the UWP application, I can also open the drive device, but after update the driver, the UWP application can no longer open the driver device.
Does this mean the problem is with the driver?
After that, I created a new KMDF project and a UWP project, only printed some information, and the same error occurred after installing to the virtual machine.
It is worth noting that when I saw the UWP access to the drive device in DbgView, the EvtDeviceFileCreate event callback was triggered, but the EvtDeviceClose event callback was triggered immediately, I think, there should be no problem with the device interface.
Also, in the beginning, I used the device manager to "Add legacy hardware" to load the driver, then I tried to install the driver using devcon, both can install the driver, but it seems to be slightly different, I am not sure if this also It will have an impact, although both installation methods currently do not solve the problem I am encountering.
Below are some settings for UWP app and drivers.
Register device interface and add custom capability:
In this part, I refer to Microsoft's official sample kmdf_fx2.
WDFSTRING symbolicLinkString = NULL;
UNICODE_STRING symbolicLinkName = SymbolicName;
DEVPROP_BOOLEAN isRestricted;
status = WdfDeviceCreateDeviceInterface(
hDevice,
(LPGUID)&GUID_INTERFACE_HSADRVSAMPLE1,
NULL); // Reference String
if (!NT_SUCCESS(status)) {
KdPrint(("WdfDeviceCreateDeviceInterface Fail\n"));
goto Error;
}
if (g_pIoSetDeviceInterfacePropertyData != NULL) {
status = WdfStringCreate(NULL,
WDF_NO_OBJECT_ATTRIBUTES,
&symbolicLinkString);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfStringCreate Fail\n"));
goto Error;
}
status = WdfDeviceRetrieveDeviceInterfaceString(
hDevice,
(LPGUID)&GUID_INTERFACE_HSADRVSAMPLE1,
NULL,
symbolicLinkString);
if (!NT_SUCCESS(status)) {
KdPrint(("WdfDeviceRetrieveDeviceInterfaceString Fail\n"));
goto Error;
}
WdfStringGetUnicodeString(symbolicLinkString, &symbolicLinkName);
isRestricted = DEVPROP_TRUE;
status = g_pIoSetDeviceInterfacePropertyData(
&symbolicLinkName,
&DEVPKEY_DeviceInterface_Restricted,
0,
0,
DEVPROP_TYPE_BOOLEAN,
sizeof(isRestricted),
&isRestricted);
if (!NT_SUCCESS(status)) {
KdPrint(("g_pIoSetDeviceInterfacePropertyData Fail\n"));
goto Error;
}
#if defined(NTDDI_WIN10_RS2) && (NTDDI_VERSION >= NTDDI_WIN10_RS2)
static const wchar_t customCapabilities[] = L"ColinTest.HSADrvSample_2022051717171\0";
status = g_pIoSetDeviceInterfacePropertyData(
&symbolicLinkName,
&DEVPKEY_DeviceInterface_UnrestrictedAppCapabilities,
0,
0,
DEVPROP_TYPE_STRING_LIST,
sizeof(customCapabilities),
(PVOID)&customCapabilities);
if (!NT_SUCCESS(status)) {
KdPrint(("g_pIoSetDeviceInterfacePropertyData Fail\n"));
goto Error;
}
#endif
WdfObjectDelete(symbolicLinkString);
}
Error:
if (symbolicLinkString != NULL) {
WdfObjectDelete(symbolicLinkString);
}
Driver INF:
;
; HSADrvSample1.inf
;
[Version]
Signature="$WINDOWS NT$"
Class=Test ; TODO: edit Class
ClassGuid={160303BD-D84C-4819-B962-9B1BDBB52310} ; TODO: edit ClassGuid
Provider=%ManufacturerName%
CatalogFile=HSADrvSample1.cat
DriverVer = 05/19/2022,9.21.50.151
PnpLockDown=1
[DestinationDirs]
DefaultDestDir = 12
HSADrvSample1_Device_CoInstaller_CopyFiles = 11
; ================= Class section =====================
[ClassInstall32]
Addreg=SampleClassReg
[SampleClassReg]
HKR,,,0,%ClassName%
HKR,,Icon,,-5
[SourceDisksNames]
1 = %DiskName%,,,""
[SourceDisksFiles]
HSADrvSample1.sys = 1,,
WdfCoInstaller01011.dll=1 ; make sure the number matches with SourceDisksNames
;*****************************************
; Install Section
;*****************************************
[Manufacturer]
%ManufacturerName%=Standard,NTamd64
[Standard.NTamd64]
%HSADrvSample1.DeviceDesc%=HSADrvSample1_Device, Root\HSADrvSample1 ; TODO: edit hw-id
[HSADrvSample1_Device.NT]
CopyFiles=Drivers_Dir
[Drivers_Dir]
HSADrvSample1.sys
;-------------- Service installation
[HSADrvSample1_Device.NT.Services]
AddService = HSADrvSample1,%SPSVCINST_ASSOCSERVICE%, HSADrvSample1_Service_Inst
; -------------- HSADrvSample1 driver install sections
[HSADrvSample1_Service_Inst]
DisplayName = %HSADrvSample1.SVCDESC%
ServiceType = 1 ; SERVICE_KERNEL_DRIVER
StartType = 3 ; SERVICE_DEMAND_START
ErrorControl = 1 ; SERVICE_ERROR_NORMAL
ServiceBinary = %12%\HSADrvSample1.sys
;
;--- HSADrvSample1_Device Coinstaller installation ------
;
[HSADrvSample1_Device.NT.CoInstallers]
AddReg=HSADrvSample1_Device_CoInstaller_AddReg
CopyFiles=HSADrvSample1_Device_CoInstaller_CopyFiles
[HSADrvSample1_Device_CoInstaller_AddReg]
HKR,,CoInstallers32,0x00010000, "WdfCoInstaller01011.dll,WdfCoInstaller"
[HSADrvSample1_Device_CoInstaller_CopyFiles]
WdfCoInstaller01011.dll
[HSADrvSample1_Device.NT.Wdf]
KmdfService = HSADrvSample1, HSADrvSample1_wdfsect
[HSADrvSample1_wdfsect]
KmdfLibraryVersion = 1.11
[Strings]
SPSVCINST_ASSOCSERVICE= 0x00000002
ManufacturerName="Colin" ;TODO: Replace with your manufacturer name
ClassName="Test" ; TODO: edit ClassName
DiskName = "HSADrvSample1 Installation Disk"
HSADrvSample1.DeviceDesc = "HSADrvSample1 Device"
HSADrvSample1.SVCDESC = "HSADrvSample1 Service"
SCCD File:
The file is configured as per the official documentationHardware Support App (HSA): Steps for App Developers, the file is already set to content.
<?xml version="1.0" encoding="utf-8"?>
<CustomCapabilityDescriptor xmlns="http://schemas.microsoft.com/appx/2018/sccd" xmlns:s="http://schemas.microsoft.com/appx/2018/sccd">
<CustomCapabilities>
<CustomCapability Name="ColinTest.HSADrvSample_2022051717171"></CustomCapability>
<AuthorizedEntities>
<AuthorizedEntity AppPackageFamilyName="Colin.HSA.APP_4a8dxf1xdwf12" CertificateSignatureHash="2d6e4f1418bc13447bb8c10067d0af418cb8a2f9e14c014e03a1e0ec811735af"></AuthorizedEntity>
</AuthorizedEntities>
<Catalog>FFFF</Catalog>
</CustomCapabilityDescriptor>
Part of Package.appxmanifest:
<Capabilities>
<Capability Name="internetClient" />
<uap4:CustomCapability Name="ColinTest.HSADrvSample_2022051717171"/>
</Capabilities>
Part of UWP Code:
string selector = CustomDevice.GetDeviceSelector(DeviceInterfaceGuid);
DeviceInformationCollection enumDevice = await DeviceInformation.FindAllAsync(selector);
string DeviceID = enumDevice[0].Id;
try
{
CustomDevice Device = await CustomDevice.FromIdAsync(DeviceID, DeviceAccessMode.ReadWrite, DeviceSharingMode.Shared);
if (null != Device)
{
Note.Text = "Open successfully";
}
}
catch (Exception ex)
{
Note.Text = "Failed to open!" + ex.Message;
}
I would like to know at which step am I getting the error? How to solve?
At the suggestion of #Nico Zhu - MSFT, I checked the CustomCapabilityName again.
There are three places in my code related to CustomCapabilityName, but they are all the same.
To test if the problem lies here, I reset the name.
Driver Code
static const wchar_t customCapabilities[] = L"Test.hsaTestCustomCapability_1653011401000\0";
CustomCapability.SCCD
<?xml version="1.0" encoding="utf-8"?>
<CustomCapabilityDescriptor xmlns="http://schemas.microsoft.com/appx/2018/sccd" xmlns:s="http://schemas.microsoft.com/appx/2018/sccd">
<CustomCapabilities>
<CustomCapability Name="Test.hsaTestCustomCapability_1653011401000"></CustomCapability>
</CustomCapabilities>
<AuthorizedEntities AllowAny="true"/>
<Catalog>0000</Catalog>
</CustomCapabilityDescriptor>
Package.appxmanifest
<Capabilities>
<Capability Name="internetClient" />
<uap4:CustomCapability Name="Test.hsaTestCustomCapability_1653011401000"/>
</Capabilities>
After that, I uninstalled the previously installed apps and drivers, restarted and installed the latest version of the program, but I still can't access it.
My SDK and WDK version is 10.0.19041.0, test machine OS version is Windows 10 Pro Build 19041.vb_release.191206-1406
I think I made a low-level mistake, the function g_pIoSetDeviceInterfacePropertyData that sets the device interface properties needs to be set in the DriverEntry.
But I didn't, which caused the CustomCapabilityName I set to not take effect.
UNICODE_STRING funcName;
RtlInitUnicodeString(&funcName, L"IoSetDeviceInterfacePropertyData");
g_pIoSetDeviceInterfacePropertyData = (PFN_IO_SET_DEVICE_INTERFACE_PROPERTY_DATA)(ULONG_PTR)
MmGetSystemRoutineAddress(&funcName);
However, it is still an unsolved mystery why the driver works properly in the most initial version...

How to build multiple c# projects using MSBuild engine without using command prompt?

I am working on windows application project and from that project want to build different multiple c# projects which are in one solution of visual studio 2015 and also want them to be build programmatically individually using MSBuild tool without using command prompt and finally want to show the output in log file not in command prompt (means those project is building successfully or having any errors like this message in log file)
Do I need to use any MSBuild API and how to add in this project?
I have seen many questions like this (not exactly same) but it didn't work for me. please can anybody help me with this?
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Logging;
...
public static BuildResult Compile(string solution_name, out string buildLog)
{
buildLog = "";
string projectFilePath = solution_name;
ProjectCollection pc = new ProjectCollection();
Dictionary<string, string> globalProperty = new Dictionary<string, string>();
globalProperty.Add("nodeReuse", "false");
BuildParameters bp = new BuildParameters(pc);
bp.Loggers = new List<Microsoft.Build.Framework.ILogger>()
{
new FileLogger() {Parameters = #"logfile=buildresult.txt"}
};
BuildRequestData buildRequest = new BuildRequestData(projectFilePath, globalProperty, "4.0",
new string[] {"Clean", "Build"}, null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(bp, buildRequest);
BuildManager.DefaultBuildManager.Dispose();
pc = null;
bp = null;
buildRequest = null;
if (buildResult.OverallResult == BuildResultCode.Success)
{
Console.ForegroundColor = ConsoleColor.Green;
}
else
{
if (Directory.Exists("C:\\BuildResults") == false)
{
Directory.CreateDirectory("C:\\BuildResults");
}
buildLog = File.ReadAllText("buildresult.txt");
Console.WriteLine(buildLog);
string fileName = "C:\\BuildResults\\" + DateTime.Now.Ticks + ".txt";
File.Move("buildresult.txt", fileName);
Console.ForegroundColor = ConsoleColor.Red;
Thread.Sleep(5000);
}
Console.WriteLine("Build Result " + buildResult.OverallResult.ToString());
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine("================================");
return buildResult;
}
This is some old code I had lying around.
I use this to programatically build solutions and C# Projects. The output will be a BuildResult.Success or BuildResult.Failure.
The variable buildLog will contain the build output.
Note - the only way to access the build output that I am aware of is to use the above methodology of having a log file generated and then reading it in your C# code.
One thing to be aware of and I never did find a fix for this, is that the application that runs this code, may keep dll's it loads into memory from nuget package directories in memory. This makes deleting those directories problematic. I found a work around by having my application run as a MS Service - it seems when it runs as a local service, it has enough permissions to delete files held in memory.

C# install software that requires administrative privileges

I've developed a small C# software that interfaces with a piece of hardware that will always be connected to the pc. Since this software requires administrative privileges and I want it to start as the PC starts, I'm evaluating what's the best way to deploy it.
The ideal would be to create an installer that takes care of disabling the UAC prompt for that specific software during its installation, so that everytime that specific software starts I won't receive any UAC prompt. Would this be possible? What are the possible alternatives?
You can't create a setup that installs an application in such a way that an interactive app requires admin privilege but does not prompt for it. The install is separate from the app.
Assuming you build an MSI-based Windows Installer setup:
The install almost certainly requires admin privileges to install, and the tool you use to build the MSI will let you say that, and the install will prompt for elevation.
The way you build an app that runs elevated is to have a manifest that requests elevation when it starts.
If you literally want your code to run when the machine starts then it must be installed as a service. Practically all other methods (the Run registry key, the Startup folder in Program menu etc) are called when a user logs in (NOT when the system starts). If you need a UI to do something with the device then you'll need a Windows UI app that talks to the service (because services cannot interact with the desktop).
I find the answer for run a application with admin permission at startup.
Basically I just created a task with run level Highest and your trigger is on Logon.
I found the code in vb in this repository: https://bitbucket.org/trparky/start_program_at_startup_without_uac
Sub addTask(taskName As String, taskDescription As String, taskEXEPath As String, taskParameters As String)
taskName = taskName.Trim
taskDescription = taskDescription.Trim
taskEXEPath = taskEXEPath.Trim
taskParameters = taskParameters.Trim
If Not IO.File.Exists(taskEXEPath) Then
MsgBox("Executable path not found.", MsgBoxStyle.Critical, Me.Text)
Exit Sub
End If
Dim taskService As TaskService = New TaskService()
Dim newTask As TaskDefinition = taskService.NewTask
newTask.RegistrationInfo.Description = taskDescription
If chkEnabled.Checked Then newTask.Triggers.Add(New LogonTrigger)
Dim exeFileInfo As New FileInfo(taskEXEPath)
newTask.Actions.Add(New ExecAction(Chr(34) & taskEXEPath & Chr(34), taskParameters, exeFileInfo.DirectoryName))
newTask.Principal.RunLevel = TaskRunLevel.Highest
newTask.Settings.Compatibility = TaskCompatibility.V2_1
newTask.Settings.AllowDemandStart = True
newTask.Settings.DisallowStartIfOnBatteries = False
newTask.Settings.RunOnlyIfIdle = False
newTask.Settings.StopIfGoingOnBatteries = False
newTask.Settings.AllowHardTerminate = False
newTask.Settings.UseUnifiedSchedulingEngine = True
newTask.Settings.ExecutionTimeLimit = Nothing
newTask.Settings.Priority = ProcessPriorityClass.Normal
newTask.Principal.LogonType = TaskLogonType.InteractiveToken
taskService.RootFolder.SubFolders(strTaskFolderName).RegisterTaskDefinition(taskName, newTask)
newTask.Dispose()
taskService.Dispose()
newTask = Nothing
taskService = Nothing
End Sub
So all I did was translated this code to c# and make tests
using Microsoft.Win32.TaskScheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CreateTaskTest
{
class Program
{
static void Main(string[] args)
{
addTask();
//deleteTask();
}
static void addTask()
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition newTask = ts.NewTask();
newTask.RegistrationInfo.Description = "Rondinelli Morais Create Task";
newTask.Triggers.Add(new LogonTrigger());
newTask.Actions.Add(new ExecAction("C:\\Windows\\regedit.exe"));
newTask.Principal.RunLevel = TaskRunLevel.Highest;
newTask.Principal.LogonType = TaskLogonType.InteractiveToken;
newTask.Settings.Compatibility = TaskCompatibility.V2_1;
newTask.Settings.AllowDemandStart = true;
newTask.Settings.DisallowStartIfOnBatteries = false;
newTask.Settings.RunOnlyIfIdle = false;
newTask.Settings.StopIfGoingOnBatteries = false;
newTask.Settings.AllowHardTerminate = false;
newTask.Settings.UseUnifiedSchedulingEngine = true;
newTask.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(#"Test", newTask);
newTask.Dispose();
ts.Dispose();
}
}
static void deleteTask()
{
using (TaskService ts = new TaskService())
{
var tasks = ts.FindAllTasks(new System.Text.RegularExpressions.Regex(#"Test"));
foreach(var task in tasks){
ts.RootFolder.DeleteTask(task.Name);
}
}
}
}
}
I'm using regedit.exe on exemple because this program required admin permission for run.
Create the task, make logoff and login again and you will see the regedit open after logon.
OBS: To create or delete task you have run visual studio as administrator, or put this code in the install process of your program
Let me know if this worked for someone

Cancelling Installer from Installing setup in Visual Studio Setup

I have a installer class which is taking a vale from the user at the time of installation.Now as per my requirement if the value provided is not correct i have to cancel the installation but i am not getting how to get this ..
Here is my installer.cs file..
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
// Retrieve configuration settings
string targetSite = Context.Parameters["targetsite"];
string targetVDir = Context.Parameters["targetvdir"];
string targetDirectory = Context.Parameters["targetdir"];
string value = Context.Parameters["value"];
string connectionstring = Context.Parameters["db"];
if (targetSite == null)
throw new InstallException("IIS Site Name Not Specified!");
if (targetSite.StartsWith("/LM/"))
targetSite = targetSite.Substring(4);
if (connectionstring == null)
throw new InstallException("You did not specify a database to use!");
if (value.Equals("123"))
{
RegisterScriptMaps(targetSite, targetVDir);
ConfigureDatabase(targetSite, targetVDir, connectionstring);
}
else {
Rollback(stateSaver);
}
}
Inspite of Rollback(stateSaver); my setup gets installed..
Please help me..
Just calling InstallException will do the rollback. That's the usual way and it works, so if it doesn't then something else is going on.
You should think about using another tool that lets you validate the data when it gets entered. VS custom actions always run after all the files have been installed, so basically you're installing the entire app and then rolling it back rather than using an MSI build tool that lets you validate when it's entered.

How to Get Last Shutdown Time using C#

I have an application, that needs to get the last shutdown time. I have used EventLog class to get the shutdown time. I have separate class file that is designed to read/write event log. ReadPowerOffEvent function is intended to get the power off event.
public void ReadPowerOffEvent()
{
EventLog eventLog = new EventLog();
eventLog.Log = logName;
eventLog.MachineName = machineName;
if (eventLog.Entries.Count > 0)
{
for (int i = eventLog.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry currentEntry = eventLog.Entries[i];
if (currentEntry.InstanceId == 1074 && currentEntry.Source=="USER32")
{
this.timeGenerated = currentEntry.TimeGenerated;
this.message = currentEntry.Message;
}
}
}
}
But whenever it tries to get the event entry count, it throws an IOException saying "The Network Path Not found". I tried to resolve, but I failed. Please help me out...
I think you sent wrong Log name, this worked for me
EventLog myLog = new EventLog();
myLog.Log = "System";
myLog.Source = "User32";
var lastEntry = myLog;
EventLogEntry sw;
for (var i = myLog.Entries.Count -1 ; i >=0; i--)
{
if (lastEntry.Entries[i].InstanceId == 1074)
sw = lastEntry.Entries[i];
break;
}
}
You have to have the "Remote Registry" service running on your machine (or the machine you want to run this app on). I suspect that this service in set to manual start on your machine. You may have to change the setting on this service to automatic.
If this app is going to be running on other machines, you may want to put some logic into your app to check to make sure this service is running first. If it isn't then you will need to start it up through your app.
Note:
The "Remote Registry" service enables remote users to modify registry setting on your computer. By default, the "Startup type" setting for the "Remote Registry" service may be set to "Automatic" or "Manual" which is a security risk for a single user (or) notebook PC user.
So, to make sure that only users on your computer can modify the system registry disable this "Remote Registry" service.

Categories

Resources