Windows store app error during print operation - c#

I am running my windows store app and i got error like this.
An exception of type 'System.InvalidOperationException' occurred in mscorlib.dll but was not handled in user code
WinRT information: Only one handler for the PrintTaskRequested event may be registered at a time.
Additional information: A method was called at an unexpected time.
My code is here.help me to get understand the problem and resolve this issue.Kindly tell me know the exact problem.
//print sample
protected PrintDocument printDocument = null;
protected IPrintDocumentSource printDocumentSource = null;
internal List<UIElement> printPreviewElements = new List<UIElement>();
protected event EventHandler pagesCreated;
Error came in print task requested handler
protected virtual void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs e)
{
PrintTask printTask = null;
printTask = e.Request.CreatePrintTask("C# Printing SDK Sample", sourceRequested =>
{
printTask.Completed += async (s, args) =>
{
if (args.Completion == PrintTaskCompletion.Failed)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
MessageDialog dialog = new MessageDialog("Something went wrong while trying to print. Please try again.");
await dialog.ShowAsync();
});
}
};
sourceRequested.SetSource(printDocumentSource);
});
}
protected virtual void RegisterForPrinting()
{
printDocument = new PrintDocument();
printDocumentSource = printDocument.DocumentSource;
printDocument.Paginate += CreatePrintPreviewPages;
printDocument.GetPreviewPage += GetPrintPreviewPage;
printDocument.AddPages += AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested += PrintTaskRequested;
}
protected virtual void UnregisterForPrinting()
{
if (printDocument != null)
{
printDocument.Paginate -= CreatePrintPreviewPages;
printDocument.GetPreviewPage -= GetPrintPreviewPage;
printDocument.AddPages -= AddPrintPages;
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= PrintTaskRequested;
}
}
protected virtual void CreatePrintPreviewPages(object sender, PaginateEventArgs e)
{
printPreviewElements.Clear();
PrintTaskOptions printingOptions = ((PrintTaskOptions)e.PrintTaskOptions);
PrintPageDescription pageDescription = printingOptions.GetPageDescription(0);
AddOnePrintPreviewPage(pageDescription);
if (pagesCreated != null)
{
pagesCreated.Invoke(printPreviewElements, null);
}
((PrintDocument)sender).SetPreviewPageCount(printPreviewElements.Count, PreviewPageCountType.Intermediate);
}
protected virtual void GetPrintPreviewPage(object sender, GetPreviewPageEventArgs e)
{
((PrintDocument)sender).SetPreviewPage(e.PageNumber, printPreviewElements[e.PageNumber - 1]);
}
protected virtual void AddPrintPages(object sender, AddPagesEventArgs e)
{
foreach (UIElement element in printPreviewElements)
{
printDocument.AddPage(element);
}
((PrintDocument)sender).AddPagesComplete();
}
protected virtual void AddOnePrintPreviewPage(PrintPageDescription printPageDescription)
{
TextBlock block = new TextBlock();
block.Text = "This is an example.";
block.Width = printPageDescription.PageSize.Width;
block.Height = printPageDescription.PageSize.Height;
printPreviewElements.Add(block);
}
//protected override void OnNavigatedTo(NavigationEventArgs e)
//{
// RegisterForPrinting();
//}
//protected override void OnNavigatedFrom(NavigationEventArgs e)
//{
// UnregisterForPrinting();
//}
private void printBirth_Click(object sender, RoutedEventArgs e)
{
RegisterForPrinting();
}

you can use it
private async void printBirth_Click(object sender, RoutedEventArgs e)
{
await Windows.Graphics.Printing.PrintManager.showPrintUIAsync()
}

Related

Show message after a successful record saving

