/// <summary> /// Creates a LoginDialog inside of the current window. /// </summary> /// <param name="title">The title of the LoginDialog.</param> /// <param name="message">The message contained within the LoginDialog.</param> /// <param name="settings">Optional settings that override the global metro dialog settings.</param> /// <returns>The text that was entered or null (Nothing in Visual Basic) if the user cancelled the operation.</returns> public static Task<LoginDialogData> ShowLoginAsync(this MetroWindow window, string title, string message, LoginDialogSettings settings = null) { window.Dispatcher.VerifyAccess(); return HandleOverlayOnShow(settings, window).ContinueWith(z => { return (Task<LoginDialogData>)window.Dispatcher.Invoke(new Func<Task<LoginDialogData>>(() => { if (settings == null) { settings = new LoginDialogSettings(); } //create the dialog control LoginDialog dialog = new LoginDialog(window, settings); dialog.Title = title; dialog.Message = message; SizeChangedEventHandler sizeHandler = SetupAndOpenDialog(window, dialog); dialog.SizeChangedHandler = sizeHandler; return dialog.WaitForLoadAsync().ContinueWith(x => { if (DialogOpened != null) { window.Dispatcher.BeginInvoke(new Action(() => DialogOpened(window, new DialogStateChangedEventArgs() { }))); } return dialog.WaitForButtonPressAsync().ContinueWith(y => { //once a button as been clicked, begin removing the dialog. dialog.OnClose(); if (DialogClosed != null) { window.Dispatcher.BeginInvoke(new Action(() => DialogClosed(window, new DialogStateChangedEventArgs() { }))); } Task closingTask = (Task)window.Dispatcher.Invoke(new Func<Task>(() => dialog._WaitForCloseAsync())); return closingTask.ContinueWith<Task<LoginDialogData>>(a => { return ((Task)window.Dispatcher.Invoke(new Func<Task>(() => { window.SizeChanged -= sizeHandler; window.metroDialogContainer.Children.Remove(dialog); //remove the dialog from the container return HandleOverlayOnHide(settings, window); //window.overlayBox.Visibility = System.Windows.Visibility.Hidden; //deactive the overlay effect }))).ContinueWith(y3 => y).Unwrap(); }); }).Unwrap(); }).Unwrap().Unwrap(); })); }).Unwrap(); }
private async Task LaunchGameFromWindow() { try { string userName = playerNameTextBox.Text; #region 检查有效数据 if (authTypeCombobox.SelectedItem == null) { await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyAuthType"), App.GetResourceString("String.Message.EmptyAuthType2")); return; } if (string.IsNullOrWhiteSpace(userName)) { await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyUsername"), App.GetResourceString("String.Message.EmptyUsername2")); return; } if (launchVersionCombobox.SelectedItem == null) { await this.ShowMessageAsync(App.GetResourceString("String.Message.EmptyLaunchVersion"), App.GetResourceString("String.Message.EmptyLaunchVersion2")); return; } if (App.handler.Java == null) { await this.ShowMessageAsync(App.GetResourceString("String.Message.NoJava"), App.GetResourceString("String.Message.NoJava2")); return; } #endregion LaunchSetting launchSetting = new LaunchSetting() { Version = (Core.Modules.Version)launchVersionCombobox.SelectedItem }; this.loadingGrid.Visibility = Visibility.Visible; this.loadingRing.IsActive = true; #region 验证 AuthTypeItem auth = (AuthTypeItem)authTypeCombobox.SelectedItem; //设置CLIENT TOKEN if (string.IsNullOrWhiteSpace(App.config.MainConfig.User.ClientToken)) { App.config.MainConfig.User.ClientToken = Guid.NewGuid().ToString("N"); } else { Requester.ClientToken = App.config.MainConfig.User.ClientToken; } #region NewData string autoVerifyingMsg = null; string autoVerifyingMsg2 = null; string autoVerificationFailedMsg = null; string autoVerificationFailedMsg2 = null; string loginMsg = null; string loginMsg2 = null; LoginDialogSettings loginDialogSettings = new LoginDialogSettings() { NegativeButtonText = App.GetResourceString("String.Base.Cancel"), AffirmativeButtonText = App.GetResourceString("String.Base.Login"), RememberCheckBoxText = App.GetResourceString("String.Base.ShouldRememberLogin"), UsernameWatermark = App.GetResourceString("String.Base.Username"), InitialUsername = userName, RememberCheckBoxVisibility = Visibility, EnablePasswordPreview = true, PasswordWatermark = App.GetResourceString("String.Base.Password"), NegativeButtonVisibility = Visibility.Visible }; string verifyingMsg = null, verifyingMsg2 = null, verifyingFailedMsg = null, verifyingFailedMsg2 = null; #endregion switch (auth.Type) { #region 离线验证 case Config.AuthenticationType.OFFLINE: var loginResult = Core.Auth.OfflineAuthenticator.DoAuthenticate(userName); launchSetting.AuthenticateAccessToken = loginResult.Item1; launchSetting.AuthenticateUUID = loginResult.Item2; break; #endregion #region Mojang验证 case Config.AuthenticationType.MOJANG: Requester.AuthURL = "https://authserver.mojang.com"; autoVerifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Mojang.AutoVerifying"); autoVerifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Mojang.AutoVerifying2"); autoVerificationFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Mojang.AutoVerificationFailed"); autoVerificationFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Mojang.AutoVerificationFailed2"); loginMsg = App.GetResourceString("String.Mainwindow.Auth.Mojang.Login"); loginMsg2 = App.GetResourceString("String.Mainwindow.Auth.Mojang.Login2"); verifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Mojang.Verifying"); verifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Mojang.Verifying2"); verifyingFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Mojang.VerificationFailed"); verifyingFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Mojang.VerificationFailed2"); break; #endregion #region 统一通行证验证 case Config.AuthenticationType.NIDE8: if (App.nide8Handler == null) { await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Nide8.NoID"), App.GetResourceString("String.Mainwindow.Auth.Nide8.NoID2")); return; } Requester.AuthURL = string.Format("{0}authserver", App.nide8Handler.BaseURL); autoVerifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Nide8.AutoVerifying"); autoVerifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Nide8.AutoVerifying2"); autoVerificationFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Nide8.AutoVerificationFailed"); autoVerificationFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Nide8.AutoVerificationFailed2"); loginMsg = App.GetResourceString("String.Mainwindow.Auth.Nide8.Login"); loginMsg2 = App.GetResourceString("String.Mainwindow.Auth.Nide8.Login2"); verifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Nide8.Verifying"); verifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Nide8.Verifying2"); verifyingFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Nide8.VerificationFailed"); verifyingFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Nide8.VerificationFailed2"); loginDialogSettings.NegativeButtonVisibility = Visibility.Visible; var nide8ChooseResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Nide8.Login2"), App.GetResourceString("String.Base.Choose"), MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings() { AffirmativeButtonText = App.GetResourceString("String.Base.Login"), NegativeButtonText = App.GetResourceString("String.Base.Cancel"), FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Register"), DefaultButtonFocus = MessageDialogResult.Affirmative }); if (nide8ChooseResult == MessageDialogResult.Negative) { return; } if (nide8ChooseResult == MessageDialogResult.FirstAuxiliary) { System.Diagnostics.Process.Start(string.Format("https://login2.nide8.com:233/{0}/register", App.nide8Handler.ServerID)); return; } break; #endregion #region 自定义验证 case Config.AuthenticationType.CUSTOM_SERVER: string customAuthServer = App.config.MainConfig.User.AuthServer; if (string.IsNullOrWhiteSpace(customAuthServer)) { await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.Auth.Custom.NoAdrress"), App.GetResourceString("String.Mainwindow.Auth.Custom.NoAdrress2")); return; } else { Requester.AuthURL = customAuthServer; } autoVerifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Custom.AutoVerifying"); autoVerifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Custom.AutoVerifying2"); autoVerificationFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Custom.AutoVerificationFailed"); autoVerificationFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Custom.AutoVerificationFailed2"); loginMsg = App.GetResourceString("String.Mainwindow.Auth.Custom.Login"); loginMsg2 = App.GetResourceString("String.Mainwindow.Auth.Custom.Login2"); verifyingMsg = App.GetResourceString("String.Mainwindow.Auth.Custom.Verifying"); verifyingMsg2 = App.GetResourceString("String.Mainwindow.Auth.Custom.Verifying2"); verifyingFailedMsg = App.GetResourceString("String.Mainwindow.Auth.Custom.VerificationFailed"); verifyingFailedMsg2 = App.GetResourceString("String.Mainwindow.Auth.Custom.VerificationFailed2"); break; #endregion default: var defaultLoginResult = Core.Auth.OfflineAuthenticator.DoAuthenticate(userName); launchSetting.AuthenticateAccessToken = defaultLoginResult.Item1; launchSetting.AuthenticateUUID = defaultLoginResult.Item2; break; } if (auth.Type != Config.AuthenticationType.OFFLINE) { try { #region 如果记住登陆(有登陆记录) if ((!string.IsNullOrWhiteSpace(App.config.MainConfig.User.AccessToken)) && (App.config.MainConfig.User.AuthenticationUUID != null)) { var loader = await this.ShowProgressAsync(autoVerifyingMsg, autoVerifyingMsg2); loader.SetIndeterminate(); Validate validate = new Validate(App.config.MainConfig.User.AccessToken); var validateResult = await validate.PerformRequestAsync(); if (validateResult.IsSuccess) { launchSetting.AuthenticateAccessToken = App.config.MainConfig.User.AccessToken; launchSetting.AuthenticateUUID = App.config.MainConfig.User.AuthenticationUUID; await loader.CloseAsync(); } else { Refresh refresher = new Refresh(App.config.MainConfig.User.AccessToken); var refreshResult = await refresher.PerformRequestAsync(); await loader.CloseAsync(); if (refreshResult.IsSuccess) { App.config.MainConfig.User.AccessToken = refreshResult.AccessToken; launchSetting.AuthenticateUUID = App.config.MainConfig.User.AuthenticationUUID; launchSetting.AuthenticateAccessToken = refreshResult.AccessToken; } else { App.config.MainConfig.User.AccessToken = string.Empty; App.config.Save(); await this.ShowMessageAsync(autoVerificationFailedMsg, autoVerificationFailedMsg2); return; } } } #endregion #region 从零登陆 else { var loginMsgResult = await this.ShowLoginAsync(loginMsg, loginMsg2, loginDialogSettings); if (loginMsgResult == null) { return; } var loader = await this.ShowProgressAsync(verifyingMsg, verifyingMsg2); loader.SetIndeterminate(); userName = loginMsgResult.Username; Authenticate authenticate = new Authenticate(new Credentials() { Username = loginMsgResult.Username, Password = loginMsgResult.Password }); var aloginResult = await authenticate.PerformRequestAsync(); await loader.CloseAsync(); if (aloginResult.IsSuccess) { if (loginMsgResult.ShouldRemember) { App.config.MainConfig.User.AccessToken = aloginResult.AccessToken; } App.config.MainConfig.User.AuthenticationUserData = aloginResult.User; App.config.MainConfig.User.AuthenticationUUID = aloginResult.SelectedProfile; launchSetting.AuthenticateAccessToken = aloginResult.AccessToken; launchSetting.AuthenticateUUID = aloginResult.SelectedProfile; launchSetting.AuthenticationUserData = aloginResult.User; } else { await this.ShowMessageAsync(verifyingFailedMsg, verifyingFailedMsg2 + aloginResult.Error.ErrorMessage); return; } } #endregion } catch (Exception ex) { await this.ShowMessageAsync(verifyingFailedMsg, verifyingFailedMsg2 + ex.Message); return; } } App.config.MainConfig.User.AuthenticationType = auth.Type; #endregion #region 检查游戏完整 List <DownloadTask> losts = new List <DownloadTask>(); App.logHandler.AppendInfo("检查丢失的依赖库文件中..."); var lostDepend = await GetLost.GetLostDependDownloadTaskAsync( App.config.MainConfig.Download.DownloadSource, App.handler, launchSetting.Version); if (auth.Type == Config.AuthenticationType.NIDE8) { string nideJarPath = App.handler.GetNide8JarPath(); if (!File.Exists(nideJarPath)) { lostDepend.Add(new DownloadTask("统一通行证核心", "https://login2.nide8.com:233/index/jar", nideJarPath)); } } if (App.config.MainConfig.Environment.DownloadLostDepend && lostDepend.Count != 0) { MessageDialogResult downDependResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.NeedDownloadDepend"), App.GetResourceString("String.Mainwindow.NeedDownloadDepend2"), MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings() { AffirmativeButtonText = App.GetResourceString("String.Base.Download"), NegativeButtonText = App.GetResourceString("String.Base.Cancel"), FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Unremember"), DefaultButtonFocus = MessageDialogResult.Affirmative }); switch (downDependResult) { case MessageDialogResult.Affirmative: losts.AddRange(lostDepend); break; case MessageDialogResult.FirstAuxiliary: App.config.MainConfig.Environment.DownloadLostDepend = false; break; default: break; } } App.logHandler.AppendInfo("检查丢失的资源文件中..."); if (App.config.MainConfig.Environment.DownloadLostAssets && (await GetLost.IsLostAssetsAsync(App.config.MainConfig.Download.DownloadSource, App.handler, launchSetting.Version))) { MessageDialogResult downDependResult = await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.NeedDownloadAssets"), App.GetResourceString("String.Mainwindow.NeedDownloadAssets2"), MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, new MetroDialogSettings() { AffirmativeButtonText = App.GetResourceString("String.Base.Download"), NegativeButtonText = App.GetResourceString("String.Base.Cancel"), FirstAuxiliaryButtonText = App.GetResourceString("String.Base.Unremember"), DefaultButtonFocus = MessageDialogResult.Affirmative }); switch (downDependResult) { case MessageDialogResult.Affirmative: var lostAssets = await GetLost.GetLostAssetsDownloadTaskAsync( App.config.MainConfig.Download.DownloadSource, App.handler, launchSetting.Version); losts.AddRange(lostAssets); break; case MessageDialogResult.FirstAuxiliary: App.config.MainConfig.Environment.DownloadLostAssets = false; break; default: break; } } if (losts.Count != 0) { App.downloader.SetDownloadTasks(losts); App.downloader.StartDownload(); await new Windows.DownloadWindow().ShowWhenDownloading(); } #endregion #region 根据配置文件设置 launchSetting.AdvencedGameArguments += App.config.MainConfig.Environment.AdvencedGameArguments; launchSetting.AdvencedJvmArguments += App.config.MainConfig.Environment.AdvencedJvmArguments; launchSetting.GCArgument += App.config.MainConfig.Environment.GCArgument; launchSetting.GCEnabled = App.config.MainConfig.Environment.GCEnabled; launchSetting.GCType = App.config.MainConfig.Environment.GCType; launchSetting.JavaAgent += App.config.MainConfig.Environment.JavaAgent; if (auth.Type == Config.AuthenticationType.NIDE8) { launchSetting.JavaAgent += string.Format(" \"{0}\"={1}", App.handler.GetNide8JarPath(), App.config.MainConfig.User.Nide8ServerID); } //直连服务器设置 if ((auth.Type == Config.AuthenticationType.NIDE8) && App.config.MainConfig.User.AllUsingNide8) { var nide8ReturnResult = await App.nide8Handler.GetInfoAsync(); if (App.config.MainConfig.User.AllUsingNide8 && !string.IsNullOrWhiteSpace(nide8ReturnResult.Meta.ServerIP)) { Server server = new Server(); string[] serverIp = nide8ReturnResult.Meta.ServerIP.Split(':'); if (serverIp.Length == 2) { server.Address = serverIp[0]; server.Port = ushort.Parse(serverIp[1]); } else { server.Address = nide8ReturnResult.Meta.ServerIP; server.Port = 25565; } launchSetting.LaunchToServer = server; } } else if (App.config.MainConfig.Server.LaunchToServer) { launchSetting.LaunchToServer = new Server() { Address = App.config.MainConfig.Server.Address, Port = App.config.MainConfig.Server.Port }; } //自动内存设置 if (App.config.MainConfig.Environment.AutoMemory) { var m = SystemTools.GetBestMemory(App.handler.Java); App.config.MainConfig.Environment.MaxMemory = m; launchSetting.MaxMemory = m; } else { launchSetting.MaxMemory = App.config.MainConfig.Environment.MaxMemory; } launchSetting.VersionType = App.config.MainConfig.Customize.VersionInfo; launchSetting.WindowSize = App.config.MainConfig.Environment.WindowSize; #endregion #region 配置文件处理 App.config.MainConfig.User.UserName = userName; App.config.Save(); #endregion #region 启动 App.logHandler.OnLog += (a, b) => { this.Invoke(() => { launchInfoBlock.Text = b.Message; }); }; var result = await App.handler.LaunchAsync(launchSetting); App.logHandler.OnLog -= (a, b) => { this.Invoke(() => { launchInfoBlock.Text = b.Message; }); }; //程序猿是找不到女朋友的了 :) if (!result.IsSuccess) { await this.ShowMessageAsync(App.GetResourceString("String.Mainwindow.LaunchError") + result.LaunchException.Title, result.LaunchException.Message); App.logHandler.AppendError(result.LaunchException); } else { try { await Task.Factory.StartNew(() => { result.Process.WaitForInputIdle(); }); } catch (Exception ex) { await this.ShowMessageAsync("启动后等待游戏窗口响应异常", "这可能是由于游戏进程发生意外(闪退)导致的。具体原因:" + ex.Message); return; } if (App.config.MainConfig.Environment.ExitAfterLaunch) { Application.Current.Shutdown(); } this.WindowState = WindowState.Minimized; Refresh(); //自定义处理 if (!string.IsNullOrWhiteSpace(App.config.MainConfig.Customize.GameWindowTitle)) { GameHelper.SetGameTitle(result, App.config.MainConfig.Customize.GameWindowTitle); } if (App.config.MainConfig.Customize.CustomBackGroundMusic) { mediaElement.Volume = 0.5; await Task.Factory.StartNew(() => { try { for (int i = 0; i < 50; i++) { this.Dispatcher.Invoke(new Action(() => { this.mediaElement.Volume -= 0.01; })); Thread.Sleep(50); } this.Dispatcher.Invoke(new Action(() => { this.mediaElement.Stop(); })); } catch (Exception) {} }); } } #endregion } catch (Exception ex) { App.logHandler.AppendFatal(ex); } finally { this.loadingGrid.Visibility = Visibility.Hidden; this.loadingRing.IsActive = false; } }
public async Task <LoginDialogData> ShowLoginAsync(string title, string message, LoginDialogSettings settings = null) { return(await instance.ShowLoginAsync(this, title, message, settings)); }
async void Btn_ingresar_Click(object sender, RoutedEventArgs e) { LoginDialogSettings settings = new LoginDialogSettings(); settings.ColorScheme = MetroDialogOptions.ColorScheme; settings.PasswordWatermark = "Password"; settings.UsernameWatermark = "Username"; settings.AffirmativeButtonText = StringResources.lblBtnLogin; settings.EnablePasswordPreview = true; //Abrimos el mensaje modal para que el usuario ingrese sus credenciales, el resultado lo guardamos en una variable local. LoginDialogData result = await this.ShowLoginAsync(StringResources.ttlAuthentication, StringResources.lblEnterCredentials, settings); //Comparamos si el resultado es distinto de nulo. Si es igual a nulo quiere decir que el usuario cancelo la captura o cerró inesperadamente la pantalla. if (result != null) { //Incializamos los servicios de dialog. DialogService dialog = new DialogService(); //Declaramos un objeto de tipo ProgressDialogController, el cual servirá para recibir el resultado el mensaje progress. ProgressDialogController AsyncProgress; //Ejecutamos el método para enviar un mensaje de espera mientras se comprueban los datos. AsyncProgress = await dialog.SendProgressAsync(StringResources.lblLogIn, ""); //Declaramos un objeto con el cual se realiza la encriptación Services.Encriptacion encriptar = new Services.Encriptacion(); //Ejecutamos el método para encriptar tanto el usuario como la contraseña y los guardamos en variables locales respectivamente. string usuario = encriptar.encript(result.Username); string contrasena = encriptar.encript(result.Password); //Ejecutamos el método para verificar las credenciales, el resultado lo asignamos a un objeto local de tipo Usuario. Usuario usuarioConectado = await DataManager.GetLogin(usuario, contrasena); //Verificamos el resultado, si es direfente de nulo quiere decir que el logueo fué correcto, si es igual a nulo quiere decir que el usuario no existe con las credenciales proporcionadas. if (usuarioConectado != null) { //Ejecutamos el método para cerrar el mensaje de espera. await AsyncProgress.CloseAsync(); //Verificamos si el usuario no esta bloqueado. if (usuarioConectado.Block) { //Enviamos un mensaje para indicar que el usuario está bloqueado. MessageDialogResult message = await this.ShowMessageAsync(StringResources.lblInformation, StringResources.lblUserNotActive); } else { SpeechSynthesizer _SS = new SpeechSynthesizer(); _SS.Volume = 100; _SS.Rate = 1; _SS.SpeakAsync("Welcome, " + usuarioConectado.Nombre + ", To Process Design Engineering Program"); //Enviamos un mensaje de bienvenida al usuario. MessageDialogResult message = await this.ShowMessageAsync(StringResources.lblWelcome, usuarioConectado.Nombre); //Obtenemos la fecha del servidor DateTime date_now = DataManagerControlDocumentos.Get_DateTime(); //Ejecutamos el método para desbloquear el sistema, si se venció la fecha final DataManagerControlDocumentos.DesbloquearSistema(date_now); //Obtenemos los detalles del usuario logueado. usuarioConectado.Details = DataManager.GetUserDetails(usuarioConectado.NombreUsuario); //Verificamos si esta cargada la foto, sino asignamos una por default. if (string.IsNullOrEmpty(usuarioConectado.Details.PathPhoto)) { usuarioConectado.Details.PathPhoto = System.Configuration.ConfigurationManager.AppSettings["PathDefaultImage"]; } //Insertamos el ingreso a la bitácora. DataManager.InserIngresoBitacora(Environment.MachineName, usuarioConectado.Nombre + " " + usuarioConectado.ApellidoPaterno + " " + usuarioConectado.ApellidoMaterno); //Validamos si el usuario nuevo tiene la contraseña random if (usuarioConectado.Details.Temporal_Password == true) { //Cargamnos las vista de ModificarContrasena ModificarContrasena vistacontrasena = new ModificarContrasena(); //Cargamnos el modelo de CambiarContraseniaViewModel CambiarContraseniaViewModel vmcambiarconatraseña = new CambiarContraseniaViewModel(usuarioConectado); //Asingamos el DataContext. vistacontrasena.DataContext = vmcambiarconatraseña; //Mostramos la ventana de modificacion de contraseña vistacontrasena.ShowDialog(); //Verificamos el valor de la variable CierrePantalla, si en la View Model de CambiarContrasenia la variable es false, dejamos continual el proceso if (vmcambiarconatraseña.CierrePantalla == false) { return; } } //#region Configuración del correo electrónico ////Verificamos si esta configurado el correo electrónico en la plataforma. //if (!usuarioConectado.Details.IsAvailableEmail || !System.IO.File.Exists(usuarioConectado.Pathnsf)) //{ // //Configuramos las opciones del mesaje de pregunta. // MetroDialogSettings settings = new MetroDialogSettings(); // settings.AffirmativeButtonText = StringResources.lblYes; // settings.NegativeButtonText = StringResources.lblNo; // //Preguntamos al usuario si lo quiere configurar en estos momentos. // MessageDialogResult resultMSG = await this.ShowMessageAsync(StringResources.ttlAtencion + usuarioConectado.Nombre, StringResources.msgConfiguracionCorreo, MessageDialogStyle.AffirmativeAndNegative, settings); // //Verificamos la respuesta del usuario, si es afirmativa iniciamos el proceso de configuración. // if (resultMSG == MessageDialogResult.Affirmative) // { // settings = new MetroDialogSettings(); // settings.AffirmativeButtonText = StringResources.ttlOkEntiendo; // await this.ShowMessageAsync(usuarioConectado.Nombre + StringResources.msgParaTuInf, StringResources.msgProcesoConfiguracion, MessageDialogStyle.Affirmative, settings); // ProgressDialogController AsyncProgressConfigEmail; // AsyncProgressConfigEmail = await dialog.SendProgressAsync(StringResources.ttlEspereUnMomento + usuarioConectado.Nombre + "...", StringResources.msgEstamosConfigurando); // ConfigEmailViewModel configEmail = new ConfigEmailViewModel(usuarioConectado); // // Se reciben valores de las 2 propiedades del objeto // DO_PathMail respuestaConfigEmail = await configEmail.setEmail(); // await AsyncProgressConfigEmail.CloseAsync(); // if (respuestaConfigEmail.respuesta) // { // // Actualizamos el path de usuario en la misma sesión // usuarioConectado.Pathnsf = respuestaConfigEmail.rutamail; // settings.AffirmativeButtonText = StringResources.ttlGenial; // await this.ShowMessageAsync(StringResources.msgPerfecto + usuarioConectado.Nombre, StringResources.msgCuentaConfigurada, MessageDialogStyle.Affirmative, settings); // } // else // { // await this.ShowMessageAsync(StringResources.ttlOcurrioError, StringResources.msgErrorVincular); // } // } //} //#endregion if (Module.UsuarioIsRol(usuarioConectado.Roles, 2)) { DashboardViewModel context; FDashBoard pDashBoard = new FDashBoard(); context = new DashboardViewModel(usuarioConectado); context.ModelUsuario = usuarioConectado; //NOTA IMPORTANTE: Se hizo una redundancia al asignarle en la propiedad página su misma pantalla. Solo es por ser la primeva vez y tenernos en donde descanzar la primera pantalla. context.Pagina = pDashBoard; //Asignamos al DataContext de la PantallaHome el context creado anteriormente. pDashBoard.DataContext = context; //Declaramos la pantalla en la que descanzan todas las páginas. Layout masterPage = new Layout(); //Asingamos el DataContext. masterPage.DataContext = context; //Ejecutamos el método el cual despliega la pantalla. masterPage.ShowDialog(); } else { Home PantallaHome = new Home(usuarioConectado.NombreUsuario); //Creamos un objeto UsuarioViewModel, y le asignamos los valores correspondientes, a la propiedad Pagina se le asigna la pantalla inicial de Home. UsuarioViewModel context = new UsuarioViewModel(usuarioConectado, PantallaHome); context.ModelUsuario = usuarioConectado; //NOTA IMPORTANTE: Se hizo una redundancia al asignarle en la propiedad página su misma pantalla. Solo es por ser la primeva vez y tenernos en donde descanzar la primera pantalla. context.Pagina = PantallaHome; //Asignamos al DataContext de la PantallaHome el context creado anteriormente. PantallaHome.DataContext = context; //Declaramos la pantalla en la que descanzan todas las páginas. Layout masterPage = new Layout(); //Asingamos el DataContext. masterPage.DataContext = context; //Ejecutamos el método el cual despliega la pantalla. masterPage.ShowDialog(); } //Una vez que el usuario hizo clic en aceptar el mensaje de bienvenida, se procede con la codificación de la presentación de la pantalla inicial. //Creamos un objeto de tipo Home, la cual es la pantalla inicial del sistema. //Home PantallaHome = new Home(usuarioConectado.NombreUsuario); //Creamos un objeto UsuarioViewModel, y le asignamos los valores correspondientes, a la propiedad Pagina se le asigna la pantalla inicial de Home. //UsuarioViewModel context = new UsuarioViewModel { ModelUsuario = usuarioConectado, Pagina = PantallaHome }; //UsuarioViewModel context = new UsuarioViewModel(usuarioConectado, PantallaHome); //context.ModelUsuario = usuarioConectado; ////NOTA IMPORTANTE: Se hizo una redundancia al asignarle en la propiedad página su misma pantalla. Solo es por ser la primeva vez y tenernos en donde descanzar la primera pantalla. //context.Pagina = PantallaHome; ////Asignamos al DataContext de la PantallaHome el context creado anteriormente. //PantallaHome.DataContext = context; ////Declaramos la pantalla en la que descanzan todas las páginas. //Layout masterPage = new Layout(); ////Asingamos el DataContext. //masterPage.DataContext = context; ////Ejecutamos el método el cual despliega la pantalla. //masterPage.ShowDialog(); ////Si el usuario es administrador, le mostramos la pantalla de Dashboard. //if (Module.UsuarioIsRol(usuarioConectado.Roles, 2)) //{ // FDashBoard pDashBoard = new FDashBoard(); // DashboardViewModel wm = new DashboardViewModel(pDashBoard, usuarioConectado); // pDashBoard.DataContext = wm; // //Declaramos la pantalla en la que descanzan todas las páginas. // Layout masterPage1 = new Layout(); // //Asingamos el DataContext. // masterPage1.DataContext = wm; // //Ejecutamos el método el cual despliega la pantalla. // masterPage1.ShowDialog(); //} //else //{ //} } } else { //Ejecutamos el método para cerrar el mensaje de espera. await AsyncProgress.CloseAsync(); //Enviamos un mensaje indicando que las credenciales escritas son incorrectas. MessageDialogResult message = await this.ShowMessageAsync(StringResources.ttlAlerta, StringResources.lblPasswordIncorrect); } } }
/// <inheritdoc /> public async Task <LoginDialogData> ShowLoginAsync(string title, string message, LoginDialogSettings settings = null) { using (await _lock.EnterAsync()) { if (ShellView != null) { return(await ShellView.ShowLoginAsync( L(nameof(Resources.SettingsViewModel_SetSourceUsernameAndPasswordTitle)), L(nameof(Resources.SettingsViewModel_SetSourceUsernameAndPasswordMessage)), settings)); } return(null); } }
private async void Tile_Click(object sender, RoutedEventArgs e) { var tile = (Tile)e.Source; var metroDialogSettings = new MetroDialogSettings { AffirmativeButtonText = "Login", FirstAuxiliaryButtonText = "Register", AnimateShow = true }; var result = await App.Window.ShowMessageAsync("Credentials", $"You Selected {tile.Title} as a User Role ", MessageDialogStyle.AffirmativeAndNegativeAndSingleAuxiliary, metroDialogSettings); var dialogSettings = new LoginDialogSettings { UsernameWatermark = "Email", PasswordWatermark = "Password", EnablePasswordPreview = true, FirstAuxiliaryButtonText = "Reset Password", }; switch (result) { case MessageDialogResult.Affirmative: var loginResult = await App.Window.ShowLoginAsync("Login", "Enter your username and password", dialogSettings); if (loginResult == null) { return; } var loginResultString = POS.LoginCheck(loginResult.Username, loginResult.Password, tile.Title); if (loginResultString == "Login Successful" || loginResultString == "Welcome Admin") { App.User = POS.GetUser <Models.User>(loginResult.Username); App.Window.MainContentControl.Content = new MainControl { Margin = new Thickness(100) }; App.Window.UserFlyout.SetControl(); } await App.Window.ShowMessageAsync("Login", loginResultString); break; case MessageDialogResult.FirstAuxiliary: var nameResult = App.Window.ShowModalInputExternal($"Role : {tile.Title}", "Set your name for your role"); if (nameResult == null) { await App.Window.ShowMessageAsync("Register", "You must enter a name"); } else { dialogSettings.AffirmativeButtonText = "Register"; var registerResult = await App.Window.ShowLoginAsync("Register", $"{tile.Title}: {nameResult} enter your credentials for security", dialogSettings); await App.Window.ShowMessageAsync("Register", POS.RegisterCheck(nameResult, registerResult?.Username, registerResult?.Password, tile.Title)); } break; } }