Пример #1
0
 private void ConfirmClicked(object sender, KeyRoutedEventArgs e)
 {
     if (e.Key != VirtualKey.Accept && e.Key != VirtualKey.Enter)
     {
         return;
     }
     e.Handled = true;
     if (Passcode.Password.Equals(Options.Passcode))
     {
         LoggingService.Log($"Pincode matched, going to {SDKManager.RootApplicationPage}", LoggingLevel.Verbose);
         AuthStorageHelper.StorePincode(Options.Policy, Options.Passcode);
         PincodeManager.Unlock();
         Frame.Navigate(SDKManager.RootApplicationPage);
     }
     else
     {
         DisplayErrorFlyout(LocalizedStrings.GetString("passcode_must_match"));
     }
 }
Пример #2
0
        public async Task ExportToExcel(string GridModel)
        {
            ExcelExport exp  = new ExcelExport();
            var         data = await GetData();

            var users      = data.UsersViewModel.ToList();
            var DataSource = users;

            currentData = users;
            var currentDate = DateTime.Today.ToShortDateString().Replace("/", "-");

            GridProperties obj = (GridProperties)Syncfusion.JavaScript.Utils.DeserializeToModel(typeof(GridProperties), GridModel);

            //Clear if there are any filter columns
            //syncfusion bug in exporting while in filter mode
            obj.FilterSettings.FilteredColumns.Clear();

            obj.ServerExcelQueryCellInfo = QueryCellInfo;

            exp.Export(obj, DataSource, LocalizedStrings.GetString("User") + " " + currentDate + ".xlsx", ExcelVersion.Excel2010, false, false, "flat-saffron");
        }
Пример #3
0
        public async Task <ActionResult> InsertSurvey(CRUDModel <SurveyViewModel> survey)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
                }

                var newSurvey = new Survey
                {
                    Name = survey.Value.Name
                };

                Survey[] addSurvey = new[] { newSurvey };
                await _prepareService.SaveSurveys(addSurvey);

                var newSurveys = await _prepareService.GetSurveys();

                var createdSurvey = newSurveys.Last(u => u.Name == survey.Value.Name);
                survey.Value.SurveyId = createdSurvey.Id;
                survey.Value.Name     = survey.Value.Name;
                return(Json(survey.Value, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));
                if (ex.Message == "Common_CannotUseSameName")
                {
                    message = LocalizedStrings.GetString("Common_CannotUseSameName");
                }
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
            }
        }
Пример #4
0
        public async Task <ActionResult> UpdateSurvey(CRUDModel <SurveyViewModel> survey)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
                }

                var surveysEdit = await _prepareService.GetSurveys(survey.Value.SurveyId);

                var surveyEdit = surveysEdit.FirstOrDefault();
                surveyEdit.StartTracking();

                surveyEdit.Name = survey.Value.Name;
                surveyEdit.MarkAsModified();

                Survey[] editSurvey = new[] { surveyEdit };
                await _prepareService.SaveSurveys(editSurvey);

                survey.Value.SurveyId = editSurvey.FirstOrDefault().Id;
                return(Json(survey.Value, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));
                if (ex.Message == "Common_CannotUseSameName")
                {
                    message = LocalizedStrings.GetString("Common_CannotUseSameName");
                }
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
            }
        }
 private void CreateClicked(object sender, KeyRoutedEventArgs e)
 {
     if (e.Key != VirtualKey.Accept && e.Key != VirtualKey.Enter)
     {
         return;
     }
     e.Handled = true;
     if (Passcode.Password.Length >= Options.User.Policy.PinLength)
     {
         LoggingService.Log("Going to confirmation page", LoggingLevel.Verbose);
         var options = new PincodeOptions(PincodeOptions.PincodeScreen.Confirm, Options.User, Passcode.Password);
         // As per MSDN documentation (https://msdn.microsoft.com/en-us/library/windows/apps/hh702394.aspx)
         // the second param of Frame.Navigate must be a basic type otherwise Suspension manager will crash
         // when serializing frame's state. So we serialize custom object using Json and pass that as the
         // second param to avoid this crash.
         Frame.Navigate(typeof(PincodeDialog), PincodeOptions.ToJson(options));
     }
     else
     {
         DisplayErrorFlyout(String.Format(LocalizedStrings.GetString("passcode_length"),
                                          Options.User.Policy.PinLength));
     }
 }
        public void ContinueWebAuthentication(WebAuthenticationBrokerContinuationEventArgs args)
        {
            WebAuthenticationResult webResult = args.WebAuthenticationResult;

            var logMsg = String.Format("AccountPage.ContinueWebAuthentication - WebAuthenticationResult: Status={0}", webResult.ResponseStatus);

            if (webResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                logMsg += string.Format(", ErrorDetail={0}", webResult.ResponseErrorDetail);
            }

            PlatformAdapter.SendToCustomLogger(logMsg, LoggingLevel.Verbose);

            if (webResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(webResult.ResponseData);
                if (!responseUri.Query.Contains("error="))
                {
                    AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1));
                    PlatformAdapter.Resolve <IAuthHelper>().EndLoginFlow(SalesforceConfig.LoginOptions, authResponse);
                }
                else
                {
                    DisplayErrorDialog(LocalizedStrings.GetString("generic_error"));
                    SetupAccountPage();
                }
            }
            else if (webResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                SetupAccountPage();
            }
            else
            {
                DisplayErrorDialog(LocalizedStrings.GetString("generic_authentication_error"));
                SetupAccountPage();
            }
        }
Пример #7
0
        private void LoadFonts()
        {
            Task.Run(() =>
            {
                var x       = new List <string>();
                var factory = new Factory();
                FontCollection fontCollection = factory.GetSystemFontCollection(false);
                int familyCount = fontCollection.FontFamilyCount;
                for (int i = 0; i < familyCount; i++)
                {
                    FontFamily fontFamily        = fontCollection.GetFontFamily(i);
                    LocalizedStrings familyNames = fontFamily.FamilyNames;
                    int index;
                    if (!familyNames.FindLocaleName(CultureInfo.CurrentCulture.Name, out index))
                    {
                        familyNames.FindLocaleName("en-us", out index);
                    }

                    string name = familyNames.GetString(index);
                    x.Add(name);
                }
                Fonts = new ObservableCollection <string>(x.OrderBy(y => y));
            });
        }
Пример #8
0
        public async Task <ActionResult> DeleteInspectionCurrentAuditAsync()
        {
            try
            {
                var userId       = Convert.ToInt32(System.Web.HttpContext.Current.User.Identity.GetUserId());
                var currentAudit = await _prepareService.GetActiveAudit(userId);

                if (currentAudit == null)
                {
                    return(Json(new { Success = false, Message = LocalizedStrings.GetString("Audit_Not_Exist_Anymore") }));
                }

                currentAudit.IsDeleted = true;
                currentAudit.MarkAsModified();
                //currentAudit.IsMarkedAsModified = true;
                await _prepareService.SaveAudit(currentAudit);

                return(Json(new { Success = true }));
            }
            catch (Exception ex)
            {
                return(Json(new { Success = false, Message = ex.Message }));
            }
        }
        private async void LockedClick(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key != VirtualKey.Accept && e.Key != VirtualKey.Enter)
            {
                return;
            }
            e.Handled = true;
            Account account = AccountManager.GetAccount();

            if (account == null)
            {
                await SDKServiceLocator.Get <IAuthHelper>().StartLoginFlowAsync();
            }
            else if (AuthStorageHelper.ValidatePincode(Passcode.Password))
            {
                PincodeManager.Unlock();
                if (Frame.CanGoBack)
                {
                    Frame.GoBack();
                }
                else
                {
                    Frame.Navigate(SDKManager.RootApplicationPage);
                }
            }
            else
            {
                if (RetryCounter <= 1)
                {
                    await SDKManager.GlobalClientManager.Logout();
                }
                RetryCounter--;
                ContentFooter.Text       = String.Format(LocalizedStrings.GetString("passcode_incorrect"), RetryCounter);
                ContentFooter.Visibility = Visibility.Visible;
            }
        }
Пример #10
0
            public override void Draw(TGPASpriteBatch spriteBatch)
            {
                TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, button, TGPAContext.Instance.Player1.Device.Type, locationP1, Color.White * alphaColor);

                TGPAContext.Instance.TextPrinter.Color = Color.Black * alphaColor;
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, locationP1.X + ((button == "#Move" && TGPAContext.Instance.Player1.Device.Type == DeviceType.KeyboardMouse) ? 150 : 50), locationP1.Y, LocalizedStrings.GetString(button.Replace("#", "Player")), 128);
                TGPAContext.Instance.TextPrinter.Color = Color.Black;
            }
