Printing from a windows service on Windows Server 2012 - c#

I have a windows service in C# .NET 4.6.1 that is building SSRS reports and sending the report to various network printers. All printers are installed locally on the server where the service is installed. All this was working on a Windows Server 2008R2 server and recently the client upgraded to Windows Server 2012R2 and now no printouts. I am getting no errors and when checking the job status on the printer I can see the job count on the printer increase by 1 and the PrintJobStatus.Spooling is true but nothing comes out on the printer.
private bool PrintSheet(AppPrintRequest model, PackagingEntities db)
{
try
{
var oPrinter = db.AppPrinters.Where(x => x.AppPrinterID == model.AppPrinterID).FirstOrDefault();
var lpsPrintServer = new LocalPrintServer();
var psPrintServer = new PrintServer();
var sbLog = new StringBuilder();
byte[] reportBytes = BuildSSRSReport(model);
PrintQueueCollection pqcAvailablePrinters;
if (!string.IsNullOrEmpty(oPrinter.AppPrinterServer))
{
pqcAvailablePrinters = lpsPrintServer.GetPrintQueues();
}
else
{
pqcAvailablePrinters = psPrintServer.GetPrintQueues();
}
sbLog.AppendFormat("System: {0} ", model.AppPrintRequestSystem);
sbLog.AppendFormat("Printer: {0} ", oPrinter.AppPrinterAddress);
foreach(var oAvailablePrinter in pqcAvailablePrinters)
{
sbLog.AppendFormat("Printer FullName: {0} ", oAvailablePrinter.FullName);
sbLog.AppendFormat("Printer Name: {0} ", oAvailablePrinter.Name);
sbLog.AppendFormat("Printer Description: {0} ", oAvailablePrinter.Description);
}
var oLaserPrinter = pqcAvailablePrinters.FirstOrDefault(pqCurrent => pqCurrent.Name.ToUpper() == oPrinter.AppPrinterAddress.ToUpper());
sbLog.AppendFormat("Report Bytes is null = {0} ", reportBytes == null);
sbLog.AppendFormat("Laser Print is null = {0} ", oLaserPrinter == null);
if (reportBytes != null && oLaserPrinter != null)
{
sbLog.AppendFormat("Report Bytes Length: {0} ", reportBytes.Length);
sbLog.AppendFormat("Laser Printer: {0} ", oLaserPrinter.Name);
sbLog.AppendFormat("Laser Printer Busy: {0} ", oLaserPrinter.IsBusy);
PrintSystemJobInfo oPrintJob = oLaserPrinter.AddJob();
sbLog.AppendFormat("Laser Printer Job Count: {0} ", oLaserPrinter.NumberOfJobs);
GetPrintJobStatus(oPrintJob, sbLog);
oPrintJob.JobStream.Write(reportBytes, 0, reportBytes.Length);
oPrintJob.JobStream.Close();
oPrintJob.Refresh();
sbLog.AppendFormat("Job Completed: {0} ", oPrintJob.IsCompleted);
NLogger.Debug(string.Format("Print Sheet: {0}", sbLog.ToString()));
return true;
}
NLogger.Debug(string.Format("Print Sheet: {0}", sbLog.ToString()));
return false;
}
catch (Exception ex)
{
NLogger.Fatal("PrintEngine_PrintSheet", ex);
return false;
}
}

Related

C# IBM MQ Unmanaged Client Multithread Get Message

