コード例 #1
0
        /// <summary>
        /// Email the Log file on file rolled
        /// </summary>
        /// <param name="filePath"></param>
        protected override void OnFileRolled(string filePath)
        {
            if (!File.Exists(filePath))
            {
                return;
            }

            try
            {
                int totalErrors   = File.ReadAllLines(filePath).Count(line => Regex.IsMatch(line, ERROR_REGEX));
                int totalWarnings = File.ReadAllLines(filePath).Count(line => Regex.IsMatch(line, WARNING_REGEX));

                string environment = ApplicationSettingsHelper.LoadAppSetting("environment", false, string.Empty);
                if (!string.IsNullOrEmpty(environment))
                {
                    environment = "[{0}]".fmt(environment);
                }

                var info = new SysInfo();
                using (Emailer mailer = Kernel.Get <Emailer>())
                {
                    mailer.AddRecipient(EmailRecipients.Split(';', ','));
                    mailer.AttachFile(filePath);
                    mailer.Send(
                        "[{0} - {1}] {2} {3}"
                        .fmt(EmailSubject,
                             totalErrors != 0 ? "Error" : (totalWarnings != 0 ? "Warning" : "Information"),
                             environment,
                             DateTime.Now.ToString("dd/MM/yyyy")),
                        "{0}\r\n\r\nLog file attached".fmt(info.GetRamDiskUsage()));
                }
            }
            catch (Exception e)
            {
                Logger.WriteUnexpectedException(e, "Failed to email rolled file.", Category.GeneralError);
            }
        }
コード例 #2
0
        private static void TestReadXmlSettings(Type localXmlSettingsClass)
        {
            var settings = ApplicationSettingsHelper.GetSettingsClassInstance(localXmlSettingsClass);

            var         appValue    = @"<test><app/></test>";
            XmlDocument appDocument = new XmlDocument();

            appDocument.LoadXml(appValue);
            settings.SetSharedPropertyValue(LocalXmlSettingsBase.PropertyApp, appDocument);

            var         userValue    = @"<test><user/></test>";
            XmlDocument userDocument = new XmlDocument();

            userDocument.LoadXml(userValue);
            settings.SetSharedPropertyValue(LocalXmlSettingsBase.PropertyUser, userDocument);

            var reader = new ConfigurationFileReader(SystemConfigurationHelper.GetExeConfiguration().FilePath);
            var path   = new ConfigurationSectionPath(localXmlSettingsClass, SettingScope.Application);
            var values = reader.GetSettingsValues(path);

            Assert.AreEqual(1, values.Count);

            XmlDocument testDocument = new XmlDocument();

            testDocument.LoadXml(values[LocalXmlSettingsBase.PropertyApp]);
            Assert.AreEqual(appDocument.InnerXml, testDocument.InnerXml);

            path   = new ConfigurationSectionPath(localXmlSettingsClass, SettingScope.User);
            values = reader.GetSettingsValues(path);
            Assert.AreEqual(1, values.Count);

            testDocument = new XmlDocument();
            testDocument.LoadXml(values[LocalXmlSettingsBase.PropertyUser]);
            Assert.AreEqual(userDocument.InnerXml, testDocument.InnerXml);

            SystemConfigurationHelper.GetExeConfiguration().RemoveSettingsValues(localXmlSettingsClass);
        }
コード例 #3
0
        private void Sort(Func <SongItem, object> selector)
        {
            int id = -1;

            if (isNowPlaying)
            {
                if (playlist.Count == 0)
                {
                    return;
                }
                id = playlist.ElementAt(index).SongId;
            }
            if (ascending)
            {
                Playlist = new ObservableCollection <SongItem>(playlist.OrderBy(selector));
            }
            else
            {
                Playlist = new ObservableCollection <SongItem>(playlist.OrderByDescending(selector));
            }
            if (isNowPlaying)
            {
                int i = 0;
                foreach (var item in playlist)
                {
                    if (item.SongId == id)
                    {
                        break;
                    }
                    i++;
                }
                index = i;
                ApplicationSettingsHelper.SaveSongIndex(index);
                Library.Current.SetNowPlayingList(Playlist);
                NPChange.SendMessageNPSorted();
            }
        }
コード例 #4
0
ファイル: BackgroundAudioTask.cs プロジェクト: scbj/musixx
        private void PlaybackList_CurrentItemChanged(MediaPlaybackList sender, CurrentMediaPlaybackItemChangedEventArgs args)
        {
            var item = args.NewItem;

            Debug.WriteLine("PlaybackList_CurrentItemChanged: " + (item == null ? "null" : GetTrackId(item).ToString()));

            UpdateSMTCInfosOnNewTrack(item);

            Uri currentTrackId = null;

            if (item != null)
            {
                currentTrackId = item.Source.CustomProperties[TrackIdKey] as Uri;
            }

            if (foregroundAppState == AppState.Active)
            {
                MessageService.SendMessageToForeground(new TrackChangedMessage(currentTrackId));
            }
            else
            {
                ApplicationSettingsHelper.SaveSettingsValue(TrackIdKey, currentTrackId);
            }
        }
コード例 #5
0
ファイル: PlaylistService.cs プロジェクト: yueyz818/vlc-winrt
        public void Restore()
        {
            if (!ApplicationSettingsHelper.Contains(nameof(Index)))
            {
                return;
            }

            var playlist = BackgroundTrackRepository.LoadPlaylist();

            if (!playlist.Any())
            {
                return;
            }

            var trackIds         = playlist.Select(node => node.TrackId);
            var restoredplaylist = new SmartCollection <IMediaItem>();

            foreach (int trackId in trackIds)
            {
                var trackItem = Locator.MediaLibrary.LoadTrackById(trackId);
                if (trackItem != null)
                {
                    restoredplaylist.Add(trackItem);
                }
            }

            if (restoredplaylist.Count == 0)
            {
                return;
            }
            clear();
            _playlist = restoredplaylist;
            OnPlaylistChanged?.Invoke();
            _index = (int)ApplicationSettingsHelper.ReadSettingsValue(nameof(Index));
            OnCurrentMediaChanged?.Invoke(_playlist[_index], true);
        }