Пример #11
0
        public override void Update(GameTime gameTime)
        {
            bool left  = false;
            bool right = false;
            bool apply = false;

            if (actionCooldown > 0f)
            {
                actionCooldown -= (float)gameTime.ElapsedGameTime.TotalMilliseconds;
            }

            if (TGPAContext.Instance.Player1.IsPlayingOnWindows())
            {
                if (leftArrowDst.Intersects(TGPAContext.Instance.MouseDst))
                {
                    this.focus = leftArrowDst;
                    if (TGPAContext.Instance.InputManager.PlayerIsPressingButtonConfirm(TGPAContext.Instance.Player1))
                    {
                        if (actionCooldown <= 0f)
                        {
                            left           = true;
                            actionCooldown = 100f;
                        }
                    }
                }
                else if (rightArrowDst.Intersects(TGPAContext.Instance.MouseDst))
                {
                    this.focus = rightArrowDst;
                    if (TGPAContext.Instance.InputManager.PlayerIsPressingButtonConfirm(TGPAContext.Instance.Player1))
                    {
                        if (actionCooldown <= 0f)
                        {
                            right          = true;
                            actionCooldown = 100f;
                        }
                    }
                }
                else if (confirmButton.Intersects(TGPAContext.Instance.MouseDst))
                {
                    this.focus = confirmButton;
                    if (TGPAContext.Instance.InputManager.PlayerPressButtonConfirm(TGPAContext.Instance.Player1))
                    {
                        apply = true;
                    }
                }
                else
                {
                    this.focus = Rectangle.Empty;
                }
            }
            else
            {
                if (this.Focus)
                {
                    if (TGPAContext.Instance.InputManager.PlayerPressLeft(TGPAContext.Instance.Player1))
                    {
                        this.focus = leftArrowDst;

                        if (actionCooldown <= 0f)
                        {
                            left           = true;
                            actionCooldown = 100f;
                        }
                    }
                    if (TGPAContext.Instance.InputManager.PlayerPressRight(TGPAContext.Instance.Player1))
                    {
                        this.focus = rightArrowDst;

                        if (actionCooldown <= 0f)
                        {
                            right          = true;
                            actionCooldown = 100f;
                        }
                    }
                    else if (TGPAContext.Instance.InputManager.PlayerPressButtonConfirm(TGPAContext.Instance.Player1))
                    {
                        this.focus = confirmButton;
                        apply      = true;
                    }
                }
            }

            //Update values
            if (this.Focus)
            {
                if (left)
                {
                    this.PreviousElement();
                    SoundEngine.Instance.PlaySound("listSelectionChanged");
                }
                else if (right)
                {
                    this.NextElement();
                    SoundEngine.Instance.PlaySound("listSelectionChanged");
                }
            }

            this.DstRect = new Rectangle((int)location.X, (int)location.Y, 200 + leftArrowDst.Width + rightArrowDst.Width + this.focusedElement.SrcRect.Width, Math.Max(this.focusedElement.SrcRect.Height, arrowSrc.Height));


            this.focusedElement.Update(gameTime);

            this.drawLeft = true;
            if (this.indexList == 0)
            {
                this.drawLeft = false;
            }

            this.drawRight = true;
            if (this.indexList == this.elements.Count - 1)
            {
                this.drawRight = false;
            }

            if (confirmButtonEnable)
            {
                this.Changed = apply;

                confirmButton = new Rectangle(rightArrowDst.Right + 30,
                                              (int)this.location.Y - 10,
                                              50 + (int)(11f * TGPAContext.Instance.TextPrinter.Size) * LocalizedStrings.GetString(this.confirmButtonlabel).Length,
                                              55);
                Rectangle dRect = this.DstRect;
                dRect.Width += 95;
                this.DstRect = dRect;
            }

            base.Update(gameTime);
        }
Пример #12
0
        public override void Draw(TGPASpriteBatch spriteBatch)
        {
            Rectangle src = new Rectangle();
            Rectangle dst = new Rectangle();

            Color c = Color.White;

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

            if (Focus)
            {
                //Draw left arrow
                //************************************************************

                if (!drawLeft)
                {
                    c = (Color.Gray * 0.3f);
                }

                leftArrowDst   = arrowSrc;
                leftArrowDst.X = (int)location.X + 200;
                leftArrowDst.Y = (int)location.Y;

                src = arrowSrc;
                if (focus == leftArrowDst)
                {
                    src.X += src.Width;
                }
                spriteBatch.Draw(this.Sprite, leftArrowDst, src, c);
            }
            spriteBatch.End();

            //Draw element
            //************************************************************
            dst   = this.focusedElement.SrcRect;
            dst.X = (int)location.X + 200 + arrowSrc.Width;
            dst.Y = (int)location.Y;

            src = this.focusedElement.SrcRect;
            this.focusedElement.Draw(dst, spriteBatch);

            if (Focus)
            {
                //Draw right arrow
                //************************************************************
                c = Color.White;
                if (!drawRight)
                {
                    c = Color.Gray * 0.3f;
                }

                rightArrowDst   = arrowSrc;
                rightArrowDst.X = (int)location.X + 200 + arrowSrc.Width + this.focusedElement.SrcRect.Width;
                rightArrowDst.Y = (int)location.Y;

                src = arrowSrc;
                if (focus == rightArrowDst)
                {
                    src.X += src.Width;
                }
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(this.Sprite, rightArrowDst, src, c, 0.0f, Vector2.Zero, SpriteEffects.FlipHorizontally, 1.0f);

                //************************************************************
                spriteBatch.End();

                if (confirmButtonEnable)
                {
                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                    if (focus == this.confirmButton)
                    {
                        spriteBatch.Draw(TGPAContext.Instance.HudTex, this.confirmButton, TGPAContext.Instance.PaperRect, Color.Green * 0.5f);
                    }
                    else
                    {
                        spriteBatch.Draw(TGPAContext.Instance.HudTex, this.confirmButton, TGPAContext.Instance.PaperRect, Color.Aquamarine * 0.5f);
                    }

                    spriteBatch.End();

                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, this.confirmButton.X + 15, this.confirmButton.Y + 15, LocalizedStrings.GetString(this.confirmButtonlabel), 512);
                }


                //Draw help buttons for Pad
                if (TGPAContext.Instance.Player1.IsPlayingOnWindows() == false && (Focus))
                {
                    if (confirmButtonEnable)
                    {
                        TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Confirm", TGPAContext.Instance.Player1.Device.Type, confirmButton.X + confirmButton.Width, this.confirmButton.Y);
                    }
                }
            }

            TGPAContext.Instance.TextPrinter.Color = Color.Navy;
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, this.location.X, this.location.Y, this.name, 512);
            TGPAContext.Instance.TextPrinter.Color = Color.Black;
        }