I am trying to use multiple threads to open an IBM MQ queue manager and get message from it from every thread.
I have encountered a couple of problems with the code.
When the threads are started, the first one or two threads will fail
with "Object not set to an instance" error near the "pnrQ.Get(msg,
gmo);"
When the subsequent threads are started, only one thread is reading messages from the queue, the other threads will all have the
"MQC.MQRC_NO_MSG_UNDER_CURSOR" error
Does this have something to do with the "openOptions" I declare for the Queue Manager? Or something to do with the "MQGetMessageOptions" I declare?
Where can I refer to some sample codes for IBM MQ Unmanaged Client multithread sample codes?
using System;
using System.Collections;
using IBM.WMQ;
using System.Configuration;
using System.Text;
using System.IO;
using System.Threading;
using System.Globalization;
namespace MqClientUnmanaged
{
class MqClientUnmanaged
{
static void Main(string[] args)
{
Hashtable prop = new Hashtable();
prop.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings.Get("host"));
prop.Add(MQC.PORT_PROPERTY, ConfigurationManager.AppSettings.Get("port"));
prop.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings.Get("channel"));
prop.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT);
prop.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
prop.Add(MQC.SSL_CERT_STORE_PROPERTY, ConfigurationManager.AppSettings.Get("sslKeyRepository"));
prop.Add(MQC.SSL_CIPHER_SPEC_PROPERTY, ConfigurationManager.AppSettings.Get("cipherSpec"));
prop.Add(MQC.CERT_LABEL_PROPERTY, ConfigurationManager.AppSettings.Get("certLabel"));
foreach (DictionaryEntry de in prop)
{
Console.WriteLine("Property: {0}, Value: {1}", de.Key, de.Value);
}
//MQQueueManager[] queueManager = new MQQueueManager[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
//MQQueue[] pnrQueue = new MQQueue[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
try
{
var queueManager = new MQQueueManager[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
var pnrQueue = new MQQueue[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
int openOptions = MQC.MQGMO_SYNCPOINT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INPUT_SHARED | MQC.MQOO_BROWSE;
Thread[] threads = new Thread[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
for(int thread_array_count = 0; thread_array_count < int.Parse(ConfigurationManager.AppSettings["number_of_thread"]); thread_array_count++)
{
try
{
queueManager[thread_array_count] = new MQQueueManager(ConfigurationManager.AppSettings.Get("queue_manager"), prop);
pnrQueue[thread_array_count] = queueManager[thread_array_count].AccessQueue(ConfigurationManager.AppSettings.Get("queue"), openOptions);
Console.WriteLine("Thread #" + thread_array_count.ToString() + " successfully connected to " + ConfigurationManager.AppSettings.Get("queue"));
threads[thread_array_count] = new Thread(() => LoopMessage(thread_array_count, pnrQueue[thread_array_count]));
threads[thread_array_count].Name = string.Concat("Threads ", (thread_array_count).ToString());
threads[thread_array_count].Start();
Thread.Sleep(Convert.ToInt32(ConfigurationManager.AppSettings["thread-sleep"]));
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
catch (System.Exception ex)
{
Console.WriteLine("A System error occurred: {0}, {1}", ex.Message.ToString(), ex.StackTrace.ToString());
}
finally
{
try
{
if (pnrQueue[thread_array_count] != null)
pnrQueue[thread_array_count].Close();
Console.WriteLine("Thread #" + thread_array_count.ToString() + " " + ConfigurationManager.AppSettings.Get("queue") + " is closed");
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
try
{
if (queueManager[thread_array_count] != null)
queueManager[thread_array_count].Disconnect();
Console.WriteLine("Thread #" + thread_array_count.ToString() + " " + ConfigurationManager.AppSettings.Get("queue_manager") + " is disconnected");
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
}
}
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
catch (System.Exception ex)
{
Console.WriteLine("A System error occurred: {0}, {1}", ex.Message.ToString(), ex.StackTrace.ToString());
}
Console.WriteLine("Press any key to EXIT.......");
Console.ReadKey();
}
private static void LoopMessage(int thread_num, MQQueue pnrQ)
{
bool flag = true;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options = MQC.MQGMO_WAIT | MQC.MQGMO_BROWSE_FIRST;
gmo.WaitInterval = int.Parse(ConfigurationManager.AppSettings.Get("wait_interval")); //1 to 2 second wait time or MQC.MQEI_UNLIMITED
while (flag)
{
try
{
//IMPORTANT: must declare a new message here
MQMessage msg = new MQMessage();
pnrQ.Get(msg, gmo);
Console.WriteLine("Thread # ", thread_num.ToString() + "; Message Length = " + msg.MessageLength.ToString());
if(msg.MessageLength > 0)
{
string newMessage = msg.ReadString(msg.MessageLength);
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff", CultureInfo.InvariantCulture);
string guid = Guid.NewGuid().ToString();
Console.WriteLine("Thread # ", thread_num.ToString() + "; Message Id = " + ByteArrayToString(msg.MessageId));
//write to text file
using (StreamWriter writer = new StreamWriter(string.Concat(ConfigurationManager.AppSettings.Get("pnr_file_path"), "sbr.", thread_num.ToString(), ".", timestamp, ".", guid, ".", ByteArrayToString(msg.MessageId), ".txt")))
{
writer.WriteLine(newMessage);
}
Console.WriteLine(string.Concat("Writing PNR file with name = ", string.Concat(ConfigurationManager.AppSettings.Get("pnr_file_path"), "sbr.", thread_num.ToString(), ".", timestamp, ".", guid, ".", ByteArrayToString(msg.MessageId), ".txt")));
Console.WriteLine(new string('*', 100));
}
// set te cursor to remove the message from the queue
gmo.Options = MQC.MQGMO_MSG_UNDER_CURSOR;
pnrQ.Get(msg, gmo);
gmo.Options = MQC.MQGMO_WAIT | MQC.MQGMO_BROWSE_NEXT;
}
catch (MQException mqex)
{
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE || mqex.Reason == MQC.MQRC_NO_MSG_UNDER_CURSOR)
{
//no meesage - life is good - loop again
Console.WriteLine("Thread # " + thread_num.ToString() + "; MqClientUnmanaged reason code = " + mqex.ReasonCode + "; MqClientUnmanaged reason = " + mqex.Message);
}
else
{
Console.WriteLine("MqClientUnmanaged reason code = " + mqex.ReasonCode);
Console.WriteLine("MqClientUnmanaged error message = " + mqex.Message);
Console.WriteLine("MqClientUnmanaged StackTrace = " + mqex.StackTrace);
flag = false; //severe error - time to exit
}
}
catch (Exception ex)
{
Console.WriteLine("MqClientUnmanaged error message = " + ex.Message);
Console.WriteLine("MqClientUnmanaged stack trace = " + ex.StackTrace);
flag = false; //severe error - time to exit
}
}
}
private static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}

php exec or pro_open C# exe OutOfMemoryException,CLI OK

Environment:Win10 64bit, WAMP3.0.6 64bit(PHP v7.0.10,apache v2.4.23),ppt2png.exe(Written by C#,Call dcom PowerPoint Application)
1.php code :exec(ppt2png.exe,in ppt,out pngs).
<?php
//echo exec('whoami');
$cmd="D:\wamp64\www\convert\application\convert\util/../bin/ppt2png/ppt2img.exe D:\wamp64\www\convert\application\convert\util/../convert_tmp/ppt/ba228be6f2cfa6a6bc2a66878afacb662018-01-15-15-04-57-7206.pptx -t png -o D:\wamp64\www\convert\application\convert\util/../convert_tmp/png/ba228be6f2cfa6a6bc2a66878afacb662018-01-15-15-04-57-7206";
exec($cmd, $output, $status);
//var_dump($status);
var_dump($output);
// pro_open($cmd);
function pro_open($cmd)
{
$cmdErrorTxt = "error-output.txt";
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", $cmdErrorTxt, "a"),
);
$process = proc_open($cmd, $descriptorspec, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
$return_value = proc_close($process);
return $return_value;
}
return 0;
}
2.c# ppt2png.exe code
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(#"Usage: ppt2img <ppt|pptx> [options]
Option:
-t|--type <png|jpg>
-o|--output <dir>");
return;
}
try
{
for (int i = 0; i < args.Length; ++i)
{
if (args[i] == "--type" || args[i] == "-t")
{
++i;
imgType = args[i];
}
else if (args[i] == "--output" || args[i] == "-o")
{
++i;
outDir = args[i];
}
else if (inPpt.Length == 0)
inPpt = args[i];
else
throw new Exception("Unknow option '" + args[i] + "'");
}
}
catch (Exception e)
{
Console.WriteLine("Invalid args");
Console.WriteLine("{0}", e.Message);
return;
}
outDir = Path.GetFullPath(outDir);
inPpt = Path.GetFullPath(inPpt);
baseName = Path.GetFileNameWithoutExtension(inPpt);
Type officeType = Type.GetTypeFromProgID("Powerpoint.Application");
if (officeType == null)
{
// Powerpoint is not installed.
// Show message or alert that Powerpoint is not installed.
}
else
{
// Powerpoint is installed.
// Continue your work.
}
Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
Microsoft.Office.Interop.PowerPoint.Presentations multi_presentations = PowerPoint_App.Presentations;
Microsoft.Office.Interop.PowerPoint.Presentation presentation = multi_presentations.Open(inPpt,
MsoTriState.msoTrue /* ReadOnly=true */,
MsoTriState.msoTrue /* Untitled=true */,
MsoTriState.msoFalse /* WithWindow=false */);
int count = presentation.Slides.Count;
for (int i = 0; i < count; i++)
{
Console.WriteLine("Saving slide {0} of {1}...", i + 1, count);
string fmtI= i.ToString("000");
String outName = String.Format(#"{0}\slide_{2}.{3}", outDir, baseName, fmtI, imgType);
try
{
presentation.Slides[i + 1].Export(outName, imgType, width, height);
}
catch (Exception e)
{
Console.WriteLine("Failed to export slide {0}", i + 1);
Console.WriteLine("{0}", e.Message);
break;
}
}
PowerPoint_App.Quit();
Console.WriteLine("Done");
}
This is correct when executed in cmd.
executed in cmd alone
executed in cmd by php cli
But wrong when executed by browser(when web server is Apache Or IIS) throwing OutOfMemoryException.
error-output.txt contains 'unhandled exception: OutOfMemoryException.'.
C# log indicates that C# program stops at
Microsoft.Office.Interop.PowerPoint.Application PowerPoint_App = new Microsoft.Office.Interop.PowerPoint.Application();
But when web server is Nginx,there is no such exception,it works out.
Who can give me some tips? thanks a lot!
That's not a PHP problem. It's an issue with the ppt2png.exe program. It's likely a PPT file that's too big or something but you should contact the original author of that program for support.
Old, but in case someone else has this issue - I had exactly the same issue with a C# program that used Interop to convert PPT slides to PNG on Windows Server 2008 R2. Called from command line worked perfectly, called from PHP via exec() gave Out of Memory error. Turned out I'd installed 64-bit Office 2016 but PHP was 32-bit. Reinstalling 32-bit Office solved the issue. Maybe that helps someone.

SSH connection remained open after debug error

So i am making an application which can open connections to remote devices and execute different commands. So yesterday before i left work i was debugging when i got an error. But as my application ignored it and proceeded and having not enough time to fix it immedietly i decided to do it today. When i wanted to make connection with my program again it said it couldn't authenticate (note* the parameters did not change).
So i did some checks to determine the problem, after logging in on the server and running netstat i found out that there was an active connection to port 22, which originated from my application.
Somehow the connection did not show up in my SSH manager until i rebooted it TWICE.
So to prevent things like this in a production environment, how do i prevent things like this.
my Program.cs
class Program
{
static void Main(string[] args)
{
var ip="";
var port=0;
var user="";
var pwd="";
var cmdCommand="";
ConnectionInfo ConnNfo;
ExecuteCommand exec = new ExecuteCommand();
SSHConnection sshConn = new SSHConnection();
if (args.Length > 0)
{
ip = args[0];
port = Convert.ToInt32(args[1]);
user = args[2];
pwd = args[3];
cmdCommand = args[4];
ConnNfo = sshConn.makeSSHConnection(ip, port, user, pwd);
exec.executeCMDbySSH(ConnNfo, cmdCommand);
}
else {
try
{
XMLParser parser = new XMLParser();
List<List<string>> configVars = parser.createReader("C:\\Users\\myusername\\Desktop\\config.xml");
Console.WriteLine("this is from program.cs");
//iterate through array
for (int i = 0; i < configVars[0].Count; i++)
{
if ((configVars[0][i].ToString() == "device" && configVars[1][i].ToString() == "device") && (configVars[0][i + 6].ToString() == "device" && configVars[1][i + 6].ToString() == "no value"))
{
string ipAdress = configVars[1][i + 1].ToString();
int portNum = Convert.ToInt32(configVars[1][i + 2]);
string username = configVars[1][i + 3].ToString();
string passwd = configVars[1][i + 4].ToString();
string command = configVars[1][i + 5].ToString();
Console.WriteLine("making connection with:");
Console.WriteLine(ipAdress + " " + portNum + " " + username + " " + passwd + " " + command);
ConnNfo = sshConn.makeSSHConnection(ipAdress, portNum, username, passwd);
Console.WriteLine("executing command: ");
exec.executeCMDbySSH(ConnNfo, command);
}
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
Console.WriteLine("press a key to exit");
Console.ReadKey();
}
}
my executeCommand class:
public class ExecuteCommand
{
public ExecuteCommand()
{
}
public void executeCMDbySSH(ConnectionInfo ConnNfo, string cmdCommand )
{
try
{
using (var sshclient = new SshClient(ConnNfo))
{
//the error appeared here at sshclient.Connect();
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(cmdCommand))
{
cmd.Execute();
Console.WriteLine("Command>" + cmd.CommandText);
Console.WriteLine(cmd.Result);
Console.WriteLine("Return Value = {0}", cmd.ExitStatus);
}
sshclient.Disconnect();
}
}
catch (Exception e) { Console.WriteLine("Error occurred: " + e); }
}
}
and my class where i make conenction:
public class SSHConnection
{
public SSHConnection() { }
public ConnectionInfo makeSSHConnection(string ipAdress, int port, string user, string pwd)
{
ConnectionInfo ConnNfo = new ConnectionInfo(ipAdress, port, user,
new AuthenticationMethod[]{
// Pasword based Authentication
new PasswordAuthenticationMethod(user,pwd),
}
);
return ConnNfo;
}
}
Note* i have not included my XMLParser class because it is not relevant to the question, nor does it have any connections regarding SSH in general.
EDIT
i found out i had compiled the application and it was running in the commandline. Turns out there is no error with the code

Download Email Attachments from Outlook 2007

I am new 2 C# and i have been given a task...
I have to write a C# code to download the email attachments from outlook 2007 to a local drive or any specified location.The program should be in such a way that, given any username and password it should connect to that particular users outlook and download the files specified from a particular from address or subject line.
Any kind of help is appreciated.
So you are using outlook in an Exchange 2007/2010 environment? If yes you cold take a look at EWS.
Go through the following piece of code. It should work!
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
Microsoft.Office.Interop.Outlook.PostItem item = null;
Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null;
//Microsoft.Office.Interop.Outlook.MAPIFolder subFolder = null;
try
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
ns.Logon(null,null,false, false);
inboxFolder = ns.GetDefaultFolder (Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
//subFolder = inboxFolder.Folders["MySubFolderName"];
//folder.Folders[1]; also works
//Console.WriteLine("Folder Name: {0}, EntryId: {1}", subFolder.Name, subFolder.EntryID);
//Console.WriteLine("Num Items: {0}", subFolder.Items.Count.ToString());
for (int i = 1; i <= inboxFolder.Items.Count; i++)
{
item = (Microsoft.Office.Interop.Outlook.PostItem)inboxFolder.Items[i];
foreach (Microsoft.Office.Interop.Outlook.Attachments attachment in item.Attachments)
{
// Process the "attachment" object as per your requirement!
}
//Console.WriteLine("Item: {0}", i.ToString());
//Console.WriteLine("Subject: {0}", item.Subject);
//Console.WriteLine("Sent: {0} {1}", item.SentOn.ToLongDateString(), item.SentOn.ToLongTimeString());
//Console.WriteLine("Categories: {0}", item.Categories);
//Console.WriteLine("Body: {0}", item.Body);
//Console.WriteLine("HTMLBody: {0}", item.HTMLBody);
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
ns = null;
app = null;
inboxFolder = null;
}

WMI invalid Class error (trying to uninstall a software on remote pc)

All,
I am trying to uninstall a software remotely, it is working fine in the test machines, but i got problem in production servers.
test machines i have used windows xp, windows 2003 server,
production machine : windows server 2003.
what could be the cause of this error, any help would be more appreciated.
if you have any other way to unistall a software on the remote PC, please share.
public void Uninstallwithguid(string targetServer, string product,string guid, string version)
{
this.Project.Log(Level.Info, "Starting Uninstall " );
this.Project.Log(Level.Info, "targetServer :" + targetServer );
this.Project.Log(Level.Info, "product :" + product );
this.Project.Log(Level.Info, "guid :" + guid );
this.Project.Log(Level.Info, "version :" + version );
System.Management.ConnectionOptions connoptions = new System.Management.ConnectionOptions();
connoptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;
connoptions.Timeout = new TimeSpan(0, 0, 10); // 10 seconds
System.Management.ManagementScope scope = new System.Management.ManagementScope(#"\\" + targetServer + #"\root\cimv2", connoptions);
scope.Connect();
System.Management.ObjectGetOptions objoptions = new System.Management.ObjectGetOptions();
string test = #"\\" + targetServer + #"\root\cimv2";
string objPath = string.Format("Win32_Product.IdentifyingNumber='{0}',Name='{1}',Version='{2}'",guid, product, version);
System.Management.ManagementPath path = new System.Management.ManagementPath(objPath);
System.Management.ManagementObject moobj = new System.Management.ManagementObject(scope, path, null);
UInt32 res1 = 0;
try
{
res1 = (UInt32)moobj.InvokeMethod("Uninstall", null);
}
catch(Exception ex)
{
this.Project.Log(Level.Error, ex.ToString());
throw ex;
}
if (res1 != 0)
{
this.Project.Log(Level.Error, "Uninstall error " + res1.ToString());
throw new Exception("Uninstall error " + res1.ToString());
}
}
Error Description :
System.Management.ManagementException: Invalid class
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementObject.get_ClassPath()
at System.Management.ManagementObject.GetMethodParameters(String methodName, ManagementBaseObject& inParameters, IWbemClassObjectFreeThreaded& inParametersClass, IWbemClassObjectFreeThreaded& outParametersClass)
at System.Management.ManagementObject.InvokeMethod(String methodName, Object[] args)
Win2003 doesn't have this class installed by default - you have to install it manually from the product disc.

Categories