private bool AudioClipDataIsComplete(bool fileGenerationOnly = false)
        {
            bool          allOK = true;
            StringBuilder sb    = new StringBuilder();

            if (!fileGenerationOnly && String.IsNullOrEmpty(AudioClipLabel))
            {
                sb.AppendLine("Please give the audioclip a label.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioClipText))
            {
                sb.AppendLine("Please set the audioclip text.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioFileDirectory))
            {
                sb.AppendLine("Please set a directory for the audio clip.");
                allOK = false;
            }
            if (String.IsNullOrEmpty(AudioFileName))
            {
                sb.AppendLine("Please set a filename.");
                allOK = false;
            }
            if (!allOK)
            {
                var messageWin = new MessageWin("Save Audioclip", sb.ToString());
                messageWin.Show();
            }
            return(allOK);
        }
Beispiel #2
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            String OldPwd  = OldPwdBox.Password;
            String NewPwd  = NewPwdBox.Password;
            String CNewPwd = ConfirmNewPwdBox.Password;
            String Message = "";
            bool   res     = false;

            if (NewPwd != CNewPwd)
            {
                Message = "两次密码不一样";
            }
            else
            {
                var userService = IoC.Get <IUserService>();
                res = userService.ChangeUserPwd(NewPwd, OldPwd, out Message);
            }
            Button     btn = sender as Button;
            MessageWin win = new MessageWin(Message);

            btn.ShowHint(win);
            if (res)
            {
                this.Close();
            }
        }
Beispiel #3
0
        public static void CheckAudioFiles()
        {
            // Runs at startup if 'Check Audio files' in Settings screen is checked

            Logger.AddLogEntry(LogCategory.INFO, "Checking audio files...");
            bool allOK = true;

            if (!AudioClipsMgr.CheckAudioFiles())
            {
                allOK = false;
            }
            if (allOK)
            {
                Logger.AddLogEntry(LogCategory.INFO, "Audio files OK");
            }
            else
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                {
                    var messageWin = new MessageWin("Audio Files Check", "WARNING: One or more audio files is missing\nCheck Event Log for details.");
                    messageWin.Show();
                }));
                Logger.AddLogEntry(LogCategory.ERROR, "One or more audio files is missing");
            }
        }
Beispiel #4
0
 public static void ShowDatabaseFailure(string message)
 {
     MessageWin message_win = new MessageWin();
     if (string.IsNullOrEmpty(message))
         message_win.ShowDialog("糟糕!数据库操作出现了点问题,请重新登陆或联系管理员。", "错误");
     else
         message_win.ShowDialog("糟糕!数据库操作出现了点问题,请重新登陆或联系管理员.\n错误信息:" + message, "错误");
 }
        private void RealButton_Click(object sender, EventArgs e)
        {
            //MessageBox.Show("导入失败");
            isFailed = true;
            BarGo();
            MessageWin wm = new MessageWin("已手动停止资源获取,本次导入资源失败。");

            wm.Show(true);
        }
        public static string GenerateSpeech(string audioText)
        {
            /*
             * Generates audio when online;
             * Default fileName is audio text with illegal characters replaced by "_"
             * FileName can be specified to avoid long filenames
             *
             */
            if (!String.IsNullOrEmpty(audioText))
            {
                string credentialsFile = GetCredentialsFile();
                if (!String.IsNullOrEmpty(credentialsFile))
                {
                    try
                    {
                        GoogleCredential         credentials = GoogleCredential.FromFile(credentialsFile);
                        SynthesizeSpeechResponse response;
                        using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                        {
                            response = textToSpeechClient.SynthesizeSpeech(
                                new SynthesisInput()
                            {
                                Text = audioText
                            },
                                new VoiceSelectionParams()
                            {
                                LanguageCode = LanguageCode,
                                Name         = Voice,
                                SsmlGender   = Gender
                            },
                                new AudioConfig()
                            {
                                AudioEncoding   = AudioEncoding.Mp3,
                                SpeakingRate    = (float?)(0.95 * AudioMgr.SpeedRatio), // default speed set to 0.95
                                SampleRateHertz = 24000
                            }
                                );
                        }

                        string speechFile = Path.Combine(DirectoryMgr.TempDirectory, Guid.NewGuid().ToString() + ".mp3");
                        File.WriteAllBytes(speechFile, response.AudioContent);
                        return(speechFile);
                    }
                    catch (Exception e)
                    {
                        Logger.AddLogEntry(LogCategory.ERROR,
                                           String.Format("TextToSpeechMgr: Error reading Google credentials file: {0} ", e.ToString()));
                        var messageWin = new MessageWin("TextToSpeechMgr",
                                                        String.Format("Error reading Google credentials file - audio not generated."));
                        messageWin.Show();
                        return(null);
                    }
                }
            }
            return(null);
        }
 private void SaveChanges(object obj)
 {
     if (AudioClipDataIsComplete())
     {
         int    returnValue;
         string msg = "Audio clip saved.";
         if (SelectedAudioClip == null)
         {
             SelectedAudioClip = new AudioClip();
             newAudioClip      = true;
         }
         SelectedAudioClip.Label          = AudioClipLabel;
         SelectedAudioClip.StateText      = AudioClipText;
         SelectedAudioClip.StateAudioFile = Path.Combine(AudioFileDirectory, AudioFileName);
         SelectedAudioClip.Category       = SelectedCategory;
         SelectedAudioClip.IsVisible      = ClipVisibility.Equals("Visible") ? true : false;
         if (SelectedAudioClip.IsVisible)
         {
             SelectedAudioClip.ButtonColour = ButtonColour;
         }
         else
         {
             SelectedAudioClip.ButtonColour = ColourHelper.HiddenColour;
         }
         if (newAudioClip)
         {
             returnValue = AudioClipsMgr.AddAudioClip(SelectedAudioClip);
             if (returnValue > 0)
             {
                 newAudioClip = false;
             }
         }
         else
         {
             returnValue = AudioClipsMgr.UpdateAudioClipToDB(SelectedAudioClip);
         }
         if (returnValue > 0)
         {
             RefreshAudioClips();
             PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(AudioClips)));
             EventSystem.Publish(new AudioClipsInventoryChanged());
         }
         if (returnValue == -1)
         {
             msg = "Error: Audio clip label already exists - please choose another label.";
         }
         else if (returnValue == -2)
         {
             msg = "Error: Problem saving audioClip to database.";
         }
         var messageWin = new MessageWin("Save Audioclip", msg);
         messageWin.Show();
     }
 }
