C# WPF OpenFileDialog causing crash in XP, not in Vista - c#

I have a WPF application that runs fine on my Vista development machine, but not on the production XP boxes. The only problem is with a call to OpenFileDialog.Show(). As soon as I call the method, the application is terminated on the XP box.
The problem does not trigger an exception. (I've surrounded the block in a try-catch block to no avail.) When I click on File->Open the application just up and quits in XP. Interestingly, I can write files to disk with File->Save and using the Save As dialog. I've tried building it to .Net 3.0 and 3.5 but it doesn't make a difference.
I've tried both Microsoft.Win32.OpenFileDialog and System.Windows.Forms.OpenFileDialog and get the exact same symptom.
The code block for the Microsoft.Win32 variant:
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog().Value)
{
//do something
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error!");
}
The only clues I have is the following (partial) entry from the security event log.
Event Type: Failure Audit
Event Source: Security
Event Category: Object Access
Event ID: 560
Description:
Object Open:
Object Server: Security
Object Type: Key
Object Name: \REGISTRY\MACHINE\SOFTWARE\Microsoft\EnterpriseCertificates\Disallowed
Accesses: DELETE
READ_CONTROL
WRITE_DAC
WRITE_OWNER
Query key value
Set key value
Create sub-key
Enumerate sub-keys
Notify about changes to keys
Create link
Any ideas? (Pleeeease!)

Thanks for the advice. I verified both the registry permissions and the full-trust issue. It turns out that, although I specifically built my application to .Net 3.0 (based on the standard organizational image), there was a dependency on .Net 3.5 SP1 that I still don't fully understand. The solution to my problem was to install .Net 3.5 SP1 on all the affected computers.
I just wanted to close the loop. Thanks, again, to all who contributed ideas.

It seems there is a permission problem with the registry key. My first suggestion would be to check the permissions on that key and verify that the ACL's are correct (best compare them to another XP box where the app is working).
If the permissions are OK, then you should try reinstalling .NET (maybe the installer will reset some required permissons on the registry keys).
If all else fails, reinstall XP on problematic machines, unless someone has a better idea.

It doesn't appear your production assembly is running under full trust. Are you running from a network share?

Related

System.Security.SecurityException when writing to Event Log C#

My application is in C#.NET and it is deployed on different machines. Users of my application have normal access rights ( no ADMIN rights). On a few system I am getting System.Security.SecurityException. It says "System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security"
I did a few workarounds :-
on one machine I launched my app with admin rights, It worked fine - No issue.
I added user group in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security.
It worked fine.
I dont want to go to every machine and do above workarounds. I need any generic workaround that can be applied once in all machine.
Any help?
Writing down a few lines of code :-
Config file :-
<add key="E_Source" Value="ABC">
C# code
Public static readonly string E_Source = ConfigManager.GetString("E_Source");
EventLog.writeEntry(E_Source, logtext, logtype);
Thanks in advance
To find the Source you want to write, .NET enumerates through all event logs. If it doesn't exist, .NET will eventually try enumerating through the Security log, for which you don't even have read rights as normal user. Thus, you get a SecurityException.
So you have to make sure that the event log exists (which AFAIK you can't do without triggering the exception). Normally, you would do that as part of your setup/install. Then, when writing, catch the SecurityException and handle it as appropriate (ex. show an error message that you couldn't write to the log).
If you're writing to the EventLog programmatically, you will need to create an event source with elevated permissions, as noted in the documentation on the EventLog class:
https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28v=vs.110%29.aspx

Windows Service not working when installed, works fine in Debug mode; crashes on Moving/deleting files