Пример #13
0
        public async Task <ActionResult> SaveSmtpParameters(SMTPParameters parameters)
        {
            bool   useAnonymMode = parameters.useAnonymMode;
            string senderEmail   = parameters.senderEmail;
            string password      = parameters.password;
            string serverAddress = parameters.serverAddress;
            int    serverPort    = parameters.serverPort;
            bool   useSSL        = parameters.useSSL;

            try
            {
                if (string.IsNullOrEmpty(senderEmail))
                {
                    throw new Exception(LocalizedStrings.GetString("Web_Controller_Notification_SenderEmailCantBeNullOrEmpty"));
                }
                if (string.IsNullOrEmpty(serverAddress))
                {
                    throw new Exception(LocalizedStrings.GetString("Web_Controller_Notification_ServerAddressCantBeNullOrEmpty"));
                }
                if (serverPort == 0)
                {
                    throw new Exception(LocalizedStrings.GetString("Web_Controller_Notification_ServerPortCantBeNullOrEmpty"));
                }
                if (!useAnonymMode && string.IsNullOrEmpty(password))
                {
                    throw new Exception(LocalizedStrings.GetString("Web_Controller_Notification_PasswordCantBeNullOrEmptyWhenNotUsingAnonymMode"));
                }
                if (string.IsNullOrEmpty(password))
                {
                    password = string.Empty;
                }

                var editedSettings = new List <AppSetting>();
                var appSettings    = await _prepareService.GetAllAppSettings();

                var editSetting = appSettings.Any(_ => _.Key == "SMTP_UseAnonymMode") ? appSettings.Single(_ => _.Key == "SMTP_UseAnonymMode") : new AppSetting {
                    Key = "SMTP_UseAnonymMode", Value = Encoding.UTF8.GetBytes(useAnonymMode.ToString())
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(useAnonymMode.ToString());
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                editSetting = appSettings.Any(_ => _.Key == "Email_Sender_Address") ? appSettings.Single(_ => _.Key == "Email_Sender_Address") : new AppSetting {
                    Key = "Email_Sender_Address", Value = Encoding.UTF8.GetBytes(senderEmail)
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(senderEmail);
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                editSetting = appSettings.Any(_ => _.Key == "Email_Sender_Password") ? appSettings.Single(_ => _.Key == "Email_Sender_Password") : new AppSetting {
                    Key = "Email_Sender_Password", Value = Encoding.UTF8.GetBytes(password)
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(password);
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                editSetting = appSettings.Any(_ => _.Key == "SMTP_Client") ? appSettings.Single(_ => _.Key == "SMTP_Client") : new AppSetting {
                    Key = "SMTP_Client", Value = Encoding.UTF8.GetBytes(serverAddress)
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(serverAddress);
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                editSetting = appSettings.Any(_ => _.Key == "SMTP_Port") ? appSettings.Single(_ => _.Key == "SMTP_Port") : new AppSetting {
                    Key = "SMTP_Port", Value = Encoding.UTF8.GetBytes(serverPort.ToString())
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(serverPort.ToString());
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                editSetting = appSettings.Any(_ => _.Key == "SMTP_EnableSsl") ? appSettings.Single(_ => _.Key == "SMTP_EnableSsl") : new AppSetting {
                    Key = "SMTP_EnableSsl", Value = Encoding.UTF8.GetBytes(useSSL.ToString())
                };
                if (!editSetting.IsMarkedAsAdded)
                {
                    editSetting.Value = Encoding.UTF8.GetBytes(useSSL.ToString());
                    editSetting.MarkAsModified();
                }
                editedSettings.Add(editSetting);

                await _prepareService.SaveAppSettings(editedSettings.ToArray());

                HttpContext.Response.StatusDescription = $"{HttpStatusCode.OK}";
                return(Content($"{HttpStatusCode.OK}"));
            }
            catch (Exception ex)
            {
                HttpContext.Response.StatusDescription = $"{HttpStatusCode.InternalServerError}";
                return(Content(ex.Message));
            }
        }
 public PincodeDialog()
 {
     InitializeComponent();
     Passcode.PlaceholderText = LocalizedStrings.GetString("passcode");
     ErrorFlyout.Closed      += ErrorFlyout_Closed;
 }
Пример #15
0
        public async Task <ActionResult> UpdateUser(CRUDModel <UserViewModel> user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
                }

                if (user.Value.Roles == null || !user.Value.Roles.Any())
                {
                    throw new Exception(LocalizedStrings.GetString("AskSelectRole"));
                }

                var(Users, Roles, Languages, Teams) = await _applicationUsersService.GetUsersAndRolesAndLanguages();

                var userEdit = Users.FirstOrDefault(u => u.UserId == user.Value.UserId);
                userEdit.StartTracking();

                userEdit.DefaultLanguageCode = user.Value.DefaultLanguageCode;
                userEdit.Tenured             = user.Value.Tenured;
                userEdit.Username            = user.Value.Username;
                userEdit.Firstname           = user.Value.Firstname;
                userEdit.Name        = user.Value.Name;
                userEdit.Email       = user.Value.Email;
                userEdit.PhoneNumber = user.Value.PhoneNumber;
                if (user.Value.NewPassword != null)
                {
                    var hash = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(
                        Encoding.Default.GetBytes(user.Value.NewPassword));
                    userEdit.Password = hash;
                }
                // Reset the roles
                userEdit.Roles.Clear();
                foreach (var role in user.Value.Roles[0].Split(','))
                {
                    if (string.IsNullOrWhiteSpace(role))
                    {
                        continue;
                    }

                    userEdit.Roles.Add(Roles.First(u => u.RoleCode == role));
                }

                IEnumerable <User> editUser = new[] { userEdit };
                await _applicationUsersService.SaveUsers(editUser);

                var users = await GetData();

                var updateUser = users.UsersViewModel.First(u => u.Username == userEdit.Username);
                return(Json(updateUser, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Пример #16
0
        public void Update(GameTime gameTime)
        {
            this.remainingTime -= gameTime.ElapsedGameTime.TotalMilliseconds;

#if XBOX
            if (TGPAContext.Instance.InputManager.PlayerPressYButton(TGPAContext.Instance.Player1))
            {
                if (Guide.IsVisible == false)
                {
                    //Player need rights
                    SignedInGamer xboxProfile = Device.DeviceProfile(TGPAContext.Instance.Player1.Device);

                    if (xboxProfile.Privileges.AllowPurchaseContent)
                    {
                        Guide.ShowMarketplace((PlayerIndex)TGPAContext.Instance.Player1.Device.Index);
                    }
                    else
                    {
                        Guide.BeginShowMessageBox(LocalizedStrings.GetString("BuyFailTitle"), LocalizedStrings.GetString("BuyFailContent"), new List <string> {
                            "OK"
                        }, 0, MessageBoxIcon.Warning, null, null);
                    }
                }
            }
#endif
            //Leave the game with fade out
            if (alpha < 1f)
            {
                if ((TGPAContext.Instance.InputManager.PlayerPressButtonConfirm(TGPAContext.Instance.Player1)) ||
                    (this.remainingTime < 0f) ||
                    (Keyboard.GetState().IsKeyDown(Keys.Escape)) ||
                    (TGPAContext.Instance.IsTrialMode == false)
                    )
                {
                    alpha += 0.05f;
                    this.remainingTime = -1f;
                }
            }
            else
            {
                if (TGPAContext.Instance.IsTrialMode == false)
                {
                    TGPAContext.Instance.CurrentGameState = GameState.LevelSelectionScreen;
                }
                else
                {
                    TGPAContext.Instance.CurrentGameState = GameState.TitleScreen;
                }
            }
        }
Пример #17
0
        public void Draw(TGPASpriteBatch spriteBatch)
        {
            if (playersOut)
            {
                if (fadeOut > 0f)
                {
                    Color backscreen;

                    if (victory)
                    {
                        backscreen = (Color.White * this.fadeOut);
                    }
                    else
                    {
                        backscreen = (Color.Black * this.fadeOut);
                    }
                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                    spriteBatch.Draw(TGPAContext.Instance.NullTex, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), backscreen);
                    spriteBatch.End();
                }

                //Level
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(TGPAContext.Instance.HudTex, levelDst, TGPAContext.Instance.PaperRect, Color.White * (this.fadeOut + 0.1f));
                spriteBatch.End();

                String toPrint = "Level : " + TGPAContext.Instance.Map.Level;
                int    w       = 20 + toPrint.Length * 11;
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, levelDst.X + (levelDst.Width / 2) - w / 2, levelDst.Y + (levelDst.Height / 4), toPrint, 512);

                toPrint = TGPAContext.Instance.Map.Name;
                w       = 20 + toPrint.Length * 11;
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, levelDst.X + (levelDst.Width / 2) - w / 2, levelDst.Y + (levelDst.Height / 2), TGPAContext.Instance.Map.Name, 512);

                //Score
                #region Score compute
                if (playersOut)
                {
                    scoreDst.X = TGPAContext.Instance.ScreenWidth / 2 - scoreDst.Width / 2;

                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                    spriteBatch.Draw(sprites, scoreDst, scoreSrc, Color.White);
                    spriteBatch.End();

                    double duree = (elapsedGameTime - startGameTime);
                    int    h     = (int)((duree / 1000) / 3600);
                    int    m     = (int)(((duree / 1000) / 60) % 60);
                    int    s     = (int)((duree / 1000) % 60);

                    if (!victory)
                    {
                        TGPAContext.Instance.TextPrinter.Color = Color.Red;
                    }

                    if (cheat)
                    {
                        TGPAContext.Instance.TextPrinter.Color = Color.Silver;
                    }


                    int x    = 137;
                    int xbis = 337;
                    int y    = 212;

                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, x, y, LocalizedStrings.GetString("EndlevelScreenElapsedTime") + " : ");

                    TGPAContext.Instance.TextPrinter.Color = Color.Black;

                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, xbis, 240, h.ToString("00") + "h" + m.ToString("00") + "m" + s.ToString("00") + "s");

                    if ((victory) && (!cheat))
                    {
                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, x, scoreDst.Y + 150, LocalizedStrings.GetString("EndlevelScreenRemainingLives") + " :");

                        //Display heart icons or just a heart and a number
                        if (displayedLives < 6)
                        {
                            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                            for (int i = 0; i < displayedLives; i++)
                            {
                                Rectangle heartDst = new Rectangle(x + i * (heartSrc.Width / 2), scoreDst.Y + 180, heartSrc.Width, heartSrc.Height);
                                spriteBatch.Draw(sprites, heartDst, heartSrc, Color.White);
                            }

                            spriteBatch.End();
                        }
                        else
                        {
                            Rectangle heartDst = new Rectangle(x, scoreDst.Y + 180, heartSrc.Width, heartSrc.Height);

                            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                            spriteBatch.Draw(sprites, heartDst, heartSrc, Color.White);
                            spriteBatch.End();

                            TGPAContext.Instance.TextPrinter.Color = Color.DarkMagenta;
                            TGPAContext.Instance.TextPrinter.Write(spriteBatch, heartDst.Right + 10, heartDst.Center.Y, " x " + displayedLives, 128);
                            TGPAContext.Instance.TextPrinter.Color = Color.Black;
                        }


                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, xbis, scoreDst.Y + 179, totalLives.ToString("0000000 pts"));

                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, x, scoreDst.Y + 238, LocalizedStrings.GetString("EndlevelScreenRemainingBombs") + " :");

                        spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                        for (int i = 0; i < displayedBombs; i++)
                        {
                            Rectangle bombDst = new Rectangle(x + i * (bombSrc.Width / 2), scoreDst.Y + 265, bombSrc.Width, bombSrc.Height);
                            spriteBatch.Draw(sprites, bombDst, bombSrc, Color.White);
                        }
                        spriteBatch.End();

                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, xbis, scoreDst.Y + 270, totalBombs.ToString("0000000 pts"));

                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, x, scoreDst.Y + 325, LocalizedStrings.GetString("EndlevelScreenLevelPoints") + " : ");

                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, xbis, scoreDst.Y + 355, score.ToString("0000000 pts"));

                        if (scoreOK)
                        {
                            TGPAContext.Instance.TextPrinter.Color = Color.Blue;
                            TGPAContext.Instance.TextPrinter.Write(spriteBatch, x, scoreDst.Y + 380, "Supertotal : ");
                            TGPAContext.Instance.TextPrinter.Write(spriteBatch, xbis - 40, scoreDst.Y + 410, scoreTotal.ToString("0000000000 pts"));
                            TGPAContext.Instance.TextPrinter.Color = Color.Black;
                        }
                    }
                }
                #endregion

                #region Highscore
                if (highscoreOK)
                {
                    int xHighscoreOK = 480;

                    TGPAContext.Instance.TextPrinter.Size = 0.9f;

                    String mode = this.scoreTypeDisplay == ScoreType.Single ? "Mode1P" : "Mode2P";
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, xHighscoreOK + 65, scoreDst.Y + 90, "(" + LocalizedStrings.GetString(mode) + ")");

                    if (cheat)
                    {
                        TGPAContext.Instance.TextPrinter.Color = Color.Red;
                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, xHighscoreOK + 65, scoreDst.Y + 120, "Cheats ON (no score)");
                        TGPAContext.Instance.TextPrinter.Color = Color.Black;
                    }

                    for (int i = 0; i < 7; i++)
                    {
                        if ((scoreRank == (i + 1)) && (this.scoreTypeSave == this.scoreTypeDisplay))
                        {
                            TGPAContext.Instance.TextPrinter.Color = Color.Green;
                        }

                        SerializableDictionary <string, ScoreLine[]> scoreDictionnary;

                        if (TGPAContext.Instance.Saver.SaveData.ScoresBylevel.TryGetValue(this.scoreTypeDisplay, out scoreDictionnary))
                        {
                            ScoreLine[] scoreLines;

                            if (scoreDictionnary.TryGetValue(TGPAContext.Instance.CurrentMap, out scoreLines))
                            {
                                TGPAContext.Instance.TextPrinter.Write(spriteBatch, xHighscoreOK + 65, scoreDst.Y + 150 + (i * 30), (i + 1) + ". " + scoreLines[i].ToString());
                            }
                        }
                        else
                        {
                            TGPAContext.Instance.Saver.AddScore(TGPAContext.Instance.CurrentMap, this.scoreTypeDisplay, ScoreLine.GetDefaultScoreLine(1));
                        }

                        if (scoreRank == (i + 1))
                        {
                            TGPAContext.Instance.TextPrinter.Color = Color.Black;
                        }
                    }

                    TGPAContext.Instance.TextPrinter.Size = 1f;

                    //Buttons
                    //***************************************************************************
                    if (highscoreOK)
                    {
                        TGPAContext.Instance.TextPrinter.Color = Color.LightSalmon;
                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, 600, this.scoreDst.Bottom - 65, LocalizedStrings.GetString(this.scoreTypeDisplay == ScoreType.Single ? "SwitchToScoreTypeCoop" : "SwitchToScoreTypeSingle"));
                        TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Plus", TGPAContext.Instance.Player1.Device.Type, 550, this.scoreDst.Bottom - 70);

                        if (victory)
                        {
                            TGPAContext.Instance.TextPrinter.Color = Color.Black;
                        }
                        else
                        {
                            TGPAContext.Instance.TextPrinter.Color = Color.White;
                        }

                        TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Back", TGPAContext.Instance.Player1.Device.Type, 150, 700);
                        if (TGPAContext.Instance.Player1.IsPlayingOnWindows() == false)
                        {
                            TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Cancel", TGPAContext.Instance.Player1.Device.Type, 200, 700);
                        }
                        TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Confirm", TGPAContext.Instance.Player1.Device.Type, 550, 700);

                        if (victory)
                        {
                            TGPAContext.Instance.TextPrinter.Write(spriteBatch, 600, 700, LocalizedStrings.GetString("EndlevelScreenPressAcontinue"));
                        }
                        else
                        {
                            TGPAContext.Instance.TextPrinter.Write(spriteBatch, 600, 700, LocalizedStrings.GetString("EndlevelScreenPressAretry"));
                        }
                        TGPAContext.Instance.TextPrinter.Write(spriteBatch, 245, 700, LocalizedStrings.GetString("EndlevelScreenPressB"));

                        TGPAContext.Instance.TextPrinter.Color = Color.Black;
                    }
                }
                #endregion
            }
        }
        /// <summary>
        /// Draw a map with points for each level, and way between them
        /// </summary>
        /// <param name="spriteBatch"></param>
        /// <param name="Game"></param>
        public void Draw(TGPASpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

            //Background
            spriteBatch.Draw(background, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), null, Color.White);

            Rectangle LastLevelDst = Rectangle.Empty;

            //Draw levels and a way between them
            for (int i = 0; i < WorldCount; i++)
            {
                //The player need to have unlocked the level to display it
                Rectangle levelDst = Rectangle.Empty;
                if ((i <= TGPAContext.Instance.Saver.SaveData.LastLevel) && (i < WorldCount))
                {
                    Vector2 loc = levelPositionOnMap[i];
                    levelDst = new Rectangle(
                        (int)loc.X - levelSrc.Width / 2,
                        (int)loc.Y - levelSrc.Height / 2,
                        levelSrc.Width,
                        levelSrc.Height
                        );

                    Color levelColor = Color.White;
                    Color blinkColor = Color.Gray * alphaColorForLevelBlinking;

                    if ((selectedIndex == i) & (!shipIsMoving))
                    {
                        levelColor = Color.Red;
                        blinkColor = Color.OrangeRed * 0.0f;
                    }
                    else if (pointedIndex == i)
                    {
                        levelColor = Color.SpringGreen;
                        blinkColor = Color.White * 0.0f;
                    }
                    else if (i == TGPAContext.Instance.Saver.SaveData.LastLevel)
                    {
                        blinkColor = Color.PaleVioletRed * alphaColorForLevelBlinking;
                    }
                    spriteBatch.Draw(buttons, levelDst, levelSrc, levelColor);
                    spriteBatch.Draw(buttons, levelDst, levelSrc, blinkColor);

                    //Draw the way
                    if (i > 0)
                    {
                        Vector2 p1             = levelPositionOnMap[i - 1];
                        Vector2 p2             = pointsBezier[i - 1][0];
                        Vector2 p3             = pointsBezier[i - 1][1];
                        Vector2 p4             = levelPositionOnMap[i];
                        int     requiredPoints = (int)(Math.Sqrt(Math.Pow(p4.X - p1.X, 2) + Math.Pow(p4.Y - p1.Y, 2)) / 50) + 2; //evaluate number of point to show depending of the distance between p1 an p4

                        Rectangle wayDst = waySrc;

                        for (int x = 1; x < requiredPoints; x++)
                        {
                            float t = (float)x / (float)(requiredPoints); //quadratic bezier equation need a parameter t, with 0<=t<=1
                            if (t <= 1)
                            {
                                wayDst.X = (int)((Math.Pow(1 - t, 3)) * p1.X + 3 * (Math.Pow(1 - t, 2)) * t * p2.X + 3 * (1 - t) * t * t * p3.X + t * t * t * p4.X) - wayDst.Width / 2;
                                wayDst.Y = (int)((Math.Pow(1 - t, 3)) * p1.Y + 3 * (Math.Pow(1 - t, 2)) * t * p2.Y + 3 * (1 - t) * t * t * p3.Y + t * t * t * p4.Y) - wayDst.Height / 2;

                                spriteBatch.Draw(buttons, wayDst, waySrc, Color.White, 0.0f, new Vector2(waySrc.Width / 2, waySrc.Height / 2), SpriteEffects.None, 1.0f);
                            }
                        }
                    }
                }
            }

            //Draw little ship
            spriteBatch.Draw(buttons, shipDst, shipSrc, Color.White, 0.0f, Vector2.Zero, shipFlip, 1.0f);

            //Draw selected world information

            Vector2 v = levelPositionOnMap[selectedIndex];

            Color whiteColor = Color.White * alphaPostIt;

            spriteBatch.Draw(buttons, postitDst, postitSrc, whiteColor);

            //Play and back Buttonfor PC
            if (TGPAContext.Instance.Player1.IsPlayingOnWindows())
            {
                //Launch game
                if (focus == LevelSelectionScreenButton.Play)
                {
                    Rectangle srcBis = arrowSrc;
                    srcBis.Y += srcBis.Height;
                    spriteBatch.Draw(buttons, playDst, srcBis, whiteColor, 0.0f, Vector2.Zero, SpriteEffects.FlipHorizontally, 1.0f);
                }
                else
                {
                    spriteBatch.Draw(buttons, playDst, arrowSrc, whiteColor, 0.0f, Vector2.Zero, SpriteEffects.FlipHorizontally, 1.0f);
                }

                //Back
                if (focus == LevelSelectionScreenButton.Back)
                {
                    Rectangle srcBis = arrowSrc;
                    srcBis.Y += srcBis.Height;
                    spriteBatch.Draw(buttons, backDst, srcBis, whiteColor);
                }
                else
                {
                    spriteBatch.Draw(buttons, backDst, arrowSrc, whiteColor);
                }
            }

            spriteBatch.End();

            //Play and back text for PC
            if (TGPAContext.Instance.Player1.IsPlayingOnWindows())
            {
                if (alphaPostIt > 0.8f)
                {
                    playDst.X = 290;
                    playDst.Y = 485;

                    backDst.X = 90;
                    backDst.Y = 555;

                    string playText = "Play";
                    string backText = "Back to title";

                    TGPAContext.Instance.TextPrinter.Color = Color.Navy;
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, playDst.X - (playText.Length * 12), playDst.Y + 5, playText);
                    TGPAContext.Instance.TextPrinter.Color = Color.Red;
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, backDst.X + backDst.Width, backDst.Y + 5, backText);
                    TGPAContext.Instance.TextPrinter.Color = Color.Black;
                }
            }

            TGPAContext.Instance.TextPrinter.Color = (Color.Black * alphaPostIt);

            TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 20, postitDst.Y + 100, "Level " + overview.Level);
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 20, postitDst.Y + 130, overview.Name);

            TGPAContext.Instance.TextPrinter.Size = 0.8f;

            for (int i = 0; i < this.levelParts.Length; i++)
            {
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 25, postitDst.Y + 170 + (80 * i), LocalizedStrings.GetString("LevelSelectionScreenPart") + " " + i + " - " + LocalizedStrings.GetString("LevelSelectionScreenBestScore"));

                ScoreLine bestScore = TGPAContext.Instance.Saver.GetBestScoreForLevel(this.levelParts[i], this.scoreType);
                if (bestScore.Score > 0)
                {
                    TGPAContext.Instance.TextPrinter.Color = (Color.Blue * alphaPostIt);
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 25, postitDst.Y + 190 + (80 * i), bestScore.ToString());
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 105, postitDst.Y + 210 + (80 * i), bestScore.GetDifficultyString());
                }
                else
                {
                    TGPAContext.Instance.TextPrinter.Color = (Color.Red * alphaPostIt);
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, postitDst.X + 25, postitDst.Y + 190 + (80 * i), LocalizedStrings.GetString("LevelSelectionScreenNoHighscore"));
                }

                TGPAContext.Instance.TextPrinter.Color = (Color.Black * alphaPostIt);
            }

            TGPAContext.Instance.TextPrinter.Color = Color.Black;
            TGPAContext.Instance.TextPrinter.Size  = 1f;


            if (launchLevel == false)
            {
                //Buttons
                //***************************************************************************
                if (TGPAContext.Instance.Player1.IsPlayingOnWindows() == false)
                {
                    TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Move", TGPAContext.Instance.Player1.Device.Type, 535, 630);
                    TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Confirm", TGPAContext.Instance.Player1.Device.Type, 535, 700);
                    TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Cancel", TGPAContext.Instance.Player1.Device.Type, 150, 630);

                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, 595, 650, LocalizedStrings.GetString("LevelSelectionScreenMove"));
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, 595, 700, LocalizedStrings.GetString("LevelSelectionScreenPressA"));
                    TGPAContext.Instance.TextPrinter.Write(spriteBatch, 205, 650, LocalizedStrings.GetString("LevelSelectionScreenPressB"));
                }

                TGPAContext.Instance.TextPrinter.Write(spriteBatch, 170, 700, LocalizedStrings.GetString(this.scoreType == ScoreType.Single ? "SwitchToScoreTypeCoop" : "SwitchToScoreTypeSingle"));
                TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Plus", TGPAContext.Instance.Player1.Device.Type, 115, 690);
            }

            if (fadeoutAlpha > 0f)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(background, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), null, (Color.Black * fadeoutAlpha));
                spriteBatch.End();
            }

            if (launchLevel)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(TGPAContext.Instance.HudTex, rectDst, TGPAContext.Instance.PaperRect, Color.White);
                spriteBatch.End();


                TGPAContext.Instance.TextPrinter.Write(spriteBatch, rectDst.X + 50, rectDst.Y + 60, LocalizedStrings.GetString("Difficulty"));

                difficultyListControl.Draw(spriteBatch);

                TGPAContext.Instance.TextPrinter.Size = 0.8f;
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, rectDst.X + 40, rectDst.Y + 125, LocalizedStrings.GetString((Difficulty)this.difficultyListControl.FocusedElement.Value + "Desc"), 50);
                TGPAContext.Instance.TextPrinter.Size = 1f;

                TGPAContext.Instance.TextPrinter.Color = Color.White;
                TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Back", TGPAContext.Instance.Player1.Device.Type, 350, 550);
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, 400, 560, LocalizedStrings.GetString("CancelLaunchLevel"));
                TGPAContext.Instance.TextPrinter.Color = Color.Black;
            }
        }
