protected void continueButton_Click(object sender, EventArgs e)
        {
            SqlConnection connection = MarinaDBConnnection.GetConnection();
            string        sql        = "SELECT * FROM Customer WHERE UserName = @UserName";
            SqlCommand    command    = new SqlCommand(sql, connection);

            command.Parameters.AddWithValue("@UserName", userNameTextBox.Text);
            SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

            if (reader.HasRows == false)
            {
                passwordInvalidLabel.Text = "Username does not exist!";
            }
            else
            {
                while (reader.Read())
                {
                    string decryptedPwd = LoginUtility.GetDecryptedValue(reader["Password"].ToString());

                    if (passwordTextBox.Text == decryptedPwd)
                    {
                        //Create a session
                        Session["UserName"] = reader["ID"].ToString();
                        //Assign customer id to the session
                        Response.Redirect("Lease.aspx");
                    }
                    else
                    {
                        passwordInvalidLabel.Text = "Password is invalid";
                    }
                }
            }
        }
示例#2
0
        public async Task <IActionResult> Logout(LogoutInputModel model)
        {
            // build a model so the logged out page knows what to display
            var vm = await LoginUtility.BuildLoggedOutViewModelAsync(model.LogoutId, _interaction, User, HttpContext);

            if (User?.Identity.IsAuthenticated == true)
            {
                // delete local authentication cookie
                await HttpContext.SignOutAsync();

                // raise the logout event
                await _events.RaiseAsync(new UserLogoutSuccessEvent(User.GetSubjectId(), User.GetDisplayName()));
            }

            // check if we need to trigger sign-out at an upstream identity provider
            if (vm.TriggerExternalSignout)
            {
                // build a return URL so the upstream provider will redirect back
                // to us after the user has logged out. this allows us to then
                // complete our single sign-out processing.
                string url = Url.Action("Logout", new { logoutId = vm.LogoutId });

                // this triggers a redirect to the external provider for sign-out
                return(SignOut(new AuthenticationProperties {
                    RedirectUri = url
                }, vm.ExternalAuthenticationScheme));
            }

            //return View("LoggedOut", vm);
            return(Redirect(vm.PostLogoutRedirectUri));
        }
示例#3
0
        void PerformRefreshList()
        {
            LoginUtility.RequestFullLicenseInfo();
            Thread.Sleep(500);

            UpdateList();

            Thread thread1 = new Thread(ThreadGetStoreItems);

            thread1.Start();
        }
示例#4
0
        public IActionResult Contact()
        {
            // Ensures that the user is logged in and if not redirects to the login page
            if (!LoginUtility.CheckAuthenticated(HttpContext.Session))
            {
                return(RedirectToAction("Index", "Login"));
            }

            ViewData["Message"] = "Address";

            return(View());
        }
示例#5
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            //This is for Skipping auth if needed
            if (actionContext.ActionDescriptor.GetCustomAttributes <SkipAuthFilterAttribute>().Any())
            {
                return;
            }

            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response);
            }
            else
            {
                UserTokenDTO loginUser = null;
                try
                {
                    //Gets token key from header
                    var tokenKey = actionContext.Request.Headers.Authorization.Parameter;

                    //Decrypts token key
                    var jsonString = FTH.Extension.Encrypter.Decrypt(tokenKey, LoginUtility.PRIVATE_KEY);

                    //Deserializes json string to get UserToken object
                    loginUser = JsonConvert.DeserializeObject <UserTokenDTO>(jsonString);

                    #region - Old Basic Authorization -
                    //Converting token key base64 to string and encode it as UTF8
                    //var emailPassword = Encoding.UTF8.GetString(Convert.FromBase64String(tokenKey));
                    //var userInfoArray = emailPassword.Split(':');
                    //var email = userInfoArray[0];
                    //var password = userInfoArray[1];
                    #endregion
                }
                catch
                {
                    actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response);
                    return;
                }

                User user = LoginUtility.GetUserByEmailAndPassword(loginUser.email, loginUser.password);
                if (user != null && DateTime.Compare(DateTime.Now, loginUser.expireDate) < 0)
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(loginUser.email), null);
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response);
                }
            }
        }