I created a windows service which watches a directory. When a file is dumped into it, it takes the data and puts it into a database. Then this file is moved to another directory and deleted. It works fine in debug mode. But when i install it on my computer it stops after throwing the data into the database and the file in question is neither moved or deleted. I suspect a permission issue is involved. I tried to create a event log:
public Service1()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
So i have three questions.
(1) What could be causing my service to work as described in debug but fail when installed on my computer.(2) I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method.(3) Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools? stored as a file on some directory?
Here is edit to this post in lieu of the grateful advice given below.
try
{
File.Move(e.FullPath, finalString);
File.Delete(e.FullPath);
}
catch(Exception q)
{
EventLog.WriteEntry("MySource", q.ToString(), EventLogEntryType.Error);
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["fmd"], true))
{
w.Write(DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss"));
w.Write(q.ToString());
}
}
As per suggestion i put a try-catch around the file move and delete plus i added a OnShutdown method:
protected override void OnShutdown()
{
using (StreamWriter w = new StreamWriter(ConfigurationManager.AppSettings["ond"], true))
{
w.Write("stop OnShutdown");
}
//EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
}
I do not know how to pass any system error message to the shutdown method, so any advice appreciated. When i installed my modified code as a service, it again stopped before moving or deleting the files. Neither of my two logs accessed by a stream recorded anything. Plus the event viewer showed nothing either?
You can write as following,
if (!EventLog.SourceExists("MySource"))
EventLog.CreateEventSource("MySource", "Application");
EventLog.WriteEntry("MySource", message, EventLogEntryType.Error);
to view the event log messages, Goto Administrator Tools -> Event Viewer and look for the source you have created. or Just simply type eventvwr in run window.
When Services installed, it works under SYSTEM User account where service might not have access to some resources. Please put logs and see where exactly the issue is.
If you service installed in your development machine, use attach to process option under DEBUG Menu in Visual Studio to find out.
What could be causing my service to work as described in debug but fail when installed on my computer?
Permissions. The service is likely running under LocalSystem or Network Service if you didn't provide a different identity.
I have initiated a event log as shown above. But do i need to add other code to record the event of my service stopping. I presume this would be done in a 'override onShutdown' method?
Yes, you're assumption is correct.
Finally when my service stops, i want to look at the event log. But i do not know how to do this, is in administrative tools?
Just hit Windows Key+R to get the Run dialog and type eventvwr.
Well i found the reason for all the commotion. I eventually found some logs in the event viewer. They were listed in Administrative events in custom logs. There were three error logs: .Net runtime; Application error & Service Control Manager. In '.Net Runtime' the stack showed a unhandled exception for system.windows.forms. I stupidly included a pop up box in my release version. But even when i commented this away; i got a error. So i went back and found other message boxes, primarily in try catch statements. Removed these and solved the issue.

Clickonce full trust app update failing with TrustNotGrantedException on Windows 8

We have a winforms clickonce application in C# which is granted full trust and signed using a valid certificate.
The application runs fine and updates correctly on Windows XP, Windows 7. However, on a Windows 8 machine, it just fails to update. The application runs correctly though. However, the first update request to move up to a later version fails with: System.Deployment.Application.TrustNotGrantedException
The code failed after the call to ApplicationDeployment::CheckForDetailedUpdate() failed. Wondering why this could happen as the exact same code is running fine on all previous versions of Windows. Any help will be appreciated. Below is the relevant stack trace:
System.Deployment.Application.TrustNotGrantedException: User has refused to grant required permissions to the application.
at System.Deployment.Application.ApplicationTrust.RequestTrust(SubscriptionState subState, Boolean isShellVisible, Boolean isUpdate, ActivationContext actCtx, TrustManagerContext tmc)
at System.Deployment.Application.DeploymentManager.DetermineTrustCore(Boolean blocking, TrustParams tp)
at System.Deployment.Application.DeploymentManager.DetermineTrust(TrustParams trustParams)
at System.Deployment.Application.ApplicationDeployment.CheckForDetailedUpdate(Boolean persistUpdateCheckResult)
at System.Deployment.Application.ApplicationDeployment.CheckForDetailedUpdate()
The only time I'd seen this stack trace was when I tried calling CheckForDetailedUpdate() without setting up the explicit trust before hand. After adding the code below, the update check worked.
// Setup the trust level
var deployment = ApplicationDeployment.CurrentDeployment;
var appId = new ApplicationIdentity(deployment.UpdatedApplicationFullName);
var unrestrictedPerms = new PermissionSet(PermissionState.Unrestricted);
var appTrust = new ApplicationTrust(appId) {
DefaultGrantSet = new PolicyStatement(unrestrictedPerms),
IsApplicationTrustedToRun = true,
Persist = true
};
ApplicationSecurityManager.UserApplicationTrusts.Add(appTrust);
// Check for update
var info = deployment.CheckForDetailedUpdate();
From this MSDN page there are two causes. But it seems TrustNotGrantedException is usually raised when a new ClickOnce update has been deployed that uses more privileges than the previous version...
The application uses permission elevation and the user denies the request for elevated trust; or
The application uses Trusted Application Deployment and the digital certificate used to sign the application is not listed as a trusted publisher on the local machine. If you have deployed an update to an application, and the update uses more permissions than the previous version, and ClickOnce throws a TrustNotGrantedException, the new version will not install.
So it makes sense that it would fail to update, because the apps security level has changed since the user last installed it - so they will need to reinstall it.
We had the same problem and ended up using the InPlaceHostingManager class. It's made for installing or updating a ClickOnce deployment. GetManifestAsync() fires the GetManifestCompleted event, which gives you the version number. Then you can call DownloadApplicationAsync() and handle the DownloadApplicationCompleted event. So far this works and no TrustNotGrantedException is thrown.

C# WinForm nothing happen