Пример #19
0
        private async void DoAuthFlow(LoginOptions loginOptions)
        {
            loginOptions.DisplayType = LoginOptions.DefaultStoreDisplayType;
            var loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
            var callbackUri = new Uri(loginOptions.CallbackUrl);

            OAuth2.ClearCookies(loginOptions);
            WebAuthenticationResult webAuthenticationResult;

            try
            {
                PlatformAdapter.SendToCustomLogger(
                    "AccountPage.DoAuthFlow - calling WebAuthenticationBroker.AuthenticateAsync()", LoggingLevel.Verbose);
                if (loginOptions.UseTwoParamAuthAsyncMethod)
                {
                    webAuthenticationResult =
                        await
                        WebAuthenticationBroker.AuthenticateAsync(loginOptions.BrokerOptions, loginUri);
                }
                else
                {
                    webAuthenticationResult =
                        await
                        WebAuthenticationBroker.AuthenticateAsync(loginOptions.BrokerOptions, loginUri, callbackUri);
                }
            }
            // If a bad URI was passed in the user is shown an error message by the WebAuthenticationBroken, when user
            // taps back arrow we are then thrown a FileNotFoundException, but since user already saw error message we
            // should just swallow that exception
            catch (FileNotFoundException)
            {
                SetupAccountPage();
                return;
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger("AccountPage.StartLoginFlow - Exception occured", LoggingLevel.Critical);
                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Critical);

                DisplayErrorDialog(LocalizedStrings.GetString("generic_error"));
                SetupAccountPage();
                return;
            }

            if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(webAuthenticationResult.ResponseData);
                if (!String.IsNullOrWhiteSpace(responseUri.Query) &&
                    responseUri.Query.IndexOf("error", StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    DisplayErrorDialog(LocalizedStrings.GetString("generic_authentication_error"));
                    SetupAccountPage();
                }
                else
                {
                    try
                    {
                        AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1));
                        PlatformAdapter.SendToCustomLogger("AccountPage.DoAuthFlow - calling EndLoginFlow()", LoggingLevel.Verbose);
                        await PlatformAdapter.Resolve <IAuthHelper>().EndLoginFlow(loginOptions, authResponse);
                    }
                    catch (Exception ex)
                    {
                        DisplayErrorDialog($"Login failed: { ex.Message }");
                        SetupAccountPage();
                    }
                }
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                SetupAccountPage();
            }
            else
            {
                DisplayErrorDialog(LocalizedStrings.GetString("generic_error"));
                SetupAccountPage();
            }
        }
 public string GetDifficultyString()
 {
     return(" (" + LocalizedStrings.GetString(this.Difficulty.ToString()) + ")");
 }
