/// <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(); }
public LoginScene() { SoundManager.PlaySound(SoundList.IntroMusic, true); Disposing += (o, e) => SoundManager.StopSound(SoundList.IntroMusic); _background = new MirAnimatedControl { Animated = false, AnimationCount = 19, AnimationDelay = 100, Index = 0, Library = Libraries.ChrSel, Loop = false, Parent = this, }; _login = new LoginDialog {Parent = _background, Visible = false}; _login.AccountButton.Click += (o, e) => { _login.Hide(); _account = new NewAccountDialog { Parent = _background }; _account.Disposing += (o1, e1) => _login.Show(); }; _login.PassButton.Click += (o, e) => { _login.Hide(); _password = new ChangePasswordDialog { Parent = _background }; _password.Disposing += (o1, e1) => _login.Show(); }; Version = new MirLabel { AutoSize = true, BackColour = Color.FromArgb(200, 50, 50, 50), Border = true, BorderColour = Color.Black, Location = new Point(5, 580), Parent = _background, Text = string.Format("Version: {0}", Application.ProductVersion), }; _connectBox = new MirMessageBox("Attempting to connect to the server.", MirMessageBoxButtons.Cancel); _connectBox.CancelButton.Click += (o, e) => Program.Form.Close(); Shown += (sender, args) => { Network.Connect(); _connectBox.Show(); }; }
private void loginMenuItem_Click(object sender, RoutedEventArgs e) { // Instantiate the dialog box LoginDialog dlg = new LoginDialog(); // Configure the dialog box dlg.Owner = this; // Open the dialog box modally dlg.ShowDialog(); // Process data entered by user if dialog box is accepted if (dlg.DialogResult == true) { // Attempt to login the user if (userDataModel.LoadUser(dlg.Username, dlg.Password)) { if ((userDataModel.User.UserInRoles != null) && (userDataModel.User.UserInRoles.Count == 1)) { if (userDataModel.User.UserInRoles[0].Role.RoleName.CompareTo("Administrator") == 0) { currentUserRole = UserRole.Administrator; } else if (userDataModel.User.UserInRoles[0].Role.RoleName.CompareTo("Experimenter") == 0) { currentUserRole = UserRole.Experimenter; } else if (userDataModel.User.UserInRoles[0].Role.RoleName.CompareTo("Operator") == 0) { currentUserRole = UserRole.Experimenter; } else { return; } SetupViewByRole(); } } else { return; } } }
private async void NavigationViewItem_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e) { if (!Login.IsLogin) { var dialog = new LoginDialog(); var result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { DisplayCompleteDialog(); btnLogin.Content = "Logout"; } } else { DisplayNoWifiDialog(); Login.Logout(); btnLogin.Content = "Login"; } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += Application_ThreadException; InitializeLogging(); ApplyLocale(); //显示登录窗口 using (var dialog = new LoginDialog()) { var result = dialog.ShowDialog(); if (result != DialogResult.OK) { return; } } Application.Run(new MainForm()); }
public static bool Login(string info, bool relogin) { try { IOptionsDataAccessAgent optionsAgent = DataAccessServices.GetDataAccessService <IOptionsDataAccessAgent>(); PasswordOptions passwordOptions = optionsAgent.Get <PasswordOptions>("PasswordOptions", new PasswordOptions()); LoginDialog dlgLogin = new LoginDialog(passwordOptions.LoginType); Process process = Process.GetCurrentProcess(); string lastUser = optionsAgent.Get <string>("LastUser", string.Empty); bool lastLoginUseCardReader = optionsAgent.Get <bool>("LastLoginUseCardReader", false); dlgLogin.Text = Shell.storageServerName + " Login"; dlgLogin.Info = info; dlgLogin.RegularUsername = lastUser; if (passwordOptions.LoginType == LoginType.Both) { dlgLogin.UseCardReaderCheckBox = lastLoginUseCardReader; } dlgLogin.CanSetUserName = !relogin; dlgLogin.AuthenticateUser += new EventHandler <AuthenticateUserEventArgs>(dlgLogin_AuthenticateUser); if (dlgLogin.ShowDialog(new WindowWrapper(process.MainWindowHandle)) == DialogResult.OK) { UserManager.User = new ManagerUser(dlgLogin.GetUserName(), dlgLogin.GetFriendlyName(), UserManager.GetUserPermissions(dlgLogin.GetUserName())); optionsAgent.Set <bool>("LastLoginUseCardReader", dlgLogin.UseCardReaderCheckBox); LoadSplash(); return(true); } return(false); } catch (Exception ex) { Messager.ShowError(null, ex); return(false); } }
public async Task <Tuple <string, string> > OnLogInChallenge() { if (Settings.Instance.LastLoggedUser != null) { var rememberedUser = Accounts.Get(Settings.Instance.LastLoggedUser); if (rememberedUser != null) { return(new Tuple <string, string>(rememberedUser.UserName, rememberedUser.Password)); } } var dialog = new LoginDialog(); var result = await dialog.ShowAsync(); if (result != ContentDialogResult.Primary) { return(new Tuple <string, string>(null, null)); } Remember = dialog.Remember; return(new Tuple <string, string>(dialog.Username, dialog.Password)); }
public LoginScreen(ScreenManager Manager, SpriteBatch SBatch) : base(Manager, "LoginScreen", SBatch, new Vector2(0, 0), new Vector2(GlobalSettings.Default.ScreenWidth, GlobalSettings.Default.ScreenHeight)) { m_BackgroundImg = new UIImage(FileManager.GetTexture((ulong)FileIDs.UIFileIDs.setup, false), this); m_LoginDiag = new LoginDialog(this, new Vector2(GlobalSettings.Default.ScreenWidth / 2, GlobalSettings.Default.ScreenHeight / 2)); m_LoginProgressDiag = new LoginProgressDialog(this, new Vector2(GlobalSettings.Default.ScreenWidth / 2, (GlobalSettings.Default.ScreenHeight / 2) + 50)); foreach (KeyValuePair <string, UIElement> KVP in m_LoginDiag.RegistrableUIElements) { m_PResult.Elements.Add(KVP.Key, KVP.Value); } m_PResult.Elements.Add("LoginDialog", m_LoginDiag); foreach (KeyValuePair <string, UIElement> KVP in m_LoginProgressDiag.RegistrableUIElements) { m_PResult.Elements.Add(KVP.Key, KVP.Value); } m_PResult.Elements.Add("LoginProgressDialog", m_LoginProgressDiag); }
protected override async void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); LoginDialog = new LoginDialog { Cancelable = false }; LoginDialog.LoginBegin += UserLoging; GetUserToken(); ErrorMessage = Toast.MakeText(this, "Something went wrong ...", ToastLength.Short); NetworkErrorMessage = Toast.MakeText(this, "No internet connection !", ToastLength.Short); ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); ApiClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + UserToken.UserAccessToken); LoadingDialog = new Dialog(this, Android.Resource.Style.ThemeOverlayMaterial); LoadingDialog.SetContentView(Resource.Layout.LoadingScreenView); LoginDialog.Cancelable = false; LoadingDialog.Show(); await AuthorizationCheck(); }
private async Task <bool> TryUpdateAuthenticationAsync(GrpcApplicationAgent agent, HostEndpointAddress endpointAddress) { var input = await LoginDialog.GetInputAsync("Authentication required"); if (input == null) { ToastHelper.Display("Authentication required", ToastLength.Long); return(false); } var loginResponse = await GetLoginResponseAsync(agent, input); if (loginResponse.InvalidCredentials) { ToastHelper.Display("Invalid credentials", ToastLength.Long); return(false); } var authenticationStorage = new AuthenticationStorage(endpointAddress); await authenticationStorage.UpdateAsync(loginResponse.AccessToken, loginResponse.RefreshToken).ConfigureAwait(false); return(true); }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); //#if DEBUG // AuthController.UserIdentity.Authenticate("admin", "comdat2389"); //#else Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; LoginDialog login = new LoginDialog(); if (login.ShowDialog() ?? false) { MainWindow window = new MainWindow(); Current.ShutdownMode = ShutdownMode.OnMainWindowClose; Current.MainWindow = window; window.Show(); } else { Current.Shutdown(); } //#endif }
public override void Run() { LoginDialog loginForm = new LoginDialog(); loginForm.TopMost = false; if (DialogResult.OK == loginForm.ShowDialog() && !LoginDialog.flag) { foreach (IViewContent viewContent in WorkbenchSingleton.Workbench.ViewContentCollection) { if (viewContent.TitleName != StringParser.Parse("${res:FanHai.Hemera.Addins.StartPage.StartPageViewContent.TitleName}")) { viewContent.WorkbenchWindow.CloseWindow(true); } } //hide pad ---pad can't be closed but only hided foreach (PadDescriptor padDescriptor in WorkbenchSingleton.Workbench.PadContentCollection) { WorkbenchSingleton.Workbench.WorkbenchLayout.HidePad(padDescriptor); } //end WorkbenchSingleton.Workbench.RedrawMenu(); } }
public static bool Login() { if (IsUserDBConfigured()) { LoginDialog dlgLogin = new LoginDialog(); Process process = Process.GetCurrentProcess(); dlgLogin.Text = "Patient Updater Login"; dlgLogin.AuthenticateUser += new EventHandler <AuthenticateUserEventArgs>(dlgLogin_AuthenticateUser); if (dlgLogin.ShowDialog() == DialogResult.OK) { UserManager.User = new ManagerUser(dlgLogin.Username, UserManager.GetUserPermissions(dlgLogin.Username)); return(true); } } else { MessageBox.Show("Patient Updater DB Configuration Incomplete. Please run " + Program.PacsDatabaseConfigurationDemoNames[0] + " to configure the database.", "Application will exit.", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); } return(false); }
protected override void InitializeShell(Window shell) { LoginDialog logger = Container.Resolve <LoginDialog>(); LabDbContext.LabDbEntities entities = new LabDbContext.LabDbEntities(); if (!entities.Database.Exists()) { Application.Current.Shutdown(); } if (logger.ShowDialog() == true) { AppDomain.CurrentDomain.SetThreadPrincipal(logger.AuthenticatedPrincipal); Application.Current.MainWindow = shell; LabDB2.Properties.Settings.Default.LastLogUser = logger.UserName; LabDB2.Properties.Settings.Default.Save(); Current.MainWindow.Show(); } else { Application.Current.Shutdown(); } }
internal static void RunInternal(bool showTipOfTheDay) { using (var login = new LoginDialog()) { login.Owner = Workbench.Instance; var result = login.ShowDialog(); if (showTipOfTheDay) { TipOfTheDayDialog.FirstTimeOpen(); } if (result == System.Windows.Forms.DialogResult.OK) { var conn = login.Connection; //TODO: Determine if this is a http connection. If not, //wrap it in an IServerConnection decorator that will do all the //request dispatch broadcasting. This will solve trac #1505 and will //work for any future non-http implementations var mgr = ServiceRegistry.GetService <ServerConnectionManager>(); Debug.Assert(mgr != null); // Connection display names should be unique. A duplicate means we are connecting to the same MG server LoggingService.Info("Connection created: " + conn.DisplayName); //NOXLATE if (mgr.GetConnection(conn.DisplayName) == null) { mgr.AddConnection(conn.DisplayName, conn); Workbench.Instance.ActiveSiteExplorer.FullRefresh(); } else { MessageService.ShowError(Strings.ConnectionAlreadyEstablished); } } } }
public override void Run() { var wb = Workbench.Instance; var svc = ServiceRegistry.GetService <ServerConnectionManager>(); var exp = wb.ActiveSiteExplorer; if (exp.SelectedItems.Length == 1 && !exp.SelectedItems[0].IsFolder) { var source = svc.GetConnection(exp.ConnectionName); var login = new LoginDialog(); if (login.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var target = login.Connection; var dlg = new MigrateDialog(source, target); dlg.ResourceID = exp.SelectedItems[0].ResourceId; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { DoMigrate(source, target, dlg.ResourceID, dlg.DependentResources, dlg.OverwriteExisting); MessageService.ShowMessage(string.Format(Strings.ResourceMigrated, exp.SelectedItems[0].ResourceId)); } } } }
public override void OnRegister() { if (InvokeRequired) { Invoke((MethodInvoker) delegate() { OnRegister(); }); return; } CoreSystem.CheckForIllegalCrossThreadCalls = false; LoginDialog.CheckForIllegalCrossThreadCalls = false; loginForm = new LoginDialog(); mainForm = new CoreSystem(); Core.RegisterMediator(loginForm); Core.RegisterMediator(mainForm); Core.RegisterCommand(DO_LOGIN, new DoLogin()); Core.RegisterCommand(DO_REGISTER, new DoRegister()); Core.RegisterCommand(DO_UPDATE_SITES, new DoUpdateSites()); Core.RegisterCommand(ASK_4_NEW_URL, new DoAskNextUrl()); Core.SendNotification(SHOW_LOGIN); NetworkManager.Start(); }
public static bool Logout() { bool noProblem = false; if (RUNNING_COPYS_COUNT > 0) { MessageBoxResult res = MessageBox.Show("Existen copias en curso. ¿Confirma que desea cancelarlas?", "Información", MessageBoxButton.YesNo); if (res == MessageBoxResult.Yes) { PHome._PHome.CancelRunningCopys(); noProblem = true; } } else { noProblem = true; } if (noProblem) { _current_user = null; copia_punto = null; MainWindow mw = Application.Current.Windows.OfType <MainWindow>().FirstOrDefault(); mw.Hide(); _loginDialog = new LoginDialog(); _loginDialog.Show(); mw.Close(); userLogged = false; } return(noProblem); // else // NavigationHelper.ToUri(NavigationCommands.PreviousPage); }
public InputKeyDialog(LoginDialog loginDialog) { _loginDialog = loginDialog; Index = 1080; Library = Libraries.Prguse; Location = new Point((Client.Settings.ScreenWidth - Size.Width) / 2 + 285, (Client.Settings.ScreenHeight - Size.Height) / 2 + 150); Visible = true; KeyEscButton = new MirButton { HoverIndex = 301, Index = 300, Library = Libraries.Title, Location = new Point(12, 12), Parent = this, PressedIndex = 302 }; KeyEscButton.Click += (o, e) => Dispose(); KeyDelButton = new MirButton { HoverIndex = 304, Index = 303, Library = Libraries.Title, Location = new Point(140, 76), Parent = this, PressedIndex = 305 }; KeyDelButton.Click += (o, e) => SecureKeyDelete(); KeyEnterButton = new MirButton { HoverIndex = 307, Index = 306, Library = Libraries.Title, Location = new Point(140, 236), Parent = this, PressedIndex = 308 }; KeyEnterButton.Click += (o, e) => { KeyPressEventArgs arg = new KeyPressEventArgs((char)Keys.Enter); _loginDialog.TextBox_KeyPress(o, arg); }; KeyRandButton = new MirButton { HoverIndex = 310, Index = 309, Library = Libraries.Title, Location = new Point(76, 236), Parent = this, PressedIndex = 311 }; KeyRandButton.Click += (o, e) => { _letters = new string(_letters.OrderBy(s => Guid.NewGuid()).ToArray()).ToCharArray(); _numbers = new string(_numbers.OrderBy(s => Guid.NewGuid()).ToArray()).ToCharArray(); UpdateKeys(); }; UpdateKeys(); }
private void LoginThread() { var context = new ERPDBModelContainer(); //Liberar apenas para teste //context.Database.ExecuteSqlCommand("TRUNCATE TABLE UsuarioSet_Administrador"); var query = context.UsuarioSet.OfType <Administrador>().ToList(); if (Controller.LoggedUser == null) { if (query.Count == 0) { Application.Current.Dispatcher.Invoke((Action)(() => { var dialog = new CreateAdminDialog(); foreach (Button b in GridButtons.Children) { b.IsEnabled = true; } LoadingGrid.Visibility = Visibility.Collapsed; Menu.IsEnabled = true; if (dialog.ShowDialog() == true) { Controller.LoggedUser = dialog.getAdmin; context.UsuarioSet.Add(Controller.LoggedUser); context.SaveChanges(); } })); } var valid = false; if (Controller.LoggedUser == null) { Application.Current.Dispatcher.Invoke((Action)(() => { foreach (Button b in GridButtons.Children) { b.IsEnabled = true; } LoadingGrid.Visibility = Visibility.Collapsed; Menu.IsEnabled = true; })); while (!valid) { Application.Current.Dispatcher.Invoke((Action)(() => { var dialog = new LoginDialog(); if (dialog.ShowDialog() == true) { var users = context.UsuarioSet.Where(u => u.Nome.ToLower() == dialog.getFuncionario.Nome.ToLower()).ToList(); foreach (Funcionario f in users) { if (f.Senha == dialog.getFuncionario.Senha) { Controller.LoggedUser = f; valid = true; } } } if (Controller.LoggedUser == null) { MessageBox.Show("Usuário Inválido", "Erro ao acessar"); } })); } } } else { context.UsuarioSet.Add(Controller.LoggedUser); context.SaveChanges(); Application.Current.Dispatcher.Invoke((Action)(() => { foreach (Button b in GridButtons.Children) { b.IsEnabled = true; } LoadingGrid.Visibility = Visibility.Collapsed; Menu.IsEnabled = true; })); } Application.Current.Dispatcher.Invoke((Action)(() => { TextBlockNomeUsuario.Text = Controller.LoggedUser.Nome; })); }
public delegate PublishView Factory(); //autofac uses this public PublishView(PublishModel model, SelectedTabChangedEvent selectedTabChangedEvent, LocalizationChangedEvent localizationChangedEvent, BookTransfer bookTransferrer, LoginDialog login, NavigationIsolator isolator, PublishToAndroidApi publishApi, PublishEpubApi publishEpubApi, BloomWebSocketServer webSocketServer) { _bookTransferrer = bookTransferrer; _loginDialog = login; _isolator = isolator; _publishApi = publishApi; _publishEpubApi = publishEpubApi; _webSocketServer = webSocketServer; InitializeComponent(); if (this.DesignMode) { return; } _model = model; _model.View = this; _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted); _pdfViewer.PrintProgress += new System.EventHandler <PdfPrintProgressEventArgs>(OnPrintProgress); // BL-625: With mono, if a RadioButton group has its AutoCheck properties set to true, the default RadioButton.OnEnter // event checks to make sure one of the RadioButtons is checked. If none are checked, the one the mouse pointer // is over is checked, causing the CheckChanged event to fire. if (SIL.PlatformUtilities.Platform.IsMono) { SetAutoCheck(false); } //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger //off the tab itself changing, either to us or away from us. selectedTabChangedEvent.Subscribe(c => { if (c.To == this) { Activate(); } else if (c.To != this) { Deactivate(); } }); //TODO: find a way to call this just once, at the right time: // DeskAnalytics.Track("Publish"); //#if DEBUG // var linkLabel = new LinkLabel() {Text = "DEBUG"}; // linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout()); // tableLayoutPanel1.Controls.Add(linkLabel); //#endif _menusToolStrip.BackColor = _layoutChoices.BackColor = tableLayoutPanel1.BackColor = Palette.GeneralBackground; if (SIL.PlatformUtilities.Platform.IsMono) { BackgroundColorsForLinux(); } // Adding this renderer prevents a white line from showing up under the components. _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer(); // As far as I can tell, this is not needed anymore, and its presence, // at least in this place in the code, causes errors when running command-line tools // like UploadCommand which needs a PublishView but must not have something fully initialized. //GeckoPreferences.Default["pdfjs.disabled"] = false; SetupLocalization(); localizationChangedEvent.Subscribe(o => { SetupLocalization(); UpdateLayoutChoiceLabels(); UpdateSaveButton(); }); // Make this extra box available to show when wanted. _previewBox = new PictureBox(); _previewBox.Visible = false; Controls.Add(_previewBox); _previewBox.BringToFront(); }
public void ShowConnectionDialog() { LoginDialog dialog = new LoginDialog(this); dialog.ShowDialog(); }
void Awake() { //Check if instance already exists if (Instance == null) { //if not, set instance to this Instance = this; LoadingGameSettings = true; LoadingPlayerSettings = true; LoadingHeroData = true; LoadingWorldData = true; // only time game state will be null is if in slapsh scene in which case I will // assign main menu as next in most case. in the case that it is not next, // I will let the Login dialog logic sort out what to do AddToSceneBreadCrumb(GameState.Constants.SCENE_START_MENU, GameState.Constants.START_MENU); } //If instance already exists and it's not this: else if (Instance != this) { //Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager. Destroy(gameObject); // allow this class to persist from scene-to-scene } DontDestroyOnLoad(gameObject); // gather all the game menus if (GameTitleInScene == null) { GameTitleInScene = Object.FindObjectOfType <GameTitle>(); } if (OptionsMenuInScene == null) { OptionsMenuInScene = Object.FindObjectOfType <OptionsMenu>(); } if (MainMenuInScene == null) { MainMenuInScene = Object.FindObjectOfType <MainMenu>(); } if (StartMenuInScene == null) { StartMenuInScene = Object.FindObjectOfType <StartMenu>(); } if (GameSettingsInScene == null) { GameSettingsInScene = Object.FindObjectOfType <GameSettings>(); } if (CharacterCustomizationInScene == null) { CharacterCustomizationInScene = Object.FindObjectOfType <CharacterCustomization>(); } if (SaveGameStateDialogInScene == null) { SaveGameStateDialogInScene = Object.FindObjectOfType <SaveGameStateDialog>(); } if (LoginDialogInScene == null) { LoginDialogInScene = Object.FindObjectOfType <LoginDialog>(); } if (CharacterSelectionInScene == null) { CharacterSelectionInScene = Object.FindObjectOfType <CharacterSelection>(); } if (LevelMenuInScene == null) { LevelMenuInScene = Object.FindObjectOfType <LevelMenu>(); } if (HUDMenuInScene == null) { HUDMenuInScene = Object.FindObjectOfType <HUDMenu>(); } }
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var shell = UiStarter.Start <IDockWindow>( new Bootstrap(), new UiShowStartWindowOptions { Title = "Kanban.Desktop", ToolPaneWidth = 100 }); AuthProcess.Start( getAuthenticationData: () => LoginDialog.GetAutenticationDataTask(), authentication: async(x) => { if (x == null) { return(false); } var authContext = shell.Container.Resolve <IAuthenticationContext>(); return(await authContext.LoginAsync(x.Username, x.Password)); }, authenticationSuccess: () => { shell.ShowView <ISettingsView>( options: new UiShowOptions { Title = "Settings" }); shell.ShowView <IKanbanBoardView>(); shell.ShowView <IKanbanBoardView>( new KanbanViewRequest { ConfigurtaionName = "h_status_v_assigned_c_subject_treker_details" }, new KanbanShowOptions { Title = "Kanban dynamic dimension", }); shell.ShowView <IKanbanBoardView>( new KanbanViewRequest { ConfigurtaionName = "ods" }, new KanbanShowOptions { Title = "ods", }); shell.ShowView <IIssueView>( new IssueViewRequest { IssueId = 4689 }); shell.ShowTool <IIssuesTool>(); }, authenticationFail: () => Current.MainWindow.Close()); }
public delegate PublishView Factory(); //autofac uses this public PublishView(PublishModel model, SelectedTabChangedEvent selectedTabChangedEvent, LocalizationChangedEvent localizationChangedEvent, BookTransfer bookTransferrer, LoginDialog login) { _bookTransferrer = bookTransferrer; _loginDialog = login; InitializeComponent(); if (this.DesignMode) { return; } _model = model; _model.View = this; _makePdfBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(_makePdfBackgroundWorker_RunWorkerCompleted); //NB: just triggering off "VisibilityChanged" was unreliable. So now we trigger //off the tab itself changing, either to us or away from us. selectedTabChangedEvent.Subscribe(c => { if (c.To == this) { Activate(); } else if (c.To != this && IsMakingPdf) { _makePdfBackgroundWorker.CancelAsync(); } }); //TODO: find a way to call this just once, at the right time: // DeskAnalytics.Track("Publish"); //#if DEBUG // var linkLabel = new LinkLabel() {Text = "DEBUG"}; // linkLabel.Click+=new EventHandler((x,y)=>_model.DebugCurrentPDFLayout()); // tableLayoutPanel1.Controls.Add(linkLabel); //#endif _menusToolStrip.Renderer = new EditingView.FixedToolStripRenderer(); GeckoPreferences.Default["pdfjs.disabled"] = false; SetupLocalization(); localizationChangedEvent.Subscribe(o => SetupLocalization()); }
protected override void Dispose(bool disposing) { if (disposing) { _background = null; Version = null; _login = null; _account = null; _password = null; _connectBox = null; } base.Dispose(disposing); }
public static void Main(string[] args) { System.Windows.Forms.Application.EnableVisualStyles(); System.Windows.Forms.Application.DoEvents(); PreferredSiteList.InitCulture(); //Init the Maestro connection registry with additional providers from ConnectionProviders.xml ConnectionProviderRegistry.InitRegistry(); //Parameters: //mapagent= //username= //password= //mapdefinition= //scaleindex=0,1,2,3,4,5 //basegroups="x","y" //extentoverride=minx,miny,maxx,maxy bool cmdLineMode = false; string mapdefinitions = string.Empty; string scaleindex = string.Empty; string basegroups = string.Empty; string limitRows = string.Empty; string limitCols = string.Empty; string tileWidth = string.Empty; string tileHeight = string.Empty; string DPI = string.Empty; string metersPerUnit = string.Empty; IEnvelope overrideExtents = null; List <string> largs = new List <string>(args); Dictionary <string, string> opts = CommandLineParser.ExtractOptions(largs); if (opts.ContainsKey(TileRunParameters.MAPDEFINITIONS)) { mapdefinitions = opts[TileRunParameters.MAPDEFINITIONS]; } if (opts.ContainsKey(TileRunParameters.SCALEINDEX)) { scaleindex = opts[TileRunParameters.SCALEINDEX]; } if (opts.ContainsKey(TileRunParameters.BASEGROUPS)) { basegroups = opts[TileRunParameters.BASEGROUPS]; } if (opts.ContainsKey(TileRunParameters.LIMITROWS)) { limitRows = opts[TileRunParameters.LIMITROWS]; } if (opts.ContainsKey(TileRunParameters.LIMITCOLS)) { limitCols = opts[TileRunParameters.LIMITCOLS]; } if (opts.ContainsKey(TileRunParameters.TILEWIDTH)) { tileWidth = opts[TileRunParameters.TILEWIDTH]; } if (opts.ContainsKey(TileRunParameters.TILEHEIGHT)) { tileHeight = opts[TileRunParameters.TILEHEIGHT]; } if (opts.ContainsKey(TileRunParameters.DOTSPERINCH)) { DPI = opts[TileRunParameters.DOTSPERINCH]; } if (opts.ContainsKey(TileRunParameters.METERSPERUNIT)) { metersPerUnit = opts[TileRunParameters.METERSPERUNIT]; } if (opts.ContainsKey(TileRunParameters.EXTENTOVERRIDE)) { string[] parts = opts[TileRunParameters.EXTENTOVERRIDE].Split(','); if (parts.Length == 4) { double minx; double miny; double maxx; double maxy; if ( double.TryParse(parts[0], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out minx) && double.TryParse(parts[1], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out miny) && double.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out maxx) && double.TryParse(parts[3], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out maxy) ) { overrideExtents = ObjectFactory.CreateEnvelope(minx, miny, maxx, maxy); } } } if (largs.IndexOf("batch") >= 0 || largs.IndexOf("/batch") >= 0 || largs.IndexOf("commandline") >= 0 || largs.IndexOf("/commandline") >= 0) { cmdLineMode = true; } try { Console.Clear(); m_loggableProgress = true; } catch { hasConsole = false; m_loggableProgress = false; } IServerConnection connection = null; string[] maps = mapdefinitions.Split(','); string username = string.Empty; string password = string.Empty; if (opts.ContainsKey(TileRunParameters.PROVIDER) && opts.ContainsKey(TileRunParameters.CONNECTIONPARAMS)) { var initP = ConnectionProviderRegistry.ParseConnectionString(opts[TileRunParameters.CONNECTIONPARAMS]); connection = ConnectionProviderRegistry.CreateConnection(opts[TileRunParameters.PROVIDER], initP); } else { if (cmdLineMode) { throw new ArgumentException(string.Format(Strings.MissingRequiredConnectionParameters, TileRunParameters.PROVIDER, TileRunParameters.CONNECTIONPARAMS)); } var frm = new LoginDialog(); if (frm.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return; } username = frm.Username; password = frm.Password; connection = frm.Connection; } if (connection == null) { if (opts.ContainsKey(TileRunParameters.PROVIDER) && opts.ContainsKey(TileRunParameters.CONNECTIONPARAMS)) { var initP = ConnectionProviderRegistry.ParseConnectionString(opts[TileRunParameters.CONNECTIONPARAMS]); connection = ConnectionProviderRegistry.CreateConnection(opts[TileRunParameters.PROVIDER], initP); } else { throw new ArgumentException(string.Format(Strings.MissingRequiredConnectionParameters, TileRunParameters.PROVIDER, TileRunParameters.CONNECTIONPARAMS)); } } if (!cmdLineMode) { SetupRun sr = null; if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { sr = new SetupRun(username, password, connection, maps, opts); } else { sr = new SetupRun(connection, maps, opts); } using (sr) { sr.ShowDialog(); return; } } TilingRunCollection bx = new TilingRunCollection(connection); int x; if (!string.IsNullOrEmpty(limitCols) && int.TryParse(limitCols, out x)) { bx.LimitCols(x); } if (!string.IsNullOrEmpty(limitRows) && int.TryParse(limitRows, out x)) { bx.LimitRows(x); } if (!string.IsNullOrEmpty(tileWidth) && int.TryParse(tileWidth, out x)) { bx.Config.TileWidth = x; } if (!string.IsNullOrEmpty(tileHeight) && int.TryParse(tileHeight, out x)) { bx.Config.TileHeight = x; } if (!string.IsNullOrEmpty(DPI) && int.TryParse(DPI, out x)) { bx.Config.DPI = x; } double d; if (!string.IsNullOrEmpty(metersPerUnit) && double.TryParse(metersPerUnit, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture, out d)) { bx.Config.MetersPerUnit = d; } if (opts.ContainsKey(TileRunParameters.RANDOMTILEORDER)) { bx.Config.RandomizeTileSequence = true; } if (opts.ContainsKey(TileRunParameters.THREADCOUNT) && int.TryParse(opts[TileRunParameters.THREADCOUNT], out x) && x > 0) { bx.Config.ThreadCount = x; } //Now that all global parameters are set, we can now add the map definitions bx.AddMapDefinitions(maps); //basegroups must be set in each mapdefinition if (!string.IsNullOrEmpty(basegroups)) { List <string> groups = new List <string>(); foreach (string s in basegroups.Split(',')) { string f = s; if (f.StartsWith("\"")) { f = f.Substring(1); } if (f.EndsWith("\"")) { f = f.Substring(0, f.Length - 1); } groups.Add(f); } bx.SetGroups(groups.ToArray()); } if (overrideExtents != null) { List <int> scales = new List <int>(); int tmp; foreach (string s in scaleindex.Split(',')) { if (int.TryParse(s, out tmp)) { scales.Add(tmp); } } foreach (MapTilingConfiguration bm in bx.Maps) { bm.SetScalesAndExtend(scales.ToArray(), overrideExtents); } } else if (!string.IsNullOrEmpty(scaleindex)) { List <int> scales = new List <int>(); int tmp; foreach (string s in scaleindex.Split(',')) { if (int.TryParse(s, out tmp)) { scales.Add(tmp); } } bx.SetScales(scales.ToArray()); } if (!cmdLineMode) { Progress pg = new Progress(bx); pg.ShowDialog(); } else { bx.BeginRenderingMap += OnBeginRenderingMap; bx.FinishRenderingMap += OnFinishRenderingMap; bx.BeginRenderingGroup += OnBeginRenderingGroup; bx.FinishRenderingGroup += OnFinishRenderingGroup; bx.BeginRenderingScale += OnBeginRenderingScale; bx.FinishRenderingScale += OnFinishRenderingScale; bx.BeginRenderingTile += OnBeginRenderingTile; bx.FinishRenderingTile += OnFinishRenderingTile; bx.FailedRenderingTile += OnFailedRenderingTile; mapCount = 0; lastUpdate = DateTime.Now; bx.RenderAll(); } }
public BloomLibraryPublishControl(PublishView parentView, BookTransfer bookTransferrer, LoginDialog login, Book.Book book) { _parentView = parentView; _bookTransferrer = bookTransferrer; _loginDialog = login; _book = book; InitializeComponent(); _originalLoginText = _loginLink.Text; // Before anything might modify it (but after InitializeComponent creates it). _titleLabel.Text = book.BookInfo.Title; _progressBox.ShowDetailsMenuItem = true; _progressBox.ShowCopyToClipboardMenuItem = true; _progressBox.LinkClicked += _progressBox_LinkClicked; var metadata = book.GetLicenseMetadata(); // This is usually redundant, but might not be on old books where the license was set before the new // editing code was written. book.SetMetadata(metadata); var license = metadata.License; if (license == null || (license is NullLicense && string.IsNullOrWhiteSpace(metadata.CopyrightNotice))) { // A null license and no copyright indicates they never even opened the ClearShare dialog to choose a license. _usingCcControls = false; _usingNotesLabel = false; _licenseSuggestion.Text = _pleaseSetThis; _okToUpload = false; } else if (license is CreativeCommonsLicense) { _creativeCommonsLink.Text = license.Token.ToUpperInvariant(); _usingNotesSuggestion = false; if (string.IsNullOrWhiteSpace(license.RightsStatement)) { _licenseNotesLabel.Hide(); } else { _licenseNotesLabel.Text = LocalizationManager.GetString("PublishTab.Upload.AdditionalRequests", "Additional Requests: ") + license.RightsStatement; } } else if (license is NullLicense) { _usingCcControls = false; _licenseNotesLabel.Text = LocalizationManager.GetString("PublishTab.Upload.AllReserved", "All rights reserved (Contact the Copyright holder for any permissions.)"); if (!string.IsNullOrWhiteSpace(license.RightsStatement)) { _licenseNotesLabel.Text += Environment.NewLine + license.RightsStatement; } _licenseSuggestion.Text = LocalizationManager.GetString("PublishTab.Upload.SuggestAssignCC", "Suggestion: Assigning a Creative Commons License makes it easy for you to clearly grant certain permissions to everyone."); } else { // So far, this means it must be custom license (with non-blank rights...actually, currently, the palaso dialog will not allow a custom license with no rights statement). _usingCcControls = false; _licenseNotesLabel.Text = license.RightsStatement; _licenseSuggestion.Text = LocalizationManager.GetString("PublishTab.Upload.SuggestChangeCC", "Suggestion: Creative Commons Licenses make it much easier for others to use your book, even if they aren't fluent in the language of your custom license."); } _copyrightLabel.Text = book.BookInfo.Copyright; var allLanguages = book.AllLanguages; var okToUploadWithNoLanguages = book.BookInfo.IsSuitableForMakingShells; foreach (var lang in allLanguages.Keys) { var checkBox = new CheckBox(); checkBox.Text = _book.PrettyPrintLanguage(lang); if (allLanguages[lang]) { checkBox.Checked = true; } else { checkBox.Text += @" " + LocalizationManager.GetString("PublishTab.Upload.IncompleteTranslation", "(incomplete translation)", "This is added after the language name, in order to indicate that some parts of the book have not been translated into this language yet."); } checkBox.Size = new Size(TextRenderer.MeasureText(checkBox.Text, checkBox.Font).Width + 50, checkBox.Height); checkBox.Tag = lang; checkBox.CheckStateChanged += delegate(object sender, EventArgs args) { bool someLangChecked = _languagesFlow.Controls.Cast <CheckBox>().Any(b => b.Checked); _langsLabel.ForeColor = someLangChecked || okToUploadWithNoLanguages ? Color.Black : Color.Red; if (_okToUploadDependsOnLangsChecked) { _okToUpload = someLangChecked || okToUploadWithNoLanguages; UpdateDisplay(); } }; _languagesFlow.Controls.Add(checkBox); } _creditsLabel.Text = book.BookInfo.Credits; _summaryBox.Text = book.BookInfo.Summary; try { _loginDialog.LogIn(); // See if saved credentials work. } catch (Exception e) { SIL.Reporting.ErrorReport.NotifyUserOfProblem(e, LocalizationManager.GetString("PublishTab.Upload.LoginFailure", "Bloom could not log in to BloomLibrary.org using your saved credentials. Please check your network connection.")); } _optional1.Left = _summaryBox.Right - _optional1.Width; // right-align these (even if localization changes their width) // Copyright info is not required if the book has been put in the public domain if (!license.Url.StartsWith("http://creativecommons.org/publicdomain/zero/")) { RequireValue(_copyrightLabel); } RequireValue(_titleLabel); if (BookTransfer.UseSandbox) { var oldTextWidth = TextRenderer.MeasureText(_uploadButton.Text, _uploadButton.Font).Width; _uploadButton.Text = LocalizationManager.GetString("PublishTab.Upload.UploadSandbox", "Upload Book (to Sandbox)"); var neededWidth = TextRenderer.MeasureText(_uploadButton.Text, _uploadButton.Font).Width; _uploadButton.Width += neededWidth - oldTextWidth; } // After considering all the factors except whether any languages are selected, // if we can upload at this point, whether we can from here on depends on whether one is checked. // This test needs to come after evaluating everything else uploading depends on (except login) _okToUploadDependsOnLangsChecked = _okToUpload; if (!allLanguages.Keys.Any()) { _langsLabel.Text += " " + LocalizationManager.GetString("PublishTab.Upload.NoLangsFound", "(None found)"); if (!okToUploadWithNoLanguages) { _langsLabel.ForeColor = Color.Red; _okToUpload = false; } } }
protected void onLoginActionClicked(object sender, EventArgs e) { LoginDialog dialog = new LoginDialog(); dialog.Show(); }
public EchoBot(ConversationState conversationState, LoginDialog loginDialog) { _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState)); _loginDialog = loginDialog ?? throw new ArgumentNullException(nameof(loginDialog)); }
public BloomLibraryPublishControl(PublishView parentView, BookTransfer bookTransferrer, LoginDialog login, Book.Book book) { _parentView = parentView; _bookTransferrer = bookTransferrer; _loginDialog = login; _book = book; InitializeComponent(); _originalLoginText = _loginLink.Text; // Before anything might modify it (but after InitializeComponent creates it). _titleLabel.Text = book.BookInfo.Title; _progressBox.ShowDetailsMenuItem = true; _progressBox.ShowCopyToClipboardMenuItem = true; _progressBox.LinkClicked += _progressBox_LinkClicked; var metadata = book.GetLicenseMetadata(); // This is usually redundant, but might not be on old books where the license was set before the new // editing code was written. book.UpdateLicenseMetdata(metadata); var license = metadata.License; if (license == null || (license is NullLicense && string.IsNullOrWhiteSpace(metadata.CopyrightNotice))) { // A null license and no copyright indicates they never even opened the ClearShare dialog to choose a license. _usingCcControls = false; _usingNotesLabel = false; _licenseSuggestion.Text = _pleaseSetThis; _okToUpload = false; } else if (license is CreativeCommonsLicense) { _creativeCommonsLink.Text = license.Token.ToUpperInvariant(); _usingNotesSuggestion = false; if (string.IsNullOrWhiteSpace(license.RightsStatement)) { _licenseNotesLabel.Hide(); } else { _licenseNotesLabel.Text = LocalizationManager.GetString("PublishTab.Upload.AdditionalRequests", "AdditionalRequests: ") + license.RightsStatement; } } else if (license is NullLicense) { _usingCcControls = false; _licenseNotesLabel.Text = LocalizationManager.GetString("PublishTab.Upload.AllReserved", "All rights reserved (Contact the Copyright holder for any permissions.)"); if (!string.IsNullOrWhiteSpace(license.RightsStatement)) { _licenseNotesLabel.Text += Environment.NewLine + license.RightsStatement; } _licenseSuggestion.Text = LocalizationManager.GetString("PublishTab.Upload.SuggestAssignCC", "Suggestion: Assigning a Creative Commons License makes it easy for you to clearly grant certain permissions to everyone."); } else { // So far, this means it must be custom license (with non-blank rights...actually, currently, the palaso dialog will not allow a custom license with no rights statement). _usingCcControls = false; _licenseNotesLabel.Text = license.RightsStatement; _licenseSuggestion.Text = LocalizationManager.GetString("PublishTab.Upload.SuggestChangeCC", "Suggestion: Creative Commons Licenses make it much easier for others to use your book, even if they aren't fluent in the language of your custom license."); } _copyrightLabel.Text = book.BookInfo.Copyright; _languagesLabel.Text = string.Join(", ", book.AllLanguages.Select(lang => _book.PrettyPrintLanguage(lang)).ToArray()); _creditsLabel.Text = book.BookInfo.Credits; _summaryBox.Text = book.BookInfo.Summary; try { _loginDialog.LogIn(); // See if saved credentials work. } catch (Exception e) { Palaso.Reporting.ErrorReport.NotifyUserOfProblem(e, LocalizationManager.GetString("PublishTab.Upload.LoginFailure", "Bloom could not log in to BloomLibrary.org using your saved credentials. Please check your network connection.")); } _optional1.Left = _summaryBox.Right - _optional1.Width; // right-align these (even if localization changes their width) RequireValue(_copyrightLabel); RequireValue(_titleLabel); RequireValue(_languagesLabel); if (BookTransfer.UseSandbox) { var oldTextWidth = TextRenderer.MeasureText(_uploadButton.Text, _uploadButton.Font).Width; _uploadButton.Text = LocalizationManager.GetString("PublishTab.Upload.UploadSandbox", "Upload Book (to Sandbox)"); var neededWidth = TextRenderer.MeasureText(_uploadButton.Text, _uploadButton.Font).Width; _uploadButton.Width += neededWidth - oldTextWidth; } }
public static void Login() { if (CurrentUser.currentUser != null) { return; } var dialog = new LoginDialog(); if ((bool)dialog.ShowDialog()) { var userLogin = database.Users.FirstOrDefault(u => u.Username == dialog.username.Text.ToLower()); //Handle User Not Found if (userLogin == null) { new LoginStatusMessageDialog("User Not Found").ShowDialog(); return; } //Handle Account Disabled if ((userLogin.AccountStatus & AccountStatus.AccountDisabled) == AccountStatus.AccountDisabled) { new LoginStatusMessageDialog("Account Disabled").ShowDialog(); return; } //Handle Account Locked if ((userLogin.AccountStatus & AccountStatus.AccountLocked) == AccountStatus.AccountLocked) { if (DateTime.Now - userLogin.AccountLocked > TimeSpan.FromMinutes(ACCOUNT_RESET_TIMESPAN)) { userLogin.AccountStatus ^= AccountStatus.AccountLocked; userLogin.FailedLoginCounter = 0; database.UserLog.Add(new UserLogEvent() { Timestamp = DateTime.Now, User = userLogin, UserEvent = UserEvents.AccountUnlocked }); } else { new LoginStatusMessageDialog("Account Locked").ShowDialog(); return; } } //Validate Password if (!userLogin.Password.SequenceEqual(PasswordHasher.HashPassword(dialog.Username, dialog.Password))) { new LoginStatusMessageDialog("Password Incorrect").ShowDialog(); database.UserLog.Add(new UserLogEvent() { Timestamp = DateTime.Now, User = userLogin, UserEvent = UserEvents.FailedLogin }); userLogin.FailedLoginCounter++; if (userLogin.FailedLoginCounter > 5) { userLogin.AccountStatus |= AccountStatus.AccountLocked; database.UserLog.Add(new UserLogEvent() { Timestamp = DateTime.Now, User = userLogin, UserEvent = UserEvents.AccountLocked }); } return; } //Handle Change Password while ((userLogin.AccountStatus & AccountStatus.UserMustChangePassword) == AccountStatus.UserMustChangePassword) { var changePasswordDialog = new UserMustChangePasswordDialog(); changePasswordDialog.ShowDialog(); if (PasswordHasher.HashPassword(userLogin.Username, changePasswordDialog.OldPassword).SequenceEqual(userLogin.Password)) { userLogin.Password = PasswordHasher.HashPassword(userLogin.Username, changePasswordDialog.NewPassword); userLogin.AccountStatus ^= AccountStatus.UserMustChangePassword; database.UserLog.Add(new UserLogEvent() { Timestamp = DateTime.Now, User = userLogin, UserEvent = UserEvents.PasswordChanged }); Save(); } else { new LoginStatusMessageDialog("Password Incorrect").ShowDialog(); } } //Login Success! Reset counters, log event and set current user. userLogin.FailedLoginCounter = 0; database.UserLog.Add(new UserLogEvent() { Timestamp = DateTime.Now, User = userLogin, UserEvent = UserEvents.UserLogin }); CurrentUser.SetCurrentUser(userLogin); } }
private void LoginItem_Click(object sender, RoutedEventArgs e) { LoginDialog logDialog = new LoginDialog(); logDialog.ShowDialog(); if (logDialog.Online) { BitmapImage bitmap = new BitmapImage(new Uri("Resources\\greendot.png", UriKind.Relative)); OnlineImage.Source = bitmap; ChangeActiveButtons(true); menuItemLogin.Header = "Log out"; menuItemLogin.Click -= LoginItem_Click; menuItemLogin.Click += new RoutedEventHandler(LogoutItem_Click); } }
public static void NewAccount(NewAccount P) { NewAccountDialog.ConfirmButton.Enabled = true; switch (P.Result) { case 0: SceneFunctions.ShowMessage("An error occured whilst creating the account."); NewAccountDialog.Hide(); NewAccountDialog.Clear(); LoginDialog.Show(); break; case 1: SceneFunctions.ShowMessage("Account creation is currently disabled."); NewAccountDialog.Hide(); NewAccountDialog.Clear(); LoginDialog.Show(); break; case 2: SceneFunctions.ShowMessage("Your AccountID is not acceptable."); NewAccountDialog.AccountIDTextBox.SetFocus(); break; case 3: SceneFunctions.ShowMessage("Your Password is not acceptable."); NewAccountDialog.Password1TextBox.SetFocus(); break; case 4: SceneFunctions.ShowMessage("Your E-Mail Address is not acceptable."); NewAccountDialog.EMailTextBox.SetFocus(); break; case 5: SceneFunctions.ShowMessage("Your User Name is not acceptable."); NewAccountDialog.UserNameTextBox.SetFocus(); break; case 6: SceneFunctions.ShowMessage("Your Secret Question is not acceptable."); NewAccountDialog.QuestionTextBox.SetFocus(); break; case 7: SceneFunctions.ShowMessage("Your Secret Answer is not acceptable."); NewAccountDialog.AnswerTextBox.SetFocus(); break; case 8: SceneFunctions.ShowMessage("An Account with this ID already exists."); NewAccountDialog.AccountIDTextBox.SetFocus(); NewAccountDialog.AccountIDTextBox.Text = string.Empty; break; case 9: SceneFunctions.ShowMessage("Your account was created successfully."); NewAccountDialog.Hide(); NewAccountDialog.Clear(); LoginDialog.Show(); break; #if DEBUG default: throw new NotImplementedException(); #endif } }
public bool? ShowDialog() { _dlg = new LoginDialog(this); return _dlg.ShowDialog(); }
public static async Task Run(string[] paramStrings) { try { var splash = new FrmInternalSplash(); splash.Show(); System.Windows.Forms.Application.DoEvents(); Info("Starting up Discord Media Loader application..."); var useTrace = false; #if DEBUG //temporary add debug log level if debugging... GlobalLogLevel |= LogLevel.Debug; Debug("Running in debug configuartion. Added log level debug."); #endif Debug($"Parameters: {string.Join(", ", paramStrings)}"); if (paramStrings.Contains("--trace") || paramStrings.Contains("-t")) { useTrace = true; GlobalLogLevel |= LogLevel.Trace; Trace("Trace parameter found. Added log level trace."); } Debug($"Application data folder: {DataDirectory}"); Trace("Checking application data folder..."); if (!Directory.Exists(DataDirectory)) { Debug("Creating application data folder..."); Directory.CreateDirectory(DataDirectory); Trace("Creating application data folder."); } Trace("Initializing profile optimizations..."); ProfileOptimization.SetProfileRoot(System.Windows.Forms.Application.UserAppDataPath); ProfileOptimization.StartProfile("profile.opt"); Trace("Finished initializing profile optimizations."); Trace("Trying to identify log memory..."); var logMemory = DefaultLogMemory as ArchivableConsoleLogMemory; if (logMemory != null) { var logFolder = Path.Combine(DataDirectory, "logs"); if (!Directory.Exists(logFolder)) { Debug("Creating log folder..."); Directory.CreateDirectory(logFolder); Trace("Created log folder."); } var logFile = Path.Combine(logFolder, SweetUtils.LegalizeFilename($"{DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern)}.log.zip")); Trace($"Setting log file: {logFile}"); logMemory.AutoArchiveOnDispose = true; logMemory.ArchiveFile = logFile; } Debug("Loading database..."); Database = new LiteDatabase(Path.Combine(DataDirectory, "config.db")); Database.Log.Logging += (message) => Trace($"LiteDB: {message}"); Debug("Loading settings collection out of database..."); var settingsDB = Database.GetCollection <Settings>("settings"); if (settingsDB.Count() > 1) { Warn("Found more than one setting. Loading first one..."); } Settings = settingsDB.FindAll().FirstOrDefault(); if (Settings == null) { Warn("Settings not found. Creating new one. This is normal on first start up..."); Settings = new Settings(); Settings.Store(); } Debug("Loading jobs collection out of database..."); Scheduler.JobList = Job.RestoreJobs().ToList(); Info("Loaded settings."); Debug( $"Settings: Email: {Settings.Email}, password: {(string.IsNullOrEmpty(Settings.Password) ? "not set" : "is set")}, use username: {Settings.UseUserData}, loginToken: {Settings.LoginToken}"); Trace("Updating log level..."); GlobalLogLevel = Settings.ApplicactionLogLevel; #if DEBUG //temporary add debug log level if debugging... GlobalLogLevel |= LogLevel.Debug; Debug("Running in debug configuartion. Added log level debug."); #endif if (useTrace) { GlobalLogLevel |= LogLevel.Trace; Trace("Creating application data folder."); } Debug("Creating discord client..."); Client = new DiscordSocketClient(); Client.Log += (arg) => { var logMessage = $"DiscordClient: {arg.Message}"; switch (arg.Severity) { case LogSeverity.Verbose: Trace(logMessage); break; case LogSeverity.Debug: Trace(logMessage); break; case LogSeverity.Info: Info(logMessage); break; case LogSeverity.Warning: Warn(logMessage); break; case LogSeverity.Error: Error(logMessage); break; } return(Task.CompletedTask); }; Info("Trying to log into discord..."); var abort = false; Client.Connected += Client_Connected; while (Client.LoginState != LoginState.LoggedIn && !abort) { Debug(Client.ConnectionState.ToString()); Debug(Client.LoginState.ToString()); Trace("Entering login loop."); try { if (Client.ConnectionState == ConnectionState.Connecting) { continue; } if (!string.IsNullOrEmpty(Settings.LoginToken)) { Debug("Trying to login with last known token..."); await Client.LoginAsync(TokenType.User, Settings.LoginToken); await Task.Delay(1000); } } catch (HttpException ex) { Warn($"Login seems to have failed or gone wrong: {ex.GetType().Name} - {ex.Message}"); } if (Client.LoginState == LoginState.LoggedOut) { Settings.Password = string.Empty; Debug("Showing dialog for username and password..."); var loginDlg = new LoginDialog(); loginDlg.ShowDialog(); Trace("Dialog closed."); } } Debug("Start checking for invalid jobs..."); //Client while (Client.Guilds.Count == 0) { // wait until guilds are loaded } for (var i = Scheduler.JobList.Count - 1; i >= 0; i--) { var job = Scheduler.JobList[i]; var isError = false; var guild = FindServerById(job.GuildId); if (guild == null) { isError = true; } else { var channel = FindChannelById(guild, job.ChannelId); if (channel == null) { isError = true; } } if (isError) { MessageBox.Show($"Invalid job for guild {job.GuildId}, channel {job.ChannelId} found. Guild or channel may not exist any more. This job will be deleted...", "Invalid job", MessageBoxButtons.OK, MessageBoxIcon.Warning); Scheduler.JobList.Remove(job); Scheduler.RunningJobs.Remove(job.Id); job.Stop(); job.Delete(); } } splash.Close(); Info("Starting scheduler..."); Scheduler.Start(); System.Windows.Forms.Application.Run(new MainForm()); Info("Stopping scheduler..."); Scheduler.Stop(); } catch (Exception ex) { Error($"{ex.Message} occured at: {ex.StackTrace}"); } }
public LoginScene() { SoundManager.PlaySound(SoundList.IntroMusic, true); Disposing += (o, e) => SoundManager.StopSound(SoundList.IntroMusic); _background = new MirAnimatedControl { Animated = false, AnimationCount = 19, AnimationDelay = 100, Index = 0, Library = Libraries.ChrSel, Loop = false, Parent = this, }; _login = new LoginDialog {Parent = _background, Visible = false}; _login.AccountButton.Click += (o, e) => { _login.Hide(); if(_ViewKey != null && !_ViewKey.IsDisposed) _ViewKey.Dispose(); _account = new NewAccountDialog { Parent = _background }; _account.Disposing += (o1, e1) => _login.Show(); }; _login.PassButton.Click += (o, e) => { _login.Hide(); if (_ViewKey != null && !_ViewKey.IsDisposed) _ViewKey.Dispose(); _password = new ChangePasswordDialog { Parent = _background }; _password.Disposing += (o1, e1) => _login.Show(); }; _login.ViewKeyButton.Click += (o, e) => //ADD { if (_ViewKey != null && !_ViewKey.IsDisposed) return; _ViewKey = new InputKeyDialog(_login) { Parent = _background }; }; Version = new MirLabel { AutoSize = true, BackColour = Color.FromArgb(200, 50, 50, 50), Border = true, BorderColour = Color.Black, Location = new Point(5, 580), Parent = _background, Text = string.Format("Version: {0}", Application.ProductVersion), }; //ViolenceLabel = new MirImageControl //{ // Index = 89, // Library = Libraries.Prguse, // Parent = this, // Location = new Point(471, 10) //}; //MinorLabel = new MirImageControl //{ // Index = 87, // Library = Libraries.Prguse, // Parent = this, // Location = new Point(578, 10) //}; //YouthLabel = new MirImageControl //{ // Index = 88, // Library = Libraries.Prguse, // Parent = this, // Location = new Point(684, 10) //}; _connectBox = new MirMessageBox("Attempting to connect to the server.", MirMessageBoxButtons.Cancel); _connectBox.CancelButton.Click += (o, e) => Program.Form.Close(); Shown += (sender, args) => { Network.Connect(); _connectBox.Show(); }; }
public void Login() { LoginDialog login = new LoginDialog (); var saved = GetSavedCredentials(); try { if (saved != null) { login.Username = saved.AutoLoginUser; var savedCreds = saved.Credentials.Where(x => x.UserName == saved.AutoLoginUser).FirstOrDefault(); if (savedCreds != null) { login.Password = savedCreds.Password; login.RememberCredentials = true; } } while (true) { int response = login.Run (); if (response == (int)Gtk.ResponseType.Ok) { var auth = new MinecraftAuthentication (); string message = "Invalid login!"; try { Session = auth.Login (login.Username, login.Password); } catch (Exception e) { Session = null; message = e.Message; } if (Session == null || Session.AccessToken == null) { DedicatedLauncher.MessageBox (message); continue; } break; } else if (response == (int)Gtk.ResponseType.Cancel) { throw new CancelException(); } } saved = new SavedCredentials() { AutoLoginUser = login.Username, Credentials = new List<SavedCredential>() }; if (login.RememberCredentials) { saved.Credentials = new List<SavedCredential>() { new SavedCredential() { UserName = login.Username, Password = login.Password } }; } Directory.CreateDirectory(System.IO.Path.GetDirectoryName(SavedCredentialsFile)); using (StreamWriter sw = new StreamWriter(SavedCredentialsFile)) sw.Write(saved.ToJson()); login.Hide (); login.Destroy(); usernameLabel.Markup = string.Format ("Playing as <b>{0}</b>", Session.Username); } finally { login.Destroy(); } }
/// <summary> /// Displays login dialog. /// </summary> /// <param name="onOK">Function to execute when user clicks OK.</param> /// <param name="onCancel">Function to execute when user clicks cancel. /// If you pass null here, then nothing will happen when the user /// clicks cancel.</param> public void DisplayLoginDialog( Action onOK, Action onCancel ) { if( IsModalDialogAlreadyDisplaying == false ) { // Create the login dialog, passing references to // the functions that are to be executed when the // user clicks ok, and when the user clicks cancel loginDialog = new LoginDialog( game, gui, onOK, onCancel ); // Now show it, as a MODAL dialog (meaning that // no other GUI elements will be displayed as long // as this one hasn't been dismissed yet) loginDialog.Show( true ); } }
private void OnGetTagFromFingerprint(object sender, EventArgs args) { active = true; Source source = ServiceManager.SourceManager.ActiveSource; UserJob job = new UserJob(AddinManager.CurrentLocalizer.GetString("Getting sound fingerprint")); job.SetResources(Resource.Cpu, Resource.Disk, Resource.Database); job.PriorityHints = PriorityHints.SpeedSensitive; job.Status = AddinManager.CurrentLocalizer.GetString("Scanning..."); job.IconNames = new string [] { "system-search", "gtk-find" }; job.CanCancel = true; job.CancelRequested += HandleJobCancelRequested; job.Register(); if (account == null) { account = new LastfmAccount(); LoginDialog dialog = new LoginDialog(account, true); dialog.Run(); dialog.Destroy(); } //comment the timeout system for TOS because still have issue and not seems to be linked... //System.DateTime start = System.DateTime.MinValue; ThreadPool.QueueUserWorkItem(delegate { try { var selection = ((ITrackModelSource)source).TrackModel.Selection; int total = selection.Count; int count = 0; foreach (TrackInfo track in ((ITrackModelSource)source).TrackModel.SelectedItems) { if (!active) { break; } if (String.IsNullOrEmpty(track.Uri.AbsolutePath)) { continue; } ad = new AudioDecoder((int)track.Duration.TotalSeconds); //respect last fm term of service : //You will not make more than 5 requests per originating IP address per second, averaged over a 5 minute period // 2 requests are done on each loop ==> time allowed by loop : 400ms /*if (start != System.DateTime.MinValue) { * TimeSpan span = System.DateTime.Now - start; * if (lastFmTOSMinTimeout > span) * Thread.Sleep (lastFmTOSMinTimeout - span); * } * start = DateTime.Now; */ byte[] fingerprint = ad.Decode(track.Uri.AbsolutePath); FingerprintRequest request = new FingerprintRequest(); request.Send(track, fingerprint, account); int fpid = request.GetFpId(); //force GC to dispose ad = null; Log.DebugFormat("Last.fm fingerprint id for {0} is {1}", track.TrackTitle, fpid); if (fpid > 0) { FetchMetadata(track, fpid); } else { Log.WarningFormat("Could not find fingerprint id for the track {0} !", track.TrackTitle); } job.Progress = (double)++count / (double)total; } } catch (Exception e) { account = null; Log.Exception(e); } finally { job.Finish(); } }); }
public static async Task Run(string[] paramStrings) { try { var splash = new FrmInternalSplash(); splash.Show(); System.Windows.Forms.Application.DoEvents(); Logger.Info("Starting up Discord Media Loader application..."); var useTrace = false; #if DEBUG //temporary add debug log level if debugging... Logger.GlobalLogLevel |= LogLevel.Debug; Logger.Debug("Running in debug configuartion. Added log level debug."); #endif Logger.Debug($"Parameters: {string.Join(", ", paramStrings)}"); if (paramStrings.Contains("--trace") || paramStrings.Contains("-t")) { useTrace = true; Logger.GlobalLogLevel |= LogLevel.Trace; Logger.Trace("Trace parameter found. Added log level trace."); } Logger.Debug($"Application data folder: {DataDirectory}"); Logger.Trace("Checking application data folder..."); if (!Directory.Exists(DataDirectory)) { Logger.Debug("Creating application data folder..."); Directory.CreateDirectory(DataDirectory); Logger.Trace("Creating application data folder."); } Logger.Trace("Initializing profile optimizations..."); ProfileOptimization.SetProfileRoot(System.Windows.Forms.Application.UserAppDataPath); ProfileOptimization.StartProfile("profile.opt"); Logger.Trace("Finished initializing profile optimizations."); Logger.Trace("Trying to identify log memory..."); var logMemory = Logger.DefaultLogMemory as ArchivableConsoleLogMemory; if (logMemory != null) { var logFolder = Path.Combine(DataDirectory, "logs"); if (!Directory.Exists(logFolder)) { Logger.Debug("Creating log folder..."); Directory.CreateDirectory(logFolder); Logger.Trace("Created log folder."); } var logFile = Path.Combine(logFolder, SweetUtils.LegalizeFilename($"{DateTime.Now.ToString(CultureInfo.CurrentCulture.DateTimeFormat.SortableDateTimePattern)}.log.zip")); Logger.Trace($"Setting log file: {logFile}"); logMemory.AutoArchiveOnDispose = true; logMemory.ArchiveFile = logFile; } Logger.Debug("Loading database..."); Database = new LiteDatabase(Path.Combine(DataDirectory, "config.db")); Database.Log.Logging += (message) => Logger.Trace($"LiteDB: {message}"); Logger.Debug("Loading settings collection out of database..."); var settingsDB = Database.GetCollection <Settings>("settings"); if (settingsDB.Count() > 1) { Logger.Warn("Found more than one setting. Loading first one..."); } Settings = settingsDB.FindAll().FirstOrDefault(); if (Settings == null) { Logger.Warn("Settings not found. Creating new one. This is normal on first start up..."); Settings = new Settings(); Settings.Store(); } if (Settings.ShowStartUpHints) { if (MessageBox.Show(splash, "This tool is considered as a selfbot which may violate the Discord TOS. By using this tool you take the risk to get your account banned. Although this never happened yet (as far as I know) you have to confirm to this.\n\r\n\rDo you wish to continue?", "HOLD UP!!", MessageBoxButtons.YesNo) != DialogResult.Yes) { splash.Close(); return; } Settings.ShowStartUpHints = false; Settings.Store(); } Logger.Debug("Loading jobs collection out of database..."); Scheduler.JobList = Job.RestoreJobs().ToList(); Logger.Info("Loaded settings."); Logger.Debug( $"Settings: Email: {Settings.Email}, password: {(string.IsNullOrEmpty(Settings.Password) ? "not set" : "is set")}, use username: {Settings.UseUserData}, loginToken: {Settings.LoginToken}"); Logger.Trace("Updating log level..."); Logger.GlobalLogLevel = Settings.ApplicactionLogLevel; #if DEBUG //temporary add debug log level if debugging... Logger.GlobalLogLevel |= LogLevel.Debug; Logger.Debug("Running in debug configuartion. Added log level debug."); #endif if (useTrace) { Logger.GlobalLogLevel |= LogLevel.Trace; Logger.Trace("Creating application data folder."); } Logger.Debug("Creating discord client..."); var config = new DiscordSocketConfig() { DefaultRetryMode = RetryMode.AlwaysRetry, }; //Client = new DiscordSocketClient(config); DMLClient.Client.Log += (arg) => { var logMessage = $"DiscordClient: {arg.Message}"; switch (arg.Severity) { case LogSeverity.Verbose: Logger.Trace(logMessage); break; case LogSeverity.Debug: Logger.Trace(logMessage); break; case LogSeverity.Info: Logger.Info(logMessage); break; case LogSeverity.Warning: Logger.Warn(logMessage); break; case LogSeverity.Error: Logger.Error(logMessage); break; } return(Task.CompletedTask); }; Logger.Info("Trying to log into discord..."); DMLClient.Client.Connected += Client_Connected; var loggedIn = false; while (!loggedIn) { try { if (!string.IsNullOrEmpty(Settings.LoginToken)) { Logger.Debug("Trying to login with last known token..."); loggedIn = await DMLClient.Login(Settings.LoginToken); } } catch (HttpException) { Logger.Warn("HTTPException occured during login. Probably from login token."); } if (!loggedIn) { Logger.Debug("Showing dialog for username and password..."); var loginDlg = new LoginDialog(); if (loginDlg.ShowDialog() != DialogResult.OK) { return; } } } Logger.Debug("Start checking for invalid jobs..."); //Client while (DMLClient.Client.Guilds.Count == 0) { // wait until guilds are loaded } for (var i = Scheduler.JobList.Count - 1; i >= 0; i--) { var job = Scheduler.JobList[i]; var isError = false; var guild = FindServerById(job.GuildId); if (guild == null) { isError = true; } else { var channel = FindChannelById(guild, job.ChannelId); if (channel == null) { isError = true; } } if (isError) { MessageBox.Show($"Invalid job for guild {job.GuildId}, channel {job.ChannelId} found. Guild or channel may not exist any more. This job will be deleted...", "Invalid job", MessageBoxButtons.OK, MessageBoxIcon.Warning); Scheduler.JobList.Remove(job); Scheduler.RunningJobs.Remove(job.Id); job.Stop(); job.Delete(); } } splash.Close(); Logger.Info("Starting scheduler..."); Scheduler.Start(); System.Windows.Forms.Application.Run(new MainForm()); Logger.Info("Stopping scheduler..."); Scheduler.Stop(); } catch (Exception ex) { Logger.Error($"{ex.Message} [{ex.GetType().Name}] occured at: {ex.StackTrace}"); if (MessageBox.Show($"An error occured while running Discord Media Loader:\n{ex.GetType().Name}: {ex.Message}\n\nDo you aggree to sending the error report to the creator of the tool?", "Discord Media Loader", MessageBoxButtons.YesNo) == DialogResult.Yes) { Raven.Capture(new SentryEvent(ex)); } } }
private void OnLogin( object o, EventArgs args ) { LoginDialog dlg = new LoginDialog( MainWindow ); switch( (ResponseType)dlg.Run() ) { case ResponseType.Ok: ThreadPool.QueueUserWorkItem( new WaitCallback(LoginThread), new string [] { dlg.Username, dlg.Password } ); break; default: break; } dlg.Destroy(); }