예제 #1
0
 public static void RegisterReader(string scheme, ReaderFactory factory)
 {
     readers.Add(scheme, factory);
 }
예제 #2
0
 private void update(Object message)
 {
     factory = RssReaderFactory.getInstance();
     this.channels.Add(factory.createChannel(link, FeedType.RSS));
     parseChannels();
 }
예제 #3
0
        private ArgumentHandleResult ProcessSharedUserChampionship(SharedEntry shared, byte[] data)
        {
            string sharedId = null;

            using (var stream = new MemoryStream(data)) {
                var reader = ReaderFactory.Open(stream);

                var written = 0;
                try {
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            var name = reader.Entry.Key;
                            if (name.EndsWith(UserChampionshipObject.FileExtension))
                            {
                                sharedId = name;
                            }

                            written++;
                        }
                    }
                } catch (EndOfStreamException) {
                    if (written < 1)
                    {
                        throw;
                    }
                }
            }

            if (sharedId == null)
            {
                throw new InformativeException("Can’t install championship", "Main file is missing.");
            }

            var existing = UserChampionshipsManager.Instance.GetById(sharedId);
            var result   = ShowDialog(shared, applyable: false, additionalButton: existing == null ? null : $"Overwrite “{existing.Name}”");

            switch (result)
            {
            case Choise.Save:
            case Choise.Extra:
                string replacementId = null;
                if (existing != null && result == Choise.Save)
                {
                    for (var i = 0; i < 999; i++)
                    {
                        var candidate = Guid.NewGuid() + UserChampionshipObject.FileExtension;
                        if (UserChampionshipsManager.Instance.GetById(candidate) == null)
                        {
                            replacementId = candidate;
                            break;
                        }
                    }

                    if (replacementId == null)
                    {
                        throw new InformativeException("Can’t install championship", "Can’t find a new ID.");
                    }
                }

                var directory = UserChampionshipsManager.Instance.Directories.EnabledDirectory;
                Directory.CreateDirectory(directory);

                using (var stream = new MemoryStream(data)) {
                    var reader = ReaderFactory.Open(stream);

                    var written = 0;
                    try {
                        while (reader.MoveToNextEntry())
                        {
                            if (!reader.Entry.IsDirectory)
                            {
                                var name = reader.Entry.Key;
                                if (replacementId != null)
                                {
                                    name = name.Replace(sharedId, replacementId);
                                }

                                reader.WriteEntryToFile(Path.Combine(directory, name), new ExtractionOptions {
                                    Overwrite = true
                                });
                                written++;
                            }
                        }
                    } catch (EndOfStreamException) {
                        if (written < 1)
                        {
                            throw;
                        }
                    }
                }

                return(ArgumentHandleResult.SuccessfulShow);

            default:
                return(ArgumentHandleResult.Failed);
            }
        }
예제 #4
0
        private void ExtractFile()
        {
            new Thread(() =>
            {
                try
                {
                    Status = "Extracting";
                    Directory.CreateDirectory(_extractedLocation);
                    using (var stream = File.OpenRead(_downloadedFileLocation))
                    {
                        using (var reader = ReaderFactory.Open(stream))
                        {
                            while (reader.MoveToNextEntry())
                            {
                                if (reader.Entry.IsDirectory)
                                {
                                    continue;
                                }
                                var fileName = Path.GetFileName(reader.Entry.FilePath);
                                if (string.IsNullOrEmpty(fileName))
                                {
                                    continue;
                                }
                                reader.WriteEntryToDirectory(_extractedLocation,
                                                             ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                                if (fileName.EndsWith(".exe"))
                                {
                                    var p = new Process
                                    {
                                        StartInfo =
                                        {
                                            CreateNoWindow   = true,
                                            UseShellExecute  = false,
                                            WindowStyle      = ProcessWindowStyle.Hidden,
                                            WorkingDirectory = _extractedLocation,
                                            FileName         = Path.Combine(_extractedLocation, fileName)
                                        }
                                    };
                                    p.Start();
                                    Status = "Installing";
                                    p.WaitForExit();
                                }
                            }
                        }
                    }
                    Status = "Install complete";
                }
                catch (Exception ex)
                {
                    Status    = "Coult not complete";
                    IsRunning = false;
                }

                try
                {
                    File.Delete(_downloadedFileLocation);
                    Directory.Delete(_extractedLocation);
                }
                catch (Exception ex)
                {
                }
                IsRunning = false;
            }).Start();
        }
        private void describe_stream_in()
        {
            context["given that I'm a consumer of the containerizer api"] = () =>
            {
                HttpClient client = null;

                before = () => client = process.GetClient();

                context["there exists a container with a given id"] = () =>
                {
                    before = () => handle = Helpers.CreateContainer(client);
                    after  = () => Helpers.DestroyContainer(client, handle);

                    context["when I stream in a file into the container"] = () =>
                    {
                        HttpResponseMessage responseMessage = null;
                        Stream fileStream = null;

                        before = () =>
                        {
                            var content = new MultipartFormDataContent();
                            fileStream = new FileStream(tgzName, FileMode.Open);
                            var streamContent = new StreamContent(fileStream);
                            streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                            content.Add(streamContent);
                            string path = "/api/containers/" + handle + "/files?destination=%2F";
                            responseMessage = client.PutAsync(path, streamContent).GetAwaiter().GetResult();
                        };

                        after = () =>
                        {
                            fileStream.Close();
                        };

                        it["returns a successful status code"] = () =>
                        {
                            responseMessage.IsSuccessStatusCode.should_be_true();
                        };

                        context["and I stream the file out of the container"] = () =>
                        {
                            it["returns a tarred version of the file"] = () =>
                            {
                                responseMessage.IsSuccessStatusCode.should_be_true();

                                HttpResponseMessage getTask =
                                    client.GetAsync("/api/containers/" + handle + "/files?source=/file.txt")
                                    .GetAwaiter()
                                    .GetResult();
                                getTask.IsSuccessStatusCode.should_be_true();
                                Stream tarStream = getTask.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                                using (IReader tar = ReaderFactory.Open(tarStream))
                                {
                                    tar.MoveToNextEntry().should_be_true();
                                    tar.Entry.Key.should_be("file.txt");

                                    tar.MoveToNextEntry().should_be_false();
                                }
                            };
                        };
                    };
                };
            };
        }
예제 #6
0
        public async Task Update(bool restartOnUpdate = true, IProgress <double> progress = default)
        {
            var updateFile = await _updateProvider.DownloadUpdate(progress);

            if (string.IsNullOrWhiteSpace(updateFile))
            {
                // TODO There should probably be an error here?
                return;
            }

            var runElevated = UpdateNeedsElevation();

            // Get a temporary path to extract the update to, we'll
            // be using this to start the updater and copy the files
            // over
            var updatePath = Path.GetTempPath();

            using (var stream = File.OpenRead(updateFile))
            {
                var readerOptions = new ReaderOptions
                {
                    LeaveStreamOpen = false,
                    ArchiveEncoding = { Default = Encoding.GetEncoding(866) },
                };

                using (var reader = ReaderFactory.Open(stream, readerOptions))
                {
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            reader.WriteEntryToDirectory(updatePath, new ExtractionOptions()
                            {
                                ExtractFullPath = true,
                                Overwrite       = true
                            });
                        }
                    }
                }
            }

            var installLocation = Assembly.GetEntryAssembly().Location;

            var args = new Dictionary <string, string>
            {
                ["mode"]        = "update",
                ["path"]        = installLocation,
                ["cleanupPath"] = updatePath,
            };

            if (restartOnUpdate)
            {
                args.Add("restartApp", string.Empty);
            }

            if (runElevated)
            {
                args.Add("elevated", string.Empty);
            }

            UpdateHelper.StartUpdater(updatePath, args, runElevated);
        }
예제 #7
0
        /// <summary>
        /// Loads a zip file
        /// </summary>
        /// <param name="fse"></param>
        /// <param name="thumbnailOptions"></param>
        private async void LoadZip(FileSystemElement fse, FileSystemRetrieveService.ThumbnailFetchOptions thumbnailOptions, CancellationToken token)
        {
            elements.Clear();
            currentDepth   = 0;
            folderIndex    = 0;
            currentZIPFile = await FileSystem.GetFileAsync(fse);

            currentFSE = fse;

            using (Stream stream = await currentZIPFile.OpenStreamForReadAsync())
            {
                var reader = ReaderFactory.Open(stream);
                while (reader.MoveToNextEntry())
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    var entry    = reader.Entry;
                    var keySplit = entry.Key.Split("/");
                    var subPath  = string.Join(@"\", keySplit, 0, keySplit.Length - 1);

                    int            depth;
                    ZipFileElement element;
                    if (entry.IsDirectory)
                    {
                        var name = keySplit[keySplit.Length - 2];
                        depth = keySplit.Length - 2;

                        element = new ZipFileElement(
                            name,
                            fse.Path + @"\" + subPath,
                            entry.LastModifiedTime.Value,
                            (ulong)entry.Size,
                            entry.Key,
                            depth
                            );

                        elements.AddFirst(depth, element);
                    }
                    else
                    {
                        var name = keySplit[keySplit.Length - 1];
                        depth = keySplit.Length - 1;

                        string fileExtension = "";
                        var    fileName      = entry.Key.Split(".");
                        if (fileName.Length > 1)
                        {
                            fileExtension = fileName[fileName.Length - 1];
                        }

                        //Store fileStream to access it later
                        var elementStream = new MemoryStream();
                        reader.WriteEntryTo(elementStream);
                        await elementStream.FlushAsync();

                        var thumbnail = await FileSystem.GetFileExtensionThumbnail(fileExtension, thumbnailOptions.Mode, thumbnailOptions.Size, thumbnailOptions.Scale);

                        element = new ZipFileElement(
                            name,
                            fse.Path + @"\" + subPath,
                            entry.LastModifiedTime.Value,
                            (ulong)entry.Size,
                            thumbnail,
                            "." + fileExtension,
                            fileExtension,
                            entry.Key,
                            depth,
                            elementStream
                            );

                        elements.Add(depth, element);
                    }

                    AddToViewItems(element);
                }
            }
        }