Пример #21
0
        /// <summary>
        /// Mapping users and roles to view model
        /// </summary>
        /// <returns></returns>
        private async Task <UserManageViewModel> GetData()
        {
            var license = await LicenseMapper.GetLicense();

            ViewBag.ActivatedUsersCount = license?.UsersPool?.Count ?? 0;
            ViewBag.ActivatedUsersMax   = license?.NumberOfUsers ?? 0;

            var(Users, Roles, Languages, Teams) = await _applicationUsersService.GetUsersAndRolesAndLanguages();

            UserManageViewModel userManageModel = new UserManageViewModel();
            var users = Users.Select(u =>
            {
                var rolesInfo = GetRolesForUser(u, Roles);
                return(new UserViewModel
                {
                    UserId = u.UserId,
                    DefaultLanguageCode = u.DefaultLanguageCode,
                    Username = u.Username,
                    Firstname = u.Firstname,
                    Name = u.Name,
                    Email = u.Email,
                    PhoneNumber = u.PhoneNumber,
                    Roles = rolesInfo.Item1,
                    RolesId = rolesInfo.Item2,
                    Tenured = u.Tenured,
                    TenuredDisplay = u.Tenured.HasValue? u.Tenured.Value? LocalizedStrings.GetString("Tenant") : LocalizedStrings.GetString("Interim") : "",
                    Teams = u.Teams.Select(t => t.Name).ToList(),
                    IsActive = license?.UsersPool?.Contains(u.UserId) == true ? true : false
                });
            });
            var allRoles = Roles.ToList();
            var roleList = allRoles.Select(r => new RoleViewModel
            {
                RoleCode   = r.RoleCode,
                ShortLabel = r.ShortLabel
            });
            var allLanguages = Languages.ToList();
            var languageList = allLanguages.Select(l => new LanguageViewModel
            {
                LanguageCode = l.LanguageCode,
                Label        = l.Label
            });

            userManageModel.RolesViewModel = roleList.ToList();
            userManageModel.UsersViewModel = users.ToList();

            userManageModel.LanguagesViewModel = languageList.ToList();
            return(userManageModel);
        }
