System.Printing.PrintQueue QueueStatus not updating - wpf

Is there a way to update the print queue status information contained in the PrintQueue object?
I've tried calling Refresh on the PrintQueue object but that doesn't really do anything. For instance, I've turned off the printer and the Control Panel correctly shows the printer as "Offline", however the QueueStatus property, as well as the IsOffline property don't reflect that - no matter how many times I call Refresh on both the PrintServer and the PrintQueue in question.
I've seen examples of how to get status information using WMI queries but I wonder - since these properties are available on the PrintQueue object - whether there is any way to use those.

After try to print your PrintDocument (System.Drawing.Printing), try to check status of printjobs.
First step:
Initialize your printDocument.
Second step:
Get your printer Name From System.Drawing.Printing.PrinterSettings.InstalledPrinters.Cast<string>();
And copy it into your printerDocument.PrinterSettings.PrinterName
Third step:
Try to print and dispose.
printerDocument.Print();
printerDocument.Dispose();
Last step: Run the check in a Task (do NOT block UI thread).
Task.Run(()=>{
if (!IsPrinterOk(printerDocument.PrinterSettings.PrinterName,checkTimeInMillisec))
{
// failed printing, do something...
}
});
Here is the implementation:
private bool IsPrinterOk(string name,int checkTimeInMillisec)
{
System.Collections.IList value = null;
do
{
//checkTimeInMillisec should be between 2000 and 5000
System.Threading.Thread.Sleep(checkTimeInMillisec);
using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PrintJob WHERE Name like '%" + name + "%'"))
{
value = null;
if (searcher.Get().Count == 0) // Number of pending document.
return true; // return because we haven't got any pending document.
else
{
foreach (System.Management.ManagementObject printer in searcher.Get())
{
value = printer.Properties.Cast<System.Management.PropertyData>().Where(p => p.Name.Equals("Status")).Select(p => p.Value).ToList();
break;
}
}
}
}
while (value.Contains("Printing") || value.Contains("UNKNOWN") || value.Contains("OK"));
return value.Contains("Error") ? false : true;
}
Good luck.

Related

Why can not update autocomplete suggestions?