示例#6
0
        public async Task <IActionResult> Logout(string logoutId)
        {
            // build a model so the logout page knows what to display
            var vm = await LoginUtility.BuildLogoutViewModelAsync(logoutId, _interaction, User);

            if (vm.ShowLogoutPrompt == false)
            {
                // if the request for logout was properly authenticated from IdentityServer, then
                // we don't need to show the prompt and can just log the user out directly.
                return(await Logout(vm));
            }

            return(View(vm));
        }
示例#7
0
        public async Task <IActionResult> Login(string returnUrl)
        {
            // build a model so we know what to show on the login page
            var vm = await LoginUtility.BuildLoginViewModelAsync(returnUrl, _interaction, User, _schemeProvider, _clientStore);

            if (vm.IsExternalLoginOnly)
            {
                // we only have one option for logging in and it's an external provider
                return(RedirectToAction("Challenge", "External",
                                        new { provider = vm.ExternalLoginScheme, returnUrl }));
            }

            return(View(vm));
        }
        protected void registerButton_Click(object sender, EventArgs e)
        {
            if (RegistrationDB.isCustomerExist(userNameTextBox.Text))
            {
                failedLabel.Visible = true;
                return;
            }

            failedLabel.Visible = false;
            string encryptedPwd = LoginUtility.GetEncryptedValue(passwordTextBox.Text);

            RegistrationDB.AddCustomer(firstNameTextBox.Text, lastNameTextBox.Text,
                                       phoneTextBox.Text, cityTextBox.Text,
                                       userNameTextBox.Text, encryptedPwd);
            successLabel.Visible = true;
        }
示例#9
0
        public IActionResult Index()
        {
            // Ensures that the user is logged in and if not redirects to the login page
            if (!LoginUtility.CheckAuthenticated(HttpContext.Session))
            {
                return(RedirectToAction("Index", "Login"));
            }

            var _stats = _context.Stats.ToList();
            var _teams = _context.Team.ToList();

            // Fetch the 3 players with the most goals
            var stats = _context.Stats.Include(s => s.Player.Team)
                        .GroupBy(i => i.Player)
                        .Select(g => new { Player = g.Key, Team = g.Key.Team, Total = g.Sum(j => j.Goals) })
                        .OrderByDescending(g => g.Total).Take(3);

            // Convert from a dynamic type to a tuple (because of errors)
            List <(Player, Team, int)> realStats = new List <(Player, Team, int)>();

            foreach (var stat in stats.ToList())
            {
                realStats.Add((stat.Player, stat.Team, (int)stat.Total));
            }
            // Add to view
            ViewBag.topPlayers = realStats.ToList();

            // Fetch the teams with the most goals
            var teamStats = _context.Stats.Include(s => s.Player).Include(s => s.Player.Team)
                            .GroupBy(i => i.Player.Team)
                            .Select(g => new { Team = g.Key, Total = g.Sum(j => j.Player.Stats.Sum(k => k.Goals)) })
                            .OrderByDescending(g => g.Total).Take(3);

            // Convert from a dynamic type to a tuple (because of errors)
            List <(Team, int)> realTeamStats = new List <(Team, int)>();

            foreach (var stat in teamStats.ToList())
            {
                realTeamStats.Add((stat.Team, (int)stat.Total));
            }
            // Add to view
            ViewBag.topTeams = realTeamStats.ToList();

            return(View());
        }