Пример #22
0
        /// <summary>
        /// Insert user information
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task <ActionResult> InsertUser(CRUDModel <UserViewModel> user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var message = string.Join(" | ", ModelState.Values
                                              .SelectMany(v => v.Errors)
                                              .Select(e => e.ErrorMessage));
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, message));
                }

                if (user.Value.Roles == null || !user.Value.Roles.Any() || user.Value.Roles.Any(n => n == ""))
                {
                    throw new Exception(LocalizedStrings.GetString("AskSelectRole"));
                }

                var(Users, Roles, Languages, Teams) = await _applicationUsersService.GetUsersAndRolesAndLanguages();

                var newUser = new User
                {
                    Username            = user.Value.Username,
                    DefaultLanguageCode = user.Value.DefaultLanguageCode,
                    Tenured             = user.Value.Tenured,
                    Firstname           = user.Value.Firstname,
                    Name                 = user.Value.Name,
                    Email                = user.Value.Email,
                    PhoneNumber          = user.Value.PhoneNumber,
                    CreationDate         = DateTime.Now,
                    LastModificationDate = DateTime.Now
                };
                //Add password to user
                if (user.Value.Password != null)
                {
                    newUser.Password = new System.Security.Cryptography.SHA1CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(user.Value.Password));
                }

                foreach (var role in user.Value.Roles[0].Split(','))
                {
                    if (string.IsNullOrWhiteSpace(role))
                    {
                        continue;
                    }
                    newUser.Roles.Add(Roles.First(u => u.RoleCode == role));
                }

                IEnumerable <User> addUser = new[] { newUser };
                await _applicationUsersService.SaveUsers(addUser);

                var users = await GetData();

                var createdUser = users.UsersViewModel.First(u => u.Username == newUser.Username);
                user.Value.UserId         = createdUser.UserId;
                user.Key                  = user.Value.UserId;
                user.KeyColumn            = "UserId";
                user.Value.Roles          = createdUser.Roles;
                user.Value.Teams          = createdUser.Teams;
                user.Value.TenuredDisplay = createdUser.Tenured.HasValue ? createdUser.Tenured.Value ? LocalizedStrings.GetString("Tenant") : LocalizedStrings.GetString("Interim") : "";
                return(Json(user.Value, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Пример #23
0
        public async Task <ActionResult> UpdateUserStatus(List <int> userIds, bool status)
        {
            if (Request.Cookies.AllKeys.Contains("token"))
            {
                _apiHttpClient.Token = Request.Cookies["token"].Value;
            }

            try
            {
                var license = await LicenseMapper.GetLicense();

                if (license.Status == WebLicenseStatus.NotFound)
                {
                    return(Json(new { Success = false, message = LocalizedStrings.GetString("Web_Controller_User_LicenseDoesntExist") }, JsonRequestBehavior.AllowGet));
                }
                else if (license.Status == WebLicenseStatus.MachineHashMismatch)
                {
                    return(Json(new { Success = false, message = LocalizedStrings.GetString("Web_Controller_User_LicenseMismatchesMachine") }, JsonRequestBehavior.AllowGet));
                }
                //Check user maximum limit
                if (status == true)
                {
                    if (license.UsersPool.Count >= license.NumberOfUsers)
                    {
                        return(Json(new { Success = false, message = LocalizedStrings.GetString("Web_Controller_User_OverageOfUsers") }, JsonRequestBehavior.AllowGet));
                    }
                }
                //Admin cannot deactivate his own Active status
                if (status == false && userIds.Any(u => u == int.Parse(System.Web.HttpContext.Current.User.Identity.GetUserId())))
                {
                    return(Json(new { Success = false, message = LocalizedStrings.GetString("Web_Controller_User_CantSelfDeactivate") }, JsonRequestBehavior.AllowGet));
                }

                if (status)
                {
                    foreach (var id in userIds)
                    {
                        license.UsersPool.Add(id);
                    }
                }
                else
                {
                    await CancelAndDisableUserRelatedActivity(userIds);

                    foreach (var id in userIds)
                    {
                        license.UsersPool.Remove(id);
                    }
                }

                await LicenseMapper.SetLicense(license);

                var users = await GetData();

                var updateUsers = users.UsersViewModel;

                return(Json(new { Success = true, Users = updateUsers, activatedCount = license.UsersPool.Count() }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                var message = string.Join(" | ", ModelState.Values
                                          .SelectMany(v => v.Errors)
                                          .Select(e => e.ErrorMessage));
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, ex.Message));
            }
        }
Пример #24
0
        public async Task <ActionResult> SaveDefault()
        {
            if (Request.Cookies.AllKeys.Contains("token"))
            {
                _apiHttpClient.Token = Request.Cookies["token"].Value;
            }

            HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
            var uploadedLicenseFile = System.Web.HttpContext.Current.Request.Files["uploadLicense"];

            var name    = System.Web.HttpContext.Current.Request.Headers["name"];
            var company = System.Web.HttpContext.Current.Request.Headers["company"];
            var email   = System.Web.HttpContext.Current.Request.Headers["email"];
            await LicenseMapper.SetUserInformation(name, company, email);

            ProductLicenseInfo licenseInfo = null;

            try
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader(uploadedLicenseFile.InputStream))
                {
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ProductLicenseInfo));
                    licenseInfo = (ProductLicenseInfo)serializer.Deserialize(reader);
                }
            }
            catch (Exception e)
            {
                _traceManager.TraceError(e, e.Message);
                HttpContext.Response.StatusDescription = $"{HttpStatusCode.BadRequest}";
                return(Content(LocalizedStrings.GetString("Web_Controller_License_CantCheckLicense")));
            }

            try
            {
                WebProductLicense license = await LicenseMapper.ActivateLicense(licenseInfo);

                if (license.Status == WebLicenseStatus.OverageOfUsers)
                {
                    HttpContext.Response.StatusDescription = $"{HttpStatusCode.ExpectationFailed}";
                    return(Content(LocalizedStrings.GetStringFormat(license.StatusReason, license.StatusReasonParams?.Select(_ => _.ToString()).ToArray())));
                }
                // Comment this part if you want to be able to save a expired license
                if (license.Status != WebLicenseStatus.Licensed && license.Status != WebLicenseStatus.TrialVersion)
                {
                    HttpContext.Response.StatusDescription = $"{HttpStatusCode.Forbidden}";
                    return(Content(LocalizedStrings.GetStringFormat(license.StatusReason, license.StatusReasonParams?.Select(_ => _.ToString()).ToArray())));
                }

                //First initialize of license, set UserPool to current Admin
                if (license.UsersPool.Count == 0)
                {
                    //Get current user id - Admin
                    var adminId = int.Parse(System.Web.HttpContext.Current.User.Identity.GetUserId());
                    license.UsersPool.Add(adminId);
                }
                await LicenseMapper.SetLicense(license);

                // TODO : Update license infos from the secured storage
            }
            catch (Exception e)
            {
                _traceManager.TraceError(e, e.Message);
                HttpContext.Response.StatusDescription = $"{HttpStatusCode.BadRequest}";
                return(Content(LocalizedStrings.GetString("Web_Controller_License_LicenseInvalid")));
            }

            HttpContext.Response.StatusDescription = $"{HttpStatusCode.OK}";
            return(Content($"{HttpStatusCode.OK}"));
        }