コード例 #6
0
        public static void PopulateSimpleStore(Type type)
        {
            ResetSimpleStore();
            TestApplicationSettingsBase.ResetAll();
            var settings = ApplicationSettingsHelper.GetSettingsClassInstance(type);

            foreach (SettingsProperty property in settings.Properties)
            {
                var value = CreateSettingsPropertyValue(property, MigrationScope.User, SettingValue.Current);
                if (value != null)
                {
                    SimpleSettingsStore.Instance.CurrentUserValues.Add(value);
                }

                value = CreateSettingsPropertyValue(property, MigrationScope.User, SettingValue.Previous);
                if (value != null)
                {
                    SimpleSettingsStore.Instance.PreviousUserValues.Add(value);
                }

                value = CreateSettingsPropertyValue(property, MigrationScope.Shared, SettingValue.Current);
                if (value != null)
                {
                    SimpleSettingsStore.Instance.CurrentSharedValues.Add(value);
                }

                value = CreateSettingsPropertyValue(property, MigrationScope.Shared, SettingValue.Previous);
                if (value != null)
                {
                    SimpleSettingsStore.Instance.PreviousSharedValues.Add(value);
                }
            }

            ValidateStoredValues(type, MigrationScope.Shared, SettingValue.Current);
            ValidateStoredValues(type, MigrationScope.User, SettingValue.Current);
        }
コード例 #7
0
        /// <summary>
        /// Handles background task cancellation. Task cancellation happens due to:
        /// 1. Another Media app comes into foreground and starts playing music
        /// 2. Resource pressure. Your task is consuming more CPU and memory than allowed.
        /// In either case, save state so that if foreground app resumes it can know where to start.
        /// </summary>
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            // You get some time here to save your state before process and resources are reclaimed
            Debug.WriteLine("BackgroundAudioTask " + sender.Task.TaskId + " Cancel Requested...");
            try
            {
                // immediately set not running
                backgroundTaskStarted.Reset();

                // save state
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, GetCurrentTrackId() == null ? null : GetCurrentTrackId().ToString());
                //ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.BackgroundTaskState, BackgroundTaskState.Canceled.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.AppState, Enum.GetName(typeof(AppState), foregroundAppState));

                // unsubscribe from list changes
                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                // unsubscribe event handlers
                BackgroundMediaPlayer.MessageReceivedFromForeground -= BackgroundMediaPlayer_MessageReceivedFromForeground;
                smtc.ButtonPressed   -= smtc_ButtonPressed;
                smtc.PropertyChanged -= smtc_PropertyChanged;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            deferral.Complete(); // signals task completion.
            Debug.WriteLine("BackgroundAudioTask Cancel complete...");
        }
コード例 #8
0
        private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
        {
            FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;

            if (args != null)
            {
                if (args.Files.Count == 0)
                {
                    return;
                }

                view.Activated -= viewActivated;
                StorageFile   SelectedImageFile = args.Files[0];
                StorageFolder localFolder       = ApplicationData.Current.LocalFolder;
                string        name = "userbgimage" + System.IO.Path.GetExtension(SelectedImageFile.Path);
                StorageFile   img  = await SelectedImageFile.CopyAsync(localFolder, name, NameCollisionOption.ReplaceExisting);

                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.BackgroundImagePath, img.Path);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.IsBGImageSet, true);
                App.Current.Resources["UserListFontColor"] = new SolidColorBrush(Windows.UI.Colors.White);
                ((ImageBrush)App.Current.Resources["BgImage"]).ImageSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri(img.Path, UriKind.RelativeOrAbsolute));
                ShowBGImage_ToggleSwitch.IsOn = true;
            }
        }
コード例 #9
0
        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        /// The source of the event; typically <see cref="NavigationHelper"/>
        /// </param>
        /// <param name="e">Event data that provides both the navigation parameter passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
        /// a dictionary of state preserved by this page during an earlier
        /// session.  The state will be null the first time a page is visited.</param>
        private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            initialization = true;
            if (e.PageState != null && e.PageState.ContainsKey("pivotIndex"))
            {
                PivotSettings.SelectedIndex = (int)e.PageState["pivotIndex"];
            }

            //General Settings
            //Library scan
            var a = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.MediaScan);

            if (a != null)
            {
                DisableControls();
            }
            //Timer
            var d = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TimerTime);

            var t = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TimerOn);

            if (t == null)
            {
                isTimerOn = false;
            }
            else
            {
                isTimerOn = (bool)t;
            }

            if (isTimerOn)
            {
                timerPicker.IsEnabled  = true;
                timerToggleSwitch.IsOn = true;

                if (d != null)
                {
                    loading          = true;
                    timerPicker.Time = TimeSpan.FromTicks((long)d);
                }
            }
            else
            {
                timerPicker.IsEnabled  = false;
                timerToggleSwitch.IsOn = false;
            }
            //Transparent tile
            string isTr = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TileAppTransparent) as string;

            if (isTr == "yes")
            {
                transparentToggleSwitch.IsOn = true;
            }

            //Personalize
            //Color accent
            bool isPhoneAccent = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsPhoneAccentSet);

            if (isPhoneAccent)
            {
                phoneAccentToggleSwitch.IsOn = true;
            }
            //Theme
            string appTheme = (string)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppTheme);

            if (appTheme.Equals(AppThemeEnum.Dark.ToString()))
            {
                RBDark.IsChecked = true;
            }
            else if (appTheme.Equals(AppThemeEnum.Light.ToString()))
            {
                RBLight.IsChecked = true;
            }
            //Background image
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsBGImageSet))
            {
                ShowBGImage_ToggleSwitch.IsOn = true;
                //SelectImage_Button.IsEnabled = true;
            }
            else
            {
                ShowBGImage_ToggleSwitch.IsOn = false;
                //SelectImage_Button.IsEnabled = false;
            }
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.ShowCoverAsBackground))
            {
                ShowAlbumCover_ToggleSwitch.IsOn = true;
            }

            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmSendNP))
            {
                ToggleSwitchSendNP.IsOn = true;
            }
            else
            {
                ToggleSwitchSendNP.IsOn = false;
            }
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs))
            {
                ToggleSwitchLoveTrack.IsOn = true;
            }
            else
            {
                ToggleSwitchLoveTrack.IsOn = false;
            }
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmPassword).ToString() == "")
            {
                LFMLogoutButton.Visibility = Visibility.Collapsed;
                LFMLoginButton.Visibility  = Visibility.Visible;
            }
            else
            {
                LFMLoginButton.Visibility  = Visibility.Collapsed;
                LFMLogoutButton.Visibility = Visibility.Visible;

                TBLogin.Visibility          = Visibility.Collapsed;
                TBPassword.Visibility       = Visibility.Collapsed;
                TBYouAreLoggedIn.Visibility = Visibility.Visible;

                LFMPassword.Visibility = Visibility.Collapsed;
                LFMLogin.Visibility    = Visibility.Collapsed;
            }
            int love   = Int32.Parse(ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.LfmLove).ToString());
            int unlove = Int32.Parse(ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.LfmUnLove).ToString());

            MaxUnLove.SelectedIndex = unlove - 1;
            MinLove.SelectedIndex   = love - 1;


            var navigableViewModel = this.DataContext as INavigable;

            if (navigableViewModel != null)
            {
                navigableViewModel.Activate(e.NavigationParameter, e.PageState);
            }
            initialization = false;
            //App.TelemetryClient.TrackEvent("Settings page open");
        }
