/// <summary> /// Singleton 응용 프로그램 개체를 초기화합니다. 이것은 실행되는 작성 코드의 첫 번째 /// 줄이며 따라서 main() 또는 WinMain()과 논리적으로 동일합니다. /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; /*** Injecting objects to public static instances ***/ // App MobileService = new MobileServiceClient( "https://pinthecloud.azure-mobile.net/", "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23" ); ApplicationSessions = new WSApplicationSessions(); ApplicationSettings = new WSApplicationSettings(); // Manager SpotManager = new SpotManager(); Geolocator = new Geolocator(); BlobStorageManager = new BlobStorageManager(); LocalStorageManager = new LocalStorageManager(); OneDriveManager = new OneDriveManager(); DropBoxManager = new DropboxManager(); GoogleDriveManger = new GoogleDriveManager(); ///////////////////////////////////////////////////// // This order will be displayed at every App Pages ///////////////////////////////////////////////////// StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager); StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager); StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger); Switcher.SetStorageToMainPlatform(); AccountManager = new AccountManager(); }
public void SaveAndLoad_Encrypted() { new LocalStorageManager("qwert").Add(new EcKeyPair(), this.storageName1); var result = new LocalStorageManager("qwert").GetAll <EcKeyPair>(this.storageName1); Assert.That(result.Count(), Is.EqualTo(1)); }
private void RefreshPublicKeys() { List <EcKeyPairInfoViewModel> loadedKeys; try { loadedKeys = new LocalStorageManager().GetAll <EcKeyPairInfoViewModel>(StorageNames.PublicKeys.ToString()).ToList(); } catch (Exception e) { loadedKeys = Enumerable.Empty <EcKeyPairInfoViewModel>().ToList(); } DispatcherHelper.CheckBeginInvokeOnUI(() => { this.PublicKeys = new ObservableCollection <EcKeyPairInfoViewModel>(loadedKeys); if (!loadedKeys.Any()) { this.PublicKeysNotAvailable = true; } this.PublicKeysIsBusy = false; }); }
public SubscriptionsPageViewModel([NotNull] INavigationService navigationService, [NotNull] ApiClient apiClient, [NotNull] AppSettingsService settingsService, [NotNull] TelemetryClient telemetryClient, [NotNull] TileManager tileManager, [NotNull] LocalStorageManager localStorageManager, [NotNull] SubscriptionsManager subscriptionsManager, [NotNull] NetworkManager networkManager) { if (navigationService == null) { throw new ArgumentNullException("navigationService"); } if (apiClient == null) { throw new ArgumentNullException("apiClient"); } if (settingsService == null) { throw new ArgumentNullException("settingsService"); } if (telemetryClient == null) { throw new ArgumentNullException("telemetryClient"); } if (tileManager == null) { throw new ArgumentNullException("tileManager"); } if (localStorageManager == null) { throw new ArgumentNullException("localStorageManager"); } if (subscriptionsManager == null) { throw new ArgumentNullException("subscriptionsManager"); } if (networkManager == null) { throw new ArgumentNullException("networkManager"); } _navigationService = navigationService; _apiClient = apiClient; _settingsService = settingsService; _telemetryClient = telemetryClient; _tileManager = tileManager; _localStorageManager = localStorageManager; _subscriptionsManager = subscriptionsManager; _networkManager = networkManager; _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher; Application.Current.Resuming += Application_Resuming; _networkManager.NetworkChanged += _networkManager_NetworkChanged; }
public void SaveAndLoad() { new LocalStorageManager().Add(new EcKeyPair(), this.storageName1); Console.Out.WriteLine(File.ReadAllText(LocalStorageManager.GetStoragePath(false))); var result = new LocalStorageManager().GetAll <EcKeyPair>(this.storageName1); Assert.That(result.Count(), Is.EqualTo(1)); }
public void IsJson() { var localStorageManager = new LocalStorageManager(); localStorageManager.Add(new EcKeyPair(), this.storageName1); var content = File.ReadAllText(localStorageManager.StoragePath); Assert.DoesNotThrow(() => JsonConvert.DeserializeObject(content), "Can parse as json"); }
private async void GetAllFav() { var AllFav = LocalStorageManager.GetFavoriteRecipes(); foreach (int ele in AllFav) { lstRecipe.Add(await SpoonacularService.GetRecipeById(ele)); } BindingContext = this; }
public void UpdateLocalStorageRegistrationById_RegistrationNameNull() { LocalStorageManager localStorageManager = new LocalStorageManager(TestLocalStore); localStorageManager.UpdateRegistrationByRegistrationId(DefaultRegistrationId, null, DefaultChannelUri); StoredRegistrationEntry storedRegistrationEntry = localStorageManager.GetRegistration(Registration.NativeRegistrationName); Assert.AreEqual(storedRegistrationEntry.RegistrationName, Registration.NativeRegistrationName); Assert.AreEqual(storedRegistrationEntry.RegistrationId, DefaultRegistrationId); Assert.AreEqual(localStorageManager.PushHandle, DefaultChannelUri); localStorageManager.DeleteRegistrationByRegistrationId(DefaultRegistrationId); }
public LoginViewModel() { LocalStorageManager localStorage = new LocalStorageManager(); localStorage.GetUseridAndPassword(); if (localStorage.UserId != "") { Login(localStorage.UserId.Trim(), localStorage.Password.Trim(), true); } LoginRequired = true; }
private async void MenuLogout_OnClicked(object sender, EventArgs e) { var response = await DisplayAlert("Close the application", "Do you also want to logout from the application?", "Yes", "No"); if (response == true) { LocalStorageManager localStorage = new LocalStorageManager(); localStorage.ClearUseridAndPassword(); } DependencyService.Get <IApplicationUtilities>().CloseApp(); }
public void UpdateLocalStorageRegistrationById_RegistrationNameNull() { LocalStorageManager localStorageManager = new LocalStorageManager(TestLocalStore); localStorageManager.UpdateRegistrationByRegistrationId(DefaultRegistrationId, null, DefaultChannelUri); StoredRegistrationEntry storedRegistrationEntry = localStorageManager.GetRegistration(Registration.NativeRegistrationName); Assert.AreEqual(storedRegistrationEntry.RegistrationName, Registration.NativeRegistrationName); Assert.AreEqual(storedRegistrationEntry.RegistrationId, DefaultRegistrationId); Assert.AreEqual(localStorageManager.PushHandle, DefaultChannelUri); localStorageManager.DeleteRegistrationByRegistrationId(DefaultRegistrationId); }
private void button_Clicked(object sender, System.EventArgs e) { if (button.Text == "Add to fav") { LocalStorageManager.AddRecipeAsFavorite(Id); button.Text = "Remove to fav"; } else { LocalStorageManager.DeleteFavoriteRecipe(Id); button.Text = "Add to fav"; } }
public AzureADAuthRestResponse <AccessTokenClass, OAuthError> GetAccessToken_UserCredential(DatabaseManager dbmanager) { StateManager _stateIdManager = new StateManager(Config.LoggedInUserEmail, Config.Scope); LocalStorageManager _localStorage = new LocalStorageManager(Config, dbmanager); string _stateId = _stateIdManager.GetStateIdForCurrentUser(dbmanager); var resp = new AzureADAuthRestResponse <AccessTokenClass, OAuthError>(); // try to look for the available token first // if token not available then use authorize code to download it // if token expires then download new token using refresh token and store in database // if authorize token not available send send the response then auhorize token not available AccessTokenClass token = _localStorage.GetAccessToken(_stateId); if (token == null) { // check if authcode available AuthCode authcode = _localStorage.GetAuthCode(_stateId); if (authcode == null) { resp.OAuthError = OAuthErrors.AuthCodeNotFound; return(resp); } var res = GetAccessToken(authcode.code, TokenRetrivalType.AuthorizationCode); // check for any error in response if (res.IsSucceeded) { token = res.Result; _localStorage.AddAccessToken(_stateId, token); // add token into database } else { // send status to front page that it is not authorized, authorization code has expired resp.OAuthError = OAuthErrors.AuthCodeExpires; return(resp); } } // check for token's validity, if expires then recalculate from refresh token if (!validateToken(token)) { var res = GetAccessToken(token.RefreshToken, TokenRetrivalType.RefreshToken); // check for any error, if error is not present then cast to if (res.IsSucceeded) { token = res.Result; _localStorage.UpdateAccessToken(_stateId, token); } } resp.Result = token; resp.OAuthError = OAuthErrors.None; return(resp); }
private void CheckedFav(int id) { var allFav = LocalStorageManager.GetFavoriteRecipes(); Id = id; if (allFav.Contains(id)) { button.Text = "Remove to fav"; } else { button.Text = "Add to fav"; } }
protected override async Task OnInitializeAsync(IActivatedEventArgs args) { await base.OnInitializeAsync(args); _container.RegisterInstance <ISessionStateService>(SessionStateService); _container.RegisterInstance <INavigationService>(NavigationService); _container.RegisterType <ICredentialService, CredentialService>(new ContainerControlledLifetimeManager()); _container.RegisterType <NetworkManager>(new ContainerControlledLifetimeManager()); _container.RegisterType <TileManager>(new ContainerControlledLifetimeManager()); _container.RegisterInstance(_appSettingsService); _container.RegisterInstance(_telemetryClient); _container.RegisterType <ImageManager>(new ContainerControlledLifetimeManager()); var uri = new Uri("ms-appx:///Assets/ApiAuth.json"); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); var strData = await FileIO.ReadTextAsync(file); var data = JObject.Parse(strData); var appId = data["AppId"].ToString(); var appKey = data["AppKey"].ToString(); _apiClient = new ApiClient(appId, appKey); _container.RegisterInstance(_apiClient); var localStorageManager = new LocalStorageManager(_telemetryClient); localStorageManager.Init(); _container.RegisterInstance(localStorageManager); var savedStreamManager = new SavedStreamManager(localStorageManager); _container.RegisterInstance(savedStreamManager); _tagsManager = _container.Resolve <TagsManager>(); _container.RegisterInstance(_tagsManager); _tagsManager.ProcessQueue(); Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = _appSettingsService.DisplayCulture; var unityServiceLocator = new UnityServiceLocator(_container); ServiceLocator.SetLocatorProvider(() => unityServiceLocator); ViewModelLocationProvider.SetDefaultViewModelFactory(ViewModelFactory); ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(ViewModelTypeResolver); }
private void LoadState() { var state = new LocalStorageManager().GetAll <DataViewRowState>("SelectedPublicKeysAns1")?.FirstOrDefault(); if (state == null) { return; } var toSelect = this.PublicKeys.Where(model => state.SelectedPublicKeys.Any(bytes => bytes.SequenceEqual(model.KeyPairInfos.PublicKey.ToAns1()))).ToList(); toSelect.ForEach(model => model.IsSelected = true); CommandManager.InvalidateRequerySuggested(); }
public MainWindow() { InitializeComponent(); image.Source = new BitmapImage(new Uri($"/keks/kek-{kekn}.jpg", UriKind.Relative)); fsmanager = new LocalStorageManager(); visibleThreats = new List <Threat>(); if (fsmanager.FindLocalStorage(out threats)) { MessageBox.Show("Локальное хранилище найдено!", "Good news", MessageBoxButton.OK); for (int i = 0; i < PAGE_SIZE && i < threats.Count; i++) { visibleThreats.Add(threats[i]); } } else { var res = MessageBox.Show("Локальное хранилище не найдено!\nСкачать данные из официального банка данных угроз ФСТЭК России?", "Bad news", MessageBoxButton.YesNo); if (res == MessageBoxResult.Yes) { try { FileInfo file; fsmanager.DownloadFile(out file); if (fsmanager.TryParseThreats(file, out threats)) { for (int i = 0; i < PAGE_SIZE && i < threats.Count; i++) { visibleThreats.Add(threats[i]); } } } catch (WebException) { MessageBox.Show("Ошибка загрузки файла", "Bad News", MessageBoxButton.OK); return; } catch (UnauthorizedAccessException) { MessageBox.Show("Недостаточно прав для создания директории локального хранилища", "Bad News", MessageBoxButton.OK); return; } } } this.dataGrid.ItemsSource = visibleThreats; }
/// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override async void OnNavigatedTo(NavigationEventArgs e) { if (await LiveConnection.Instance.CreateConnectionAsync()) { var info = await SayHi(); var localStorageManager =new LocalStorageManager("UserInfo.xml"); await localStorageManager.SaveAsync(info); await UploadFile(); await DownloadFile(); var dlocalStorageManager = new LocalStorageManager("DownloadedUserInfo.xml"); var restoreData = await dlocalStorageManager.RestoreAsync<UserInformationModel>(); } }
public void Setup() { var tryDelete = new Action <string>(s => { if (File.Exists(s)) { File.Delete(s); } }); tryDelete(LocalStorageManager.GetStoragePath(false)); tryDelete(LocalStorageManager.GetStoragePath(true)); this.storageName1 = Guid.NewGuid().ToString(); this.storageName2 = Guid.NewGuid().ToString(); this.storageName3 = Guid.NewGuid().ToString(); }
public ListStreamPageViewModel([NotNull] ApiClient apiClient, [NotNull] INavigationService navigationService, [NotNull] TelemetryClient telemetryClient, [NotNull] TagsManager tagsManager, [NotNull] AppSettingsService settingsService, [NotNull] SavedStreamManager savedStreamManager, [NotNull] LocalStorageManager localStorageManager, [NotNull] NetworkManager networkManager) : base(apiClient, navigationService, telemetryClient, tagsManager, settingsService, savedStreamManager, localStorageManager, networkManager) { }
protected override async Task OnInitializeAsync(IActivatedEventArgs args) { await base.OnInitializeAsync(args); _container.RegisterInstance<ISessionStateService>(SessionStateService); _container.RegisterInstance<INavigationService>(NavigationService); _container.RegisterType<ICredentialService, CredentialService>(new ContainerControlledLifetimeManager()); _container.RegisterType<NetworkManager>(new ContainerControlledLifetimeManager()); _container.RegisterType<TileManager>(new ContainerControlledLifetimeManager()); _container.RegisterInstance(_appSettingsService); _container.RegisterInstance(_telemetryClient); _container.RegisterType<ImageManager>(new ContainerControlledLifetimeManager()); var uri = new Uri("ms-appx:///Assets/ApiAuth.json"); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); var strData = await FileIO.ReadTextAsync(file); var data = JObject.Parse(strData); var appId = data["AppId"].ToString(); var appKey = data["AppKey"].ToString(); _apiClient = new ApiClient(appId, appKey); _container.RegisterInstance(_apiClient); var localStorageManager = new LocalStorageManager(_telemetryClient); localStorageManager.Init(); _container.RegisterInstance(localStorageManager); var savedStreamManager = new SavedStreamManager(localStorageManager); _container.RegisterInstance(savedStreamManager); _tagsManager = _container.Resolve<TagsManager>(); _container.RegisterInstance(_tagsManager); _tagsManager.ProcessQueue(); Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = _appSettingsService.DisplayCulture; var unityServiceLocator = new UnityServiceLocator(_container); ServiceLocator.SetLocatorProvider(() => unityServiceLocator); ViewModelLocationProvider.SetDefaultViewModelFactory(ViewModelFactory); ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver(ViewModelTypeResolver); }
public void SaveAndLoad_DifferentTypeDifferentValues() { #region Arrange new LocalStorageManager().Add(new EcKeyPair() { Version = 1 }, this.storageName1); new LocalStorageManager().Add(new EcKeyPair() { Version = 2 }, this.storageName1); new LocalStorageManager().Add(new EcIdentifier(), this.storageName2); new LocalStorageManager().Add(new EcIdentifier(), this.storageName2); new LocalStorageManager().Add(new EcIdentifier(), this.storageName2); new LocalStorageManager().Add(new EcKeyPairInfo(), this.storageName3); Console.Out.WriteLine(File.ReadAllText(LocalStorageManager.GetStoragePath(false))); #endregion #region Act var result1 = new LocalStorageManager().GetAll <EcKeyPair>(this.storageName1); var result2 = new LocalStorageManager().GetAll <EcIdentifier>(this.storageName2); var result3 = new LocalStorageManager().GetAll <EcKeyPairInfo>(this.storageName3); #endregion #region Assert Assert.That(result1.Count(), Is.EqualTo(2)); Assert.That(result2.Count(), Is.EqualTo(3)); Assert.That(result3.Count(), Is.EqualTo(1)); Assert.That(result1.ToArray()[0].Version, Is.EqualTo(1)); Assert.That(result1.ToArray()[1].Version, Is.EqualTo(2)); #endregion }
public void RemoveAll() { #region Arrange var data = new[] { new EcKeyPair() { Version = 1 }, new EcKeyPair() { Version = 2 } }; var storageName = Guid.NewGuid().ToString(); #endregion #region Act new LocalStorageManager().AddRange(data, storageName); Console.Out.WriteLine(File.ReadAllText(LocalStorageManager.GetStoragePath(false))); new LocalStorageManager().RemoveAll(storageName); Console.Out.WriteLine(File.ReadAllText(LocalStorageManager.GetStoragePath(false))); new LocalStorageManager().AddRange(data.Take(1), storageName); Console.Out.WriteLine(File.ReadAllText(LocalStorageManager.GetStoragePath(false))); var result1 = new LocalStorageManager().GetAll <EcKeyPair>(storageName); #endregion #region Assert Assert.That(result1.Count(), Is.EqualTo(1)); Assert.That(result1.ToArray()[0].Version, Is.EqualTo(1)); #endregion }
public SettingsPageViewModel([NotNull] AppSettingsService settingsService, [NotNull] TelemetryClient telemetryClient, [NotNull] LocalStorageManager localStorageManager) { if (settingsService == null) { throw new ArgumentNullException("settingsService"); } if (telemetryClient == null) { throw new ArgumentNullException("telemetryClient"); } if (localStorageManager == null) { throw new ArgumentNullException("localStorageManager"); } _settingsService = settingsService; _telemetryClient = telemetryClient; _localStorageManager = localStorageManager; _initialDisplayCulture = _settingsService.DisplayCulture; }
/// <summary> /// Singleton 응용 프로그램 개체를 초기화합니다. 이것은 실행되는 작성 코드의 첫 번째 /// 줄이며 따라서 main() 또는 WinMain()과 논리적으로 동일합니다. /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; /*** Injecting objects to public static instances ***/ // App MobileService = new MobileServiceClient( "https://pinthecloud.azure-mobile.net/", "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23" ); ApplicationSessions = new WSApplicationSessions(); ApplicationSettings = new WSApplicationSettings(); // Manager SpotManager = new SpotManager(); Geolocator = new Geolocator(); BlobStorageManager = new BlobStorageManager(); LocalStorageManager = new LocalStorageManager(); OneDriveManager = new OneDriveManager(); DropBoxManager = new DropboxManager(); GoogleDriveManger = new GoogleDriveManager(); ///////////////////////////////////////////////////// // This order will be displayed at every App Pages ///////////////////////////////////////////////////// StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager); StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager); StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger); Switcher.SetStorageToMainPlatform(); AccountManager = new AccountManager(); }
/// <summary> /// Application 개체의 생성자입니다. /// </summary> public App() { // Catch되지 않은 예외의 전역 처리기입니다. UnhandledException += Application_UnhandledException; // 표준 XAML 초기화 InitializeComponent(); // 전화 관련 초기화 InitializePhoneApplication(); // 언어 표시 초기화 InitializeLanguage(); /*** Injecting objects to public static instances ***/ // App MobileService = new MobileServiceClient( "https://pinthecloud.azure-mobile.net/", "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23" ); ApplicationSettings = IsolatedStorageSettings.ApplicationSettings; // Manager SpotManager = new SpotManager(); Geolocator = new Geolocator(); BlobStorageManager = new BlobStorageManager(); LocalStorageManager = new LocalStorageManager(); OneDriveManager = new OneDriveManager(); DropBoxManager = new DropboxManager(); GoogleDriveManger = new GoogleDriveManager(); ///////////////////////////////////////////////////// // This order will be displayed at every App Pages ///////////////////////////////////////////////////// StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager); StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager); StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger); Switcher.SetStorageToMainPlatform(); AccountManager = new AccountManager(); // 디버깅하는 동안 그래픽 프로파일링 정보를 표시합니다. if (Debugger.IsAttached) { // 현재 프레임 속도 카운터를 표시합니다. Application.Current.Host.Settings.EnableFrameRateCounter = true; // 각 프레임에서 다시 그려지는 응용 프로그램의 영역을 표시합니다. //Application.Current.Host.Settings.EnableRedrawRegions = true; // 색이 지정된 오버레이로 가속된 GPU에 전달되는 페이지 영역을 표시하는 // 비프로덕션 분석 시각화 모드를 설정합니다. //Application.Current.Host.Settings.EnableCacheVisualization = true; // 응용 프로그램의 유휴 검색을 사용하지 않도록 설정하여 디버거를 // 사용하는 동안 화면이 꺼지지 않도록 방지합니다. // 주의:- 디버그 모드에서만 사용합니다. 사용자 유휴 검색을 해제하는 응용 프로그램은 사용자가 전화를 사용하지 않을 경우에도 // 계속 실행되어 배터리 전원을 소모합니다. PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled; } }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG // Show graphics profiling information while debugging. if (System.Diagnostics.Debugger.IsAttached) { // Display the current frame rate counters this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication().Clear(); Windows.UI.Notifications.BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear(); Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter var localStorageManager = new LocalStorageManager(); CookieContainer cookieTest = await localStorageManager.LoadCookie(Constants.COOKIE_FILE); if (cookieTest.Count <= 0) { if (!rootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!rootFrame.Navigate(typeof(MainForumsPage))) { throw new Exception("Failed to create initial page"); } } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); // TODO: change this value to a cache size that is appropriate for your application rootFrame.CacheSize = 1; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // Removes the turnstile navigation for startup. if (rootFrame.ContentTransitions != null) { this.transitions = new TransitionCollection(); foreach (var c in rootFrame.ContentTransitions) { this.transitions.Add(c); } } rootFrame.ContentTransitions = null; rootFrame.Navigated += this.RootFrame_FirstNavigated; // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter var localStorageManager = new LocalStorageManager(); CookieContainer cookieTest = await localStorageManager.LoadCookie(Constants.COOKIE_FILE); if (cookieTest.Count <= 0) { if (!rootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!rootFrame.Navigate(typeof(MainForumsPage))) { throw new Exception("Failed to create initial page"); } } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ ポイントは、 /// アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。 /// </summary> /// <param name="e">起動の要求とプロセスの詳細を表示します。</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif if (_localSettings.Values.ContainsKey(Constants.ThemeDefault)) { var themeType = (ThemeTypes)_localSettings.Values[Constants.ThemeDefault]; switch (themeType) { case ThemeTypes.YOSPOS: ThemeManager.SetThemeManager(ElementTheme.Dark); ThemeManager.ChangeTheme(new Uri("ms-appx:///Themes/Yospos.xaml")); break; } } SystemNavigationManager.GetForCurrentView().BackRequested += BackPressed; RootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (RootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page RootFrame = new Frame(); // Set the default language RootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; RootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = RootFrame; } if (_localSettings.Values.ContainsKey(Constants.BookmarkBackground) && (bool)_localSettings.Values[Constants.BookmarkBackground]) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.BackgroundTaskName); var task = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.BackgroundTaskEntryPoint, BackgroundTaskUtils.BackgroundTaskName, new TimeTrigger(15, false), null); } var localStorageManager = new LocalStorageManager(); CookieContainer cookieTest = await localStorageManager.LoadCookie("SACookies2.txt"); if (cookieTest.Count <= 0) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!RootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override async void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG // Show graphics profiling information while debugging. if (Debugger.IsAttached) { // Display the current frame rate counters DebugSettings.EnableFrameRateCounter = true; } #endif var rootFrame = Window.Current.Content as Frame; SettingsPane.GetForCurrentView().CommandsRequested += SettingCharmManager_CommandsRequested; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active TileUpdateManager.CreateTileUpdaterForApplication().Clear(); BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear(); TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); //Associate the frame with a SuspensionManager key SuspensionManager.RegisterFrame(rootFrame, "AppFrame"); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { // Restore the saved session state only when appropriate try { await SuspensionManager.RestoreAsync(); } catch (SuspensionManagerException) { //Something went wrong restoring state. //Assume there is no state and continue } } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter var localStorageManager = new LocalStorageManager(); CookieContainer cookieTest = await localStorageManager.LoadCookie(Constants.COOKIE_FILE); if (cookieTest.Count <= 0) { if (!rootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { var localSettings = ApplicationData.Current.LocalSettings; if (localSettings.Values.ContainsKey(Constants.BOOKMARK_STARTUP) && (bool)localSettings.Values[Constants.BOOKMARK_STARTUP]) { var forum = new ForumEntity() { Name = "Bookmarks", IsSubforum = false, Location = Constants.USER_CP }; string jsonObjectString = JsonConvert.SerializeObject(forum); rootFrame.Navigate(typeof(ThreadListPage), jsonObjectString); } else { if (!rootFrame.Navigate(typeof(MainForumsPage))) { throw new Exception("Failed to create initial page"); } } } } // Ensure the current window is active Window.Current.Activate(); }
public async void Login(string username, string password, bool rememberMe) { AccountManager accountManager = new AccountManager(); LoginReponse logedinUser = await accountManager.DoLogin(username, password); if (logedinUser.StatusCode == 0) { try { CurrentUser.EmployeeId = logedinUser.EmployeeId; CurrentUser.UserId = logedinUser.UserId; CurrentUser.LocationId = logedinUser.LocationId; CurrentUser.FullName = logedinUser.FullName; CurrentUser.DefaultClintId = logedinUser.DefaultClintId; CurrentUser.DefaultContractId = 1; //CurrentUser.DefaultContractId = logedinUser.DefaultContractId; CurrentUser.StartTime = logedinUser.StartTime; CurrentUser.EndTime = logedinUser.EndTime; CurrentUser.LunchBreak = logedinUser.LunchBreak; CurrentUser.EmployeeContracts = logedinUser.EmployeeContracts; } catch (Exception ex) { _logger.LoggError(ex, new Dictionary <string, string>() { { "Function", "Login:SetCurrentUser" } }); } try { if (rememberMe) { LocalStorageManager localStorage = new LocalStorageManager(); localStorage.SaveUseridAndPassword(username, password); _logger.LoggEvent("Save user for auto-login", new Dictionary <string, string>() { { "Username", username } }); } else { LocalStorageManager localStorage = new LocalStorageManager(); localStorage.ClearUseridAndPassword(); _logger.LoggEvent("Clear username for auto-login", new Dictionary <string, string>() { { "Username", username } }); } } catch (Exception ex) { _logger.LoggError(ex, new Dictionary <string, string>() { { "Function", "Login:SetRememberMe" } }); } Insights.Identify(CurrentUser.UserId.ToLower()); Dictionary <string, string> myDict = new Dictionary <string, string> { { "Username", username }, { "EmployeeId", CurrentUser.EmployeeId.ToString() } }; _logger.LoggEvent("UserLogin", myDict); LoginMessage = "Login successfull, redirecting.."; //Ändra till true sen när validering på ,user och pass finns LoginRequired = false; } else { _logger.LoggText("Invalid user login! " + username); LoginRequired = true; LoginMessage = "Username or Password is wrong"; } }
/// <summary> /// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ ポイントは、 /// アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。 /// </summary> /// <param name="e">起動の要求とプロセスの詳細を表示します。</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif await JumpListCreator.CreateDefaultList(); if (_localSettings.Values.ContainsKey(Constants.ThemeDefault)) { var themeType = (ThemeTypes)_localSettings.Values[Constants.ThemeDefault]; switch (themeType) { case ThemeTypes.YOSPOS: ThemeManager.SetThemeManager(ElementTheme.Dark); ThemeManager.ChangeTheme(new Uri("ms-appx:///Themes/Yospos.xaml")); break; } } SystemNavigationManager.GetForCurrentView().BackRequested += BackPressed; RootFrame = Window.Current.Content as Frame; if (_localSettings.Values.ContainsKey(Constants.NavigateBack) && (bool)_localSettings.Values[Constants.NavigateBack]) { if (RootFrame != null) { return; } } var isIoT = ApiInformation.IsTypePresent("Windows.Devices.Gpio.GpioController"); if (!isIoT) { TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (RootFrame == null) { CreateRootFrame(); } if (!isIoT) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.ToastBackgroundTaskName); var task2 = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.ToastBackgroundTaskEntryPoint, BackgroundTaskUtils.ToastBackgroundTaskName, new ToastNotificationActionTrigger(), null); if (_localSettings.Values.ContainsKey(Constants.BackgroundEnable) && (bool)_localSettings.Values[Constants.BackgroundEnable]) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.BackgroundTaskName); var task = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.BackgroundTaskEntryPoint, BackgroundTaskUtils.BackgroundTaskName, new TimeTrigger(15, false), null); } } var localStorageManager = new LocalStorageManager(); CookieContainer cookieContainer = await localStorageManager.LoadCookie("SACookies2.txt"); bool cookieTest = true; foreach (Cookie cookie in cookieContainer.GetCookies(new Uri(Constants.CookieDomainUrl))) { if (cookie.Expired) { cookieTest = false; } } if (cookieContainer.Count <= 0) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!cookieTest) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } if (!RootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); try { // Install the main VCD. Since there's no simple way to test that the VCD has been imported, or that it's your most recent // version, it's not unreasonable to do this upon app load. StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"SomethingAwfulCommands.xml"); await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Installing Voice Commands Failed: " + ex.ToString()); } }
/// <summary> /// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ ポイントは、 /// アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。 /// </summary> /// <param name="e">起動の要求とプロセスの詳細を表示します。</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif if (_localSettings.Values.ContainsKey(Constants.ThemeDefault)) { var themeType = (ThemeTypes)_localSettings.Values[Constants.ThemeDefault]; switch (themeType) { case ThemeTypes.YOSPOS: ThemeManager.SetThemeManager(ElementTheme.Dark); ThemeManager.ChangeTheme(new Uri("ms-appx:///Themes/Yospos.xaml")); break; } } SystemNavigationManager.GetForCurrentView().BackRequested += BackPressed; RootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (RootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page RootFrame = new Frame(); // Set the default language RootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; RootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = RootFrame; } if (_localSettings.Values.ContainsKey(Constants.BookmarkBackground) && (bool)_localSettings.Values[Constants.BookmarkBackground]) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.BackgroundTaskName); var task = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.BackgroundTaskEntryPoint, BackgroundTaskUtils.BackgroundTaskName, new TimeTrigger(15, false), null); } var localStorageManager = new LocalStorageManager(); CookieContainer cookieTest = await localStorageManager.LoadCookie("SACookies2.txt"); if (cookieTest.Count <= 0) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!RootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); }
/// <summary> /// アプリケーションがエンド ユーザーによって正常に起動されたときに呼び出されます。他のエントリ ポイントは、 /// アプリケーションが特定のファイルを開くために起動されたときなどに使用されます。 /// </summary> /// <param name="e">起動の要求とプロセスの詳細を表示します。</param> protected async override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif await JumpListCreator.CreateDefaultList(); if (_localSettings.Values.ContainsKey(Constants.ThemeDefault)) { var themeType = (ThemeTypes)_localSettings.Values[Constants.ThemeDefault]; switch (themeType) { case ThemeTypes.YOSPOS: ThemeManager.SetThemeManager(ElementTheme.Dark); ThemeManager.ChangeTheme(new Uri("ms-appx:///Themes/Yospos.xaml")); break; } } SystemNavigationManager.GetForCurrentView().BackRequested += BackPressed; RootFrame = Window.Current.Content as Frame; if (_localSettings.Values.ContainsKey(Constants.NavigateBack) && (bool) _localSettings.Values[Constants.NavigateBack]) { if (RootFrame != null) { return; } } var isIoT = ApiInformation.IsTypePresent("Windows.Devices.Gpio.GpioController"); if (!isIoT) { TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true); } // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (RootFrame == null) { CreateRootFrame(); } if (!isIoT) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.ToastBackgroundTaskName); var task2 = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.ToastBackgroundTaskEntryPoint, BackgroundTaskUtils.ToastBackgroundTaskName, new ToastNotificationActionTrigger(), null); if (_localSettings.Values.ContainsKey(Constants.BackgroundEnable) && (bool)_localSettings.Values[Constants.BackgroundEnable]) { BackgroundTaskUtils.UnregisterBackgroundTasks(BackgroundTaskUtils.BackgroundTaskName); var task = await BackgroundTaskUtils.RegisterBackgroundTask(BackgroundTaskUtils.BackgroundTaskEntryPoint, BackgroundTaskUtils.BackgroundTaskName, new TimeTrigger(15, false), null); } } var localStorageManager = new LocalStorageManager(); CookieContainer cookieContainer = await localStorageManager.LoadCookie("SACookies2.txt"); bool cookieTest = true; foreach (Cookie cookie in cookieContainer.GetCookies(new Uri(Constants.CookieDomainUrl))) { if (cookie.Expired) { cookieTest = false; } } if (cookieContainer.Count <= 0) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } else { if (!cookieTest) { if (!RootFrame.Navigate(typeof(LoginPage))) { throw new Exception("Failed to create initial page"); } } if (!RootFrame.Navigate(typeof(MainPage), e.Arguments)) { throw new Exception("Failed to create initial page"); } } // Ensure the current window is active Window.Current.Activate(); try { // Install the main VCD. Since there's no simple way to test that the VCD has been imported, or that it's your most recent // version, it's not unreasonable to do this upon app load. StorageFile vcdStorageFile = await Package.Current.InstalledLocation.GetFileAsync(@"SomethingAwfulCommands.xml"); await Windows.ApplicationModel.VoiceCommands.VoiceCommandDefinitionManager.InstallCommandDefinitionsFromStorageFileAsync(vcdStorageFile); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Installing Voice Commands Failed: " + ex.ToString()); } }