I am new to XAF Blazor so I trying to display a message to end users after a successful record saving, so I wrote the following code:
public partial class MessageSavedSuccessfullyViewController : ViewController
{
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.Committing += ObjectSpace_Committing;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.Committing -= ObjectSpace_Committing;
base.OnDeactivated();
}
private void ObjectSpace_Committing(object sender, CancelEventArgs e)
{
if (View.ObjectSpace.IsCommitting)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = string.Format("Record Saved Successfully");
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
}
}
}
but when I run the code, nothing happens.
Is there something I am missing?
This code should be used across my entire application, not just in a specific view.
public partial class MessageSavedSuccessfullyViewController : ViewController<DetailView>
{
private string message;
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed += ObjectSpace_Committed;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.ObjectChanged -= ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed -= ObjectSpace_Committed;
base.OnDeactivated();
}
void ObjectSpace_Committed(object sender, EventArgs e)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = message;
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
message = string.Empty;
}
void ObjectSpace_ObjectChanged(object sender, ObjectChangedEventArgs e)
{
if (ObjectSpace.IsNewObject(e.Object))
{
message=string.Format("Record Saved Successfully");
}
else if (ObjectSpace.IsDeleting)
{
message = string.Format("Record Deleted Successfully");
}
else if (ObjectSpace.IsModified && e.OldValue != e.NewValue)
{
message = string.Format("Record Updated Successfully");
}
}
}

SystemEvents.SessionSwitch doesn´t fire in a c# wpf application

i have a small c# wpf application. The application starts hidden and i use the systemtray to show the main window. I would like to do some actions when a user unlocks the desktop. I use the SystemEvents.SessionSwitch event, bit the event doesn´t fire. I've read some posts and this event seems to be the right one for WPF applications, but it doesn't work. Are there perhaps DLLs missing or is the call to register the event too late? Is there a problem with the UI Thead?
My Application Code:
public partial class App : Application
{
private System.Windows.Forms.NotifyIcon _notifyIcon;
private bool _isExit;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
MainWindow = new MainWindow();
MainWindow.Closing += MainWindow_Closing;
_notifyIcon = new System.Windows.Forms.NotifyIcon();
_notifyIcon.DoubleClick += (s, args) => ShowMainWindow();
_notifyIcon.Icon = CiGCoachingClient.Properties.Resources.MyIcon;
_notifyIcon.Visible = true;
CreateContextMenu();
}
private void CreateContextMenu()
{
_notifyIcon.ContextMenuStrip =
new System.Windows.Forms.ContextMenuStrip();
//_notifyIcon.ContextMenuStrip.Items.Add("MainWindow...").Click += (s, e) => ShowMainWindow();
_notifyIcon.ContextMenuStrip.Items.Add("Exit").Click += (s, e) => ExitApplication();
}
private void ExitApplication()
{
_isExit = true;
MainWindow.Close();
_notifyIcon.Dispose();
_notifyIcon = null;
}
private void ShowMainWindow()
{
if (MainWindow.IsVisible)
{
if (MainWindow.WindowState == WindowState.Minimized)
{
MainWindow.WindowState = WindowState.Normal;
}
MainWindow.Activate();
}
else
{
MainWindow.Visibility = Visibility.Visible;
MainWindow.Show();
}
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
if (!_isExit)
{
e.Cancel = true;
MainWindow.Hide(); // A hidden window can be shown again, a closed one not
}
}
private void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
Console.WriteLine("i left my desk");
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
Console.WriteLine("i returned to my desk");
}
}
}
What could be the reason for this? Is there a error in the code?
Regards
Sascha

c# Android access textview from another class