예제 #8
0
        public DirectoryInfo GetDirectoryAsLocal(string remote_path, string local_path)
        {
            CallerInformation   here = this.Here();
            Stopwatch           sw   = new Stopwatch();
            string              dir_archive_filename = string.Format("_devaudit_{0}.tgz", this.GetTimestamp());
            SshCommandSpawanble cs = new SshCommandSpawanble(this.SshClient.CreateCommand(string.Format("tar -czf {0} -C {1} . && stat {0} || echo Failed", dir_archive_filename, remote_path)));

            sw.Start();
            ExpectNet.Session cmd_session = Expect.Spawn(cs, this.LineTerminator);
            List <IResult>    r           = cmd_session.Expect.RegexEither("Size:\\s+([0-9]+)", null, "Failed", null);

            sw.Stop();
            long dir_archive_size;

            cs.Dispose();
            if (r[0].IsMatch)
            {
                Match m = r[0].Result as Match;
                dir_archive_size = long.Parse(m.Groups[1].Value);
                Debug(here, "Archive file {0} created with size {1} bytes in {2} ms.", dir_archive_filename, dir_archive_size, sw.ElapsedMilliseconds);
            }
            else
            {
                Error(here, "Archive file {0} could not be created, command output: {1}", dir_archive_filename, r[1].Text);
                return(null);
            }
            sw.Restart();
            SshAuditFileInfo   dir_archive_file = new SshAuditFileInfo(this, dir_archive_filename);
            LocalAuditFileInfo lf = dir_archive_file.GetAsLocalFile();

            sw.Stop();
            if (lf == null)
            {
                Error(here, "Failed to get archive file {0} as local file.", dir_archive_filename);
                return(null);
            }
            Info("Downloaded archive file {0} in to local file {1} in {2} ms.", dir_archive_file.FullName, lf.FullName, sw.ElapsedMilliseconds);
            cs          = new SshCommandSpawanble(this.SshClient.CreateCommand(string.Format("rm {0} && echo Succeded || echo Failed", dir_archive_filename)));
            cmd_session = Expect.Spawn(cs, this.LineTerminator);
            r           = cmd_session.Expect.RegexEither("Succeded", null, "Failed", null);
            if (r[0].IsMatch)
            {
                Debug("Deleted archive file {0} from remote server.", dir_archive_file.FullName);
            }
            else
            {
                Debug("Failed to delete archive file {0} from remote server. It is safe to delete this file manually.", dir_archive_file.FullName);
            }
            sw.Restart();
            try
            {
                using (Stream fs = File.OpenRead(lf.FullName))
                {
                    ReaderFactory.Open(fs).WriteAllToDirectory(this.WorkDirectory.FullName,
                                                               new ExtractionOptions()
                    {
                        Overwrite       = true,
                        ExtractFullPath = true
                    });
                }

                /*
                 * ArchiveFactory.WriteToDirectory(lf.FullName, , new ExtractionOptions()
                 * {
                 *  Overwrite = true,
                 *
                 * });*/
                sw.Stop();
                Debug(here, "Extracting archive file {0} to work directory {1} in {2} ms.", lf.FullName, this.WorkDirectory.FullName, sw.ElapsedMilliseconds);
                return(this.WorkDirectory);
            }
            catch (Exception e)
            {
                Error(here, e);
                return(null);
            }
            finally
            {
                if (sw != null && sw.IsRunning)
                {
                    sw.Stop();
                }
            }
        }
예제 #9
0
 /// <summary>
 /// 解压缩文件
 /// </summary>
 /// <param name="ZipFileName">压缩文件</param>
 /// <param name="TargetFolder">目标文件夹</param>
 public static void UnZipFile(string ZipFileName, string TargetFolder)
 {
     if (ZipFileName.ToLower().Contains("rar"))
     {
         if (!Directory.Exists(TargetFolder))
         {
             Directory.CreateDirectory(TargetFolder);
         }
         using (Stream stream = File.OpenRead(ZipFileName))
         {
             var reader = ReaderFactory.Open(stream);
             while (reader.MoveToNextEntry())
             {
                 if (!reader.Entry.IsDirectory)
                 {
                     reader.WriteEntryToDirectory(TargetFolder);
                 }
             }
         }
     }
     else
     {
         if (!File.Exists(ZipFileName))
         {
             return;
         }
         FileStream     FileS       = File.OpenRead(ZipFileName);
         ZipInputStream zipInStream = new ZipInputStream(FileS);
         zipInStream.Password = Zipkey;
         //zipInStream.Password = "******";
         string FolderPath = Path.GetDirectoryName(TargetFolder);
         if (!Directory.Exists(TargetFolder))
         {
             Directory.CreateDirectory(FolderPath);
         }
         ZipEntry tEntry;
         while ((tEntry = zipInStream.GetNextEntry()) != null)
         {
             string fileName = Path.GetFileName(tEntry.Name);
             string tempPath = TargetFolder + "\\" + Path.GetDirectoryName(tEntry.Name);
             if (!Directory.Exists(tempPath))
             {
                 Directory.CreateDirectory(tempPath);
             }
             if (fileName != null && fileName.Length > 0)
             {
                 FileStream   streamWriter = File.Create(TargetFolder + "\\" + tEntry.Name);
                 byte[]       data         = new byte[2048];
                 System.Int32 size;
                 try
                 {
                     do
                     {
                         size = zipInStream.Read(data, 0, data.Length);
                         streamWriter.Write(data, 0, size);
                     } while (size > 0);
                 }
                 catch (System.Exception ex)
                 {
                     throw ex;
                 }
                 streamWriter.Close();
             }
         }
         zipInStream.Close();
     }
 }
