/// <summary>
        /// Executes flush operation on a collection of data pieces asynchronously.
        /// </summary>
        private async Task FlushCoreAsync(ICollection <DataPiece> data)
        {
            var    filename = FileNaming.GenerateDataQueueFilename();
            string filepath = Path.Combine(FileNaming.DataQueuePath, filename);

            Log.Debug("Flushing collector with {0} data pieces to {1}", data.Count, filename);

            try {
                using (var fileStream = await FileOperations.CreateNewFile(filepath)) {
                    using (var textWrite = new StreamWriter(fileStream, Encoding.UTF8)) {
                        var serializer = JsonSerializer.Create();

                        await Task.Run(() => {
                            serializer.Serialize(textWrite, data, typeof(ICollection <DataPiece>));

                            //Early flush on background thread
                            textWrite.Flush();
                            fileStream.Flush();
                        });
                    }
                }
            }
            catch (Exception ex) {
                Log.Error(ex, "Failed flushing data collector to file {0}", filepath);
                UserLog.Add(UserLog.Icon.Error, LogStrings.FileWriteError);
            }

            UserLog.Add(UserLog.Icon.None, LogStrings.FileWriteSuccess);
            OnFileGenerated(filepath);
        }
Esempio n. 2
0
        /// <summary>
        /// Loads the movie DB.
        /// </summary>
        private static void LoadMovieDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            FileData[] files = FastDirectoryEnumerator.GetFiles(path, "*.movie.gz", SearchOption.TopDirectoryOnly);

            MovieDBFactory.MovieDatabase.Clear();

            foreach (FileData file in files)
            {
                string json = Gzip.Decompress(file.Path);

                var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel;

                MovieDBFactory.MovieDatabase.Add(movieModel);

                string title = FileNaming.RemoveIllegalChars(movieModel.Title);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";

                if (File.Exists(poster))
                {
                    movieModel.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    movieModel.SmallFanart = ImageHandler.LoadImage(fanart);
                }
            }
        }
Esempio n. 3
0
        public void FileDateTimePatten()
        {
            String   pattern  = "*CFyyyy*_hello";
            DateTime fileDate = file.CreationTime;


            string name = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            Assert.AreEqual(fileDate.ToString("yyyy") + "_hello.jpg", Path.GetFileName(name));


            pattern = "*CFyy*_hi.tmp";
            name    = FileNaming.GenerateFileName(png_file, pattern, false, dir, "");
            Assert.AreEqual(fileDate.ToString("yy") + "_hi.tmp.png", Path.GetFileName(name));

            pattern = "hello_*CFMM*_World.jpeg";
            name    = FileNaming.GenerateFileName(file, pattern, false, dir, "");
            Assert.AreEqual("hello_" + fileDate.ToString("MM") + "_World.jpeg", Path.GetFileName(name));


            pattern = "*CFyy*_*CFMMM*_*CFdd*_*CFHH*_*CFmm*_*CFss*.jpeg";
            name    = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            string generated = fileDate.ToString("yy") + "_" + fileDate.ToString("MMM") +
                               "_" + fileDate.ToString("dd") + "_" + fileDate.ToString("HH") +
                               "_" + fileDate.ToString("mm") + "_" + fileDate.ToString("ss") + ".jpeg";

            Assert.AreEqual(generated, Path.GetFileName(name));

            //fffffff
            pattern = "*CFff*";
            name    = FileNaming.GenerateFileName(file, pattern, false, dir, "");
            Assert.AreEqual(fileDate.ToString("ff") + ".jpg", Path.GetFileName(name));
        }
Esempio n. 4
0
        /// <summary>
        /// Handles the DoWork event of the SavingTVDB control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void SavingTVDB_DoWork(object sender, DoWorkEventArgs e)
        {
            var    series = e.Argument as Series;
            string path   = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;
            string title  = FileNaming.RemoveIllegalChars(series.SeriesName);

            string writePath = path + title + ".Series";
            string json      = JsonConvert.SerializeObject(series);

            Gzip.CompressString(json, writePath + ".gz");

            if (series.SmallBanner != null)
            {
                var smallBanner = new Bitmap(series.SmallBanner);
                smallBanner.Save(path + title + ".banner.jpg");
            }

            if (series.SmallFanart != null)
            {
                var smallFanart = new Bitmap(series.SmallFanart);
                smallFanart.Save(path + title + ".fanner.jpg");
            }

            if (series.SmallPoster != null)
            {
                var smallPoster = new Bitmap(series.SmallPoster);
                smallPoster.Save(path + title + ".poster.jpg");
            }
        }
