await x.ShowAsync(); shown in Windows Phone 8.1 app Error - c#

An exception is thrown when using "await" operator inside a function as follows:
The 'await' operator can only be used within an async method.
Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
int snooze;
string audioSrc;
int year = datepicker.Date.Year;
int month = datepicker.Date.Month;
int day = datepicker.Date.Day;
int hour = timepicker.Time.Hours;
int min = timepicker.Time.Minutes;
int sec = timepicker.Time.Seconds;
// string audioSrc = alrm_sound.SelectionBoxItem.ToString();
try
{
snooze = Convert.ToInt16(CustomSnoozeTime.SelectionBoxItem.ToString());
}
catch
{
snooze = 5;
}
try
{
audioSrc = alrm_sound.SelectionBoxItem.ToString();
}
catch
{
audioSrc = "Default";
}
DateTime myDate1 = new DateTime(year, month, day, hour, min, sec);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate1 - myDate2;
if (myDate2 > myDate1)
{
var x = new MessageDialog("Invalid date or time");
await x.ShowAsync();
}
else
{
string title = "Alarm!";
string message = alm_msg.Text;
string imgURL = "ms-appx:///Assets/Capture.PNG";
string toastXmlString =
"<toast><visual version='1'><binding template='toastImageAndText02'><text id='1'>"
+ title + "</text><text id='2'>"
+ message + "</text><image id='1' src='" + imgURL + "'/></binding></visual>\n" +
"<commands scenario=\"alarm\">\n" +
"<command id=\"snooze\"/>\n" +
"<command id=\"dismiss\"/>\n" +
"</commands>\n" +
"<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>" +
"</toast>";
Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(toastXmlString);
var toastNotifier1 = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
double x1 = myDateResult.TotalSeconds;
int customSnoozeSeconds = snooze * 60;
TimeSpan snoozeInterval = TimeSpan.FromSeconds(customSnoozeSeconds);
var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification(toastDOM, DateTime.Now.AddSeconds(x1), snoozeInterval, 0);
toastNotifier1.AddToSchedule(customAlarmScheduledToast);
var x = new MessageDialog("Alarm Set!");
await x.ShowAsync();
}
}
catch
{ }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
int snooze;
string audioSrc;
int year = datepicker.Date.Year;
int month = datepicker.Date.Month;
int day = datepicker.Date.Day;
int hour = timepicker.Time.Hours;
int min = timepicker.Time.Minutes;
int sec = timepicker.Time.Seconds;
// string audioSrc = alrm_sound.SelectionBoxItem.ToString();
try
{
snooze = Convert.ToInt16(CustomSnoozeTime.SelectionBoxItem.ToString());
}
catch
{
snooze = 5;
}
try
{
audioSrc = alrm_sound.SelectionBoxItem.ToString();
}
catch
{
audioSrc = "Default";
}
DateTime myDate1 = new DateTime(year, month, day, hour, min, sec);
DateTime myDate2 = DateTime.Now;
TimeSpan myDateResult = new TimeSpan();
myDateResult = myDate1 - myDate2;
if (myDate2 > myDate1)
{
var x = new MessageDialog("Invalid date or time");
await x.ShowAsync();
}
else
{
string title = "Alarm!";
string message = alm_msg.Text;
string imgURL = "ms-appx:///Assets/Capture.PNG";
string toastXmlString =
"<toast><visual version='1'><binding template='toastImageAndText02'><text id='1'>"
+ title + "</text><text id='2'>"
+ message + "</text><image id='1' src='" + imgURL + "'/></binding></visual>\n" +
"<commands scenario=\"alarm\">\n" +
"<command id=\"snooze\"/>\n" +
"<command id=\"dismiss\"/>\n" +
"</commands>\n" +
"<audio src='ms-winsoundevent:Notification." + audioSrc + "'/>" +
"</toast>";
Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(toastXmlString);
var toastNotifier1 = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();
double x1 = myDateResult.TotalSeconds;
int customSnoozeSeconds = snooze * 60;
TimeSpan snoozeInterval = TimeSpan.FromSeconds(customSnoozeSeconds);
var customAlarmScheduledToast = new Windows.UI.Notifications.ScheduledToastNotification(toastDOM, DateTime.Now.AddSeconds(x1), snoozeInterval, 0);
toastNotifier1.AddToSchedule(customAlarmScheduledToast);
var x = new MessageDialog("Alarm Set!");
await x.ShowAsync();
}
}
catch
{ }
}