示例#10
0
        private void kryptonButtonLogin_Click(object sender, EventArgs e)
        {
            var email    = kryptonTextBoxLoginEmail.Text.Trim().ToLower();
            var password = kryptonTextBoxLoginPassword.Text;

            if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password))
            {
                return;
            }

            if (!IsValidEmail(email))
            {
                EditorMessageBox.ShowWarning("Invalid email.");
                return;
            }

            LoginUtility.SetCurrentLicense(kryptonTextBoxLoginEmail.Text, kryptonTextBoxLoginPassword.Text);
        }
示例#11
0
        private async void BtnUpdateInfo_ClickAsync(object sender, EventArgs e)
        {
            FragmentTransaction transaction = FragmentManager.BeginTransaction();
            DialogInfo          dialog      = new DialogInfo();

            dialog.Show(transaction: transaction, "dialog info");
            ISharedPreferences prefs    = PreferenceManager.GetDefaultSharedPreferences(this.Activity);
            string             username = prefs.GetString("username", "");
            string             password = prefs.GetString("password", "");

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                Toast.MakeText(this.Activity, "Hãy thử đăng nhập lại !!!", ToastLength.Short).Show();
                //Show message failture
                return;
            }
            if (Connectivity.NetworkAccess == NetworkAccess.None)
            {
                dialog.Dismiss();
                Toast.MakeText(this.Activity, "Không thể kết nối với Wifi/3G/4G", ToastLength.Short).Show();
                return;
            }
            bool isLoginSuccess = await LoginUtility.CrawlData(username, password).ConfigureAwait(true);

            if (isLoginSuccess)
            {
                DatabaseUtility.GetDataScheduler();
                DatabaseUtility.GetDataExam();
                DatabaseUtility.SaveInfoDatabase();
                dialog.Dismiss();
                Toast.MakeText(this.Activity, "Cập nhật thành công !", ToastLength.Short).Show();
            }
            else
            {
                dialog.Dismiss();
                Toast.MakeText(this.Activity, "Cập nhật thất bại !", ToastLength.Short).Show();
            }
        }