예제 #10
0
        public Tasker.Conclusion AddGames(Tasker tasker, Object syncObject = null)
        {
            tasker.SetProgress(-1, -1, Tasker.State.Running, Resources.AddingGames);
            tasker.SetTitle(Resources.AddingGames);
            tasker.SetStatusImage(Resources.sign_cogs);

            // static presets
            NesApplication.ParentForm           = tasker.HostForm;
            NesApplication.NeedPatch            = null;
            NesApplication.Need3rdPartyEmulator = null;
            NesApplication.CachedCoverFiles     = null;
            NesGame.IgnoreMapper           = null;
            SnesGame.NeedAutoDownloadCover = null;

            int total = files.Count();
            int count = 0;
            var gamesWithMultipleArt = new List <NesApplication>();

            foreach (var sourceFileName in files)
            {
                NesApplication app = null;
                try
                {
                    tasker.SetStatus(string.Format(Resources.AddingGame, Path.GetFileName(sourceFileName)));
                    var    fileName = sourceFileName;
                    var    ext      = Path.GetExtension(sourceFileName).ToLower();
                    byte[] rawData  = null;
                    string tmp      = null;
                    if (!asIs && (ext == ".7z" || ext == ".zip" || ext == ".rar" || ext == ".clvg"))
                    {
                        if (ext == ".clvg")
                        {
                            tmp = TempHelpers.getUniqueTempPath();
                            Directory.CreateDirectory(tmp);

                            using (var file = File.OpenRead(sourceFileName))
                                using (var reader = ReaderFactory.Open(file))
                                {
                                    reader.WriteAllToDirectory(tmp, new ExtractionOptions()
                                    {
                                        ExtractFullPath = true, PreserveFileTime = true
                                    });
                                }

                            var gameFilesInArchive = Directory.GetFiles(tmp, "*.desktop").Select(o => new DirectoryInfo(o)).Cast <DirectoryInfo>().ToArray();

                            switch (gameFilesInArchive.LongLength)
                            {
                            case 0:
                                // no files found
                                break;

                            case 1:
                                // one file found
                                fileName = gameFilesInArchive[0].FullName;
                                break;

                            default:
                                // multiple files found
                                var r = SelectFile(tasker, gameFilesInArchive.Select(o => o.FullName).ToArray());
                                if (r == DialogResult.OK)
                                {
                                    fileName = selectedFile;
                                }
                                else if (r == DialogResult.Ignore)
                                {
                                    fileName = sourceFileName;
                                }
                                else
                                {
                                    continue;
                                }
                                break;
                            }
                        }
                        else
                        {
                            using (var extractor = ArchiveFactory.Open(sourceFileName))
                            {
                                var filesInArchive     = extractor.Entries;
                                var gameFilesInArchive = new List <string>();
                                foreach (var f in extractor.Entries)
                                {
                                    if (!f.IsDirectory)
                                    {
                                        var e = Path.GetExtension(f.Key).ToLower();
                                        if (e == ".desktop")
                                        {
                                            gameFilesInArchive.Clear();
                                            gameFilesInArchive.Add(f.Key);
                                            break;
                                        }
                                        else if (CoreCollection.Extensions.Contains(e))
                                        {
                                            gameFilesInArchive.Add(f.Key);
                                        }
                                    }
                                }
                                if (gameFilesInArchive.Count == 1) // Only one known file (or app)
                                {
                                    fileName = gameFilesInArchive[0];
                                }
                                else if (gameFilesInArchive.Count > 1) // Many known files, need to select
                                {
                                    var r = SelectFile(tasker, gameFilesInArchive.ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                else if (filesInArchive.Count() == 1) // No known files but only one another file
                                {
                                    fileName = filesInArchive.First().Key;
                                }
                                else // Need to select
                                {
                                    var r = SelectFile(tasker, filesInArchive.Select(f => f.Key).ToArray());
                                    if (r == DialogResult.OK)
                                    {
                                        fileName = selectedFile;
                                    }
                                    else if (r == DialogResult.Ignore)
                                    {
                                        fileName = sourceFileName;
                                    }
                                    else
                                    {
                                        continue;
                                    }
                                }
                                if (fileName != sourceFileName)
                                {
                                    var o = new MemoryStream();
                                    if (Path.GetExtension(fileName).ToLower() == ".desktop" || // App in archive, need the whole directory
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".jpg") || // Or it has cover in archive
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".png") ||
                                        filesInArchive.Select(f => f.Key).Contains(Path.GetFileNameWithoutExtension(fileName) + ".ips")    // Or IPS file
                                        )
                                    {
                                        tmp = Path.Combine(tempDirectory, fileName);
                                        Directory.CreateDirectory(tmp);
                                        extractor.WriteToDirectory(tmp, new ExtractionOptions()
                                        {
                                            ExtractFullPath = true, Overwrite = true
                                        });
                                        fileName = Path.Combine(tmp, fileName);
                                    }
                                    else
                                    {
                                        extractor.Entries.Where(f => f.Key == fileName).First().WriteTo(o);
                                        rawData = new byte[o.Length];
                                        o.Seek(0, SeekOrigin.Begin);
                                        o.Read(rawData, 0, (int)o.Length);
                                    }
                                }
                            }
                        }
                    }
                    app = NesApplication.Import(fileName, sourceFileName, rawData, asIs);

                    if (ext == ".clvg")
                    {
                        app.SkipCoreSelect = true;
                    }
                    else
                    {
                        if (app.CoverArtMatches != null && app.CoverArtMatches.Count() > 1)
                        {
                            gamesWithMultipleArt.Add(app);
                        }
                        if (ConfigIni.Instance.EnableImportScraper && Program.TheGamesDBAPI != null &&
                            app.Metadata.OriginalCrc32 != 0 &&
                            data.GamesDB.HashLookup.ContainsKey(app.Metadata.OriginalCrc32) &&
                            data.GamesDB.HashLookup[app.Metadata.OriginalCrc32].Length > 0)
                        {
                            var api  = Program.TheGamesDBAPI;
                            var task = api.GetInfoByID(data.GamesDB.HashLookup[app.Metadata.OriginalCrc32]);
                            try
                            {
                                task.Wait();
                                var result = task.Result;

                                if (result.Items.Count() > 0)
                                {
                                    var first = result.Items.First();

                                    if (first.Name != null)
                                    {
                                        app.Desktop.Name     = first.Name;
                                        app.Desktop.SortName = Shared.GetSortName(first.Name);
                                    }

                                    if (first.Publishers != null && first.Publishers.Length > 0)
                                    {
                                        app.Desktop.Publisher = String.Join(", ", first.Publishers).ToUpper();
                                    }
                                    else if (first.Developers != null && first.Developers.Length > 0)
                                    {
                                        if (first.ReleaseDate != null)
                                        {
                                            app.Desktop.Copyright = $"© {first.ReleaseDate.Year} {String.Join(", ", first.Developers)}";
                                        }
                                        else
                                        {
                                            app.Desktop.Copyright = $"© {String.Join(", ", first.Developers)}";
                                        }
                                    }

                                    if (first.Description != null)
                                    {
                                        app.Desktop.Description = first.Description;
                                    }

                                    if (first.ReleaseDate != null)
                                    {
                                        app.Desktop.ReleaseDate = first.ReleaseDate.ToString("yyyy-MM-dd");
                                    }

                                    if (first.PlayerCount > 0)
                                    {
                                        app.Desktop.Players      = Convert.ToByte(first.PlayerCount);
                                        app.Desktop.Simultaneous = first.PlayerCount == 2;
                                    }

                                    if (first.Genres != null && first.Genres.Length > 0)
                                    {
                                        foreach (var genre in first.Genres)
                                        {
                                            var match = ScraperForm.TheGamesDBGenreLookup.Where(g => g.Value.Contains(genre.ID)).Select(g => g.Key);

                                            if (match.Count() > 0)
                                            {
                                                var firstGenre = match.First();

                                                app.Desktop.Genre = firstGenre;
                                                break;
                                            }
                                        }
                                    }

                                    using (var wc = new HakchiWebClient())
                                    {
                                        try
                                        {
                                            var front = first.Images.Where(i => i.Type == TeamShinkansen.Scrapers.Enums.ArtType.Front).ToArray();

                                            if (front.Length > 0 && !app.CoverArtMatchSuccess)
                                            {
                                                var data = wc.DownloadData(front[0].Url);
                                                using (var ms = new MemoryStream(data))
                                                    using (var bm = new Bitmap(ms))
                                                    {
                                                        app.SetImage(bm);
                                                    }
                                            }
                                        }
                                        catch (WebException ex) { }

                                        try
                                        {
                                            var imageData = wc.DownloadData($"https://cdn.thegamesdb.net/images/original/clearlogo/{first.ID}.png");

                                            using (var ms = new MemoryStream(imageData))
                                                using (var clearLogo = File.OpenWrite(Path.Combine(app.BasePath, $"{app.Code}_logo.png")))
                                                {
                                                    ms.Seek(0, SeekOrigin.Begin);
                                                    ms.CopyTo(clearLogo);
                                                }
                                        }
                                        catch (WebException ex) { }
                                    }
                                }
                            }
                            catch (Exception) { }
                        }
                    }

                    if (app is ISupportsGameGenie && Path.GetExtension(fileName).ToLower() == ".nes")
                    {
                        var lGameGeniePath = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".xml");
                        if (File.Exists(lGameGeniePath))
                        {
                            GameGenieDataBase lGameGenieDataBase = new GameGenieDataBase(app);
                            lGameGenieDataBase.ImportCodes(lGameGeniePath, true);
                            lGameGenieDataBase.Save();
                        }
                    }

                    if (!string.IsNullOrEmpty(tmp) && Directory.Exists(tmp))
                    {
                        Directory.Delete(tmp, true);
                    }
                }
                catch (Exception ex)
                {
                    if (ex is ThreadAbortException)
                    {
                        return(Tasker.Conclusion.Abort);
                    }
                    if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                    {
                        Trace.WriteLine(ex.InnerException.Message + ex.InnerException.StackTrace);
                        tasker.ShowError(ex.InnerException, Path.GetFileName(sourceFileName));
                    }
                    else
                    {
                        Trace.WriteLine(ex.Message + ex.StackTrace, Path.GetFileName(sourceFileName));
                        tasker.ShowError(ex);
                    }
                    return(Tasker.Conclusion.Error);
                }
                if (app != null)
                {
                    addedApps.Add(app);
                }
                tasker.SetProgress(++count, total);
            }
            if (gamesWithMultipleArt.Count > 0)
            {
                tasker.HostForm.Invoke(new Action(() => {
                    using (SelectCoverDialog selectCoverDialog = new SelectCoverDialog())
                    {
                        selectCoverDialog.Games.AddRange(gamesWithMultipleArt);
                        selectCoverDialog.ShowDialog(tasker.HostForm);
                    }
                }));
            }
            return(Tasker.Conclusion.Success);
        }