Пример #25
0
        public async Task <LicenseViewModel> GetData()
        {
            if (Request.Cookies.AllKeys.Contains("token"))
            {
                _apiHttpClient.Token = Request.Cookies["token"].Value;
            }

            var model = new LicenseViewModel
            {
                //Prepare LicenseInfo
                LicenseInfo = new LicenseInfoViewModel
                {
                    ActivatedUsers = new List <UserViewModel>()
                }
            };

            //User information
            var userProvider = await LicenseMapper.GetUserInformation();

            if (userProvider != null)
            {
                model.LicenseInfo.Name    = userProvider.Username;
                model.LicenseInfo.Company = userProvider.Company;
                model.LicenseInfo.Email   = userProvider.Email;
            }

            var license = await LicenseMapper.GetLicense();

            if (license.Status != WebLicenseStatus.NotFound && license.Status != WebLicenseStatus.MachineHashMismatch)
            {
                model.LicenseFile                            = license;
                model.LicenseInfo.LicenseFile                = license;
                model.LicenseInfo.LicenseMaxActivateUser     = license.NumberOfUsers;
                model.LicenseInfo.LicenseTotalActivatedUsers = license.UsersPool.Count;
                model.LicenseInfo.ExpiredDate                = license.ActivationDate.AddDays(license.TrialDays);

                model.LicenseInfo.Status       = license.Status;
                model.LicenseInfo.StatusReason = license.StatusReason;

                //To display license information
                if ((model.LicenseInfo.Status != WebLicenseStatus.Licensed && DateTime.Now > model.LicenseInfo.ExpiredDate) || model.LicenseInfo.Status == WebLicenseStatus.Expired)
                {
                    model.LicenseInfo.LicenseInformation = LocalizedStrings.GetString("Web_Controller_License_InfoLicenseExpired");
                }
                else if (license.Status == WebLicenseStatus.OverageOfUsers)
                {
                    model.LicenseInfo.LicenseInformation = LocalizedStrings.GetString("Web_Controller_License_InfoOverageOfUsers");
                }
                else
                {
                    model.LicenseInfo.LicenseInformation = LocalizedStrings.GetString("Web_Controller_License_InfoLicenseValid");
                }

                if (model.LicenseInfo.LicenseTotalActivatedUsers != 0)
                {
                    //collect activated users
                    var usersRolesLanguages = await _applicationUsersService.GetUsersAndRolesAndLanguages();

                    var users = usersRolesLanguages.Users;
                    model.LicenseInfo.ActivatedUsers = license.UsersPool
                                                       .Where(userId => users.Any(_ => _.UserId == userId))
                                                       .Select(userId => users.Single(_ => _.UserId == userId))
                                                       .Select(user => new UserViewModel
                    {
                        UserId   = user.UserId,
                        FullName = user.FullName
                    }).ToList();
                }
            }

            model.LicenseInfo.IDMachine = await LicenseMapper.GetMachineHash();

            model.LicenseInfo.Status       = license.Status;
            model.LicenseInfo.StatusReason = LocalizedStrings.GetStringFormat(license.StatusReason, license.StatusReasonParams?.Select(_ => _.ToString()).ToArray());

            //Email to kprocess
            model.LicenseInfo.EmailTarget = ActivationConstants.KProcessEmail;

            return(model);
        }
Пример #26
0
        public void Draw(TGPASpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            spriteBatch.Draw(videoBackground, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), Color.White);
            spriteBatch.End();

            if (playVideo)
            {
                TGPAContext.Instance.TextPrinter.Color = Color.White;

                if (this.videoPlayer.State == MediaState.Playing)
                {
                    //Display video
                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                    spriteBatch.Draw(this.videoPlayer.GetTexture(), this.videoDst, Color.White);
                    spriteBatch.End();
                }
            }
            else if (playCredits)
            {
                TGPAContext.Instance.TextPrinter.Color = Color.Black;

                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                if (currentPageIndex > 0)
                {
                    spriteBatch.Draw(backgrounds[currentPageIndex - 1], bgDst, Color.White);
                }

                spriteBatch.Draw(backgrounds[currentPageIndex], bgDst, new Color(Color.White.R, Color.White.G, Color.White.B, transitionAlpha));

                spriteBatch.End();

                this.pages[currentPageIndex].Draw(spriteBatch);
            }

            if (playVideo)
            {
                TGPAContext.Instance.TextPrinter.Color = Color.White;
            }
            else
            {
                TGPAContext.Instance.TextPrinter.Color = Color.Navy;
            }
            TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Back", TGPAContext.Instance.Player1.Device.Type, new Vector2(750, TGPAContext.Instance.ScreenHeight - 110));
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, new Vector2(800, TGPAContext.Instance.ScreenHeight - 100), LocalizedStrings.GetString("CreditsScreenLeave"));

            TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Confirm", TGPAContext.Instance.Player1.Device.Type, new Vector2(750, TGPAContext.Instance.ScreenHeight - 55));
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, new Vector2(800, TGPAContext.Instance.ScreenHeight - 45), LocalizedStrings.GetString("CreditsScreenNext"));

            TGPAContext.Instance.TextPrinter.Color = Color.Black;
        }
Пример #27
0
        public void Draw(TGPASpriteBatch spriteBatch)
        {
            //Display ad
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            spriteBatch.Draw(TGPAContext.Instance.NullTex, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), Color.White);

            bool      specialCenter = false;
            Rectangle inboundsDst   = TGPAContext.Instance.TitleSafeArea;

            if ((inboundsDst.Width > 1024) || (inboundsDst.Height > 768))
            {
                specialCenter = true;
            }

            if (specialCenter)
            {
                Rectangle dst = new Rectangle(0, 0, 1024, 768);
                dst.X = TGPAContext.Instance.ScreenWidth / 2 - dst.Width / 2;
                dst.Y = TGPAContext.Instance.ScreenHeight / 2 - dst.Height / 2;

                spriteBatch.Draw(background, dst, Color.White);
            }
            else
            {
                spriteBatch.Draw(background, inboundsDst, Color.White);
            }

            if (alpha > 0f)
            {
                spriteBatch.Draw(TGPAContext.Instance.NullTex, new Rectangle(0, 0, TGPAContext.Instance.ScreenWidth, TGPAContext.Instance.ScreenHeight), Color.Black * alpha);
            }

            spriteBatch.End();