Add the "async" keyword in the method's declaration.
for example, if your method is like -
public void MyMethod()
{
await x.ShowAsync();
}
change it like this -
public async void MyMethod()
{
await x.ShowAsync();
}
Update :-
Also, if your method returns a value/object, do it like this -
public async Task<int> MyMethod()
{
int i = await x.ShowAsync();
return i;
}
Update:-
Change your function as follows-
private void Button_Click(object sender, RoutedEventArgs e)
Change this to-
private async void Button_Click(object sender, RoutedEventArgs e)

You need to add the async modifier to the Button_Click method like so:
private async void Button_Click(object sender, RoutedEventArgs e)
{
// rest of code
}

Related

millisecond at which a key or a mouse stroke is pressed in C#

Currently I have two functions which do this :-
protected override void OnInitialized(EventArgs a)
{
base.OnInitialized(a);
var timer4 = new DispatcherTimer();
timer4.Interval = TimeSpan.FromMilliseconds(1);
timer4.Tick += (s, e) => Main.EventMouseTimer();
timer4.Tick += (s, e) => Gauge.Text = Main.EnergyGauge;
timer4.Start();
}
public void EventMouseTimer()
{
String DateToday = DateTime.Today.ToShortTimeString();
String TimeToday = DateTime.Now.ToShortTimeString();
float TimeNow = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
//before your loop
var csv = new StringBuilder();
//in your loop
var mouse = MouseButtons.Left.ToString();
var Date = DateToday.ToString();
var Time = TimeToday.ToString();
var Milliseconds = TimeNow.ToString();
for (int i = 0; i < 10000; i++)
{
var newLine = string.Format("{0},{1},{2},{3}", mouse, Date, Time, Milliseconds);
csv.AppendLine(newLine);
//after your loop
string path = Directory.GetCurrentDirectory();
string filename = "Temp";
string FileName = Path.Combine(path, filename + ".txt");
File.WriteAllText(FileName, csv.ToString());
}
}
This doesn't seem to be working. How can I capture the exact millisecond when a key is pressed?
Thanks # The General. This solved the issue.

How to scroll down while page loading - GeckoFx C#

I want to scroll down while a page loading in geckofx 45.
I tried to to do with following code, but it seems not to work.
wb.Navigate("javascript: var s = function() { window.scrollBy(550, 10000); }; s();");
How is that possible?
int scrollTo = 30;
public void scrollDown()
{
this.wb.Focus();
string result = string.Empty;
AutoJSContext context;
string jsScript = string.Empty;
try
{
if (scrollTo > 100)
{
scrollTo = 5;
}
context = new AutoJSContext(this.wb.Window);
jsScript = "var x = document.getElementsByClassName('ANY_ELEMENTS_CLASS_NAME'); x[" + (scrollTo * 2) + "].scrollIntoView(); ";// CHANGE ANY_ELEMENTS_CLASS_NAME
context.EvaluateScript(jsScript, (nsISupports)wb.Window.DomWindow, out result);
scrollTo += 5;
}
catch (Exception e)
{
}
}
this helped me

(webform) how can i get the value from 9 different textbox and post back the value follow by ascending