Beispiel #8
0
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (tbContent.HasItems)
     {
         if (!MessageWin.Confirm("确定退出?") ?? true)
         {
             e.Cancel = true;
             return;
         }
         CloseAll();
     }
     MainWindowVM.SaveSetting();
 }
 private void ShowWin <T>(RightEnum rightEnum)
 {
     if (Constants.Login.CheckRight(rightEnum))
     {
         var VM = IoC.Get <T>();
         windowManager.ShowDialog(VM);
     }
     else
     {
         var msg = new MessageWin("权限不足");
         this.View.ShowHint(msg);
     }
 }
Beispiel #10
0
 private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
 {
     try
     {
         e.Handled = true; //把 Handled 属性设为true,表示此异常已处理,程序可以继续运行,不会强制退出
         Logger.Fatal("UI线程异常", e.Exception);
         MessageWin.Error("系统发生未处理的异常", "系统错误");
         ShutdownWhenNoMainWindow();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "UI线程发生未处理错误", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
        public static bool GenerateAudiofile(string audioText, string fileName)
        {
            /*
             * Method generates audio clips for use offline
             */
            string credentialsFile = GetCredentialsFile();

            if (!String.IsNullOrEmpty(credentialsFile))
            {
                try
                {
                    GoogleCredential         credentials = GoogleCredential.FromFile(credentialsFile);
                    SynthesizeSpeechResponse response;
                    using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                    {
                        response = textToSpeechClient.SynthesizeSpeech(
                            new SynthesisInput()
                        {
                            Text = audioText
                        },
                            new VoiceSelectionParams()
                        {
                            LanguageCode = LanguageCode,
                            Name         = Voice,
                            SsmlGender   = Gender
                        },
                            new AudioConfig()
                        {
                            AudioEncoding   = AudioEncoding.Mp3,
                            SpeakingRate    = (float?)0.95, // default speed set to 0.95
                            SampleRateHertz = 24000
                        }
                            );
                    }
                    // check all required directories exist
                    Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                    string speechFile = Path.Combine(fileName + ".mp3");
                    File.WriteAllBytes(speechFile, response.AudioContent);
                    return(true);
                }
                catch (Exception e)
                {
                    string msg        = String.Format("Error reading Google credentials file - audio file not generated.\n{0} ", e.ToString());
                    var    messageWin = new MessageWin("TextToSpeechMgr", msg);
                    messageWin.Show();
                    Logger.AddLogEntry(LogCategory.ERROR, msg);
                }
            }
            return(false);
        }
Beispiel #12
0
 private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
 {
     try
     {
         Logger.Fatal("Task线程异常", e.Exception);
         e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
         MessageWin.Error("系统发生未处理的异常", "系统错误");
         ShutdownWhenNoMainWindow();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "非UI线程发生未处理错误", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Beispiel #13
0
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogoutMenuItem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (MessageWin.Confirm("确定要退出登录?") != true)
            {
                return;
            }
            //string output = HttpHelper.GetUrl("/Auth/LoginOut", null, UserInfo.Token);
            //this.CloseWithoutAsk = true;

            //var frmLogin = new Login(UserInfo.Account, string.Empty);
            //frmLogin.Show();
            //UserInfo.UserID = 0;
            //UserInfo.PassWord = "";
            //UserInfo.UserMenu = null;
            //UserInfo.Account = UserInfo.UserName = UserInfo.DepartmentName = UserInfo.Token = string.Empty;
            this.Close();
        }
 private void TimeTriggerMessageResponse(object sender, string e)
 {
     messageDialogWin.MessageResponse -= TimeTriggerMessageResponse;
     if (e.Equals("Yes"))
     {
         MessageWin msgWin;
         if (AudioFileGenerator.GenerateTimeTriggerAudioFiles())
         {
             msgWin = new MessageWin("Generate Time Trigger Clips", "Time Trigger clips generated.");
         }
         else
         {
             msgWin = new MessageWin("Generate Time Trigger Clips", "Problem generating Time Trigger clips.");
         }
         msgWin.Show();
     }
     messageDialogWin.Close();
 }
 private void RulesetMessageResponse(object sender, string e)
 {
     messageDialogWin.MessageResponse -= RulesetMessageResponse;
     if (e.Equals("Yes"))
     {
         MessageWin msgWin;
         if (AudioFileGenerator.GenerateCommonRulesetAudioFiles())
         {
             msgWin = new MessageWin("Generate Common Ruleset Clips", "Common Ruleset Clips generated.");
         }
         else
         {
             msgWin = new MessageWin("Generate Common Ruleset Clips", "Problem generating Common Ruleset Clips.");
         }
         msgWin.Show();
     }
     messageDialogWin.Close();
 }
        private void SaveSettings(string setting)
        {
            string msg = String.Empty;

            switch (setting)
            {
            case "CheckAudioFiles":
                Settings.CheckAudioFiles = CheckAudioFiles;
                msg = "Check Audio Files option saved.";
                break;

            case "CredentialsFile":
                Settings.CredentialsFile = CredentialsFile;
                msg = "Google Application Credentials file setting saved.";
                break;

            case "MaxLogEntries":
                Settings.MaxLogEntries = MaxLogEntries;
                msg = "Maximum log entries option saved.";
                break;

            case "OnlineVoice":
            case "LanguageCode":
                Settings.LanguageCode = SelectedLanguageCode;
                Settings.OnlineVoice  = SelectedVoice;
                msg = "Online voice options saved.";
                break;
            }
            if (SettingsTableMgr.SaveSettingsToDB())
            {
                if (!String.IsNullOrEmpty(msg))
                {
                    var messageWin = new MessageWin("Save Settings", msg);
                    messageWin.Show();
                }
                Logger.AddLogEntry(LogCategory.INFO, "App options saved.");
            }
            else
            {
                var messageWin = new MessageWin("Save Settings", "Error: problem saving app options.");
                messageWin.Show();
                Logger.AddLogEntry(LogCategory.ERROR, "SaveSettings: Problem saving app options");
            }
        }
Beispiel #17
0
        public void SaveParameter(Button btn)
        {
            bool DoContinue = false;

            if (!userService.ValidateConfigPWD(Constants.ConfigPwd))
            {
                var v   = IoC.Get <ValidatePwdViewModel>();
                var res = windowManager.ShowDialog(v);
                if (res.HasValue)
                {
                    DoContinue = res.Value;
                }
            }
            else
            {
                DoContinue = true;
            }
            if (!DoContinue)
            {
                return;
            }

            TabControl tabControl = (this.View as BJParametersView).TabContent;

            var frames = (tabControl.SelectedItem as TabItem).GetControls <Frame>();

            if (frames.Count > 0)
            {
                var                  f       = frames[0];
                BJParameterView      BJView  = f.Content as BJParameterView;
                BJParameterViewModel BjModel = BJView.DataContext as BJParameterViewModel;
                if (BjModel.SaveParameter(out String Msg))
                {
                    var msg = new MessageWin();
                    btn.ShowHint(msg);
                }
                else
                {
                    var msg = new MessageWin(Msg);
                    btn.ShowHint(msg);
                }
            }
        }
Beispiel #18
0
        /// <summary>
        /// 删除
        /// </summary>
        public void Delitem()
        {
            if (SelectedObj == null)
            {
                return;
            }
            var result = windowManager.ShowMessageBox(String.Format("确定删除【{0}】吗?", SelectedObj.Name), "系统提示", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Asterisk);

            if (result == System.Windows.MessageBoxResult.Yes)
            {
                if (!userService.ValidateConfigPWD(Constants.ConfigPwd))
                {
                    var v   = IoC.Get <ValidatePwdViewModel>();
                    var res = windowManager.ShowDialog(v);
                    if (!res.HasValue || !res.Value)
                    {
                        return;
                    }
                }
                if (SelectedObj.ID == 0)
                {
                    BJObjList.Remove(SelectedObj);
                }
                else
                {
                    if (bjService.DeleteBJ(SelectedObj))
                    {
                        var id = SelectedObj.ID;
                        BJObjList.Remove(SelectedObj);
                        if (Constants.BJDict.ContainsKey(T.Name))
                        {
                            Constants.BJDict[T.Name].Remove(Constants.BJDict[T.Name].Where(c => c.ID == id).First());
                        }
                    }
                    else
                    {
                        MessageWin MW = new MessageWin("删除失败!");
                        this.View.ShowHint(MW);
                    }
                }
            }
        }
        private static string GetCredentialsFile()
        {
            string credentialsFile = Settings.CredentialsFile;

            if (!File.Exists(credentialsFile))
            {
                credentialsFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
                                                                     EnvironmentVariableTarget.User);
                if (!File.Exists(credentialsFile))
                {
                    var messageWin = new MessageWin("TextToSpeechMgr",
                                                    String.Format("TextToSpeechMgr Error: Google credentials file not found"));
                    messageWin.Show();
                    Logger.AddLogEntry(LogCategory.ERROR,
                                       String.Format("TextToSpeechMgr: Google credentials file: not found"));
                    return(null);
                }
            }
            return(credentialsFile);
        }
 private void SaveMaxLogEntries(object obj)
 {
     if (Int32.TryParse(MaxLogEntriesTxt, out int maxEntries))
     {
         if (maxEntries >= 0)
         {
             MaxLogEntries = maxEntries;
             SaveSettings("MaxLogEntries");
         }
         else
         {
             MaxLogEntriesTxt = Settings.MaxLogEntries.ToString();
         }
     }
     else
     {
         MaxLogEntriesTxt = Settings.MaxLogEntries.ToString();
         var messageWin = new MessageWin("App Options", String.Format("{0} is not valid for maximum log entries - please update setting.", MaxLogEntriesTxt));
         messageWin.Show();
     }
 }
        public static void LoadOnlineVoices()
        {
            string credentialsFile = GetCredentialsFile();

            if (!String.IsNullOrEmpty(credentialsFile))
            {
                try
                {
                    GoogleCredential credentials = GoogleCredential.FromFile(credentialsFile);
                    using (var textToSpeechClient = TextToSpeechClient.Create(credentials))
                    {
                        Voices        = new List <string>();
                        LanguageCodes = new List <string>();
                        var voices = textToSpeechClient.ListVoices();
                        foreach (var voice in voices)
                        {
                            Voices.Add(String.Format("{0} ({1})", voice.Name, voice.SsmlGender.ToLower()));
                            int    index        = voice.Name.IndexOf('-', voice.Name.IndexOf('-') + 1);
                            string languageCode = voice.Name.Substring(0, index);
                            if (!LanguageCodes.Contains(languageCode))
                            {
                                LanguageCodes.Add(languageCode);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.AddLogEntry(LogCategory.ERROR,
                                       String.Format("TextToSpeechMgr: Error reading Google credentials file: {0} ", e.ToString()));
                    var messageWin = new MessageWin("TextToSpeechMgr",
                                                    String.Format("Error reading Google credentials file - voice list not generated."));
                    messageWin.Show();
                }
                if (Voices != null)
                {
                    OnlineVoicesTableMgr.SaveOnlineVoicesToDB(Voices);
                }
            }
        }
Beispiel #22
0
 private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     try
     {
         var msg = "非UI线程发生";
         msg += e.IsTerminating ? "致命错误" : "异常";
         if (e.ExceptionObject is Exception ex)
         {
             Logger.Fatal(msg, ex);
         }
         else
         {
             Logger.Fatal(msg, new Exception(e.ExceptionObject?.ToString()));
         }
         MessageWin.Error("系统发生未处理的异常", "系统错误");
         ShutdownWhenNoMainWindow();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "非UI线程发生未处理错误", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Beispiel #23
0
        private UserControl CreateView(string className, string title)
        {
            UserControl view = null;

            try
            {
                view = Container.ResolveNamed <IDependency>(className) as UserControl;
                if (view == null)
                {
                    Logger.Warn($"【{title}】初始化失败");
                    MessageWin.Warn($"【{title}】初始化失败");
                    return(null);
                }
                view.Unloaded += ChildView_Unloaded;
            }
            catch (Exception ex)
            {
                Logger.Error($"【{title}】初始化错误", ex);
                MessageWin.Error($"【{title}】初始化错误");
                return(null);
            }
            return(view);
        }
Beispiel #24
0
 public void Win() => MessageWin?.Invoke();
Beispiel #25
0
 public static void MessageWarn(string msg, string title = "警告")
 {
     DispatcherInvoke(() => { MessageWin.Warn(msg, title); });
 }
Beispiel #26
0
 public static void MessageInfo(string msg, string title = "提示")
 {
     DispatcherInvoke(() => { MessageWin.Info(msg, title); });
 }
Beispiel #27
0
 public static bool?MessageConfirm(string msg, string title = "确认")
 {
     return(DispatcherInvoke(() => { return MessageWin.Confirm(msg, title); }));
 }
Beispiel #28
0
 public static void MessageError(string msg, string title = "错误")
 {
     DispatcherInvoke(() => { MessageWin.Error(msg, title); });
 }
 // 窗口关闭/ 注销用户
 private void Window_Closing(object sender, CancelEventArgs e)
 {
     if (TrialWin != null && TrialWin.IsLoaded)
     {
         // 弹出消息窗口,询问是否确认结束实验
         MessageWin message_win = new MessageWin();
         MessageBoxResult dialog_result = message_win.ShowDialog("确定要退出当前实验吗?", "提示", MessageBoxButton.OKCancel);
         // 处理消息窗口结果
         if (dialog_result == MessageBoxResult.OK)
         {
             TrialWin.End();
         }
         else if (dialog_result == MessageBoxResult.Cancel)
         {
             e.Cancel = true;
             return;
         }
     }
 } 
Beispiel #30
0
 public static string MessageInput(string value = "", string msg = "", string title = "查找")
 {
     return(DispatcherInvoke(() => { return MessageWin.Input(value, msg, title); }));
 }
        // 实验结束
        private void BtnExpEnd_Click(object sender, RoutedEventArgs e)
        {
            if (TrialWin == null || !TrialWin.IsLoaded)
                return;

            // 弹出消息窗口,询问是否确认结束实验
            int last_count = Int32.Parse(LabelTotalGroupCount.Content.ToString()) - Int32.Parse(LabelTrialCount.Content.ToString());
            if (last_count > 0)
            {
                if (TrialWin != null)
                    TrialWin.Pause();
                MessageWin message_win = new MessageWin();
                MessageBoxResult dialog_result = message_win.ShowDialog("还有" + last_count + "组实验,确定要结束实验吗?", "提示", MessageBoxButton.OKCancel);
                if (dialog_result == MessageBoxResult.OK)
                {
                    IsRunning = false;
                    CurrentExpIndex = CurrentExpIndex - 1;
                    if (TrialWin != null)
                        TrialWin.End();
                }
                else if (dialog_result == MessageBoxResult.Cancel)
                {
                    TrialWin.Restart();
                    return;
                }
            }
            else
            {
                TrialWin.End();
            }            

        }
        // 组数更新
        private void TxtGroupCount_TextChanged(object sender, TextChangedEventArgs e)
        {
            int training_count = 0;
            int test_count = 0;
            if (!string.IsNullOrEmpty(TxtTrainingGroupCount.Text.Trim()) && !Int32.TryParse(TxtTrainingGroupCount.Text.Trim(), out training_count))
            {
                MessageWin message_win = new MessageWin();
                message_win.ShowDialog("请输入数字.", "提示");
            }
            if (!string.IsNullOrEmpty(TxtTestGroupCount.Text.Trim()) && !Int32.TryParse(TxtTestGroupCount.Text.Trim(), out test_count))
            {
                MessageWin message_win = new MessageWin();
                message_win.ShowDialog("请输入数字.", "提示");
            }

            LabelTotalGroupCount.Content = (training_count + test_count).ToString();
        }
        // 开始实验
        private void TrialStart()
        {
            int training_count = 0;
            int test_count = 0;
            if (string.IsNullOrEmpty(TxtTrainingGroupCount.Text.Trim()))
            {
                MessageWin message_win = new MessageWin();
                message_win.ShowDialog("请先设定训练组数.", "提示", MessageBoxButton.OK);
                return;
            }
            else
            {
                training_count = Int32.Parse(TxtTrainingGroupCount.Text.Trim());
            }
            if (string.IsNullOrEmpty(TxtTestGroupCount.Text.Trim()))
            {
                MessageWin message_win = new MessageWin();
                message_win.ShowDialog("请先设定测试组数.", "提示", MessageBoxButton.OK);
                return;
            }
            else
            {
                test_count = Int32.Parse(TxtTestGroupCount.Text.Trim());
            }

            // 将一条新实验记录写入数据库
            try
            {
                // 查询该实验者已经做过该实验多少次
                int count;
                CurrentExperimentRecord.ExperimentName = (ExperimentType)Enum.Parse(typeof(ExperimentType), ExpType[CurrentExpIndex]);
                if (DatabaseHelper.GetExperimentRecordCount(CurrentExperimentRecord.UserInfoID, CurrentExperimentRecord.ExperimentName, out count))
                {
                    CurrentExperimentRecord.Date = DateTime.Now;
                    CurrentExperimentRecord.Times = count + 1;                  // 相同用户相同实验的实验记录加1
                    if (DatabaseHelper.SaveExperimentRecord(CurrentExperimentRecord))
                    {
                        if (DatabaseHelper.GetExperimentRecordID(CurrentExperimentRecord.UserInfoID, CurrentExperimentRecord.ExperimentName,
                            CurrentExperimentRecord.Times, out ExperimentRecordID))
                        {
                            // 开始实验
                            if (EyeState && (CurrentExperimentRecord.ExperimentName.ToString() == "Exp001" || CurrentExperimentRecord.ExperimentName.ToString() == "Exp005" || CurrentExperimentRecord.ExperimentName.ToString() == "Exp006"))
                            {
                                 
                                Init(ExperimentRecordID, EyeState);
                                IsRunning2 = true;
                            }

                            // 由实验类型的字符串得到类名
                            Type t = Type.GetType(string.Concat("ThuIPsySystem.Experiments.", CurrentExperimentRecord.ExperimentName.ToString(), ".Trial"));
                            Object obj = System.Activator.CreateInstance(t);    // 实例化该实验的类
                            TrialWin = obj as KeyTrial;
                            
                            TrialWin.Owner = this;
                            TrialWin.Show();
                            TrialWin.TrialEvent += new EventHandler<TrialEventArgs>(TrialWin_TrialEvent);
                            // 设置正负性的判断键
                            KeyTrial.PositiveKey = ComboBoxJudgementType.SelectedValue.ToString() == JudgementType[0] ? PositiveKey : NegativeKey;
                            KeyTrial.NegativeKey = ComboBoxJudgementType.SelectedValue.ToString() == JudgementType[0] ? NegativeKey : PositiveKey;
                            // 初始化
                            if (CurrentExperimentRecord.ExperimentName.ToString() == "Exp007")
                                test_count = 159;
                            TrialWin.Init(ExperimentRecordID, training_count, test_count, KeyTrial.PositiveKey == PositiveKey);

                            // 控制UI是否接受焦点
                            TxtTrainingGroupCount.IsEnabled = false;
                            TxtTestGroupCount.IsEnabled = false;
                            BtnExpEnd.IsEnabled = true;
                            BtnExpResult.IsEnabled = false;
                            this.Focus();
                            TrialWin.Focus();

                            return;
                        }
                    }
                }
                DatabaseMessage.ShowDatabaseFailure("");
            }
            catch (Exception ex)
            {
                DatabaseMessage.ShowDatabaseFailure(ex.Message);
            }
        }
        // 实验过渡
        private void TrialTransition()
        {
            if (IsRunning && CurrentExpIndex >= 0)
            {
                // 更新实验项目面板
                LabelExpType[CurrentExpIndex].Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                if (PanelExpToDo.Children.Contains(LabelExpType[CurrentExpIndex]))
                    PanelExpToDo.Children.Remove(LabelExpType[CurrentExpIndex]);
                if (!PanelExpDone.Children.Contains(LabelExpType[CurrentExpIndex]))
                    PanelExpDone.Children.Add(LabelExpType[CurrentExpIndex]);
            }

            // 开始下一个键盘实验
            if (CurrentExpIndex + 1 < ExpType.Count && IsRunning)
            {
                CurrentExpIndex = CurrentExpIndex + 1;  // 完成一项实验,所以加一

                LabelExpType[CurrentExpIndex].Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                LabelExperimenterState.Content = "Ready";
                LabelTrialCount.Content = "0";
                
                // 实验开始
                TrialStart();

                BtnExpRun.Content = "暂  停";
            }
            else            // 所有实验结束
            {
                TrialTimer.Stop();
                BtnExpRun.Content = "开  始";

                if (IsRunning)
                {
                    // 弹出消息窗口,询问是否确认结束实验
                    MessageWin message_win = new MessageWin();
                    MessageBoxResult dialog_result = message_win.ShowDialog("全部实验结束,感谢您的时间!", "提示", MessageBoxButton.OK);
                }
            }
        }
Beispiel #35
0
 /// <summary>
 /// 关于
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void AboutMenuItem_MouseUp(object sender, MouseButtonEventArgs e)
 {
     MessageWin.Info(this.Title, "关于");
     e.Handled = true;
 }
Beispiel #36
0
 private void BtnConfigMysql_Click(object sender, RoutedEventArgs e)
 {
     // 只在初始配置数据库时运行
     try
     {
         MySqlHelper.InitializeDatabase(ComboBoxServer.SelectedValue.ToString(), TextBoxPort.Text, "root", "root123");
         MySqlHelper.ConfigMySqlDatabase(TableType.User);
         MySqlHelper.ConfigMySqlDatabase(TableType.KeyExperiment);
         MessageWin message_win = new MessageWin();
         message_win.Owner = (Window)this.Parent;
         message_win.ShowDialog("数据库初始化成功!", "提示", MessageBoxButton.OK);
         Flyouts[0].IsOpen = !Flyouts[0].IsOpen;
     }
     catch (Exception ex)
     {
         MessageWin message_win = new MessageWin();
         message_win.Owner = (Window)this.Parent;
         message_win.ShowDialog("糟糕!数据库初始化失败!请检查是否启动了MySql.\n错误信息:" + ex.Message, "提示", MessageBoxButton.OK);
     }
 }
Beispiel #37
0
        public bool End()
        {
            if (IsSaved)
                return true;

            // 状态6:实验结束
            State = 6;
            TrialTimer.Stop();
            CurrentTrialState = TrialState.End;
            ClearDisplay();

            if (UnVoteSceneIndices.Count == 0)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageWin message_win = new MessageWin();
                    message_win.ShowDialog(EndWords, "提示");
                    this.Close();
                }), null);
                if (!SaveVoteRecord())
                {
                    MessageWin message_win = new MessageWin();
                    message_win.ShowDialog("噢……数据保存失败!", "提示");
                }

                IsSaved = true;
                return true;       // 打分完成,确定终止实验
            }
            else
            {
                // 弹出消息窗口,询问是否确认结束实验
                string words = "还有" + UnVoteSceneIndices.Count.ToString() + "张图片等待打分,确定要退出吗?";
                MessageWin message_win = new MessageWin();
                MessageBoxResult dialog_result = message_win.ShowDialog(words, "提示", MessageBoxButton.OKCancel);
                // 处理消息窗口结果
                if (dialog_result == MessageBoxResult.OK)
                {
                    if (UnVoteSceneIndices.Count < TrialTotalCount)
                    {
                        // 打分未完成,询问是否保存数据
                        MessageWin message_win_save = new MessageWin();
                        MessageBoxResult dialog_result_save = message_win_save.ShowDialog("没有完成图片打分,是否保存数据?", "提示", MessageBoxButton.OKCancel);
                        if (dialog_result_save == MessageBoxResult.OK)
                        {
                            if (!SaveVoteRecord())
                            {
                                MessageWin message_win_fail = new MessageWin();
                                message_win_fail.ShowDialog("噢……数据保存失败!", "提示");
                            }
                            else
                            {
                                MessageWin message_win_success = new MessageWin();
                                message_win_success.ShowDialog("数据保存成功!", "提示");
                                IsSaved = true;
                            }
                        }
                    }

                    return true;    // 打分未完成,确定终止实验
                }
                else if (dialog_result == MessageBoxResult.Cancel)
                {
                    Pause();
                    return false;       // 打分未完成,取消终止实验
                }

                return true;
            }

        }
Beispiel #38
0
        public override void End()
        {
            // 状态6:实验结束
            State = 6;
            TrialTimer.Stop();
            CurrentTrialState = TrialState.End;
            if (TrialCount >= TrialTotalCount)
            {
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageWin message_win = new MessageWin();
                    message_win.ShowDialog(EndWords, "提示");
                    this.TrialEvent(this, new TrialEventArgs(TrialState.End, TrialCount));
                }), null);
            }
            else
            {
                this.TrialEvent(this, new TrialEventArgs(TrialState.End, TrialCount));
            }

            ClearDisplay();
        }