예제 #11
0
        /// <summary>
        /// 确认更新 ==》更新操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAllCheck_Click(object sender, EventArgs e)
        {
            try
            {
                handZip = true;
                if (File.Exists(downFile))
                {
                    FileInfo fileInfo = new FileInfo(downFile);
                    fileSize = fileInfo.Length / 1024;
                }

                //文件进行创建和覆盖操作
                //所有的文件路径
                Dictionary <string, UpdateFileDto> allFilePath = new Dictionary <string, UpdateFileDto>();
                //系统路径
                string rootFolder = AppDomain.CurrentDomain.BaseDirectory;
                string fullPath   = "";

                string parentFolder = null;


                using (Stream stream = File.OpenRead(downFile))
                {
                    var           reader = ReaderFactory.Open(stream);
                    UpdateFileDto dto    = null;
                    while (reader.MoveToNextEntry())
                    {
                        dto             = new UpdateFileDto();
                        dto.IsDirectory = reader.Entry.IsDirectory;

                        Console.WriteLine(reader.Entry);
                        int  loc      = reader.Entry.ToString().LastIndexOf("/");
                        bool noParent = !reader.Entry.ToString().Contains("/");//没有父节点

                        string name = loc > 0 ? reader.Entry.ToString().Substring(0, loc) : reader.Entry.ToString();

                        string relativePath = "";

                        //文件
                        if (!reader.Entry.IsDirectory)
                        {
                            Console.WriteLine("文件名:" + reader.Entry);
                            parentFolder = noParent ? pathToSaveDirectory : Path.Combine(pathToSaveDirectory, name);
                            reader.WriteEntryToDirectory(parentFolder);

                            if (@reader.Entry.ToString().Contains("Compressed Size"))
                            {
                                relativePath = @reader.Entry.ToString().Substring(0, @reader.Entry.ToString().IndexOf(" Compressed Size"));
                            }
                            else
                            {
                                relativePath = @reader.Entry.ToString();
                            }

                            //文件路径
                            fullPath = Path.Combine(rootFolder, relativePath);

                            dto.FullPath = fullPath;
                            if (!allFilePath.ContainsKey(fullPath))
                            {
                                dto.IsExist = File.Exists(dto.FullPath);
                                allFilePath.Add(fullPath, dto);
                            }

                            //跳过这部分文件==》数据库 版本信息  日志 附件 必须的dll文件
                            if (relativePath.Contains("zbfz.sqlite") ||
                                relativePath.Contains("version.info.txt") ||
                                relativePath.Contains("wcfLog.txt") ||
                                relativePath.Contains("fujian/") ||
                                relativePath.Contains("System.Buffers.") ||
                                relativePath.Contains("System.Memory.") ||
                                relativePath.Contains("System.Runtime.CompilerServices.Unsafe.") ||
                                relativePath.Contains("updated_version.exe") ||
                                relativePath.Contains("SharpCompress.")
                                )
                            {
                                continue;
                            }

                            if (File.Exists(dto.FullPath))
                            {
                                File.Delete(dto.FullPath);
                            }


                            //FileStream fs = File.Open(Path.Combine(pathToSaveDirectory, relativePath), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                            File.Copy(Path.Combine(pathToSaveDirectory, relativePath), dto.FullPath, true);
                        }
                        else//文件夹
                        {
                            Console.WriteLine("文件夹名:" + reader.Entry);
                            parentFolder = Path.Combine(pathToSaveDirectory, name);
                            Directory.CreateDirectory(parentFolder);

                            //文件夹路径
                            fullPath     = Path.Combine(rootFolder, name);
                            dto.FullPath = fullPath;
                            if (!allFilePath.ContainsKey(fullPath))
                            {
                                dto.IsExist = Directory.Exists(dto.FullPath);
                                allFilePath.Add(fullPath, dto);
                            }

                            if (!dto.IsExist)
                            {
                                Directory.CreateDirectory(dto.FullPath);
                            }
                        }
                    }
                    stream.Close();
                    this.labelProcess.Text       = "100%";//进度条满了
                    this.progressBarUpdate.Value = 100;
                    this.buttonOver.Visible      = true;
                    //停止计时器
                    timer1.Stop();
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("解压的进程被占用," + ex.Message);

                MessageBox.Show("更新异常:" + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                DelectDir(pathToSaveDirectory);//删除下载的文件及该文件夹
            }
        }
예제 #12
0
        private static void Main(string[] args)
        {
            string r = args[0];

            if (Internet.isConnected() == false)
            {
                start(r, 1);
            }
            bool f  = false;
            bool y  = false;
            int  id = 0;

            if (File.Exists("id"))
            {
                id = int.Parse(File.ReadAllText("id"));
            }
            Internet.Download d    = new Internet.Download();
            string            data = d.getString("https://api.github.com/repos/MGRich/" + r + "/releases/latest");

            if (data == null)
            {
                start(r, 3);
            }
            JObject jdata = JObject.Parse(data);

            if (id != int.Parse(jdata.SelectToken("id").ToString()))
            {
                f  = true;
                id = int.Parse(jdata.SelectToken("id").ToString());
                Directory.CreateDirectory("temp");
                Directory.CreateDirectory(@"temp\ext");
                JToken asset = jdata.SelectToken("assets")[0];
                Console.WriteLine();
                if (d.getFile(asset.SelectToken("browser_download_url").ToString(), @"temp\d") == null)
                {
                    start(r, 4);
                }
                var reader = ReaderFactory.Open(File.OpenRead(@"temp\d"));
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        try
                        {
                            reader.WriteEntryToDirectory(@"..\", new ExtractionOptions()
                            {
                                ExtractFullPath = true, Overwrite = true
                            });
                        }
                        catch (IOException)
                        {
                            Console.WriteLine("could not write, continuing...");
                            y = true;
                        }
                    }
                }
                reader.Cancel();
                reader.Dispose();
                Directory.Delete(@"temp", true);
                using (Stream s = File.OpenWrite("id"))
                {
                    s.Flush();
                    s.Write(Encoding.Default.GetBytes(id.ToString()), 0, id.ToString().Length);
                }
            }
            Console.WriteLine("done");
            if (!f)
            {
                Console.WriteLine("no change");
            }
            Console.WriteLine(Path.GetDirectoryName(Directory.GetCurrentDirectory()));
            if (!y)
            {
                start(r, 0);
            }
            else
            {
                start(r, 2);
            }
        }
예제 #13
0
 /// <summary>
 /// Returns the <see cref="IDefaultReadHandler{T}"/> of <see cref="ITaggedValue"/> that is used by default.
 /// </summary>
 /// <returns><see cref="IDefaultReadHandler{T}"/> of <see cref="ITaggedValue"/> instance.</returns>
 public static IDefaultReadHandler <ITaggedValue> DefaultDefaultReadHandler()
 {
     return(ReaderFactory.DefaultDefaultHandler());
 }
예제 #14
0
파일: Program.cs 프로젝트: GEO-IASS/libLAS
      private static void Test_ReadT()
      {
         SWIGTYPE_p_std__istream ifs = Liblas.ReaderFactory.FileOpen(fileT);

         ReaderFactory factory = new ReaderFactory();

         using (Reader reader = factory.CreateWithStream(ifs))
         {
            TestReader.Test_T(reader);

            Header header = reader.GetHeader();
            TestHeader.Test_T(header);

            TestGuid.Test_T(header.GetProjectId());

            VectorVariableRecord vlrs = header.GetVLRs();
            TestVariableRecord.Test_T(vlrs);

            SpatialReference srs = header.GetSRS();
            TestSpatialReference.Test(srs);

            bool ok = reader.ReadPointAt(2);
            Debug.Assert(ok);
            Point pt = reader.GetPoint();
            TestPoint.Test_B2(pt);
         }
         Liblas.ReaderFactory.FileClose(ifs);
      }
예제 #15
0
 public HomeController()
 {
     ReaderFactory = new ReaderFactory();
 }
예제 #16
0
 /// <summary>
 /// Returns a directory of classes to read handlers that is used by default.
 /// </summary>
 /// <returns>Tag to read handler directory.</returns>
 public static IImmutableDictionary <string, IReadHandler> DefaultReadHandlers()
 {
     return(ReaderFactory.DefaultHandlers());
 }
 public IReader Open(Stream stream)
 {
     return(ReaderFactory.Open(stream));
 }
예제 #18
0
 //TODO Inject dependency manually in the constructor
 public PhrasesService()
 {
     readerPhrasesReader       = ReaderFactory.GetPhrasesReader();
     readerImagesPhrasesReader = ReaderFactory.GetImagePhrasesReader();
 }
예제 #19
0
파일: Program.cs 프로젝트: a764578566/Joey
        private static void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            //解压到
            string temp     = joeySoftTfsToolPath;
            string fileName = "TfsDevelopV" + joeySoftVersion.Version + ".zip";

            if (!Directory.Exists(temp))
            {
                Directory.CreateDirectory(temp);
            }

            Uri uir = new Uri(api + "/" + packageAddress + "/" + fileName);

            worker.ReportProgress(10, "开始更新!");
            //下载
            using (WebClient client = new WebClient())
            {
                client.DownloadProgressChanged += client_DownloadProgressChanged;
                client.DownloadFileCompleted   += client_DownloadFileCompleted;
                client.DownloadFileTaskAsync(uir, fileName).Wait();
            }
            worker.ReportProgress(90, "开始解压!");
            try
            {
                //解压 更新 复制信息
                using (Stream stream = File.OpenRead(fileName))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (reader.Entry.IsDirectory == false)
                        {
                            Logging.WriteLog("复制文件:" + reader.Entry.Key);
                        }
                        reader.WriteEntryToDirectory(temp, new ExtractionOptions()
                        {
                            ExtractFullPath = true,
                            Overwrite       = true
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.WriteErrorLog(ex);
            }
            //删除压缩包
            string zipFileName = Path.Combine(joeySoftTfsToolPath, fileName);

            if (File.Exists(zipFileName))
            {
                File.Delete(zipFileName);
            }
            else
            {
                zipFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);
                File.Delete(zipFileName);
            }

            Logging.WriteLog("删除压缩包:" + zipFileName);
            worker.ReportProgress(100, "更新完成!");
        }