Esempio n. 5
0
        public void DatePattern()
        {
            String pattern = "*yyyy*_hello";

            string name = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            Assert.AreEqual(DateTime.Now.ToString("yyyy") + "_hello.jpg", Path.GetFileName(name));


            pattern = "*yy*_hi.tmp";
            name    = FileNaming.GenerateFileName(png_file, pattern, false, dir, "");
            Assert.AreEqual(DateTime.Now.ToString("yy") + "_hi.tmp.png", Path.GetFileName(name));

            pattern = "hello_*MM*_World.jpeg";
            name    = FileNaming.GenerateFileName(file, pattern, false, dir, "");
            Assert.AreEqual("hello_" + DateTime.Now.ToString("MM") + "_World.jpeg", Path.GetFileName(name));


            pattern = "*yy*_*MMM*_*dd*_*HH*_*mm*_*ss*.jpeg";
            name    = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            string generated = DateTime.Now.ToString("yy") + "_" + DateTime.Now.ToString("MMM") +
                               "_" + DateTime.Now.ToString("dd") + "_" + DateTime.Now.ToString("HH") +
                               "_" + DateTime.Now.ToString("mm") + "_" + DateTime.Now.ToString("ss") + ".jpeg";

            Assert.AreEqual(generated, Path.GetFileName(name));

            //Fails because timing is too fine
            //pattern = "*fffffff*";
            //name = FileNaming.GenerateFileName(file, pattern, false, dir, "");
            //Assert.AreEqual(DateTime.Now.ToString("fffffff") + ".jpg", Path.GetFileName(name));
        }
        public static void Rename(List <FileInfo> listOfSelectedFiles, int roundRobinValue, Dictionary <string, bool> dynamicsCheckBoxStates, Note _selectedStartingNote, Note _selectedEndingNote, string _fileName, string fileFormat, Dictionary <string, bool> dynamicsStates)
        {
            int fileCount = 0;

            if (_fileName.Contains("."))
            {
                _fileName = FileNaming.removeFormat(_fileName);
            }

            List <Note> notesBetween = NoteGenerator.createNotes(_selectedStartingNote, _selectedEndingNote);

            List <string> namingOrder = FileNaming.namingOrder(notesBetween, roundRobinValue, dynamicsCheckBoxStates);

            string folderPath = listOfSelectedFiles[0].DirectoryName;


            foreach (FileInfo file in listOfSelectedFiles)
            {
                if (fileCount + 1 > namingOrder.Count)
                {
                    break;
                }
                string newFileName = _fileName + $"({fileCount}) " + namingOrder[fileCount] + fileFormat;
                string temppath    = Path.Combine(folderPath, newFileName);

                file.MoveTo(temppath);
                fileCount++;
            }
        }
Esempio n. 7
0
        public DataReader(Guid trackId)
        {
            _trackId = trackId;

            var filepath = FileNaming.GetDataTrackFilepath(trackId);

            _reader = new StreamReader(FileOperations.ReadFile(filepath));
        }
Esempio n. 8
0
        private static void SaveTvDB()
        {
            SavingCount++;

            var path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            Folders.DeleteFilesInFolder(path);

            string writePath = path + "hidden.hiddenSeries";
            string json      = JsonConvert.SerializeObject(TvDBFactory.HiddenTvDatabase);

            Gzip.CompressString(json, writePath + ".gz");

            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 6
            };

            SavingTVDBMax   = TvDBFactory.TvDatabase.Count;
            SavingTVDBValue = 0;

            Parallel.ForEach(
                TvDBFactory.TvDatabase,
                parallelOptions,
                series =>
            {
                var title      = FileNaming.RemoveIllegalChars(series.Value.SeriesName);
                var seriesPath = string.Concat(Get.FileSystemPaths.PathDatabases, OutputName.TvDb, Path.DirectorySeparatorChar, title, ".Series.gz");

                json = JsonConvert.SerializeObject(series.Value);
                Gzip.CompressString(json, seriesPath);

                if (series.Value.SmallBanner != null)
                {
                    var smallBanner = new Bitmap(series.Value.SmallBanner);
                    smallBanner.Save(path + title + ".banner.jpg");
                }

                if (series.Value.SmallFanart != null)
                {
                    var smallFanart = new Bitmap(series.Value.SmallFanart);
                    smallFanart.Save(path + title + ".fanner.jpg");
                }

                if (series.Value.SmallPoster != null)
                {
                    var smallPoster = new Bitmap(series.Value.SmallPoster);
                    smallPoster.Save(path + title + ".poster.jpg");
                }

                SavingTVDBValue++;

                Application.DoEvents();
            });

            SavingCount--;
            frmSavingDB.TvDBFinished();
        }