示例#12
0
        private void EditorForm_Load(object sender, EventArgs e)
        {
            if (EditorUtility.IsDesignerHosted(this))
            {
                return;
            }

            //hide ribbon to avoid redrawing
            kryptonRibbon.Visible = false;

            // create cover
            coverControl           = new Control();
            coverControl.BackColor = Color.FromArgb(40, 40, 40);
            // 127, 127, 127 );
            //coverControl.BackColor = DarkTheme ? Color.FromArgb( 40, 40, 40 ) : Color.FromArgb( 42, 87, 154 );
            //coverControl.BackColor = Color.Black;
            coverControl.Dock = DockStyle.Fill;
            Controls.Add(coverControl);
            coverControl.BringToFront();
            Application.DoEvents();

            //dpi
            try
            {
                using (Graphics graphics = CreateGraphics())
                {
                    dpi = graphics.DpiX;
                }
            }
            catch (Exception ex)
            {
                dpi = 96;
                Log.Warning("EditorForm: CreateGraphics: Call failed. " + ex.Message);
            }

            kryptonRibbon.RibbonTabs.Clear();

            {
                EngineApp.InitSettings.UseApplicationWindowHandle = Handle;

                if (!EngineApp.Create())
                {
                    Log.Fatal("EngineApp.Create() failed.");
                    Close();
                    return;
                }

                //эксепшен не генегируется, просто падает

                //bool created = false;

                //if( Debugger.IsAttached )
                //	created = EngineApp.Create();
                //else
                //{
                //	try
                //	{
                //		//!!!!
                //		Log.Info( "dd" );

                //		created = EngineApp.Create();

                //		//!!!!
                //		Log.Info( "tt" );

                //	}
                //	catch( Exception e2 )
                //	{
                //		//!!!!
                //		Log.Info( "ee" );

                //		Log.FatalAsException( e2.ToString() );
                //	}
                //}

                //if( !created )
                //{
                //	Log.Fatal( "EngineApp.Create() failed." );
                //	Close();
                //	return;
                //}
            }

            EngineApp.DefaultSoundChannelGroup.Volume = 0;

            //set theme
            if (ProjectSettings.Get.Theme.Value == Component_ProjectSettings.ThemeEnum.Dark)
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlack;
            }
            else
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlue;
            }

            KryptonDarkThemeUtility.DarkTheme = EditorAPI.DarkTheme;
            if (EditorAPI.DarkTheme)
            {
                EditorAssemblyInterface.Instance.SetDarkTheme();
            }

            Aga.Controls.Tree.NodeControls.BaseTextControl.DarkTheme = EditorAPI.DarkTheme;

            //app button
            kryptonRibbon.RibbonAppButton.AppButtonText = EditorLocalization.Translate("AppButton", kryptonRibbon.RibbonAppButton.AppButtonText);
            if (DarkTheme)
            {
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorDark  = Color.FromArgb(40, 40, 40);
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorLight = Color.FromArgb(54, 54, 54);
            }

            //!!!! default editor layout:

            // IsSystemWindow = true for this:
            // для этих "системных" окон используется отдельная логика сериализации (окна создаются до загрузки конфига)
            // и отдельная логика закрытия (hide/remove)
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ObjectsWindow(), new SettingsWindow() }, DockingEdge.Right);
            //workspaceController.AddDockspace(new MembersWindow(), "Members", DockingEdge.Right, new Size(300, 300));
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ResourcesWindow(), new SolutionExplorer(), new PreviewWindow() }, DockingEdge.Left);
            workspaceController.AddToDockspace(new DockWindow[] { new MessageLogWindow(), new OutputWindow(), new DebugInfoWindow() }, DockingEdge.Bottom);

            //!!!!
            //workspaceController.AddDockWindow( new TipsWindow(), true, false );

            //!!!!эвент чтобы свои добавлять. и пример

            //load docking state
            {
                string configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileName);
                //default settings
                if (!File.Exists(configFile))
                {
                    configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileNameDefault);
                }

                if (File.Exists(configFile))
                {
                    //try
                    //{
                    ////!!!! If xml broken, we will not get an exception.
                    //// the exception is swallowed inside the krypton.
                    //// how do I know if an error has occurred?
                    workspaceController.LoadLayoutFromFile(configFile);
                    //}
                    //	catch
                    //	{
                    //		//!!!!TODO: layout broken. fix this!
                    //	}
                }
            }

            InitQAT();
            InitRibbon();

            UpdateText();

            //apply editor settings
            EditorSettingsSerialization.InitAfterFormLoad();

            XmlDocumentationFiles.PreloadBaseAssemblies();

            EditorAPI.SelectedDocumentWindowChanged += EditorAPI_SelectedDocumentWindowChanged;

            UpdateRecentProjectsInRegistry();

            LoginUtility.RequestFullLicenseInfo();

            loaded = true;
        }
