WMI PrinterStatus always 0 - c#

I want to check if the printer has a paper or not, for this I use WMI to pick up the printer and use PrinterStatus, the problem is that it always returns 0 ("Unknow"), and I don't understand the reason, my code is as follows:
public int ImpresoraStatus()
{
var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer WHERE Name = \"KPOS_80 Printer\"");
foreach (var printer in printerQuery.Get())
{
int status = (int)printer["PrinterStatus"];
return status;
}
return 404;
}
Any improvements or something I'm missing?

It is a known issue AFAIK. You probably need to try printing something first and then check the status.
See: Not Able to Monitor Printers' States and Statuses

Related

Can't retrieve application rules with HNetCfg.FwMgr + AuthorizedApplications

I'm trying to retrieve all authorized applications with C#:
ArrayList result = new ArrayList();
INetFwMgr firewallManager = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
Console.WriteLine(app.Name);
}
The AuthorizedApplications is empty, but in Control Panel I can see many rules, enabled or not:
What was wrong? I tried other profiles, e.g DOMAIN/STANDARD, same result.
console.write(result); check if forEach method brings you all aplications authorized with C# should be a loop instead
foreach (INetFwAuthorizedApplication app in
firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications)
{
Console.WriteLine(app.Name);
}e.g for(INetFwAuthorizedApplication app in
firewallManager.LocalPolicy.CurrentProfile.AuthorizedApplications){console.log(app.Name);} Are you sure Name is the correct value?, shouldn't be app.name?
It seems you can iterate the app list, but you are not finding the correct name for app. Use name instead Name. Try console.WriteLine(app.name) or console.WriteLine(app.GetName)
Maybe try this:
public List<Object>(String name){
ArrayList result = new ArrayList();
INetFwMgr firewallManager =
(INetFwMgr)Activator.CreateInstance
(Type.GetTypeFromProgID("HNetCfg.FwMgr"));
foreach (INetFwAuthorizedApplication app in
firewallManager.LocalPolicy
.CurrentProfile.AuthorizedApplications)
{
if(app.Name == _name){
app.Name = name;
Console.WriteLine(app.Name);
}
}
return result;
}

How to point to the correct Store in Outlook automation by C#?

I have a lot of VBA automation that interlinks an Outlook and Word solution; it is fine, but time is inexorable... so, I'm start to decorating and extending that old solution, wraping it with C#/VS2017.
Through a conventional Winform I can choose my patients, and from this action I do a lot of actions, including open the correct Outlook contact; that's the problem, because I can't get the correct Store; the patients.pst, depending on the machine, may be the 1st, 2nd, 3rd...
In VBA I do this:
WhichStoreNameToPointAt="patients"
Set myNamespace = myolApp.GetNamespace("MAPI")
For i = 1 To myNamespace.Stores.Count Step 1
If myNamespace.Stores.item(i).DisplayName = WhichStoreNameToPointAt Then
intOutlookItemStore = i
End if
End If
Set myFolderPatients = myNamespace.Stores.item(intOutlookItemStore).GetDefaultFolder(olFolderContacts)
And it always functions like a charm.
In C# I tried a lot of variations, and could not point to the correct store:
public void OpenPatientContact(string patientName)
{
Outlook.Store whichStore = null;
Outlook.NameSpace nameSpace = OlkApp.Session;
int i = 1;
foreach (Outlook.Folder folder in nameSpace.Folders)
{
bool p = false;
if (whichStoreNameToPointAt == folder.Name)
{
p = true;
whichStore = folder.Store;
//Correct Store selected; I can tell because of this watch:
//whichStore.displayname == whichStoreNameToPointAt
}
i++;
if (p)
break;
}
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
// The problem is below; always the first Store
Outlook.ContactItem contact = (Outlook.ContactItem)contactItemsOlk
.Find(string.Format("[FullName]='{0}'", patientName)); //[1];
if (contact != null)
{
contact.Display(true);
}
else
{
MessageBox.Show("The contact information was not found.");
}
}
Unfortunately, it keeps pointing ever to the same first Store, the one that has no patients...
If I change the Store order I can get past this and test other stuff, but of course it is not the right way.
Any other heads/eyes to see the light?
TIA
While seated writing the question, looking at a yellow rubber duck - and a lot of other stuff that belongs to my 1 yo daughter ;), I realized that whichStore.Session.GetDefaultFolder is a little strange in this context. I only changed this
var contactItemsOlk = whichStore.Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
To that:
var contactItemsOlk = whichStore.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderContacts).Items;
Voilá! Magic happens with C# too!
Session returns the default NameSpace object for the current session.
PS: yellow rubber duck; guys of The Pragmatic Programmer really knows some secrets and tricks ;)
Thanks Thomas and Hunt!