Esempio n. 9
0
        public void NoPatterDoOverwrite()
        {
            string newName = FileNaming.GenerateFileName(file, "", false, dir, "");

            Assert.AreNotEqual(file.FullName, newName);

            string newNameOnly = Path.GetFileName(newName);

            Assert.AreEqual("example(1).jpg", newNameOnly);
        }
Esempio n. 10
0
        public void SimplePatternDoOverwrite()
        {
            String pattern = "example.jpg";

            Assert.IsTrue(File.Exists("files/" + pattern));

            string name = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            Assert.AreEqual("example(1).jpg", Path.GetFileName(name));
        }
Esempio n. 11
0
        public void SimplePatternNoOverwrite()
        {
            String pattern = "hello.jpg";

            Assert.IsFalse(File.Exists("files/" + pattern));

            string name = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            Assert.AreEqual(pattern, Path.GetFileName(name));
        }
        /// <summary>
        /// Collects a new piece of data.
        /// </summary>
        public void Collect(DataPiece piece)
        {
            if (_previous != null)
            {
                if (_previous.TrackId == piece.TrackId)
                {
                    _ppeAccumulator += piece.Ppe;
                    _ppeCount       += 1;
                    _ppeBins[PpeMapper.GetBinIndex(piece.Ppe)] += 1;
                    if (piece.Ppe > _ppeMax)
                    {
                        _ppeMax = piece.Ppe;
                    }

                    if (piece.StartTimestamp < _tsStart)
                    {
                        _tsStart = piece.StartTimestamp;
                    }
                    if (piece.EndTimestamp > _tsEnd)
                    {
                        _tsEnd = piece.EndTimestamp;
                    }
                    _elapsed += (piece.EndTimestamp - piece.StartTimestamp);

                    var traveledDistance = GeoHelper.DistanceBetweenPoints(
                        _previous.Latitude, _previous.Longitude,
                        piece.Latitude, piece.Longitude
                        ) * DistanceFactor;
                    _distance += traveledDistance;

                    Log.Debug("Traveled {0:F3}km, count {1} {2:t}-{3:t}", traveledDistance, _ppeCount, _tsStart, _tsEnd);
                }
                else
                {
                    Log.Warning(new ArgumentException(nameof(piece.TrackId)), "Different track ID seen while collecting statistics");

                    CompleteSession();
                }
            }

            // Dump data
            // Generates approximately 42 bytes per measurement (~147 KB/hour)
            if (_dumpWriter == null)
            {
                var dumpStream = FileOperations.AppendFile(FileNaming.GetDataTrackFilepath(piece.TrackId));
                _dumpWriter = new StreamWriter(dumpStream);
            }
            _dumpWriter.WriteLine(
                string.Format(CultureInfo.InvariantCulture, "{0},{1:F5},{2:F5},{3:F2}", piece.StartTimestamp.Ticks, piece.Latitude, piece.Longitude, piece.Ppe)
                );

            _previous = piece;

            Log.Debug("Data piece collected");
        }
Esempio n. 13
0
        public void SimplePatternNoExtensionDoOverwrite()
        {
            String pattern = "example";

            string name = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            Assert.AreEqual("example(1).jpg", Path.GetFileName(name));

            name = FileNaming.GenerateFileName(png_file, pattern, false, dir, "");
            Assert.AreEqual("example(1).png", Path.GetFileName(name));
        }