示例#13
0
        private async void BtnLogin_Click(object sender, EventArgs e)
        {
            if (txtUsername.Text.Length == 0)
            {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Thông báo");
                alert.SetMessage("Tên đăng nhập không được để trống");
                alert.SetButton("OK", (c, events) => { });
                alert.Show();
                return;
            }
            else if (txtPassword.Text.Length == 0)
            {
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Thông báo");
                alert.SetMessage("Mật khẩu không được để trống");
                alert.SetButton("OK", (c, events) => { });
                alert.Show();
                return;
            }


            if (Connectivity.NetworkAccess == NetworkAccess.None)
            {
                Toast.MakeText(this, "Không thể kết nối với Wifi/3G/4G", ToastLength.Short).Show();
                return;
            }
            new Thread(() =>
            {
                LoginDataManager.GetWeekInYear();
            }).Start();
            RunOnUiThread(new Action(() =>
            {
                progressBar.Visibility = ViewStates.Visible;
                btnLogin.Visibility    = ViewStates.Gone;
                txtUsername.Enabled    = txtPassword.Enabled = false;
            }));
            bool isLoginSuccess = await LoginUtility.CrawlData(txtUsername.Text, txtPassword.Text).ConfigureAwait(true);

            if (isLoginSuccess)
            {
                SaveAccountPrefers();
                DatabaseUtility.GetDataScheduler();
                DatabaseUtility.GetDataExam();
                DatabaseUtility.GetProfile();


                Handler handler = new Handler();
                Action  action  = new Action(() =>
                {
                    Intent intent = new Intent(this, typeof(MainActivity));
                    this.StartActivity(intent);
                });
                handler.Post(action);
                handler.Post(new Action(() => { DatabaseUtility.SaveInfoDatabase(); }));

                this.Finish();
            }
            else
            {
                progressBar.Visibility = ViewStates.Gone;
                btnLogin.Visibility    = ViewStates.Visible;
                txtUsername.Enabled    = txtPassword.Enabled = true;
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                AlertDialog         alert  = dialog.Create();
                alert.SetTitle("Thông báo");
                alert.SetMessage("Đăng nhập thất bại! Vui lòng thử lại sau!");
                alert.SetButton("OK", (c, events) => { });
                alert.Show();
            }
        }
示例#14
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // check if we are in the context of an authorization request
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // the user clicked the "cancel" button
            if (button != "login")
            {
                if (context != null)
                {
                    // if the user cancels, send a result back into IdentityServer as if they
                    // denied the consent (even if this client does not require consent).
                    // this will send back an access denied OIDC error response to the client.
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // if the client is PKCE then we assume it's native, so this change in how to
                        // return the response is for better UX for the end user.
                        return(this.LoadingPage("Redirect", model.ReturnUrl));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // since we don't have a valid context, then we just go back to the home page
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                // validate username/password against in-memory store
                if (_users.ValidateCredentials(model.Username, model.Password))
                {
                    var user = _users.FindByUsername(model.Username);
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.SubjectId, user.Username,
                                                                       clientId : context?.ClientId));

                    // only set explicit expiration here if user chooses "remember me".
                    // otherwise we rely upon expiration configured in cookie middleware.
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                        };
                    }

                    ;

                    // issue authentication cookie with subject ID and username
                    var isuser = new IdentityServerUser(user.SubjectId)
                    {
                        DisplayName = user.Username
                    };

                    await HttpContext.SignInAsync(isuser, props);

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // if the client is PKCE then we assume it's native, so this change in how to
                            // return the response is for better UX for the end user.
                            return(this.LoadingPage("Redirect", model.ReturnUrl));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    // request for a local page
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // user might have clicked on a malicious link - should be logged
                        throw new Exception("invalid return URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "invalid credentials",
                                                                   clientId : context?.ClientId));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // something went wrong, show form with error
            var vm = await LoginUtility.BuildLoginViewModelAsync(model, _interaction, User, _schemeProvider, _clientStore);

            return(View(vm));
        }