コード例 #10
0
        void OnMessageFromForegroundReceived(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            AppSuspendedMessage appSuspendedMessage;

            if (MessageService.TryParseMessage(e.Data, out appSuspendedMessage))
            {
                foregroundAppState = AppState.Suspended;
                var currentTrackId = GetCurrentTrackId();
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, currentTrackId == null ? null : currentTrackId.ToString());
                return;
            }

            AppResumedMessage appResumedMessage;

            if (MessageService.TryParseMessage(e.Data, out appResumedMessage))
            {
                foregroundAppState = AppState.Active;
                return;
            }

            StartPlaybackMessage startPlaybackMessage;

            if (MessageService.TryParseMessage(e.Data, out startPlaybackMessage))
            {
                StartPlayback();
                return;
            }

            SkipNextMessage skipNextMessage;

            if (MessageService.TryParseMessage(e.Data, out skipNextMessage))
            {
                SkipToNext();
                return;
            }

            SkipPreviousMessage skipPreviousMessage;

            if (MessageService.TryParseMessage(e.Data, out skipPreviousMessage))
            {
                SkipToPrevious();
                return;
            }

            TrackChangedMessage trackChangedMessage;

            if (MessageService.TryParseMessage(e.Data, out trackChangedMessage))
            {
                var index = playbackList.Items.ToList().FindIndex(i => GetTrackId(i) == trackChangedMessage.TrackId);
                smtc.PlaybackStatus = MediaPlaybackStatus.Changing;
                playbackList.MoveTo((uint)index);
                return;
            }

            UpdatePlaylistMessage updatePlaylistMessage;

            if (MessageService.TryParseMessage(e.Data, out updatePlaylistMessage))
            {
                CreatePlaybackList(updatePlaylistMessage.Songs);
                return;
            }
        }
コード例 #11
0
 /// <summary>
 ///  应用状态恢复
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void App_Resuming(object sender, object e)
 {
     ApplicationSettingsHelper.SaveSettingToLocalSettings(ApplicationSettingsConstants.AppState, AppState.Active.ToString());
 }
コード例 #12
0
        private static void ValidateLocalMixedScopeSettingsValuesInConfig(Type mixedScopeSettingsClass, System.Configuration.Configuration configuration, SettingValue settingValue)
        {
            if (!mixedScopeSettingsClass.IsSubclassOf(typeof(MixedScopeSettingsBase)))
            {
                throw new ArgumentException();
            }

            var settings = ApplicationSettingsHelper.GetSettingsClassInstance(mixedScopeSettingsClass);

            settings.Reload();

            SettingsProperty property = settings.Properties[MixedScopeSettingsBase.PropertyApp1];
            string           expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            var actual = (string)settings[property.Name];

            Assert.AreEqual(expected, actual);
            actual = (string)settings.GetSharedPropertyValue(property.Name);
            Assert.AreEqual(expected, actual);

            property = settings.Properties[MixedScopeSettingsBase.PropertyApp2];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = (string)settings[property.Name];
            Assert.AreEqual(expected, actual);
            actual = (string)settings.GetSharedPropertyValue(property.Name);
            Assert.AreEqual(expected, actual);

            property = settings.Properties[MixedScopeSettingsBase.PropertyUser1];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = (string)settings.GetSharedPropertyValue(property.Name);
            Assert.AreEqual(expected, actual);

            property = settings.Properties[MixedScopeSettingsBase.PropertyUser2];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = (string)settings.GetSharedPropertyValue(property.Name);
            Assert.AreEqual(expected, actual);

            var values = configuration.GetSettingsValues(mixedScopeSettingsClass, SettingScope.Application);

            Assert.AreEqual(2, values.Count);
            property = settings.Properties[MixedScopeSettingsBase.PropertyApp1];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = values[property.Name];
            Assert.AreEqual(expected, actual);

            property = settings.Properties[MixedScopeSettingsBase.PropertyApp2];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = values[property.Name];
            Assert.AreEqual(expected, actual);

            values = configuration.GetSettingsValues(mixedScopeSettingsClass, SettingScope.User);
            Assert.AreEqual(2, values.Count);
            property = settings.Properties[MixedScopeSettingsBase.PropertyUser1];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = values[property.Name];
            Assert.AreEqual(expected, actual);

            property = settings.Properties[MixedScopeSettingsBase.PropertyUser2];
            expected = CreateSettingValue(property, MigrationScope.Shared, settingValue);
            actual   = values[property.Name];
            Assert.AreEqual(expected, actual);
        }
コード例 #13
0
        public override async void Execute(object parameter)
        {
            /* Connect when ENTER key is pressed */
            var keyStroke = parameter as KeyRoutedEventArgs;

            if (keyStroke != null)
            {
                if (keyStroke.Key == Windows.System.VirtualKey.Enter)
                {
                    keyStroke.Handled = true;
                }
                else
                {
                    return;
                }
            }

            if (Loc.Main.AccountManager.Accounts.FirstOrDefault(x => x.Pseudo == Loc.Main.AccountManager.CurrentAccount.Pseudo) != null)
            {
                return;
            }
            await ThreadUI.Invoke(() =>
            {
                Loc.Main.AccountManager.CurrentAccount.ConnectionErrorStatus = "Connecting";
                Loc.Main.AccountManager.CurrentAccount.IsConnecting          = true;
            });

            bool success = await Loc.Main.AccountManager.CurrentAccount.BeginAuthentication(true);

            if (success)
            {
                Loc.Main.AccountManager.Accounts.Add(Loc.Main.AccountManager.CurrentAccount);
                Loc.Main.AccountManager.AddCurrentAccountInDB();

                var autoConnectFromRoamingSettings = ApplicationSettingsHelper.Contains(nameof(Loc.Main.AccountManager.CurrentAccount.Pseudo), false);
                var md = new MessageDialog("Voulez-vous être connecté automatiquement à ce compte ?", "Juste une question");
                if (!autoConnectFromRoamingSettings)
                {
                    md.Commands.Add(new UICommand()
                    {
                        Label   = "Oui",
                        Invoked = async(command) =>
                        {
                            await ThreadUI.Invoke(() =>
                            {
                                Loc.Main.AccountManager.AddCurrentAccountInRoamingSettings();
                            });
                        },
                    });
                    md.Commands.Add(new UICommand()
                    {
                        Label   = "Non",
                        Invoked = (command) =>
                        {
                        },
                    });
                }
                await ThreadUI.Invoke(async() =>
                {
                    if (!autoConnectFromRoamingSettings)
                    {
                        await md.ShowAsync();
                    }
                    Loc.Main.AccountManager.CurrentAccount.IsConnecting          = false;
                    Loc.Main.AccountManager.CurrentAccount.ConnectionErrorStatus = "Login succeeded";
                    Loc.NavigationService.Navigate(View.Main);
                });
            }
            else
            {
                await ThreadUI.Invoke(() =>
                {
                    Loc.Main.AccountManager.CurrentAccount.IsConnecting          = false;
                    Loc.Main.AccountManager.CurrentAccount.ConnectionErrorStatus = "Login failed";
                    ToastHelper.Simple("Echec de la connexion");
                });

                Debug.WriteLine("Login failed");
            }
        }
