UWP C++ PrintTask PreviewPage Duplication Error - c++

I'm currently working on a print task within my app to print a couple of pages to either printer or PDF. I'm using the microsoft printsample as the basis for my code and it all works with the exception of one thing. When I change printers, the printer preview creates duplicate pages of the content I sent to the printer preview.
Here is all my code that handles the printing. Does anyone know what might be causing the print UI to create duplicate preview pages when changing between printers and or print to PDF? thanks.
void MainPage::Print_Test_Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (isPrinting) {
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
}
this->Certificate_SV_1->ScrollToVerticalOffset(0.0);
this->Certificate_SV_2->ScrollToVerticalOffset(0.0);
// CREATE THE PRINT DOCUMENT
pDocument = ref new Windows::UI::Xaml::Printing::PrintDocument();
// SAVE DOCUMENT SOURCE
pDocumentSource = pDocument->DocumentSource;
// CLEAR CACHE OF PREVIEW PAGES
printPreviewPages.clear();
// Add an event handler which creates preview pages.
pDocument->Paginate += ref new Windows::UI::Xaml::Printing::PaginateEventHandler(this, &MainPage::CreatePrintPreviewPages);
// Add an event handler which provides a specified preview page.
pDocument->GetPreviewPage += ref new Windows::UI::Xaml::Printing::GetPreviewPageEventHandler(this, &MainPage::GetPrintPreviewPage);
// Add an event handler which provides all final print pages.
pDocument->AddPages += ref new Windows::UI::Xaml::Printing::AddPagesEventHandler(this, &MainPage::AddPrintPages);
// PRINT MANAGER
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
// RAISE NEW PRINT TASK REQUEST
printTaskRequestedEventToken = printMan->PrintTaskRequested += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintManager^, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^>(this, &MainPage::PrintTaskRequested);
// SHOWS THE PRINTER UI
printMan->ShowPrintUIAsync();
}
.
void MainPage::CreatePrintPreviewPages(Object^ sender, Windows::UI::Xaml::Printing::PaginateEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
hasOverFlow = false;
StackPanel^ PrinterPage = ref new StackPanel();
PrinterPage->Width = 794; PrinterPage->Height = 1123;
PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_1);
// ADD PAGE TO THE COLLECTION
printPreviewPages.push_back(PrinterPage);
PrinterPage = safe_cast<StackPanel^>(this->Certificate_Page_2);
printPreviewPages.push_back(PrinterPage);
// Report the number of preview pages created
printDocument->SetPreviewPageCount(printPreviewPages.size(), Windows::UI::Xaml::Printing::PreviewPageCountType::Final);
}
.
void MainPage::GetPrintPreviewPage(Object^ sender, Windows::UI::Xaml::Printing::GetPreviewPageEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ localprintDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
localprintDocument->SetPreviewPage(e->PageNumber, printPreviewPages[e->PageNumber - 1]);
}
.
void MainPage::AddPrintPages(Object^ sender, Windows::UI::Xaml::Printing::AddPagesEventArgs^ e)
{
Windows::UI::Xaml::Printing::PrintDocument^ printDocument = safe_cast<Windows::UI::Xaml::Printing::PrintDocument^>(sender);
for (uint8_t i = 0; i < printPreviewPages.size(); i++) {
printDocument->AddPage(printPreviewPages[i]);
}
// Indicate that all of the print pages have been provided
printDocument->AddPagesComplete();
}
.
void MainPage::PrintTaskRequested(Windows::Graphics::Printing::PrintManager^ sender, Windows::Graphics::Printing::PrintTaskRequestedEventArgs^ e) {
Windows::Graphics::Printing::PrintTask^ printTask = e->Request->CreatePrintTask("PRINT TASK", ref new Windows::Graphics::Printing::PrintTaskSourceRequestedHandler([=](Windows::Graphics::Printing::PrintTaskSourceRequestedArgs^ args)
{
args->SetSource(pDocumentSource);
}));
// Print Task event handler is invoked when the print job is completed.
printTask->Completed += ref new Windows::Foundation::TypedEventHandler<Windows::Graphics::Printing::PrintTask^, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^>([=](Windows::Graphics::Printing::PrintTask^ sender, Windows::Graphics::Printing::PrintTaskCompletedEventArgs^ e)
{
// Notify the user when the print operation fails.
if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Failed)
{
auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
{
this->DataStreamWindow->Text = "Printing Failed!";
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
}
else if (e->Completion == Windows::Graphics::Printing::PrintTaskCompletion::Canceled)
{
auto callback = ref new Windows::UI::Core::DispatchedHandler([=]()
{
this->DataStreamWindow->Text = "Printing Cancelled!";
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, callback);
}
pDocument->InvalidatePreview();
printMan = Windows::Graphics::Printing::PrintManager::GetForCurrentView();
printMan->PrintTaskRequested -= printTaskRequestedEventToken;
isPrinting = false;
});
}

Related

Bukkit Player check achievements

I don't know what I should put into player.getAdvancementProgress(Here).
if (player.getAdvancementProgress().isDone()) {
}
Maybe someone knows something?
You should use an Advancement object, specially the advancement that you are looking for informations.
You can get it with Bukkit.getAdvancement(NamespacedKey.fromString("advancement/name")) where advancement/name can be nether/all_potions for example. You can get all here (column: "Resource location). If you are getting it from command, I suggest you to add tab complete.
Example of TAB that show only not-done success :
#Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] arg) {
List<String> list = new ArrayList<>();
if(!(sender instanceof Player))
return list;
Player p = (Player) sender;
String prefix = arg[arg.length - 1].toLowerCase(Locale.ROOT); // the begin of the searched advancement
Bukkit.advancementIterator().forEachRemaining((a) -> {
AdvancementProgress ap = p.getAdvancementProgress(a);
if((prefix.isEmpty() || a.getKey().getKey().toLowerCase().startsWith(prefix)) && !ap.isDone() && !a.getKey().getKey().startsWith("recipes"))
list.add(a.getKey().getKey());
});
return list;
}
Then, in the command you can do like that:
#Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
if(!(sender instanceof Player)) // not allowed for no-player
return false;
Player p = (Player) sender;
// firstly: try to get advancement
Advancement a = Bukkit.getAdvancement(NamespacedKey.fromString(arg[0]));
if(a == null)
a = Bukkit.getAdvancement(NamespacedKey.minecraft(arg[0]));
if(a == null) // can't find it
p.sendMessage(ChatColor.RED + "Failed to find success " + arg[0]);
else { // founded :
AdvancementProgress ap = p.getAdvancementProgress(a);
p.sendMessage(ChatColor.GREEN + "Achivement " + a.getKey().getKey() + " stay: " + ChatColor.YELLOW + String.join(", ", ap.getRemainingCriteria().stream().map(this::getCleaned).collect(Collectors.toList())));
}
return false;
}
private String getCleaned(String s) { // this method is only to make content easier to read
String[] args = s.split("/");
return args[args.length - 1].replace(".png", "").replace(".jpg", "").replace("minecraft:", "").replace("_", " ");
}
Else, if you want to get all advancements, you should use Bukkit.advancementIterator().