Esempio n. 14
0
        /// <summary>
        /// Handles the DoWork event of the bgwSaveMovieSets control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void bgwSaveMovieSets_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieSets + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            foreach (MovieSetModel set in MovieSetManager.CurrentDatabase)
            {
                string json = JsonConvert.SerializeObject(set);
                Gzip.CompressString(json, path + FileNaming.RemoveIllegalChars(set.SetName) + ".MovieSet.gz");
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Loads the movie DB.
        /// </summary>
        private static void LoadMovieDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);
            var files = FileHelper.GetFilesRecursive(path, "*.movie.gz").ToArray();

            MovieDBFactory.MovieDatabase.Clear();

            foreach (var file in files)
            {
                string json = Gzip.Decompress(file);

                var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel;

                if (json.Contains(@"ChangedText"":false"))
                {
                    movieModel.ChangedText = false;
                }

                if (json.Contains(@"ChangedPoster"":false"))
                {
                    movieModel.ChangedPoster = false;
                }

                if (json.Contains(@"ChangedFanart"":false"))
                {
                    movieModel.ChangedFanart = false;
                }

                movieModel.DatabaseSaved = true;

                MovieDBFactory.MovieDatabase.Add(movieModel);

                string title = FileNaming.RemoveIllegalChars(movieModel.Title);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";

                if (File.Exists(poster))
                {
                    movieModel.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    movieModel.SmallFanart = ImageHandler.LoadImage(fanart);
                }
            }
        }
Esempio n. 16
0
        public void RandomStringPattern()
        {
            String pattern = "*RAND4*.jpg";
            string name1   = FileNaming.GenerateFileName(file, pattern, false, dir, "");
            string name2   = FileNaming.GenerateFileName(file, pattern, false, dir, "");

            name1 = Path.GetFileName(name1);
            name2 = Path.GetFileName(name2);


            Assert.AreEqual(name1.Length, 8);
            Assert.AreEqual(name2.Length, 8);
            Assert.AreNotEqual(name1, name2);
        }
Esempio n. 17
0
        /// <summary>
        /// Handles the DoWork event of the bgw control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void bgwSaveMovieDBWork_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            var movieModel = e.Argument as MovieModel;

            string title = FileNaming.RemoveIllegalChars(movieModel.Title);

            string writePath = path + title + ".movie";

            bool writeText   = false;
            bool writeImages = false;

            if (!movieModel.DatabaseSaved)
            {
                writeImages = true;
            }

            if (!movieModel.DatabaseSaved || movieModel.ChangedText)
            {
                writeText = true;
            }

            if (writeText)
            {
                movieModel.DatabaseSaved = true;
                string json = JsonConvert.SerializeObject(movieModel);
                Gzip.CompressString(json, writePath + ".gz");
            }

            var posterPath = path + title + ".poster.jpg";
            var fanartPath = path + title + ".fanart.jpg";

            if (movieModel.SmallPoster != null && (movieModel.ChangedPoster || writeImages))
            {
                movieModel.SmallPoster.Save(posterPath);
            }

            if (movieModel.SmallFanart != null && (movieModel.ChangedFanart || writeImages))
            {
                movieModel.SmallFanart.Save(fanartPath);
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Loads the TV DB db
        /// </summary>
        private static void LoadTvDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            var files = FileHelper.GetFilesRecursive(path, "*.Series.gz");

            TvDBFactory.TvDatabase.Clear();

            foreach (var file in files)
            {
                string json = Gzip.Decompress(file);

                var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series;

                string title = FileNaming.RemoveIllegalChars(series.SeriesName);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";
                string banner = path + title + ".banner.jpg";

                if (File.Exists(poster))
                {
                    series.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    series.SmallFanart = ImageHandler.LoadImage(fanart);
                }

                if (File.Exists(banner))
                {
                    series.SmallBanner = ImageHandler.LoadImage(banner);
                }

                TvDBFactory.TvDatabase.Add(series.SeriesName, series);
            }

            TvDBFactory.GeneratePictureGallery();
            TvDBFactory.GenerateMasterSeriesList();
        }