コード例 #14
0
ファイル: AccountManager.cs プロジェクト: boubou10/HFR10
 internal void AddCurrentAccountInRoamingSettings()
 {
     ApplicationSettingsHelper.SaveSettingsValue(nameof(CurrentAccount.Pseudo), CurrentAccount.Pseudo, false);
     ApplicationSettingsHelper.SaveSettingsValue(nameof(CurrentAccount.Password), CurrentAccount.Password, false);
 }
コード例 #15
0
        /// <summary>
        /// Raised when a message is recieved from the foreground app
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            AppSuspendedMessage appSuspendedMessage;

            if (MessageService.TryParseMessage(e.Data, out appSuspendedMessage))
            {
                Debug.WriteLine("App suspending"); // App is suspended, you can save your task state at this point
                foregroundAppState = AppState.Suspended;
                var currentTrackId = GetCurrentTrackId();
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, currentTrackId == null ? null : currentTrackId.ToString());
                return;
            }

            AppResumedMessage appResumedMessage;

            if (MessageService.TryParseMessage(e.Data, out appResumedMessage))
            {
                Debug.WriteLine("App resuming"); // App is resumed, now subscribe to message channel
                foregroundAppState = AppState.Active;
                return;
            }

            StartPlaybackMessage startPlaybackMessage;

            if (MessageService.TryParseMessage(e.Data, out startPlaybackMessage))
            {
                //Foreground App process has signalled that it is ready for playback
                Debug.WriteLine("Starting Playback");
                StartPlayback();
                return;
            }

            SkipNextMessage skipNextMessage;

            if (MessageService.TryParseMessage(e.Data, out skipNextMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to next");
                SkipToNext();
                return;
            }

            SkipPreviousMessage skipPreviousMessage;

            if (MessageService.TryParseMessage(e.Data, out skipPreviousMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to previous");
                SkipToPrevious();
                return;
            }

            TrackChangedMessage trackChangedMessage;

            if (MessageService.TryParseMessage(e.Data, out trackChangedMessage))
            {
                var index = playbackList.Items.ToList().FindIndex(i => (Uri)i.Source.CustomProperties[TrackIdKey] == trackChangedMessage.TrackId);
                Debug.WriteLine("Skipping to track " + index);
                smtc.PlaybackStatus = MediaPlaybackStatus.Changing;
                playbackList.MoveTo((uint)index);
                return;
            }

            UpdatePlaylistMessage updatePlaylistMessage;

            if (MessageService.TryParseMessage(e.Data, out updatePlaylistMessage))
            {
                CreatePlaybackList(updatePlaylistMessage.Songs);
                return;
            }
        }
コード例 #16
0
ファイル: Numbers.cs プロジェクト: iAmeng/VR-for-VLC
 public static bool NeedsToDrop()
 {
     if (ApplicationSettingsHelper.Contains(Strings.AlreadyLaunched, true) && ApplicationSettingsHelper.Contains(Strings.DatabaseVersion, true) && (int)ApplicationSettingsHelper.ReadSettingsValue(Strings.DatabaseVersion, true) == Numbers.DbVersion)
     {
         LogHelper.Log("DB does not need to be dropped.");
         return(false);
     }
     else
     {
         LogHelper.Log("DB needs to be dropped.");
         ApplicationSettingsHelper.SaveSettingsValue(Strings.DatabaseVersion, Numbers.DbVersion, true);
         ApplicationSettingsHelper.SaveSettingsValue(Strings.AlreadyLaunched, true, true);
         return(true);
     }
 }
コード例 #17
0
        public async Task SetMedia(IVLCMedia media, bool forceVlcLib = false, bool autoPlay = true)
        {
            if (media == null)
            {
                throw new ArgumentNullException("media", "Media parameter is missing. Can't play anything");
            }
            Stop();
            UseVlcLib = true; // forceVlcLib;

            if (media is VideoItem)
            {
                await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    PlayingType = PlayingType.Video;
                    IsStream    = false;
                    Locator.NavigationService.Go(VLCPage.VideoPlayerPage);
                });

                var video = (VideoItem)media;
                await Locator.MediaPlaybackViewModel.InitializePlayback(video, autoPlay);

                if (video.TimeWatched != TimeSpan.FromSeconds(0))
                {
                    await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Locator.MediaPlaybackViewModel.Time = (Int64)video.TimeWatched.TotalMilliseconds);
                }

                await SetMediaTransportControlsInfo(string.IsNullOrEmpty(video.Name)? "Video" : video.Name);

                UpdateTileHelper.UpdateMediumTileWithVideoInfo();
            }
            else if (media is TrackItem)
            {
                await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    IsStream    = false;
                    PlayingType = PlayingType.Music;
                });

                var         track = (TrackItem)media;
                StorageFile currentTrackFile;
                try
                {
                    currentTrackFile = track.File ?? await StorageFile.GetFileFromPathAsync(track.Path);
                }
                catch (Exception exception)
                {
                    await MusicLibraryManagement.RemoveTrackFromCollectionAndDatabase(track);

                    await Task.Delay(500);

                    if (TrackCollection.CanGoNext)
                    {
                        await PlayNext();
                    }
                    else
                    {
                        await App.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => Locator.NavigationService.GoBack_Specific());
                    }
                    return;
                }
                await Locator.MediaPlaybackViewModel.InitializePlayback(track, autoPlay);

                if (_playerEngine != PlayerEngine.BackgroundMFPlayer)
                {
                    await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        await Locator.MusicPlayerVM.SetCurrentArtist();
                        await Locator.MusicPlayerVM.SetCurrentAlbum();
                        await Locator.MusicPlayerVM.UpdatePlayingUI();
                        Locator.Slideshow.AddImg(Locator.MusicPlayerVM.CurrentArtist.Picture);
#if WINDOWS_APP
                        await Locator.MusicPlayerVM.UpdateWindows8UI();
                        await Locator.MusicPlayerVM.Scrobble();
#endif
                    });
                }
                ApplicationSettingsHelper.SaveSettingsValue(BackgroundAudioConstants.CurrentTrack, TrackCollection.CurrentTrack);
            }
            else if (media is StreamMedia)
            {
                UseVlcLib = true;
                await App.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Locator.VideoVm.CurrentVideo = null;
                    Locator.MediaPlaybackViewModel.PlayingType = PlayingType.Video;
                    IsStream = true;
                });

                await Locator.MediaPlaybackViewModel.InitializePlayback(media, autoPlay);
            }
        }
