Access Denied when calling PrintQueue.Pause() method in C#.net - c#

I'm trying to pause a windows 7 print queue using C#.NET visual studio 2008. I have full administrator rights but when I run the following code to Pause the Queue it says Access is Denied. Please help me.
LocalPrintServer lps = new LocalPrintServer(PrintSystemDesiredAccess.AdministrateServer);
//PrintServer lps = new PrintServer("\\\\NOTEBOOK-CI3", PrintSystemDesiredAccess.AdministratePrinter);
lps.Commit();
PrintQueue queue = lps.GetPrintQueue(listBox1.SelectedItem.ToString());
if (!queue.IsPaused)
queue.Pause();
queue.Commit();
lps.Commit();

I had the same problem, so for me this was the best solution:
PrintS = new PrintServer();
PrintQ = new PrintQueue(PrintS, PrinterName, PrintSystemDesiredAccess.AdministratePrinter);
PrintQ.Pause();
Tested with local PDF-Printer

I'm not sure but have you tried to change LocalPrinterServer to PrinterServer? Take a look at http://www.visualbasicask.com/visual-basic-language/printqueuepause.shtml.
He had the exact same problem and could solve it by using PrintSystemDesiredAccess.AdministrateServer (which you do use). The only difference is that you're using LocalPrinterServer instead of PrinterServer.

Are you running your website as 4.0? I ran into issues when we upgraded our website from 3.5 to 4.0 Framework. The Print Purging functionality stopped working in the 4.0 Framework. Ultimately I ended up creating a web service that used the 3.5 framework and had the 4.0 website communicate the printer it wanted to purge to the 3.5 web service.
(Sorry to revive this thread, this was one of the threads I stumbled onto when I was looking for an answer. Figured I'd post this if it helps someone that runs into the same situation)

Related

System.Windows.Forms.Application' does not contain a definition for 'ExecutablePath

I am using compact framework 3.5 to build a windows mobile application.I need to restart the application after saving the application settings. I tried the below one,from How do I restart my C# WinForm Application?
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
Process.Start(path, "");
I am not getting any error,but my application is not restarting.I am checking in my simulator.Do restart working in mobile simulator.
Need solution to solve this problem.
Thanks
Try using this code to access the path:
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
But to restart the application you can use RunAppAtTime method:
var time = DateTime.Now.AddSeconds(3); // immediate restart
Notify.RunAppAtTime(thisName, time); // restart the app
Note that although the time is set to 3 seconds from now it will restart immediately. To have a real delay the time difference must be higher than 10 seconds.
More on that here: https://stackoverflow.com/a/6133136/3330348
An .net application can not restart itself. As it is running on Mobile only one instance is ensured by the framework, if you had targetted Windows CE, you would be able to run multiple instances.
So, RunAppAtTime is a good solution to let the app be started by the Mobile scheduler after the app itself has terminated using Application.Exit().
Another option would be a second application that is started at Application.Exit(), watches the process list to see when main applicaton is terminated (or use GetProcessExitCode), and then starts a new instance of main application. This techique is used for updaters etc.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I have written a few C# apps that I have running via windows task scheduler. They are running successfully (as I can see from the log files that they are writing ) but windows task scheduler shows them returning a last run result of 0xE0434352. Is there something I need to do in my C# application so that it returns a success code to the windows task scheduler?
Another option is to simply use the Application log accessible via the Windows Event Viewer. The .Net error will be recorded to the Application log.
You can see these events here:
Event Viewer (Local) > Windows Logs > Application
When setup a job in new windows you have two fields "program/script" and "Start in(Optional)". Put program name in first and program location in second.
If you will not do that and your program start not in directory with exe, it will not find files that are located in it.
Hans Passant was correct, I added a handler for AppDomain.CurrentDomain.UnhandledException as described here http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception(v=vs.71).aspx I was able to find the exception that was occurring and corrected it.
I was referencing a mapped drive and I found that the mapped drives are not always available to the user account that is running the scheduled task so I used \\IPADDRESS instead of MAPDRIVELETTER: and I am up and running.
In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.
I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.
I got the same error but I have fixed it by changing the file reading path from "ConfigFile.xml" to AppDomain.CurrentDomain.BaseDirectory.ToString() + "ConfigFile.xml"
In my case, this error due to file path error because task manager starts program from "System32" as initial path but the folder we thought.
I was getting the same message message within dotNet Core 2.2 using MVC 5, however nothing was being logged to the Windows Event Viewer.
I found that I had changed the Project sdk from Microsoft.NET.Sdk.Web to Microsoft.NET.Sdk.Razor (seen within the projects.csproj file). I changed this back and it worked fine :)
In my case it was because I had message boxes. Once I commented that code out, it started working. I remembered that could be a problem when I looked at the event log as suggested in this thread. Thank you everyone!
I encountered this problem when working with COM objects. Under certain circumstances (my fault), I destroyed an external .EXE process, in a parallel thread, a variable tried to access the com interface app.method and a COM-level crash occurred. Task Scheduler noticed this and shut down the app. But if you run the app in the console and don't handle the exception, the app will continue to work ...
Please note that if you use unmanaged code or external objects (AD, Socket, COM ...), you need to monitor them!
Also message box in PowerShell. I converted PowerShell script to exe. When running as admin it's worked but in task schedule I received this error also.
There was an line in PowerShell script with write-output. After commented this line and compile new exe Task Schedule was completed successfully.
It is permission issue in my case the task scheduler has a user which doesn't have permission on the server in which the database is present.