I am using two AutocompleteTextFilters as depended filters. I want the second one filter to change its options depending on the suggestion of the first filter.
I have bind an event listener on the first filter so as when it loose focus it triggers a proccess on the second filter.
The proble is that the second filter never changes its options. I even have setup hardcoded values in case somethig was wrong on my code but no luck.
The code I use is below:
public CreateSubmission(com.codename1.ui.util.Resources resourceObjectInstance, Map<String, ProjectType> projectTypes) {
this.projectTypes = projectTypes;
initGuiBuilderComponents(resourceObjectInstance);
gui_ac_projecttype.clear();
gui_ac_projecttype.setCompletion( this.projectTypes.keySet().toArray( new String[0]) );
gui_ac_projecttype.addFocusListener( new ProjectTypeFocusListener( this ));
gui_ac_steps.setCompletion( new String[]{"t10", "t20"});
}
public void makeSteps (String selection) {
ProjectType projectType = this.projectTypes.get( selection );
if (projectType != null) {
this.selectedProjectType = selection;
int length = projectType.projectSteps.length;
String[] steps = new String[ length ];
for(int i =0; i < length; i ++) {
steps[i] = projectType.projectSteps[i].projectStep;
}
// String[] s = gui_ac_steps.getCompletion();
gui_ac_steps.setCompletion( new String[]{"t1", "t2"} );
gui_ac_steps.repaint();
}
else {
}
}
public class ProjectTypeFocusListener implements FocusListener{
private CreateSubmission parent;
public ProjectTypeFocusListener( CreateSubmission parent ) {
this.parent = parent;
}
#Override
public void focusGained(Component cmp) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void focusLost(Component cmp) {
this.parent.makeSteps (
((AutoCompleteTextField)cmp).getText()
);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
On the above code the initialization happens on "public CreateSubmission" method.
"gui_ac_projecttype" is the first AutocompletionTextField that triggers the whole proccess through it's FocusListener handler (class ProjectTypeFocusListener )
"gui_ac_steps" is the second AutocompleteTextField filter that must change its values. On the code above I initialize it's suggestions to "t10", "t20". Those two values are shown correctly.
Later from iside the FoculListenerHandler's method "ProjectTypeFocusListener.focusLost" I call method "makeSteps" which sets the suggestion options to "t1", "t2 and then I repaint the component. These two last values are never shown. It remains on the first values "t10", "t20".
The Strange thing is that in debugger when I ask gui_ac_steps.getCompletion(); to see the current options ( the code that is commentd out into makeSteps method) I get the correct values "t1", "t2".
But on the screen it keeps showing "t10", "t20".
any help is aprreciated.
You shouldn't do anything "important" in a focus listener. Especially not with a text field. They are somewhat unreliable because the text field switches to native editing and in effect transfers the focus there. The problem is that some events are delayed due to the back and forth with the native editing so by the time the focus event is received you've moved on to the next field.
Try something like this for this specific use case https://www.codenameone.com/blog/dynamic-autocomplete.html

how do i get imagedownloadservice to work with multilist component in codenameone?

I have created a multi list in GUI Designer. I am setting the model as below
#Override
protected boolean initListModelMultiIssueList(List cmp) {
fetchIssues(cmp);
if (issueVector != null ) {
cmp.setModel(new DefaultListModel(issueVector));
System.out.println(cmp);
}
return true;
}
void fetchIssues( List c){
//fetch issues based on the searchquery hash
//first thing is to create the query from the hash
System.out.println("Starting to fetch results");
try{
java.util.List<ServiceRequest> serviceRequests = ServiceRequest.getServiceRequests(formQuery(searchQuery),true);
//we need to now populate the issueVector
//with the data
System.out.println(serviceRequests.toString());
if (issueVector != null ) {
issueVector.clear();
} else {
issueVector = new Vector();
}
int index = 0;
for (ServiceRequest serviceRequest : serviceRequests) {
Hashtable hIssue = new Hashtable();
hIssue.put("id",serviceRequest.getHref());
//System.out.println(hIssue);
ImageDownloadService.createImageToStorage(serviceRequest.getRequestPictureURL().toString(),
c, index, "icon",
"service-icon-"+ index ,null);
//hIssue.put("icon", serviceRequest.getRequestPictureURL().toString());
//System.out.println(hIssue);
//reverse geocode the location
Double x = new Double(0.0);
x=new Double(serviceRequest.getRequestLocationLatitude());
Double y = new Double(serviceRequest.getRequestLocationLongitude());
String location=reverseGeocode(x, y);
hIssue.put("location", location);
//System.out.println(hIssue);
Service service = serviceRequest.loadService();
hIssue.put("service", serviceRequest.loadService().getName().toString());
hIssue.put("reportedOn",serviceRequest.getCreatedAt().toString());
//System.out.println("Final hIssue" + hIssue.toString());
issueVector.add(hIssue);
index=index+1;
System.out.println(issueVector);
}
}catch (Exception e){
System.out.println("Error loading search results");
System.out.println(e);
}
}
The icon in the multi list GUI design has been set to the appropriate property. ImageDownloadService does download the image files but then it does not display in the list as expected. What am I doing wrong?
Its possible that the image is downloaded before the entry is available. Although its hard to tell with the code and without a clear explanation of the symptoms.
You need to first create the model and set it to the list (ideally with a blank placeholder image so the list doesn't "jump"). Then you need to loop over the list and invoke the image download service, otherwise it might return before the data is in the list and fail! This can happen if the image is already in cache so its very likely to fail fast in that case.

Application Won't 'new' when called

I am calling a new xaml application with some parameter inputs using the word new, but it does not seem to be working. I am also attempting to use onclosing to set it to null. When launching it for the first time it works (everything is new), but launching it after it finished, it seems to continue its previous state (brings to finished score board). Here is the snipplet of the code . . .
quizUI = new QuizzUI.MainWindow(App.User, true);
quizUI.Closed += (o, s) =>
{
quizUI = null;
};
quizUI.LaunchQuiz(qSet);
this is hooked to a button event. does anyone know how i can absolutely new this object's state every time? the two paramters are user's info and second one is to shortcut without prompt screen/loading screen.
Here is the code for QuizzUI.MainWindow.LaunchQuizz:
public void LaunchQuiz(GameQuizzSet quiz)
{
this.Hide();
quizz = new QuizzContainer()
{
QSet = quiz,
};
if (isShortCutted)
{
bool? diag = quizz.ShowDialog();
if (diag.HasValue)
{
quizz.Close();
Close();
}
}
else
{
quizz.ShowDialog();
this.Show();
}
}
the QuizzUI.MainWindow allows the user to select their profile and which quiz to execute.

OnPropertyChanged reaction different the first time and the second time

I have got a collection of viewModels(InputViewModel) in an other viewModel(ScenarioManager).
each InputviewModel has an instance of a Class(RestOfInput) which contains properties able to raise the OnPropertyChanged.
when one of these properties changes the event is handled by this method (in InputViewModel) :
public void TestAfterChanges(object sender, PropertyChangedEventArgs e)
{
MessageBox.Show("not ref");
bool isInTheList = false;
RestOfInput roi = sender as RestOfInput;
string prop = e.PropertyName;
if (prop!="NameFile")
{
Difference d = new Difference();
d.Length = prop;
d.Value1 = reference.RoI.getValueByPropertyName(prop);
d.Value2 = roi.getValueByPropertyName(prop);
foreach (Difference diff in _ListOfDifferences)
{
if (diff.Length==prop)
{
if ( (Math.Abs(d.Value2-d.Value1)>0.001*d.Value1))
{
//replace by le new one
_ListOfDifferences.Insert(_ListOfDifferences.IndexOf(diff), d);
_ListOfDifferences.Remove(diff);
}
else
{
//if change make the field value equal to the ref then remove from difference list
_ListOfDifferences.Remove(diff);
}
isInTheList = true;
}
}
if ((Math.Abs(d.Value2 - d.Value1) > 0.001 * d.Value1) && isInTheList==false)
{
_ListOfDifferences.Add(d);
}
}
}
this method gives just a summary of the differences between this particular case and the reference case.
Now if the reference case changes I have to update all the cases and the event is handled
in ScenarioManager :
public void refCaseChanging(object sender, PropertyChangedEventArgs e)
{
MessageBox.Show("ref");
string propname = e.PropertyName;
foreach (InputViewModel item in _casesList)
{
if (item!=inpVM)
{
item.RoI.OnPropertyChanged(propname);
}
}
}
inpVM is the reference case.
Then I have this behavior :
-if I change a field in a case which is not the reference case : everything is ok.
-if I change a particular field in the reference case : the first time, everything is ok.
But the second time, only the reference case and the first case (in the collection) which is not the reference case are updated>
It is like the foreach loop is broken..
Any explications.
If the message is not clear please tell me ( not easy to explain ;) )
An exception could explain that processing stops (although one expects that it would be caught and displayed somewehre).
Have you tried to ask VS to halt your program when an exception is thrown ? (if you have never done this before, go to Debug / Exceptions and check the check box for CLR exceptions)

Large method causing silverlight application to go into "Not responding" state

I am working on an application that plays videos through the silverlight MediaElement object.
I have a large method which is responsible for the following
Opens a FileInfo item on the local file path of the video and strips the file name to get the first portion of the filename which we use as part of the license acquisition process
Sets the LicenseAcquirer on the MediaElement
Sets the Source property of the MediaElement
When this method is called, it actually causes the application to go into a "Not reponding" state for a couple of seconds. How do I avoid this? I have tried putting this all into a background worker but I have to invoke the UI thread for almost all of the calls and this didnt help it seemed to actually make things slower.
I have a busy box that shows while this all happens but that actually stops reporting progress in those seconds where the application is not responding. I understand why this is happening - a lot of work happening on the main UI thread, but how do I avoid this?
This is the code that is causing the trouble:
private void SetupMediaElement(String mediaElementType)
{
Messenger.Default.Send("Loading video...", "SetNowWatchingVideoBusyBoxText");
Messenger.Default.Send(true, "SetNowWatchingVideoBusyBox");
try
{
if (_mainMediaElement != null)
{
VideoItem vi = CurrentSession.NowPlayingVideoItem;
if (vi != null)
{
CurrentVideoItem = vi;
MustShowImage = true;
if (vi.ID != string.Empty)
{
String mediaId = String.Empty;
if (vi.LocalFilePath != DEMOVIDEOPATH)
{
if (vi.LocalFilePath != String.Empty)
{
var fi =
new FileInfo(vi.LocalFilePath);
if (fi.Exists)
{
mediaId = fi.Name.Substring(fi.Name.LastIndexOf('-') + 1,
(fi.Name.LastIndexOf('.') -
(fi.Name.LastIndexOf('-') + 1)));
}
}
else
{
Debug.WriteLine("localFilePath is empty");
}
Debug.WriteLine("MediaId = " + mediaId +
", SessionId = " +
CurrentSession.LoggedOnUser.SessionId +
",Ticket = " +
CurrentSession.LoggedOnUser.Ticket);
string licenseURL = GetLicenseURL(mediaId, CurrentSession.LoggedOnUser.SessionId,
CurrentSession.LoggedOnUser.Ticket);
if (licenseURL != string.Empty)
{
var la = new LicenseAcquirer
{
LicenseServerUriOverride
=
new Uri(
licenseURL)
};
la.AcquireLicenseCompleted += la_AcquireLicenseCompleted;
_mainMediaElement.LicenseAcquirer = la;
}
var fileInfo = new FileInfo(vi.LocalFilePath);
string playURL = #"file://" +
Path.Combine(CoreConfig.HOME_FULL_PATH, fileInfo.Name);
playURL = playURL.Replace("\\", #"/");
VideoURL = playURL;
}
else
{
VideoURL = vi.LocalFilePath;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
_totalDurationSet = false;
TotalTime = FormatTextHoursMinutesSecond(_mainMediaElement.NaturalDuration.TimeSpan);
SetSliderPosition();
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
else
{
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
VideoURL = DEMOVIDEOPATH;
Messenger.Default.Send(false, "SetNowWatchingVideoBusyBox");
}
}
Thanks
EDIT:
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.
You should do some diagnostics to determine which line(s) are truely costing all that time, its unlikely that amount of time is spread evenly across the whole function.
Place that line (or lines) in a background thread (hopefully that line doesn't need to be on the UI thread).
So it turns out that the method posted above is NOT the cause of the delay - that code executes in under a second. The problem comes in when the media element's source is set and it reads the file to the end - large files take time and this is the delay. Am opening a new question based on this.

Resources