i have created C# WinForm on my Windows server 2008 and it works fine.
but when i transfert this MyProg.exe into computer window 7, and i run it, nothing happen.
my code:
[STAThread]
static void Main()
{
try
{
Application.SetCompatibleTextRenderingDefault(false);
DevExpress.UserSkins.BonusSkins.Register();
Application.EnableVisualStyles();
//Pour TEST
//Le_ClientID = "850001";
//Le_Login = "850001FA";
using (var loginForm = new Login())
{
if (loginForm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
}
Application.Run(new Le_MainForm());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Anybody have an idea ?
event log show:
- System
Provider
[ Name] Application Error
EventID 1000
[ Qualifiers] 0
Level 2
Task 100
Keywords 0x80000000000000
TimeCreated
[ SystemTime] 2012-05-14T09:40:39.000000000Z
EventRecordID 3557
Channel Application
Computer anjouachemineme
Security
EventData
FrontEnd_Offline.exe
1.0.0.0
4fb0c28b
KERNELBASE.dll
6.1.7601.17651
4e2111c0
e0434352
0000d36f
f84
01cd31b59ee78b7d
C:\Soft8_Local\FrontEnd_Offline.exe
C:\Windows\system32\KERNELBASE.dll
dcb7cb01-9da8-11e1-bf8c-1c6f65c1ad74
Thanks you in advance,
Stev
PS: As i lunch MyProg.exe, it listed on Task Manger, but it disapear (killed) in about 3 second after.
Execute the exe (Start as Administrator)
or
this may happen if you dont have Framework Installed in which you created the application by default windows 7 comes with 2.0 and 3.5 Framework . if you created application in visual studio 2010 then you need to download FrameWork 4.0 from Microsoft website to run that exe in Windows 7
you can download Framework 4.0 from here
I just encountered this issue in a Windows form App I created. Apparently there is a plethora of issues that can cause this. In my case you could open the Task Manager, click the application, see it open in the task manager, and immediately close. The only way to see what the issue was, was to look at the event viewer and find the error.
The first is dependencies. Like mentioned above, ensure all required .dlls are included and that you have the required framework(s) installed.
Second KERNELBASE.dll can become corrupted. To ensure that is not the case you can run the System File checker. Instructions can be found here: http://support.microsoft.com/kb/929833
Third, is my case. I had a method running in the constructor of Program.cs which is the first thing instantiated when you start a windows form app. I had a bug in code that was causing an exception before any exception handling was created. To fix the problem I moved the code to a point after I create an unhandled exception method as such:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
in my forms constructor. Now the program would start and actually throw an error. I then just had to fix the bug in my code.
I hope this can help you or anyone else out there.

Debugging TrustNotGrantedException in VSTO word addin

I'm getting TrustNotGrantedException thrown for some specific users of our VSTO word addin.
These users have the certificate installed correctly.
The exception is being thrown when the app checks for updates:
try
{
ApplicationDeployment.CurrentDeployment.CheckForUpdate()
}
catch(TrustNotGrantedException ex)
{
Log(ex);
}
The stack trace is logged as follows:
User has refused to grant required permissions to the application.
at System.Deployment.Application.ApplicationTrust.RequestTrust(SubscriptionState subState, Boolean isShellVisible, Boolean isUpdate, ActivationContext actCtx, TrustManagerContext tmc) at System.Deployment.Application.DeploymentManager.DetermineTrustCore(Boolean blocking, TrustParams tp) at System.Deployment.Application.DeploymentManager.DetermineTrust(TrustParams trustParams) at System.Deployment.Application.ApplicationDeployment.CheckForDetailedUpdate(Boolean persistUpdateCheckResult) at System.Deployment.Application.ApplicationDeployment.CheckForUpdate() at iReport.iReportAddIn.CheckForUpdates()
Has anyone experienced this or knows how to prevent this in the code or with any workarounds?
Edit:
I have read through this blog post on the issues and it seems like it could be an issue with CAS Permissions for the problem users.
I'll try and give a problem user access to the update URL using this and will follow up in a bit, although I would much prefer to be able to prevent this in the code instead of fixing individual client machines. Something like:
caspol -m -ag 1 -url "http://machinename/application/*" FullTrust -exclusive on
Edit2:
Using caspol.exe worked! Does anyone know a way to prevent this from happening in the code?
Or can anyone explain why it could only be happening to select users?
Edit3:
I'm going to try add
<system.web>
<!-- level="[Full|High|Medium|Low|Minimal]" -->
<trust level="Full" originUrl=""/>
</system.web>
to the app.config
Edit4:
Adding full CAS trust to the app.config didn't help. Can anyone show me if its possible to achieve what CASPOL is doing in code?
Edit5:
If it isn't possible to do this in code, is there a easy way to run the CASPOL command as part of the clickonce install?
In recent versions of Windows, downloaded files are flagged as blocked and have security restrictions imposed on them that can cause breakage when consumed by other apps due to the sandboxing.
The implementation uses NTFS alternate streams. If the file is blocked you can tell by right clicking on the file, viewing properties and seeing the unblock button. Clicking unblock removes the stream and releases the extra security restrictions.
It can also be removed using sysinternals streams.exe. Test whether this is your issue by downloading your plugin on a Windows 7 machine, and then install without unblocking to see if it reproduces the issue.

Categories

Resources