I have been forced to use the RawPrinterHelper class to print to a thermal printer because the PrintDocument method has proven unfit for POS printing.
I now need to check the status of the printer prior to printing to be sure that it is, online and ready to print. I have been able to successful check attributes from Win32_Printer. I can see properties such as PrinterStatus, changing from 3, to a 2 or a 1 when out of paper or tray is open. This is great.
My question is, which properties should indicate it is O.K. to print? There must be more than just checking if PrinterStatus is idle (3).
private bool ReadyCheck(string printerName)
{
bool ready = false;
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
try
{
foreach (ManagementObject printer in coll)
{
// Print status = 3, idle and ready to print
string status = printer.Properties["PrinterStatus"].Value.ToString();
string extendedPrinterStatus = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
// What else means printer is ready?
if (status.Trim() == "3")
ready = true;
}
}
catch (ManagementException ex)
{
Console.WriteLine(ex.Message);
}
}
return ready;
}
Edit:
#vendettamit Sorry I didn't ask very well. For instance, Idle (3) indicates it's OK to print. I am wondering if there are more which also indicate it's OK to print such as; Printing (4), WarmUp (5), ect, or is Idle (3) the only time you should send the next print job? Thanks
Below are the values that you can take into account to check if It's ready to print:
Other (1)
Unknown (2)
Idle (3)
Printing (4)
Warmup (5)
Stopped Printing (6)
Offline (7)
Also a note from Remarks on MSDN documentation for Win32_Printer-
If you are retrieving PrinterStatus = 3 or PrinterState = 0, the printer driver may not be feeding accurate information into WMI. WMI retrieves the printer information from the spoolsv.exe process. It is possible the printer driver does not report its status to the spooler. In this case, Win32_Printer reports the printer as Idle.
**//check printer is online**
private static bool IsOnline(ManagementBaseObject printer)
{
bool isOnlineprinter = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var ResultPrinter01 = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
var ResultPrinter02 = printer.Properties["PrinterState"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(no internet connection or printer switched off):PrinterState
if (ResultPrinter02 == "128"|| ResultPrinter02=="4096")
{
isOnlineprinter = false;
}
////printer is initializing....
//if (ResultPrinter02 == "16")
//{
// isOnlineprinter = false;
//}
//(no internet connection or printer switched off):ExtendedPrinterStatus
if (ResultPrinter01 == "7")
{
isOnlineprinter = false;
}
}
return isOnlineprinter;
}
**//check for out of paper**
private static bool IspaperOK(ManagementBaseObject printer)
{
bool PaperOK = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var PaperStatus = printer.Properties["PrinterState"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)16 = Out of Paper
//(PrinterState)5 = Out of paper
//(PrinterState)4 = paperjam
//(PrinterState)144 = Out of paper
if ((PaperStatus == "5") || (PaperStatus == "16")||(PaperStatus=="144"))
{
PaperOK = false;
}
}
return PaperOK;
}
**//Verify still printing state or not**
private static bool Isprinting(ManagementBaseObject printer)
{
bool Isprintingnow = false;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var printing01 = printer.Properties["PrinterState"].Value.ToString();
var printing02 = printer.Properties["PrinterStatus"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)11 = Printing
//(PrinterState)1024 = printing
//(PrinterStatus)4 = printing
if (printing01 == "11" || printing01 == "1024" || printing02=="4")
{
Isprintingnow = true;
}
}
return Isprintingnow;
}
**//check for error (Printer)**
private static bool IsPrinterError(ManagementBaseObject printer)
{
bool PrinterOK = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var PrinterSpecificError = printer.Properties["PrinterState"].Value.ToString();
var otherError = printer.Properties["ExtendedPrinterStatus"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
//(PrinterState)2 - error of printer
//(PrinterState)131072 - Toner Low
//(PrinterState)18 - Toner Low
//(PrinterState)19 - No Toner
if ((PrinterSpecificError == "131072")||(PrinterSpecificError == "18")||(PrinterSpecificError == "19")||(PrinterSpecificError == "2")||(PrinterSpecificError == "7"))
{
PrinterOK = false;
}
//(ExtendedPrinterStatus) 2 - no error
if (otherError=="2")
{
PrinterOK = true;
}
else
{
PrinterOK = false;
}
}
return PrinterOK;
}
**//check Network or USB**
private static bool IsNetworkPrinter(ManagementBaseObject printer)
{
bool IsNetwork = true;
PrinterNative.PrinterNative.PrinterNative printerNative = new PrinterNative.PrinterNative.PrinterNative();
var PrinterName = printerNative.GetPrinterName();
var PrinterNameProperty = printer.Properties["DeviceId"].Value.ToString();
var network = printer.Properties["Network"].Value.ToString();
var local = printer.Properties["Local"].Value.ToString();
if (PrinterNameProperty == PrinterName)
{
if (network == "True")
{
IsNetwork = true;
}
if (network == "True" && local == "True")
{
IsNetwork = true;
}
if (local == "True" && network=="False")
{
IsNetwork = false;
}
}
return IsNetwork;
}
//(PrinterState)16 = Out of Paper
//(PrinterState)5 = Out of paper
//(PrinterState)4 = paperjam
//(PrinterState)144 = Out of paper
//(PrinterState)4194432 = Lid Open
//(PrinterState)4194448 = Out of paper/Lid open
//(PrinterState)4096= Offline
//(PrinterState)1024= Printing
//(PrinterState)128= Printer is offline
Related
I would like to use gstreamer to display udpsrc video, but it does not work.
On the command line it works fine.
"Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(msg)" will always be False.
Please help me...
send command:
gst-launch-1.0.exe autovideosrc ! videoconvert ! vp8enc deadline=1 ! rtpvp8pay pt=96 ! udpsink port=5200 host=<MY-LOCALIP> async=false
recv command:
gst-launch-1.0.exe udpsrc port=5200 caps="application/x-rtp,payload=(int)96" ! rtpjitterbuffer latency=10 ! rtpvp8depay ! avdec_vp8 output-corrupt=false ! videoconvert ! autovideosink
csharp program:
private void CreatePipeLine()
{
if(pipeline != null)
{
pipeline.SetState(State.Null);
islive = false;
return;
}
pipeline = new Pipeline("pipeline");//"playback");
var udpsrc = Gst.ElementFactory.Make("udpsrc", "source");
udpsrc["port"] = 5200;
//udpsrc["caps"] = "application/x-rtp,payload=96";
var jitter = Gst.ElementFactory.Make("rtpjitterbuffer", "jitter");
jitter["latency"] = 10;
var depay = Gst.ElementFactory.Make("rtpvp8depay", "depay");
var avdec = Gst.ElementFactory.Make("avdec_vp8", "avdec");
avdec["output-corrupt"] = false;
var convert = Gst.ElementFactory.Make("videoconvert", "convert");
var capsRTP = Gst.Global.CapsFromString("application/x-rtp,payload=96");
var mAppSink = new AppSink("appsink");
mAppSink["emit-signals"] = true;
mAppSink["caps"] = capsRTP;
mAppSink.NewSample += OnNewSample;
ink = Gst.ElementFactory.Make("autovideosink", "ink");
pipeline.Add(udpsrc, jitter, depay, avdec, convert, mAppSink); //ink);
udpsrc.Link(jitter);
jitter.Link(depay);
depay.Link(avdec);
avdec.Link(convert);
convert.Link(ink);
Bus bus = pipeline.Bus;
bus.AddSignalWatch();
bus.Message += OnBusMessage;
bus.EnableSyncMessageEmission();
bus.SyncMessage += new SyncMessageHandler(OnBusSynMessage);
/*
VideoSink = new AppSink(ink.Handle);
VideoSink.Drop = true;
VideoSink.MaxLateness = (1000 / 30) * 1000000;
VideoSink.MaxBuffers = 1;
VideoSink.Qos = true;
VideoSink.EnableLastSample = false;
VideoSink.Caps = Gst.Caps.FromString("video/x-raw,format=RGBA");
pipeline.Bus.EnableSyncMessageEmission();
pipeline.Bus.AddSignalWatch();
pipeline.Bus.SyncMessage += OnBusSynMessage;
pipeline.Bus.Message += OnBusMessage;
*/
pipeline.SetState(State.Null);
var ret = pipeline.SetState(State.Ready);
}
private void OnBusSynMessage(object o, SyncMessageArgs sargs)
{
Gst.Message msg = sargs.Message;
if (!Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(msg)) { return;}
Element src = msg.Src as Element;
if(src == null) { return;}
try { src["force-aspect-ration"] = true;}
catch(PropertyNotFoundException) { }
Element overlay = ((Gst.Bin)src).GetByInterface(VideoOverlayAdapter.GType);
if(overlay == null)
{
System.Diagnostics.Debug.WriteLine($"Overlay is null");
return;
}
_adapter = new VideoOverlayAdapter(overlay.Handle);
_adapter.WindowHandle = _windowHandle;
_adapter.HandleEvents(true);
_isRender = true;
}
Tried this method during playback, but "sample" was null.
var sink = VideoSink;
if(sink == null) { return; }
Sample sample = sink.TryPullSample(5000);
if(sample == null)
{
return;
}
Reference Site:
https://github.com/vladkol/gstreamer-netcore/tree/master/samples/AvaloniaPlayer
how to use application/x-rtp binding with gstreamer-sharp?
I've changed the caps location to udpsrc,
I have tried autovideosink, etc.
Gst.Video.Global.IsVideoOverlayPrepareWindowHandleMessage(msg)
will be not null only if you have autovideosink in your pipeline. This is because a Window creation request will be created if you have Window "VideoSink" like autovideosink, glvideosink... which implements GstVideoOverlay. (https://gstreamer.freedesktop.org/documentation/opengl/glimagesink.html?gi-language=c#hierarchy see implemented interfaces)
pipeline.Add(udpsrc, jitter, depay, avdec, convert, ink);
Why not setting your pipeline to playing instead of ready ?
var ret = pipeline.SetState(State.Playing);
I'm trying to print a ticket using .NET POS but i'm not able to get the Default printer.
PosPrinter defaultPrinter = await PosPrinter.GetDefaultAsync();
I also tried this:
string deviceSelector = PosPrinter.GetDeviceSelector();
PosPrinter printer = await PosPrinter.FromIdAsync(deviceSelector);
I have my thermal printer configured as default.
Have you tried the way using the PosExplorer and the printer name? Snippet:
public PosPrinter GetPrinterByName(System.Windows.Forms.Form mainForm, string printerName)
{
PosPrinter printer = null;
PosExplorer explorer = new PosExplorer(mainForm);
DeviveCollection printers = explorer.GetDevices(DeviceType.PosPrinter);
if (printers != null && printers.Count > 0)
{
for (int i = 0; i < printers.Count; i++)
{
if(0 == string.Compare(printerName, printers[i].ServiceObjectName))
{
printer = printers[i];
break;
}
}
}
return printer;
}
I'm having the difficulties to use watin bringtofront function. It just doesn't bring my browser to the front - someone please shed me some light on it.
Here's my code:
public bool GenerateReport(string rptPath, string rptName)
{
var popupTitle = new Regex("Crystal Reports ActiveX");
var popUpBrowser = WatiN.Core.Browser.AttachTo<IE>(Find.ByTitle(popupTitle));
if (popUpBrowser != null)
{
var result = false;
try
{
popUpBrowser.AutoClose = false;
popUpBrowser.BringToFront();
popUpBrowser.ShowWindow(NativeMethods.WindowShowStyle.ShowMaximized);
popUpBrowser.DialogWatcher.CloseUnhandledDialogs = false;
result = ExportPdfFile(popUpBrowser, rptPath + rptName + RptExt);
}
finally
{
popUpBrowser.Close();
}
return result;
}
return false;
}
For load testing purposes I need to simulate multiple users trying to login to a system at the same time. I have code written by another developer that can send a login request to the system. With an ok login it will also return other information in xml.
I've tried using Parallel.ForEach, but dont have any real experience with parallel programming:
Parallel.ForEach(clientList, client =>
{
RunTest(client);
});
public void RunTest(object data)
{
if (!(data is IGprsClient))
{
return;
}
_noRunningTests += 1;
IGprsClient gprsClient = data as IGprsClient;
DateTime startTime = DateTime.Now;
Log(gprsClient.Id, "Test started.");
bool result = gprsClient.StartTest(20000);
DateTime endTime = DateTime.Now;
TimeSpan diff = endTime - startTime;
if (result == false)
{
Log(gprsClient.Id, "Test failed.");
}
Log(gprsClient.Id, "Test took {0}ms. ", (int)diff.TotalMilliseconds);
_noRunningTests -= 1;
}
override public bool StartTest(int timeout)
{
_testStarted = true;
try
{
LogDebug("Trying to connect.");
_client = new TcpClient(ipAddress, port);
LogDebug("Connected.");
bool result = false;
//Todo: insert testcase into client
switch (TestCaseName)
{
case "LoginTEST":
var testCase = new LoginTEST(this);
result = testCase.Execute(user, pwd, phoneNum);
break;
default:
Log("Unknown test case: " + TestCaseName);
break;
}
_client.Close();
return result;
}
catch (Exception ex)
{
if (_client != null)
_client.Close();
Log(ex.Message);
return false;
}
}
Which in turn will send the request and read the response.
public bool Execute(string user, string pwd, string phoneNum)
{
SendDataListRequest(userId);
string requiredDataResponse = Client.ReadMsg();
return true;
}
Run test will send a request and reads the message like so:
public string ReadMsg()
{
int msgLength = -1;
var stream = _client.GetStream();
while (_testStarted)
{
int b = stream.ReadByte();
if (b == -1)
{
return "";
}
else if (b == 0x02 || msgLength == -1)
{
while (b != 0x02 && _testStarted)
{
b = stream.ReadByte(); // Finds the start token
if (b == -1)
{
return "";
}
}
msgLength = 0; // Starts collecting data
}
else if (b == 0x03)
{
byte[] encryptedMsg = Convert.FromBase64String(
Encoding.UTF8.GetString(byteBuffer, 0, msgLength));
byte[] decryptedMsg = SttCipher.DecryptMessage(encryptedMsg);
MemoryStream ms = new MemoryStream(decryptedMsg);
GZipStream gZipStream = new GZipStream(ms, CompressionMode.Decompress, true);
var bufLen = ReadAllBytesFromStream(gZipStream, decompressedBuffer);
gZipStream.Close();
string completeMsg = Encoding.UTF8.GetString(decompressedBuffer, 0, bufLen);
if (completeMsg.Length < 500)
LogDebug("Received XML-data:\n{0}", completeMsg);
else
LogDebug("Received XML-data: {0} bytes\n{1}...", completeMsg.Length, completeMsg.Substring(0, 500));
return completeMsg;
}
else
{
if (byteBuffer.Length <= msgLength)
{
throw new Exception("XML message too long!");
}
byteBuffer[msgLength] = (byte)b;
msgLength++;
}
}
return "";
}
Running one client is fine and will wait for the response. The issue is with several clients, the responses gets cut off. Leaving me with unclosed xml in the response.But I cant't figure out why. Does anyone have a reasonable explanation and/or a solution or a better way of doing it?
I'm wanting to create a new Hyper-V VM with a determined amount of RAM, network card, number of processor cores, and attach a VHD file to the IDE controller.
The problem is that the Msvm_ResourceAllocationSettingData is not very easy to work with. The code I'm using doesn't work (this is code to attach a VHD to an existing VM, however I would also like to use it when creating a new VHD too).
public void AttachVhd(IdeChannel ideChannel, String vhdPath) {
// Get VirtualSystemSettingData
ManagementObject vssd = this.GetVirtualSystemSettingData();
// Get the IDE Controller
ManagementObject ideController = this.GetResourceAllocationSettingData(ResourceType.IdeController, ResourceSubType.IdeController);
// Create synthetic disk:
ManagementObject syntheticDiskRasd = this.GetResourceAllocationSettingData(ResourceType.Disk, ResourceSubType.DiskSynthetic);
syntheticDiskRasd["Parent"] = ideController.Path;
syntheticDiskRasd["Address"] = ideChannel == IdeChannel.Primary ? "0" : "1";
this.AddVirtualSystemResources(syntheticDiskRasd);
// Attach it
ManagementObject vhdRasd = this.GetResourceAllocationSettingData(ResourceType.StorageExtent, ResourceSubType.Vhd); ;
vhdRasd["Parent"] = syntheticDiskRasd.Path;
vhdRasd["Connection"] = new String[] { vhdPath };
this.AddVirtualSystemResources( vhdRasd );
// Cleanup
vhdRasd.Dispose();
syntheticDiskRasd.Dispose();
ideController.Dispose();
vssd.Dispose();
}
private ManagementObject GetResourceAllocationSettingData(ResourceType resourceType, ResourceSubType resourceSubType)
{
String desiredSubType = ResourceSubTypeStrings.GetString(resourceSubType); // Scout.Common.Extensions.GetDescription( resourceType );
using(ManagementObjectCollection settingsDatas = _vm.GetRelated("Msvm_VirtualSystemSettingData"))
foreach(ManagementObject settingData in settingsDatas)
{
using(ManagementObjectCollection rasds = settingData.GetRelated("Msvm_ResourceAllocationSettingData"))
foreach(ManagementObject rasd in rasds)
{
ResourceType rasdResourceType = (ResourceType)(UInt16)rasd["ResourceType"];
String rasdResourceSubType = (String)rasd["ResourceSubType"];
String rasdOtherType = (String)rasd["OtherResourceType"];
if( rasdResourceType == resourceType && rasdResourceSubType == desiredSubType )
{
return rasd;
}
}
}
return null;
}
private void AddVirtualSystemResources(ManagementObject rasd)
{
using (ManagementObject vmService = HyperV.GetManagementService())
{
ManagementBaseObject inParams = vmService.GetMethodParameters("AddVirtualSystemResources");
inParams["TargetSystem"] = _vm;
inParams["ResourceSettingsData"] = rasd.GetText(TextFormat.CimDtd20);
ManagementBaseObject outParams = vmService.InvokeMethod("AddVirtualSystemResources", inParams, options: null);
String[] addedResources = (String[])outParams["NewResources"];
OperationReturnCode returnValue = (OperationReturnCode)(UInt32)outParams["ReturnValue"];
if (returnValue == OperationReturnCode.JobStarted)
{
String jobPath = (String)outParams["Job"];
HyperV.MonitorJob(jobPath);
}
else if (returnValue == OperationReturnCode.Completed)
{
}
else
{
throw new ApplicationException( returnValue.ToString() );
}
}
}
Rather than find your problem, can I point you to an example that works?
See WmiCalls.DeployVirtualMachine in my Apache CloudStack Hyper-V plugin
Post a comment if you need additional detail, and I will update the answer.