Esempio n. 19
0
        /// <summary>
        /// Handles the DoWork event of the bgw control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.ComponentModel.DoWorkEventArgs"/> instance containing the event data.
        /// </param>
        private static void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

            var movieModel = e.Argument as MovieModel;

            string title = FileNaming.RemoveIllegalChars(movieModel.Title);

            string writePath = path + title + ".movie";
            string json      = JsonConvert.SerializeObject(movieModel);

            Gzip.CompressString(json, writePath + ".gz");

            if (movieModel.SmallPoster != null)
            {
                movieModel.SmallPoster.Save(path + title + ".poster.jpg");
            }

            if (movieModel.SmallFanart != null)
            {
                movieModel.SmallFanart.Save(path + title + ".fanart.jpg");
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Loads the TV DB db
        /// </summary>
        private static void LoadTvDB()
        {
            string path = Get.FileSystemPaths.PathDatabases + OutputName.TvDb + Path.DirectorySeparatorChar;

            Directory.CreateDirectory(path);

            List <string> files = FileHelper.GetFilesRecursive(path, "*.Series.gz");

            TvDBFactory.TvDatabase.Clear();

            var hidden = path + "hidden.hiddenSeries.gz";

            if (File.Exists(hidden))
            {
                var json = Gzip.Decompress(hidden);
                TvDBFactory.HiddenTvDatabase =
                    JsonConvert.DeserializeObject(json, typeof(BindingList <Series>)) as BindingList <Series>;
            }

            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 6
            };

            Parallel.ForEach(
                files,
                parallelOptions,
                file =>
            {
                var json = Gzip.Decompress(file);

                var series = JsonConvert.DeserializeObject(json, typeof(Series)) as Series;

                string title = FileNaming.RemoveIllegalChars(series.SeriesName);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";
                string banner = path + title + ".banner.jpg";

                if (File.Exists(poster))
                {
                    series.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    series.SmallFanart = ImageHandler.LoadImage(fanart);
                }

                if (File.Exists(banner))
                {
                    series.SmallBanner = ImageHandler.LoadImage(banner);
                }

                foreach (var season in series.Seasons)
                {
                    for (int index = 0; index < season.Value.Episodes.Count; index++)
                    {
                        var episode = season.Value.Episodes[index];
                        if (episode.FilePath.PathAndFilename != string.Empty &&
                            !File.Exists(episode.FilePath.PathAndFilename))
                        {
                            Log.WriteToLog(
                                LogSeverity.Info,
                                LoggerName.GeneralLog,
                                "Internal > DatabaseIOFactory > LoadTvDB",
                                string.Format(
                                    "Deleting {0}. Episode not found on the filesystem",
                                    episode.FilePath.PathAndFilename));
                            // We should check for network path and make sure the file has actually been deleted or removed
                            File.Delete(file);
                            series.Seasons[season.Key].Episodes.Remove(episode);
                        }
                    }
                }

                lock (TvDBFactory.TvDatabase)
                {
                    TvDBFactory.TvDatabase.Add(series.SeriesName, series);
                }
            });

            TvDBFactory.GeneratePictureGallery();
            TvDBFactory.GenerateMasterSeriesList();
        }
Esempio n. 21
0
        private static void SaveMovies(BindingList <MovieModel> database)
        {
            int max = database.Count;

            if (max == 0)
            {
                return;
            }

            SavingMovieMax += database.Count - 1;
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 6
            };

            Parallel.ForEach(
                database,
                parallelOptions,
                movie =>
            {
                SavingCount++;

                var path = Get.FileSystemPaths.PathDatabases + OutputName.MovieDb + Path.DirectorySeparatorChar;

                var title = FileNaming.RemoveIllegalChars(movie.Title);

                string writePath;

                if (movie.Hidden)
                {
                    writePath = path + title + ".hiddenmovie";
                }
                else
                {
                    writePath = path + title + ".movie";
                }

                movie.DatabaseSaved = true;
                var json            = JsonConvert.SerializeObject(movie);
                Gzip.CompressString(json, writePath + ".gz");

                var posterPath = path + title + ".poster.jpg";
                var fanartPath = path + title + ".fanart.jpg";

                if (movie.SmallPoster != null)
                {
                    movie.SmallPoster.Save(posterPath);
                }

                if (movie.SmallFanart != null)
                {
                    movie.SmallFanart.Save(fanartPath);
                }

                Application.DoEvents();

                SavingMovieValue++;
            });

            frmSavingDB.MovieDBFinished();

            SavingMovieDB = false;
        }