示例#15
0
        public async Task <IActionResult> Callback()
        {
            // read external identity from the temporary cookie
            var result =
                await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants
                                                    .ExternalCookieAuthenticationScheme);

            if (result?.Succeeded != true)
            {
                throw new Exception("External authentication error");
            }

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                var externalClaims = result.Principal.Claims.Select(c => $"{c.Type}: {c.Value}");
                _logger.LogDebug("External claims: {@claims}", externalClaims);
            }

            // lookup our user and external provider info
            var(user, provider, providerUserId, claims) = LoginUtility.FindUserFromExternalProvider(result, _users);
            if (user == null)
            {
                // this might be where you might initiate a custom workflow for user registration
                // in this sample we don't show how that would be done, as our sample implementation
                // simply auto-provisions new external user
                user = LoginUtility.AutoProvisionUser(provider, providerUserId, claims, _users);
            }

            // this allows us to collect any additional claims or properties
            // for the specific protocols used and store them in the local auth cookie.
            // this is typically used to store data needed for signout from those protocols.
            var additionalLocalClaims = new List <Claim>();
            var localSignInProps      = new AuthenticationProperties();

            LoginUtility.ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
            //ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
            //ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);

            // issue authentication cookie for user
            var isuser = new IdentityServerUser(user.SubjectId)
            {
                DisplayName      = user.Username,
                IdentityProvider = provider,
                AdditionalClaims = additionalLocalClaims
            };

            await HttpContext.SignInAsync(isuser, localSignInProps);

            // delete temporary cookie used during external authentication
            await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);

            // retrieve return URL
            var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";

            // check if external login is in the context of an OIDC request
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.SubjectId, user.Username,
                                                               true, context?.ClientId));

            if (context != null)
            {
                if (await _clientStore.IsPkceClientAsync(context.ClientId))
                {
                    // if the client is PKCE then we assume it's native, so this change in how to
                    // return the response is for better UX for the end user.
                    return(this.LoadingPage("Redirect", returnUrl));
                }
            }

            return(Redirect(returnUrl));
        }