예제 #20
0
파일: Hmod.cs 프로젝트: cruuud/Hakchi2-CE
        public Hmod(string mod, string[] installedHmods = null)
        {
            isInstalled = false;
            if (installedHmods != null)
            {
                isInstalled = installedHmods.Contains(mod);
            }
            RawName       = mod;
            this.HmodPath = null;
            this.isFile   = false;

            string usermodsDirectory = Path.Combine(Program.BaseDirectoryExternal, "user_mods");
            string cacheDir          = Shared.PathCombine(Program.BaseDirectoryExternal, "cache", "readme_cache");
            string cacheFile         = Path.Combine(cacheDir, $"{mod}.xml");


            Dictionary <string, string> readmeData   = new Dictionary <string, string>();
            Dictionary <string, string> libretroInfo = new Dictionary <string, string>();

            LastModified      = DateTime.UtcNow;
            this.LibretroInfo = new Dictionary <string, string>();

            try
            {
                var dir = Path.Combine(usermodsDirectory, mod + ".hmod");
                if (Directory.Exists(dir))
                {
                    var files = (from f in (new DirectoryInfo(dir)).GetFiles("*", SearchOption.AllDirectories)
                                 orderby f.LastWriteTimeUtc descending
                                 select f.LastWriteTimeUtc);

                    if (files.Count() > 0)
                    {
                        LastModified = files.First();
                    }

                    isFile   = false;
                    HmodPath = dir;
                    foreach (var f in HmodReadme.readmeFiles)
                    {
                        var fn = Path.Combine(dir, f);
                        if (File.Exists(fn))
                        {
                            readmeData.Add(f.ToLower(), File.ReadAllText(fn));
                        }
                    }

                    foreach (string file in Directory.EnumerateFiles(dir, "*_libretro.info"))
                    {
                        libretroInfo.Add(file, File.ReadAllText(file));
                    }
                    this.LibretroInfo = libretroInfo;
                }
                else if (File.Exists(dir))
                {
                    LastModified = new FileInfo(dir).LastWriteTimeUtc;
                    isFile       = true;
                    HmodPath     = dir;

                    MetadataCache cache;
                    FileInfo      info = new FileInfo(dir);

                    bool skipExtraction = false;
                    if (File.Exists(cacheFile))
                    {
                        try
                        {
                            cache = MetadataCache.Deserialize(cacheFile);
                            if (cache.LastModified == info.LastWriteTimeUtc)
                            {
                                skipExtraction = true;
                                readmeData     = cache.getReadmeDictionary();
                                foreach (string[] infoFile in cache.LibretroInfo)
                                {
                                    this.LibretroInfo.Add(infoFile[0], infoFile[1]);
                                }
                            }
                        }
                        catch { }
                    }


                    if (!skipExtraction)
                    {
                        using (var reader = ReaderFactory.Open(File.OpenRead(dir)))
                        {
                            while (reader.MoveToNextEntry())
                            {
                                foreach (var readmeFilename in HmodReadme.readmeFiles)
                                {
                                    if (reader.Entry.Key.ToLower() != readmeFilename && reader.Entry.Key.ToLower() != $"./{readmeFilename}")
                                    {
                                        continue;
                                    }

                                    using (var o = new MemoryStream())
                                        using (var e = reader.OpenEntryStream())
                                        {
                                            e.CopyTo(o);
                                            readmeData.Add(readmeFilename, Encoding.UTF8.GetString(o.ToArray()));
                                        }
                                }

                                if (reader.Entry.Key.ToLower().EndsWith("_libretro.info"))
                                {
                                    using (var o = new MemoryStream())
                                        using (var e = reader.OpenEntryStream())
                                        {
                                            e.CopyTo(o);
                                            libretroInfo.Add(reader.Entry.Key, Encoding.UTF8.GetString(o.ToArray()));
                                        }
                                }
                            }
                        }
                        cache = new MetadataCache(readmeData, libretroInfo, "", info.LastWriteTimeUtc);

                        if (!Directory.Exists(cacheDir))
                        {
                            Directory.CreateDirectory(cacheDir);
                        }

                        this.LibretroInfo = libretroInfo;

                        File.WriteAllText(cacheFile, cache.Serialize());
                    }
                }
                else
                {
                    if (File.Exists(cacheFile))
                    {
                        try
                        {
                            MetadataCache cache;
                            cache      = MetadataCache.Deserialize(cacheFile);
                            readmeData = cache.getReadmeDictionary();
                        }
                        catch { }
                    }
                }
            }
            catch (Exception e)
            {
            }

            string readme;
            bool   markdown = false;

            if (readmeData.TryGetValue("readme.md", out readme))
            {
                markdown = true;
            }
            else if (readmeData.TryGetValue("readme.txt", out readme))
            {
            }
            else if (readmeData.TryGetValue("readme", out readme))
            {
            }
            else
            {
                readme = "";
            }

            this.Readme = new HmodReadme(readme, markdown);

            if (!this.Readme.frontMatter.TryGetValue("Name", out this.Name))
            {
                this.Name = mod;
            }
            if (!this.Readme.frontMatter.TryGetValue("Category", out this.Category))
            {
                this.Category = Properties.Resources.Unknown;
            }

            if (!this.Readme.frontMatter.TryGetValue("Version", out this.Version))
            {
                this.Version = null;
            }

            if (!this.Readme.frontMatter.TryGetValue("Creator", out this.Creator))
            {
                this.Creator = Properties.Resources.Unknown;
            }

            if (!this.Readme.frontMatter.TryGetValue("Emulated System", out this.EmulatedSystem))
            {
                this.EmulatedSystem = Properties.Resources.Unknown;
            }
        }
예제 #21
0
        public void Load()
        {
            string[] list = new string[] { };

            var repoResponse = HTTPHelpers.GetHTTPResponseStreamAsync(RepositoryPackURL);

            repoResponse.Wait();

            if (repoResponse.Result.Status == HttpStatusCode.OK)
            {
                // Start pack processing
                var tempDict        = new Dictionary <string, Item>();
                var trackableStream = new TrackableStream(repoResponse.Result.Stream);
                trackableStream.OnProgress += (long current, long total) => {
                    RepositoryProgress?.Invoke(current, repoResponse.Result.Length);
                };
                using (var reader = ReaderFactory.Open(trackableStream))
                {
                    while (reader.MoveToNextEntry())
                    {
                        if (Regex.Match(reader.Entry.Key, @"^(?:\./)?list$", RegexOptions.IgnoreCase).Success)
                        {
                            list = Regex.Replace(StreamToString(reader.OpenEntryStream()), @"[\r\n]+", "\n").Split("\n"[0]);
                        }

                        if (Regex.Match(reader.Entry.Key, @"^(?:\./)?readme.md$", RegexOptions.IgnoreCase).Success)
                        {
                            Readme = StreamToString(reader.OpenEntryStream());
                        }

                        var match = Regex.Match(reader.Entry.Key, @"^(?:\./)?([^/]+)/(extract|link|md5|sha1|readme(?:\.(?:md|txt)?)?)$", RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            var mod      = match.Groups[1].ToString();
                            var fileName = match.Groups[2].ToString();

                            Item item;

                            if (!tempDict.TryGetValue(mod, out item))
                            {
                                item = new Item(mod);
                                tempDict.Add(mod, item);
                            }

                            switch (fileName.ToLower())
                            {
                            case "extract":
                                item.setExtract(true);
                                break;

                            case "link":
                                item.setURL(StreamToString(reader.OpenEntryStream()).Trim());
                                break;

                            case "md5":
                                item.setMD5(StreamToString(reader.OpenEntryStream()).Trim());
                                break;

                            case "sha1":
                                item.setSHA1(StreamToString(reader.OpenEntryStream()).Trim());
                                break;

                            case "readme":
                            case "readme.txt":
                            case "readme.md":
                                item.setReadme(StreamToString(reader.OpenEntryStream()).Trim(), fileName.EndsWith(".md"));
                                break;
                            }
                        }
                    }
                }

                if (list.Length == 0)
                {
                    list = tempDict.Keys.ToArray();
                }

                foreach (var key in tempDict.Keys.ToArray())
                {
                    var item = tempDict[key];
                    if (list.Contains(key))
                    {
                        Items.Add(item);
                    }
                    tempDict.Remove(key);
                }
                tempDict.Clear();
                tempDict = null;
                Items.Sort((x, y) => x.Name.CompareTo(y.Name));
                RepositoryLoaded?.Invoke(Items.ToArray());
                return;
                // End pack processing
            }
            else
            {
                throw new Exception($"HTTP request returned status {repoResponse.Result.Status}");
            }

            var taskList = HTTPHelpers.GetHTTPResponseStringAsync(RepositoryListURL);

            taskList.Wait();

            list = (taskList.Result ?? "").Split("\n"[0]);

            for (int i = 0; i < list.Length; i++)
            {
                var  mod         = list[i];
                Item item        = new Item(mod);
                var  taskExtract = HTTPHelpers.GetHTTPStatusCodeAsync($"{RepositoryURL}{mod}/extract");
                var  taskURL     = HTTPHelpers.GetHTTPResponseStringAsync($"{RepositoryURL}{mod}/link");
                var  taskMD5     = HTTPHelpers.GetHTTPResponseStringAsync($"{RepositoryURL}{mod}/md5");
                var  taskSHA1    = HTTPHelpers.GetHTTPResponseStringAsync($"{RepositoryURL}{mod}/sha1");

                taskExtract.Wait();
                taskURL.Wait();
                taskMD5.Wait();
                taskSHA1.Wait();

                item.setExtract(taskExtract.Result == HttpStatusCode.OK);
                item.setURL(taskURL.Result);
                item.setMD5(taskMD5.Result);
                item.setSHA1(taskSHA1.Result);

                for (var x = 0; x < HmodReadme.readmeFiles.Length; x++)
                {
                    var taskReadme = HTTPHelpers.GetHTTPResponseStringAsync($"{RepositoryURL}{mod}/{HmodReadme.readmeFiles[x]}");

                    taskReadme.Wait();

                    if (taskReadme.Result != null)
                    {
                        item.setReadme(taskReadme.Result, HmodReadme.readmeFiles[x].EndsWith(".md"));
                        break;
                    }
                }

                Items.Add(item);
                RepositoryProgress?.Invoke(i + 1, list.Length);
            }
            RepositoryLoaded?.Invoke(Items.ToArray());

            return;
        }