Accessing retrofit 2 data outside on response?

I am working on two apps, in one of my app "A" i applied retrofit 2.
This was the method i used to retrieve data.
But here in on Response the data retrieved in response body can be set to activity variables and can be used outside this method without getting null values.
public void fetch_information() {
ApiInterface = ApiClient.getApiClient().create(Api.class);
Call<List<City>> call = ApiInterface.GetCities();
call.enqueue(new Callback<List<City>>() {
#Override
public void onResponse(Call<List<City>> call, Response<List<City>> response) {
citylist = new ArrayList<City>();
citylist = response.body();
cities = new String[citylist.size()];
citiesid = new String[citylist.size()];
for (int i = 0; i < citylist.size(); i++) {
cities[i] = citylist.get(i).getCityName();
citiesid[i] = citylist.get(i).getCityId();
}
city_adapter = new ArrayAdapter<String>(Pay_Payment_X.this, android.R.layout.simple_list_item_1, cities);
city_adapter.setDropDownViewResource(R.layout.spinner_dropdown_layout);
City_Spinner.setAdapter(city_adapter);
}
#Override
public void onFailure(Call<List<City>> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
after applying this method and on debugging this method i will retain values of varaibles "cities" and "citiesid"out side onResponse.
But applying retrofit 2 similarly on another app "B", i did the same thing for retrieving data on different URL.
ApiUtil.getServiceClass().getAllPost().enqueue(new Callback<List<ApiObject>>() {
#Override
public void onResponse(Call<List<ApiObject>> call, Response<List<ApiObject>> response) {
if (response.isSuccessful()) {
List<ApiObject> postList = response.body();
try {
for (int i = 0; i < postList.size(); i++) {
String Name = postList.get(i).getGamesName();
mGamesName.add(Name);
}
} catch (Exception e) {
}
Log.d(TAG, "Returned count " + postList.size());
NewAdapter adapter = new NewAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<List<ApiObject>> call, Throwable t) {
//showErrorMessage();
Log.d(TAG, "error loading from API");
}
});
the data is retrievable inside onResponse but outside it shows null.
So here variables are not retaining values.
Why is this happening?
the only thing came to mind is retrieving data can take time while your code lines are being read and finding null values as data has not been received yet.
Also to mention in app "A" the data retrieved is huge but in app "B" only 3 objects with string values.But still in app"A" data is retrievable.
In app 2 did this for resolving my issue.
public void doRequest( final ApiCallback callback){
ApiUtil.getServiceClass().getAllPost().enqueue(new Callback<List<ApiObject>>() {
#Override
public void onResponse(Call<List<ApiObject>> call, Response<List<ApiObject>> response) {
if (response.isSuccessful()) {
List<ApiObject> postList = response.body();
callback.onSuccess(postList);
// apobject =response.body();
if(response.isSuccessful()) {
try {
for (int i = 0; i < postList.size(); i++) {
String Name = postList.get(i).getGamesName().toString();
mGamesName.add(Name);
}
} catch (Exception e) {
}
}
Log.d(TAG, "Returned count " + postList.size());
NewAdapter adapter = new NewAdapter(getApplicationContext(), postList);
recyclerView.setAdapter(adapter);
}
}
#Override
public void onFailure(Call<List<ApiObject>> call, Throwable t) {
//showErrorMessage();
Log.d(TAG, "error loading from API");
}
});
}
pass an interface
public interface ApiCallback{
void onSuccess(List<ApiObject> result);
}
and in on Create view of activity i called this
doRequest(new ApiCallback(){
#Override
public void onSuccess(List<ApiObject> result){
//here i can set variable values
}
});
the only thing came to mind is retrieving data can take time while your code lines are being read and finding null values as data has not been received yet.
That's entirely correct. Your call is finishing after you check the values. I'm going to go on a limb here and say that it's just a coincidence that it works on one app and not in the other (if they are actually doing it the same way)
When you call callback.onSuccess(postList); doesn't seem to be right either, because you haven't checked yet for success. This means that response.body() might be null and response.errorBody() will contain the body of the error.
If you'd move callback.onSuccess inside the if this would be fixed:
if(response.isSuccessful()) {
callback.onSuccess(response.body());
try {
for (int i = 0; i < postList.size(); i++) {
String Name = postList.get(i).getGamesName().toString();
mGamesName.add(Name);
}
} catch (Exception e) {
}
Last but not least, inside the onSuccess method is when you can use your global variables. Maybe it's better to stop using global variables and just use the callback parameters.

Object reference not set to an instance Of Object

Good day to all,
Please I need somebody to help me have a look at my codes.I am having this error of** Object reference not set to an instance Of Object**.It appears the error is within this lines of codes
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
but unfortunately I was unable to resolve this error.I would be very glad if somebody could help me out.thank you for the usual support.best regards.
Firstoption.
Below are the remaining part of the codes.
byte[] data = new byte[5];
private Timer _scrollingTimer = null;
private void button3_Click(object sender, EventArgs e)
{
UInt32 numBytesWritten = 0;
data[0] = 1;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
data[0] = 0x6A;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UInt32 numBytesWritten = 1;
string dataToWrite = "#0";
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
_scrollingTimer.Tick += (s, ea) =>
{
if (trackBar1.Value == (int)_scrollingTimer.Tag)
{
_scrollingTimer.Stop();
myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
int percent = (int)(((double)trackBar1.Value / (double)trackBar1.Maximum) * 100);
label2.Text = (percent.ToString()) + "%";
data[0] = Convert.ToByte(percent);
data[1] = 0x6A;
myFtdiDevice.Write(data, 2, ref numBytesWritten);
_scrollingTimer.Dispose();
_scrollingTimer = null;
}
else
{
_scrollingTimer.Tag = trackBar1.Value;
}
};
_scrollingTimer.Start();
}
}
sender is not a TrackBar. Looks like it's probably backgroundWorker1.

Detect USB devices event

I made a console application which detects plugin and plugout events for all type of usb devices. but I wanted some filteration in it like I wanted to detect only webcams . This was done by using GUID class. The class for webcam is 'Image' class with GUID "{6bdd1fc5-810f-11d0-bec7-08002be2092f}" .The problem is that this 'Image' class is also used for scanners and I dont want to detect scanners.The code is given below:
static void Main(string[] args)
{
WqlEventQuery weqQuery = new WqlEventQuery();
weqQuery.EventClassName = "__InstanceOperationEvent";
weqQuery.WithinInterval = new TimeSpan(0, 0, 3);
weqQuery.Condition = #"TargetInstance ISA 'Win32_PnPEntity'";
ManagementEventWatcher m_mewWatcher = new ManagementEventWatcher(weqQuery);
m_mewWatcher.EventArrived += new EventArrivedEventHandler(m_mewWatcher_EventArrived);
m_mewWatcher.Start();
Console.ReadLine();
}
static void m_mewWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
bool bUSBEvent = false;
string deviceCaption = "";
string deviceType = "";
foreach (PropertyData pdData in e.NewEvent.Properties)
{
try
{
ManagementBaseObject mbo = (ManagementBaseObject)pdData.Value;
if (mbo != null)
{
foreach (PropertyData pdDataSub in mbo.Properties)
{
Console.WriteLine(pdDataSub.Name + " = " + pdDataSub.Value);
if (pdDataSub.Name == "Caption")
{
deviceCaption = pdDataSub.Value.ToString();
}
if (pdDataSub.Name == "ClassGuid" && pdDataSub.Value.ToString() == "{6bdd1fc5-810f-11d0-bec7-08002be2092f}")
{
bUSBEvent = true;
deviceType = "Image";
}
}
if (bUSBEvent)
{
if (e.NewEvent.ClassPath.ClassName == "__InstanceCreationEvent")
{
Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged in at " + DateTime.Now.ToString());
}
else if (e.NewEvent.ClassPath.ClassName == "__InstanceDeletionEvent")
{
Console.WriteLine("A " + deviceType + " device " + deviceCaption + " was plugged out at " + DateTime.Now.ToString());
}
}
}
}
catch (Exception ex)
{
}
}
}
for references check this link
I waited but no body answered this question so, after seeing all properties of ManagementBaseObject I found that there is a property named Service which is different for scanners. In scanners the value of Service property is usbscan while in cameras it is usbvideo.
eg.
you can do something like this
if (mbo.Properties["Service"].Value.ToString() == "usbscan")
{
//then it means it is a scanner
}
else
{
//then it means it is a camera
}
note: The main question was that how can we differentiate between a scanner and a webcam because they both use same GUID.

LWUIT List not scrolling

I have inserted a list in my j2ME project,designed using LWUIT. The code is as follows
Button btnHome;
Button btnExit;
List list;
setScrollableY(false);
setScrollable(false);
list = new List();
MyRenderer render = new MyRenderer();
list.setListCellRenderer(render);
list.getStyle().setFgColor(0xfaedf2);
list.setSmoothScrolling(true);
list.addSelectionListener(new SelectionListener(){
public void selectionChanged(int i, int i1) {
try {
InformationForm form = new InformationForm();
form.show();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
String[] arrString = builder.getArrName();
System.out.println(arrString.length);
for (int i = 0; i < arrString.length ; i++)
{
list.addItem(arrString[i]);
// System.out.println("item no " + i +" = " +arrString[i] + "added in list");
}
BorderLayout bl=new BorderLayout();
setLayout(bl);
Container holdingContainer=new Container(new FlowLayout(Component.LEFT));
Container c0 = new Container(new BoxLayout(BoxLayout.X_AXIS));
Container c1 = new Container(new FlowLayout(Component.LEFT));
Container c2 = new Container(new FlowLayout(Component.LEFT));
Container footerContainer=new Container(new BoxLayout(BoxLayout.X_AXIS));
c0.addComponent(cityChoice);
c0.addComponent(btnFilter);
//c2.addComponent(list);
c1.setPreferredH(25);
holdingContainer.addComponent(c0);
holdingContainer.addComponent(c1);
getStyle().setBgColor(0x730E36);
// holdingContainer.addComponent(c2);
holdingContainer.setPreferredH(280);
holdingContainer.setScrollableY(true);
addComponent(BorderLayout.CENTER,list);
//addComponent(BorderLayout.WEST,holdingContainer);
footerContainer.getStyle().setMargin(Component.LEFT, 0);
footerContainer.addComponent(btnHome);
footerContainer.addComponent(btnExit);
addComponent(BorderLayout.SOUTH,footerContainer);
The renderer for list is,
public class MyRenderer extends TextArea implements ListCellRenderer{
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected){
getStyle().setBorder(Border.createEmpty());
getStyle().setFgColor(0xfaedf2);
getStyle().setBgColor(isSelected ? 0x630A2E : 0x730E36);
setText(value.toString());
if (isSelected) {
setFocus(true);
getStyle().setBgTransparency(100);
} else {
setFocus(false);
getStyle().setBgTransparency(0);
}
return this;
}
public Component getListFocusComponent(List list){
return null;}
}
The problem is when on device, i try to scroll the list, the item on which i touched is selected immediatly and the new form for it is opened. I do not able to scroll the list at all. Please help me in solving this problem.
Is it possible you are using a SelectionListener instead of an ActionListener?