Beispiel #39
0
        private void BtnRegister_Click(object sender, RoutedEventArgs e)
        {
            // Check input
            this.ShowMessage(Visibility.Hidden, "");
            if (string.IsNullOrEmpty(this.TxtRegisterName.Text.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "User name required.");
                this.TxtRegisterName.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtRegisterPwd.Password.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Password required.");
                this.TxtRegisterPwd.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtRegisterPwdRepeat.Password.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Password required.");
                this.TxtRegisterPwdRepeat.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtRealName.Text.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Real name required.");
                this.TxtRealName.Focus();
                return;
            }
            if (RadioBtnMale.IsChecked == false && RadioBtnFemale.IsChecked == false)
            {
                this.ShowMessage(Visibility.Visible, "Sex required.");
                this.RadioBtnMale.Focus();
                return;
            }
            if (string.IsNullOrEmpty(((DateTime)(this.DatePickerBirthday.SelectedDate)).ToString("d")))
            {
                this.ShowMessage(Visibility.Visible, "Birthday required.");
                this.DatePickerBirthday.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.ComboBoxEducation.SelectedValue.ToString().Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Education required.");
                this.ComboBoxEducation.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtPhone.Text.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Phone required.");
                this.TxtPhone.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtEmail.Text.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Email required.");
                this.TxtEmail.Focus();
                return;
            }
            if (string.IsNullOrEmpty(this.TxtStudentID.Text.Trim()))
            {
                this.ShowMessage(Visibility.Visible, "Student ID required.");
                this.TxtStudentID.Focus();
                return;
            }

            // Read user info
            UserInfo user_info = new UserInfo();
            user_info.LoginName = this.TxtRegisterName.Text.Trim();
            user_info.Password = this.TxtRegisterPwd.Password.Trim();
            user_info.UserName = this.TxtRealName.Text.Trim();
            user_info.Sex = this.RadioBtnMale.IsChecked == true ? SexType.Male : SexType.Femal;
            user_info.Birthday = (DateTime)(this.DatePickerBirthday.SelectedDate);
            user_info.Education = (EducationType)(this.ComboBoxEducation.SelectedIndex);
            user_info.Phone = this.TxtPhone.Text.Trim();
            user_info.Email = this.TxtEmail.Text.Trim();
            user_info.StudentID = this.TxtStudentID.Text.Trim();
            user_info.Authority = AuthorityType.Experimenter;

            // Register
            try
            {
                // Check user info
                if (DatabaseHelper.IsUserRegistered(user_info.LoginName))
                {
                    ShowMessage(Visibility.Visible, "User name already exists");
                    TxtRegisterName.Focus();
                    return;
                }
                if (this.TxtRegisterPwdRepeat.Password.Trim() != this.TxtRegisterPwd.Password.Trim())
                {
                    ShowMessage(Visibility.Visible, "Two input passwords do not match.");
                    TxtRegisterPwdRepeat.Focus();
                    return;
                }
                // Register
                if (DatabaseHelper.RegisterUserInfo(user_info))
                {
                    MessageWin message_win = new MessageWin();
                    message_win.ShowDialog("注册成功!请登录。", "提示", MessageBoxButton.OK);
                    // 转到登陆界面
                    ShowLoginUI();
                }
                else
                {
                    this.ShowMessage(Visibility.Visible, "Unknown user name or incorrect password.");
                }
            }
            catch (Exception ex)
            {
                DatabaseMessage.ShowDatabaseFailure(ex.Message);
            }
        }
Beispiel #40
0
 public void Win()
 {
     MessageWin?.Invoke();
 }
Beispiel #41
0
 private bool InitDatabase()
 {
     // 初始化数据库
     //MySqlHelper.InitializeDatabase("3dimage.ee.tsinghua.edu.cn", "3306", "root", "root123");
     //MySqlHelper.InitializeDatabase("166.111.64.55", "3306", "root", "root123");
         
     // 只在初始配置数据库时运行
     if (!DatabaseInitialized)
     {       
         try
         {
             MySqlHelper.InitializeDatabase("localhost", "3306", "root", "root123");
             MySqlHelper.ConfigMySqlDatabase(TableType.User);
         }
         catch (Exception ex)
         {
             MessageWin message_win = new MessageWin();
             message_win.Owner = (Window)this.Parent;
             message_win.ShowDialog("糟糕!数据库初始化失败!请检查是否启动了MySql.\n错误信息:" + ex.Message, "提示", MessageBoxButton.OK);
             return false;
         }
     }
     
     return true;
 }