public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; try { String[] ReturnValue; Char[] InputValue = {'d', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y'}; DateTime Test = new DateTime(2000, 06, 06); CultureInfo[] ciTest = CultureInfo.GetCultures (CultureTypes.AllCultures); strLoc = "Loc_400vy"; foreach (CultureInfo ci in ciTest) { if(ci.IsNeutralCulture) continue; foreach (Char inputchar in InputValue) { iCountTestcases++; ReturnValue = Test.GetDateTimeFormats(inputchar,ci); if (ReturnValue.Length < 1) { printerr( "Error_100aa! No Date Time Formats were returned SentIn==(" + inputchar.ToString() + "," + ci.ToString() + ")" ); } } } strLoc = "Loc_524vy"; iCountTestcases++; try { ReturnValue = Test.GetDateTimeFormats('a',CultureInfo.InvariantCulture); iCountErrors++; printerr( "Error_200bb! no exception thrown"); } catch (FormatException) { printinfo( "Info_512ad! Caught FormatException"); } catch (Exception e) { ++iCountErrors; printerr( "Error_200aa! Wrong exception thrown: " + e.ToString()); } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
public void GeraUpdateComparadorProduto() { DateTime data = new DateTime(2015, 11, 07); ComparadorProdutos comparador = new ComparadorProdutos(); comparador.Id = 20; DictionaryEntitiesAspects.GetInstance().AddOrRefreshAspect(comparador); target = new CommandUpdateGenerator(comparador); Assert.That(target.GetCommand(), Is.EqualTo("")); comparador.DataComparacao = data; comparador.ProdutoA = new Produto(); comparador.ProdutoA.Id = 4; comparador.ProdutoA.Nome = "Trigo"; comparador.ProdutoB = new Produto(); comparador.ProdutoB.Id = 23; comparador.ProdutoB.Nome = "Macarrão"; string update = ""; update += "UPDATE comparador_produtos "; update += "SET data_comparacao = '" + data.GetDateTimeFormats()[54] + "', "; update += "id_produto_a = 4, "; update += "id_produto_b = 23 "; update += "WHERE id = 20"; target = new CommandUpdateGenerator(comparador); Assert.That(target.GetCommand(), Is.EqualTo(update)); }
// See Autodesk AuthTokenServer.js // Request token from Autodesk API using credentials private async Task<BrokerToken> GetAccessToken() { string baseUrl = "https://developer.api.autodesk.com/"; HttpContent reqData = new FormUrlEncodedContent(Credentials); try { using (var client = new HttpClient()) { string contentText = null; client.BaseAddress = new Uri(baseUrl); reqData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage response = await client.PostAsync("authentication/v1/authenticate", reqData); if (!response.IsSuccessStatusCode) { Debug.WriteLine("AUTH TOKEN: Call to AD authenticate failed."); } contentText = await response.Content.ReadAsStringAsync(); TokenIssuedTime = DateTime.Now; Debug.WriteLine(contentText, "AUTH TOKEN: Content text is "); Debug.WriteLine(TokenIssuedTime.GetDateTimeFormats('T')[0], "AUTH TOKEN: Issued time is "); return JsonConvert.DeserializeObject<BrokerToken>(contentText); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine("AUTH TOKEN: Caught authenticate call to AD API."); System.Diagnostics.Debug.WriteLine(exception); throw; } }
public String ToString(List<Column> excludedColumns) { StringBuilder row = new StringBuilder(""); if (Values.Count > 0) { DateTime dateTime = new DateTime(); dateTime.GetDateTimeFormats(); for (int i = 0; i < Values.Count; i++) { if (!isExcludedValue(excludedColumns, Values[i])) { if (row.Length > 0) row.Append(","); if (isValidValue(Values[i].Value.ToString())) { if (!isDate(Values[i].Value.ToString(), out dateTime)) row.Append("'" + Values[i].Value + "'"); else row.Append("'" + dateTime.ToString("yyyy-MM-dd") + "'"); } else { row.Append("NULL"); } } } } return row.ToString(); }
public string UnixTimeToDateTime(double value) { System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddSeconds(value); string newDate = dateTime.GetDateTimeFormats('d')[0]; return(newDate); }
private void button3_Click(object sender, RoutedEventArgs e) { double timestamp = Convert.ToDouble("1363195860"); // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(timestamp); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. string printDate = dateTime.GetDateTimeFormats()[104]; MessageBox.Show(printDate); }
/// <summary> /// Выбираем записи для синхронизации /// </summary> /// <param name="DT">Дата последней синхронизации</param> public List<string> GetSyncData(DateTime DT) { List<string> res = new List<string>(); var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, dbname); using (var db = new SQLiteConnection(dbPath)) { string[] tm = DT.GetDateTimeFormats(); var changes = db.Query<ChangesTable>("SELECT _DBString FROM ChangesTable WHERE _ChangesDateTime >'" + tm[46] + "';"); foreach (ChangesTable ct in changes) { res.Add(ct._DBString); } } return res; }
public ReportViewModel ConvertToViewModel(IEnumerable<Record> records, double sum, DateTime date) { var todayDate = new DateViewModel { FullDate = DateTime.Now.GetDateTimeFormats()[0], ShortDate = DateTime.Now.Month + "/" + DateTime.Now.Day + "/" + DateTime.Now.Year }; var reportDate = new DateViewModel { FullDate = date.GetDateTimeFormats()[0], ShortDate = date.Month + "/" + date.Day + "/" + date.Year }; var recordsViewModel = new RecordsViewModel { Records = records.Select(ConvertToViewModel), Sum = sum }; return new ReportViewModel(todayDate, reportDate, recordsViewModel); }
public bool runTest() { Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer); String strLoc = "Loc_000oo"; String strValue = String.Empty; int iCountErrors = 0; int iCountTestcases = 0; try { String[] ReturnValue; DateTime Test = new DateTime(2000, 06, 06); CultureInfo[] ciTest = CultureInfo.GetCultures(CultureTypes.AllCultures); strLoc = "Loc_400vy"; foreach (CultureInfo ci in ciTest) { iCountTestcases++; if(ci.IsNeutralCulture) continue; ReturnValue = Test.GetDateTimeFormats(ci); if (ReturnValue.Length < 1) { ++iCountErrors; printerr( "Error_100aa! No Date Time Formats were returned"); } } } catch (Exception exc_general ) { ++iCountErrors; Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy! strLoc=="+ strLoc +", exc_general=="+exc_general.ToString()); } if ( iCountErrors == 0 ) { Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString()); return true; } else { Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums ); return false; } }
private void UpdatePage(DateTime date) { try { var ValuesList = new List<DateValues>(); VentsTools.currentActionString = "Подключаюсь к Базе данных"; _fndHwnd = GetCurrentThreadId(); //запустим таймер с задержкой в 1с для отображения прогрессбара (бесячий кругалек, когда все зависло) ProgressBarPerform = new KeyValuePair<bool, int>(true, 1000); string ventName = (string)Dispatcher.Invoke(new Func<string>(() => (VentsListBox.SelectedItem as Vents).name)); // возвращает название выбранного вентилятора bool RDVres = _vt.ReadDayValuesFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref ValuesList); if (!RDVres) throw new Exception(String.Format("Не удалось получить ежедневные данные для {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); })))); //разобьем список на несколько по VentsConst._VALUE_ROWS_HOURTABLE итемов в каждом var parts = ValuesList.DivideByLenght(VentsConst._VALUE_ROWS_DAYTABLE); double cellWidth = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Width / VentsConst._MAXIMUM_COLUMNS_DAYTABLE)); double cellHeight = (double)Dispatcher.Invoke(new Func<double>(() => workGrid.Height / VentsConst._MAXIMUM_ROWS_DAYTABLE)); Dispatcher.Invoke(new Action(delegate { BuildDayTable(parts, cellWidth, cellHeight); })); //построим таблицу #region autogenerated datagrid //Dispatcher.Invoke(new Action(delegate //{ // workGrid.Children.Clear(); // for (int i = 0; i < 3;i++ ) // { // List<DateValues> listDV = parts[i]; // DataGrid dataGrid = new DataGrid(); // dataGrid.AutoGenerateColumns = true; // dataGrid.MaxHeight = 380; // //dataGrid.MaxWidth = 140; // dataGrid.Width = 156; // dataGrid.MaxWidth = 156; // dataGrid.Margin = new Thickness(200 + dataGrid.Width * i, 59, 0, 0); // dataGrid.RowHeight = 30; // dataGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; // dataGrid.VerticalAlignment = System.Windows.VerticalAlignment.Top; // dataGrid.CanUserAddRows = false; // dataGrid.CanUserDeleteRows = false; // dataGrid.CanUserReorderColumns = false; // dataGrid.CanUserResizeColumns = false; // dataGrid.CanUserResizeRows = false; // dataGrid.CanUserSortColumns = false; // dataGrid.IsReadOnly = true; // dataGrid.IsHitTestVisible = false; // dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled; // dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; // // dataGrid.HorizontalGridLinesBrush = new SolidColorBrush(Color.FromRgb(255,255,255)); // dataGrid.ItemsSource = listDV; // dataGrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(OnAutoGeneratingColumn); // // var trtr = dataGrid.ColumnWidth; // workGrid.Children.Add(dataGrid); // } //})); #endregion //calculate monthly electric power expense int monthlyExpense = 0; if (date != _firstMonth) { bool daylyRes = _vt.ReadMonthlyExpenseFromDB(VentsConst.connectionString, VentsConst._DATAtb, ventName, date, ref monthlyExpense); if (!daylyRes) { throw new Exception(String.Format("Не удалось получить данные для месячного расхода {0} за {1}", (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })), (string)Dispatcher.Invoke(new Func<string>(delegate { return (string)dateP.DisplayDate.ToString(); })))); } } else { monthlyExpense = ValuesList.Last<DateValues>().value - ValuesList.First<DateValues>().value; } monthlyExpense = monthlyExpense * 100; Dispatcher.Invoke(new Action(delegate { totaltb.Text = String.Format("Расход {0} за {1} равен {2} кВтч", (VentsListBox.SelectedItem as Vents).descr, date.GetDateTimeFormats('O')[0].Substring(0, 8), monthlyExpense.ToString()); })); //generate current action string and update content of main window textbox string descr = (string)Dispatcher.Invoke(new Func<string>(delegate { return (VentsListBox.SelectedItem as Vents).descr; })); VentsTools.currentActionString = String.Format("Показания за {0} {1}", date.Date.GetDateTimeFormats('D', CultureInfo.CreateSpecificCulture("ru-ru"))[0], descr); ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000); _fndHwnd = IntPtr.Zero; } catch (Exception ex) { VentsTools.currentActionString = "Не удалось подключиться к базе данных"; _log.Error(ex.Message); ProgressBarPerform = new KeyValuePair<bool, int>(false, 1000); _fndHwnd = IntPtr.Zero; } }
/// <summary></summary> /// <param name="classificazioni"></param> /// <param name="infoUtente"></param> /// <returns></returns> public static DocsPaVO.documento.FileDocumento getTitolarioReport(string idAmministrazione, string idGruppo, string idPeople, System.Collections.ArrayList classificazioni) { DocsPaVO.documento.FileDocumento result = new DocsPaVO.documento.FileDocumento(); //string path = ReportUtils.getPathName(); //string path = DocsPaUtils.Functions.Functions.GetReportsPath(); string path = AppDomain.CurrentDomain.BaseDirectory; try { string headerString = ReportUtils.stringFile(path + "report\\titolario\\headerTitolario.txt"); logger.Debug("Generazione report"); System.DateTime data = System.DateTime.Now; System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("it-IT"); string[] formats = data.GetDateTimeFormats(ci); string dataString = formats[5]; headerString = headerString.Replace("XDATA", dataString); //string titolo=ConfigurationManager.AppSettings["intestazioneTitolario"]; string titolo = "Titolario"; // prima lo prendeva dal web.config, ma non esiste più if (titolo != null) { headerString = headerString.Replace("XTITOLO", titolo); } else { headerString = headerString.Replace("XTITOLO", ""); } System.Collections.ArrayList report = new System.Collections.ArrayList(); ReportUtils.addStringToReport(headerString, ref report); logger.Debug("Inserimento voci di titolario"); for (int i = 0; i < classificazioni.Count; i++) { DocsPaVO.fascicolazione.Classificazione classificazione = (DocsPaVO.fascicolazione.Classificazione)classificazioni[i]; string headerTableString = ReportUtils.stringFile(path + "report\\titolario\\headerTableTitolario.txt"); headerTableString = headerTableString.Replace("XPRIMO_CODICE", classificazione.codice); headerTableString = headerTableString.Replace("XPRIMA_DESCR", classificazione.descrizione); ReportUtils.addStringToReport(headerTableString, ref report); for (int j = 0; j < classificazione.childs.Count; j++) { buildClassificazione(idAmministrazione, idGruppo, idPeople, (DocsPaVO.fascicolazione.Classificazione)classificazione.childs[j], 0, ref report, path); } //inserimento fascicoli proc //addFascProc(idAmministrazione, idGruppo, idPeople, classificazione,0,ref report,path); string bottomTableString = ReportUtils.stringFile(path + "report\\titolario\\bottomTableTitolario.txt"); ReportUtils.addStringToReport(bottomTableString, ref report); } logger.Debug("Inserimento bottom"); string bottomString = ReportUtils.stringFile(path + "report\\titolario\\bottomTitolario.txt"); ReportUtils.addStringToReport(bottomString, ref report); logger.Debug("Generazione fileDocumento"); result.content = (byte[])report.ToArray(typeof(byte)); result.length = result.content.Length; result.contentType = "application/rtf"; result.name = "report.rtf"; logger.Debug("fileDocumento generato"); } catch (Exception e) { logger.Debug("Errore nella gestione di Report (getTitolarioReport)", e); throw e; } return(result); }
public void default_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { String speech1 = e.Result.Text; // of.mainLabel.Text = speech1; Login login = new Login(of); Admin admin = new Admin(of); if (speech1 == "Hello" && e.Result.Confidence > 0.92 || speech1 == "Open admin" && e.Result.Confidence > 0.92 || speech1 == "Close admin" && e.Result.Confidence > 0.92) { switch (speech1) { case "What time is it?": System.DateTime now = System.DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; of.optio.SpeakAsync(time); of.productLabel.Text = ""; break; case "What day is it today?": string dayis; dayis = "Today is " + System.DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-US")); of.optio.SpeakAsync(dayis); of.productLabel.Text = ""; break; case "What is todays date?": string date; date = "the date is " + System.DateTime.Now.ToString("dd MMM yyyy", new System.Globalization.CultureInfo("en-US")); of.optio.SpeakAsync(date); of.productLabel.Text = ""; break; case "What can you do?": string action; action = "I can help you find anything you are looking for"; of.optio.SpeakAsync(action); of.productLabel.Text = ""; of.mainLabel.Text = action; break; case "What is your name?": string name; name = "My name is Optio"; of.optio.SpeakAsync(name); of.productLabel.Text = ""; of.mainLabel.Text = name; break; case "Hello": string greeting; greeting = "Hi, what would you like to find?"; of.optio.SpeakAsync(greeting); of.mainLabel.Text = greeting; of.productLabel.Text = ""; break; case "Open admin": of.optio.SpeakAsync("opening Admin"); of.productLabel.Text = ""; of.mainLabel.Text = ""; Task.Delay(5000); if (Application.OpenForms.OfType <Login>().Count() == 1) { Application.OpenForms.OfType <Login>().First().Close(); } login.Show(); login.TopMost = true; Cursor.Show(); volumeCheck(); break; case "Close admin": // of.optio.Volume = 100; of.optio.SpeakAsync("Closing admin"); of.refreshForm(); if (Application.OpenForms.OfType <Login>().Count() == 1) { Application.OpenForms.OfType <Login>().Last().Close(); } break; } } }
private void speechreco_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { int ranNum; Random rnd = new Random(); richTextBox1.Text = e.Result.Text; string speech = e.Result.Text; if (speech == "hello") { jarvis.Speak("hello and how are you?"); UnloadJarvis(); } if (speech == "how are you jarvis") { jarvis.Speak("i am fine sir, what would you like to do?"); UnloadJarvis(); } if (speech == "open google") { jarvis.Speak("loading google"); System.Diagnostics.Process.Start("http://www.google.com"); UnloadJarvis(); } if (speech == "open youtube") { jarvis.Speak("loading youtube"); System.Diagnostics.Process.Start("http://www.youtube.com"); UnloadJarvis(); } if (speech == "bye" || speech =="see you jarvis") { jarvis.Speak("Goodbye Sir, See you next time"); this.Close(); } if (speech == "hide") { jarvis.Speak("call me when you need me i'll be right here"); this.Hide(); UnloadJarvis(); } if (speech == "say hi jarvis") { jarvis.Speak("Hello Ladies and gentlemen!"); UnloadJarvis(); } if (speech == "whats the weather") { jarvis.Speak("i'll check for you now"); System.Diagnostics.Process.Start("http://www.weatherzone.com.au/"); UnloadJarvis(); } if (speech == "open steam") { jarvis.Speak("opening steam"); System.Diagnostics.Process.Start(@"S:\Steam\Steam.exe"); UnloadJarvis(); } if (speech == "open notepad") { jarvis.Speak("opening"); System.Diagnostics.Process.Start("c:\\windows\\system32\\notepad.exe"); UnloadJarvis(); } if (speech == "close notepad") { jarvis.Speak("closing notepad"); System.Diagnostics.Process q; q = System.Diagnostics.Process.GetProcessesByName("notepad")[0]; q.Kill(); UnloadJarvis(); } if (speech == "open visual studio") { jarvis.Speak("opening visual studio"); System.Diagnostics.Process.Start(@"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2017"); UnloadJarvis(); } if (speech == "who made you") { jarvis.Speak("Abner the great made me"); UnloadJarvis(); } if (speech == "how old are you") { jarvis.Speak("Not very old, i was born on April 12, 2017 "); UnloadJarvis(); } if (speech == "open facebook") { jarvis.Speak("opening facebook"); System.Diagnostics.Process.Start("https://www.facebook.com/"); UnloadJarvis(); } if (speech == "close window") { jarvis.Speak("Closing Window"); SendKeys.SendWait("%{F4}"); jarvis.Speak("Window Closed"); UnloadJarvis(); } if (speech == "show desktop") { jarvis.Speak("agreed"); this.WindowState = FormWindowState.Minimized; Type typeShell = Type.GetTypeFromProgID("Shell.Application"); object objShell = Activator.CreateInstance(typeShell); typeShell.InvokeMember("MinimizeAll", System.Reflection.BindingFlags.InvokeMethod, null, objShell, null); jarvis.Speak("here is your desktop"); UnloadJarvis(); } if (speech == "hey jarvis" || speech == "jarvis") { HeyJarvis(); ranNum = rnd.Next(1, 5); if (ranNum == 1) { jarvis.Speak("Yes sir");} else if (ranNum == 2) { jarvis.Speak("Yes?");} else if (ranNum == 3) { jarvis.Speak("Yes sir. How may I help?");} else if (ranNum == 4) { jarvis.Speak("Yes sir. How may I be of assistance?");} } if (speech == "whats the date today") { string date; date = "the date is," + System.DateTime.Now.ToString("dd MMMM", new System.Globalization.CultureInfo("en-US")); jarvis.SpeakAsync(date); date = "" + System.DateTime.Today.ToString(" yyyy"); jarvis.Speak(date); UnloadJarvis(); } if (speech == "what day is it") { string dayis; dayis = "Today is," + System.DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("en-US")); jarvis.SpeakAsync(dayis); UnloadJarvis(); } if (speech == "what time is it" || speech == "whats the time") { System.DateTime now = System.DateTime.Now; ranNum = rnd.Next(1, 3); string time = now.GetDateTimeFormats('t')[0]; if (ranNum == 1) { jarvis.Speak("Time check " + time);} else if (ranNum == 2) { jarvis.Speak("The time is" + time);} else if (ranNum == 3) { jarvis.Speak("Wait I am reading the time " + " The time is " + time);} UnloadJarvis(); } if (speech == "show yourself" || speech == "expand") { jarvis.Speak("Expanding"); Form1 frm = new Form1(); this.Show(); frm.BringToFront(); UnloadJarvis(); } if (speech == "open email") { jarvis.Speak("loading email"); System.Diagnostics.Process.Start("https://login.yahoo.com/config/mail?&.src=ym&.intl=au"); UnloadJarvis(); } if (speech == "find jobs") { jarvis.Speak("i'll search for you"); System.Diagnostics.Process.Start("https://www.seek.com.au/?tracking=SEM-GGL-SRC-PaidSearchAU-3698&gclid=Cj0KEQjww7zHBRCToPSj_c_WjZIBEiQAj8il5O3TUIwVOq_LFns6msF0USeDTNqGyS5JncCDWJxG1pIaAvJy8P8HAQ&gclsrc=aw.ds&dclid=CJ7e-uutodMCFYJ1vQodWhsNcA"); jarvis.Speak("Search desired job here"); UnloadJarvis(); } if (speech == "open coin spot") { jarvis.Speak("Okay, opening coinspot"); System.Diagnostics.Process.Start("https://www.coinspot.com.au"); jarvis.Speak("Here's your crypto currency status sir"); UnloadJarvis(); } jarvis.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>(jarvis_SpeakCompleted); }
private int IsAddDayFun(DateTime dt, DateTime isAddDay, int days, bool schedule) { long num_date = CommonFunction.GetPHPTime(dt.ToString());///獲得基本發貨時間的基數 string dtFlagStr = isAddDay.GetDateTimeFormats()[0] + " 15:00";///計算出是否+1天的時間邊 long dtFlag = CommonFunction.GetPHPTime(dtFlagStr);///獲得當天15:00的時間蹉 long isAddDayInt = CommonFunction.GetPHPTime(isAddDay.ToString("yyyy-MM-dd HH:mm:ss"));///獲得下單時間的時間戳 DateTime dateBase = dt.Date;///獲得預計出貨日的日期部份 DateTime dateDay = isAddDay.Date;///獲得下單日期的日期部份 if (dateBase != dateDay && schedule==true) { return days; } else { return days = (isAddDayInt - dtFlag) > 0 ? days + 1 : days; //判斷時間是否大於15點,大於時,運達天數加1 } }
/// <summary> /// Performs file rollover by renaming the current log file and deleting old files as necessary. /// The rename causes the next log request to generate a new file and log to it. /// </summary> /// <param name="logFile">Base log file name.</param> /// <param name="createdDate">The date the file to be renamed was initially created.</param> /// <param name="rollOverFilesToKeep">Number of files to keep. Causes deletion of oldest files.</param> /// <returns>True if successful.</returns> private bool RolloverFile(string logFile, DateTime createdDate, int rollOverFilesToKeep) { string stringDate = createdDate.GetDateTimeFormats()[103]; //Get the date in a format to use in the file name. stringDate = stringDate.Replace(":", "."); string stringTicks = DateTime.Now.Ticks.ToString(); string directoryName = Path.GetDirectoryName(logFile); string rolledLogFile = ""; bool success = false; try { //Rename the file with date and time plus ticks to ensure uniqueness rolledLogFile = Path.Combine(directoryName, Path.GetFileNameWithoutExtension(logFile) + "_" + stringDate + "." + stringTicks + Path.GetExtension(logFile)); File.Move(logFile, rolledLogFile); //Rename the file with a date. string[] archivedFiles = Directory.GetFiles(directoryName, Path.GetFileNameWithoutExtension(logFile) + "_*" + Path.GetExtension(logFile)); if (archivedFiles.Length > (rollOverFilesToKeep)) { Array.Sort(archivedFiles); for (int i=0; i < (archivedFiles.Length - rollOverFilesToKeep); i++) { File.Delete(Path.Combine(directoryName, archivedFiles[i])); } } success = true; } catch (Exception e) { //Default to continue logging rather than raising an error. //If the file was already moved or other error, we're assuming another process succeeded. Logger.Write("Failed rolling over or deleting files: " + logFile + Environment.NewLine + e.Message); } return success; }
public static void GetDateTimeFormats_FormatSpecifier_InvalidFormat() { var dateTime = new DateTime(2009, 7, 28, 5, 23, 15); Assert.Throws<FormatException>(() => dateTime.GetDateTimeFormats('x')); // No such format }
public static void TestGetDateTimeFormats() { char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); List<string> july28Formats = new List<string>(); foreach (char format in allStandardFormats) { string[] dates = july28.GetDateTimeFormats(format); Assert.True(dates.Length > 0); DateTime parsedDate; Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate)); july28Formats.AddRange(dates); } List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); }
private void button1_Click(object sender, RoutedEventArgs e) { var webClient = new WebClient(); string server_time = webClient.DownloadString("http://fuzonmedia.com/BC_Service_Important/server_time.txt"); //Configure the ProgressBar ProgressBar1.Minimum = 0; ProgressBar1.Value = 0; //Stores the value of the ProgressBar double p_value = 0; UpdateProgressBarDelegate updatePbDelegate = new UpdateProgressBarDelegate(ProgressBar1.SetValue); List <task_data> freport = new List <task_data>(); process_status.Content = "Please wait while we creating task ...."; button1.Content = "Wait..."; button1.IsEnabled = false; if (MessageBox.Show("Are you sure want to proceed?", "Warning!", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { try { ProgressBar1.Minimum = 0; ProgressBar1.Value = 0; ProgressBar1.Maximum = 50; WebRequest req_big_order_count = WebRequest.Create(big_storeurl.Text + "orders?status_id=11"); // WebRequest req_big_order_count = WebRequest.Create(big_storeurl.Text + "orders/2338"); HttpWebRequest httpreq_order_count = (HttpWebRequest)req_big_order_count; httpreq_order_count.Method = "GET"; httpreq_order_count.ContentType = "text/xml; charset=utf-8"; double timestamp = Convert.ToDouble(server_time); // First make a System.DateTime equivalent to the UNIX Epoch. System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); // Add the number of seconds in UNIX timestamp to be converted. dateTime = dateTime.AddSeconds(timestamp); // The dateTime now contains the right date/time so to format the string, // use the standard formatting methods of the DateTime object. string printDate = dateTime.GetDateTimeFormats()[104]; httpreq_order_count.IfModifiedSince = Convert.ToDateTime(printDate); httpreq_order_count.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_order = (HttpWebResponse)httpreq_order_count.GetResponse(); StreamReader rdr_product_count = new StreamReader(res_order.GetResponseStream()); string result_order = rdr_product_count.ReadToEnd(); //textBox1.Text = result_order; if (res_order.StatusCode == HttpStatusCode.OK || res_order.StatusCode == HttpStatusCode.Accepted) { XDocument doc_orders = XDocument.Parse(result_order); foreach (XElement order_data in doc_orders.Descendants("order")) { p_value += 1; Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, p_value }); task_data tsata = new task_data(); tsata.order_id = order_data.Element("id").Value.ToString(); // MessageBox.Show(tsata.order_id); tsata.c_message = order_data.Element("customer_message").Value.ToString().Replace("\"", "\\\"").Replace("\r\n", "\\n").Replace("\n", "\\n"); tsata.c_name = order_data.Element("billing_address").Element("first_name").Value.ToString() + " " + order_data.Element("billing_address").Element("last_name").Value.ToString(); tsata.total_cost = Convert.ToDouble(order_data.Element("total_inc_tax").Value.ToString()).ToString("0.00", CultureInfo.InvariantCulture); tsata.c_email = order_data.Element("billing_address").Element("email").Value.ToString(); tsata.c_phone = order_data.Element("billing_address").Element("phone").Value.ToString(); // MessageBox.Show("shiipping_Addes"); WebRequest req_big_shipping_count = WebRequest.Create(big_storeurl.Text + "orders/" + tsata.order_id + "/shippingaddresses"); HttpWebRequest httpreq_shipping_count = (HttpWebRequest)req_big_shipping_count; httpreq_shipping_count.Method = "GET"; httpreq_shipping_count.ContentType = "text/xml; charset=utf-8"; httpreq_shipping_count.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_shipping = (HttpWebResponse)httpreq_shipping_count.GetResponse(); StreamReader rdr_shipping_count = new StreamReader(res_shipping.GetResponseStream()); string result_shipping = rdr_shipping_count.ReadToEnd(); if (res_shipping.StatusCode == HttpStatusCode.OK || res_shipping.StatusCode == HttpStatusCode.Accepted) { XDocument doc_shippings = XDocument.Parse(result_shipping); foreach (XElement order_shipping in doc_shippings.Descendants("address")) { tsata.shipping_address = order_shipping.Element("street_1").Value.ToString() + " " + order_shipping.Element("street_2").Value.ToString(); tsata.shipping_address += "\\n" + order_shipping.Element("city").Value.ToString() + "," + order_shipping.Element("state").Value.ToString() + "," + order_shipping.Element("zip").Value.ToString(); break; } } // MessageBox.Show("Products"); WebRequest req_big_productcount = WebRequest.Create(big_storeurl.Text + "orders/" + tsata.order_id + "/products"); HttpWebRequest httpreq_product_count = (HttpWebRequest)req_big_productcount; httpreq_product_count.Method = "GET"; httpreq_product_count.ContentType = "text/xml; charset=utf-8"; httpreq_product_count.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_product = (HttpWebResponse)httpreq_product_count.GetResponse(); StreamReader rdr_product_data = new StreamReader(res_product.GetResponseStream()); string result_product = rdr_product_data.ReadToEnd(); // MessageBox.Show(result_product); if (res_product.StatusCode == HttpStatusCode.OK || res_product.StatusCode == HttpStatusCode.Accepted) { XDocument doc_products = XDocument.Parse(result_product); foreach (XElement order_product in doc_products.Descendants("product")) { string pr_op = ""; foreach (XElement order_product_options in order_product.Descendants("product_options").Descendants("option")) { // MessageBox.Show(order_product_options.Element("display_value").Value.ToString()); pr_op += order_product_options.Element("display_value").Value.ToString().Replace("\"", "\\\"") + " "; } tsata.item_details += order_product.Element("name").Value.ToString().Replace("\"", "\\\"") + " X " + order_product.Element("quantity").Value.ToString() + " - " + pr_op + " - $" + Convert.ToDouble(order_product.Element("price_inc_tax").Value.ToString()).ToString("0.00", CultureInfo.InvariantCulture) + "\\n"; } } // MessageBox.Show(tsata.shipping_address); // MessageBox.Show(tsata.item_details); // MessageBox.Show("Asana Set"); WebRequest req_asana = WebRequest.Create("https://app.asana.com/api/1.0/tasks"); HttpWebRequest httpreq_asana = (HttpWebRequest)req_asana; httpreq_asana.Method = "POST"; httpreq_asana.ContentType = "application/json"; httpreq_asana.Headers.Add("Authorization", "Basic " + asana_APIKey.Text); Stream str_asana = httpreq_asana.GetRequestStream(); StreamWriter strwriter_asana = new StreamWriter(str_asana, Encoding.ASCII); // string soaprequest_asana = "{\"data\":{\"workspace\":"+workSpaceID.Text+",\"name\":\""+"(#"+tsata.order_id+") "+tsata.c_name+" $"+tsata.total_cost+"\",\"notes\":\""+tsata.c_email+" - "+ tsata.c_phone +"\\n\\n" + tsata.shipping_address+"\\n\\n" +tsata.item_details+"\",\"assignee\":"+Assignee_ID.Text+"}}"; string soaprequest_asana = "{\"data\":{\"workspace\":" + workSpaceID.Text + ",\"name\":\"" + "(#" + tsata.order_id + ") " + tsata.c_name + " $" + tsata.total_cost + "\",\"notes\":\"" + tsata.c_email + " - " + tsata.c_phone + "\\n\\n" + tsata.shipping_address + "\\n\\n" + tsata.item_details + "\\n\\n" + tsata.c_message + "\",\"projects\":[812474455499]}}"; // MessageBox.Show(soaprequest_asana); textBox1.Text = soaprequest_asana.ToString(); strwriter_asana.Write(soaprequest_asana.ToString()); strwriter_asana.Close(); HttpWebResponse res_asana = (HttpWebResponse)httpreq_asana.GetResponse(); StreamReader rdr_asana = new StreamReader(res_asana.GetResponseStream()); string result_asana_task = rdr_asana.ReadToEnd(); // MessageBox.Show(result_asana_task); freport.Add(tsata); } } WebRequest req_big_time = WebRequest.Create(big_storeurl.Text + "time"); HttpWebRequest httpreq_time = (HttpWebRequest)req_big_time; httpreq_time.Method = "GET"; httpreq_time.ContentType = "text/xml; charset=utf-8"; httpreq_time.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_time = (HttpWebResponse)httpreq_time.GetResponse(); StreamReader rdr_time = new StreamReader(res_time.GetResponseStream()); string result_time = rdr_time.ReadToEnd(); // MessageBox.Show(result_time); if (res_time.StatusCode == HttpStatusCode.OK || res_time.StatusCode == HttpStatusCode.Accepted) { XDocument doc_time = XDocument.Parse(result_time); string stime = doc_time.Element("time").Element("time").Value.ToString(); var webClient_1 = new WebClient(); string readHtml_1 = webClient_1.DownloadString("http://fuzonmedia.com/BC_Service_Important/getData.php?time=" + stime); // File.WriteAllText("server_time.txt", stime); } p_value = 50; Dispatcher.Invoke(updatePbDelegate, System.Windows.Threading.DispatcherPriority.Background, new object[] { ProgressBar.ValueProperty, p_value }); MessageBox.Show("Task Completed"); process_status.Content = "Task Completed"; button1.IsEnabled = true; button1.Content = "Create Task"; } catch (Exception ex) { if (ex.Message == "The remote server returned an error: (304) Not Modified.") { WebRequest req_big_time = WebRequest.Create(big_storeurl.Text + "time"); HttpWebRequest httpreq_time = (HttpWebRequest)req_big_time; httpreq_time.Method = "GET"; httpreq_time.ContentType = "text/xml; charset=utf-8"; httpreq_time.Credentials = new NetworkCredential(big_user.Text, big_pass.Text); HttpWebResponse res_time = (HttpWebResponse)httpreq_time.GetResponse(); StreamReader rdr_time = new StreamReader(res_time.GetResponseStream()); string result_time = rdr_time.ReadToEnd(); // MessageBox.Show(result_time); if (res_time.StatusCode == HttpStatusCode.OK || res_time.StatusCode == HttpStatusCode.Accepted) { XDocument doc_time = XDocument.Parse(result_time); string stime = doc_time.Element("time").Element("time").Value.ToString(); var webClient_1 = new WebClient(); string readHtml_1 = webClient_1.DownloadString("http://fuzonmedia.com/BC_Service_Important/getData.php?time=" + stime); // File.WriteAllText("server_time.txt", stime); } MessageBox.Show("No New Orders yet "); process_status.Content = "No New Orders yet"; } else { MessageBox.Show(ex.Message.ToString()); process_status.Content = "Error :" + ex.Message.ToString(); } button1.IsEnabled = true; button1.Content = "Create Task"; // textBox1.Text = ex.Message.ToString(); } } else { button1.IsEnabled = true; process_status.Content = ""; button1.Content = "Create Task"; } }
private void User_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string input = e.Result.Text; Random rnd = new Random(); DateTime now = new DateTime(); switch (input) { case "hai": case "hello": case "hello bunny": if ( now.Hour >= 5 && now.Hour < 12) { bunny.SpeakAsync("Good Morning" +userName ); } if (now.Hour >= 12 && now.Hour < 18) { bunny.SpeakAsync("Good Afternoon " +userName); } if (now.Hour >= 18 && now.Hour < 24) { bunny.SpeakAsync("Good Evening " +userName); } if (now.Hour < 5) { bunny.SpeakAsync("Hello " +userName + ", it's getting late"); } break; case "bunny": case "hey": ranNum = rnd.Next(1, 5); if (ranNum == 1) { bunny.SpeakAsync("Yes sir"); } else if (ranNum == 2) { bunny.SpeakAsync("Yes?"); } else if (ranNum == 3) { bunny.SpeakAsync("How may I help?"); } else if (ranNum == 4) { bunny.SpeakAsync("How may I be of assistance?"); } break; case "what is my name": bunny.SpeakAsync( " " +userName.ToString() ); break; case "what time is it": string time = now.GetDateTimeFormats('t')[0]; bunny.SpeakAsync("time"); break; case "what day is it": bunny.SpeakAsync(DateTime.Today.ToString("dddd")); break; case "what date is it": bunny.SpeakAsync(DateTime.Today.ToString("dd-MM-yyyy")); break; case "out of the way": case "offscreen": if (WindowState == FormWindowState.Normal || WindowState == FormWindowState.Maximized) { WindowState = FormWindowState.Minimized; bunny.SpeakAsync("My Apologies"); } break; case "come back": case "onscreen": if (WindowState == FormWindowState.Minimized) { bunny.SpeakAsync("Onscreen Sir"); WindowState = FormWindowState.Normal; } break; case "go fullscreen": FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Maximized; TopMost = true; bunny.SpeakAsync("Expanding sir"); break; case "exit fullscreen": FormBorderStyle = FormBorderStyle.Sizable; WindowState = FormWindowState.Normal; TopMost = false; bunny.SpeakAsync("Exiting sir"); break; case "goodbye": case "bye": case "goodbye bunny": case "close bunny": case "go offline": case "see you": if (ranNum > 6) { bunny.SpeakAsync("Farewell"); Close(); } else { bunny.SpeakAsync("GoodBye"); Close(); } break; case "shutdown": System.Diagnostics.Process.Start("shutdown" , "-s"); break; case "logoff": System.Diagnostics.Process.Start("logoff" , "-l"); break; case "restart": System.Diagnostics.Process.Start("restart" , "-r"); break; } }
public override void Run(String called) { called = called.ToLower(); called = called.Replace("\"", ""); called = called.Replace("o'clock", ""); List<String> words = new List<string>(called.Split(' ')); for (int i = words.Count - 1; i >= 0; --i) { if (_units.Keys.Contains<String>(words[i])) continue; words.RemoveAt(i); } String[] numbersString = words.ToArray(); if (numbersString.Length > 2 || numbersString.Length == 0) { Speak("I don't understand that time " + String.Join(" ", numbersString)); return; } int year = DateTime.Today.Year; int month = DateTime.Today.Month; int day = DateTime.Today.Day; int hour = _units[numbersString[0]]; int minute = numbersString.Length == 2 ? _units[numbersString[1]] : 0; DateTime wakeupTime = new DateTime(year, month, day, hour, minute, 0); DateTime old = wakeupTime; if (wakeupTime < DateTime.Now) { wakeupTime = wakeupTime.AddHours(12); if (wakeupTime < DateTime.Now) { wakeupTime = old.AddDays(1); } } SetWaitForWakeUpTime(wakeupTime); _wakeUpTimer = new Timer(); _wakeUpTimer.Interval = (int)(wakeupTime - DateTime.Now).TotalMilliseconds; _wakeUpTimer.AutoReset = false; _wakeUpTimer.Elapsed += new ElapsedEventHandler(_wakeUpTimer_Elapsed); _wakeUpTimer.Start(); Speak("Wake up set for " + wakeupTime.GetDateTimeFormats()[110]); WakeUpSet = true; Settings.Muted = true; }
private void MainEvent_Recognized(object sender, SpeechRecognizedEventArgs e) { try { string Name = "Trendon"; string AI_name = "Decca"; string speech = e.Result.Text; int ranNum; if (speech == "Hey Decca") { wake = true; } if (speech == "stop talking") { Decca.SpeakAsyncCancelAll(); ranNum = rnd.Next(1, 2); if (ranNum == 1) { SayAsync("Yes sir"); } if (ranNum == 2) { SayAsync("I am sorry I will be quiet"); } } if (wake == true) { RoskamWeightEst Roskam = new RoskamWeightEst(); SystemsEngApproachAircraftDesign systemsEng = new SystemsEngApproachAircraftDesign(); GAAircraftDesign gA = new GAAircraftDesign(); switch (speech) { case "what's up": //Decca.SpeakAsync("hello" + Name); System.DateTime timenow = System.DateTime.Now; if (timenow.Hour >= 5 && timenow.Hour < 12) { SayAsync("Goodmorning" + Name); } if (timenow.Hour >= 12 && timenow.Hour < 18) { SayAsync("Good afternoon" + Name); } if (timenow.Hour >= 18 && timenow.Hour < 24) { SayAsync("Good evening" + Name); } if (timenow.Hour < 5) { SayAsync("Hello" + Name + ", you are still awake, you should go to sleep, it's getting late."); } break; case "stop listening": SayAsync("If you need me ask"); Recog_speech.RecognizeAsyncCancel(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "stop talking": Decca.SpeakAsyncCancelAll(); ranNum = rnd.Next(1, 2); if (ranNum == 1) { SayAsync("Yes sir"); } if (ranNum == 2) { SayAsync("I am sorry I will be quiet"); } break; case "What time is it": System.DateTime now = System.DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; SayAsync(time); break; case "what day is it": string dayis; dayis = "Today is, " + System.DateTime.Now.ToString("dddd"); SayAsync(dayis); break; case "what is todays date": string date = "Today is, " + System.DateTime.Now.ToString("dd MMM"); SayAsync(date); date = "" + "in the year, " + System.DateTime.Now.ToString("yyyy"); SayAsync(date); break; case "slow down decca": Decca.Rate -= 1; break; case "speed up decca": Decca.Rate += 1; break; case "crossword": SayAsync("Opening Teachers Corner"); Process.Start(@"https://worksheets.theteacherscorner.net/make-your-own/crossword/"); break; case "coin market cap": Process.Start(@"https://coinmarketcap.com/"); break; case "youtube history": SayAsync("Opening your youtube history"); Process.Start(@"https://www.youtube.com/feed/history"); break; case "bitcoin chart": Process.Start(@"https://www.tradingview.com/chart/Vu7Cuxnk/-"); break; case "Professor Black": SayAsync("Opening Professor Black"); Process.Start(@"https://www.youtube.com/channel/UCRteR6kiJwk-bTA5eWPqapg/videos"); break; case "Jason Black": SayAsync("Opening Jason Black"); Process.Start(@"https://www.youtube.com/channel/UCRteR6kiJwk-bTA5eWPqapg/videos"); break; case "Doctor Mumbi": SayAsync("Opening Doctor Mumbi"); Process.Start(@"https://www.youtube.com/channel/UCypMLiyzMFoBQFAu346lh7w/videos"); break; case "Fox Learn": SayAsync("Opening Fox Learn"); Process.Start(@"https://www.youtube.com/channel/UC8inCnD25Es0VLokfmhko5g/playlists"); break; case "Money GPS": SayAsync("Opening Money GPS"); Process.Start(@"https://www.youtube.com/user/TheMoneyGPS/videos"); break; case "L A R Movement": SayAsync("Opening L A R Movement"); Process.Start(@"https://www.youtube.com/user/larmovement/videos"); break; case "Quizlet": SayAsync("Opening Quizlet"); Process.Start(@"https://quizlet.com/latest"); break; case "Influence Frame": SayAsync("Opening Influence Frame"); Process.Start(@"https://www.youtube.com/channel/UCfhb_xrcYP-m2OQPybV-Khw/videos"); break; case "Youtube Money Income Profit": SayAsync("Opening Money Income Profit"); Process.Start(@"https://www.youtube.com/user/Glendon007/videos"); break; case "Money Income Profit": SayAsync("Opening Money Income Profit"); Process.Start(@"https://moneyincomeprofit.com/courses/enrolled/473974"); break; case "School tests": case "School comments": SayAsync("Opening Lingoseed Teacher Portal"); Process.Start(@"https://drive.google.com/drive/folders/1G23irleFIGcCBQf7Y8Oh93xlGEAmI6hK"); break; case "library": LibraryOpen(); break; case "who are you": SayAsync("I am Decca, you're personal assistant in your creative design endeavors"); break; case "what is your name": SayAsync("My name is " + AI_name + ", How can I help you " + Name); break; case "open website reader": Decca.Speak("Opening website reader"); DeccaWebSearch deccaWeb = new DeccaWebSearch(); deccaWeb.Show(); Recog_speech.RecognizeAsyncCancel(); // Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "open weather": Decca.Speak("Opening weather app"); DeccaWeather deccaWeather = new DeccaWeather(); deccaWeather.Show(); Recog_speech.RecognizeAsyncCancel(); //Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "open media player": Decca.Speak("Opening media player"); DeccaMediaPlayer deccaMediaPlayer = new DeccaMediaPlayer(); deccaMediaPlayer.Show(); Recog_speech.RecognizeAsyncCancel(); //Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "close library": killProg("LibraryManagement"); break; case "Roskam Design": Decca.Speak("Opening Roskam Design"); Roskam.Show(); Recog_speech.RecognizeAsyncCancel(); //Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "G A Design": Decca.Speak("Opening General Aviation Design"); gA.Show();; Recog_speech.RecognizeAsyncCancel(); //wRecog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "Systems Design": Decca.Speak("Opening Systems Design"); systemsEng.Show(); Recog_speech.RecognizeAsyncCancel(); //Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "Calculator": Decca.Speak("Opening Altitude Calculator"); DeccaCalculator deccaCalculator = new DeccaCalculator(); deccaCalculator.Show();; Recog_speech.RecognizeAsyncCancel(); //Recog_speech.Dispose(); listen.RecognizeAsync(RecognizeMode.Multiple); break; case "See you later Decca": case "Bye Bye": case "Later Decca": System.DateTime timenow1 = System.DateTime.Now; if (timenow1.Hour >= 5 && timenow1.Hour < 12) { Decca.Speak("Have a wonderful morning and spectacular day" + Name); } if (timenow1.Hour >= 12 && timenow1.Hour < 18) { Decca.Speak("Have a splendid afternoon" + Name); } if (timenow1.Hour >= 18 && timenow1.Hour < 24) { Decca.Speak("What a wonderful evening, do not forget to grab dinner" + Name); } if (timenow1.Hour < 5) { Decca.Speak(Name + ", you are still awake, you should go to sleep, it's getting late."); } Application.Exit(); break; } } } catch { return; } }
public string ChangeToDatetimeFormat(string ticks) { System.DateTime time = new System.DateTime(long.Parse(ticks)); string[] datetimeFormat = time.GetDateTimeFormats('f'); return(datetimeFormat[0]); }
//returns the Google Time Format String of a given .Net DateTime value //Google Time Format = "2012-08-20T00:00:00+02:00" public string GoogleTimeFrom(DateTime dt) { string timezone = TimeZoneInfo.Local.GetUtcOffset(dt).ToString(); if (timezone[0] != '-') timezone = '+' + timezone; timezone = timezone.Substring(0,6); string result = dt.GetDateTimeFormats('s')[0] + timezone; return result; }
private void Speechreco_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { /* * Could create a text document with only sophie * Then when Sophie is mentioned, loadGrammarAndCommands * See how I use sleep. This could also be done to trigger Jarvis, but I like this better * Possibly have a new text file for tasks, such as call the Weather Function. * Should call Weather, until we close weather, close in itself should loadGrammar * * Check IMDB ratings * Evt check movie times Adda kino (maa forandre hver gang) */ OutputTextBox.Text = e.Result.Text; string speech = (e.Result.Text); switch (speech) { //greetings case "hello": case "hi": case "hello sophie": System.DateTime timenow = System.DateTime.Now; if (timenow.Hour >= 5 && timenow.Hour < 12) { sophie.SpeakAsync("Good morning " + ArrayUserSettings[0]); } else if (timenow.Hour >= 12 && timenow.Hour < 18) { sophie.SpeakAsync("Good afternoon " + ArrayUserSettings[0]); } else { sophie.SpeakAsync("Good Evening " + ArrayUserSettings[0]); } loadGrammar(); break; //attitudes case "sophie who is william": sophie.SpeakAsync("He is a sexy guy from Sweden playing Football"); loadGrammar(); break; case "how are you": sophie.SpeakAsync("i am happy as always " + ArrayUserSettings[0] + ", how about you"); loadGrammar(); break; // Time and Date case "time": //time System.DateTime now = System.DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; sophie.SpeakAsync(time); loadGrammar(); break; case "date": //date string date = System.DateTime.Now.ToString("dd MMM", new System.Globalization.CultureInfo("en-US")) + "" + System.DateTime.Today.ToString(" yyyy"); sophie.SpeakAsync(date); loadGrammar(); break; //Useful Facts case "internet status": //internet bool network = NetworkInterface.GetIsNetworkAvailable(); if (network) { sophie.SpeakAsync("You are Connected to the Internet"); } else { sophie.SpeakAsync("You are Disconnected from the Internet"); } loadGrammar(); break; case "read me poetry": string poem = getPoetry(); sophie.SpeakAsync(poem); loadGrammar(); break; case "tell me a story": string story = getShortStory(); sophie.SpeakAsync(story); loadGrammar(); break; //ToDos case "open google": case "can you open google": sophie.SpeakAsync("loading"); System.Diagnostics.Process.Start("http://www.google.com"); UnloadAndLoadCommands(); break; case "open facebook": case "can you open facebook": sophie.SpeakAsync("loading"); System.Diagnostics.Process.Start("http://www.facebook.com"); UnloadAndLoadCommands(); break; case "sophie weather": // weather sophie.SpeakAsync("Loading Weather"); UnloadAndLoadCommands(); //WeatherReader weather_read = new WeatherReader(); //weather_read.Show(); //weather_read.TopMost = true; break; case "sophie write": // writer sophie.SpeakAsync("Loading Writer"); UnloadAndLoadCommands(); //TextReader text_read = new TextReader(); //text_read.Show(); //text_read.TopMost = true; break; case "sophie calculate": // calculator sophie.SpeakAsync("Loading Weather"); UnloadAndLoadCommands(); //Calculator calculate = new Calculator(); //calculate.Show(); //calculate.TopMost = true; break; // ShutDowns case "sophie sleep": //sleep sophie.SpeakAsync("see you later, ali gator"); Thread.Sleep(2400); UnloadAndLoadSleep(); break; case "sophie wake up": // wake up from sleep sophie.SpeakAsync("What can I help you with?"); UnloadAndLoadGrammar(); break; case "sophie shutdown": //sleep sophie.SpeakAsync("shutting down"); Application.Exit(); this.Close(); break; case "stop": case "sophie stop": sophie.SpeakAsyncCancelAll(); UnloadAndLoadGrammar(); break; case "sophie who is eirin": sophie.SpeakAsync("She is a pretty funny girl you matched on Tinder"); UnloadAndLoadGrammar(); break; case "should eirin go out with me": sophie.SpeakAsync("Yes! She should. You are worth it, Master"); UnloadAndLoadGrammar(); break; case "close": sophie.SpeakAsyncCancelAll(); Process[] AllProcesses = Process.GetProcesses(); foreach (var process in AllProcesses) { if (process.MainWindowTitle != "") { string s = process.ProcessName.ToLower(); if (s == "iexplore" || s == "iexplorer" || s == "chrome" || s == "firefox" || s == "microsoftedgecp") { process.Kill(); //currently does not work on my computer? } } } UnloadAndLoadGrammar(); break; case "sophie commands": String lines = File.ReadAllText(Environment.CurrentDirectory + "\\Grammar.txt"); sophie.SpeakAsync("My Pleasure, all the commands are : " + lines); Thread.Sleep(8000); UnloadAndLoadGrammar(); break; // NEED TO ADD / Commands // Sophie has to be static, and user should be able to create new commands default: UnloadAndLoadGrammar(); break; } }
private void Mainevent_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { //System Username string Name = Environment.UserName; //Recognized Spoken words result is e.Result.Text string speech = e.Result.Text; //Debug_Livetxt.Text += "You said : " + e.Result.Text + "\n"; //Switch to e.Result.Text switch (speech) { //Greetings case "hello": Jarvis.SpeakAsync("hello " + Name); System.DateTime timenow = System.DateTime.Now; if (timenow.Hour >= 5 && timenow.Hour < 12) { Jarvis.SpeakAsync("Goodmorning " + Name); } if (timenow.Hour >= 12 && timenow.Hour < 18) { Jarvis.SpeakAsync("Good afternoon " + Name); } if (timenow.Hour >= 18 && timenow.Hour < 24) { Jarvis.SpeakAsync("Good evening " + Name); } if (timenow.Hour < 5) { Jarvis.SpeakAsync("Hello " + Name + ", you are still awake you should go to sleep, it's getting late"); } break; case "what time is it": System.DateTime now = System.DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; Jarvis.SpeakAsync(time); break; case "what day is it": string day = "Today is," + System.DateTime.Now.ToString("dddd"); Jarvis.SpeakAsync(day); break; case "what is the date": case "what is todays date": string date = "The date is, " + System.DateTime.Now.ToString("dd MMM"); Jarvis.SpeakAsync(date); date = "" + System.DateTime.Today.ToString(" yyyy"); Jarvis.SpeakAsync(date); break; case "who are you": Jarvis.SpeakAsync("i am your personal assistant"); Jarvis.SpeakAsync("i can read email, weather report, i can search web for you, anything that you need like a personal assistant do, you can ask me question i will reply to you"); break; case "what is my name": Jarvis.SpeakAsync(Name); break; case "get all emails": case "get all inbox emails": EmailBtn.PerformClick(); AllEmails(); break; case "check for new emails": EmailBtn.PerformClick(); QEvent = "Checkfornewemails"; Jarvis.SpeakAsyncCancelAll(); EmailNum = 0; CheckEmails(); break; case "read the email": Jarvis.SpeakAsyncCancelAll(); try { Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { Jarvis.SpeakAsync("There are no emails to read"); } break; case "next email": Jarvis.SpeakAsyncCancelAll(); try { EmailNum += 1; Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { EmailNum -= 1; Jarvis.SpeakAsync("There are no further emails"); } break; case "previous email": Jarvis.SpeakAsyncCancelAll(); try { EmailNum -= 1; Jarvis.SpeakAsync(MsgList[EmailNum]); } catch { EmailNum += 1; Jarvis.SpeakAsync("There are no previous emails"); } break; //This is for text reader case "start reading": //ReadBtn.PerformClick(); if (tabControl1.SelectedIndex == 1) { Jarvis.SpeakAsync(Readtxt.Text); } if (tabControl1.SelectedIndex == 3) { Jarvis.SpeakAsync(convertedtxt.Text); } break; case "pause": //PauseBtn.PerformClick(); if (tabControl1.SelectedIndex == 1) { if (Jarvis.State == SynthesizerState.Speaking) { Jarvis.Pause(); } } if (tabControl1.SelectedIndex == 3) { if (Jarvis.State == SynthesizerState.Speaking) { Jarvis.Pause(); } } break; case "resume": PauseBtn.PerformClick(); if (tabControl1.SelectedIndex == 1) { if (Jarvis.State == SynthesizerState.Speaking) { Jarvis.Resume(); } } if (tabControl1.SelectedIndex == 3) { if (Jarvis.State == SynthesizerState.Speaking) { Jarvis.Resume(); } } break; case "stop": StopBtn.PerformClick(); break; case "open text file": Open_FileBtn.PerformClick(); break; //---untill here--- // case "change voice speed to minis two": Jarvis.Rate = -2; break; case "change voice speed to minis four": Jarvis.Rate = -4; break; case "change voice speed to minis six": Jarvis.Rate = -6; break; case "change voice speed to minis eight": Jarvis.Rate = -8; break; case "change voice speed to minis ten": Jarvis.Rate = -10; break; case "change voice speed back to normal": Jarvis.Rate = 0; break; case "change voice speed to two": Jarvis.Rate = 2; break; case "change voice speed to four": Jarvis.Rate = 4; break; case "change voice speed to six": Jarvis.Rate = 6; break; case "change voice speed to eight": Jarvis.Rate = 8; break; case "change voice speed to ten": Jarvis.Rate = 10; break; //For Media Player case "i want to add music": case "i want to add video": Jarvis.Speak("choose, music file from your drives"); Add_Music.PerformClick(); break; case "play music": case "play video": PlayBtn.PerformClick(); break; case "stop media player": MediaStopBtn.PerformClick(); break; case "fast forward": FastfarwardBtn.PerformClick(); break; case "fast reverse": FastReverseBtn.PerformClick(); break; case "media player resume": PlayBtn.PerformClick(); break; case "media player pause": PlayBtn.PerformClick(); break; case "media player previous": PreviousBtn.PerformClick(); break; case "media player next": NextBtn.PerformClick(); break; case "activate full screen mode": FullScreen.PerformClick(); break; case "exit full screen": FullScreen.PerformClick(); break; case "mute volume": case "volume down": Unmute_Volum.PerformClick(); break; case "unmute volume": case "volume up": Unmute_Volum.PerformClick(); break; //This is for news reader case "get bing news": GetBingNews(); break; //Untill here // //Weather grammar case "get weather report": Jarvis.SpeakAsync("ok, " + Name + " here is the weather report"); GetWeather(); break; } }
public string ChangeToDatetimeFormat(string ticks) { System.DateTime time = new System.DateTime(long.Parse(ticks)); string[] datetimeFormat = time.GetDateTimeFormats('f'); return datetimeFormat[0]; }
public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat() { DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x')); }
private void myspeech_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { string speech = e.Result.Text; // while (completed == false && speech == "hello vision" || speech == "vision") // { // if (speech == "active yourself vision") // { if (stl == true) { if (completed2 == false) { if (completed == false) { if (speech == "are you there") { myspeech.RecognizeAsyncStop(); vision.Speak("yes. what can i do for you sir"); completed = true; //reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "kill any") { myspeech.RecognizeAsyncStop(); vision.Speak("Oh ! you are asking to kill my creator ! This is not possible. Better get lost."); completed = true; //reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "do me a favor" || speech == "help me") { myspeech.RecognizeAsyncStop(); vision.Speak("and what is your command sir"); completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "i am bored vision" || speech == "i am feeling lonely") { myspeech.RecognizeAsyncStop(); vision.Speak("oh, i am feeling bad for you sir. you can listen to music or you can watch movies or call your friends to hangout"); completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "describe yourself") { myspeech.RecognizeAsyncStop(); vision.Speak("i am your personal assistant sir. i can do anything for you, you can ask me question or to do something i will reply to you or do that for you"); completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } // completed = true; // vision.SpeakAsyncCancelAll(); if (speech == "what is the date" || speech == "what is todays date" || speech == "tell me the date" || speech == "i forget the date") { myspeech.RecognizeAsyncStop(); string date; date = "the date is, " + System.DateTime.Now.ToString("dd MMM", new System.Globalization.CultureInfo("en-US")); vision.Speak(date); date = "" + System.DateTime.Today.ToString(" yyyy"); vision.Speak(date); completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "what time is now" || speech == "what time is it" || speech == "tell me the time") { myspeech.RecognizeAsyncStop(); System.DateTime now = System.DateTime.Now; string time = now.GetDateTimeFormats('t')[0]; vision.Speak(time); //vision.SpeakAsyncCancelAll(); completed = true; //reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "open facebook" || speech == "take me to the facebook") { myspeech.RecognizeAsyncStop(); System.Diagnostics.Process.Start("https://www.facebook.com"); completed = true; //reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "close tab") { SendKeys.SendWait("^(w)"); completed = true; scrl1 = true; scrl2 = true; //SendKeys.Send("{PGDN}"); } if (speech == "close it") { SendKeys.SendWait("%{F4}"); completed = true; //SendKeys.Send("{PGDN}"); } if (speech == "i want to change tab") { myspeech.RecognizeAsyncStop(); vision.Speak("sure"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; tabchange = false; //SendKeys.Send("{PGDN}"); } if (speech == "shut down my system") { myspeech.RecognizeAsyncStop(); vision.Speak("good bye sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); Process.Start("shutdown.exe", "-s -t 00"); //SendKeys.Send("{PGDN}"); } if (speech == "start scrolling down") { //SendKeys.Send("^(w)"); myspeech.RecognizeAsyncStop(); vision.Speak("ready"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; // reco = true; scrl1 = false; scrl2 = true; tabchange = true; } if (speech == "start scrolling up") { //SendKeys.Send("^(w)"); myspeech.RecognizeAsyncStop(); vision.Speak("ready"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; // reco = true; scrl2 = false; scrl1 = true; } if (speech == "deactivate yourself now") { myspeech.RecognizeAsyncStop(); vision.Speak("ok sir. i am deactivating myself. have a good day"); this.Close(); completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "enable operational keys") { myspeech.RecognizeAsyncStop(); vision.Speak("enabled ! you can use them now"); completed = true; oppkeys = false; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "disable operational keys") { myspeech.RecognizeAsyncStop(); vision.Speak("disabled !"); completed = true; oppkeys = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "show applications") { AppList al = new AppList(); al.Show(); } if (speech == "show running programs") { RunningPro rp = new RunningPro(); rp.Show(); } if (speech == "show my location") { Location lc = new Location(); lc.Show(); } if (speech == "close chrome browser") { myspeech.RecognizeAsyncStop(); Process[] AllProcesses = Process.GetProcesses(); foreach (var process in AllProcesses) { if (process.MainWindowTitle != "") { string s = process.ProcessName.ToLower(); if (s == "chrome") { process.Kill(); } } } completed = true; // reco = true; myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (speech == "tell me about the weather" || speech == "read weather") { //vision.Pause(); yahoobtn_CLICK(); // WeatherReport wreport = new WeatherReport(); // wreport.Show(); //myspeech.UnloadAllGrammars(); // wreport.TopMost = true; completed = true; // reco = true; //myspeech.UnloadAllGrammars(); //UnLoadCommands(); } /* if (speech == "clear the board") * { * if (Wreading.Text == "") * { * myspeech.RecognizeAsyncStop(); * vision.Speak("i could, but, it is already cleared sir"); * myspeech.RecognizeAsync(RecognizeMode.Multiple); * completed = true; * * * } * else * { * Wreading.Text = ""; * templabel.Text = ""; * condlabel.Text = ""; * myspeech.RecognizeAsyncStop(); * vision.Speak("cleared"); * myspeech.RecognizeAsync(RecognizeMode.Multiple); * completed = true; * * } * * }*/ } } if (speech == "vision") { completed = false; tabchange = true; tabchange = true; } if (speech == "start menu") { //SendKeys.Send("^(w)"); SendKeys.SendWait("^{ESC}"); // SendKeys.SendWait("{TAB}"); //SendKeys.SendWait("{TAB}"); //SendKeys.SendWait("{TAB}"); //completed = true; startmenu = false; } if (speech == "down" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{DOWN}"); // Keyboard.SendKeys(this.UIMap.Window, "{DOWN}"); //completed = true; } if (speech == "up" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{UP}"); //completed = true; } if (speech == "right" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{RIGHT}"); // completed = true; } if (speech == "left" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{LEFT}"); //completed = true; } if (speech == "tab" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{TAB}"); // completed = true; } if (speech == "space" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{SPACE}"); // completed = true; } if (speech == "enter" && oppkeys == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("{ENTER}"); // completed = true; } if (speech == "close menu" && startmenu == false) { //SendKeys.Send("^(w)"); SendKeys.SendWait("^{ESC}"); // SendKeys.SendWait("{TAB}"); //SendKeys.SendWait("{TAB}"); //SendKeys.SendWait("{TAB}"); //completed = true; startmenu = false; } if (speech == "scroll" && scrl1 == false) { SendKeys.SendWait("{PGDN}"); } if (speech == "scroll" && scrl2 == false) { //completed = false; SendKeys.SendWait("{PGUP}"); } if (speech == "next tab" && tabchange == false) { //completed = false; SendKeys.SendWait("^({TAB})"); } if (speech == "back tab" && tabchange == false) { //completed = false; SendKeys.SendWait("^+({TAB})"); } if (speech == "activate yourself vision") { myspeech.RecognizeAsyncStop(); vision.Speak("hello sir. i am active now. how can i help you"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed2 = false; } if (speech == "ops. i am sorry vision") { myspeech.RecognizeAsyncStop(); vision.Speak("i dont mind sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); } if (completed == false) { if (speech == "stop listening to me") { myspeech.RecognizeAsyncStop(); vision.Speak("ok sir. i will wait for your command"); myspeech.RecognizeAsync(RecognizeMode.Multiple); stl = false; } if (speech == "good morning") { DateTime d = new DateTime(); var res2 = d.ToString("tt"); System.DateTime timenow = System.DateTime.Now; if (timenow.Hour >= 5 && timenow.Hour < 12 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("good morning sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 12 && timenow.Hour < 18) { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not morning sir. good afternoon by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 18 && timenow.Hour < 24) { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not morning sir. good evening by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour == 24 || timenow.Hour < 5 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not morning. its night sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } completed2 = false; //var res = d.ToString("hh:mm tt"); // this show 11:12 Pm // this show 23:12 } if (speech == "good afternoon") { DateTime d = new DateTime(); var res2 = d.ToString("tt"); System.DateTime timenow = System.DateTime.Now; if (timenow.Hour >= 12 && timenow.Hour < 18) { myspeech.RecognizeAsyncStop(); vision.Speak("good afternoon sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 5 && timenow.Hour < 12 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its morning sir. good morning by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 18 && timenow.Hour < 24) { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its evening sir. good evening by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour == 24 || timenow.Hour < 5 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its night sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } completed2 = false; //var res = d.ToString("hh:mm tt"); // this show 11:12 Pm // this show 23:12 } if (speech == "good evening") { DateTime d = new DateTime(); var res2 = d.ToString("tt"); System.DateTime timenow = System.DateTime.Now; int hour = timenow.Hour; // templabel.Text = hour.ToString(); if (hour >= 18 && hour < 24) { myspeech.RecognizeAsyncStop(); vision.Speak("good evening sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 12 && timenow.Hour < 18) { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not evening sir. good afternoon by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 5 && timenow.Hour < 12 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not evening sir. good morning by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (hour == 24 || timenow.Hour < 5 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not evening. its night sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } completed2 = false; //var res = d.ToString("hh:mm tt"); // this show 11:12 Pm // this show 23:12 } if (speech == "good night") { DateTime d = new DateTime(); var res2 = d.ToString("tt"); System.DateTime timenow = System.DateTime.Now; int hour = timenow.Hour; if (hour == 24 || timenow.Hour < 5 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("oops. its too late. you should sleep now. good night sir"); myspeech.RecognizeAsync(RecognizeMode.Multiple); //this.Close(); completed = true; } if (timenow.Hour >= 18 && timenow.Hour < 24) { myspeech.RecognizeAsyncStop(); vision.Speak(" sorry to say but its not night sir. its evening. good evening by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 12 && timenow.Hour < 18) { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its not night sir. good afternoon by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } if (timenow.Hour >= 5 && timenow.Hour < 12 && res2 == "AM") { myspeech.RecognizeAsyncStop(); vision.Speak("sorry to say but its morning sir. good morning by the way"); myspeech.RecognizeAsync(RecognizeMode.Multiple); completed = true; } completed2 = false; //var res = d.ToString("hh:mm tt"); // this show 11:12 Pm // this show 23:12 } /*if (speech == "good evening vision") * { * System.DateTime timenow = System.DateTime.Now; * * * DateTime d = new DateTime(); * var res2 = d.ToString("tt"); * vision.Speak(res2); * templabel.Text = timenow.ToString(""); * } * if (speech == "good morning vision") * { * vision.Speak("morning sir"); * }*/ if (speech == "shut up") { if (vision.State == SynthesizerState.Paused) { vision.Resume(); // weather report can be stopped by this } // vision.SpeakAsyncCancelAll(); } } } if (speech == "start listening to me vision") { vision.Speak("listening sir"); stl = true; } }