void IDisposable.Dispose() { ServiceManager.PlaybackController.Stopped -= HandleServiceManagerPlaybackControllerStopped; ServiceManager.PlayerEngine.DisconnectEvent(playerEvent_Handler); client = null; }
static async Task MainAsync(string[] args, CancellationToken token) { if (args.Length != 3) { Console.WriteLine("No arguments found."); Console.WriteLine("Example: Server.exe /ServerUrl=http://localhost:9000/ /ServerId=0480216b-6c6c-4990-b8db-8ad9f1f78b83 /LogServer=http://localhost:8999/"); return; } var _serverUrlArg = args[0].Replace("/ServerUrl=", ""); var _serverIdArg = args[1].Replace("/ServerId=", ""); var _logServerArg = args[2].Replace("/LogServer=", ""); Console.WriteLine("Server base address: " + _serverUrlArg); Console.WriteLine("Server Id: " + _serverIdArg); Console.WriteLine("Log server address: " + _logServerArg); try { _serverId = new Guid(_serverIdArg); _log = new LogClient(_logServerArg, _serverId); string baseAddress = _serverUrlArg; await LogMessage("Server startup: " + baseAddress, MessageType.Message, token); using (WebApp.Start<Startup>(url: baseAddress)) { Console.WriteLine("Server is running: " + baseAddress); Console.WriteLine("Waiting for client incoming connections..."); await LogMessage("Server activated: " + baseAddress, MessageType.Message, token); Console.Read(); } } catch (Exception ex) { var exceptionMessage = await LogException("Error connecting to server", ex, token); Console.WriteLine(exceptionMessage); } await LogMessage("Server terminated", MessageType.Message, token); Console.WriteLine("Done"); }
static async Task MainAsync(string[] args, CancellationToken token) { if (args.Length != 3) { Console.WriteLine("No arguments found."); Console.WriteLine("Example: Client.exe /ClientId=bebbf242-3140-444d-9039-3e38b9b61834 /ServerUrl=http://localhost:9000/ /LogServer=http://localhost:8999/"); return; } var _clientIdArg = args[0].Replace("/ClientId=", ""); var _serverUrlArg = args[1].Replace("/ServerUrl=", ""); var _logServerArg = args[2].Replace("/LogServer=", ""); Console.WriteLine("Client Id: " + _clientIdArg); Console.WriteLine("Server address: " + _serverUrlArg); Console.WriteLine("Log server address: " + _logServerArg); try { _clientID = new Guid(_clientIdArg); _client = new RestClient(_serverUrlArg); _log = new LogClient(_logServerArg, _clientID); await LogMessage("Client started", MessageType.Message, token); await Connect(_clientID, token); var jobList = await GetCommands(_clientID, token); foreach (var job in jobList ?? new List<Dto.Job>()) { await ExecuteCommand(job, _clientID, token); } } catch(Exception ex) { Console.WriteLine(ex.Message); } await LogMessage("Client terminated", MessageType.Message, token); Console.WriteLine("Done"); }
public ZeitgeistClient () { dsReg = new DataSourceClient (); MonoDevelop.Core.LoggingService.LogInfo ("Zg#: init new"); Event ev = new Event (); ev.Actor = MonoDevelopUri; Subject sub = new Subject (); sub.Interpretation = Interpretation.Instance.Document.Document; sub.Manifestation = Manifestation.Instance.FileDataObject.FileDataObject; ev.Subjects.Add (sub); try { dsReg.RegisterDataSources (monodevelopDataSourceId, monodevelopDataSourceName, monodevelopDataSourceDesc, new List<Event> (){ev}); client = new LogClient (); } catch (Exception ex) { MonoDevelop.Core.LoggingService.LogError ("Error init", ex); } }
/// <summary> /// Connecte un client sur le site. ///</summary> public InfoBaseClient PostConnexionClient(int siteId, LogClient log) { return(base.Post <LogClient, InfoBaseClient>($"app/crosscanal/commandes/{ base.ConvertDataToUrlFragment(siteId, siteId.GetType()) }/clients/connexion", log)); }
private async Task GetGenresCommonAsync(IList <Genre> genres, GenreOrder genreOrder) { try { // Order the incoming Genres List <Genre> orderedGenres = await Common.Database.Utils.OrderGenresAsync(genres, genreOrder); // Create new ObservableCollection ObservableCollection <GenreViewModel> genreViewModels = new ObservableCollection <GenreViewModel>(); await Task.Run(() => { var tempGenreViewModels = new List <GenreViewModel>(); // Workaround to make sure the "#" GroupHeader is shown at the top of the list if (genreOrder == GenreOrder.Alphabetical) { tempGenreViewModels.AddRange(orderedGenres.Select((gen) => new GenreViewModel { Genre = gen, IsHeader = false }).Where((gvm) => gvm.Header.Equals("#"))); } tempGenreViewModels.AddRange(orderedGenres.Select((gen) => new GenreViewModel { Genre = gen, IsHeader = false }).Where((gvm) => !gvm.Header.Equals("#"))); if (genreOrder == GenreOrder.ReverseAlphabetical) { tempGenreViewModels.AddRange(orderedGenres.Select((gen) => new GenreViewModel { Genre = gen, IsHeader = false }).Where((gvm) => gvm.Header.Equals("#"))); } foreach (GenreViewModel gvm in tempGenreViewModels) { genreViewModels.Add(gvm); } }); // Unbind to improve UI performance if (this.GenresCvs != null) { this.GenresCvs.Filter -= new FilterEventHandler(GenresCvs_Filter); } this.Genres = null; this.GenresCvs = null; // Populate ObservableCollection this.Genres = new ObservableCollection <ISemanticZoomable>(genreViewModels); } catch (Exception ex) { LogClient.Error("An error occurred while getting Genres. Exception: {0}", ex.Message); // Failed getting Genres. Create empty ObservableCollection. this.Genres = new ObservableCollection <ISemanticZoomable>(); } // Populate CollectionViewSource this.GenresCvs = new CollectionViewSource { Source = this.Genres }; this.GenresCvs.Filter += new FilterEventHandler(GenresCvs_Filter); // Update count this.GenresCount = this.GenresCvs.View.Cast <ISemanticZoomable>().Count(); // Update Semantic Zoom Headers this.UpdateSemanticZoomHeaders(); }
static async Task Main(string[] args) { string socketname = "client.sock"; string mac = "000000000000"; string rfpMmask = "000000000000"; string filter = String.Empty; string filterMask = String.Empty; bool showHelp = false; bool logRaw = false; bool unknown = false; string pcap = null; var options = new OptionSet { { "s|socket=", "socket path", x => socketname = x }, { "r|rfp=", "rfp MAC address", x => mac = x }, { "rm|rfpmask=", "rfp mask", x => rfpMmask = x }, { "f|filter=", "filter", x => filter = x }, { "fm|filtermask=", "filter mask", x => filterMask = x }, { "raw", "log raw packets", x => logRaw = x != null }, { "u|unknown", "log only packets with unknown payload", x => unknown = x != null }, { "pcap=", "read packets from pcap file", x => pcap = x }, { "h|help", "show help", x => showHelp = x != null }, }; try { if (options.Parse(args).Count > 0) { showHelp = true; } } catch (OptionException ex) { Console.Error.Write("rfpproxy.log: "); Console.Error.WriteLine(ex.Message); Console.Error.WriteLine("Try 'dotnet rfpproxy.log.dll --help' for more information"); return; } if (showHelp) { options.WriteOptionDescriptions(Console.Error); return; } try { using (var cts = new CancellationTokenSource()) using (var client = new LogClient(socketname, logRaw, unknown)) { Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); client.Stop(); }; if (pcap != null) { await ReadPcapAsync(pcap, client.OnMessage, cts.Token).ConfigureAwait(false); return; } client.Log += (s, e) => { Console.Write(e.Direction == LogDirection.Read ? "< " : "> "); Console.WriteLine(e.Message); }; await client.AddListenAsync(mac, rfpMmask, filter, filterMask, cts.Token).ConfigureAwait(false); await client.RunAsync(cts.Token).ConfigureAwait(false); } } catch (OperationCanceledException) { } catch (SocketException ex) when(ex.SocketErrorCode == SocketError.OperationAborted) { } }
public void Close() { if (_logService != null && _logService.State != CommunicationState.Closed) _logService.Close(); _logService = null; }
private async Task <bool> InitializeNoteStorageDirectoryAsync() { bool isSuccess = true; var migrator = new DbMigrator(); // Move the old "Knowte.db" database file to "Notes\Notes.db". TODO: remove this later (e.g. in version 1.2) try { string oldDatabaseFile = Path.Combine(SettingsClient.ApplicationFolder(), "Knowte.db"); if (File.Exists(oldDatabaseFile) && !File.Exists(migrator.DatabaseFile)) { File.Move(oldDatabaseFile, migrator.DatabaseFile); } } catch (Exception ex) { LogClient.Error("The old database file could not be moved. Exception: {0}", ex.Message); this.errorMessage = ex.Message; isSuccess = false; } // Make sure the default note storage location exists if (!Directory.Exists(ApplicationPaths.DefaultNoteStorageLocation)) { Directory.CreateDirectory(ApplicationPaths.DefaultNoteStorageLocation); } // Further verification is only needed when not using the default storage location if (ApplicationPaths.IsUsingDefaultStorageLocation) { return(true); } try { await Task.Run(() => { if (!Directory.Exists(ApplicationPaths.CurrentNoteStorageLocation)) { LogClient.Warning("Note storage location '{0}' could not be found.", ApplicationPaths.CurrentNoteStorageLocation); isSuccess = false; } if (!migrator.DatabaseExists()) { LogClient.Warning("Database file '{0}' could not be found.", migrator.DatabaseFile); isSuccess = false; } if (!isSuccess) { // Restore the default storage location SettingsClient.Set <string>("General", "NoteStorageLocation", ""); LogClient.Warning("Default note storage location was restored."); // Allow the application to start up after the default storage location was restored isSuccess = true; } }); } catch (Exception ex) { LogClient.Error("There was a problem initializing the note storage location. Exception: {0}", ex.Message); this.errorMessage = ex.Message; isSuccess = false; } return(isSuccess); }
private async Task AddArtworkInBackgroundAsync(int passNumber) { LogClient.Info("+++ STARTED ADDING ARTWORK IN THE BACKGROUND +++"); this.canIndexArtwork = true; this.isIndexingArtwork = true; DateTime startTime = DateTime.Now; await Task.Run(async() => { using (SQLiteConnection conn = this.factory.GetConnection()) { try { IList <string> albumKeysWithArtwork = new List <string>(); IList <AlbumData> albumDatasToIndex = await this.trackRepository.GetAlbumDataToIndexAsync(); foreach (AlbumData albumDataToIndex in albumDatasToIndex) { // Check if we must cancel artwork indexing if (!this.canIndexArtwork) { try { LogClient.Info("+++ ABORTED ADDING ARTWORK IN THE BACKGROUND. Time required: {0} ms +++", Convert.ToInt64(DateTime.Now.Subtract(startTime).TotalMilliseconds)); this.AlbumArtworkAdded(this, new AlbumArtworkAddedEventArgs() { AlbumKeys = albumKeysWithArtwork }); // Update UI } catch (Exception ex) { LogClient.Error("Failed to commit changes while aborting adding artwork in background. Exception: {0}", ex.Message); } this.isIndexingArtwork = false; return; } // Start indexing artwork try { // Delete existing AlbumArtwork await this.albumArtworkRepository.DeleteAlbumArtworkAsync(albumDataToIndex.AlbumKey); // Create a new AlbumArtwork var albumArtwork = new AlbumArtwork(albumDataToIndex.AlbumKey); if (passNumber.Equals(1)) { // During the 1st pass, look for artwork in file(s). // Only set NeedsAlbumArtworkIndexing = 0 if artwork was found. So when no artwork was found, // this gives the 2nd pass a chance to look for artwork on the Internet. albumArtwork.ArtworkID = await this.GetArtworkFromFile(albumDataToIndex.AlbumKey); if (!string.IsNullOrEmpty(albumArtwork.ArtworkID)) { await this.trackRepository.DisableNeedsAlbumArtworkIndexingAsync(albumDataToIndex.AlbumKey); } } else if (passNumber.Equals(2)) { // During the 2nd pass, look for artwork on the Internet and set NeedsAlbumArtworkIndexing = 0. // We don't want future passes to index for this AlbumKey anymore. albumArtwork.ArtworkID = await this.GetArtworkFromInternet( albumDataToIndex.AlbumTitle, DataUtils.SplitAndTrimColumnMultiValue(albumDataToIndex.AlbumArtists).ToList(), albumDataToIndex.TrackTitle, DataUtils.SplitAndTrimColumnMultiValue(albumDataToIndex.Artists).ToList() ); await this.trackRepository.DisableNeedsAlbumArtworkIndexingAsync(albumDataToIndex.AlbumKey); } // If artwork was found, keep track of the albumID if (!string.IsNullOrEmpty(albumArtwork.ArtworkID)) { albumKeysWithArtwork.Add(albumArtwork.AlbumKey); conn.Insert(albumArtwork); } // If artwork was found for 20 albums, trigger a refresh of the UI. if (albumKeysWithArtwork.Count >= 20) { var eventAlbumKeys = new List <string>(albumKeysWithArtwork); albumKeysWithArtwork.Clear(); this.AlbumArtworkAdded(this, new AlbumArtworkAddedEventArgs() { AlbumKeys = eventAlbumKeys }); // Update UI } } catch (Exception ex) { LogClient.Error("There was a problem while updating the cover art for Album {0}/{1}. Exception: {2}", albumDataToIndex.AlbumTitle, albumDataToIndex.AlbumArtists, ex.Message); } } try { this.AlbumArtworkAdded(this, new AlbumArtworkAddedEventArgs() { AlbumKeys = albumKeysWithArtwork }); // Update UI } catch (Exception ex) { LogClient.Error("Failed to commit changes while finishing adding artwork in background. Exception: {0}", ex.Message); } } catch (Exception ex) { LogClient.Error("Unexpected error occurred while updating artwork in the background. Exception: {0}", ex.Message); } } }); this.isIndexingArtwork = false; LogClient.Error("+++ FINISHED ADDING ARTWORK IN THE BACKGROUND. Time required: {0} ms +++", Convert.ToInt64(DateTime.Now.Subtract(startTime).TotalMilliseconds)); }
private async Task <long> AddTracksAsync() { long numberAddedTracks = 0; var args = new IndexingStatusEventArgs() { IndexingAction = IndexingAction.AddTracks, ProgressPercent = 0 }; await Task.Run(() => { try { long currentValue = 0; long totalValue = this.newDiskPaths.Count; long saveItemCount = IndexerUtils.CalculateSaveItemCount(totalValue); long unsavedItemCount = 0; int lastPercent = 0; using (var conn = this.factory.GetConnection()) { conn.BeginTransaction(); foreach (FolderPathInfo newDiskPath in this.newDiskPaths) { Track diskTrack = Track.CreateDefault(newDiskPath.Path); try { this.ProcessTrack(diskTrack, conn); if (!this.cache.HasCachedTrack(ref diskTrack)) { conn.Insert(diskTrack); this.cache.AddTrack(diskTrack); numberAddedTracks += 1; unsavedItemCount += 1; } conn.Insert(new FolderTrack(newDiskPath.FolderId, diskTrack.TrackID)); // Intermediate save to the database if 20% is reached if (unsavedItemCount == saveItemCount) { unsavedItemCount = 0; conn.Commit(); // Intermediate save conn.BeginTransaction(); } } catch (Exception ex) { LogClient.Error("There was a problem while adding Track with path='{0}'. Exception: {1}", diskTrack.Path, ex.Message); } currentValue += 1; int percent = IndexerUtils.CalculatePercent(currentValue, totalValue); // Report progress if at least 1 track is added OR when the progress // interval has been exceeded OR the maximum has been reached. bool mustReportProgress = numberAddedTracks == 1 || percent >= lastPercent + 5 || percent == 100; if (mustReportProgress) { lastPercent = percent; args.ProgressCurrent = numberAddedTracks; args.ProgressPercent = percent; this.IndexingStatusChanged(args); } } conn.Commit(); // Final save } } catch (Exception ex) { LogClient.Error("There was a problem while adding Tracks. Exception: {0}", ex.Message); } }); return(numberAddedTracks); }
private async Task <long> UpdateTracksAsync() { long numberUpdatedTracks = 0; var args = new IndexingStatusEventArgs() { IndexingAction = IndexingAction.UpdateTracks, ProgressPercent = 0 }; await Task.Run(() => { try { using (var conn = this.factory.GetConnection()) { conn.BeginTransaction(); List <Track> alltracks = conn.Table <Track>().Select((t) => t).ToList(); long currentValue = 0; long totalValue = alltracks.Count; int lastPercent = 0; foreach (Track dbTrack in alltracks) { try { if (IndexerUtils.IsTrackOutdated(dbTrack) | dbTrack.NeedsIndexing == 1) { this.ProcessTrack(dbTrack, conn); conn.Update(dbTrack); numberUpdatedTracks += 1; } } catch (Exception ex) { LogClient.Error("There was a problem while updating Track with path='{0}'. Exception: {1}", dbTrack.Path, ex.Message); } currentValue += 1; int percent = IndexerUtils.CalculatePercent(currentValue, totalValue); // Report progress if at least 1 track is updated OR when the progress // interval has been exceeded OR the maximum has been reached. bool mustReportProgress = numberUpdatedTracks == 1 || percent >= lastPercent + 5 || percent == 100; if (mustReportProgress) { lastPercent = percent; args.ProgressPercent = percent; this.IndexingStatusChanged(args); } } conn.Commit(); } } catch (Exception ex) { LogClient.Error("There was a problem while updating Tracks. Exception: {0}", ex.Message); } }); return(numberUpdatedTracks); }
private async Task <long> RemoveTracksAsync() { long numberRemovedTracks = 0; var args = new IndexingStatusEventArgs() { IndexingAction = IndexingAction.RemoveTracks, ProgressPercent = 0 }; await Task.Run(() => { try { using (var conn = this.factory.GetConnection()) { conn.BeginTransaction(); // Create a list of folderIDs List <long> folderTrackIDs = conn.Table <FolderTrack>().ToList().Select((t) => t.TrackID).Distinct().ToList(); List <Track> alltracks = conn.Table <Track>().Select((t) => t).ToList(); List <Track> tracksInMissingFolders = alltracks.Select((t) => t).Where(t => !folderTrackIDs.Contains(t.TrackID)).ToList(); List <Track> remainingTracks = new List <Track>(); // Processing tracks in missing folders in bulk first, then checking // existence of the remaining tracks, improves speed of removing tracks. if (tracksInMissingFolders.Count > 0 && tracksInMissingFolders.Count < alltracks.Count) { remainingTracks = alltracks.Except(tracksInMissingFolders).ToList(); } else { remainingTracks = alltracks; } // 1. Process tracks in missing folders // ------------------------------------ if (tracksInMissingFolders.Count > 0) { // Report progress immediately, as there are tracks in missing folders. this.IndexingStatusChanged(args); // Delete foreach (Track trk in tracksInMissingFolders) { conn.Delete(trk); } numberRemovedTracks += tracksInMissingFolders.Count; } // 2. Process remaining tracks // --------------------------- if (remainingTracks.Count > 0) { foreach (Track trk in remainingTracks) { // If a remaining track doesn't exist on disk, delete it from the collection. if (!System.IO.File.Exists(trk.Path)) { conn.Delete(trk); numberRemovedTracks += 1; // Report progress as soon as the first track was removed. // This is indeterminate progress. No need to sent it multiple times. if (numberRemovedTracks == 1) { this.IndexingStatusChanged(args); } } } } conn.Commit(); } } catch (Exception ex) { LogClient.Error("There was a problem while removing Tracks. Exception: {0}", ex.Message); } }); return(numberRemovedTracks); }
private async Task CheckCollectionAsync(bool forceIndexing) { if (this.IsIndexing) { return; } LogClient.Info("+++ STARTED CHECKING COLLECTION +++"); this.canIndexArtwork = false; // Wait until artwork indexing is stopped while (this.isIndexingArtwork) { await Task.Delay(100); } await this.watcherManager.StopWatchingAsync(); try { this.allDiskPaths = await this.GetFolderPaths(); using (var conn = this.factory.GetConnection()) { bool performIndexing = false; if (forceIndexing) { performIndexing = true; } else { long databaseNeedsIndexingCount = conn.Table <Track>().Select(t => t).ToList().Where(t => t.NeedsIndexing == 1).LongCount(); long databaseLastDateFileModified = conn.Table <Track>().Select(t => t).ToList().OrderByDescending(t => t.DateFileModified).Select(t => t.DateFileModified).FirstOrDefault(); long diskLastDateFileModified = this.allDiskPaths.Count > 0 ? this.allDiskPaths.Select((t) => t.DateModifiedTicks).OrderByDescending((t) => t).First() : 0; long databaseTrackCount = conn.Table <Track>().Select(t => t).LongCount(); performIndexing = databaseNeedsIndexingCount > 0 | databaseTrackCount != this.allDiskPaths.Count | databaseLastDateFileModified < diskLastDateFileModified; } if (performIndexing) { await Task.Delay(1000); await this.IndexCollectionAsync(); } else { if (SettingsClient.Get <bool>("Indexing", "RefreshCollectionAutomatically")) { this.AddArtworkInBackgroundAsync(); await this.watcherManager.StartWatchingAsync(); } } } } catch (Exception ex) { LogClient.Error("Could not check the collection. Exception: {0}", ex.Message); } }
public async Task <DequeueResult> DequeueAsync(IList <TrackViewModel> tracks) { bool isSuccess = true; bool isPlayingTrackDequeued = false; IList <TrackViewModel> dequeuedTracks = new List <TrackViewModel>(); TrackViewModel nextAvailableTrack = null; await Task.Run(() => { lock (this.queueLock) { try { // First, get the tracks to dequeue and which are in the queue (normally it's all of them. But we're just making sure.) IList <TrackViewModel> tracksToDequeue = this.queue.Where(x => tracks.Contains(x)).ToList(); // Then, remove from playbackOrder foreach (TrackViewModel trackToDequeue in tracksToDequeue) { try { try { nextAvailableTrack = this.queue[this.playbackOrder[this.FindPlaybackOrderIndex(trackToDequeue) + 1]]; } catch (Exception) { // Intended suppression } this.playbackOrder.Remove(this.FindPlaybackOrderIndex(trackToDequeue)); } catch (Exception ex) { LogClient.Error($"Error while removing track with path='{trackToDequeue.Path}' from the playbackOrder. Exception: {ex.Message}"); throw; } } // Finally, remove from queue foreach (TrackViewModel trackToDequeue in tracksToDequeue) { try { this.queue.Remove(trackToDequeue); isPlayingTrackDequeued = isPlayingTrackDequeued || trackToDequeue.Equals(this.currentTrack); dequeuedTracks.Add(trackToDequeue); } catch (Exception ex) { LogClient.Error($"Error while removing track with path='{trackToDequeue.Path}' from the queue. Exception: {ex.Message}"); throw; } } } catch (Exception ex) { LogClient.Error($"Error while removing tracks from the queue. Queue will be cleared. Exception: {ex.Message}"); isSuccess = false; } } }); if (!isSuccess) { LogClient.Warning($"Removing tracks from queue failed. Clearing queue."); await this.ClearQueueAsync(); dequeuedTracks = new List <TrackViewModel>(tracks); } var dequeueResult = new DequeueResult { IsSuccess = isSuccess, DequeuedTracks = dequeuedTracks, NextAvailableTrack = nextAvailableTrack, IsPlayingTrackDequeued = isPlayingTrackDequeued }; return(dequeueResult); }
protected override void RegisterTypes(IContainerRegistry containerRegistry) { RegisterCoreComponents(); RegisterFactories(); RegisterRepositories(); RegisterServices(); InitializeServices(); RegisterViews(); RegisterViewModels(); void RegisterCoreComponents() { containerRegistry.RegisterInstance <IContainerProvider>(Container); containerRegistry.RegisterInstance <ILocalizationInfo>(new LocalizationInfo()); } void RegisterFactories() { containerRegistry.RegisterSingleton <ISQLiteConnectionFactory, SQLiteConnectionFactory>(); } void RegisterRepositories() { containerRegistry.RegisterSingleton <IFolderRepository, FolderRepository>(); containerRegistry.RegisterSingleton <ITrackRepository, TrackRepository>(); containerRegistry.RegisterSingleton <IAlbumArtworkRepository, AlbumArtworkRepository>(); containerRegistry.RegisterSingleton <IQueuedTrackRepository, QueuedTrackRepository>(); } void RegisterServices() { containerRegistry.RegisterSingleton <ICacheService, CacheService>(); containerRegistry.RegisterSingleton <IUpdateService, UpdateService>(); containerRegistry.RegisterSingleton <IAppearanceService, AppearanceService>(); containerRegistry.RegisterSingleton <II18nService, I18nService>(); containerRegistry.RegisterSingleton <IDialogService, DialogService>(); containerRegistry.RegisterSingleton <IIndexingService, IndexingService>(); containerRegistry.RegisterSingleton <IStatisticsService, StatisticsService>(); containerRegistry.RegisterSingleton <IPlaybackService, PlaybackService>(); containerRegistry.RegisterSingleton <IWin32InputService, Win32InputService>(); containerRegistry.RegisterSingleton <ISearchService, SearchService>(); containerRegistry.RegisterSingleton <ITaskbarService, TaskbarService>(); containerRegistry.RegisterSingleton <ICollectionService, CollectionService>(); containerRegistry.RegisterSingleton <IFoldersService, FoldersService>(); containerRegistry.RegisterSingleton <IJumpListService, JumpListService>(); containerRegistry.RegisterSingleton <IFileService, FileService>(); containerRegistry.RegisterSingleton <ICommandService, CommandService>(); containerRegistry.RegisterSingleton <IMetadataService, MetadataService>(); containerRegistry.RegisterSingleton <IEqualizerService, EqualizerService>(); containerRegistry.RegisterSingleton <IProviderService, ProviderService>(); containerRegistry.RegisterSingleton <IScrobblingService, ScrobblingService>(); containerRegistry.RegisterSingleton <IPlaylistService, PlaylistService>(); containerRegistry.RegisterSingleton <IExternalControlService, ExternalControlService>(); containerRegistry.RegisterSingleton <IWindowsIntegrationService, WindowsIntegrationService>(); containerRegistry.RegisterSingleton <ILyricsService, LyricsService>(); containerRegistry.RegisterSingleton <IShellService, ShellService>(); containerRegistry.RegisterSingleton <ILifetimeService, LifetimeService>(); containerRegistry.RegisterSingleton <IInfoDownloadService, InfoDownloadService>(); INotificationService notificationService; // NotificationService contains code that is only supported on Windows 10 if (Core.Base.Constants.IsWindows10 && MediaFoundationHelper.HasMediaFoundationSupport(true)) { // On some editions of Windows 10, constructing NotificationService still fails // (e.g. Windows 10 Enterprise N 2016 LTSB). Hence the try/catch block. try { notificationService = new NotificationService( Container.Resolve <IPlaybackService>(), Container.Resolve <ICacheService>(), Container.Resolve <IMetadataService>()); } catch (Exception ex) { LogClient.Error("Constructing NotificationService failed. Falling back to LegacyNotificationService. Exception: {0}", ex.Message); notificationService = new LegacyNotificationService( Container.Resolve <IPlaybackService>(), Container.Resolve <ICacheService>(), Container.Resolve <IMetadataService>()); } } else { notificationService = new LegacyNotificationService( Container.Resolve <IPlaybackService>(), Container.Resolve <ICacheService>(), Container.Resolve <IMetadataService>()); } containerRegistry.RegisterInstance(notificationService); } void InitializeServices() { // Making sure resources are set before we need them Container.Resolve <II18nService>().ApplyLanguageAsync(SettingsClient.Get <string>("Appearance", "Language")); Container.Resolve <IAppearanceService>().ApplyTheme(SettingsClient.Get <bool>("Appearance", "EnableLightTheme")); Container.Resolve <IAppearanceService>().ApplyColorSchemeAsync( SettingsClient.Get <string>("Appearance", "ColorScheme"), SettingsClient.Get <bool>("Appearance", "FollowWindowsColor"), SettingsClient.Get <bool>("Appearance", "FollowAlbumCoverColor") ); Container.Resolve <IExternalControlService>(); } void RegisterViews() { // Misc. containerRegistry.Register <object, Oobe>(typeof(Oobe).FullName); containerRegistry.Register <object, TrayControls>(typeof(TrayControls).FullName); containerRegistry.Register <object, Shell>(typeof(Shell).FullName); containerRegistry.Register <object, Empty>(typeof(Empty).FullName); containerRegistry.Register <object, FullPlayer>(typeof(FullPlayer).FullName); containerRegistry.Register <object, CoverPlayer>(typeof(CoverPlayer).FullName); containerRegistry.Register <object, MicroPlayer>(typeof(MicroPlayer).FullName); containerRegistry.Register <object, NanoPlayer>(typeof(NanoPlayer).FullName); containerRegistry.Register <object, NowPlaying>(typeof(NowPlaying).FullName); containerRegistry.Register <object, WindowControls>(typeof(WindowControls).FullName); // Collection containerRegistry.Register <object, CollectionMenu>(typeof(CollectionMenu).FullName); containerRegistry.Register <object, Collection>(typeof(Collection).FullName); containerRegistry.Register <object, CollectionAlbums>(typeof(CollectionAlbums).FullName); containerRegistry.Register <object, CollectionArtists>(typeof(CollectionArtists).FullName); containerRegistry.Register <object, CollectionPlaylists>(typeof(CollectionPlaylists).FullName); containerRegistry.Register <object, CollectionFolders>(typeof(CollectionFolders).FullName); containerRegistry.Register <object, CollectionGenres>(typeof(CollectionGenres).FullName); containerRegistry.Register <object, CollectionTracks>(typeof(CollectionTracks).FullName); // Settings containerRegistry.Register <object, SettingsMenu>(typeof(SettingsMenu).FullName); containerRegistry.Register <object, Settings>(typeof(Settings).FullName); containerRegistry.Register <object, SettingsAppearance>(typeof(SettingsAppearance).FullName); containerRegistry.Register <object, SettingsBehaviour>(typeof(SettingsBehaviour).FullName); containerRegistry.Register <object, SettingsOnline>(typeof(SettingsOnline).FullName); containerRegistry.Register <object, SettingsPlayback>(typeof(SettingsPlayback).FullName); containerRegistry.Register <object, SettingsStartup>(typeof(SettingsStartup).FullName); // Information containerRegistry.Register <object, InformationMenu>(typeof(InformationMenu).FullName); containerRegistry.Register <object, Information>(typeof(Information).FullName); containerRegistry.Register <object, InformationHelp>(typeof(InformationHelp).FullName); containerRegistry.Register <object, InformationAbout>(typeof(InformationAbout).FullName); // Now playing containerRegistry.Register <object, NowPlayingArtistInformation>(typeof(NowPlayingArtistInformation).FullName); containerRegistry.Register <object, NowPlayingLyrics>(typeof(NowPlayingLyrics).FullName); containerRegistry.Register <object, NowPlayingPlaylist>(typeof(NowPlayingPlaylist).FullName); containerRegistry.Register <object, NowPlayingShowcase>(typeof(NowPlayingShowcase).FullName); } void RegisterViewModels() { } }
public GsMeasurementDetail() { Checked = false; _logClient = new LogClient(typeof(GsMeasurementDetail)); }
void IExtensionService.Initialize() { try { client = new LogClient (); if (client != null) { Log.Debug("Zeitgeist client created"); // Try to register the datasource in DataSource registry dsReg = new DataSourceClient(); try { // Register the datasource/dataprovider dsReg.RegisterDataSources(bansheeDataSourceId, bansheeDataSourceName, bansheeDataSourceDesc , PopulateAllDataSourceTemplates() ); } catch(Exception exp) { // Nazi exception handler // Can be fixed when zeitgeist-sharp is migrated from ndesk-dbus to dbus-sharp Log.Exception(exp); } // Handle the events ServiceManager.PlaybackController.Stopped += HandleServiceManagerPlaybackControllerStopped; ServiceManager.PlayerEngine.ConnectEvent(playerEvent_Handler, PlayerEvent.StartOfStream | PlayerEvent.EndOfStream); } else { Log.Warning ("Could not create Zeitgeist client"); } } catch (Exception e) { Log.Exception (e); } }
private void AddTimeStampToSelectedLyricsLine() { if (this.lyricsTextBox != null) { try { int lineIndex = this.lyricsTextBox.GetLineIndexFromCharacterIndex(this.lyricsTextBox.CaretIndex); int lineStartIndex = this.lyricsTextBox.GetCharacterIndexFromLineIndex(lineIndex); string line = this.lyricsTextBox.GetLineText(lineIndex); if (line.Trim().Length == 0) { this.lyricsTextBox.CaretIndex += 1; // Jump to the next line return; // Don't try to add a timeStamp to an empty line (Trim removes newline characters) } string strippedLine = string.Empty; if (line.Length > 0 && line.StartsWith("[")) { int index = line.IndexOf(']'); if (index > 0) { strippedLine = line.Substring(index + 1); } } else { strippedLine = line; } TimeSpan currentPlaybackTime = this.playbackService.GetCurrentTime; int minutes = currentPlaybackTime.Minutes + currentPlaybackTime.Hours * 60; int seconds = currentPlaybackTime.Seconds; int milliseconds = currentPlaybackTime.Milliseconds; string format = string.Format("[{0:00}:{1:00}.{2:000}]", minutes, seconds, milliseconds); string newLine = string.Format("{0}{1}", new DateTime(currentPlaybackTime.Ticks).ToString(format), strippedLine); this.lyricsTextBox.Text = this.lyricsTextBox.Text.Remove(lineStartIndex, line.Length); this.lyricsTextBox.Text = this.lyricsTextBox.Text.Insert(lineStartIndex, newLine); this.lyricsTextBox.CaretIndex = lineStartIndex + newLine.Length; // Jump over empty lines line = this.lyricsTextBox.GetLineText(this.lyricsTextBox.GetLineIndexFromCharacterIndex(this.lyricsTextBox.CaretIndex)); while (line.Trim().Length == 0) { // Make sure to get out of the loop if an empty line was found at the end of the lyrics if (this.lyricsTextBox.CaretIndex == this.lyricsTextBox.Text.Length) { break; } this.lyricsTextBox.CaretIndex += 1; line = this.lyricsTextBox.GetLineText(this.lyricsTextBox.GetLineIndexFromCharacterIndex(this.lyricsTextBox.CaretIndex)); } } catch (Exception ex) { LogClient.Error("Could not add timeStamp to selected lyrics line. Exception: {0}", ex.Message); } } }
/// <summary> /// Starts our new bot thread /// </summary> public void begin() { _logger = Log.createClient(_config["General/botScript"].Value); _botThread = new Thread(new ThreadStart(newBot)); _botThread.IsBackground = true; _botThread.Name = "BotThread"; _botThread.Start(); }
public async Task <DequeueResult> DequeueAsync(IList <KeyValuePair <string, PlayableTrack> > tracks) { bool isSuccess = true; var dequeuedTracks = new List <KeyValuePair <string, PlayableTrack> >(); int indexOfLastDeueuedTrack = 0; bool isPlayingTrackDequeued = false; await Task.Run(() => { lock (this.queueLock) { foreach (KeyValuePair <string, PlayableTrack> track in tracks) { try { if (this.queue.ContainsKey(track.Key)) { // If the key is known, remove by key. this.queue.Remove(track.Key); dequeuedTracks.Add(track); // If the key is known, indicate if the current track was dequeued by comparing the keys. isPlayingTrackDequeued = track.Key.Equals(this.currentTrack.Key); } else { // If the key is not known, get all queued tracks which have the same path. List <KeyValuePair <string, PlayableTrack> > queuedTracksWithSamePath = this.queue.Select(t => t).Where(t => t.Value.SafePath.Equals(track.Value.SafePath)).ToList(); // Remove all queued track which have the same path foreach (KeyValuePair <string, PlayableTrack> queuedTrackWithSamePath in queuedTracksWithSamePath) { this.queue.Remove(queuedTrackWithSamePath.Key); dequeuedTracks.Add(queuedTrackWithSamePath); // If the key is not known, indicate if the current track was dequeued by comparing the paths. isPlayingTrackDequeued = queuedTrackWithSamePath.Value.Equals(this.currentTrack.Value); } } } catch (Exception ex) { isSuccess = false; LogClient.Error("Error while removing queued track with path='{0}'. Exception: {1}", track.Value.Path, ex.Message); } } foreach (KeyValuePair <string, PlayableTrack> dequeuedTrack in dequeuedTracks) { try { int indexOfCurrentDequeuedTrack = this.playbackOrder.IndexOf(dequeuedTrack.Key); if (indexOfLastDeueuedTrack == 0 | indexOfCurrentDequeuedTrack < indexOfLastDeueuedTrack) { indexOfLastDeueuedTrack = indexOfCurrentDequeuedTrack; } this.playbackOrder.Remove(dequeuedTrack.Key); } catch (Exception ex) { isSuccess = false; LogClient.Error("Error while removing shuffled track with path='{0}'. Exception: {1}", dequeuedTrack.Value.Path, ex.Message); } } } }); var dequeueResult = new DequeueResult { IsSuccess = isSuccess, DequeuedTracks = dequeuedTracks, IsPlayingTrackDequeued = isPlayingTrackDequeued }; if (isSuccess & isPlayingTrackDequeued & this.playbackOrder.Count > indexOfLastDeueuedTrack) { dequeueResult.NextAvailableTrack = new KeyValuePair <string, PlayableTrack>(this.playbackOrder[indexOfLastDeueuedTrack], this.queue[this.playbackOrder[indexOfLastDeueuedTrack]]); } return(dequeueResult); }
public GsOpenLocation() { _logClient = new LogClient(typeof(GsOpenLocation)); }
private async Task UpdateFileMetadataAsync() { bool restartTimer = false; this.updateFileMetadataTimer.Stop(); this.isUpdatingFileMetadata = true; var filesToSync = new List <FileMetadata>(); await Task.Run(() => { lock (lockObject) { int numberToProcess = this.fileMetadataDictionary.Count; if (numberToProcess == 0) { return; } while (numberToProcess > 0) { FileMetadata fmd = this.fileMetadataDictionary.First().Value; numberToProcess--; try { fmd.Save(); filesToSync.Add(fmd); this.fileMetadataDictionary.Remove(fmd.SafePath); } catch (IOException ex) { LogClient.Error("Unable to save metadata to the file for Track '{0}'. The file is probably playing. Trying again in {1} seconds. Exception: {2}", fmd.SafePath, this.updateFileMetadataLongTimeout / 1000, ex.Message); } catch (Exception ex) { LogClient.Error("Unable to save metadata to the file for Track '{0}'. Not trying again. Exception: {1}", fmd.SafePath, ex.Message); this.fileMetadataDictionary.Remove(fmd.SafePath); } } // If there are still queued FileMetadata's, start the timer. if (this.fileMetadataDictionary.Count > 0) { restartTimer = true; } } }); // Sync file size and last modified date in the database foreach (FileMetadata fmd in filesToSync) { await this.trackRepository.UpdateTrackFileInformationAsync(fmd.SafePath); } this.updateFileMetadataTimer.Interval = this.updateFileMetadataLongTimeout; // The next time, wait longer. this.isUpdatingFileMetadata = false; if (restartTimer) { this.updateFileMetadataTimer.Start(); } }
void IExtensionService.Initialize() { try { client = new LogClient (); if (client != null) { Log.Debug("Zeitgeist client created"); ServiceManager.PlaybackController.Stopped += HandleServiceManagerPlaybackControllerStopped; ServiceManager.PlayerEngine.ConnectEvent(playerEvent_Handler, PlayerEvent.StartOfStream); } else { Log.Warning ("Could not create Zeitgeist client"); } } catch (Exception e) { Log.Exception (e); } }
private double GetCurrentBarHeight(int barIndex, out bool isZero) { int i = 0; try { i = this.barIndexMax[barIndex]; double controlHeight = this.RenderSize.Height; double barHeight = 0d; if (this.soundPlayer.IsPlaying && i < channelData.Length) { switch (this.AnimationStyle) { case SpectrumAnimationStyle.Gentle: this.channelData[i] = Math.Max(0, this.channelData[i] - 0.003f); break; // Do nothing default: break; } double dbValue = 20 * Math.Log10(this.channelData[i]); double fftBucketHeight = ((dbValue - minDBValue) / dbScale) * controlHeight; barHeight = Math.Max(0f, fftBucketHeight); } // Bars can never surpass the height of the control if (barHeight > controlHeight) { barHeight = controlHeight; } float preData = this.preBarHeight[barIndex]; if (preData < barHeight) { preData = (float)barHeight; } else { preData = (float)(barHeight + (this.preBarHeightDelay * preData)) / ((float)(this.preBarHeightDelay + 1)); } isZero = !(preData > 0.05); this.preBarHeight[barIndex] = preData; switch (this.AnimationStyle) { case SpectrumAnimationStyle.Nervous: return(barHeight); case SpectrumAnimationStyle.Gentle: return(preData); default: return(0); } } catch (Exception ex) { LogClient.Error($"Could not determine GetCurrentBarHeight. barIndex={barIndex}, barIndexMax.Length={this.barIndexMax.Length}, preBarHeight.Length={this.preBarHeight.Length},i={i}, channelData.Length={this.channelData.Length}. Exception: {ex.Message}"); isZero = true; return(0); } }