#if XBOX
            TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Plus", TGPAContext.Instance.Player1.Device.Type, new Vector2(250, 700));
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, new Vector2(300, 700), LocalizedStrings.GetString("Buy"));
#endif
        }
        /// <summary>
        /// Draw a sleeping cat + map information
        /// </summary>
        /// <param name="spriteBatch"></param>
        public void Draw(TGPASpriteBatch spriteBatch)
        {
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            spriteBatch.Draw(TGPAContext.Instance.NullTex, backgroundDst, null, Color.White);
            spriteBatch.End();

            //Draw background
            if ((this.previewBG1 != null) && (this.previewBG1Fadeout > 0.0f))
            {
                if (this.previewBG1.SpriteTexture != null)
                {
                    Color c = Color.White * previewBG1Fadeout;

                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                    spriteBatch.Draw(this.previewBG1.SpriteTexture, backgroundDst, null, c);
                    spriteBatch.End();
                }
            }

            if ((this.previewBG2 != null) && (this.previewBG2Fadeout > 0.0f))
            {
                if (this.previewBG2.SpriteTexture != null)
                {
                    Color c = (Color.White * previewBG2Fadeout);

                    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                    spriteBatch.Draw(this.previewBG2.SpriteTexture, backgroundDst, null, c);
                    spriteBatch.End();
                }
            }

            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            spriteBatch.Draw(texture, backgroundDst, background, Color.White);
            spriteBatch.End();

            Rectangle rect2 = new Rectangle(170, 195, 685, 220);


            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
            spriteBatch.Draw(TGPAContext.Instance.NullTex, rect2, Color.White * 0.55f);
            spriteBatch.End();

            //display name and description
            Vector2 textPosition = new Vector2(500, 85);

            textPosition.X -= (overview.Name.Length / 2) * 10;

            TGPAContext.Instance.TextPrinter.Color = Color.Black;
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, textPosition.X, textPosition.Y, overview.Name, 50);

            textPosition = new Vector2(185, 180);
            TGPAContext.Instance.TextPrinter.Size = 1f;
            TGPAContext.Instance.TextPrinter.Write(spriteBatch, textPosition.X, textPosition.Y, overview.Description, 45);


            Rectangle dst = currentloading;

            dst.X = TGPAContext.Instance.ScreenWidth / 2 - dst.Width / 2;
            dst.Y = (2 * TGPAContext.Instance.ScreenHeight / 3 - dst.Height / 2);

            if (!TGPAContext.Instance.MapLoaded)
            {
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(texture, dst, currentloading, Color.White);
                spriteBatch.End();
            }
            else
            {
                Rectangle rect3 = new Rectangle(410, 470, 190, 55);

                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
                spriteBatch.Draw(TGPAContext.Instance.NullTex, rect3, Color.White * 0.45f);
                spriteBatch.End();

                dst.Y -= dst.Height;

                TGPAContext.Instance.ButtonPrinter.Draw(spriteBatch, "#Confirm", TGPAContext.Instance.Player1.Device.Type, new Vector2((TGPAContext.Instance.ScreenWidth / 2) - 100, dst.Y + dst.Height + 50), Color.White);
                TGPAContext.Instance.TextPrinter.Write(spriteBatch, TGPAContext.Instance.ScreenWidth / 2 - 50, dst.Y + dst.Height + 50, LocalizedStrings.GetString("LevelSelectionScreenPressStart"), 64);
            }
        }
Пример #29
0
        private void SetupAccountPage()
        {
            ResourceLoader   loader       = ResourceLoader.GetForCurrentView("Salesforce.SDK.Core/Resources");
            SalesforceConfig config       = SDKManager.ServerConfiguration;
            bool             titleMissing = true;

            if (!String.IsNullOrWhiteSpace(config.ApplicationTitle) && config.IsApplicationTitleVisible)
            {
                ApplicationTitle.Visibility = Visibility.Visible;
                ApplicationTitle.Text       = config.ApplicationTitle;
                titleMissing = false;
            }
            else
            {
                ApplicationTitle.Visibility = Visibility.Collapsed;
            }

            if (config.LoginBackgroundLogo != null)
            {
                if (ApplicationLogo.Items != null)
                {
                    ApplicationLogo.Items.Clear();
                    ApplicationLogo.Items.Add(config.LoginBackgroundLogo);
                }
                if (titleMissing)
                {
                    var padding = new Thickness(10, 24, 10, 24);
                    ApplicationLogo.Margin = padding;
                }
            }

            // set background from config
            if (config.LoginBackgroundColor != null)
            {
                var background = new SolidColorBrush((Color)config.LoginBackgroundColor);
                PageRoot.Background = background;
                Background          = background;
                // ServerFlyoutPanel.Background = background;
                //  AddServerFlyoutPanel.Background = background;
            }

            // set foreground from config
            if (config.LoginForegroundColor != null)
            {
                var foreground = new SolidColorBrush((Color)config.LoginForegroundColor);
                Foreground = foreground;
                ApplicationTitle.Foreground   = foreground;
                LoginToSalesforce.Foreground  = foreground;
                LoginToSalesforce.BorderBrush = foreground;
                ChooseConnection.Foreground   = foreground;
                ChooseConnection.BorderBrush  = foreground;
            }

            if (Accounts == null || Accounts.Length == 0)
            {
                _currentState = SingleUserViewState;
                SetLoginBarVisibility(Visibility.Collapsed);
                VisualStateManager.GoToState(this, SingleUserViewState, true);
            }
            else
            {
                _currentState = MultipleUserViewState;
                SetLoginBarVisibility(Visibility.Visible);
                ListTitle.Text = loader.GetString("select_account");
                VisualStateManager.GoToState(this, MultipleUserViewState, true);
            }
            ListboxServers.ItemsSource     = Servers;
            AccountsList.ItemsSource       = Accounts;
            ServerFlyout.Opening          += ServerFlyout_Opening;
            ServerFlyout.Closed           += ServerFlyout_Closed;
            AddServerFlyout.Opened        += AddServerFlyout_Opened;
            AddServerFlyout.Closed        += AddServerFlyout_Closed;
            AccountsList.SelectionChanged += accountsList_SelectionChanged;
            ListboxServers.SelectedValue   = null;
            HostName.PlaceholderText       = LocalizedStrings.GetString("name");
            HostAddress.PlaceholderText    = LocalizedStrings.GetString("address");
            AddConnection.Visibility       = (SDKManager.ServerConfiguration.AllowNewConnections
                ? Visibility.Visible
                : Visibility.Collapsed);
        }
        private async void DoAuthFlow(LoginOptions loginOptions)
        {
            loginOptions.DisplayType = LoginOptions.DefaultStoreDisplayType;
            var loginUri    = new Uri(OAuth2.ComputeAuthorizationUrl(loginOptions));
            var callbackUri = new Uri(loginOptions.CallbackUrl);
            await SDKServiceLocator.Get <IAuthHelper>().ClearCookiesAsync(loginOptions);

            WebAuthenticationResult webAuthenticationResult = null;
            var hasWebAuthErrors = false;

            try
            {
                LoggingService.Log("Launching web authentication broker", LoggingLevel.Verbose);

                webAuthenticationResult =
                    await
                    WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, loginUri, callbackUri);
            }
            // If a bad URI was passed in the user is shown an error message by the WebAuthenticationBroken, when user
            // taps back arrow we are then thrown a FileNotFoundException, but since user already saw error message we
            // should just swallow that exception
            catch (FileNotFoundException)
            {
                SetupAccountPage();
                return;
            }
            catch (Exception ex)
            {
                LoggingService.Log("Exception occurred during login flow", LoggingLevel.Critical);
                LoggingService.Log(ex, LoggingLevel.Critical);

                hasWebAuthErrors = true;
            }

            if (hasWebAuthErrors)
            {
                await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error"));

                SetupAccountPage();
                return;
            }

            if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                var responseUri = new Uri(webAuthenticationResult.ResponseData);
                if (!String.IsNullOrWhiteSpace(responseUri.Query) &&
                    responseUri.Query.IndexOf("error", StringComparison.CurrentCultureIgnoreCase) >= 0)
                {
                    await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_authentication_error"));

                    SetupAccountPage();
                }
                else
                {
                    AuthResponse authResponse = OAuth2.ParseFragment(responseUri.Fragment.Substring(1));

                    await SDKServiceLocator.Get <IAuthHelper>().OnLoginCompleteAsync(loginOptions, authResponse);
                }
            }
            else if (webAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                SetupAccountPage();
            }
            else
            {
                await DisplayErrorDialogAsync(LocalizedStrings.GetString("generic_error"));

                SetupAccountPage();
            }
        }