示例#16
0
        private void EditorForm_Load(object sender, EventArgs e)
        {
            if (WinFormsUtility.IsDesignerHosted(this))
            {
                return;
            }

            //hide ribbon to avoid redrawing
            kryptonRibbon.Visible = false;

            // create cover
            coverControl           = new Control();
            coverControl.BackColor = Color.FromArgb(40, 40, 40);
            coverControl.Dock      = DockStyle.Fill;
            Controls.Add(coverControl);
            coverControl.BringToFront();
            Application.DoEvents();

            ////dpi
            //try
            //{
            //	using( Graphics graphics = CreateGraphics() )
            //	{
            //		dpi = graphics.DpiX;
            //	}
            //}
            //catch( Exception ex )
            //{
            //	dpi = 96;
            //	Log.Warning( "EditorForm: CreateGraphics: Call failed. " + ex.Message );
            //}

            kryptonRibbon.RibbonTabs.Clear();

            {
                EngineApp.InitSettings.UseApplicationWindowHandle = Handle;

                if (!EngineApp.Create())
                {
                    Log.Fatal("EngineApp.Create() failed.");
                    Close();
                    return;
                }

                //эксепшен не генегируется, просто падает

                //bool created = false;

                //if( Debugger.IsAttached )
                //	created = EngineApp.Create();
                //else
                //{
                //	try
                //	{
                //		//!!!!
                //		Log.Info( "dd" );

                //		created = EngineApp.Create();

                //		//!!!!
                //		Log.Info( "tt" );

                //	}
                //	catch( Exception e2 )
                //	{
                //		//!!!!
                //		Log.Info( "ee" );

                //		Log.FatalAsException( e2.ToString() );
                //	}
                //}

                //if( !created )
                //{
                //	Log.Fatal( "EngineApp.Create() failed." );
                //	Close();
                //	return;
                //}
            }

            EngineApp.DefaultSoundChannelGroup.Volume = 0;

            EnableLocalization();
            PreviewImagesManager.Init();

            //set theme
            if (ProjectSettings.Get.Theme.Value == Component_ProjectSettings.ThemeEnum.Dark)
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlack;
            }
            else
            {
                kryptonManager.GlobalPaletteMode = PaletteModeManager.NeoAxisBlue;
            }

            KryptonDarkThemeUtility.DarkTheme = EditorAPI.DarkTheme;
            if (EditorAPI.DarkTheme)
            {
                EditorAssemblyInterface.Instance.SetDarkTheme();
            }
            Aga.Controls.Tree.NodeControls.BaseTextControl.DarkTheme = EditorAPI.DarkTheme;

            BackColor = EditorAPI.DarkTheme ? Color.FromArgb(40, 40, 40) : Color.FromArgb(240, 240, 240);

            //app button
            kryptonRibbon.RibbonAppButton.AppButtonText = EditorLocalization.Translate("AppButton", kryptonRibbon.RibbonAppButton.AppButtonText);
            if (DarkTheme)
            {
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorDark  = Color.FromArgb(40, 40, 40);
                kryptonRibbon.RibbonAppButton.AppButtonBaseColorLight = Color.FromArgb(54, 54, 54);
            }

            //!!!! default editor layout:

            // IsSystemWindow = true for this:
            // для этих "системных" окон используется отдельная логика сериализации (окна создаются до загрузки конфига)
            // и отдельная логика закрытия (hide/remove)
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ObjectsWindow(), new SettingsWindow() }, DockingEdge.Right);
            //workspaceController.AddDockspace(new MembersWindow(), "Members", DockingEdge.Right, new Size(300, 300));
            workspaceController.AddToDockspaceStack(new DockWindow[] { new ResourcesWindow(), new SolutionExplorer(), new PreviewWindow() }, DockingEdge.Left);
            workspaceController.AddToDockspace(new DockWindow[] { new MessageLogWindow(), new OutputWindow(), new DebugInfoWindow() }, DockingEdge.Bottom);

            Log.Info("Use Log.Info(), Log.Warning() methods to write to the window. These methods can be used in the Player. Press '~' to open console of the Player.");
            OutputWindow.Print("Use OutputWindow.Print() method to write to the window. Unlike Message Log window, this window is not a list. Here you can add text in arbitrary format.\n");

            //!!!!эвент чтобы свои добавлять. и пример

            //load docking state
            {
                string configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileName);
                //default settings
                if (!File.Exists(configFile))
                {
                    configFile = VirtualPathUtility.GetRealPathByVirtual(dockingConfigFileNameDefault);
                }

                if (File.Exists(configFile))
                {
                    //no try catch to save the ability to work with debugger. in case when error happens during loading one of documents

                    //try
                    //{
                    workspaceController.LoadLayoutFromFile(configFile);

                    //!!!!
                    //hack. unhide the page to load it correctly. after loading the page will hided
                    foreach (var page in workspaceController.DockingManager.Pages)
                    {
                        if (page.needHideAfterLoading)
                        {
                            page.needHideAfterLoading = false;

                            var window = page.GetDockWindow();
                            if (window != null)
                            {
                                workspaceController.SetDockWindowVisibility(window, false);
                            }
                        }
                    }

                    //}
                    //catch( Exception e2 )
                    //{
                    //	var text = $"Error loading docking settings.\n\n" + e2.Message;
                    //	Log.Warning( text );
                    //	EditorMessageBox.ShowWarning( text );
                    //}
                }
            }

            InitQAT();
            InitRibbon();

            UpdateText();

            //apply editor settings
            EditorSettingsSerialization.InitAfterFormLoad();

            XmlDocumentationFiles.PreloadBaseAssemblies();

            EditorAPI.SelectedDocumentWindowChanged += EditorAPI_SelectedDocumentWindowChanged;

            UpdateRecentProjectsInRegistry();

            LoginUtility.RequestFullLicenseInfo();

            kryptonRibbon.BeforeMinimizedModeChanged += KryptonRibbon_BeforeMinimizedModeChanged;
            kryptonRibbon.MinimizedModeChanged       += KryptonRibbon_MinimizedModeChanged;

            KryptonWinFormsUtility.editorFormStartTemporaryLockUpdateAction = delegate()
            {
                if (IsHandleCreated && !EditorAPI.ClosingApplication)
                {
                    KryptonWinFormsUtility.LockFormUpdate(this);
                    unlockFormUpdateInTimer = DateTime.Now + TimeSpan.FromSeconds(0.1);
                }
            };

            loaded = true;
        }
示例#17
0
        public HttpClient GetAuthenticatedHttpClient(string userName, string password)
        {
            var testHttpClient = GetHttpClient();

            return(LoginUtility.GetAuthenticatedHttpClient(userName, password, testHttpClient));
        }