コード例 #18
0
 protected string AppSettings(string key)
 {
     return(ApplicationSettingsHelper.AppSetting(key));
 }
コード例 #19
0
 protected T AppSettings <T>(string key)
 {
     return(ApplicationSettingsHelper.AppSetting <T>(key));
 }
コード例 #20
0
 public LocallyInstalledGroup(SettingsGroupDescriptor descriptor)
     : base(descriptor)
 {
     _settingsClass = ApplicationSettingsHelper.GetSettingsClass(this.Descriptor);
 }
コード例 #21
0
        public void Activate(object parameter, Dictionary <string, object> state)
        {
            //App.Current.Suspending += ForegroundApp_Suspending;
            //App.Current.Resuming += ForegroundApp_Resuming;

            index = CurrentSongIndex;
            if (index > -1)
            {
                SongItem song = Library.Current.NowPlayingList.ElementAt(index);
                CurrentNr  = index + 1;
                SongsCount = Library.Current.NowPlayingList.Count;
                songId     = song.SongId;
                Title      = song.Title;
                Artist     = song.Artist;
                Album      = song.Album;
                fromDB     = true;
                Rating     = song.Rating;
                //PlaybackRate = 100.0;
                SetCover(song.Path);

                SetupTimer();

                RepeatButtonContent     = Repeat.CurrentStateContent();
                RepeatButtonForeground  = Repeat.CurrentStateColor();
                ShuffleButtonForeground = Shuffle.CurrentStateColor();

                if (IsMyBackgroundTaskRunning)
                {
                    //Library.Current.Save("BG running");

                    AddMediaPlayerEventHandlers();

                    if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Playing)
                    {
                        PlayButtonContent = "\uE17e\uE103";//pause
                    }

                    object r = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.ResumePlayback);
                    if (r != null)
                    {
                        SendMessage(AppConstants.ResumePlayback);
                        TimeSpan t        = BackgroundMediaPlayer.Current.NaturalDuration;
                        double   absvalue = (int)Math.Round(t.TotalSeconds - 0.5, MidpointRounding.AwayFromZero);
                        ProgressBarMaxValue = absvalue;
                        EndTime             = BackgroundMediaPlayer.Current.NaturalDuration;
                        PlaybackRate        = BackgroundMediaPlayer.Current.PlaybackRate * 100.0;
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("lyrics"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("lyrics");
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("nplist"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("nplist");
                    }
                    else if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("mainpage"))//mozna chyba zmienic na Dict<> state
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("mainpage");

                        TimeSpan t        = BackgroundMediaPlayer.Current.NaturalDuration;
                        double   absvalue = (int)Math.Round(t.TotalSeconds - 0.5, MidpointRounding.AwayFromZero);
                        ProgressBarMaxValue = absvalue;
                        EndTime             = BackgroundMediaPlayer.Current.NaturalDuration;
                        PlaybackRate        = BackgroundMediaPlayer.Current.PlaybackRate * 100.0;
                    }
                    else
                    {
                        SendMessage(AppConstants.NowPlayingListChanged);
                        SendMessage(AppConstants.StartPlayback, CurrentSongIndex);
                    }
                }
                else
                {
                    if (NextPlayer.Common.SuspensionManager.SessionState.ContainsKey("mainpage"))
                    {
                        NextPlayer.Common.SuspensionManager.SessionState.Remove("mainpage");
                    }
                    object r = ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.ResumePlayback);
                    //if (r != null)
                    //{
                    //    StartBackgroundAudioTask(AppConstants.ResumePlayback, CurrentSongIndex);
                    //}
                    //else
                    //{
                    StartBackgroundAudioTask(AppConstants.StartPlayback, CurrentSongIndex);
                    //}
                }
                StartTimer();
            }
            else
            {
                navigationService.NavigateTo(ViewNames.MainView);
            }
            //if (parameter != null)
            //{

            //    if (parameter.GetType() == typeof(int))
            //    {
            //        songId = (int)parameter;
            //    }
            //}
        }
コード例 #22
0
 /// <summary>
 /// 当此页面即将显示在框架中时调用。
 /// </summary>
 /// <param name="e"></param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     ApplicationSettingsHelper.LoadSetttingFromLocalSettings(ApplicationSettingsConstants.AppState, AppState.Active.ToString());//本地配置文件加载并设置为激活状态
 }
コード例 #23
0
 private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs leavingBackgroundEventArgs)
 {
     ApplicationSettingsHelper.SaveSettingsValue("AppBackgrounded", false);
 }
コード例 #24
0
ファイル: MediaImport.cs プロジェクト: tmk907/NextPlayer
        public async static Task ImportAndUpdateDatabase(IProgress <int> progress)
        {
            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.MediaScan, true);
            IReadOnlyList <StorageFile> list = await KnownFolders.MusicLibrary.GetFilesAsync(Windows.Storage.Search.CommonFileQuery.OrderByName);

            int all   = list.Count;
            int count = 1;
            Tuple <int, int> tuple;
            Dictionary <string, Tuple <int, int> > dict = DatabaseManager.GetFilePaths();

            int w1;
            int w2;

            List <int>      toAvailable = new List <int>();//lista songId
            List <SongData> newSongs    = new List <SongData>();

            foreach (var file in list)
            {
                string type = file.FileType.ToLower();
                if (type == ".mp3" || type == ".m4a" || type == ".wma" ||
                    type == ".wav" || type == ".aac" || type == ".asf" ||
                    type == ".adt" || type == ".adts" || type == ".amr")
                {
                    //Windows.Storage.FileProperties.BasicProperties bp = await file.GetBasicPropertiesAsync();
                    // Sprawdzanie rozmiaru nie działa
                    if (dict.TryGetValue(file.Path, out tuple))
                    {
                        if (tuple.Item1 == 0)//zaznaczony jako niedostepny
                        {
                            toAvailable.Add(tuple.Item2);
                        }
                        else//zaznaczony jako dostepny
                        {
                            toAvailable.Add(tuple.Item2);
                        }
                    }
                    else
                    {
                        SongData song = await CreateSongFromFile(file);

                        newSongs.Add(song);
                    }
                }
                w1 = (100 * count / all);
                w2 = (100 * (count - 1) / all);

                if (progress != null && w1 != w2)
                {
                    progress.Report(w1);
                }
                count++;
            }
            progress.Report(99);
            DatabaseManager.ChangeAvailability(toAvailable);
            Library.Current.CheckNPAfterUpdate(toAvailable);
            await DatabaseManager.InsertSongsAsync(newSongs);

            ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.MediaScan);
            OnMediaImported("Update");
            SendToast();
        }