USB Printing for DOT Matrix POS printer

I was trying to print to an usb printer using usbmanager, the App can detect the printer device but when i run it doesnt print. there are no errors and all passing data is ok.
Printer : Bixolon SRP 275III
Type: USB
private async void printReciept()
{
UsbManager m_usbManager;
m_usbManager = (UsbManager)Application.Context.GetSystemService(Context.UsbService);
var deviceList = m_usbManager.DeviceList;
IEnumerable<UsbDevice> deviceIterator = deviceList.Values.AsEnumerable();
UsbDevice m_usbdevice = null;
if (deviceIterator.Count() > 0)
{
var device = deviceIterator.ElementAt(0);
m_usbdevice = device;
string ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
var mPermissionIntent = PendingIntent.GetBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
m_usbManager.RequestPermission(m_usbdevice, mPermissionIntent);
UsbDeviceConnection deviceConnection = null;
try
{
using (var usbInterface = m_usbdevice.GetInterface(0))
{
using (var usbEndpoint = usbInterface.GetEndpoint(0))
{
mEndPoint = usbEndpoint;
deviceConnection = m_usbManager.OpenDevice(m_usbdevice);
byte[] bytesHello = Encoding.UTF8.GetBytes("Hello");
deviceConnection.BulkTransfer(usbEndpoint, bytesHello, bytesHello.Length, 0);
}
}
}
catch
{
}
}
}
You are sending the string to be printed directly to the bulk endpoint, or actually you are doing bulk transfer to the first endpoint found without knowing any of it's characteristics? I think it is a bit more complex than that.
First try to find out whether your printer supports USB printing class or some proprietary implementation. You can do this easily e.g. by connecting the printer to Windows PC and looking from the device manager, usbdeview or some other similar application.
If it supports printing class, read this document and implement your driver based on that (or use the one you may already have in Android). If it only supports proprietary implementation, you need to get the specifications for it or do some reverse engineering.
You may need to learn about PCL which may also be needed.

Why get wrong total page of N-Up printing using Win32_PrintJob/C#?

I'm working on a program in C# to pause and get the total page count when printing, here is main code:
string wql = "SELECT * FROM Win32_PrintJob";
ManagementObjectCollection mos;
Dictionary<uint,short> checkedJobs = new Dictionary<uint,short>();
while (true)
{
Thread.Sleep(SleepTime);
try
{
mos = new ManagementObjectSearcher(wql).Get();
if (mos != null && mos.Count > 0)
{
foreach (ManagementObject mo in mos)
{
if (mo != null)
{
uint jobId = ProcessJob(mo);
if (!checkedJobs.ContainsKey(jobId))
checkedJobs.Add(jobId, 0);
}
}
}
// ...
}
}
It works fine with normal task.But in N-Up printing ,when I print more than one slides in one page(N Slides-In-One Page), it comes wrong, I can not get the right total count to print.
Is there anyone who ever meet this question~please help,many thanks
Your question is similar to another question (see my answer there and follow the link for more info) but perhaps it's different enough to warrant a different answer here.
Basically NUP is not supported by all print drivers. The application you're using may be checking the DEVMODE (or ignoring it) and handling NUP by itself rather than letting the Spooler handle it.
As I said in the other answer, the Windows page count can't be relied on for all apps and drivers. This might improve with the new XPS print system, but for old apps and drivers the only way to get a reliable page count is to parse the print spool file.

Getting all startup items?

Ok, I guess I'm having a brain fart here and cant find my way out of it. What I'm trying to accomplish is to list all startup items (applications, processes, etc) and display them on a form (like what you get with msconfig.exe). I thought this code would do it:
private List<StartupItems> getStartupItems()
{
try
{
ManagementClass cls = new ManagementClass("Win32_StartupCommand");
ManagementObjectCollection coll = cls.GetInstances();
List<StartupItems> items = new List<StartupItems>();
foreach (ManagementObject obj in coll)
{
items.Add(
new StartupItems
{
Command = obj["Command"].ToString(),
Description = obj["Description"].ToString(),
Name = obj["Name"].ToString(),
Location = obj["Location"].ToString(),
User = obj["User"].ToString()
});
}
return items;
}
catch (Exception ex)
{
_message = ex.ToString();
_status = false;
return null;
}
But all that gets are the enabled ones with my username. What I'm trying to get is all items, either my username or system, all the enabled ones and all the disabled ones as well (just like msconfig). I've done tons of searching and cannot find anything really any different than what I'm using.
Have you considered reading directly from the registry?
One alternative would be to run autorunssc (it's the command-line version of autoruns) in the background and read its response.

Categories