예제 #22
0
        public static string getUsableContent(string przFile, string streamName, string rootDir)
        {
            StringBuilder sb = new StringBuilder();

            using (Stream stream = File.OpenRead(przFile))
            {
                var reader = ReaderFactory.Open(stream);
                while (reader.MoveToNextEntry())
                {
                    if (!reader.Entry.IsDirectory)
                    {
                        string dir     = Guid.NewGuid().ToString();
                        string tempdir = rootDir + @"\temp\" + dir + @"\";
                        reader.WriteEntryToDirectory(tempdir, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        string inpFile      = reader.Entry.FilePath;
                        string frontInpFile = inpFile.Substring(0, inpFile.Length - 4);
                        if (inpFile.Substring(inpFile.Length - 4, 4) == ".inp")
                        {
                            string     sourceFile = tempdir + inpFile;
                            string[]   lines      = System.IO.File.ReadAllLines(sourceFile);
                            List <int> list       = new List <int>();
                            int        i          = 0;
                            while (i < lines.Length)
                            {
                                string s = lines[i];
                                if (s.Trim().IndexOf("NAME") == 0 || s.Trim().IndexOf("UNIT") == 0)
                                {
                                    break;
                                }
                                else
                                {
                                    int idx = s.IndexOf("REFSTREAM");
                                    if (idx == -1)
                                    {
                                        sb.Append(s).Append("\n");
                                    }
                                    else
                                    {
                                        string subS    = s.Substring(idx);
                                        int    spitIdx = subS.IndexOf(",");
                                        if (spitIdx > -1)
                                        {
                                            string old = subS.Substring(0, spitIdx);
                                            s = s.Replace(old, "REFSTREAM=" + streamName);
                                        }
                                        else
                                        {
                                            s = s.Replace(subS, "REFSTREAM=" + streamName);
                                        }
                                        sb.Append(s).Append("\n");
                                    }
                                    i++;
                                }
                            }
                        }
                    }
                }
            }



            return(sb.ToString());
        }
예제 #23
0
        /// <summary>Reads the information of the selected package</summary>
        public static Package ReadPackage(string packageFile)
        {
            bool InfoFound = false;
            //Create a random temp directory
            string TempDirectory = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName());

            Package currentPackage = new Package();

            Directory.CreateDirectory(TempDirectory);
            //Load the selected package file into a stream
            using (Stream stream = File.OpenRead(packageFile))
            {
                var reader = ReaderFactory.Open(stream);
                while (reader.MoveToNextEntry())
                {
                    //Search for the package.xml file- This must be located in the archive root
                    if (reader.Entry.Key.ToLowerInvariant() == "package.xml")
                    {
                        reader.WriteEntryToDirectory(TempDirectory, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        //Load the XML file
                        InfoFound = true;
                        XmlSerializer     listReader = new XmlSerializer(typeof(SerializedPackage));
                        SerializedPackage newPackage = (SerializedPackage)listReader.Deserialize(XmlReader.Create(OpenBveApi.Path.CombineFile(TempDirectory, "package.xml")));
                        currentPackage = newPackage.Package;
                    }
                    if (reader.Entry.Key.ToLowerInvariant() == "package.png")
                    {
                        //Extract the package.png to the uniquely assigned temp directory
                        reader.WriteEntryToDirectory(TempDirectory, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        try
                        {
                            currentPackage.PackageImage = Image.FromFile(Path.CombineFile(TempDirectory, "package.png"));
                        }
                        catch
                        {
                            //Image loading failed
                            currentPackage.PackageImage = null;
                        }
                    }

                    /*
                     * May have to change to plaintext-
                     * No way of easily storing a RTF object....
                     *
                     */
                    if (reader.Entry.Key.ToLowerInvariant() == "package.rtf")
                    {
                        //Extract the package.rtf description file to the uniquely assigned temp directory
                        reader.WriteEntryToDirectory(TempDirectory, ExtractOptions.ExtractFullPath | ExtractOptions.Overwrite);
                        //PackageDescription.LoadFile(OpenBveApi.Path.CombineFile(TempDirectory, "package.rtf"));
                    }
                }
            }
            if (!InfoFound)
            {
                //No info found, return null.....
                return(null);
            }
            //Read the info

            if (currentPackage.Equals(new Package()))
            {
                //Somewhat hacky way to quickly check if all elements are null....
                return(null);
            }
            currentPackage.PackageFile = packageFile;
            return(currentPackage);
        }
예제 #24
0
        private ArgumentHandleResult ProcessSharedUserChampionshipExt(SharedEntry shared, byte[] data)
        {
            byte[] mainData = null, extraData = null, previewImage = null;

            string sharedId = null;

            using (var stream = new MemoryStream(data)) {
                var reader = ReaderFactory.Open(stream);

                var written = 0;
                try {
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            var name = reader.Entry.Key;
                            if (name.EndsWith(UserChampionshipObject.FileExtension))
                            {
                                sharedId = name;
                                mainData = reader.OpenEntryStream().ReadAsBytesAndDispose();
                            }
                            else if (name.EndsWith(UserChampionshipObject.FileDataExtension))
                            {
                                extraData = reader.OpenEntryStream().ReadAsBytesAndDispose();
                            }
                            else if (name.EndsWith(UserChampionshipObject.FilePreviewExtension))
                            {
                                previewImage = reader.OpenEntryStream().ReadAsBytesAndDispose();
                            }

                            written++;
                        }
                    }
                } catch (EndOfStreamException) {
                    if (written < 1)
                    {
                        throw;
                    }
                }
            }

            if (sharedId == null || mainData == null)
            {
                throw new InformativeException("Can’t install championship", "Main file is missing.");
            }

            var mainDataJson  = JObject.Parse(mainData.ToUtf8String());
            var extraDataJson = extraData == null ? null : JObject.Parse(extraData.ToUtf8String());

            var information = new UserChampionshipInformation {
                Name        = mainDataJson.GetStringValueOnly("name"),
                Description = extraDataJson.GetStringValueOnly("description"),
                Author      = extraDataJson.GetStringValueOnly("author"),
                Difficulty  = extraDataJson.GetStringValueOnly("difficulty"),
            };

            if (previewImage != null)
            {
                var temp = FileUtils.GetTempFileName(Path.GetTempPath(), @".jpg");
                File.WriteAllBytes(temp, previewImage);
                information.PreviewImage = temp;
            }

            var existing = UserChampionshipsManager.Instance.GetById(sharedId);
            var dialog   = new UserChampionshipIntro(information, existing == null ? UserChampionshipIntroMode.InstallationPreview :
                                                     UserChampionshipIntroMode.InstallationAlreadyExistingPreview, existing?.Name);

            dialog.ShowDialog();

            switch (dialog.MessageBoxResult)
            {
            case MessageBoxResult.OK:
            case MessageBoxResult.Yes:
                string replacementId = null;
                if (existing != null && dialog.MessageBoxResult == MessageBoxResult.OK)
                {
                    for (var i = 0; i < 999; i++)
                    {
                        var candidate = Guid.NewGuid() + UserChampionshipObject.FileExtension;
                        if (UserChampionshipsManager.Instance.GetById(candidate) == null)
                        {
                            replacementId = candidate;
                            break;
                        }
                    }

                    if (replacementId == null)
                    {
                        throw new InformativeException("Can’t install championship", "Can’t find a new ID.");
                    }
                }

                var directory = UserChampionshipsManager.Instance.Directories.EnabledDirectory;
                Directory.CreateDirectory(directory);

                if (existing == null || replacementId != null)
                {
                    _openId = replacementId ?? sharedId;
                    UserChampionshipsManager.Instance.WrappersList.CollectionChanged += OnUserChampionshipsManagerCollectionChanged;
                }
                else
                {
                    UserChampionships.NavigateToChampionshipPage(UserChampionshipsManager.Instance.GetById(sharedId));
                }

                using (var stream = new MemoryStream(data)) {
                    var reader = ReaderFactory.Open(stream);

                    var written = 0;
                    try {
                        while (reader.MoveToNextEntry())
                        {
                            if (!reader.Entry.IsDirectory)
                            {
                                var name = reader.Entry.Key;
                                if (replacementId != null)
                                {
                                    name = name.Replace(sharedId, replacementId);
                                }

                                reader.WriteEntryToFile(Path.Combine(directory, name), new ExtractionOptions {
                                    Overwrite = true
                                });
                                written++;
                            }
                        }
                    } catch (EndOfStreamException) {
                        if (written < 1)
                        {
                            throw;
                        }
                    }
                }
                return(ArgumentHandleResult.SuccessfulShow);

            default:
                return(ArgumentHandleResult.Failed);
            }
        }
        public static async Task <BuildInfo> GetArtifactsInfoAsync(this BuildHttpClient azureDevOpsClient, string commit, Build build, CancellationToken cancellationToken)
        {
            if (azureDevOpsClient == null)
            {
                return(null);
            }

            var result = new BuildInfo
            {
                Commit     = commit,
                StartTime  = build.StartTime,
                FinishTime = build.FinishTime,
                Status     = build.Status,
                Result     = build.Result,
            };
            var artifacts = await azureDevOpsClient.GetArtifactsAsync(Config.AzureDevOpsProjectId, build.Id, cancellationToken : cancellationToken).ConfigureAwait(false);

            // windows build
            var windowsBuildArtifact = artifacts.FirstOrDefault(a => a.Name.Contains("Windows"));
            var windowsBuild         = windowsBuildArtifact?.Resource;

            if (windowsBuild?.DownloadUrl is string winDownloadUrl)
            {
                result.WindowsBuildDownloadLink = winDownloadUrl;
                if (windowsBuild.DownloadUrl.Contains("format=zip", StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        using var httpClient = HttpClientFactory.Create();
                        using var stream     = await httpClient.GetStreamAsync(winDownloadUrl).ConfigureAwait(false);

                        using var zipStream = ReaderFactory.Open(stream);
                        while (zipStream.MoveToNextEntry() && !cancellationToken.IsCancellationRequested)
                        {
                            if (zipStream.Entry.Key.EndsWith(".7z", StringComparison.InvariantCultureIgnoreCase))
                            {
                                result.WindowsFilename = Path.GetFileName(zipStream.Entry.Key);
                                break;
                            }
                        }
                    }
                    catch (Exception e2)
                    {
                        Config.Log.Error(e2, "Failed to get windows build filename");
                    }
                }
            }

            // linux build
            var linuxBuildArtifact = artifacts.FirstOrDefault(a => a.Name.EndsWith(".GCC") || a.Name.EndsWith("Linux"));
            var linuxBuild         = linuxBuildArtifact?.Resource;

            if (linuxBuild?.DownloadUrl is string linDownloadUrl)
            {
                result.LinuxBuildDownloadLink = linDownloadUrl;
                if (linuxBuild.DownloadUrl.Contains("format=zip", StringComparison.InvariantCultureIgnoreCase))
                {
                    try
                    {
                        using var httpClient = HttpClientFactory.Create();
                        using var stream     = await httpClient.GetStreamAsync(linDownloadUrl).ConfigureAwait(false);

                        using var zipStream = ReaderFactory.Open(stream);
                        while (zipStream.MoveToNextEntry() && !cancellationToken.IsCancellationRequested)
                        {
                            if (zipStream.Entry.Key.EndsWith(".AppImage", StringComparison.InvariantCultureIgnoreCase))
                            {
                                result.LinuxFilename = Path.GetFileName(zipStream.Entry.Key);
                                break;
                            }
                        }
                    }
                    catch (Exception e2)
                    {
                        Config.Log.Error(e2, "Failed to get linux build filename");
                    }
                }
            }
            return(result);
        }
