I'm working with C# xamarin forms android and I'm trying to go back using OnBackButtonPressed. It kind of works but my problem is that the user has to touch 2 times to go back. I will left a photo below to explain my point. But basically the user goes from Home page to Scaner page and when he touch buttom back when he is scanning doesn't come back to home page. He has to touch 2 times and i don't want that. I need that when he touches the buttom back he goes to the home page.
my scanPage.xaml.cs:
protected override bool OnBackButtonPressed()
{
try
{
if (Shell.Current.FlyoutIsPresented == false)
{
Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
else
{
Shell.Current.FlyoutIsPresented = false;
}
}
catch(Exception ex)
{
}
//return base.OnBackButtonPressed();
return true;
}
private async Task Scanner()
{
try
{
var scannerPage = new ZXingScannerPage();
scannerPage.AutoFocus();
scannerPage.Title = "Scanner";
using (SemaphoreSlim semaphoreSlim = new SemaphoreSlim(0, 1))
{
scannerPage.OnScanResult += (result) =>
{
scannerPage.IsScanning = false;
string resultado = Convert.ToString(result);
if (resultado.Contains("http") || resultado.Contains("https") || !resultado.Contains("\t"))
{
Navigation.PopAsync();
this.DisplayAlert("Error", "QR not valid", "OK");
}
else
Device.BeginInvokeOnMainThread(async () =>
{
try
{
await Application.Current.MainPage.Navigation.PopAsync();
subs = result.Text.Split('\t');
string cadena = "var 1: " + subs[0] + "\nvar 2: " + subs[1] + "\nvar 3: " + subs[2];
numEntrega.Text = "var 2: " + subs[1];
controlScanner = true;
await this.DisplayAlert("Data", cadena, "OK");
}
catch (Exception ex)
{
checkDoubleCalled = true;
controlScanner = false;
numEntrega.Text = "";
await DisplayAlert("Error", "QR not valid.\n try again.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
semaphoreSlim.Release();
});
};
await Navigation.PushAsync(scannerPage);
await semaphoreSlim.WaitAsync();
}
return;
}
catch(Exception ex)
{
checkDoubleCalled = true;
controlScanner = false;
numEntrega.Text = "";
await DisplayAlert("Error", "Sorry we had a problem.", "OK");
await Shell.Current.GoToAsync($"//{nameof(HomePage)}");
}
return;
}
Image of my problem:
How could I resolve this problem?
Thank you very much!
I am Making C# WPF Application That contains CSV Writing.
But, I wanna give some delays. But When i use
Thread.Sleep(ms),
UI freezes and Windows says that This Program has been Stopped.
So, I found some Alternatives like
private static DateTime Delay(int MS)
{
DateTime ThisMoment = DateTime.Now;
TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
DateTime AfterWards = ThisMoment.Add(duration);
while (AfterWards >= ThisMoment)
{
if (System.Windows.Application.Current != null)
{
System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { }));
}
ThisMoment = DateTime.Now;
}
return DateTime.Now;
}
But,when I use this method, The Program just Stops.
This is Button Code that makes, writes CSV File.
private void button_Click(object sender, RoutedEventArgs e)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"New.csv");
int a = 1;
file.WriteLine("Delta, Theta");
while (a < 20)
{
file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
a++;
file.Close();
Thread.Sleep(3000); //Delay(3000); When I use Alternative way.
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
The Main Question that I want to know is how to delay some seconds without Freezing UI. Sorry for Bad Grammar.
Make your click handler async. Then you can use Task.Delay, which will not block the thread.
private async void button_Click(object sender, RoutedEventArgs e)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(#"New.csv");
int a = 1;
file.WriteLine("Delta, Theta");
while (a < 20)
{
file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
a++;
file.Close();
await Task.Delay(3000);
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
By the way, here's one way to fix your exception:
private async void button_Click(object sender, RoutedEventArgs e)
{
const string fileName = #"New.csv";
try
{
File.AppendAllText(fileName, "Delta, Theta");
for (var a=1; a<20; a++)
{
var text = string.Format("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
File.AppendAllText(fileName, text);
await Task.Delay(3000);
}
}
catch (Exception ex)
{
throw new ApplicationException("Broken", ex);
}
}
private async void CSVexport_Click(object sender, RoutedEventArgs e) //to use Await Task.Delay(ms) Option
{
try
{
SaveFileDialog saveAsfile = new SaveFileDialog(); //Save As File
saveAsfile.InitialDirectory = #"C:\";
saveAsfile.Title = "Save As File";
saveAsfile.Filter = "CSV Document(*.csv)|*.csv|All Files(*.*)|*.*";
saveAsfile.DefaultExt = "csv";
saveAsfile.AddExtension = true;
if (saveAsfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) //Save As File Function
{
GaugeSignal.Value = 1;
if (TGLatestData.PoorSignal != -1)
{
var SignalQuality = Math.Round((200D - TGLatestData.PoorSignal) / 2D, 1);
if (SignalQuality < 0) SignalQuality = 0;
GaugeSignal.Value = SignalQuality;
TGLatestData.PoorSignal = TGLatestData.PoorSignal;
}
SQZero.Visibility = 0;
CSVexport.Visibility = Visibility.Hidden;
FileStream filestream = new FileStream(saveAsfile.FileName, FileMode.Create, FileAccess.Write);
System.Windows.MessageBox.Show("CSV Writing...\nIf you want to stop Writing CSV, Click SQ to 0 Button,", "CSV Writing...", MessageBoxButton.OK, MessageBoxImage.Warning);
System.IO.StreamWriter file = new System.IO.StreamWriter(filestream);
int time = 1000;
file.WriteLine("Signal Quality, Delta, Theta, Alpha1, Alpha2, Beta1, Beta2, Gamma1, Gamma2, Attention, Meditation, Mental Effort, Task Familiarity, Task Difficulty, Blink Strength");
while (true) //infinite loop
{
double Check_Signal_Zero_To_Stop = GaugeSignal.Value;
file.WriteLine("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, {13}, {14}", GaugeSignal.Value, TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta, TGLatestData.EegPowerAlpha1, TGLatestData.EegPowerAlpha2, TGLatestData.EegPowerBeta1, TGLatestData.EegPowerBeta2, TGLatestData.EegPowerGamma1, TGLatestData.EegPowerGamma2, TGLatestData.Attention, TGLatestData.Meditation, TGLatestData.MentalEffort, TGLatestData.TaskFamiliarity, TGLatestData.TaskDifficulty, TGLatestData.BlinkStrength);
await Task.Delay(time); //Delay Without FreezingUI (need async)
if (Check_Signal_Zero_To_Stop == 0)
{
file.Close(); //if you click SQ to 0, Do file.Close
while (true) await Task.Delay(1000000000);
}
}
}
}
catch (ApplicationException ex)
{
throw new ApplicationException("This Program is Get Broken", ex);
}
}
I changed private void to 'private async void' to use Await Task.Delay(ms) instead of Thread.Sleep(ms) and I also Made Stop Button to get out of infinite loop.
Here is SQ to 0 Button Source. If you Click this button, One variable(GaugeSignal.Value) will be 0 and it will stop Writing CSV and Saving modified file.
private async void SQzero_Click(object sender, RoutedEventArgs e)
{
int EndTime = 4000;
SQZero.Visibility = Visibility.Hidden;
System.Windows.MessageBox.Show("Stop Writing CSV... \nWait a Seconds..", "CSV Saving..", MessageBoxButton.OK, MessageBoxImage.Warning);
GaugeSignal.Value = 0;
await Task.Delay(EndTime); //Wait for Delay of CSVexport_btn
System.Windows.MessageBox.Show("CSV Saved!", "CSV Saved", MessageBoxButton.OK, MessageBoxImage.Warning);
CSVexport.Visibility = Visibility.Visible; //to Save another one Again
}
I was Foolish. I used file.Close(); in loop. So, It says IOException. I found other method to avoid them and Finally got it. Thanks to John Wu, Çöđěxěŕ to help me.
private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (Clos_flag) return;
try
{
Listening = true;
if (serialPort.IsOpen)
{
this.txt_weight.Invoke(new MethodInvoker(delegate
{
serialPort.NewLine = "\r";
string weight = serialPort.ReadLine();
weight = weight.Trim();
MessageBox.Show(weight);
if (weight.IndexOf("i") > 0)
{
weight = weight.Substring(3, 8);
txt_weight.Text = weight.Substring(0, weight.LastIndexOf("0") + 1);
}
}));
}
}
catch (Exception eg)
{
MessageBox.Show(eg.ToString());
}
finally
{
Listening = false;
}
}
I use the above code to read the weighing machine, but it keep on prompt the timeout error I'm not sure which part of the coding is wrong.
You check your configure serialport.
It may be error while run code serialPort.Open().
you can refer code:
void InitialComport1()
{
mySerialPort1 = new SerialPort(Temp._comport1);
if (mySerialPort1.IsOpen)
{
mySerialPort1.Close();
}
mySerialPort1.BaudRate = Temp._baudRate1;
mySerialPort1.Parity = Parity.None;
mySerialPort1.StopBits = StopBits.One;
mySerialPort1.DataBits = Temp._dataBit1;
mySerialPort1.Handshake = Handshake.None;
mySerialPort1.RtsEnable = true;
mySerialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler1);
try
{
mySerialPort1.Open();
}
catch
{
Messagebox.Show("Error myserialPort1")
}
}
private void DataReceivedHandler1(object sender, SerialDataReceivedEventArgs e)
{
try
{
string indata = mySerialPort1.ReadLine();
try
{
string mass = indata.Substring(7, 7);
SetText1((Convert.ToInt32(mass)).ToString());
}
catch
{
string mass = indata.Substring(3, 7);
SetText1((Convert.ToInt32(mass)).ToString());
}
}
catch (Exception eg)
{
MessageBox.Show(eg.ToString());
}
}
I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps.
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
(I've tried with GeoCoordinateWatcher but i got nothing).
These functions work perfectly when i'm standing at the same place or moving very slowly, but if i enter in a car and start to drive the app crashes after few seconds, and I don't know WHY.
I've searched a lot of codes with the same finality and all of them don't work.
Do you know any other solution for that problem or have already found yourselves in the same position as mine ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}
Yesterday I have created two forms, the first form listen requests of client out network, the second form is form alert (MessageBox custom) like MessageBox, but when a client sends a connection request to the first form, affter the form second will show, but affter click on any button to close form and I received an message below:
Title: System.InvalidOperationException
Details:
The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
The First From:
//Nhận các yêu cầu và kiểm tra và gửi phản hồi
private void OnReceive(IAsyncResult ar)
{
try
{
EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);
//Get the IP from where we got a message.
clientSocket.EndReceiveFrom(ar, ref receivedFromEP);
//Convert the bytes received into an object of type Data.
Data(byteData);
//Act according to the received message.
switch (cmdCommand)
{
//We have an incoming call.
case Command.Invite:
{
if (bIsCallActive == false)
{
//We have no active call.
//Ask the user to accept the call or not.
DialogResult result = ThongBaoCoDienThoai.HienHopThoai(strName);
if (result == DialogResult.Yes)
{
//SendMessage(Command.OK, receivedFromEP);
//Bắt đầu kết nôi
//**********************************GOI PHUONg THUC GUI NHAN DONG BO AM THANH****************
}
else
{
//The call is declined. Send a busy response.
//SendMessage(Command.Busy, receivedFromEP);
}
}
else
{
//We already have an existing call. Send a busy response.
SendMessage(Command.Busy, receivedFromEP);
}
break;
}
//OK is received in response to an Invite.
case Command.OK:
{
//Start a call.
break;
}
//Remote party is busy.
case Command.Busy:
{
MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
break;
}
case Command.Bye:
{
//Check if the Bye command has indeed come from the user/IP with which we have
//a call established. This is used to prevent other users from sending a Bye, which
//would otherwise end the call.
if (receivedFromEP.Equals(otherPartyEP) == true)
{
//End the call.
}
break;
}
}
byteData = new byte[1024];
//Get ready to receive more commands.
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback(OnReceive), null);
}
catch (Exception ex)
{
MessageBox.Show("OnReceive: " + ex.Message, "Error");
}
}
The Second Form:
static ThongBaoCoDienThoai tbcdt;
static DialogResult kq = DialogResult.No;
private Timer thoiGian;
int henGioTat; //Hẹn thời gian tắt form
SoundPlayer player; //Khởi tạo thiết bị phát (Loa)
public ThongBaoCoDienThoai()
{
InitializeComponent();
try
{
henGioTat = 30;
thoiGian = new Timer();
thoiGian.Interval = 1000;
thoiGian.Enabled = true;
thoiGian.Start();
thoiGian.Tick += new EventHandler(this.thoiGian_Tick);
//Hiển thị hộp thông báo ở góc màng hình dưới bên phải
Rectangle r = Screen.PrimaryScreen.WorkingArea;
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - this.Width, Screen.PrimaryScreen.WorkingArea.Height - this.Height);
//Phát âm thành khi form được mở
player = new SoundPlayer(Properties.Resources.ringing);
player.Load();
player.PlayLooping();
}
catch (Exception ex)
{
MessageBox.Show("ThongBaoCoDienThoai_Load :" + ex.Message, "Error");
}
}
public static DialogResult HienHopThoai(string tenNguoiGoi)
{
try
{
tbcdt = new ThongBaoCoDienThoai();
tbcdt.lbThongBao.Text = tenNguoiGoi + " đang gọi........";
tbcdt.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show("HienHopThoai: "+ex.Message,"Error");
}
return kq;
}
private void btHuy_Click(object sender, EventArgs e)
{
tbcdt.thoiGian.Stop();
tbcdt.thoiGian.Dispose();
kq = DialogResult.No;
tbcdt.Dispose();
}
private void btNhan_Click(object sender, EventArgs e)
{
ThongBaoCoDienThoai tbcdt = new ThongBaoCoDienThoai();
alertControl1.Show(tbcdt);
tbcdt.thoiGian.Stop();
tbcdt.thoiGian.Dispose();
kq = DialogResult.Yes;
tbcdt.Dispose();
}
private void thoiGian_Tick(object sender, EventArgs e)
{
henGioTat--;
if (henGioTat == 0)
{
tbcdt.thoiGian.Stop();
tbcdt.thoiGian.Dispose();
tbcdt.Dispose();
}
}
private void ThongBaoCoDienThoai_FormClosing(object sender, FormClosingEventArgs e)
{
player.Stop();
}