コード例 #25
0
ファイル: AccountManager.cs プロジェクト: boubou10/HFR10
        async Task Initialize()
        {
            var accounts = accountDataRepository?.GetAccounts();

            if (accounts != null && accounts.Any())
            {
                Accounts = accounts;
                if (accounts.Count == 1)
                {
                    CurrentAccount = accounts[0];
#warning "Optimistic: any account/cookies is supposed valid, proper implementation needed (cookies timeout check)"
                    await ThreadUI.Invoke(() =>
                    {
                        Loc.NavigationService.Navigate(View.Connect);
                        Loc.Main.AccountManager.CurrentAccount.ConnectionErrorStatus = "Connecting";
                        Loc.Main.AccountManager.CurrentAccount.IsConnecting          = true;
                    });

                    bool success = await CurrentAccount.BeginAuthentication(false);

                    if (success)
                    {
                        await ThreadUI.Invoke(() =>
                        {
                            Loc.Main.AccountManager.CurrentAccount.IsConnected = false;
                            Loc.NavigationService.Navigate(View.Main);
                        });
                    }
                    else
                    {
                        Debug.WriteLine("Login failed");
                    }
                }
                else
                {
                    // Handle selection of one of the multi accounts
                }
            }
            else
            {
                // navigate to connectpage
                await ThreadUI.Invoke(() =>
                {
                    CurrentAccount = new Account();
                    Loc.NavigationService.Navigate(View.Connect);
                    // Trying to detect login and password stored in RoamingSettings
                    if (ApplicationSettingsHelper.Contains(nameof(CurrentAccount.Pseudo), false) && ApplicationSettingsHelper.Contains(nameof(CurrentAccount.Password), false))
                    {
                        ToastHelper.Simple("Connexion automatique ...");
                        var pseudo              = ApplicationSettingsHelper.ReadSettingsValue(nameof(CurrentAccount.Pseudo), false).ToString();
                        var password            = ApplicationSettingsHelper.ReadSettingsValue(nameof(CurrentAccount.Password), false).ToString();
                        CurrentAccount.Pseudo   = pseudo;
                        CurrentAccount.Password = password;
                        ConnectCommand.Execute(null);
                    }
                });
            }
        }
コード例 #26
0
        //zwraca null, jesli nie ma nastepnego utworu do zagrania(np. jest koniec playlisty)
        public NowPlayingSong NextSong(bool userChoice)
        {
            NowPlayingSong song;
            bool           stop = false;

            previousIndex = currentIndex;

            if (repeat == RepeatEnum.NoRepeat)
            {
                if (shuffle)
                {
                    currentIndex = GetRandomIndex();
                }
                else
                {
                    if (IsLast())
                    {
                        if (userChoice)
                        {
                            currentIndex = 0;
                        }
                        else
                        {
                            stop = true;
                        }
                    }
                    else
                    {
                        currentIndex++;
                    }
                }
            }
            if (repeat == RepeatEnum.RepeatOnce)
            {
                if (isSongRepeated)
                {
                    isSongRepeated = false;
                    if (shuffle)
                    {
                        currentIndex = GetRandomIndex();
                    }
                    else
                    {
                        if (IsLast())
                        {
                            if (userChoice)
                            {
                                currentIndex = 0;
                            }
                            else
                            {
                                stop = true;
                            }
                        }
                        else
                        {
                            currentIndex++;
                        }
                    }
                }
                else
                {
                    if (userChoice)
                    {
                        if (shuffle)
                        {
                            currentIndex = GetRandomIndex();
                        }
                        else
                        {
                            if (IsLast())
                            {
                                if (userChoice)
                                {
                                    currentIndex = 0;
                                }
                                else
                                {
                                    stop = true;
                                }
                            }
                            else
                            {
                                currentIndex++;
                            }
                        }
                    }
                    else
                    {
                        isSongRepeated = true;
                    }
                }
            }
            else if (repeat == RepeatEnum.RepeatPlaylist)
            {
                if (shuffle)
                {
                    currentIndex = GetRandomIndex();
                }
                else
                {
                    if (isPlaylistRepeated)
                    {
                        if (IsLast())
                        {
                            if (userChoice)
                            {
                                currentIndex = 0;
                            }
                            else
                            {
                                currentIndex = 0;
                                //stop = true;
                            }
                        }
                        else
                        {
                            currentIndex++;
                        }
                    }
                    else
                    {
                        if (IsLast())
                        {
                            currentIndex       = 0;
                            isPlaylistRepeated = true;
                        }
                        else
                        {
                            currentIndex++;
                        }
                    }
                }
            }
            if (stop)
            {
                return(null);
            }

            ApplicationSettingsHelper.SaveSongIndex(currentIndex);
            song = GetCurrentSong();
            return(song);
        }
コード例 #27
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            try
            {
                var details = (SocketActivityTriggerDetails)taskInstance.TriggerDetails;
                Debug.WriteLine($"{details.Reason}");
                var internetProfile = NetworkInformation.GetInternetConnectionProfile();
                if (internetProfile == null)
                {
                    Debug.WriteLine("No internet..");
                    return;
                }
                string selectedUser = null;
                try
                {
                    var obj = ApplicationSettingsHelper.LoadSettingsValue("InstaApiSelectedUsername");
                    if (obj is string str)
                    {
                        selectedUser = str;
                    }
                }
                catch { }
                await CS.Load();

                A.InstaApiList = CS.InstaApiList;
                var api = !string.IsNullOrEmpty(selectedUser)?
                          (CS.InstaApiList.FirstOrDefault(x => x.GetLoggedUser().LoggedInUser.UserName.ToLower() == selectedUser.ToLower()) ?? CS.InstaApiList[0]) : CS.InstaApiList[0];


                //foreach (var api in CS.InstaApiList)
                {
                    try
                    {
                        var push = new PushClient(CS.InstaApiList, api)
                        {
                            IsRunningFromBackground = true
                        };
                        push.MessageReceived += A.OnMessageReceived;
                        push.OpenNow();
                        push.Start();

                        switch (details.Reason)
                        {
                        case SocketActivityTriggerReason.SocketClosed:
                        {
                            await Task.Delay(TimeSpan.FromSeconds(5));

                            await push.StartFresh();

                            break;
                        }

                        default:
                        {
                            var socket = details.SocketInformation.StreamSocket;
                            await push.StartWithExistingSocket(socket);

                            break;
                        }
                        }
                        await Task.Delay(TimeSpan.FromSeconds(5));

                        await push.TransferPushSocket();
                    }
                    catch { }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                Debug.WriteLine($"{typeof(SocketActivityTask).FullName}: Can't finish push cycle. Abort.");
            }
            finally
            {
                deferral.Complete();
            }
        }