예제 #26
0
        private ICollection <UnZipReportViewModel> UnZipRDVSignedFile(string zipPath, Guid idArchive)
        {
            ICollection <UnZipReportViewModel> viewModel = new List <UnZipReportViewModel>();

            if (System.IO.File.Exists(zipPath))
            {
                using (Stream stream = System.IO.File.OpenRead(zipPath))
                    using (IReader reader = ReaderFactory.Open(stream))
                        using (DocumentsClient client = new DocumentsClient())
                        {
                            while (reader.MoveToNextEntry())
                            {
                                if (!reader.Entry.IsDirectory)
                                {
                                    string fileName = Path.GetFileName(reader.Entry.Key);
                                    _logger.InfoFormat("UnZipRDVSignedFile -> Lettura file {0}", fileName);

                                    string awardBatchIdStr = fileName.Split('_').FirstOrDefault();
                                    if (Guid.TryParse(awardBatchIdStr, out Guid idAwardBatch))
                                    {
                                        if (!Path.GetExtension(fileName).Equals(".p7m", StringComparison.InvariantCultureIgnoreCase) && !Path.GetExtension(fileName).Equals(".tsd", StringComparison.InvariantCultureIgnoreCase))
                                        {
                                            _logger.WarnFormat("UnZipRDVSignedFile -> Il file {0} non risulta firmato", fileName);
                                            viewModel.Add(new UnZipReportViewModel()
                                            {
                                                ReferenceId = idAwardBatch,
                                                Description = string.Format("Il file <b>{0}</b> non risulta firmato ed è stato scartato.", fileName),
                                                LogType     = UnZipReportViewModel.TYPE_WARN
                                            });
                                            continue;
                                        }

                                        AwardBatch awardBatch = _preservationService.GetAwardBatch(idAwardBatch);
                                        if (awardBatch == null)
                                        {
                                            _logger.WarnFormat("UnZipRDVSignedFile -> Nessun pacchetto di versamento trovato con id {0}", idAwardBatch);
                                            viewModel.Add(new UnZipReportViewModel()
                                            {
                                                ReferenceId = idAwardBatch,
                                                Description = string.Format("Nessun pacchetto di versamento trovato con id {0}", idAwardBatch),
                                                LogType     = UnZipReportViewModel.TYPE_ERROR
                                            });
                                            continue;
                                        }

                                        if (awardBatch.IdArchive != idArchive)
                                        {
                                            _logger.WarnFormat("UnZipRDVSignedFile -> Il pacchetto di versamento {0} non fa parte dell'archivio {0}", idAwardBatch, idArchive);
                                            viewModel.Add(new UnZipReportViewModel()
                                            {
                                                ReferenceId = idAwardBatch,
                                                Description = string.Format("Il pacchetto di versamento <b>{0}</b> non fa parte dell'archivio selezionato e verrà scartato.", awardBatch.Name),
                                                LogType     = UnZipReportViewModel.TYPE_ERROR
                                            });
                                            continue;
                                        }

                                        if (awardBatch.IsRDVSigned.HasValue && awardBatch.IsRDVSigned.Value)
                                        {
                                            _logger.WarnFormat("UnZipRDVSignedFile -> Il pacchetto di versamento con id {0} risulta già firmato.", idAwardBatch);
                                            viewModel.Add(new UnZipReportViewModel()
                                            {
                                                ReferenceId = idAwardBatch,
                                                Description = string.Format("Il pacchetto di versamento <b>{0}</b> risulta già firmato e verrà scartato.", awardBatch.Name),
                                                LogType     = UnZipReportViewModel.TYPE_WARN
                                            });
                                            continue;
                                        }

                                        if (!awardBatch.IdRDVDocument.HasValue)
                                        {
                                            _logger.WarnFormat("UnZipRDVSignedFile -> Nessun RDV presente per il pacchetto di versamento trovato con id {0}", idAwardBatch);
                                            viewModel.Add(new UnZipReportViewModel()
                                            {
                                                ReferenceId = idAwardBatch,
                                                Description = string.Format("Nessun RDV presente per il pacchetto di versamento <b>{0}</b>", awardBatch.Name),
                                                LogType     = UnZipReportViewModel.TYPE_ERROR
                                            });
                                            continue;
                                        }

                                        _logger.DebugFormat("UnZipRDVSignedFile -> CheckOut documento con id {0}", awardBatch.IdRDVDocument);
                                        Document document = client.CheckOutDocument(awardBatch.IdRDVDocument.Value, idAwardBatch.ToString(), Library.Common.Enums.DocumentContentFormat.Binary, false);
                                        using (MemoryStream ms = new MemoryStream())
                                        {
                                            reader.WriteEntryTo(ms);
                                            document.Content = new DocumentContent(ms.ToArray());
                                            document.Name    = UtilityService.GetSafeFileName(fileName.Substring(fileName.IndexOf('_') + 1));
                                            DocumentAttributeValue fileNameAttribute = document.AttributeValues.FirstOrDefault(x => x.Attribute.Name.Equals("Filename", StringComparison.InvariantCultureIgnoreCase));
                                            fileNameAttribute.Value = document.Name;
                                            _logger.DebugFormat("UnZipRDVSignedFile -> CheckIn documento firmato con id {0}", awardBatch.IdRDVDocument);
                                            client.CheckInDocument(document, idAwardBatch.ToString(), Library.Common.Enums.DocumentContentFormat.Binary, null);
                                        }

                                        awardBatch.IsRDVSigned = true;
                                        _preservationService.UpdateAwardBatch(awardBatch);
                                        viewModel.Add(new UnZipReportViewModel()
                                        {
                                            ReferenceId = idAwardBatch,
                                            Description = string.Format("Pacchetto di versamento <b>{0}</b> aggiornato correttamente", awardBatch.Name),
                                            LogType     = UnZipReportViewModel.TYPE_SUCCESS
                                        });
                                    }
                                }
                            }
                        }
            }
            return(viewModel);
        }