Esempio n. 22
0
        /// <summary>
        /// Collects a new piece of data.
        /// </summary>
        public void Collect(DataPiece piece)
        {
            if (_record != null && (_record.TrackId != piece.TrackId))
            {
                Log.Warning(new ArgumentException(nameof(piece.TrackId)), "Different track ID seen while collecting statistics");

                CompleteSession();
            }

            if (_record == null)
            {
                _record = GetRecordForPiece(piece);
            }

            // Record set, update
            _ppeAccumulator += piece.Ppe;
            _ppeCount       += 1;
            _record.Bins[PpeMapper.GetBinIndex(piece.Ppe)] += 1;
            if (piece.Ppe > _record.MaxPpe)
            {
                _record.MaxPpe = piece.Ppe;
            }
            _record.AvgPpe               = _ppeAccumulator / _ppeCount;
            _record.DataPieceCount       = (int)_ppeCount;
            _record.End                  = piece.EndTimestamp;
            _record.ElapsedTime         += (piece.EndTimestamp - piece.StartTimestamp);
            _record.LocationEndLatitude  = piece.Latitude;
            _record.LocationEndLongitude = piece.Longitude;

            if (_previous != null)
            {
                var traveledDistance = GeoHelper.DistanceBetweenPoints(
                    _previous.Latitude, _previous.Longitude,
                    piece.Latitude, piece.Longitude
                    ) * DistanceFactor;
                _record.DistanceTraveled += traveledDistance;

                Log.Debug("Traveled {0:F3}km, count {1} {2:t}-{3:t}",
                          traveledDistance, _ppeCount, _record.Start, _record.End);
            }

            _previous = piece;

            // Flush every few minutes
            if (_ppeCount > 0 && (_ppeCount % FlushIntervalSize == 0))
            {
                Flush();
            }

            // Dump data
            // Generates approximately 89 bytes per measurement (~313 KB/hour)
            if (_dumpWriter == null)
            {
                var outputFilepath = FileNaming.GetDataTrackFilepath(piece.TrackId);
                Log.Debug("Appending to file {0}", outputFilepath);

                var dumpStream = FileOperations.AppendFile(outputFilepath);
                _dumpWriter = new StreamWriter(dumpStream);
                _dumpWriter.WriteLine("# SRS Track {0:N} {1:u}", piece.TrackId, DateTime.Now);
                _dumpWriter.WriteLine("# Start,End,Lat,Lng,PPE,PPEx,PPEy,PPEz,Speed,Bearing,Accuracy");
            }
            _dumpWriter.WriteLine(
                string.Format(CultureInfo.InvariantCulture, "{0},{1},{2:F5},{3:F5},{4:F3},{5:F2},{6:F2},{7:F2},{8:F1},{9:D},{10:D}",
                              piece.StartTimestamp.Ticks,
                              piece.EndTimestamp.Ticks,
                              piece.Latitude,
                              piece.Longitude,
                              piece.Ppe,
                              piece.PpeX,
                              piece.PpeY,
                              piece.PpeZ,
                              piece.Speed,
                              (int)piece.Bearing,
                              piece.Accuracy
                              )
                );

            Log.Debug("Data piece collected");
        }
Esempio n. 23
0
        private static void LoadMovies(string path, string[] files, BindingList <MovieModel> database)
        {
            var parallelOptions = new ParallelOptions {
                MaxDegreeOfParallelism = 6
            };

            Parallel.ForEach(
                files,
                parallelOptions,
                file =>
            {
                string json = Gzip.Decompress(file);

                var movieModel = JsonConvert.DeserializeObject(json, typeof(MovieModel)) as MovieModel;

                if (json.Contains(@"ChangedText"":false"))
                {
                    movieModel.ChangedText = false;
                }

                if (json.Contains(@"ChangedPoster"":false"))
                {
                    movieModel.ChangedPoster = false;
                }

                if (json.Contains(@"ChangedFanart"":false"))
                {
                    movieModel.ChangedFanart = false;
                }

                movieModel.DatabaseSaved = true;

                if (movieModel.AssociatedFiles.GetMediaCollection().Count > 0)
                {
                    if (!File.Exists(movieModel.AssociatedFiles.GetMediaCollection()[0].PathAndFilename))
                    {
                        Log.WriteToLog(
                            LogSeverity.Info,
                            LoggerName.GeneralLog,
                            "Internal > DatabaseIOFactory > LoadMovieDB",
                            string.Format(
                                "Deleting {0}. Movie not found on the filesystem",
                                movieModel.AssociatedFiles.GetMediaCollection()[0].FileName));
                        // We should check for network path and make sure the file has actually been deleted or removed
                        File.Delete(file);
                    }
                }

                if (movieModel != null)
                {
                    lock (database)
                    {
                        database.Add(movieModel);
                    }
                }

                string title = FileNaming.RemoveIllegalChars(movieModel.Title);

                string poster = path + title + ".poster.jpg";
                string fanart = path + title + ".fanart.jpg";

                if (File.Exists(poster))
                {
                    movieModel.SmallPoster = ImageHandler.LoadImage(poster);
                }

                if (File.Exists(fanart))
                {
                    movieModel.SmallFanart = ImageHandler.LoadImage(fanart);
                }
            });
        }
Esempio n. 24
0
        public void NoPatternNoOverwrite()
        {
            String newName = FileNaming.GenerateFileName(file, "", true, dir, "");

            Assert.AreEqual(file.FullName, newName);
        }