This is the code for webform(asp.net c#):
protected void Button2_Click(object sender, EventArgs e)
{
int no1;
int no2;
int no3;
int no4;
int no5;
int no6;
int no7;
int no8;
int no9;
no1 = int.Parse(txt1.Text);
no2 = int.Parse(txt2.Text);
no3 = int.Parse(txt3.Text);
no4 = int.Parse(txt4.Text);
no5 = int.Parse(txt5.Text);
no6 = int.Parse(txt6.Text);
no7 = int.Parse(txt7.Text);
no8 = int.Parse(txt8.Text);
no9 = int.Parse(txt9.Text);
int[] a = new int[] {no1,no2,no3,no4,no5,no6,no7,no8,no9 };
Array.Sort(a);
foreach (var str in a)
{
MessageBox.Show(str.ToString()); //display in MessageBox, but i want to display back to 9 different textbox.
}
I can display the result in MessageBox. but I can't display the result back to 9 different textbox.
How can i find the solution?
Thank you
This is the output http://i.gyazo.com/a91f7ffef1d6d1fa7815890464df3082.png
txt1.Text = a[0];
txt2.Text = a[1];
txt3.Text = a[2];
txt4.Text = a[3];
txt5.Text = a[4];
txt6.Text = a[5];
txt7.Text = a[6];
txt8.Text = a[7];
txt9.Text = a[8];
This should do the job, if I understood you correctly.

How to call GetPrice method by passing converted value into txtQty?

I'm not sure if I'm writing the call correctly. 'intQty' says doesn't exist in current context. So how would I go about fixing that?
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
//Also to compute the order total it has to be written as
Order Total = (Order Qty * Price) * (1 + Tax Rate)
what I have: decTotal = (intQty * decPrice) * (1 + fltTaxRate);
so would I replace the that with values I've already declared?
EDIT: 'intQty' is declared right under the btnCalculate_Click as 'int intQty;'
there's data validation underneath and some methods as well.
FULL CODE:
string sCboStates;
int intQty;
string sWrapperSample;
// data validation
try
{
intQty = Convert.ToInt32(txtQty.Text);
}
catch
{
MessageBox.Show("Contents are not numeric.",
"Quantity",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtQty.Focus();
return;
}
try
{
sWrapperSample = Convert.ToString(txtWrapperSample.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"Wrapper Sample",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtLine1.Focus();
return;
}
try
{
sCboStates = Convert.ToString(cboStates.Text);
}
catch
{
MessageBox.Show("Content's empty.",
"States",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
cboStates.Focus();
return;
}
}
// Method 1
private decimal getPrice(int intQty)
{
decimal decPrice;
if (intQty <= 500)
{
decPrice = 1.25m;
}
else if (intQty >= 501 && intQty <= 1000)
{
decPrice = 1.05m;
}
else if (intQty >= 1001 && intQty <= 5000)
{
decPrice = .90m;
}
else if (intQty > 5001)
{
decPrice = .75m;
}
decPrice = Convert.ToDecimal(txtPrice.Text);
txtQty.Text = intQty.ToString();
return intQty;
}
//Method 2
private float getTaxRate(string sCboStates)
{
string sStates = "";
float fltTaxRate=0;
if (sStates == "CT")
{
fltTaxRate = 0.06f;
}
else if (sStates == "MA")
{
fltTaxRate =.0625f;
}
else if (sStates == "ME")
{
fltTaxRate = .085f;
}
else if (sStates == "NH")
{
fltTaxRate = .0f;
}
else if (sStates == "RI")
{
fltTaxRate = .07f;
}
else if (sStates == "VT")
{
fltTaxRate = .06f;
}
return fltTaxRate;
}
//Method 3
private void formatWrapperSample()
{
txtWrapperSample.Text = txtLine1.Text + " " +
Environment.NewLine +
txtLine2.Text + " " +
Environment.NewLine +
txtLine3.Text;
}
// Method 4
private Color GetColor(string sColorIn)
{
return Color.FromName(sColorIn);
//CALCULATIONS
decimal decTotal = 0;
//Call the price method by passing the numeric value and the text qty
txtQty.Text = getPrice(intQty);
txtPrice.Text = decPrice.ToString("C2");
// Compute the total
decTotal = (intQty * decPrice) * (1 + fltTaxRate);
txtTotal.Text = decTotal.ToString("C2");
}
private void cboWrapperColor_SelectedIndexChanged(object sender, EventArgs e)
{
//Label Color 'cboWrapperColor_Selected' is a typo
txtWrapperSample.BackColor = GetColor(cboLabelColor.Text);
}
private void cboFontColor_SelectedIndexChanged(object sender, EventArgs e)
{
txtWrapperSample.ForeColor = GetColor(cboFontColor.Text);
}
private void cboStates_SelectedIndexChanged(object sender, EventArgs e)
{
getTaxRate("P2");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtLine1.Clear();
txtLine2.Clear();
txtLine3.Clear();
txtQty.Clear();
txtWrapperSample.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
It looks like there is some code missing, is everything starting with //CALCULATIONS to the end of the code part of the GetColor() method?
At any rate, you're declaring and initializing intQty in your btnCalculate_Click event handler. This means that the rest of your program does not know about intQty (with the exception of GetPrice() since you're passing it in).
Declare intQty as a global variable at the top of your class and then set the correct value in btnCalculate_Click
That way when you go to do the calculations it will know about intQty
Also...
You are using exceptions to control program flow, which is generally considered bad practice.
Exceptions are for exceptional cases, because they are computationally expensive.
You should use Int32.TryParse() instead
txtQty.Text = getPrice(intQty);
For one your method returns Decimal - you can't assign it to String property. C# is stringly typed.

calculate difference between 2 dates from datetimepicker [duplicate]

This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these

Categories