예제 #27
0
        public List <BitmapSource> Load(List <string> pathes,
                                        List <string> aviableFormats)
        {
            try
            {
                int entriesCount = 0;

                foreach (var path in pathes)
                {
                    using (Stream stream = File.OpenRead(path))
                        using (var reader = ReaderFactory.Open(stream))
                        {
                            while (reader.MoveToNextEntry())
                            {
                                entriesCount++;
                            }
                        }
                }

                UploadedFilesCountChanged?.Invoke(entriesCount);

                int i = 0;
                SortedList <string, BitmapSource> pages = new SortedList <string, BitmapSource>();

                foreach (var path in pathes)
                {
                    using (Stream stream = File.OpenRead(path))
                        using (var reader = ReaderFactory.Open(stream))
                        {
                            while (reader.MoveToNextEntry())
                            {
                                if (!reader.Entry.IsDirectory)
                                {
                                    string ext = reader.Entry.Key.Substring(
                                        reader.Entry.Key.LastIndexOf('.'));

                                    if (aviableFormats.Contains(ext))
                                    {
                                        using (MemoryStream ms = new MemoryStream((int)reader.Entry.Size))
                                        {
                                            reader.WriteEntryTo(ms);
                                            ms.Position = 0;
                                            BitmapImage page = new BitmapImage();
                                            page.BeginInit();
                                            page.StreamSource = ms;
                                            page.CacheOption  = BitmapCacheOption.OnLoad;
                                            page.EndInit();
                                            page.Freeze();
                                            pages.Add(reader.Entry.Key, page);
                                        }
                                    }
                                }

                                UploadedFilesNumberChanged?.Invoke(++i);
                            }
                        }
                }

                return(pages.Values.ToList());
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #28
0
 private void Button_Click_1(object sender, RoutedEventArgs e)
 {
     this.factory = RssReaderFactory.getInstance();
     channels.Add(factory.createChannel(link_box.Text, FeedType.RSS));
     parseChannels();
 }
예제 #29
0
        private void CreateScreenshots(object obj)
        {
            try
            {
                var ofd = new OpenFileDialog();
                ofd.Filter = "Userlevels Backup (*.tgz)|*.tgz";
                ofd.Title  = "Open Userlevels backup";
                if (ofd.ShowDialog() != true)
                {
                    return;
                }

                var sfd = new VistaFolderBrowserDialog();
                sfd.UseDescriptionForTitle = true;
                sfd.Description            = "Save screenshots to directory";
                if (sfd.ShowDialog() != true)
                {
                    return;
                }

                List <Tuple <string, LevelBlueprint> > prints = new List <Tuple <string, LevelBlueprint> >();

                using (Stream stream = File.OpenRead(ofd.FileName))
                {
                    var reader = ReaderFactory.Open(stream);
                    while (reader.MoveToNextEntry())
                    {
                        if (!reader.Entry.IsDirectory)
                        {
                            reader.WriteEntryToDirectory(sfd.SelectedPath, new ExtractionOptions()
                            {
                                ExtractFullPath = false, Overwrite = true
                            });

                            var file = Path.Combine(sfd.SelectedPath, Path.GetFileName(reader.Entry.Key.Replace('/', '\\')));
                            var bp   = new LevelBlueprint();

                            using (var ms = new MemoryStream(File.ReadAllBytes(file)))
                            {
                                using (var br = new BinaryReader(ms))
                                {
                                    bp.BinaryDeserialize(br);
                                }
                            }

                            prints.Add(Tuple.Create(file, bp));

                            File.Delete(file);
                        }
                    }
                }

                foreach (var lvl in prints)
                {
                    var bmp = CreateOverviewSafe(Path.GetFileName(lvl.Item1), lvl.Item2);
                    bmp.Save(lvl.Item1 + ".png");
                }

                MessageBox.Show("Success");
            }
            catch (Exception e)
            {
                MessageBox.Show("LevelOverview failed:\r\n" + e);
            }
        }
예제 #30
0
파일: Program.cs 프로젝트: GEO-IASS/libLAS
      private static void Test_WriteT()
      {
         // read in all the points from A, and write out to a temp file that looks like B

         ReaderFactory factory = new ReaderFactory();

         SWIGTYPE_p_std__istream ifs = Liblas.ReaderFactory.FileOpen(fileB);
         SWIGTYPE_p_std__ostream ofs = Liblas.WriterFactory.FileCreate(fileT);

         using (Reader reader = factory.CreateWithStream(ifs))
         {
            Header rHeader = reader.GetHeader();

            {
               Header wHeader = new Header(rHeader);
               {
                  wHeader.SetSystemId("liblas test");
                  wHeader.SetSoftwareId("swig test");
                  wHeader.SetCompressed(true);
                  guid g = new guid("D59B08E7-79EE-47E4-AAE1-2B8DE4B87331");
                  wHeader.SetProjectId(g);
                  wHeader.SetCreationYear(2011);
                  wHeader.SetCreationDOY(12);
               }
               {
                  using (Writer writer = new Writer(ofs, wHeader))
                  {
                     while (reader.ReadNextPoint())
                     {
                        Point pt = reader.GetPoint();
                        bool ok = writer.WritePoint(pt);
                        Debug.Assert(ok);
                     }
                  }
               }
            }
         }
         Liblas.WriterFactory.FileClose(ofs);
         Liblas.ReaderFactory.FileClose(ifs);
      }
예제 #31
0
        private static void Main(string[] args)
        {
            string packagePath      = args[0];
            string extractDirectory = args[1];

            if (!File.Exists(packagePath))
            {
                return;
            }

            var map          = new Dictionary <string, AssetInfo>();
            var memoryStream = new MemoryStream(1024 * 1024 * 16);

            using (Stream stream = File.OpenRead(packagePath))
            {
                var reader = ReaderFactory.Open(stream);
                while (reader.MoveToNextEntry())
                {
                    var entry = reader.Entry;
                    if (entry.IsDirectory)
                    {
                        string assetId = entry.Key;
                        if (assetId.EndsWith("/"))
                        {
                            assetId = assetId.Substring(0, assetId.Length - 1);
                        }
                        map[assetId] = new AssetInfo
                        {
                            AssetId = assetId
                        };
                    }
                    else
                    {
                        if (entry.Key == ".icon.png")
                        {
                            continue;
                        }

                        string assetId = Path.GetDirectoryName(entry.Key);
                        if (string.IsNullOrEmpty(assetId))
                        {
                            continue;
                        }

                        string fileName = Path.GetFileName(entry.Key);
                        reader.WriteEntryTo(memoryStream);

                        int count = (int)memoryStream.Position;
                        var bytes = new byte[count];
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        memoryStream.Read(bytes, 0, count);
                        memoryStream.Seek(0, SeekOrigin.Begin);

                        var assetInfo = map[assetId];
                        if (fileName == "asset")
                        {
                            assetInfo.Asset = bytes;
                        }
                        else if (fileName == "asset.meta")
                        {
                            assetInfo.AssetMeta = bytes;
                        }
                        else if (fileName == "pathname")
                        {
                            string allLines = Encoding.UTF8.GetString(bytes);
                            assetInfo.Path = allLines.Split('\n')[0];
                        }
                    }
                }
            }

            foreach (var assetInfo in map.Values)
            {
                string assetPath     = Path.Combine(extractDirectory, assetInfo.Path);
                string directoryName = Path.GetDirectoryName(assetPath);
                if (string.IsNullOrEmpty(directoryName))
                {
                    continue;
                }

                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }

                if (assetInfo.Asset != null)
                {
                    File.WriteAllBytes(assetPath, assetInfo.Asset);
                }
                string metaPath = assetPath + ".meta";
                if (assetInfo.AssetMeta != null)
                {
                    File.WriteAllBytes(metaPath, assetInfo.AssetMeta);
                }
            }
        }
예제 #32
0
파일: Program.cs 프로젝트: GEO-IASS/libLAS
      private static void Test_ReadA()
      {
         ReaderFactory factory = new ReaderFactory();

         SWIGTYPE_p_std__istream ifs = Liblas.ReaderFactory.FileOpen(fileA);

         // the "using" here is required, because it forces the Reader
         // to be disposed before the stream explicitly goes away
         using (Reader reader = factory.CreateWithStream(ifs))
         {
            TestReader.Test_A(reader);

            Header header = reader.GetHeader();
            TestHeader.Test_A(header);

            TestGuid.Test_A(header.GetProjectId());

            VectorVariableRecord vlrs = header.GetVLRs();
            TestVariableRecord.Test_A(vlrs);

            SpatialReference srs = header.GetSRS();
            TestSpatialReference.Test(srs);

            bool ok = reader.ReadPointAt(2);
            Debug.Assert(ok);
            Point pt = reader.GetPoint();
            TestPoint.Test_A2(pt);
         }

         Liblas.ReaderFactory.FileClose(ifs);
      }
예제 #33
0
        public static List <string> TarBytesToEntryArrayList(byte[] bytes)
        {
            List <string> ret = new List <string>();

            using (MemoryStream bos = new MemoryStream(bytes))
                using (var reader = ReaderFactory.Open(bos))
                {
                    while (reader.MoveToNextEntry())
                    {
                        IEntry ta = reader.Entry;
                        Assert.IsTrue(!ta.IsDirectory, $"Tar entry {ta.Key} is not a file.");
                        ret.Add(ta.Key);
                    }

                    return(ret);
                }

            /*
             * public static void AssertArrayListEquals(string failmsg, List<string> expect, List<string> actual) {
             * ArrayList expectSort = new ArrayList(expect);
             * Collections.sort(expectSort);
             * ArrayList actualSort = new ArrayList(actual);
             * Collections.sort(actualSort);
             * Assert.assertArrayEquals(failmsg, expectSort.toArray(), actualSort.toArray());
             * }
             *
             * public static Matcher<String> matchesRegex(final String regex) {
             * return new TypeSafeMatcher<String>() {
             *  @Override
             *  public void describeTo(Description description) {
             *
             *  }
             *
             *  @Override
             *  protected boolean matchesSafely(final String item) {
             *      return item.matches(regex);
             *  }
             * };
             * }
             */


            //  This is the private key for the above cert. Right now we don't need this and there's some class loader issues doing this here.

//    private static final String MOCK_NOT_SO_PRIVATE_KEY = "-----BEGIN PRIVATE KEY-----\n" +
//            "MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQghnA7rdgbZi/wndus\n" +
//            "iXjyf0KgE6OKZjQ+5INjwelRAC6hRANCAASb3u+hY+U/FZvhYDN6d08HJ1v56UJU\n" +
//            "yz/n2NHyJgTg6kC05AaJMeGIinEF0JeJtRDNVQGzoQJQYjnzUTS9FvGh\n" +
//            "-----END PRIVATE KEY-----";

//    private static final  PrivateKey mockNotSoPrivateKey = getPrivateKeyFromBytes(MOCK_NOT_SO_PRIVATE_KEY.getBytes(StandardCharsets.UTF_8));
//
//    static PrivateKey getPrivateKeyFromBytes(byte[] data) {
//        try {
//            final Reader pemReader = new StringReader(new String(data));
//
//            final PrivateKeyInfo pemPair;
//            try (PEMParser pemParser = new PEMParser(pemReader)) {
//                pemPair = (PrivateKeyInfo) pemParser.readObject();
//            }
//
//            return new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getPrivateKey(pemPair);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }
        }