I'm writing an android app in c#, which communicates with a server.
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.button1);
TextView txt = FindViewById<TextView>(Resource.Id.textView1);
Client client = new Client();
client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455);
client.Start();
...
On start up, it should display a message on the TextView.
class Client : Activity{
private WebSocket websocketClient;
...
public void Setup(string url, string protocol, WebSocketVersion version)
{
...
websocketClient.Opened += new EventHandler(websocketClient_Opened);
}
private void websocketClient_Opened(object sender, EventArgs e){
txt.Text = ("Client successfully connected."); // this line is wrong
websocketClient.Send("Hello World!");
}
}
The problem is, I have no idea, how to access the TextView. I found this, but I don't know how should I use it in my case.
I don't know what library WebSocket you a using. I using websocket-sharp. It is example use:
protected override void OnCreate(Bundle bundle)
{
TextView txt = FindViewById<TextView>(Resource.Id.My);
using (var ws = new WebSocket("ws://dragonsnest.far/Laputa"))
{
ws.OnError += (sender, e) =>
{
txt.Text = e.Message;
};
..........
}
It is work. I see error message in my TextView.
If you get error, try use RunOnUiThread.Example:
private void websocketClient_Opened(object sender, EventArgs e)
{
this.RunOnUiThread(() =>
{
txt.Text = "your message";
});
}
Hope this help.
Just make WebsocketClient a property it a instead of a class variable and then you can access it from you activity.
public class MainActivity : Activity
{
private TextView txt;
private Client client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
txt = FindViewById<TextView>(Resource.Id.textView1);
client = new Client();
client.WebsocketClient.Opened += websocketClient_Opened;
client.Setup("ws://192.168.0.14:8001", "basic", WebSocketVersion.Rfc6455);
client.Start();
}
protected override void OnDestroy()
{
client.WebsocketClient.Opened -= websocketClient_Opened;
base.OnDestroy();
}
private void websocketClient_Opened(object sender, EventArgs e)
{
txt.Text = ("Client successfully connected.");
// maybe have to be wrapped in a RunOnUiThread(() =>{ ... });
}
}
class Client
{
public WebSocket WebsocketClient { get; set; }
public void Setup(string url, string protocol, WebSocketVersion version)
{
// WebsocketClient = new ...
WebsocketClient.Opened += websocketClient_Opened;
}
private void websocketClient_Opened(object sender, EventArgs e)
{
WebsocketClient.Send("Hello World!");
}
}

Cannot assign to 'method' because it is a 'method group

I can't run my code because there is a error saying:
Cannot assign to 'OnNewLand' because it is a 'method group
This is strange because I have used the same structure as my other methods and there were no problem with them.
Here is my code.
private void CreateNewFlight()
{
string flightCode = ReadFlightCode();
//Create the new bidder
if (!string.IsNullOrEmpty(flightCode))
{
FlightWindow frm = new FlightWindow(Flightcode.Text);
frm.Show();
//Subscribe to the publisher's new bid and quit bid events
frm.NewStart += OnNewStartClick;
frm.NewChangeRoute += OnNewChangeRoute;
frm.OnNewLand += OnNewLand; <----Here is the error <-------
}
}
Cannot assign to 'OnNewLand' because it is a 'method group
My other window:
public event EventHandler<Start> NewStart;
public event EventHandler<ChangeRoute> NewChangeRoute;
public event EventHandler<Land> NewLand;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
Start startinfo = new Start(this.Title);
OnNewStart(startinfo); //Raise event
btnLand.IsEnabled = true;
Routetxt.IsEnabled = true;
changebtn.IsEnabled = true;
btnStart.IsEnabled = false;
}
private void changebtn_Click(object sender, RoutedEventArgs e)
{
ChangeRoute changeinfo = new ChangeRoute(this.Title, Routetxt.Text);
OnNewChangeRoute(changeinfo); //Raise event
}
private void btnLand_Click(object sender, RoutedEventArgs e)
{
Land landinfo = new Land(this.Title);
OnNewLand(landinfo); //Raise event
}
//Raise Event
public void OnNewStart(Start e)
{
if (NewStart != null)
NewStart(this, e);
}
public void OnNewChangeRoute(ChangeRoute e)
{
if (NewChangeRoute != null)
NewChangeRoute(this, e);
}
public void OnNewLand(Land e)
{
if (NewLand != null)
NewLand(this, e);
}
You need
frm.OnNewLand += NewLand;
instead of
frm.OnNewLand += OnNewLand;
You might be interested to know what does it mean by method group. Visit this so thread.

GSMComm phoneConnected/phoneDisconnected Handlers

Trying to develop small application using GsmComm Library.
At the moment a have some problems with detecting if phone is connected or no.
it's detects when phone is disconnected, but doesn't want to detect phone when is connected back again ...
Any idea why ?
my code:
GsmCommMain gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
gsm.PhoneConnected += new EventHandler(gsmPhoneConnected);
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}
Sorry for late answer. Just noticed your question.
There is no need to use EventHandler for connection. If you want to call some functions after phone/gsm modem is connected you should call them after you opened port and (!) checked whether connection is established using IsConnected() member function in GsmCommMain class.
var gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
//gsm.PhoneConnected += new EventHandler(gsmPhoneConnected); // not needed..
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
if(gsm.IsConnected()){
this.onPhoneConnectedChange(true);
}
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
/*public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}*/
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}

Categories