System.Management.ManagementException: Not found

I am running the following code:
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMClass.GetInstances();
which is throwing this exception:
System.Management.ManagementException: Not found
at System.Management.ThreadDispatch.Start()
at System.Management.ManagementScope.Initialize()
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementClass.GetInstances(EnumerationOptions options)
at System.Management.ManagementClass.GetInstances()
I went to check on the running services on Windows XP and found that Windows Management Instrumentation service has a status of 'Started'. I tried restarting the service but that didn't do any good.
I then tried to get the status of this service from within my running code using the ServiceController class:
ServiceController wpiService = new ServiceController();
wpiService.ServiceName = "Winmgmt";
string wmiStatus = wpiService.Status.ToString();
MessageBox.Show("WMI status= " + wmiStatus);
wmiStatus evaluates to 'Running'.
I have seen this error on only one of multiple machines running the same software. What's peculiar is that the machine was running smoothly for months, and then suddenly started showing this error.
Any clue as to what might be causing this?
I have also run into this issue. Here is one of the previously mentioned online resources explaining how one can fix WMI:
http://windowsxp.mvps.org/repairwmi.htm
The method of repairing seems to be different between different versions of Windows as explained on that page.
I had this problem on none of these versions, but on Windows Embedded Standard 2009. Since Windows XP Service Pack 2 is closest related to the listed OSes, that is the one I used:
For Windows XP Service Pack 2
Click Start, Run and type the following command:
rundll32 wbemupgd, UpgradeRepository
This command is used to detect and repair a corrupted WMI Repository. The results are stored in the setup.log (%windir%\system32\wbem\logs\setup.log) file.
The solution was to repair WMI on Windows XP. I don't have the detailed step by step fix (I'm not the one who implemented the fix), but my understanding is that a repository related to this service can get corrupted and there's a Windows utility that can repair it. There are several online resources on how to do this.

how to transfer file from PC to Windows-mobile and from Windows-mobile to PC?

i need to transfer Text.txt file from PC (using WebService)
to Windows-mobile 5.0 - and from Windows-mobile to PC
can i get any sample code in C# for the WebService and the Windows-mobile ?
thanks in advance
You cannot directly transfer files. you should try ActiveSync RAPI to send information.
Use OpenNETCF. It's a useful compact framework for WindowsMobile (.NET).
Try this:
string fileToSendToDevice = #"C:\Text.txt";
OpenNETCF.Desktop.Communication.RAPI rApi = new OpenNETCF.Desktop.Communication.RAPI();
if (!rApi.DevicePresent) return; // no active sync
if (!rApi.Connected) rApi.Connect();
if (!File.Exists(fileToSendToDevice)) return; // file not found
rApi.CopyFileToDevice(fileToSendToDevice,
Path.Combine(#"\My Documents\", Path.GetFileName(fileToSendToDevice)));
The concept is really no different than PC-to-PC if you intend to use a Web Service for the transfer (assuming the Web Service is running on the PC). Find any example on the web that transfers a file to and from a Web Service and it will likely be applicable.
If you then have a question that is more specific to WinMo/CF or an implementation problem, feel free to update this question about what you've tried and what about it is not working.
One of these two examples will probably help. The code for the PC will be likely the same if not simpler.
Then you just need to write the web service.

.Net's Directory Services throws a strange exception

I have a small C# solution used to check users credentials. It works fine for two of my teammates, but on my PC I get an exception.
The relevant code:
PrincipalContext context = new PrincipalContext(ContextType.Domain);
if (context.ValidateCredentials(System.Environment.UserDomainName + "\\" + usr, pwd))
return true;
else
return false;
And the exception is:
DirectoryOperationException, "The server cannot handle directory requests.".
I tried creating context with the explicit server name and the 636 port number, but this didn't help as well.
Any ideas?
I had this problem too using IIS Express and VS 2010. What fixed it for me was a comment on another thread.
Validate a username and password against Active Directory?
but i'll save you the click and search... :) Just add ContextOpations.Negotiate to you Validate Credentials call like below.
bool valid = context.ValidateCredentials(user, pass, ***ContextOptions.Negotiate***);
I had this issue: things were working on my dev machine but didn't work on the server. Turned out that IIS on the server was set up to run as LocalMachine. I changed it to NetworkService (the default) and things started working.
So basically check the user of the app pool if this is running on IIS.
I had to just create a new app pool and assign it .NET 2.0, then assign the new app pool to our web app, and it started working. We had .NET 3.5 SP2, so the hotfix wasn't ideal for us. Since the WWW service is usually Local System, I questioned that too. But since it was .NET and security related, I gave a shot at the app pool first and it worked.
Perhaps you need the hotfix?
FIX: DirectoryOperationException exception
And you are an Admin or the id that your service is running under is an Admin on your PC right?
I take it you already looked into this:
System.DirectoryServices.Protocols
"You may receive a less than helpful DirectoryOperationException(“The server cannot handle directory requests.”) what isn’t quite so amusing about this is that it didn’t even try to communicate with the server. The solution was to add the port number to the server. So instead of passing “Server” to open the LdapConnection, I passed “server:636”. By the way, LDAPS is port 636 – rather than the 389 port used by LDAP."
Good point, I wouldn't expect that Win7/.NET 3.5 would need that patch. How about the info provided in this question:
Setting user's password via System.DirectoryServices.Protocols in AD 2008 R2

Categories