コード例 #28
0
ファイル: App.xaml.cs プロジェクト: tmk907/NextPlayer
        /// <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 override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            var    statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
            string theme     = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppTheme) as string;
            if (theme.Equals(AppThemeEnum.Dark.ToString()))
            {
                statusBar.BackgroundColor = Windows.UI.Colors.Black;
                statusBar.ForegroundColor = Windows.UI.Colors.White;
            }
            else if (theme.Equals(AppThemeEnum.Light.ToString()))
            {
                statusBar.BackgroundColor = Windows.UI.Colors.White;
                statusBar.ForegroundColor = Windows.UI.Colors.Black;
            }
            bool isPhoneAccent = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsPhoneAccentSet);
            try
            {
                if (isPhoneAccent)
                {
                    Windows.UI.Color color = ((SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"]).Color;
                    ((SolidColorBrush)App.Current.Resources["UserAccentBrush"]).Color = color;
                }
                else
                {
                    string           hexColor = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppAccent) as string;
                    byte             a        = byte.Parse(hexColor.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
                    byte             r        = byte.Parse(hexColor.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
                    byte             g        = byte.Parse(hexColor.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
                    byte             b        = byte.Parse(hexColor.Substring(7, 2), System.Globalization.NumberStyles.HexNumber);
                    Windows.UI.Color color    = Windows.UI.Color.FromArgb(a, r, g, b);
                    ((SolidColorBrush)App.Current.Resources["UserAccentBrush"]).Color = color;
                }
            }
            catch (Exception ex)
            {
                DiagnosticHelper.TrackTrace("User accent set" + Environment.NewLine + ex.Message, SeverityLevel.Information);
            }
            if ((bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.IsBGImageSet))
            {
                Helpers.StyleHelper.EnableBGImage();
            }
            Helpers.StyleHelper.ChangeMainPageButtonsBackground();
            Helpers.StyleHelper.ChangeAlbumViewTransparency();

            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppState, AppConstants.ForegroundAppActive);
            Frame rootFrame = Window.Current.Content as Frame;

            bool fromTile = false;
            if (e.TileId.Contains(AppConstants.TileId))
            {
                string[] s = ParamConvert.ToStringArray(e.Arguments);

                if (s[0].Equals("album"))
                {
                    var a = DatabaseManager.GetSongItemsFromAlbum(s[1], s[2]);
                    Library.Current.SetNowPlayingList(a);
                }
                else if (s[0].Equals("playlist"))
                {
                    if (s[2].Equals(true.ToString()))
                    {
                        Library.Current.SetNowPlayingList(DatabaseManager.GetSongItemsFromSmartPlaylist(Int32.Parse(s[1])));
                    }
                    else
                    {
                        Library.Current.SetNowPlayingList(DatabaseManager.GetSongItemsFromPlainPlaylist(Int32.Parse(s[1])));
                    }
                }
                else if (s[0].Equals("artist"))
                {
                    Library.Current.SetNowPlayingList(DatabaseManager.GetSongItemsFromArtist(s[1]));
                }
                else if (s[0].Equals("genre"))
                {
                    Library.Current.SetNowPlayingList(DatabaseManager.GetSongItemsFromGenre(s[1]));
                }
                else if (s[0].Equals("folder"))
                {
                    Library.Current.SetNowPlayingList(DatabaseManager.GetSongItemsFromFolder(s[1]));
                }
                ApplicationSettingsHelper.SaveSongIndex(0);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TilePlay, true);
                rootFrame = null;
                fromTile  = true;
            }
            // 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();

                // Associate the frame with a SuspensionManager key.
                if (fromTile)
                {
                    SuspensionManager.SessionState.Clear();
                }
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                // TODO: change this value to a cache size that is appropriate for your application
                rootFrame.CacheSize = 1;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate.
                    if (!fromTile)
                    {
                        try
                        {
                            //Logger.Save("resumed terminate app");
                            //Logger.SaveToFile();
                            ApplicationSettingsHelper.SaveSettingsValue(AppConstants.ResumePlayback, "");
                            await SuspensionManager.RestoreAsync();
                        }
                        catch (SuspensionManagerException ex)
                        {
                            // Something went wrong restoring state.
                            // Assume there is no state and continue.
                            Logger.Save("App OnLaunched() SuspensionManagerException" + "\n" + ex.Message);
                            Logger.SaveToFileBG();
                        }
                    }
                }

                // 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
                if (!rootFrame.Navigate(typeof(View.MainPage), e.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            //rootFrame.Background = (ImageBrush)Resources["BgImage"];
            // Ensure the current window is active

            Window.Current.Activate();
            //SetDimensions();
            DispatcherHelper.Initialize();

            await HockeyClient.Current.SendCrashesAsync(true);
        }
コード例 #29
0
        /// <summary>
        /// Raised when a message is recieved from the foreground app
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            AppSuspendedMessage appSuspendedMessage;

            if (MessageService.TryParseMessage(e.Data, out appSuspendedMessage))
            {
                Debug.WriteLine("App suspending"); // App is suspended, you can save your task state at this point
                foregroundAppState = AppState.Suspended;
                var currentTrackId = GetCurrentTrackId();
                ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, currentTrackId == null ? null : currentTrackId.ToString());
                return;
            }

            AppResumedMessage appResumedMessage;

            if (MessageService.TryParseMessage(e.Data, out appResumedMessage))
            {
                Debug.WriteLine("App resuming"); // App is resumed, now subscribe to message channel
                foregroundAppState = AppState.Active;
                return;
            }

            //currentTrackId = GetCurrentTrackId();
            //ApplicationSettingsHelper.SaveSettingsValue(ApplicationSettingsConstants.TrackId, currentTrackId == null ? null : currentTrackId.ToString());
            StartPlaybackMessage startPlaybackMessage;

            if (MessageService.TryParseMessage(e.Data, out startPlaybackMessage))
            {
                //Foreground App process has signalled that it is ready for playback
                Debug.WriteLine("Starting Playback");
                StartPlayback();
                return;
            }

            SkipNextMessage skipNextMessage;

            if (MessageService.TryParseMessage(e.Data, out skipNextMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to next");
                SkipToNext();
                return;
            }

            SkipPreviousMessage skipPreviousMessage;

            if (MessageService.TryParseMessage(e.Data, out skipPreviousMessage))
            {
                // User has chosen to skip track from app context.
                Debug.WriteLine("Skipping to previous");
                SkipToPrevious();
                return;
            }

            DeleteTrackFromPlaybackList deleteTrackFromPlaybackList;

            if (MessageService.TryParseMessage(e.Data, out deleteTrackFromPlaybackList))
            {
                DeleteTrackFromPlaybackList(deleteTrackFromPlaybackList.Track.stream_url.ToString());
                return;
            }

            TrackChangedMessage trackChangedMessage;

            if (MessageService.TryParseMessage(e.Data, out trackChangedMessage))
            {
                var index = playbackList.Items.ToList().FindIndex(i => new Uri(i.Source.CustomProperties[TrackIdKey].ToString()) == trackChangedMessage.TrackId);
                Debug.WriteLine("Skipping to track " + index);
                smtc.PlaybackStatus = MediaPlaybackStatus.Changing;
                playbackList.MoveTo((uint)index);

                // TODO: Work around playlist bug that doesn't continue playing after a switch; remove later
                //BackgroundMediaPlayer.Current.Play();
                return;
            }

            UpdatePlaylistMessage updatePlaylistMessage;

            if (MessageService.TryParseMessage(e.Data, out updatePlaylistMessage))
            {
                CreatePlaybackListAndStartPlaying(updatePlaylistMessage.Songs);
                return;
            }

            DeviceFamilyMessage deviceFamilyMessage;

            if (MessageService.TryParseMessage(e.Data, out deviceFamilyMessage))
            {
                if (deviceFamilyMessage.DeviceFamily == "IoT")
                {
                    InitGPIO();
                    IsIoT = true;
                }
                return;
            }

            ShutdownBackgroundMediaPlayer shutdownBackgroundMediaPlayer;

            if (MessageService.TryParseMessage(e.Data, out shutdownBackgroundMediaPlayer))
            {
                UpdateUVCOnNewTrack(null);
                if (playbackList != null)
                {
                    playbackList.CurrentItemChanged -= PlaybackList_CurrentItemChanged;
                    playbackList = null;
                }

                BackgroundMediaPlayer.Shutdown();
                return;
            }
        }
コード例 #30
0
ファイル: App.xaml.cs プロジェクト: tmk907/NextPlayer
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            HockeyClient.Current.Configure("");

            //App.Current.RequestedTheme = ApplicationTheme.Dark;
            this.InitializeComponent();
            this.Suspending += this.OnSuspending;
            ApplicationSettingsHelper.ReadResetSettingsValue(AppConstants.MediaScan);
            var settings = ApplicationData.Current.LocalSettings;

            if (FirstRun())
            {
                //jesli jest DB jest tworzone po wersji 1.5.1.0 przy tworzeniu bazy trzeba zapisac jej wersje
                Library.Current.SetDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppTheme, AppThemeEnum.Dark.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.IsPhoneAccentSet, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.AppAccent, "#FF008A00");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.IsBGImageSet, false);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.BackgroundImagePath, "");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.ShowCoverAsBackground, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "yes");
                //DiagnosticHelper.TrackTrace("New instalation",Microsoft.HockeyApp.SeverityLevel.Information);
            }
            else
            {
                ManageSecondaryTileImages();

                if (!settings.Values.ContainsKey(AppConstants.BackgroundImagePath))
                {
                    settings.Values.Add(AppConstants.BackgroundImagePath, "");
                }
                if (!settings.Values.ContainsKey(AppConstants.IsBGImageSet))
                {
                    settings.Values.Add(AppConstants.IsBGImageSet, false);
                }
                if (!settings.Values.ContainsKey(AppConstants.AppTheme))
                {
                    settings.Values.Add(AppConstants.AppTheme, AppThemeEnum.Dark.ToString());
                }
                if (!settings.Values.ContainsKey(AppConstants.IsPhoneAccentSet))
                {
                    settings.Values.Add(AppConstants.IsPhoneAccentSet, true);
                }
                if (!settings.Values.ContainsKey(AppConstants.AppAccent))
                {
                    settings.Values.Add(AppConstants.AppAccent, "#FF008A00");
                }
                if (!settings.Values.ContainsKey(AppConstants.ShowCoverAsBackground))
                {
                    settings.Values.Add(AppConstants.ShowCoverAsBackground, true);
                }

                string theme = ApplicationSettingsHelper.ReadSettingsValue(AppConstants.AppTheme) as string;
                if (theme.Equals(AppThemeEnum.Dark.ToString()))
                {
                    App.Current.RequestedTheme = ApplicationTheme.Dark;
                }
                else if (theme.Equals(AppThemeEnum.Light.ToString()))
                {
                    App.Current.RequestedTheme = ApplicationTheme.Light;
                }

                SendLogs();

                //SaveLater.Current.SaveAllNow();
                UpdateDB();
                Logger.SaveFromSettingsToFile();
                CreateTask();
            }
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.TileAppTransparent) == null)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.TileAppTransparent, "yes");
            }
            #region LastFm

            //aplikacja jest uruchomiona 1 raz lub po aktualizacji
            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs) == null)
            {
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmRateSongs, true);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLove, 5);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmUnLove, 1);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmSendNP, false);
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmLogin, "");
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LfmPassword, "");
            }

            LastFmLove   = Int32.Parse(ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmLove).ToString());
            LastFmUnLove = Int32.Parse(ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmUnLove).ToString());
            LastFmRateOn = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmRateSongs);
            LastFmSendNP = (bool)ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LfmSendNP);

            if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LastFmDBVersion) == null)
            {
                DatabaseManager.CreateLastFmDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LastFmDBVersion, 1);
            }
            else if (ApplicationSettingsHelper.ReadSettingsValue(AppConstants.LastFmDBVersion).ToString() == "1")
            {
                DatabaseManager.DeleteLastFmDB();
                DatabaseManager.CreateLastFmDB();
                ApplicationSettingsHelper.SaveSettingsValue(AppConstants.LastFmDBVersion, 2);
            }

            #endregion LastFm

            UnhandledException += App_UnhandledException;
        }